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": "###\n# Copyright 2015 Scott Brady\n# MIT License\n# https://github.com/scottbrady/xhr",
"end": 32,
"score": 0.9998830556869507,
"start": 21,
"tag": "NAME",
"value": "Scott Brady"
},
{
"context": "15 Scott Brady\n# MIT License\n# https://github.com/scottbrady/xhr-promise... | src/xhr-promise.coffee | scottbrady/xhr-promise | 16 | ###
# Copyright 2015 Scott Brady
# MIT License
# https://github.com/scottbrady/xhr-promise/blob/master/LICENSE
###
ParseHeaders = require 'parse-headers'
###
# Module to wrap an XMLHttpRequest in a promise.
###
module.exports = class XMLHttpRequestPromise
@DEFAULT_CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=UTF-8'
##########################################################################
## Public methods #######################################################
########################################################################
###
# XMLHttpRequestPromise.send(options) -> Promise
# - options (Object): URL, method, data, etc.
#
# Create the XHR object and wire up event handlers to use a promise.
###
send: (options={}) ->
defaults =
method : 'GET'
data : null
headers : {}
async : true
username : null
password : null
withCredentials : false
options = Object.assign({}, defaults, options)
new Promise (resolve, reject) =>
if !XMLHttpRequest
@_handleError 'browser', reject, null, "browser doesn't support XMLHttpRequest"
return
if typeof options.url isnt 'string' || options.url.length is 0
@_handleError 'url', reject, null, 'URL is a required parameter'
return
# XMLHttpRequest is supported by IE 7+
@_xhr = xhr = new XMLHttpRequest
# success handler
xhr.onload = =>
@_detachWindowUnload()
try
responseText = @_getResponseText()
catch
@_handleError 'parse', reject, null, 'invalid JSON response'
return
resolve(
url : @_getResponseUrl()
status : xhr.status
statusText : xhr.statusText
responseText : responseText
headers : @_getHeaders()
xhr : xhr
)
# error handlers
xhr.onerror = => @_handleError 'error', reject
xhr.ontimeout = => @_handleError 'timeout', reject
xhr.onabort = => @_handleError 'abort', reject
@_attachWindowUnload()
xhr.open(options.method, options.url, options.async, options.username, options.password)
if options.withCredentials
xhr.withCredentials = true
if options.data? && !options.headers['Content-Type']
options.headers['Content-Type'] = @constructor.DEFAULT_CONTENT_TYPE
for header, value of options.headers
xhr.setRequestHeader(header, value)
try
xhr.send(options.data)
catch e
@_handleError 'send', reject, null, e.toString()
###
# XMLHttpRequestPromise.getXHR() -> XMLHttpRequest
###
getXHR: () ->
@_xhr
##########################################################################
## Psuedo-private methods ###############################################
########################################################################
###
# XMLHttpRequestPromise._attachWindowUnload()
#
# Fix for IE 9 and IE 10
# Internet Explorer freezes when you close a webpage during an XHR request
# https://support.microsoft.com/kb/2856746
#
###
_attachWindowUnload: () ->
@_unloadHandler = @_handleWindowUnload.bind(@)
window.attachEvent 'onunload', @_unloadHandler if window.attachEvent
###
# XMLHttpRequestPromise._detachWindowUnload()
###
_detachWindowUnload: () ->
window.detachEvent 'onunload', @_unloadHandler if window.detachEvent
###
# XMLHttpRequestPromise._getHeaders() -> Object
###
_getHeaders: () ->
ParseHeaders(@_xhr.getAllResponseHeaders())
###
# XMLHttpRequestPromise._getResponseText() -> Mixed
#
# Parses response text JSON if present.
###
_getResponseText: () ->
# Accessing binary-data responseText throws an exception in IE9
responseText = if typeof @_xhr.responseText is 'string' then @_xhr.responseText else ''
switch (@_xhr.getResponseHeader('Content-Type') || '').split(';')[0]
when 'application/json', 'text/javascript'
# Workaround Android 2.3 failure to string-cast null input
responseText = JSON.parse(responseText + '')
responseText
###
# XMLHttpRequestPromise._getResponseUrl() -> String
#
# Actual response URL after following redirects.
###
_getResponseUrl: () ->
return @_xhr.responseURL if @_xhr.responseURL?
# Avoid security warnings on getResponseHeader when not allowed by CORS
return @_xhr.getResponseHeader('X-Request-URL') if /^X-Request-URL:/m.test(@_xhr.getAllResponseHeaders())
''
###
# XMLHttpRequestPromise._handleError(reason, reject, status, statusText)
# - reason (String)
# - reject (Function)
# - status (String)
# - statusText (String)
###
_handleError: (reason, reject, status, statusText) ->
@_detachWindowUnload()
reject(
reason : reason
status : status || @_xhr.status
statusText : statusText || @_xhr.statusText
xhr : @_xhr
)
###
# XMLHttpRequestPromise._handleWindowUnload()
###
_handleWindowUnload: () ->
@_xhr.abort()
| 218569 | ###
# Copyright 2015 <NAME>
# MIT License
# https://github.com/scottbrady/xhr-promise/blob/master/LICENSE
###
ParseHeaders = require 'parse-headers'
###
# Module to wrap an XMLHttpRequest in a promise.
###
module.exports = class XMLHttpRequestPromise
@DEFAULT_CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=UTF-8'
##########################################################################
## Public methods #######################################################
########################################################################
###
# XMLHttpRequestPromise.send(options) -> Promise
# - options (Object): URL, method, data, etc.
#
# Create the XHR object and wire up event handlers to use a promise.
###
send: (options={}) ->
defaults =
method : 'GET'
data : null
headers : {}
async : true
username : null
password : <PASSWORD>
withCredentials : false
options = Object.assign({}, defaults, options)
new Promise (resolve, reject) =>
if !XMLHttpRequest
@_handleError 'browser', reject, null, "browser doesn't support XMLHttpRequest"
return
if typeof options.url isnt 'string' || options.url.length is 0
@_handleError 'url', reject, null, 'URL is a required parameter'
return
# XMLHttpRequest is supported by IE 7+
@_xhr = xhr = new XMLHttpRequest
# success handler
xhr.onload = =>
@_detachWindowUnload()
try
responseText = @_getResponseText()
catch
@_handleError 'parse', reject, null, 'invalid JSON response'
return
resolve(
url : @_getResponseUrl()
status : xhr.status
statusText : xhr.statusText
responseText : responseText
headers : @_getHeaders()
xhr : xhr
)
# error handlers
xhr.onerror = => @_handleError 'error', reject
xhr.ontimeout = => @_handleError 'timeout', reject
xhr.onabort = => @_handleError 'abort', reject
@_attachWindowUnload()
xhr.open(options.method, options.url, options.async, options.username, options.password)
if options.withCredentials
xhr.withCredentials = true
if options.data? && !options.headers['Content-Type']
options.headers['Content-Type'] = @constructor.DEFAULT_CONTENT_TYPE
for header, value of options.headers
xhr.setRequestHeader(header, value)
try
xhr.send(options.data)
catch e
@_handleError 'send', reject, null, e.toString()
###
# XMLHttpRequestPromise.getXHR() -> XMLHttpRequest
###
getXHR: () ->
@_xhr
##########################################################################
## Psuedo-private methods ###############################################
########################################################################
###
# XMLHttpRequestPromise._attachWindowUnload()
#
# Fix for IE 9 and IE 10
# Internet Explorer freezes when you close a webpage during an XHR request
# https://support.microsoft.com/kb/2856746
#
###
_attachWindowUnload: () ->
@_unloadHandler = @_handleWindowUnload.bind(@)
window.attachEvent 'onunload', @_unloadHandler if window.attachEvent
###
# XMLHttpRequestPromise._detachWindowUnload()
###
_detachWindowUnload: () ->
window.detachEvent 'onunload', @_unloadHandler if window.detachEvent
###
# XMLHttpRequestPromise._getHeaders() -> Object
###
_getHeaders: () ->
ParseHeaders(@_xhr.getAllResponseHeaders())
###
# XMLHttpRequestPromise._getResponseText() -> Mixed
#
# Parses response text JSON if present.
###
_getResponseText: () ->
# Accessing binary-data responseText throws an exception in IE9
responseText = if typeof @_xhr.responseText is 'string' then @_xhr.responseText else ''
switch (@_xhr.getResponseHeader('Content-Type') || '').split(';')[0]
when 'application/json', 'text/javascript'
# Workaround Android 2.3 failure to string-cast null input
responseText = JSON.parse(responseText + '')
responseText
###
# XMLHttpRequestPromise._getResponseUrl() -> String
#
# Actual response URL after following redirects.
###
_getResponseUrl: () ->
return @_xhr.responseURL if @_xhr.responseURL?
# Avoid security warnings on getResponseHeader when not allowed by CORS
return @_xhr.getResponseHeader('X-Request-URL') if /^X-Request-URL:/m.test(@_xhr.getAllResponseHeaders())
''
###
# XMLHttpRequestPromise._handleError(reason, reject, status, statusText)
# - reason (String)
# - reject (Function)
# - status (String)
# - statusText (String)
###
_handleError: (reason, reject, status, statusText) ->
@_detachWindowUnload()
reject(
reason : reason
status : status || @_xhr.status
statusText : statusText || @_xhr.statusText
xhr : @_xhr
)
###
# XMLHttpRequestPromise._handleWindowUnload()
###
_handleWindowUnload: () ->
@_xhr.abort()
| true | ###
# Copyright 2015 PI:NAME:<NAME>END_PI
# MIT License
# https://github.com/scottbrady/xhr-promise/blob/master/LICENSE
###
ParseHeaders = require 'parse-headers'
###
# Module to wrap an XMLHttpRequest in a promise.
###
module.exports = class XMLHttpRequestPromise
@DEFAULT_CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=UTF-8'
##########################################################################
## Public methods #######################################################
########################################################################
###
# XMLHttpRequestPromise.send(options) -> Promise
# - options (Object): URL, method, data, etc.
#
# Create the XHR object and wire up event handlers to use a promise.
###
send: (options={}) ->
defaults =
method : 'GET'
data : null
headers : {}
async : true
username : null
password : PI:PASSWORD:<PASSWORD>END_PI
withCredentials : false
options = Object.assign({}, defaults, options)
new Promise (resolve, reject) =>
if !XMLHttpRequest
@_handleError 'browser', reject, null, "browser doesn't support XMLHttpRequest"
return
if typeof options.url isnt 'string' || options.url.length is 0
@_handleError 'url', reject, null, 'URL is a required parameter'
return
# XMLHttpRequest is supported by IE 7+
@_xhr = xhr = new XMLHttpRequest
# success handler
xhr.onload = =>
@_detachWindowUnload()
try
responseText = @_getResponseText()
catch
@_handleError 'parse', reject, null, 'invalid JSON response'
return
resolve(
url : @_getResponseUrl()
status : xhr.status
statusText : xhr.statusText
responseText : responseText
headers : @_getHeaders()
xhr : xhr
)
# error handlers
xhr.onerror = => @_handleError 'error', reject
xhr.ontimeout = => @_handleError 'timeout', reject
xhr.onabort = => @_handleError 'abort', reject
@_attachWindowUnload()
xhr.open(options.method, options.url, options.async, options.username, options.password)
if options.withCredentials
xhr.withCredentials = true
if options.data? && !options.headers['Content-Type']
options.headers['Content-Type'] = @constructor.DEFAULT_CONTENT_TYPE
for header, value of options.headers
xhr.setRequestHeader(header, value)
try
xhr.send(options.data)
catch e
@_handleError 'send', reject, null, e.toString()
###
# XMLHttpRequestPromise.getXHR() -> XMLHttpRequest
###
getXHR: () ->
@_xhr
##########################################################################
## Psuedo-private methods ###############################################
########################################################################
###
# XMLHttpRequestPromise._attachWindowUnload()
#
# Fix for IE 9 and IE 10
# Internet Explorer freezes when you close a webpage during an XHR request
# https://support.microsoft.com/kb/2856746
#
###
_attachWindowUnload: () ->
@_unloadHandler = @_handleWindowUnload.bind(@)
window.attachEvent 'onunload', @_unloadHandler if window.attachEvent
###
# XMLHttpRequestPromise._detachWindowUnload()
###
_detachWindowUnload: () ->
window.detachEvent 'onunload', @_unloadHandler if window.detachEvent
###
# XMLHttpRequestPromise._getHeaders() -> Object
###
_getHeaders: () ->
ParseHeaders(@_xhr.getAllResponseHeaders())
###
# XMLHttpRequestPromise._getResponseText() -> Mixed
#
# Parses response text JSON if present.
###
_getResponseText: () ->
# Accessing binary-data responseText throws an exception in IE9
responseText = if typeof @_xhr.responseText is 'string' then @_xhr.responseText else ''
switch (@_xhr.getResponseHeader('Content-Type') || '').split(';')[0]
when 'application/json', 'text/javascript'
# Workaround Android 2.3 failure to string-cast null input
responseText = JSON.parse(responseText + '')
responseText
###
# XMLHttpRequestPromise._getResponseUrl() -> String
#
# Actual response URL after following redirects.
###
_getResponseUrl: () ->
return @_xhr.responseURL if @_xhr.responseURL?
# Avoid security warnings on getResponseHeader when not allowed by CORS
return @_xhr.getResponseHeader('X-Request-URL') if /^X-Request-URL:/m.test(@_xhr.getAllResponseHeaders())
''
###
# XMLHttpRequestPromise._handleError(reason, reject, status, statusText)
# - reason (String)
# - reject (Function)
# - status (String)
# - statusText (String)
###
_handleError: (reason, reject, status, statusText) ->
@_detachWindowUnload()
reject(
reason : reason
status : status || @_xhr.status
statusText : statusText || @_xhr.statusText
xhr : @_xhr
)
###
# XMLHttpRequestPromise._handleWindowUnload()
###
_handleWindowUnload: () ->
@_xhr.abort()
|
[
{
"context": "##\n * Federated Wiki : Node Server\n *\n * Copyright Ward Cunningham and other contributors\n * Licensed under the MIT ",
"end": 67,
"score": 0.9998807907104492,
"start": 52,
"tag": "NAME",
"value": "Ward Cunningham"
},
{
"context": "d under the MIT license.\n * https:... | server/friends.coffee | fedwiki/wiki-security-friends | 3 | ###
* Federated Wiki : Node Server
*
* Copyright Ward Cunningham and other contributors
* Licensed under the MIT license.
* https://github.com/fedwiki/wiki-node-server/blob/master/LICENSE.txt
###
# **security.coffee**
# Module for default site security.
#
# This module is not intented for use, but is here to catch a problem with
# configuration of security. It does not provide any authentication, but will
# allow the server to run read-only.
#### Requires ####
console.log 'friends starting'
fs = require 'fs'
seedrandom = require 'seedrandom'
# Export a function that generates security handler
# when called with options object.
module.exports = exports = (log, loga, argv) ->
security = {}
#### Private utility methods. ####
user = ''
owner = ''
admin = argv.admin
# save the location of the identity file
idFile = argv.id
nickname = (seed) ->
rn = seedrandom(seed)
c = "bcdfghjklmnprstvwy"
v = "aeiou"
ch = (string) -> string.charAt Math.floor rn() * string.length
ch(c) + ch(v) + ch(c) + ch(v) + ch(c) + ch(v)
#### Public stuff ####
# Retrieve owner infomation from identity file in status directory
# owner will contain { name: <name>, friend: {secret: '...'}}
security.retrieveOwner = (cb) ->
fs.exists idFile, (exists) ->
if exists
fs.readFile(idFile, (err, data) ->
if err then return cb err
owner = JSON.parse(data)
cb())
else
owner = ''
cb()
# Return the owners name
security.getOwner = getOwner = ->
if !owner.name?
ownerName = ''
else
ownerName = owner.name
ownerName
security.setOwner = setOwner = (id, cb) ->
owner = id
fs.exists idFile, (exists) ->
if !exists
fs.writeFile(idFile, JSON.stringify(id, null, " "), (err) ->
if err then return cb err
console.log "Claiming site for ", id:id
owner = id
cb())
else
cb()
security.getUser = (req) ->
if req.session.friend
return req.session.friend
else
return ''
security.isAuthorized = (req) ->
try
if req.session.friend is owner.friend.secret
return true
else
return false
catch error
return false
# Wiki server admin
security.isAdmin = (req) ->
if req.session.friend is admin
return true
else
return false
security.login = (updateOwner) ->
(req, res) ->
if owner is '' # site is not claimed
# create a secret and write it to owner file and the cookie
secret = require('crypto').randomBytes(32).toString('hex')
req.session.friend = secret
nick = nickname secret
id = {name: nick, friend: {secret: secret}}
setOwner id, (err) ->
if err
console.log 'Failed to claim wiki ', req.hostname, 'error ', err
res.sendStatus(500)
updateOwner getOwner
res.json({
ownerName: nick
})
res.end
else
console.log 'friend returning login'
res.sendStatus(501)
security.logout = () ->
(req, res) ->
req.session.reset()
res.send("OK")
security.reclaim = () ->
(req, res) ->
reclaimCode = ''
req.on('data', (chunk) ->
reclaimCode += chunk.toString())
req.on('end', () ->
try
if owner.friend.secret is reclaimCode
req.session.friend = owner.friend.secret
res.end()
else
res.sendStatus(401)
catch error
res.sendStatus(500))
security.defineRoutes = (app, cors, updateOwner) ->
app.post '/login', cors, security.login(updateOwner)
app.get '/logout', cors, security.logout()
app.post '/auth/reclaim/', cors, security.reclaim()
security
| 120464 | ###
* Federated Wiki : Node Server
*
* Copyright <NAME> and other contributors
* Licensed under the MIT license.
* https://github.com/fedwiki/wiki-node-server/blob/master/LICENSE.txt
###
# **security.coffee**
# Module for default site security.
#
# This module is not intented for use, but is here to catch a problem with
# configuration of security. It does not provide any authentication, but will
# allow the server to run read-only.
#### Requires ####
console.log 'friends starting'
fs = require 'fs'
seedrandom = require 'seedrandom'
# Export a function that generates security handler
# when called with options object.
module.exports = exports = (log, loga, argv) ->
security = {}
#### Private utility methods. ####
user = ''
owner = ''
admin = argv.admin
# save the location of the identity file
idFile = argv.id
nickname = (seed) ->
rn = seedrandom(seed)
c = "bcdfghjklmnprstvwy"
v = "aeiou"
ch = (string) -> string.charAt Math.floor rn() * string.length
ch(c) + ch(v) + ch(c) + ch(v) + ch(c) + ch(v)
#### Public stuff ####
# Retrieve owner infomation from identity file in status directory
# owner will contain { name: <name>, friend: {secret: '...'}}
security.retrieveOwner = (cb) ->
fs.exists idFile, (exists) ->
if exists
fs.readFile(idFile, (err, data) ->
if err then return cb err
owner = JSON.parse(data)
cb())
else
owner = ''
cb()
# Return the owners name
security.getOwner = getOwner = ->
if !owner.name?
ownerName = ''
else
ownerName = owner.name
ownerName
security.setOwner = setOwner = (id, cb) ->
owner = id
fs.exists idFile, (exists) ->
if !exists
fs.writeFile(idFile, JSON.stringify(id, null, " "), (err) ->
if err then return cb err
console.log "Claiming site for ", id:id
owner = id
cb())
else
cb()
security.getUser = (req) ->
if req.session.friend
return req.session.friend
else
return ''
security.isAuthorized = (req) ->
try
if req.session.friend is owner.friend.secret
return true
else
return false
catch error
return false
# Wiki server admin
security.isAdmin = (req) ->
if req.session.friend is admin
return true
else
return false
security.login = (updateOwner) ->
(req, res) ->
if owner is '' # site is not claimed
# create a secret and write it to owner file and the cookie
secret = require('crypto').randomBytes(32).toString('hex')
req.session.friend = secret
nick = nickname secret
id = {name: <NAME>, friend: {secret: secret}}
setOwner id, (err) ->
if err
console.log 'Failed to claim wiki ', req.hostname, 'error ', err
res.sendStatus(500)
updateOwner getOwner
res.json({
ownerName: <NAME>
})
res.end
else
console.log 'friend returning login'
res.sendStatus(501)
security.logout = () ->
(req, res) ->
req.session.reset()
res.send("OK")
security.reclaim = () ->
(req, res) ->
reclaimCode = ''
req.on('data', (chunk) ->
reclaimCode += chunk.toString())
req.on('end', () ->
try
if owner.friend.secret is reclaimCode
req.session.friend = owner.friend.secret
res.end()
else
res.sendStatus(401)
catch error
res.sendStatus(500))
security.defineRoutes = (app, cors, updateOwner) ->
app.post '/login', cors, security.login(updateOwner)
app.get '/logout', cors, security.logout()
app.post '/auth/reclaim/', cors, security.reclaim()
security
| true | ###
* Federated Wiki : Node Server
*
* Copyright PI:NAME:<NAME>END_PI and other contributors
* Licensed under the MIT license.
* https://github.com/fedwiki/wiki-node-server/blob/master/LICENSE.txt
###
# **security.coffee**
# Module for default site security.
#
# This module is not intented for use, but is here to catch a problem with
# configuration of security. It does not provide any authentication, but will
# allow the server to run read-only.
#### Requires ####
console.log 'friends starting'
fs = require 'fs'
seedrandom = require 'seedrandom'
# Export a function that generates security handler
# when called with options object.
module.exports = exports = (log, loga, argv) ->
security = {}
#### Private utility methods. ####
user = ''
owner = ''
admin = argv.admin
# save the location of the identity file
idFile = argv.id
nickname = (seed) ->
rn = seedrandom(seed)
c = "bcdfghjklmnprstvwy"
v = "aeiou"
ch = (string) -> string.charAt Math.floor rn() * string.length
ch(c) + ch(v) + ch(c) + ch(v) + ch(c) + ch(v)
#### Public stuff ####
# Retrieve owner infomation from identity file in status directory
# owner will contain { name: <name>, friend: {secret: '...'}}
security.retrieveOwner = (cb) ->
fs.exists idFile, (exists) ->
if exists
fs.readFile(idFile, (err, data) ->
if err then return cb err
owner = JSON.parse(data)
cb())
else
owner = ''
cb()
# Return the owners name
security.getOwner = getOwner = ->
if !owner.name?
ownerName = ''
else
ownerName = owner.name
ownerName
security.setOwner = setOwner = (id, cb) ->
owner = id
fs.exists idFile, (exists) ->
if !exists
fs.writeFile(idFile, JSON.stringify(id, null, " "), (err) ->
if err then return cb err
console.log "Claiming site for ", id:id
owner = id
cb())
else
cb()
security.getUser = (req) ->
if req.session.friend
return req.session.friend
else
return ''
security.isAuthorized = (req) ->
try
if req.session.friend is owner.friend.secret
return true
else
return false
catch error
return false
# Wiki server admin
security.isAdmin = (req) ->
if req.session.friend is admin
return true
else
return false
security.login = (updateOwner) ->
(req, res) ->
if owner is '' # site is not claimed
# create a secret and write it to owner file and the cookie
secret = require('crypto').randomBytes(32).toString('hex')
req.session.friend = secret
nick = nickname secret
id = {name: PI:NAME:<NAME>END_PI, friend: {secret: secret}}
setOwner id, (err) ->
if err
console.log 'Failed to claim wiki ', req.hostname, 'error ', err
res.sendStatus(500)
updateOwner getOwner
res.json({
ownerName: PI:NAME:<NAME>END_PI
})
res.end
else
console.log 'friend returning login'
res.sendStatus(501)
security.logout = () ->
(req, res) ->
req.session.reset()
res.send("OK")
security.reclaim = () ->
(req, res) ->
reclaimCode = ''
req.on('data', (chunk) ->
reclaimCode += chunk.toString())
req.on('end', () ->
try
if owner.friend.secret is reclaimCode
req.session.friend = owner.friend.secret
res.end()
else
res.sendStatus(401)
catch error
res.sendStatus(500))
security.defineRoutes = (app, cors, updateOwner) ->
app.post '/login', cors, security.login(updateOwner)
app.get '/logout', cors, security.logout()
app.post '/auth/reclaim/', cors, security.reclaim()
security
|
[
{
"context": "of: ['Experience']\n defaultValues: -> {name: 'Your name', age: 24}\n\n @property 'education',\n list:\n ",
"end": 337,
"score": 0.9887681007385254,
"start": 328,
"tag": "NAME",
"value": "Your name"
},
{
"context": "eof: ['Education']\n defaultValues: -> {n... | js/samples/resume_lists.coffee | vpj/models | 4 | Mod.require 'Models.Models',
'Models.Model.Base'
(MODELS, Base) ->
class Resume extends Base
@extend()
type: 'Resume'
@property 'name', {}
@property 'mobile', {}
@property 'website', {}
# @property 'address
@property 'experience',
list:
oneof: ['Experience']
defaultValues: -> {name: 'Your name', age: 24}
@property 'education',
list:
oneof: ['Education']
defaultValues: -> {name: 'Your name', age: 24}
template: (self) ->
values = self._values
@p "Name: #{values.name}"
@p "Mobile: #{values.mobile}"
@p "Website: #{values.website}"
if values.experience.length > 0
@div ->
@h4 "Experience"
for f in values.experience
@div ->
f.weya this
if values.education.length > 0
@div ->
@h4 "Education"
for f in values.education
@div ->
f.weya this
@check()
MODELS.register 'Resume', Resume
class Experience extends Base
@extend()
type: 'Experience'
@property 'from', {}
@property 'to', {}
@property 'company', {}
@property 'role', {}
template: (self) ->
values = self._values
@p "From #{values.from} To #{values.to}"
@p ->
@em "#{values.role}"
@p ->
@strong "#{values.company}"
@check()
MODELS.register 'Experience', Experience
class Education extends Base
@extend()
type: 'Education'
@property 'from', {}
@property 'to', {}
@property 'institute', {}
@property 'course', {}
template: (self) ->
values = self._values
@p "From #{values.from} To #{values.to}"
@p ->
@em "#{values.course}"
@p ->
@strong "#{values.institute}"
@check()
MODELS.register 'Education', Education
| 217135 | Mod.require 'Models.Models',
'Models.Model.Base'
(MODELS, Base) ->
class Resume extends Base
@extend()
type: 'Resume'
@property 'name', {}
@property 'mobile', {}
@property 'website', {}
# @property 'address
@property 'experience',
list:
oneof: ['Experience']
defaultValues: -> {name: '<NAME>', age: 24}
@property 'education',
list:
oneof: ['Education']
defaultValues: -> {name: '<NAME>', age: 24}
template: (self) ->
values = self._values
@p "Name: #{values.name}"
@p "Mobile: #{values.mobile}"
@p "Website: #{values.website}"
if values.experience.length > 0
@div ->
@h4 "Experience"
for f in values.experience
@div ->
f.weya this
if values.education.length > 0
@div ->
@h4 "Education"
for f in values.education
@div ->
f.weya this
@check()
MODELS.register 'Resume', Resume
class Experience extends Base
@extend()
type: 'Experience'
@property 'from', {}
@property 'to', {}
@property 'company', {}
@property 'role', {}
template: (self) ->
values = self._values
@p "From #{values.from} To #{values.to}"
@p ->
@em "#{values.role}"
@p ->
@strong "#{values.company}"
@check()
MODELS.register 'Experience', Experience
class Education extends Base
@extend()
type: 'Education'
@property 'from', {}
@property 'to', {}
@property 'institute', {}
@property 'course', {}
template: (self) ->
values = self._values
@p "From #{values.from} To #{values.to}"
@p ->
@em "#{values.course}"
@p ->
@strong "#{values.institute}"
@check()
MODELS.register 'Education', Education
| true | Mod.require 'Models.Models',
'Models.Model.Base'
(MODELS, Base) ->
class Resume extends Base
@extend()
type: 'Resume'
@property 'name', {}
@property 'mobile', {}
@property 'website', {}
# @property 'address
@property 'experience',
list:
oneof: ['Experience']
defaultValues: -> {name: 'PI:NAME:<NAME>END_PI', age: 24}
@property 'education',
list:
oneof: ['Education']
defaultValues: -> {name: 'PI:NAME:<NAME>END_PI', age: 24}
template: (self) ->
values = self._values
@p "Name: #{values.name}"
@p "Mobile: #{values.mobile}"
@p "Website: #{values.website}"
if values.experience.length > 0
@div ->
@h4 "Experience"
for f in values.experience
@div ->
f.weya this
if values.education.length > 0
@div ->
@h4 "Education"
for f in values.education
@div ->
f.weya this
@check()
MODELS.register 'Resume', Resume
class Experience extends Base
@extend()
type: 'Experience'
@property 'from', {}
@property 'to', {}
@property 'company', {}
@property 'role', {}
template: (self) ->
values = self._values
@p "From #{values.from} To #{values.to}"
@p ->
@em "#{values.role}"
@p ->
@strong "#{values.company}"
@check()
MODELS.register 'Experience', Experience
class Education extends Base
@extend()
type: 'Education'
@property 'from', {}
@property 'to', {}
@property 'institute', {}
@property 'course', {}
template: (self) ->
values = self._values
@p "From #{values.from} To #{values.to}"
@p ->
@em "#{values.course}"
@p ->
@strong "#{values.institute}"
@check()
MODELS.register 'Education', Education
|
[
{
"context": "card_travel\"\n unicode: \"e8f8\"\n }\n {\n id: \"casino\"\n unicode: \"eb40\"\n }\n {\n id: \"cast\"\n u",
"end": 7516,
"score": 0.8115791082382202,
"start": 7510,
"tag": "NAME",
"value": "casino"
},
{
"context": "ettings_new\"\n unicode: \"e8ac\"... | character-list/character-list.cson | gluons/material-design-icon-chars | 0 | icons: [
{
id: "3d_rotation"
unicode: "e84d"
}
{
id: "ac_unit"
unicode: "eb3b"
}
{
id: "access_alarm"
unicode: "e190"
}
{
id: "access_alarms"
unicode: "e191"
}
{
id: "access_time"
unicode: "e192"
}
{
id: "accessibility"
unicode: "e84e"
}
{
id: "accessible"
unicode: "e914"
}
{
id: "account_balance"
unicode: "e84f"
}
{
id: "account_balance_wallet"
unicode: "e850"
}
{
id: "account_box"
unicode: "e851"
}
{
id: "account_circle"
unicode: "e853"
}
{
id: "adb"
unicode: "e60e"
}
{
id: "add"
unicode: "e145"
}
{
id: "add_a_photo"
unicode: "e439"
}
{
id: "add_alarm"
unicode: "e193"
}
{
id: "add_alert"
unicode: "e003"
}
{
id: "add_box"
unicode: "e146"
}
{
id: "add_circle"
unicode: "e147"
}
{
id: "add_circle_outline"
unicode: "e148"
}
{
id: "add_location"
unicode: "e567"
}
{
id: "add_shopping_cart"
unicode: "e854"
}
{
id: "add_to_photos"
unicode: "e39d"
}
{
id: "add_to_queue"
unicode: "e05c"
}
{
id: "adjust"
unicode: "e39e"
}
{
id: "airline_seat_flat"
unicode: "e630"
}
{
id: "airline_seat_flat_angled"
unicode: "e631"
}
{
id: "airline_seat_individual_suite"
unicode: "e632"
}
{
id: "airline_seat_legroom_extra"
unicode: "e633"
}
{
id: "airline_seat_legroom_normal"
unicode: "e634"
}
{
id: "airline_seat_legroom_reduced"
unicode: "e635"
}
{
id: "airline_seat_recline_extra"
unicode: "e636"
}
{
id: "airline_seat_recline_normal"
unicode: "e637"
}
{
id: "airplanemode_active"
unicode: "e195"
}
{
id: "airplanemode_inactive"
unicode: "e194"
}
{
id: "airplay"
unicode: "e055"
}
{
id: "airport_shuttle"
unicode: "eb3c"
}
{
id: "alarm"
unicode: "e855"
}
{
id: "alarm_add"
unicode: "e856"
}
{
id: "alarm_off"
unicode: "e857"
}
{
id: "alarm_on"
unicode: "e858"
}
{
id: "album"
unicode: "e019"
}
{
id: "all_inclusive"
unicode: "eb3d"
}
{
id: "all_out"
unicode: "e90b"
}
{
id: "android"
unicode: "e859"
}
{
id: "announcement"
unicode: "e85a"
}
{
id: "apps"
unicode: "e5c3"
}
{
id: "archive"
unicode: "e149"
}
{
id: "arrow_back"
unicode: "e5c4"
}
{
id: "arrow_downward"
unicode: "e5db"
}
{
id: "arrow_drop_down"
unicode: "e5c5"
}
{
id: "arrow_drop_down_circle"
unicode: "e5c6"
}
{
id: "arrow_drop_up"
unicode: "e5c7"
}
{
id: "arrow_forward"
unicode: "e5c8"
}
{
id: "arrow_upward"
unicode: "e5d8"
}
{
id: "art_track"
unicode: "e060"
}
{
id: "aspect_ratio"
unicode: "e85b"
}
{
id: "assessment"
unicode: "e85c"
}
{
id: "assignment"
unicode: "e85d"
}
{
id: "assignment_ind"
unicode: "e85e"
}
{
id: "assignment_late"
unicode: "e85f"
}
{
id: "assignment_return"
unicode: "e860"
}
{
id: "assignment_returned"
unicode: "e861"
}
{
id: "assignment_turned_in"
unicode: "e862"
}
{
id: "assistant"
unicode: "e39f"
}
{
id: "assistant_photo"
unicode: "e3a0"
}
{
id: "attach_file"
unicode: "e226"
}
{
id: "attach_money"
unicode: "e227"
}
{
id: "attachment"
unicode: "e2bc"
}
{
id: "audiotrack"
unicode: "e3a1"
}
{
id: "autorenew"
unicode: "e863"
}
{
id: "av_timer"
unicode: "e01b"
}
{
id: "backspace"
unicode: "e14a"
}
{
id: "backup"
unicode: "e864"
}
{
id: "battery_alert"
unicode: "e19c"
}
{
id: "battery_charging_full"
unicode: "e1a3"
}
{
id: "battery_full"
unicode: "e1a4"
}
{
id: "battery_std"
unicode: "e1a5"
}
{
id: "battery_unknown"
unicode: "e1a6"
}
{
id: "beach_access"
unicode: "eb3e"
}
{
id: "beenhere"
unicode: "e52d"
}
{
id: "block"
unicode: "e14b"
}
{
id: "bluetooth"
unicode: "e1a7"
}
{
id: "bluetooth_audio"
unicode: "e60f"
}
{
id: "bluetooth_connected"
unicode: "e1a8"
}
{
id: "bluetooth_disabled"
unicode: "e1a9"
}
{
id: "bluetooth_searching"
unicode: "e1aa"
}
{
id: "blur_circular"
unicode: "e3a2"
}
{
id: "blur_linear"
unicode: "e3a3"
}
{
id: "blur_off"
unicode: "e3a4"
}
{
id: "blur_on"
unicode: "e3a5"
}
{
id: "book"
unicode: "e865"
}
{
id: "bookmark"
unicode: "e866"
}
{
id: "bookmark_border"
unicode: "e867"
}
{
id: "border_all"
unicode: "e228"
}
{
id: "border_bottom"
unicode: "e229"
}
{
id: "border_clear"
unicode: "e22a"
}
{
id: "border_color"
unicode: "e22b"
}
{
id: "border_horizontal"
unicode: "e22c"
}
{
id: "border_inner"
unicode: "e22d"
}
{
id: "border_left"
unicode: "e22e"
}
{
id: "border_outer"
unicode: "e22f"
}
{
id: "border_right"
unicode: "e230"
}
{
id: "border_style"
unicode: "e231"
}
{
id: "border_top"
unicode: "e232"
}
{
id: "border_vertical"
unicode: "e233"
}
{
id: "branding_watermark"
unicode: "e06b"
}
{
id: "brightness_1"
unicode: "e3a6"
}
{
id: "brightness_2"
unicode: "e3a7"
}
{
id: "brightness_3"
unicode: "e3a8"
}
{
id: "brightness_4"
unicode: "e3a9"
}
{
id: "brightness_5"
unicode: "e3aa"
}
{
id: "brightness_6"
unicode: "e3ab"
}
{
id: "brightness_7"
unicode: "e3ac"
}
{
id: "brightness_auto"
unicode: "e1ab"
}
{
id: "brightness_high"
unicode: "e1ac"
}
{
id: "brightness_low"
unicode: "e1ad"
}
{
id: "brightness_medium"
unicode: "e1ae"
}
{
id: "broken_image"
unicode: "e3ad"
}
{
id: "brush"
unicode: "e3ae"
}
{
id: "bubble_chart"
unicode: "e6dd"
}
{
id: "bug_report"
unicode: "e868"
}
{
id: "build"
unicode: "e869"
}
{
id: "burst_mode"
unicode: "e43c"
}
{
id: "business"
unicode: "e0af"
}
{
id: "business_center"
unicode: "eb3f"
}
{
id: "cached"
unicode: "e86a"
}
{
id: "cake"
unicode: "e7e9"
}
{
id: "call"
unicode: "e0b0"
}
{
id: "call_end"
unicode: "e0b1"
}
{
id: "call_made"
unicode: "e0b2"
}
{
id: "call_merge"
unicode: "e0b3"
}
{
id: "call_missed"
unicode: "e0b4"
}
{
id: "call_missed_outgoing"
unicode: "e0e4"
}
{
id: "call_received"
unicode: "e0b5"
}
{
id: "call_split"
unicode: "e0b6"
}
{
id: "call_to_action"
unicode: "e06c"
}
{
id: "camera"
unicode: "e3af"
}
{
id: "camera_alt"
unicode: "e3b0"
}
{
id: "camera_enhance"
unicode: "e8fc"
}
{
id: "camera_front"
unicode: "e3b1"
}
{
id: "camera_rear"
unicode: "e3b2"
}
{
id: "camera_roll"
unicode: "e3b3"
}
{
id: "cancel"
unicode: "e5c9"
}
{
id: "card_giftcard"
unicode: "e8f6"
}
{
id: "card_membership"
unicode: "e8f7"
}
{
id: "card_travel"
unicode: "e8f8"
}
{
id: "casino"
unicode: "eb40"
}
{
id: "cast"
unicode: "e307"
}
{
id: "cast_connected"
unicode: "e308"
}
{
id: "center_focus_strong"
unicode: "e3b4"
}
{
id: "center_focus_weak"
unicode: "e3b5"
}
{
id: "change_history"
unicode: "e86b"
}
{
id: "chat"
unicode: "e0b7"
}
{
id: "chat_bubble"
unicode: "e0ca"
}
{
id: "chat_bubble_outline"
unicode: "e0cb"
}
{
id: "check"
unicode: "e5ca"
}
{
id: "check_box"
unicode: "e834"
}
{
id: "check_box_outline_blank"
unicode: "e835"
}
{
id: "check_circle"
unicode: "e86c"
}
{
id: "chevron_left"
unicode: "e5cb"
}
{
id: "chevron_right"
unicode: "e5cc"
}
{
id: "child_care"
unicode: "eb41"
}
{
id: "child_friendly"
unicode: "eb42"
}
{
id: "chrome_reader_mode"
unicode: "e86d"
}
{
id: "class"
unicode: "e86e"
}
{
id: "clear"
unicode: "e14c"
}
{
id: "clear_all"
unicode: "e0b8"
}
{
id: "close"
unicode: "e5cd"
}
{
id: "closed_caption"
unicode: "e01c"
}
{
id: "cloud"
unicode: "e2bd"
}
{
id: "cloud_circle"
unicode: "e2be"
}
{
id: "cloud_done"
unicode: "e2bf"
}
{
id: "cloud_download"
unicode: "e2c0"
}
{
id: "cloud_off"
unicode: "e2c1"
}
{
id: "cloud_queue"
unicode: "e2c2"
}
{
id: "cloud_upload"
unicode: "e2c3"
}
{
id: "code"
unicode: "e86f"
}
{
id: "collections"
unicode: "e3b6"
}
{
id: "collections_bookmark"
unicode: "e431"
}
{
id: "color_lens"
unicode: "e3b7"
}
{
id: "colorize"
unicode: "e3b8"
}
{
id: "comment"
unicode: "e0b9"
}
{
id: "compare"
unicode: "e3b9"
}
{
id: "compare_arrows"
unicode: "e915"
}
{
id: "computer"
unicode: "e30a"
}
{
id: "confirmation_number"
unicode: "e638"
}
{
id: "contact_mail"
unicode: "e0d0"
}
{
id: "contact_phone"
unicode: "e0cf"
}
{
id: "contacts"
unicode: "e0ba"
}
{
id: "content_copy"
unicode: "e14d"
}
{
id: "content_cut"
unicode: "e14e"
}
{
id: "content_paste"
unicode: "e14f"
}
{
id: "control_point"
unicode: "e3ba"
}
{
id: "control_point_duplicate"
unicode: "e3bb"
}
{
id: "copyright"
unicode: "e90c"
}
{
id: "create"
unicode: "e150"
}
{
id: "create_new_folder"
unicode: "e2cc"
}
{
id: "credit_card"
unicode: "e870"
}
{
id: "crop"
unicode: "e3be"
}
{
id: "crop_16_9"
unicode: "e3bc"
}
{
id: "crop_3_2"
unicode: "e3bd"
}
{
id: "crop_5_4"
unicode: "e3bf"
}
{
id: "crop_7_5"
unicode: "e3c0"
}
{
id: "crop_din"
unicode: "e3c1"
}
{
id: "crop_free"
unicode: "e3c2"
}
{
id: "crop_landscape"
unicode: "e3c3"
}
{
id: "crop_original"
unicode: "e3c4"
}
{
id: "crop_portrait"
unicode: "e3c5"
}
{
id: "crop_rotate"
unicode: "e437"
}
{
id: "crop_square"
unicode: "e3c6"
}
{
id: "dashboard"
unicode: "e871"
}
{
id: "data_usage"
unicode: "e1af"
}
{
id: "date_range"
unicode: "e916"
}
{
id: "dehaze"
unicode: "e3c7"
}
{
id: "delete"
unicode: "e872"
}
{
id: "delete_forever"
unicode: "e92b"
}
{
id: "delete_sweep"
unicode: "e16c"
}
{
id: "description"
unicode: "e873"
}
{
id: "desktop_mac"
unicode: "e30b"
}
{
id: "desktop_windows"
unicode: "e30c"
}
{
id: "details"
unicode: "e3c8"
}
{
id: "developer_board"
unicode: "e30d"
}
{
id: "developer_mode"
unicode: "e1b0"
}
{
id: "device_hub"
unicode: "e335"
}
{
id: "devices"
unicode: "e1b1"
}
{
id: "devices_other"
unicode: "e337"
}
{
id: "dialer_sip"
unicode: "e0bb"
}
{
id: "dialpad"
unicode: "e0bc"
}
{
id: "directions"
unicode: "e52e"
}
{
id: "directions_bike"
unicode: "e52f"
}
{
id: "directions_boat"
unicode: "e532"
}
{
id: "directions_bus"
unicode: "e530"
}
{
id: "directions_car"
unicode: "e531"
}
{
id: "directions_railway"
unicode: "e534"
}
{
id: "directions_run"
unicode: "e566"
}
{
id: "directions_subway"
unicode: "e533"
}
{
id: "directions_transit"
unicode: "e535"
}
{
id: "directions_walk"
unicode: "e536"
}
{
id: "disc_full"
unicode: "e610"
}
{
id: "dns"
unicode: "e875"
}
{
id: "do_not_disturb"
unicode: "e612"
}
{
id: "do_not_disturb_alt"
unicode: "e611"
}
{
id: "do_not_disturb_off"
unicode: "e643"
}
{
id: "do_not_disturb_on"
unicode: "e644"
}
{
id: "dock"
unicode: "e30e"
}
{
id: "domain"
unicode: "e7ee"
}
{
id: "done"
unicode: "e876"
}
{
id: "done_all"
unicode: "e877"
}
{
id: "donut_large"
unicode: "e917"
}
{
id: "donut_small"
unicode: "e918"
}
{
id: "drafts"
unicode: "e151"
}
{
id: "drag_handle"
unicode: "e25d"
}
{
id: "drive_eta"
unicode: "e613"
}
{
id: "dvr"
unicode: "e1b2"
}
{
id: "edit"
unicode: "e3c9"
}
{
id: "edit_location"
unicode: "e568"
}
{
id: "eject"
unicode: "e8fb"
}
{
id: "email"
unicode: "e0be"
}
{
id: "enhanced_encryption"
unicode: "e63f"
}
{
id: "equalizer"
unicode: "e01d"
}
{
id: "error"
unicode: "e000"
}
{
id: "error_outline"
unicode: "e001"
}
{
id: "euro_symbol"
unicode: "e926"
}
{
id: "ev_station"
unicode: "e56d"
}
{
id: "event"
unicode: "e878"
}
{
id: "event_available"
unicode: "e614"
}
{
id: "event_busy"
unicode: "e615"
}
{
id: "event_note"
unicode: "e616"
}
{
id: "event_seat"
unicode: "e903"
}
{
id: "exit_to_app"
unicode: "e879"
}
{
id: "expand_less"
unicode: "e5ce"
}
{
id: "expand_more"
unicode: "e5cf"
}
{
id: "explicit"
unicode: "e01e"
}
{
id: "explore"
unicode: "e87a"
}
{
id: "exposure"
unicode: "e3ca"
}
{
id: "exposure_neg_1"
unicode: "e3cb"
}
{
id: "exposure_neg_2"
unicode: "e3cc"
}
{
id: "exposure_plus_1"
unicode: "e3cd"
}
{
id: "exposure_plus_2"
unicode: "e3ce"
}
{
id: "exposure_zero"
unicode: "e3cf"
}
{
id: "extension"
unicode: "e87b"
}
{
id: "face"
unicode: "e87c"
}
{
id: "fast_forward"
unicode: "e01f"
}
{
id: "fast_rewind"
unicode: "e020"
}
{
id: "favorite"
unicode: "e87d"
}
{
id: "favorite_border"
unicode: "e87e"
}
{
id: "featured_play_list"
unicode: "e06d"
}
{
id: "featured_video"
unicode: "e06e"
}
{
id: "feedback"
unicode: "e87f"
}
{
id: "fiber_dvr"
unicode: "e05d"
}
{
id: "fiber_manual_record"
unicode: "e061"
}
{
id: "fiber_new"
unicode: "e05e"
}
{
id: "fiber_pin"
unicode: "e06a"
}
{
id: "fiber_smart_record"
unicode: "e062"
}
{
id: "file_download"
unicode: "e2c4"
}
{
id: "file_upload"
unicode: "e2c6"
}
{
id: "filter"
unicode: "e3d3"
}
{
id: "filter_1"
unicode: "e3d0"
}
{
id: "filter_2"
unicode: "e3d1"
}
{
id: "filter_3"
unicode: "e3d2"
}
{
id: "filter_4"
unicode: "e3d4"
}
{
id: "filter_5"
unicode: "e3d5"
}
{
id: "filter_6"
unicode: "e3d6"
}
{
id: "filter_7"
unicode: "e3d7"
}
{
id: "filter_8"
unicode: "e3d8"
}
{
id: "filter_9"
unicode: "e3d9"
}
{
id: "filter_9_plus"
unicode: "e3da"
}
{
id: "filter_b_and_w"
unicode: "e3db"
}
{
id: "filter_center_focus"
unicode: "e3dc"
}
{
id: "filter_drama"
unicode: "e3dd"
}
{
id: "filter_frames"
unicode: "e3de"
}
{
id: "filter_hdr"
unicode: "e3df"
}
{
id: "filter_list"
unicode: "e152"
}
{
id: "filter_none"
unicode: "e3e0"
}
{
id: "filter_tilt_shift"
unicode: "e3e2"
}
{
id: "filter_vintage"
unicode: "e3e3"
}
{
id: "find_in_page"
unicode: "e880"
}
{
id: "find_replace"
unicode: "e881"
}
{
id: "fingerprint"
unicode: "e90d"
}
{
id: "first_page"
unicode: "e5dc"
}
{
id: "fitness_center"
unicode: "eb43"
}
{
id: "flag"
unicode: "e153"
}
{
id: "flare"
unicode: "e3e4"
}
{
id: "flash_auto"
unicode: "e3e5"
}
{
id: "flash_off"
unicode: "e3e6"
}
{
id: "flash_on"
unicode: "e3e7"
}
{
id: "flight"
unicode: "e539"
}
{
id: "flight_land"
unicode: "e904"
}
{
id: "flight_takeoff"
unicode: "e905"
}
{
id: "flip"
unicode: "e3e8"
}
{
id: "flip_to_back"
unicode: "e882"
}
{
id: "flip_to_front"
unicode: "e883"
}
{
id: "folder"
unicode: "e2c7"
}
{
id: "folder_open"
unicode: "e2c8"
}
{
id: "folder_shared"
unicode: "e2c9"
}
{
id: "folder_special"
unicode: "e617"
}
{
id: "font_download"
unicode: "e167"
}
{
id: "format_align_center"
unicode: "e234"
}
{
id: "format_align_justify"
unicode: "e235"
}
{
id: "format_align_left"
unicode: "e236"
}
{
id: "format_align_right"
unicode: "e237"
}
{
id: "format_bold"
unicode: "e238"
}
{
id: "format_clear"
unicode: "e239"
}
{
id: "format_color_fill"
unicode: "e23a"
}
{
id: "format_color_reset"
unicode: "e23b"
}
{
id: "format_color_text"
unicode: "e23c"
}
{
id: "format_indent_decrease"
unicode: "e23d"
}
{
id: "format_indent_increase"
unicode: "e23e"
}
{
id: "format_italic"
unicode: "e23f"
}
{
id: "format_line_spacing"
unicode: "e240"
}
{
id: "format_list_bulleted"
unicode: "e241"
}
{
id: "format_list_numbered"
unicode: "e242"
}
{
id: "format_paint"
unicode: "e243"
}
{
id: "format_quote"
unicode: "e244"
}
{
id: "format_shapes"
unicode: "e25e"
}
{
id: "format_size"
unicode: "e245"
}
{
id: "format_strikethrough"
unicode: "e246"
}
{
id: "format_textdirection_l_to_r"
unicode: "e247"
}
{
id: "format_textdirection_r_to_l"
unicode: "e248"
}
{
id: "format_underlined"
unicode: "e249"
}
{
id: "forum"
unicode: "e0bf"
}
{
id: "forward"
unicode: "e154"
}
{
id: "forward_10"
unicode: "e056"
}
{
id: "forward_30"
unicode: "e057"
}
{
id: "forward_5"
unicode: "e058"
}
{
id: "free_breakfast"
unicode: "eb44"
}
{
id: "fullscreen"
unicode: "e5d0"
}
{
id: "fullscreen_exit"
unicode: "e5d1"
}
{
id: "functions"
unicode: "e24a"
}
{
id: "g_translate"
unicode: "e927"
}
{
id: "gamepad"
unicode: "e30f"
}
{
id: "games"
unicode: "e021"
}
{
id: "gavel"
unicode: "e90e"
}
{
id: "gesture"
unicode: "e155"
}
{
id: "get_app"
unicode: "e884"
}
{
id: "gif"
unicode: "e908"
}
{
id: "golf_course"
unicode: "eb45"
}
{
id: "gps_fixed"
unicode: "e1b3"
}
{
id: "gps_not_fixed"
unicode: "e1b4"
}
{
id: "gps_off"
unicode: "e1b5"
}
{
id: "grade"
unicode: "e885"
}
{
id: "gradient"
unicode: "e3e9"
}
{
id: "grain"
unicode: "e3ea"
}
{
id: "graphic_eq"
unicode: "e1b8"
}
{
id: "grid_off"
unicode: "e3eb"
}
{
id: "grid_on"
unicode: "e3ec"
}
{
id: "group"
unicode: "e7ef"
}
{
id: "group_add"
unicode: "e7f0"
}
{
id: "group_work"
unicode: "e886"
}
{
id: "hd"
unicode: "e052"
}
{
id: "hdr_off"
unicode: "e3ed"
}
{
id: "hdr_on"
unicode: "e3ee"
}
{
id: "hdr_strong"
unicode: "e3f1"
}
{
id: "hdr_weak"
unicode: "e3f2"
}
{
id: "headset"
unicode: "e310"
}
{
id: "headset_mic"
unicode: "e311"
}
{
id: "healing"
unicode: "e3f3"
}
{
id: "hearing"
unicode: "e023"
}
{
id: "help"
unicode: "e887"
}
{
id: "help_outline"
unicode: "e8fd"
}
{
id: "high_quality"
unicode: "e024"
}
{
id: "highlight"
unicode: "e25f"
}
{
id: "highlight_off"
unicode: "e888"
}
{
id: "history"
unicode: "e889"
}
{
id: "home"
unicode: "e88a"
}
{
id: "hot_tub"
unicode: "eb46"
}
{
id: "hotel"
unicode: "e53a"
}
{
id: "hourglass_empty"
unicode: "e88b"
}
{
id: "hourglass_full"
unicode: "e88c"
}
{
id: "http"
unicode: "e902"
}
{
id: "https"
unicode: "e88d"
}
{
id: "image"
unicode: "e3f4"
}
{
id: "image_aspect_ratio"
unicode: "e3f5"
}
{
id: "import_contacts"
unicode: "e0e0"
}
{
id: "import_export"
unicode: "e0c3"
}
{
id: "important_devices"
unicode: "e912"
}
{
id: "inbox"
unicode: "e156"
}
{
id: "indeterminate_check_box"
unicode: "e909"
}
{
id: "info"
unicode: "e88e"
}
{
id: "info_outline"
unicode: "e88f"
}
{
id: "input"
unicode: "e890"
}
{
id: "insert_chart"
unicode: "e24b"
}
{
id: "insert_comment"
unicode: "e24c"
}
{
id: "insert_drive_file"
unicode: "e24d"
}
{
id: "insert_emoticon"
unicode: "e24e"
}
{
id: "insert_invitation"
unicode: "e24f"
}
{
id: "insert_link"
unicode: "e250"
}
{
id: "insert_photo"
unicode: "e251"
}
{
id: "invert_colors"
unicode: "e891"
}
{
id: "invert_colors_off"
unicode: "e0c4"
}
{
id: "iso"
unicode: "e3f6"
}
{
id: "keyboard"
unicode: "e312"
}
{
id: "keyboard_arrow_down"
unicode: "e313"
}
{
id: "keyboard_arrow_left"
unicode: "e314"
}
{
id: "keyboard_arrow_right"
unicode: "e315"
}
{
id: "keyboard_arrow_up"
unicode: "e316"
}
{
id: "keyboard_backspace"
unicode: "e317"
}
{
id: "keyboard_capslock"
unicode: "e318"
}
{
id: "keyboard_hide"
unicode: "e31a"
}
{
id: "keyboard_return"
unicode: "e31b"
}
{
id: "keyboard_tab"
unicode: "e31c"
}
{
id: "keyboard_voice"
unicode: "e31d"
}
{
id: "kitchen"
unicode: "eb47"
}
{
id: "label"
unicode: "e892"
}
{
id: "label_outline"
unicode: "e893"
}
{
id: "landscape"
unicode: "e3f7"
}
{
id: "language"
unicode: "e894"
}
{
id: "laptop"
unicode: "e31e"
}
{
id: "laptop_chromebook"
unicode: "e31f"
}
{
id: "laptop_mac"
unicode: "e320"
}
{
id: "laptop_windows"
unicode: "e321"
}
{
id: "last_page"
unicode: "e5dd"
}
{
id: "launch"
unicode: "e895"
}
{
id: "layers"
unicode: "e53b"
}
{
id: "layers_clear"
unicode: "e53c"
}
{
id: "leak_add"
unicode: "e3f8"
}
{
id: "leak_remove"
unicode: "e3f9"
}
{
id: "lens"
unicode: "e3fa"
}
{
id: "library_add"
unicode: "e02e"
}
{
id: "library_books"
unicode: "e02f"
}
{
id: "library_music"
unicode: "e030"
}
{
id: "lightbulb_outline"
unicode: "e90f"
}
{
id: "line_style"
unicode: "e919"
}
{
id: "line_weight"
unicode: "e91a"
}
{
id: "linear_scale"
unicode: "e260"
}
{
id: "link"
unicode: "e157"
}
{
id: "linked_camera"
unicode: "e438"
}
{
id: "list"
unicode: "e896"
}
{
id: "live_help"
unicode: "e0c6"
}
{
id: "live_tv"
unicode: "e639"
}
{
id: "local_activity"
unicode: "e53f"
}
{
id: "local_airport"
unicode: "e53d"
}
{
id: "local_atm"
unicode: "e53e"
}
{
id: "local_bar"
unicode: "e540"
}
{
id: "local_cafe"
unicode: "e541"
}
{
id: "local_car_wash"
unicode: "e542"
}
{
id: "local_convenience_store"
unicode: "e543"
}
{
id: "local_dining"
unicode: "e556"
}
{
id: "local_drink"
unicode: "e544"
}
{
id: "local_florist"
unicode: "e545"
}
{
id: "local_gas_station"
unicode: "e546"
}
{
id: "local_grocery_store"
unicode: "e547"
}
{
id: "local_hospital"
unicode: "e548"
}
{
id: "local_hotel"
unicode: "e549"
}
{
id: "local_laundry_service"
unicode: "e54a"
}
{
id: "local_library"
unicode: "e54b"
}
{
id: "local_mall"
unicode: "e54c"
}
{
id: "local_movies"
unicode: "e54d"
}
{
id: "local_offer"
unicode: "e54e"
}
{
id: "local_parking"
unicode: "e54f"
}
{
id: "local_pharmacy"
unicode: "e550"
}
{
id: "local_phone"
unicode: "e551"
}
{
id: "local_pizza"
unicode: "e552"
}
{
id: "local_play"
unicode: "e553"
}
{
id: "local_post_office"
unicode: "e554"
}
{
id: "local_printshop"
unicode: "e555"
}
{
id: "local_see"
unicode: "e557"
}
{
id: "local_shipping"
unicode: "e558"
}
{
id: "local_taxi"
unicode: "e559"
}
{
id: "location_city"
unicode: "e7f1"
}
{
id: "location_disabled"
unicode: "e1b6"
}
{
id: "location_off"
unicode: "e0c7"
}
{
id: "location_on"
unicode: "e0c8"
}
{
id: "location_searching"
unicode: "e1b7"
}
{
id: "lock"
unicode: "e897"
}
{
id: "lock_open"
unicode: "e898"
}
{
id: "lock_outline"
unicode: "e899"
}
{
id: "looks"
unicode: "e3fc"
}
{
id: "looks_3"
unicode: "e3fb"
}
{
id: "looks_4"
unicode: "e3fd"
}
{
id: "looks_5"
unicode: "e3fe"
}
{
id: "looks_6"
unicode: "e3ff"
}
{
id: "looks_one"
unicode: "e400"
}
{
id: "looks_two"
unicode: "e401"
}
{
id: "loop"
unicode: "e028"
}
{
id: "loupe"
unicode: "e402"
}
{
id: "low_priority"
unicode: "e16d"
}
{
id: "loyalty"
unicode: "e89a"
}
{
id: "mail"
unicode: "e158"
}
{
id: "mail_outline"
unicode: "e0e1"
}
{
id: "map"
unicode: "e55b"
}
{
id: "markunread"
unicode: "e159"
}
{
id: "markunread_mailbox"
unicode: "e89b"
}
{
id: "memory"
unicode: "e322"
}
{
id: "menu"
unicode: "e5d2"
}
{
id: "merge_type"
unicode: "e252"
}
{
id: "message"
unicode: "e0c9"
}
{
id: "mic"
unicode: "e029"
}
{
id: "mic_none"
unicode: "e02a"
}
{
id: "mic_off"
unicode: "e02b"
}
{
id: "mms"
unicode: "e618"
}
{
id: "mode_comment"
unicode: "e253"
}
{
id: "mode_edit"
unicode: "e254"
}
{
id: "monetization_on"
unicode: "e263"
}
{
id: "money_off"
unicode: "e25c"
}
{
id: "monochrome_photos"
unicode: "e403"
}
{
id: "mood"
unicode: "e7f2"
}
{
id: "mood_bad"
unicode: "e7f3"
}
{
id: "more"
unicode: "e619"
}
{
id: "more_horiz"
unicode: "e5d3"
}
{
id: "more_vert"
unicode: "e5d4"
}
{
id: "motorcycle"
unicode: "e91b"
}
{
id: "mouse"
unicode: "e323"
}
{
id: "move_to_inbox"
unicode: "e168"
}
{
id: "movie"
unicode: "e02c"
}
{
id: "movie_creation"
unicode: "e404"
}
{
id: "movie_filter"
unicode: "e43a"
}
{
id: "multiline_chart"
unicode: "e6df"
}
{
id: "music_note"
unicode: "e405"
}
{
id: "music_video"
unicode: "e063"
}
{
id: "my_location"
unicode: "e55c"
}
{
id: "nature"
unicode: "e406"
}
{
id: "nature_people"
unicode: "e407"
}
{
id: "navigate_before"
unicode: "e408"
}
{
id: "navigate_next"
unicode: "e409"
}
{
id: "navigation"
unicode: "e55d"
}
{
id: "near_me"
unicode: "e569"
}
{
id: "network_cell"
unicode: "e1b9"
}
{
id: "network_check"
unicode: "e640"
}
{
id: "network_locked"
unicode: "e61a"
}
{
id: "network_wifi"
unicode: "e1ba"
}
{
id: "new_releases"
unicode: "e031"
}
{
id: "next_week"
unicode: "e16a"
}
{
id: "nfc"
unicode: "e1bb"
}
{
id: "no_encryption"
unicode: "e641"
}
{
id: "no_sim"
unicode: "e0cc"
}
{
id: "not_interested"
unicode: "e033"
}
{
id: "note"
unicode: "e06f"
}
{
id: "note_add"
unicode: "e89c"
}
{
id: "notifications"
unicode: "e7f4"
}
{
id: "notifications_active"
unicode: "e7f7"
}
{
id: "notifications_none"
unicode: "e7f5"
}
{
id: "notifications_off"
unicode: "e7f6"
}
{
id: "notifications_paused"
unicode: "e7f8"
}
{
id: "offline_pin"
unicode: "e90a"
}
{
id: "ondemand_video"
unicode: "e63a"
}
{
id: "opacity"
unicode: "e91c"
}
{
id: "open_in_browser"
unicode: "e89d"
}
{
id: "open_in_new"
unicode: "e89e"
}
{
id: "open_with"
unicode: "e89f"
}
{
id: "pages"
unicode: "e7f9"
}
{
id: "pageview"
unicode: "e8a0"
}
{
id: "palette"
unicode: "e40a"
}
{
id: "pan_tool"
unicode: "e925"
}
{
id: "panorama"
unicode: "e40b"
}
{
id: "panorama_fish_eye"
unicode: "e40c"
}
{
id: "panorama_horizontal"
unicode: "e40d"
}
{
id: "panorama_vertical"
unicode: "e40e"
}
{
id: "panorama_wide_angle"
unicode: "e40f"
}
{
id: "party_mode"
unicode: "e7fa"
}
{
id: "pause"
unicode: "e034"
}
{
id: "pause_circle_filled"
unicode: "e035"
}
{
id: "pause_circle_outline"
unicode: "e036"
}
{
id: "payment"
unicode: "e8a1"
}
{
id: "people"
unicode: "e7fb"
}
{
id: "people_outline"
unicode: "e7fc"
}
{
id: "perm_camera_mic"
unicode: "e8a2"
}
{
id: "perm_contact_calendar"
unicode: "e8a3"
}
{
id: "perm_data_setting"
unicode: "e8a4"
}
{
id: "perm_device_information"
unicode: "e8a5"
}
{
id: "perm_identity"
unicode: "e8a6"
}
{
id: "perm_media"
unicode: "e8a7"
}
{
id: "perm_phone_msg"
unicode: "e8a8"
}
{
id: "perm_scan_wifi"
unicode: "e8a9"
}
{
id: "person"
unicode: "e7fd"
}
{
id: "person_add"
unicode: "e7fe"
}
{
id: "person_outline"
unicode: "e7ff"
}
{
id: "person_pin"
unicode: "e55a"
}
{
id: "person_pin_circle"
unicode: "e56a"
}
{
id: "personal_video"
unicode: "e63b"
}
{
id: "pets"
unicode: "e91d"
}
{
id: "phone"
unicode: "e0cd"
}
{
id: "phone_android"
unicode: "e324"
}
{
id: "phone_bluetooth_speaker"
unicode: "e61b"
}
{
id: "phone_forwarded"
unicode: "e61c"
}
{
id: "phone_in_talk"
unicode: "e61d"
}
{
id: "phone_iphone"
unicode: "e325"
}
{
id: "phone_locked"
unicode: "e61e"
}
{
id: "phone_missed"
unicode: "e61f"
}
{
id: "phone_paused"
unicode: "e620"
}
{
id: "phonelink"
unicode: "e326"
}
{
id: "phonelink_erase"
unicode: "e0db"
}
{
id: "phonelink_lock"
unicode: "e0dc"
}
{
id: "phonelink_off"
unicode: "e327"
}
{
id: "phonelink_ring"
unicode: "e0dd"
}
{
id: "phonelink_setup"
unicode: "e0de"
}
{
id: "photo"
unicode: "e410"
}
{
id: "photo_album"
unicode: "e411"
}
{
id: "photo_camera"
unicode: "e412"
}
{
id: "photo_filter"
unicode: "e43b"
}
{
id: "photo_library"
unicode: "e413"
}
{
id: "photo_size_select_actual"
unicode: "e432"
}
{
id: "photo_size_select_large"
unicode: "e433"
}
{
id: "photo_size_select_small"
unicode: "e434"
}
{
id: "picture_as_pdf"
unicode: "e415"
}
{
id: "picture_in_picture"
unicode: "e8aa"
}
{
id: "picture_in_picture_alt"
unicode: "e911"
}
{
id: "pie_chart"
unicode: "e6c4"
}
{
id: "pie_chart_outlined"
unicode: "e6c5"
}
{
id: "pin_drop"
unicode: "e55e"
}
{
id: "place"
unicode: "e55f"
}
{
id: "play_arrow"
unicode: "e037"
}
{
id: "play_circle_filled"
unicode: "e038"
}
{
id: "play_circle_outline"
unicode: "e039"
}
{
id: "play_for_work"
unicode: "e906"
}
{
id: "playlist_add"
unicode: "e03b"
}
{
id: "playlist_add_check"
unicode: "e065"
}
{
id: "playlist_play"
unicode: "e05f"
}
{
id: "plus_one"
unicode: "e800"
}
{
id: "poll"
unicode: "e801"
}
{
id: "polymer"
unicode: "e8ab"
}
{
id: "pool"
unicode: "eb48"
}
{
id: "portable_wifi_off"
unicode: "e0ce"
}
{
id: "portrait"
unicode: "e416"
}
{
id: "power"
unicode: "e63c"
}
{
id: "power_input"
unicode: "e336"
}
{
id: "power_settings_new"
unicode: "e8ac"
}
{
id: "pregnant_woman"
unicode: "e91e"
}
{
id: "present_to_all"
unicode: "e0df"
}
{
id: "print"
unicode: "e8ad"
}
{
id: "priority_high"
unicode: "e645"
}
{
id: "public"
unicode: "e80b"
}
{
id: "publish"
unicode: "e255"
}
{
id: "query_builder"
unicode: "e8ae"
}
{
id: "question_answer"
unicode: "e8af"
}
{
id: "queue"
unicode: "e03c"
}
{
id: "queue_music"
unicode: "e03d"
}
{
id: "queue_play_next"
unicode: "e066"
}
{
id: "radio"
unicode: "e03e"
}
{
id: "radio_button_checked"
unicode: "e837"
}
{
id: "radio_button_unchecked"
unicode: "e836"
}
{
id: "rate_review"
unicode: "e560"
}
{
id: "receipt"
unicode: "e8b0"
}
{
id: "recent_actors"
unicode: "e03f"
}
{
id: "record_voice_over"
unicode: "e91f"
}
{
id: "redeem"
unicode: "e8b1"
}
{
id: "redo"
unicode: "e15a"
}
{
id: "refresh"
unicode: "e5d5"
}
{
id: "remove"
unicode: "e15b"
}
{
id: "remove_circle"
unicode: "e15c"
}
{
id: "remove_circle_outline"
unicode: "e15d"
}
{
id: "remove_from_queue"
unicode: "e067"
}
{
id: "remove_red_eye"
unicode: "e417"
}
{
id: "remove_shopping_cart"
unicode: "e928"
}
{
id: "reorder"
unicode: "e8fe"
}
{
id: "repeat"
unicode: "e040"
}
{
id: "repeat_one"
unicode: "e041"
}
{
id: "replay"
unicode: "e042"
}
{
id: "replay_10"
unicode: "e059"
}
{
id: "replay_30"
unicode: "e05a"
}
{
id: "replay_5"
unicode: "e05b"
}
{
id: "reply"
unicode: "e15e"
}
{
id: "reply_all"
unicode: "e15f"
}
{
id: "report"
unicode: "e160"
}
{
id: "report_problem"
unicode: "e8b2"
}
{
id: "restaurant"
unicode: "e56c"
}
{
id: "restaurant_menu"
unicode: "e561"
}
{
id: "restore"
unicode: "e8b3"
}
{
id: "restore_page"
unicode: "e929"
}
{
id: "ring_volume"
unicode: "e0d1"
}
{
id: "room"
unicode: "e8b4"
}
{
id: "room_service"
unicode: "eb49"
}
{
id: "rotate_90_degrees_ccw"
unicode: "e418"
}
{
id: "rotate_left"
unicode: "e419"
}
{
id: "rotate_right"
unicode: "e41a"
}
{
id: "rounded_corner"
unicode: "e920"
}
{
id: "router"
unicode: "e328"
}
{
id: "rowing"
unicode: "e921"
}
{
id: "rss_feed"
unicode: "e0e5"
}
{
id: "rv_hookup"
unicode: "e642"
}
{
id: "satellite"
unicode: "e562"
}
{
id: "save"
unicode: "e161"
}
{
id: "scanner"
unicode: "e329"
}
{
id: "schedule"
unicode: "e8b5"
}
{
id: "school"
unicode: "e80c"
}
{
id: "screen_lock_landscape"
unicode: "e1be"
}
{
id: "screen_lock_portrait"
unicode: "e1bf"
}
{
id: "screen_lock_rotation"
unicode: "e1c0"
}
{
id: "screen_rotation"
unicode: "e1c1"
}
{
id: "screen_share"
unicode: "e0e2"
}
{
id: "sd_card"
unicode: "e623"
}
{
id: "sd_storage"
unicode: "e1c2"
}
{
id: "search"
unicode: "e8b6"
}
{
id: "security"
unicode: "e32a"
}
{
id: "select_all"
unicode: "e162"
}
{
id: "send"
unicode: "e163"
}
{
id: "sentiment_dissatisfied"
unicode: "e811"
}
{
id: "sentiment_neutral"
unicode: "e812"
}
{
id: "sentiment_satisfied"
unicode: "e813"
}
{
id: "sentiment_very_dissatisfied"
unicode: "e814"
}
{
id: "sentiment_very_satisfied"
unicode: "e815"
}
{
id: "settings"
unicode: "e8b8"
}
{
id: "settings_applications"
unicode: "e8b9"
}
{
id: "settings_backup_restore"
unicode: "e8ba"
}
{
id: "settings_bluetooth"
unicode: "e8bb"
}
{
id: "settings_brightness"
unicode: "e8bd"
}
{
id: "settings_cell"
unicode: "e8bc"
}
{
id: "settings_ethernet"
unicode: "e8be"
}
{
id: "settings_input_antenna"
unicode: "e8bf"
}
{
id: "settings_input_component"
unicode: "e8c0"
}
{
id: "settings_input_composite"
unicode: "e8c1"
}
{
id: "settings_input_hdmi"
unicode: "e8c2"
}
{
id: "settings_input_svideo"
unicode: "e8c3"
}
{
id: "settings_overscan"
unicode: "e8c4"
}
{
id: "settings_phone"
unicode: "e8c5"
}
{
id: "settings_power"
unicode: "e8c6"
}
{
id: "settings_remote"
unicode: "e8c7"
}
{
id: "settings_system_daydream"
unicode: "e1c3"
}
{
id: "settings_voice"
unicode: "e8c8"
}
{
id: "share"
unicode: "e80d"
}
{
id: "shop"
unicode: "e8c9"
}
{
id: "shop_two"
unicode: "e8ca"
}
{
id: "shopping_basket"
unicode: "e8cb"
}
{
id: "shopping_cart"
unicode: "e8cc"
}
{
id: "short_text"
unicode: "e261"
}
{
id: "show_chart"
unicode: "e6e1"
}
{
id: "shuffle"
unicode: "e043"
}
{
id: "signal_cellular_4_bar"
unicode: "e1c8"
}
{
id: "signal_cellular_connected_no_internet_4_bar"
unicode: "e1cd"
}
{
id: "signal_cellular_no_sim"
unicode: "e1ce"
}
{
id: "signal_cellular_null"
unicode: "e1cf"
}
{
id: "signal_cellular_off"
unicode: "e1d0"
}
{
id: "signal_wifi_4_bar"
unicode: "e1d8"
}
{
id: "signal_wifi_4_bar_lock"
unicode: "e1d9"
}
{
id: "signal_wifi_off"
unicode: "e1da"
}
{
id: "sim_card"
unicode: "e32b"
}
{
id: "sim_card_alert"
unicode: "e624"
}
{
id: "skip_next"
unicode: "e044"
}
{
id: "skip_previous"
unicode: "e045"
}
{
id: "slideshow"
unicode: "e41b"
}
{
id: "slow_motion_video"
unicode: "e068"
}
{
id: "smartphone"
unicode: "e32c"
}
{
id: "smoke_free"
unicode: "eb4a"
}
{
id: "smoking_rooms"
unicode: "eb4b"
}
{
id: "sms"
unicode: "e625"
}
{
id: "sms_failed"
unicode: "e626"
}
{
id: "snooze"
unicode: "e046"
}
{
id: "sort"
unicode: "e164"
}
{
id: "sort_by_alpha"
unicode: "e053"
}
{
id: "spa"
unicode: "eb4c"
}
{
id: "space_bar"
unicode: "e256"
}
{
id: "speaker"
unicode: "e32d"
}
{
id: "speaker_group"
unicode: "e32e"
}
{
id: "speaker_notes"
unicode: "e8cd"
}
{
id: "speaker_notes_off"
unicode: "e92a"
}
{
id: "speaker_phone"
unicode: "e0d2"
}
{
id: "spellcheck"
unicode: "e8ce"
}
{
id: "star"
unicode: "e838"
}
{
id: "star_border"
unicode: "e83a"
}
{
id: "star_half"
unicode: "e839"
}
{
id: "stars"
unicode: "e8d0"
}
{
id: "stay_current_landscape"
unicode: "e0d3"
}
{
id: "stay_current_portrait"
unicode: "e0d4"
}
{
id: "stay_primary_landscape"
unicode: "e0d5"
}
{
id: "stay_primary_portrait"
unicode: "e0d6"
}
{
id: "stop"
unicode: "e047"
}
{
id: "stop_screen_share"
unicode: "e0e3"
}
{
id: "storage"
unicode: "e1db"
}
{
id: "store"
unicode: "e8d1"
}
{
id: "store_mall_directory"
unicode: "e563"
}
{
id: "straighten"
unicode: "e41c"
}
{
id: "streetview"
unicode: "e56e"
}
{
id: "strikethrough_s"
unicode: "e257"
}
{
id: "style"
unicode: "e41d"
}
{
id: "subdirectory_arrow_left"
unicode: "e5d9"
}
{
id: "subdirectory_arrow_right"
unicode: "e5da"
}
{
id: "subject"
unicode: "e8d2"
}
{
id: "subscriptions"
unicode: "e064"
}
{
id: "subtitles"
unicode: "e048"
}
{
id: "subway"
unicode: "e56f"
}
{
id: "supervisor_account"
unicode: "e8d3"
}
{
id: "surround_sound"
unicode: "e049"
}
{
id: "swap_calls"
unicode: "e0d7"
}
{
id: "swap_horiz"
unicode: "e8d4"
}
{
id: "swap_vert"
unicode: "e8d5"
}
{
id: "swap_vertical_circle"
unicode: "e8d6"
}
{
id: "switch_camera"
unicode: "e41e"
}
{
id: "switch_video"
unicode: "e41f"
}
{
id: "sync"
unicode: "e627"
}
{
id: "sync_disabled"
unicode: "e628"
}
{
id: "sync_problem"
unicode: "e629"
}
{
id: "system_update"
unicode: "e62a"
}
{
id: "system_update_alt"
unicode: "e8d7"
}
{
id: "tab"
unicode: "e8d8"
}
{
id: "tab_unselected"
unicode: "e8d9"
}
{
id: "tablet"
unicode: "e32f"
}
{
id: "tablet_android"
unicode: "e330"
}
{
id: "tablet_mac"
unicode: "e331"
}
{
id: "tag_faces"
unicode: "e420"
}
{
id: "tap_and_play"
unicode: "e62b"
}
{
id: "terrain"
unicode: "e564"
}
{
id: "text_fields"
unicode: "e262"
}
{
id: "text_format"
unicode: "e165"
}
{
id: "textsms"
unicode: "e0d8"
}
{
id: "texture"
unicode: "e421"
}
{
id: "theaters"
unicode: "e8da"
}
{
id: "thumb_down"
unicode: "e8db"
}
{
id: "thumb_up"
unicode: "e8dc"
}
{
id: "thumbs_up_down"
unicode: "e8dd"
}
{
id: "time_to_leave"
unicode: "e62c"
}
{
id: "timelapse"
unicode: "e422"
}
{
id: "timeline"
unicode: "e922"
}
{
id: "timer"
unicode: "e425"
}
{
id: "timer_10"
unicode: "e423"
}
{
id: "timer_3"
unicode: "e424"
}
{
id: "timer_off"
unicode: "e426"
}
{
id: "title"
unicode: "e264"
}
{
id: "toc"
unicode: "e8de"
}
{
id: "today"
unicode: "e8df"
}
{
id: "toll"
unicode: "e8e0"
}
{
id: "tonality"
unicode: "e427"
}
{
id: "touch_app"
unicode: "e913"
}
{
id: "toys"
unicode: "e332"
}
{
id: "track_changes"
unicode: "e8e1"
}
{
id: "traffic"
unicode: "e565"
}
{
id: "train"
unicode: "e570"
}
{
id: "tram"
unicode: "e571"
}
{
id: "transfer_within_a_station"
unicode: "e572"
}
{
id: "transform"
unicode: "e428"
}
{
id: "translate"
unicode: "e8e2"
}
{
id: "trending_down"
unicode: "e8e3"
}
{
id: "trending_flat"
unicode: "e8e4"
}
{
id: "trending_up"
unicode: "e8e5"
}
{
id: "tune"
unicode: "e429"
}
{
id: "turned_in"
unicode: "e8e6"
}
{
id: "turned_in_not"
unicode: "e8e7"
}
{
id: "tv"
unicode: "e333"
}
{
id: "unarchive"
unicode: "e169"
}
{
id: "undo"
unicode: "e166"
}
{
id: "unfold_less"
unicode: "e5d6"
}
{
id: "unfold_more"
unicode: "e5d7"
}
{
id: "update"
unicode: "e923"
}
{
id: "usb"
unicode: "e1e0"
}
{
id: "verified_user"
unicode: "e8e8"
}
{
id: "vertical_align_bottom"
unicode: "e258"
}
{
id: "vertical_align_center"
unicode: "e259"
}
{
id: "vertical_align_top"
unicode: "e25a"
}
{
id: "vibration"
unicode: "e62d"
}
{
id: "video_call"
unicode: "e070"
}
{
id: "video_label"
unicode: "e071"
}
{
id: "video_library"
unicode: "e04a"
}
{
id: "videocam"
unicode: "e04b"
}
{
id: "videocam_off"
unicode: "e04c"
}
{
id: "videogame_asset"
unicode: "e338"
}
{
id: "view_agenda"
unicode: "e8e9"
}
{
id: "view_array"
unicode: "e8ea"
}
{
id: "view_carousel"
unicode: "e8eb"
}
{
id: "view_column"
unicode: "e8ec"
}
{
id: "view_comfy"
unicode: "e42a"
}
{
id: "view_compact"
unicode: "e42b"
}
{
id: "view_day"
unicode: "e8ed"
}
{
id: "view_headline"
unicode: "e8ee"
}
{
id: "view_list"
unicode: "e8ef"
}
{
id: "view_module"
unicode: "e8f0"
}
{
id: "view_quilt"
unicode: "e8f1"
}
{
id: "view_stream"
unicode: "e8f2"
}
{
id: "view_week"
unicode: "e8f3"
}
{
id: "vignette"
unicode: "e435"
}
{
id: "visibility"
unicode: "e8f4"
}
{
id: "visibility_off"
unicode: "e8f5"
}
{
id: "voice_chat"
unicode: "e62e"
}
{
id: "voicemail"
unicode: "e0d9"
}
{
id: "volume_down"
unicode: "e04d"
}
{
id: "volume_mute"
unicode: "e04e"
}
{
id: "volume_off"
unicode: "e04f"
}
{
id: "volume_up"
unicode: "e050"
}
{
id: "vpn_key"
unicode: "e0da"
}
{
id: "vpn_lock"
unicode: "e62f"
}
{
id: "wallpaper"
unicode: "e1bc"
}
{
id: "warning"
unicode: "e002"
}
{
id: "watch"
unicode: "e334"
}
{
id: "watch_later"
unicode: "e924"
}
{
id: "wb_auto"
unicode: "e42c"
}
{
id: "wb_cloudy"
unicode: "e42d"
}
{
id: "wb_incandescent"
unicode: "e42e"
}
{
id: "wb_iridescent"
unicode: "e436"
}
{
id: "wb_sunny"
unicode: "e430"
}
{
id: "wc"
unicode: "e63d"
}
{
id: "web"
unicode: "e051"
}
{
id: "web_asset"
unicode: "e069"
}
{
id: "weekend"
unicode: "e16b"
}
{
id: "whatshot"
unicode: "e80e"
}
{
id: "widgets"
unicode: "e1bd"
}
{
id: "wifi"
unicode: "e63e"
}
{
id: "wifi_lock"
unicode: "e1e1"
}
{
id: "wifi_tethering"
unicode: "e1e2"
}
{
id: "work"
unicode: "e8f9"
}
{
id: "wrap_text"
unicode: "e25b"
}
{
id: "youtube_searched_for"
unicode: "e8fa"
}
{
id: "zoom_in"
unicode: "e8ff"
}
{
id: "zoom_out"
unicode: "e900"
}
{
id: "zoom_out_map"
unicode: "e56b"
}
] | 37272 | icons: [
{
id: "3d_rotation"
unicode: "e84d"
}
{
id: "ac_unit"
unicode: "eb3b"
}
{
id: "access_alarm"
unicode: "e190"
}
{
id: "access_alarms"
unicode: "e191"
}
{
id: "access_time"
unicode: "e192"
}
{
id: "accessibility"
unicode: "e84e"
}
{
id: "accessible"
unicode: "e914"
}
{
id: "account_balance"
unicode: "e84f"
}
{
id: "account_balance_wallet"
unicode: "e850"
}
{
id: "account_box"
unicode: "e851"
}
{
id: "account_circle"
unicode: "e853"
}
{
id: "adb"
unicode: "e60e"
}
{
id: "add"
unicode: "e145"
}
{
id: "add_a_photo"
unicode: "e439"
}
{
id: "add_alarm"
unicode: "e193"
}
{
id: "add_alert"
unicode: "e003"
}
{
id: "add_box"
unicode: "e146"
}
{
id: "add_circle"
unicode: "e147"
}
{
id: "add_circle_outline"
unicode: "e148"
}
{
id: "add_location"
unicode: "e567"
}
{
id: "add_shopping_cart"
unicode: "e854"
}
{
id: "add_to_photos"
unicode: "e39d"
}
{
id: "add_to_queue"
unicode: "e05c"
}
{
id: "adjust"
unicode: "e39e"
}
{
id: "airline_seat_flat"
unicode: "e630"
}
{
id: "airline_seat_flat_angled"
unicode: "e631"
}
{
id: "airline_seat_individual_suite"
unicode: "e632"
}
{
id: "airline_seat_legroom_extra"
unicode: "e633"
}
{
id: "airline_seat_legroom_normal"
unicode: "e634"
}
{
id: "airline_seat_legroom_reduced"
unicode: "e635"
}
{
id: "airline_seat_recline_extra"
unicode: "e636"
}
{
id: "airline_seat_recline_normal"
unicode: "e637"
}
{
id: "airplanemode_active"
unicode: "e195"
}
{
id: "airplanemode_inactive"
unicode: "e194"
}
{
id: "airplay"
unicode: "e055"
}
{
id: "airport_shuttle"
unicode: "eb3c"
}
{
id: "alarm"
unicode: "e855"
}
{
id: "alarm_add"
unicode: "e856"
}
{
id: "alarm_off"
unicode: "e857"
}
{
id: "alarm_on"
unicode: "e858"
}
{
id: "album"
unicode: "e019"
}
{
id: "all_inclusive"
unicode: "eb3d"
}
{
id: "all_out"
unicode: "e90b"
}
{
id: "android"
unicode: "e859"
}
{
id: "announcement"
unicode: "e85a"
}
{
id: "apps"
unicode: "e5c3"
}
{
id: "archive"
unicode: "e149"
}
{
id: "arrow_back"
unicode: "e5c4"
}
{
id: "arrow_downward"
unicode: "e5db"
}
{
id: "arrow_drop_down"
unicode: "e5c5"
}
{
id: "arrow_drop_down_circle"
unicode: "e5c6"
}
{
id: "arrow_drop_up"
unicode: "e5c7"
}
{
id: "arrow_forward"
unicode: "e5c8"
}
{
id: "arrow_upward"
unicode: "e5d8"
}
{
id: "art_track"
unicode: "e060"
}
{
id: "aspect_ratio"
unicode: "e85b"
}
{
id: "assessment"
unicode: "e85c"
}
{
id: "assignment"
unicode: "e85d"
}
{
id: "assignment_ind"
unicode: "e85e"
}
{
id: "assignment_late"
unicode: "e85f"
}
{
id: "assignment_return"
unicode: "e860"
}
{
id: "assignment_returned"
unicode: "e861"
}
{
id: "assignment_turned_in"
unicode: "e862"
}
{
id: "assistant"
unicode: "e39f"
}
{
id: "assistant_photo"
unicode: "e3a0"
}
{
id: "attach_file"
unicode: "e226"
}
{
id: "attach_money"
unicode: "e227"
}
{
id: "attachment"
unicode: "e2bc"
}
{
id: "audiotrack"
unicode: "e3a1"
}
{
id: "autorenew"
unicode: "e863"
}
{
id: "av_timer"
unicode: "e01b"
}
{
id: "backspace"
unicode: "e14a"
}
{
id: "backup"
unicode: "e864"
}
{
id: "battery_alert"
unicode: "e19c"
}
{
id: "battery_charging_full"
unicode: "e1a3"
}
{
id: "battery_full"
unicode: "e1a4"
}
{
id: "battery_std"
unicode: "e1a5"
}
{
id: "battery_unknown"
unicode: "e1a6"
}
{
id: "beach_access"
unicode: "eb3e"
}
{
id: "beenhere"
unicode: "e52d"
}
{
id: "block"
unicode: "e14b"
}
{
id: "bluetooth"
unicode: "e1a7"
}
{
id: "bluetooth_audio"
unicode: "e60f"
}
{
id: "bluetooth_connected"
unicode: "e1a8"
}
{
id: "bluetooth_disabled"
unicode: "e1a9"
}
{
id: "bluetooth_searching"
unicode: "e1aa"
}
{
id: "blur_circular"
unicode: "e3a2"
}
{
id: "blur_linear"
unicode: "e3a3"
}
{
id: "blur_off"
unicode: "e3a4"
}
{
id: "blur_on"
unicode: "e3a5"
}
{
id: "book"
unicode: "e865"
}
{
id: "bookmark"
unicode: "e866"
}
{
id: "bookmark_border"
unicode: "e867"
}
{
id: "border_all"
unicode: "e228"
}
{
id: "border_bottom"
unicode: "e229"
}
{
id: "border_clear"
unicode: "e22a"
}
{
id: "border_color"
unicode: "e22b"
}
{
id: "border_horizontal"
unicode: "e22c"
}
{
id: "border_inner"
unicode: "e22d"
}
{
id: "border_left"
unicode: "e22e"
}
{
id: "border_outer"
unicode: "e22f"
}
{
id: "border_right"
unicode: "e230"
}
{
id: "border_style"
unicode: "e231"
}
{
id: "border_top"
unicode: "e232"
}
{
id: "border_vertical"
unicode: "e233"
}
{
id: "branding_watermark"
unicode: "e06b"
}
{
id: "brightness_1"
unicode: "e3a6"
}
{
id: "brightness_2"
unicode: "e3a7"
}
{
id: "brightness_3"
unicode: "e3a8"
}
{
id: "brightness_4"
unicode: "e3a9"
}
{
id: "brightness_5"
unicode: "e3aa"
}
{
id: "brightness_6"
unicode: "e3ab"
}
{
id: "brightness_7"
unicode: "e3ac"
}
{
id: "brightness_auto"
unicode: "e1ab"
}
{
id: "brightness_high"
unicode: "e1ac"
}
{
id: "brightness_low"
unicode: "e1ad"
}
{
id: "brightness_medium"
unicode: "e1ae"
}
{
id: "broken_image"
unicode: "e3ad"
}
{
id: "brush"
unicode: "e3ae"
}
{
id: "bubble_chart"
unicode: "e6dd"
}
{
id: "bug_report"
unicode: "e868"
}
{
id: "build"
unicode: "e869"
}
{
id: "burst_mode"
unicode: "e43c"
}
{
id: "business"
unicode: "e0af"
}
{
id: "business_center"
unicode: "eb3f"
}
{
id: "cached"
unicode: "e86a"
}
{
id: "cake"
unicode: "e7e9"
}
{
id: "call"
unicode: "e0b0"
}
{
id: "call_end"
unicode: "e0b1"
}
{
id: "call_made"
unicode: "e0b2"
}
{
id: "call_merge"
unicode: "e0b3"
}
{
id: "call_missed"
unicode: "e0b4"
}
{
id: "call_missed_outgoing"
unicode: "e0e4"
}
{
id: "call_received"
unicode: "e0b5"
}
{
id: "call_split"
unicode: "e0b6"
}
{
id: "call_to_action"
unicode: "e06c"
}
{
id: "camera"
unicode: "e3af"
}
{
id: "camera_alt"
unicode: "e3b0"
}
{
id: "camera_enhance"
unicode: "e8fc"
}
{
id: "camera_front"
unicode: "e3b1"
}
{
id: "camera_rear"
unicode: "e3b2"
}
{
id: "camera_roll"
unicode: "e3b3"
}
{
id: "cancel"
unicode: "e5c9"
}
{
id: "card_giftcard"
unicode: "e8f6"
}
{
id: "card_membership"
unicode: "e8f7"
}
{
id: "card_travel"
unicode: "e8f8"
}
{
id: "<NAME>"
unicode: "eb40"
}
{
id: "cast"
unicode: "e307"
}
{
id: "cast_connected"
unicode: "e308"
}
{
id: "center_focus_strong"
unicode: "e3b4"
}
{
id: "center_focus_weak"
unicode: "e3b5"
}
{
id: "change_history"
unicode: "e86b"
}
{
id: "chat"
unicode: "e0b7"
}
{
id: "chat_bubble"
unicode: "e0ca"
}
{
id: "chat_bubble_outline"
unicode: "e0cb"
}
{
id: "check"
unicode: "e5ca"
}
{
id: "check_box"
unicode: "e834"
}
{
id: "check_box_outline_blank"
unicode: "e835"
}
{
id: "check_circle"
unicode: "e86c"
}
{
id: "chevron_left"
unicode: "e5cb"
}
{
id: "chevron_right"
unicode: "e5cc"
}
{
id: "child_care"
unicode: "eb41"
}
{
id: "child_friendly"
unicode: "eb42"
}
{
id: "chrome_reader_mode"
unicode: "e86d"
}
{
id: "class"
unicode: "e86e"
}
{
id: "clear"
unicode: "e14c"
}
{
id: "clear_all"
unicode: "e0b8"
}
{
id: "close"
unicode: "e5cd"
}
{
id: "closed_caption"
unicode: "e01c"
}
{
id: "cloud"
unicode: "e2bd"
}
{
id: "cloud_circle"
unicode: "e2be"
}
{
id: "cloud_done"
unicode: "e2bf"
}
{
id: "cloud_download"
unicode: "e2c0"
}
{
id: "cloud_off"
unicode: "e2c1"
}
{
id: "cloud_queue"
unicode: "e2c2"
}
{
id: "cloud_upload"
unicode: "e2c3"
}
{
id: "code"
unicode: "e86f"
}
{
id: "collections"
unicode: "e3b6"
}
{
id: "collections_bookmark"
unicode: "e431"
}
{
id: "color_lens"
unicode: "e3b7"
}
{
id: "colorize"
unicode: "e3b8"
}
{
id: "comment"
unicode: "e0b9"
}
{
id: "compare"
unicode: "e3b9"
}
{
id: "compare_arrows"
unicode: "e915"
}
{
id: "computer"
unicode: "e30a"
}
{
id: "confirmation_number"
unicode: "e638"
}
{
id: "contact_mail"
unicode: "e0d0"
}
{
id: "contact_phone"
unicode: "e0cf"
}
{
id: "contacts"
unicode: "e0ba"
}
{
id: "content_copy"
unicode: "e14d"
}
{
id: "content_cut"
unicode: "e14e"
}
{
id: "content_paste"
unicode: "e14f"
}
{
id: "control_point"
unicode: "e3ba"
}
{
id: "control_point_duplicate"
unicode: "e3bb"
}
{
id: "copyright"
unicode: "e90c"
}
{
id: "create"
unicode: "e150"
}
{
id: "create_new_folder"
unicode: "e2cc"
}
{
id: "credit_card"
unicode: "e870"
}
{
id: "crop"
unicode: "e3be"
}
{
id: "crop_16_9"
unicode: "e3bc"
}
{
id: "crop_3_2"
unicode: "e3bd"
}
{
id: "crop_5_4"
unicode: "e3bf"
}
{
id: "crop_7_5"
unicode: "e3c0"
}
{
id: "crop_din"
unicode: "e3c1"
}
{
id: "crop_free"
unicode: "e3c2"
}
{
id: "crop_landscape"
unicode: "e3c3"
}
{
id: "crop_original"
unicode: "e3c4"
}
{
id: "crop_portrait"
unicode: "e3c5"
}
{
id: "crop_rotate"
unicode: "e437"
}
{
id: "crop_square"
unicode: "e3c6"
}
{
id: "dashboard"
unicode: "e871"
}
{
id: "data_usage"
unicode: "e1af"
}
{
id: "date_range"
unicode: "e916"
}
{
id: "dehaze"
unicode: "e3c7"
}
{
id: "delete"
unicode: "e872"
}
{
id: "delete_forever"
unicode: "e92b"
}
{
id: "delete_sweep"
unicode: "e16c"
}
{
id: "description"
unicode: "e873"
}
{
id: "desktop_mac"
unicode: "e30b"
}
{
id: "desktop_windows"
unicode: "e30c"
}
{
id: "details"
unicode: "e3c8"
}
{
id: "developer_board"
unicode: "e30d"
}
{
id: "developer_mode"
unicode: "e1b0"
}
{
id: "device_hub"
unicode: "e335"
}
{
id: "devices"
unicode: "e1b1"
}
{
id: "devices_other"
unicode: "e337"
}
{
id: "dialer_sip"
unicode: "e0bb"
}
{
id: "dialpad"
unicode: "e0bc"
}
{
id: "directions"
unicode: "e52e"
}
{
id: "directions_bike"
unicode: "e52f"
}
{
id: "directions_boat"
unicode: "e532"
}
{
id: "directions_bus"
unicode: "e530"
}
{
id: "directions_car"
unicode: "e531"
}
{
id: "directions_railway"
unicode: "e534"
}
{
id: "directions_run"
unicode: "e566"
}
{
id: "directions_subway"
unicode: "e533"
}
{
id: "directions_transit"
unicode: "e535"
}
{
id: "directions_walk"
unicode: "e536"
}
{
id: "disc_full"
unicode: "e610"
}
{
id: "dns"
unicode: "e875"
}
{
id: "do_not_disturb"
unicode: "e612"
}
{
id: "do_not_disturb_alt"
unicode: "e611"
}
{
id: "do_not_disturb_off"
unicode: "e643"
}
{
id: "do_not_disturb_on"
unicode: "e644"
}
{
id: "dock"
unicode: "e30e"
}
{
id: "domain"
unicode: "e7ee"
}
{
id: "done"
unicode: "e876"
}
{
id: "done_all"
unicode: "e877"
}
{
id: "donut_large"
unicode: "e917"
}
{
id: "donut_small"
unicode: "e918"
}
{
id: "drafts"
unicode: "e151"
}
{
id: "drag_handle"
unicode: "e25d"
}
{
id: "drive_eta"
unicode: "e613"
}
{
id: "dvr"
unicode: "e1b2"
}
{
id: "edit"
unicode: "e3c9"
}
{
id: "edit_location"
unicode: "e568"
}
{
id: "eject"
unicode: "e8fb"
}
{
id: "email"
unicode: "e0be"
}
{
id: "enhanced_encryption"
unicode: "e63f"
}
{
id: "equalizer"
unicode: "e01d"
}
{
id: "error"
unicode: "e000"
}
{
id: "error_outline"
unicode: "e001"
}
{
id: "euro_symbol"
unicode: "e926"
}
{
id: "ev_station"
unicode: "e56d"
}
{
id: "event"
unicode: "e878"
}
{
id: "event_available"
unicode: "e614"
}
{
id: "event_busy"
unicode: "e615"
}
{
id: "event_note"
unicode: "e616"
}
{
id: "event_seat"
unicode: "e903"
}
{
id: "exit_to_app"
unicode: "e879"
}
{
id: "expand_less"
unicode: "e5ce"
}
{
id: "expand_more"
unicode: "e5cf"
}
{
id: "explicit"
unicode: "e01e"
}
{
id: "explore"
unicode: "e87a"
}
{
id: "exposure"
unicode: "e3ca"
}
{
id: "exposure_neg_1"
unicode: "e3cb"
}
{
id: "exposure_neg_2"
unicode: "e3cc"
}
{
id: "exposure_plus_1"
unicode: "e3cd"
}
{
id: "exposure_plus_2"
unicode: "e3ce"
}
{
id: "exposure_zero"
unicode: "e3cf"
}
{
id: "extension"
unicode: "e87b"
}
{
id: "face"
unicode: "e87c"
}
{
id: "fast_forward"
unicode: "e01f"
}
{
id: "fast_rewind"
unicode: "e020"
}
{
id: "favorite"
unicode: "e87d"
}
{
id: "favorite_border"
unicode: "e87e"
}
{
id: "featured_play_list"
unicode: "e06d"
}
{
id: "featured_video"
unicode: "e06e"
}
{
id: "feedback"
unicode: "e87f"
}
{
id: "fiber_dvr"
unicode: "e05d"
}
{
id: "fiber_manual_record"
unicode: "e061"
}
{
id: "fiber_new"
unicode: "e05e"
}
{
id: "fiber_pin"
unicode: "e06a"
}
{
id: "fiber_smart_record"
unicode: "e062"
}
{
id: "file_download"
unicode: "e2c4"
}
{
id: "file_upload"
unicode: "e2c6"
}
{
id: "filter"
unicode: "e3d3"
}
{
id: "filter_1"
unicode: "e3d0"
}
{
id: "filter_2"
unicode: "e3d1"
}
{
id: "filter_3"
unicode: "e3d2"
}
{
id: "filter_4"
unicode: "e3d4"
}
{
id: "filter_5"
unicode: "e3d5"
}
{
id: "filter_6"
unicode: "e3d6"
}
{
id: "filter_7"
unicode: "e3d7"
}
{
id: "filter_8"
unicode: "e3d8"
}
{
id: "filter_9"
unicode: "e3d9"
}
{
id: "filter_9_plus"
unicode: "e3da"
}
{
id: "filter_b_and_w"
unicode: "e3db"
}
{
id: "filter_center_focus"
unicode: "e3dc"
}
{
id: "filter_drama"
unicode: "e3dd"
}
{
id: "filter_frames"
unicode: "e3de"
}
{
id: "filter_hdr"
unicode: "e3df"
}
{
id: "filter_list"
unicode: "e152"
}
{
id: "filter_none"
unicode: "e3e0"
}
{
id: "filter_tilt_shift"
unicode: "e3e2"
}
{
id: "filter_vintage"
unicode: "e3e3"
}
{
id: "find_in_page"
unicode: "e880"
}
{
id: "find_replace"
unicode: "e881"
}
{
id: "fingerprint"
unicode: "e90d"
}
{
id: "first_page"
unicode: "e5dc"
}
{
id: "fitness_center"
unicode: "eb43"
}
{
id: "flag"
unicode: "e153"
}
{
id: "flare"
unicode: "e3e4"
}
{
id: "flash_auto"
unicode: "e3e5"
}
{
id: "flash_off"
unicode: "e3e6"
}
{
id: "flash_on"
unicode: "e3e7"
}
{
id: "flight"
unicode: "e539"
}
{
id: "flight_land"
unicode: "e904"
}
{
id: "flight_takeoff"
unicode: "e905"
}
{
id: "flip"
unicode: "e3e8"
}
{
id: "flip_to_back"
unicode: "e882"
}
{
id: "flip_to_front"
unicode: "e883"
}
{
id: "folder"
unicode: "e2c7"
}
{
id: "folder_open"
unicode: "e2c8"
}
{
id: "folder_shared"
unicode: "e2c9"
}
{
id: "folder_special"
unicode: "e617"
}
{
id: "font_download"
unicode: "e167"
}
{
id: "format_align_center"
unicode: "e234"
}
{
id: "format_align_justify"
unicode: "e235"
}
{
id: "format_align_left"
unicode: "e236"
}
{
id: "format_align_right"
unicode: "e237"
}
{
id: "format_bold"
unicode: "e238"
}
{
id: "format_clear"
unicode: "e239"
}
{
id: "format_color_fill"
unicode: "e23a"
}
{
id: "format_color_reset"
unicode: "e23b"
}
{
id: "format_color_text"
unicode: "e23c"
}
{
id: "format_indent_decrease"
unicode: "e23d"
}
{
id: "format_indent_increase"
unicode: "e23e"
}
{
id: "format_italic"
unicode: "e23f"
}
{
id: "format_line_spacing"
unicode: "e240"
}
{
id: "format_list_bulleted"
unicode: "e241"
}
{
id: "format_list_numbered"
unicode: "e242"
}
{
id: "format_paint"
unicode: "e243"
}
{
id: "format_quote"
unicode: "e244"
}
{
id: "format_shapes"
unicode: "e25e"
}
{
id: "format_size"
unicode: "e245"
}
{
id: "format_strikethrough"
unicode: "e246"
}
{
id: "format_textdirection_l_to_r"
unicode: "e247"
}
{
id: "format_textdirection_r_to_l"
unicode: "e248"
}
{
id: "format_underlined"
unicode: "e249"
}
{
id: "forum"
unicode: "e0bf"
}
{
id: "forward"
unicode: "e154"
}
{
id: "forward_10"
unicode: "e056"
}
{
id: "forward_30"
unicode: "e057"
}
{
id: "forward_5"
unicode: "e058"
}
{
id: "free_breakfast"
unicode: "eb44"
}
{
id: "fullscreen"
unicode: "e5d0"
}
{
id: "fullscreen_exit"
unicode: "e5d1"
}
{
id: "functions"
unicode: "e24a"
}
{
id: "g_translate"
unicode: "e927"
}
{
id: "gamepad"
unicode: "e30f"
}
{
id: "games"
unicode: "e021"
}
{
id: "gavel"
unicode: "e90e"
}
{
id: "gesture"
unicode: "e155"
}
{
id: "get_app"
unicode: "e884"
}
{
id: "gif"
unicode: "e908"
}
{
id: "golf_course"
unicode: "eb45"
}
{
id: "gps_fixed"
unicode: "e1b3"
}
{
id: "gps_not_fixed"
unicode: "e1b4"
}
{
id: "gps_off"
unicode: "e1b5"
}
{
id: "grade"
unicode: "e885"
}
{
id: "gradient"
unicode: "e3e9"
}
{
id: "grain"
unicode: "e3ea"
}
{
id: "graphic_eq"
unicode: "e1b8"
}
{
id: "grid_off"
unicode: "e3eb"
}
{
id: "grid_on"
unicode: "e3ec"
}
{
id: "group"
unicode: "e7ef"
}
{
id: "group_add"
unicode: "e7f0"
}
{
id: "group_work"
unicode: "e886"
}
{
id: "hd"
unicode: "e052"
}
{
id: "hdr_off"
unicode: "e3ed"
}
{
id: "hdr_on"
unicode: "e3ee"
}
{
id: "hdr_strong"
unicode: "e3f1"
}
{
id: "hdr_weak"
unicode: "e3f2"
}
{
id: "headset"
unicode: "e310"
}
{
id: "headset_mic"
unicode: "e311"
}
{
id: "healing"
unicode: "e3f3"
}
{
id: "hearing"
unicode: "e023"
}
{
id: "help"
unicode: "e887"
}
{
id: "help_outline"
unicode: "e8fd"
}
{
id: "high_quality"
unicode: "e024"
}
{
id: "highlight"
unicode: "e25f"
}
{
id: "highlight_off"
unicode: "e888"
}
{
id: "history"
unicode: "e889"
}
{
id: "home"
unicode: "e88a"
}
{
id: "hot_tub"
unicode: "eb46"
}
{
id: "hotel"
unicode: "e53a"
}
{
id: "hourglass_empty"
unicode: "e88b"
}
{
id: "hourglass_full"
unicode: "e88c"
}
{
id: "http"
unicode: "e902"
}
{
id: "https"
unicode: "e88d"
}
{
id: "image"
unicode: "e3f4"
}
{
id: "image_aspect_ratio"
unicode: "e3f5"
}
{
id: "import_contacts"
unicode: "e0e0"
}
{
id: "import_export"
unicode: "e0c3"
}
{
id: "important_devices"
unicode: "e912"
}
{
id: "inbox"
unicode: "e156"
}
{
id: "indeterminate_check_box"
unicode: "e909"
}
{
id: "info"
unicode: "e88e"
}
{
id: "info_outline"
unicode: "e88f"
}
{
id: "input"
unicode: "e890"
}
{
id: "insert_chart"
unicode: "e24b"
}
{
id: "insert_comment"
unicode: "e24c"
}
{
id: "insert_drive_file"
unicode: "e24d"
}
{
id: "insert_emoticon"
unicode: "e24e"
}
{
id: "insert_invitation"
unicode: "e24f"
}
{
id: "insert_link"
unicode: "e250"
}
{
id: "insert_photo"
unicode: "e251"
}
{
id: "invert_colors"
unicode: "e891"
}
{
id: "invert_colors_off"
unicode: "e0c4"
}
{
id: "iso"
unicode: "e3f6"
}
{
id: "keyboard"
unicode: "e312"
}
{
id: "keyboard_arrow_down"
unicode: "e313"
}
{
id: "keyboard_arrow_left"
unicode: "e314"
}
{
id: "keyboard_arrow_right"
unicode: "e315"
}
{
id: "keyboard_arrow_up"
unicode: "e316"
}
{
id: "keyboard_backspace"
unicode: "e317"
}
{
id: "keyboard_capslock"
unicode: "e318"
}
{
id: "keyboard_hide"
unicode: "e31a"
}
{
id: "keyboard_return"
unicode: "e31b"
}
{
id: "keyboard_tab"
unicode: "e31c"
}
{
id: "keyboard_voice"
unicode: "e31d"
}
{
id: "kitchen"
unicode: "eb47"
}
{
id: "label"
unicode: "e892"
}
{
id: "label_outline"
unicode: "e893"
}
{
id: "landscape"
unicode: "e3f7"
}
{
id: "language"
unicode: "e894"
}
{
id: "laptop"
unicode: "e31e"
}
{
id: "laptop_chromebook"
unicode: "e31f"
}
{
id: "laptop_mac"
unicode: "e320"
}
{
id: "laptop_windows"
unicode: "e321"
}
{
id: "last_page"
unicode: "e5dd"
}
{
id: "launch"
unicode: "e895"
}
{
id: "layers"
unicode: "e53b"
}
{
id: "layers_clear"
unicode: "e53c"
}
{
id: "leak_add"
unicode: "e3f8"
}
{
id: "leak_remove"
unicode: "e3f9"
}
{
id: "lens"
unicode: "e3fa"
}
{
id: "library_add"
unicode: "e02e"
}
{
id: "library_books"
unicode: "e02f"
}
{
id: "library_music"
unicode: "e030"
}
{
id: "lightbulb_outline"
unicode: "e90f"
}
{
id: "line_style"
unicode: "e919"
}
{
id: "line_weight"
unicode: "e91a"
}
{
id: "linear_scale"
unicode: "e260"
}
{
id: "link"
unicode: "e157"
}
{
id: "linked_camera"
unicode: "e438"
}
{
id: "list"
unicode: "e896"
}
{
id: "live_help"
unicode: "e0c6"
}
{
id: "live_tv"
unicode: "e639"
}
{
id: "local_activity"
unicode: "e53f"
}
{
id: "local_airport"
unicode: "e53d"
}
{
id: "local_atm"
unicode: "e53e"
}
{
id: "local_bar"
unicode: "e540"
}
{
id: "local_cafe"
unicode: "e541"
}
{
id: "local_car_wash"
unicode: "e542"
}
{
id: "local_convenience_store"
unicode: "e543"
}
{
id: "local_dining"
unicode: "e556"
}
{
id: "local_drink"
unicode: "e544"
}
{
id: "local_florist"
unicode: "e545"
}
{
id: "local_gas_station"
unicode: "e546"
}
{
id: "local_grocery_store"
unicode: "e547"
}
{
id: "local_hospital"
unicode: "e548"
}
{
id: "local_hotel"
unicode: "e549"
}
{
id: "local_laundry_service"
unicode: "e54a"
}
{
id: "local_library"
unicode: "e54b"
}
{
id: "local_mall"
unicode: "e54c"
}
{
id: "local_movies"
unicode: "e54d"
}
{
id: "local_offer"
unicode: "e54e"
}
{
id: "local_parking"
unicode: "e54f"
}
{
id: "local_pharmacy"
unicode: "e550"
}
{
id: "local_phone"
unicode: "e551"
}
{
id: "local_pizza"
unicode: "e552"
}
{
id: "local_play"
unicode: "e553"
}
{
id: "local_post_office"
unicode: "e554"
}
{
id: "local_printshop"
unicode: "e555"
}
{
id: "local_see"
unicode: "e557"
}
{
id: "local_shipping"
unicode: "e558"
}
{
id: "local_taxi"
unicode: "e559"
}
{
id: "location_city"
unicode: "e7f1"
}
{
id: "location_disabled"
unicode: "e1b6"
}
{
id: "location_off"
unicode: "e0c7"
}
{
id: "location_on"
unicode: "e0c8"
}
{
id: "location_searching"
unicode: "e1b7"
}
{
id: "lock"
unicode: "e897"
}
{
id: "lock_open"
unicode: "e898"
}
{
id: "lock_outline"
unicode: "e899"
}
{
id: "looks"
unicode: "e3fc"
}
{
id: "looks_3"
unicode: "e3fb"
}
{
id: "looks_4"
unicode: "e3fd"
}
{
id: "looks_5"
unicode: "e3fe"
}
{
id: "looks_6"
unicode: "e3ff"
}
{
id: "looks_one"
unicode: "e400"
}
{
id: "looks_two"
unicode: "e401"
}
{
id: "loop"
unicode: "e028"
}
{
id: "loupe"
unicode: "e402"
}
{
id: "low_priority"
unicode: "e16d"
}
{
id: "loyalty"
unicode: "e89a"
}
{
id: "mail"
unicode: "e158"
}
{
id: "mail_outline"
unicode: "e0e1"
}
{
id: "map"
unicode: "e55b"
}
{
id: "markunread"
unicode: "e159"
}
{
id: "markunread_mailbox"
unicode: "e89b"
}
{
id: "memory"
unicode: "e322"
}
{
id: "menu"
unicode: "e5d2"
}
{
id: "merge_type"
unicode: "e252"
}
{
id: "message"
unicode: "e0c9"
}
{
id: "mic"
unicode: "e029"
}
{
id: "mic_none"
unicode: "e02a"
}
{
id: "mic_off"
unicode: "e02b"
}
{
id: "mms"
unicode: "e618"
}
{
id: "mode_comment"
unicode: "e253"
}
{
id: "mode_edit"
unicode: "e254"
}
{
id: "monetization_on"
unicode: "e263"
}
{
id: "money_off"
unicode: "e25c"
}
{
id: "monochrome_photos"
unicode: "e403"
}
{
id: "mood"
unicode: "e7f2"
}
{
id: "mood_bad"
unicode: "e7f3"
}
{
id: "more"
unicode: "e619"
}
{
id: "more_horiz"
unicode: "e5d3"
}
{
id: "more_vert"
unicode: "e5d4"
}
{
id: "motorcycle"
unicode: "e91b"
}
{
id: "mouse"
unicode: "e323"
}
{
id: "move_to_inbox"
unicode: "e168"
}
{
id: "movie"
unicode: "e02c"
}
{
id: "movie_creation"
unicode: "e404"
}
{
id: "movie_filter"
unicode: "e43a"
}
{
id: "multiline_chart"
unicode: "e6df"
}
{
id: "music_note"
unicode: "e405"
}
{
id: "music_video"
unicode: "e063"
}
{
id: "my_location"
unicode: "e55c"
}
{
id: "nature"
unicode: "e406"
}
{
id: "nature_people"
unicode: "e407"
}
{
id: "navigate_before"
unicode: "e408"
}
{
id: "navigate_next"
unicode: "e409"
}
{
id: "navigation"
unicode: "e55d"
}
{
id: "near_me"
unicode: "e569"
}
{
id: "network_cell"
unicode: "e1b9"
}
{
id: "network_check"
unicode: "e640"
}
{
id: "network_locked"
unicode: "e61a"
}
{
id: "network_wifi"
unicode: "e1ba"
}
{
id: "new_releases"
unicode: "e031"
}
{
id: "next_week"
unicode: "e16a"
}
{
id: "nfc"
unicode: "e1bb"
}
{
id: "no_encryption"
unicode: "e641"
}
{
id: "no_sim"
unicode: "e0cc"
}
{
id: "not_interested"
unicode: "e033"
}
{
id: "note"
unicode: "e06f"
}
{
id: "note_add"
unicode: "e89c"
}
{
id: "notifications"
unicode: "e7f4"
}
{
id: "notifications_active"
unicode: "e7f7"
}
{
id: "notifications_none"
unicode: "e7f5"
}
{
id: "notifications_off"
unicode: "e7f6"
}
{
id: "notifications_paused"
unicode: "e7f8"
}
{
id: "offline_pin"
unicode: "e90a"
}
{
id: "ondemand_video"
unicode: "e63a"
}
{
id: "opacity"
unicode: "e91c"
}
{
id: "open_in_browser"
unicode: "e89d"
}
{
id: "open_in_new"
unicode: "e89e"
}
{
id: "open_with"
unicode: "e89f"
}
{
id: "pages"
unicode: "e7f9"
}
{
id: "pageview"
unicode: "e8a0"
}
{
id: "palette"
unicode: "e40a"
}
{
id: "pan_tool"
unicode: "e925"
}
{
id: "panorama"
unicode: "e40b"
}
{
id: "panorama_fish_eye"
unicode: "e40c"
}
{
id: "panorama_horizontal"
unicode: "e40d"
}
{
id: "panorama_vertical"
unicode: "e40e"
}
{
id: "panorama_wide_angle"
unicode: "e40f"
}
{
id: "party_mode"
unicode: "e7fa"
}
{
id: "pause"
unicode: "e034"
}
{
id: "pause_circle_filled"
unicode: "e035"
}
{
id: "pause_circle_outline"
unicode: "e036"
}
{
id: "payment"
unicode: "e8a1"
}
{
id: "people"
unicode: "e7fb"
}
{
id: "people_outline"
unicode: "e7fc"
}
{
id: "perm_camera_mic"
unicode: "e8a2"
}
{
id: "perm_contact_calendar"
unicode: "e8a3"
}
{
id: "perm_data_setting"
unicode: "e8a4"
}
{
id: "perm_device_information"
unicode: "e8a5"
}
{
id: "perm_identity"
unicode: "e8a6"
}
{
id: "perm_media"
unicode: "e8a7"
}
{
id: "perm_phone_msg"
unicode: "e8a8"
}
{
id: "perm_scan_wifi"
unicode: "e8a9"
}
{
id: "person"
unicode: "e7fd"
}
{
id: "person_add"
unicode: "e7fe"
}
{
id: "person_outline"
unicode: "e7ff"
}
{
id: "person_pin"
unicode: "e55a"
}
{
id: "person_pin_circle"
unicode: "e56a"
}
{
id: "personal_video"
unicode: "e63b"
}
{
id: "pets"
unicode: "e91d"
}
{
id: "phone"
unicode: "e0cd"
}
{
id: "phone_android"
unicode: "e324"
}
{
id: "phone_bluetooth_speaker"
unicode: "e61b"
}
{
id: "phone_forwarded"
unicode: "e61c"
}
{
id: "phone_in_talk"
unicode: "e61d"
}
{
id: "phone_iphone"
unicode: "e325"
}
{
id: "phone_locked"
unicode: "e61e"
}
{
id: "phone_missed"
unicode: "e61f"
}
{
id: "phone_paused"
unicode: "e620"
}
{
id: "phonelink"
unicode: "e326"
}
{
id: "phonelink_erase"
unicode: "e0db"
}
{
id: "phonelink_lock"
unicode: "e0dc"
}
{
id: "phonelink_off"
unicode: "e327"
}
{
id: "phonelink_ring"
unicode: "e0dd"
}
{
id: "phonelink_setup"
unicode: "e0de"
}
{
id: "photo"
unicode: "e410"
}
{
id: "photo_album"
unicode: "e411"
}
{
id: "photo_camera"
unicode: "e412"
}
{
id: "photo_filter"
unicode: "e43b"
}
{
id: "photo_library"
unicode: "e413"
}
{
id: "photo_size_select_actual"
unicode: "e432"
}
{
id: "photo_size_select_large"
unicode: "e433"
}
{
id: "photo_size_select_small"
unicode: "e434"
}
{
id: "picture_as_pdf"
unicode: "e415"
}
{
id: "picture_in_picture"
unicode: "e8aa"
}
{
id: "picture_in_picture_alt"
unicode: "e911"
}
{
id: "pie_chart"
unicode: "e6c4"
}
{
id: "pie_chart_outlined"
unicode: "e6c5"
}
{
id: "pin_drop"
unicode: "e55e"
}
{
id: "place"
unicode: "e55f"
}
{
id: "play_arrow"
unicode: "e037"
}
{
id: "play_circle_filled"
unicode: "e038"
}
{
id: "play_circle_outline"
unicode: "e039"
}
{
id: "play_for_work"
unicode: "e906"
}
{
id: "playlist_add"
unicode: "e03b"
}
{
id: "playlist_add_check"
unicode: "e065"
}
{
id: "playlist_play"
unicode: "e05f"
}
{
id: "plus_one"
unicode: "e800"
}
{
id: "poll"
unicode: "e801"
}
{
id: "polymer"
unicode: "e8ab"
}
{
id: "pool"
unicode: "eb48"
}
{
id: "portable_wifi_off"
unicode: "e0ce"
}
{
id: "portrait"
unicode: "e416"
}
{
id: "power"
unicode: "e63c"
}
{
id: "power_input"
unicode: "e336"
}
{
id: "power_settings_new"
unicode: "e8ac"
}
{
id: "pregnant_woman"
unicode: "e91e"
}
{
id: "present_to_all"
unicode: "e0df"
}
{
id: "print"
unicode: "e8ad"
}
{
id: "priority_high"
unicode: "e645"
}
{
id: "public"
unicode: "e80b"
}
{
id: "publish"
unicode: "e255"
}
{
id: "query_builder"
unicode: "e8ae"
}
{
id: "question_answer"
unicode: "e8af"
}
{
id: "queue"
unicode: "e03c"
}
{
id: "queue_music"
unicode: "e03d"
}
{
id: "queue_play_next"
unicode: "e066"
}
{
id: "radio"
unicode: "e03e"
}
{
id: "radio_button_checked"
unicode: "e837"
}
{
id: "radio_button_unchecked"
unicode: "e836"
}
{
id: "rate_review"
unicode: "e560"
}
{
id: "receipt"
unicode: "e8b0"
}
{
id: "recent_actors"
unicode: "e03f"
}
{
id: "record_voice_over"
unicode: "e91f"
}
{
id: "redeem"
unicode: "e8b1"
}
{
id: "redo"
unicode: "e15a"
}
{
id: "refresh"
unicode: "e5d5"
}
{
id: "remove"
unicode: "e15b"
}
{
id: "remove_circle"
unicode: "e15c"
}
{
id: "remove_circle_outline"
unicode: "e15d"
}
{
id: "remove_from_queue"
unicode: "e067"
}
{
id: "remove_red_eye"
unicode: "e417"
}
{
id: "remove_shopping_cart"
unicode: "e928"
}
{
id: "reorder"
unicode: "e8fe"
}
{
id: "repeat"
unicode: "e040"
}
{
id: "repeat_one"
unicode: "e041"
}
{
id: "replay"
unicode: "e042"
}
{
id: "replay_10"
unicode: "e059"
}
{
id: "replay_30"
unicode: "e05a"
}
{
id: "replay_5"
unicode: "e05b"
}
{
id: "reply"
unicode: "e15e"
}
{
id: "reply_all"
unicode: "e15f"
}
{
id: "report"
unicode: "e160"
}
{
id: "report_problem"
unicode: "e8b2"
}
{
id: "restaurant"
unicode: "e56c"
}
{
id: "restaurant_menu"
unicode: "e561"
}
{
id: "restore"
unicode: "e8b3"
}
{
id: "restore_page"
unicode: "e929"
}
{
id: "ring_volume"
unicode: "e0d1"
}
{
id: "room"
unicode: "e8b4"
}
{
id: "room_service"
unicode: "eb49"
}
{
id: "rotate_90_degrees_ccw"
unicode: "e418"
}
{
id: "rotate_left"
unicode: "e419"
}
{
id: "rotate_right"
unicode: "e41a"
}
{
id: "rounded_corner"
unicode: "e920"
}
{
id: "router"
unicode: "e328"
}
{
id: "rowing"
unicode: "e921"
}
{
id: "rss_feed"
unicode: "e0e5"
}
{
id: "rv_hookup"
unicode: "e642"
}
{
id: "satellite"
unicode: "e562"
}
{
id: "save"
unicode: "e161"
}
{
id: "scanner"
unicode: "e329"
}
{
id: "schedule"
unicode: "e8b5"
}
{
id: "school"
unicode: "e80c"
}
{
id: "screen_lock_landscape"
unicode: "e1be"
}
{
id: "screen_lock_portrait"
unicode: "e1bf"
}
{
id: "screen_lock_rotation"
unicode: "e1c0"
}
{
id: "screen_rotation"
unicode: "e1c1"
}
{
id: "screen_share"
unicode: "e0e2"
}
{
id: "sd_card"
unicode: "e623"
}
{
id: "sd_storage"
unicode: "e1c2"
}
{
id: "search"
unicode: "e8b6"
}
{
id: "security"
unicode: "e32a"
}
{
id: "select_all"
unicode: "e162"
}
{
id: "send"
unicode: "e163"
}
{
id: "sentiment_dissatisfied"
unicode: "e811"
}
{
id: "sentiment_neutral"
unicode: "e812"
}
{
id: "sentiment_satisfied"
unicode: "e813"
}
{
id: "sentiment_very_dissatisfied"
unicode: "e814"
}
{
id: "sentiment_very_satisfied"
unicode: "e815"
}
{
id: "settings"
unicode: "e8b8"
}
{
id: "settings_applications"
unicode: "e8b9"
}
{
id: "settings_backup_restore"
unicode: "e8ba"
}
{
id: "settings_bluetooth"
unicode: "e8bb"
}
{
id: "settings_brightness"
unicode: "e8bd"
}
{
id: "settings_cell"
unicode: "e8bc"
}
{
id: "settings_ethernet"
unicode: "e8be"
}
{
id: "settings_input_antenna"
unicode: "e8bf"
}
{
id: "settings_input_component"
unicode: "e8c0"
}
{
id: "settings_input_composite"
unicode: "e8c1"
}
{
id: "settings_input_hdmi"
unicode: "e8c2"
}
{
id: "settings_input_svideo"
unicode: "e8c3"
}
{
id: "settings_overscan"
unicode: "e8c4"
}
{
id: "settings_phone"
unicode: "e8c5"
}
{
id: "settings_power"
unicode: "e8c6"
}
{
id: "settings_remote"
unicode: "e8c7"
}
{
id: "settings_system_daydream"
unicode: "e1c3"
}
{
id: "settings_voice"
unicode: "e8c8"
}
{
id: "share"
unicode: "e80d"
}
{
id: "shop"
unicode: "e8c9"
}
{
id: "shop_two"
unicode: "e8ca"
}
{
id: "shopping_basket"
unicode: "e8cb"
}
{
id: "shopping_cart"
unicode: "e8cc"
}
{
id: "short_text"
unicode: "e261"
}
{
id: "show_chart"
unicode: "e6e1"
}
{
id: "shuffle"
unicode: "e043"
}
{
id: "signal_cellular_4_bar"
unicode: "e1c8"
}
{
id: "signal_cellular_connected_no_internet_4_bar"
unicode: "e1cd"
}
{
id: "signal_cellular_no_sim"
unicode: "e1ce"
}
{
id: "signal_cellular_null"
unicode: "e1cf"
}
{
id: "signal_cellular_off"
unicode: "e1d0"
}
{
id: "signal_wifi_4_bar"
unicode: "e1d8"
}
{
id: "signal_wifi_4_bar_lock"
unicode: "e1d9"
}
{
id: "signal_wifi_off"
unicode: "e1da"
}
{
id: "sim_card"
unicode: "e32b"
}
{
id: "sim_card_alert"
unicode: "e624"
}
{
id: "skip_next"
unicode: "e044"
}
{
id: "skip_previous"
unicode: "e045"
}
{
id: "slideshow"
unicode: "e41b"
}
{
id: "slow_motion_video"
unicode: "e068"
}
{
id: "smartphone"
unicode: "e32c"
}
{
id: "smoke_free"
unicode: "eb4a"
}
{
id: "smoking_rooms"
unicode: "eb4b"
}
{
id: "sms"
unicode: "e625"
}
{
id: "sms_failed"
unicode: "e626"
}
{
id: "snooze"
unicode: "e046"
}
{
id: "sort"
unicode: "e164"
}
{
id: "sort_by_alpha"
unicode: "e053"
}
{
id: "spa"
unicode: "eb4c"
}
{
id: "space_bar"
unicode: "e256"
}
{
id: "speaker"
unicode: "e32d"
}
{
id: "speaker_group"
unicode: "e32e"
}
{
id: "speaker_notes"
unicode: "e8cd"
}
{
id: "speaker_notes_off"
unicode: "e92a"
}
{
id: "speaker_phone"
unicode: "e0d2"
}
{
id: "spellcheck"
unicode: "e8ce"
}
{
id: "star"
unicode: "e838"
}
{
id: "star_border"
unicode: "e83a"
}
{
id: "star_half"
unicode: "e839"
}
{
id: "stars"
unicode: "e8d0"
}
{
id: "stay_current_landscape"
unicode: "e0d3"
}
{
id: "stay_current_portrait"
unicode: "e0d4"
}
{
id: "stay_primary_landscape"
unicode: "e0d5"
}
{
id: "stay_primary_portrait"
unicode: "e0d6"
}
{
id: "stop"
unicode: "e047"
}
{
id: "stop_screen_share"
unicode: "e0e3"
}
{
id: "storage"
unicode: "e1db"
}
{
id: "store"
unicode: "e8d1"
}
{
id: "store_mall_directory"
unicode: "e563"
}
{
id: "straighten"
unicode: "e41c"
}
{
id: "streetview"
unicode: "e56e"
}
{
id: "strikethrough_s"
unicode: "e257"
}
{
id: "style"
unicode: "e41d"
}
{
id: "subdirectory_arrow_left"
unicode: "e5d9"
}
{
id: "subdirectory_arrow_right"
unicode: "e5da"
}
{
id: "subject"
unicode: "e8d2"
}
{
id: "subscriptions"
unicode: "e064"
}
{
id: "subtitles"
unicode: "e048"
}
{
id: "subway"
unicode: "e56f"
}
{
id: "supervisor_account"
unicode: "e8d3"
}
{
id: "surround_sound"
unicode: "e049"
}
{
id: "swap_calls"
unicode: "e0d7"
}
{
id: "swap_horiz"
unicode: "e8d4"
}
{
id: "swap_vert"
unicode: "e8d5"
}
{
id: "swap_vertical_circle"
unicode: "e8d6"
}
{
id: "switch_camera"
unicode: "e41e"
}
{
id: "switch_video"
unicode: "e41f"
}
{
id: "sync"
unicode: "e627"
}
{
id: "sync_disabled"
unicode: "e628"
}
{
id: "sync_problem"
unicode: "e629"
}
{
id: "system_update"
unicode: "e62a"
}
{
id: "system_update_alt"
unicode: "e8d7"
}
{
id: "tab"
unicode: "e8d8"
}
{
id: "tab_unselected"
unicode: "e8d9"
}
{
id: "tablet"
unicode: "e32f"
}
{
id: "tablet_android"
unicode: "e330"
}
{
id: "tablet_mac"
unicode: "e331"
}
{
id: "tag_faces"
unicode: "e420"
}
{
id: "tap_and_play"
unicode: "e62b"
}
{
id: "terrain"
unicode: "e564"
}
{
id: "text_fields"
unicode: "e262"
}
{
id: "text_format"
unicode: "e165"
}
{
id: "textsms"
unicode: "e0d8"
}
{
id: "texture"
unicode: "e421"
}
{
id: "theaters"
unicode: "e8da"
}
{
id: "thumb_down"
unicode: "e8db"
}
{
id: "thumb_up"
unicode: "e8dc"
}
{
id: "thumbs_up_down"
unicode: "e8dd"
}
{
id: "time_to_leave"
unicode: "e62c"
}
{
id: "timelapse"
unicode: "e422"
}
{
id: "timeline"
unicode: "e922"
}
{
id: "timer"
unicode: "e425"
}
{
id: "timer_10"
unicode: "e423"
}
{
id: "timer_3"
unicode: "e424"
}
{
id: "timer_off"
unicode: "e426"
}
{
id: "title"
unicode: "e264"
}
{
id: "toc"
unicode: "e8de"
}
{
id: "today"
unicode: "e8df"
}
{
id: "toll"
unicode: "e8e0"
}
{
id: "tonality"
unicode: "e427"
}
{
id: "touch_app"
unicode: "e913"
}
{
id: "toys"
unicode: "e332"
}
{
id: "track_changes"
unicode: "e8e1"
}
{
id: "traffic"
unicode: "e565"
}
{
id: "train"
unicode: "e570"
}
{
id: "tram"
unicode: "e571"
}
{
id: "transfer_within_a_station"
unicode: "e572"
}
{
id: "transform"
unicode: "e428"
}
{
id: "translate"
unicode: "e8e2"
}
{
id: "trending_down"
unicode: "e8e3"
}
{
id: "trending_flat"
unicode: "e8e4"
}
{
id: "trending_up"
unicode: "e8e5"
}
{
id: "tune"
unicode: "e429"
}
{
id: "turned_in"
unicode: "e8e6"
}
{
id: "turned_in_not"
unicode: "e8e7"
}
{
id: "tv"
unicode: "e333"
}
{
id: "unarchive"
unicode: "e169"
}
{
id: "undo"
unicode: "e166"
}
{
id: "unfold_less"
unicode: "e5d6"
}
{
id: "unfold_more"
unicode: "e5d7"
}
{
id: "update"
unicode: "e923"
}
{
id: "usb"
unicode: "e1e0"
}
{
id: "verified_user"
unicode: "e8e8"
}
{
id: "vertical_align_bottom"
unicode: "e258"
}
{
id: "vertical_align_center"
unicode: "e259"
}
{
id: "vertical_align_top"
unicode: "e25a"
}
{
id: "vibration"
unicode: "e62d"
}
{
id: "video_call"
unicode: "e070"
}
{
id: "video_label"
unicode: "e071"
}
{
id: "video_library"
unicode: "e04a"
}
{
id: "videocam"
unicode: "e04b"
}
{
id: "videocam_off"
unicode: "e04c"
}
{
id: "videogame_asset"
unicode: "e338"
}
{
id: "view_agenda"
unicode: "e8e9"
}
{
id: "view_array"
unicode: "e8ea"
}
{
id: "view_carousel"
unicode: "e8eb"
}
{
id: "view_column"
unicode: "e8ec"
}
{
id: "view_comfy"
unicode: "e42a"
}
{
id: "view_compact"
unicode: "e42b"
}
{
id: "view_day"
unicode: "e8ed"
}
{
id: "view_headline"
unicode: "e8ee"
}
{
id: "view_list"
unicode: "e8ef"
}
{
id: "view_module"
unicode: "e8f0"
}
{
id: "view_quilt"
unicode: "e8f1"
}
{
id: "view_stream"
unicode: "e8f2"
}
{
id: "view_week"
unicode: "e8f3"
}
{
id: "vignette"
unicode: "e435"
}
{
id: "visibility"
unicode: "e8f4"
}
{
id: "visibility_off"
unicode: "e8f5"
}
{
id: "voice_chat"
unicode: "e62e"
}
{
id: "voicemail"
unicode: "e0d9"
}
{
id: "volume_down"
unicode: "e04d"
}
{
id: "volume_mute"
unicode: "e04e"
}
{
id: "volume_off"
unicode: "e04f"
}
{
id: "volume_up"
unicode: "e050"
}
{
id: "vpn_key"
unicode: "e0da"
}
{
id: "vpn_lock"
unicode: "e62f"
}
{
id: "wallpaper"
unicode: "e1bc"
}
{
id: "warning"
unicode: "e002"
}
{
id: "watch"
unicode: "e334"
}
{
id: "watch_later"
unicode: "e924"
}
{
id: "wb_auto"
unicode: "e42c"
}
{
id: "wb_cloudy"
unicode: "e42d"
}
{
id: "wb_incandescent"
unicode: "e42e"
}
{
id: "wb_iridescent"
unicode: "e436"
}
{
id: "wb_sunny"
unicode: "e430"
}
{
id: "wc"
unicode: "e63d"
}
{
id: "web"
unicode: "e051"
}
{
id: "web_asset"
unicode: "e069"
}
{
id: "weekend"
unicode: "e16b"
}
{
id: "whatshot"
unicode: "e80e"
}
{
id: "widgets"
unicode: "e1bd"
}
{
id: "wifi"
unicode: "e63e"
}
{
id: "wifi_lock"
unicode: "e1e1"
}
{
id: "wifi_tethering"
unicode: "e1e2"
}
{
id: "work"
unicode: "e8f9"
}
{
id: "wrap_text"
unicode: "e25b"
}
{
id: "youtube_searched_for"
unicode: "e8fa"
}
{
id: "zoom_in"
unicode: "e8ff"
}
{
id: "zoom_out"
unicode: "e900"
}
{
id: "zoom_out_map"
unicode: "e56b"
}
] | true | icons: [
{
id: "3d_rotation"
unicode: "e84d"
}
{
id: "ac_unit"
unicode: "eb3b"
}
{
id: "access_alarm"
unicode: "e190"
}
{
id: "access_alarms"
unicode: "e191"
}
{
id: "access_time"
unicode: "e192"
}
{
id: "accessibility"
unicode: "e84e"
}
{
id: "accessible"
unicode: "e914"
}
{
id: "account_balance"
unicode: "e84f"
}
{
id: "account_balance_wallet"
unicode: "e850"
}
{
id: "account_box"
unicode: "e851"
}
{
id: "account_circle"
unicode: "e853"
}
{
id: "adb"
unicode: "e60e"
}
{
id: "add"
unicode: "e145"
}
{
id: "add_a_photo"
unicode: "e439"
}
{
id: "add_alarm"
unicode: "e193"
}
{
id: "add_alert"
unicode: "e003"
}
{
id: "add_box"
unicode: "e146"
}
{
id: "add_circle"
unicode: "e147"
}
{
id: "add_circle_outline"
unicode: "e148"
}
{
id: "add_location"
unicode: "e567"
}
{
id: "add_shopping_cart"
unicode: "e854"
}
{
id: "add_to_photos"
unicode: "e39d"
}
{
id: "add_to_queue"
unicode: "e05c"
}
{
id: "adjust"
unicode: "e39e"
}
{
id: "airline_seat_flat"
unicode: "e630"
}
{
id: "airline_seat_flat_angled"
unicode: "e631"
}
{
id: "airline_seat_individual_suite"
unicode: "e632"
}
{
id: "airline_seat_legroom_extra"
unicode: "e633"
}
{
id: "airline_seat_legroom_normal"
unicode: "e634"
}
{
id: "airline_seat_legroom_reduced"
unicode: "e635"
}
{
id: "airline_seat_recline_extra"
unicode: "e636"
}
{
id: "airline_seat_recline_normal"
unicode: "e637"
}
{
id: "airplanemode_active"
unicode: "e195"
}
{
id: "airplanemode_inactive"
unicode: "e194"
}
{
id: "airplay"
unicode: "e055"
}
{
id: "airport_shuttle"
unicode: "eb3c"
}
{
id: "alarm"
unicode: "e855"
}
{
id: "alarm_add"
unicode: "e856"
}
{
id: "alarm_off"
unicode: "e857"
}
{
id: "alarm_on"
unicode: "e858"
}
{
id: "album"
unicode: "e019"
}
{
id: "all_inclusive"
unicode: "eb3d"
}
{
id: "all_out"
unicode: "e90b"
}
{
id: "android"
unicode: "e859"
}
{
id: "announcement"
unicode: "e85a"
}
{
id: "apps"
unicode: "e5c3"
}
{
id: "archive"
unicode: "e149"
}
{
id: "arrow_back"
unicode: "e5c4"
}
{
id: "arrow_downward"
unicode: "e5db"
}
{
id: "arrow_drop_down"
unicode: "e5c5"
}
{
id: "arrow_drop_down_circle"
unicode: "e5c6"
}
{
id: "arrow_drop_up"
unicode: "e5c7"
}
{
id: "arrow_forward"
unicode: "e5c8"
}
{
id: "arrow_upward"
unicode: "e5d8"
}
{
id: "art_track"
unicode: "e060"
}
{
id: "aspect_ratio"
unicode: "e85b"
}
{
id: "assessment"
unicode: "e85c"
}
{
id: "assignment"
unicode: "e85d"
}
{
id: "assignment_ind"
unicode: "e85e"
}
{
id: "assignment_late"
unicode: "e85f"
}
{
id: "assignment_return"
unicode: "e860"
}
{
id: "assignment_returned"
unicode: "e861"
}
{
id: "assignment_turned_in"
unicode: "e862"
}
{
id: "assistant"
unicode: "e39f"
}
{
id: "assistant_photo"
unicode: "e3a0"
}
{
id: "attach_file"
unicode: "e226"
}
{
id: "attach_money"
unicode: "e227"
}
{
id: "attachment"
unicode: "e2bc"
}
{
id: "audiotrack"
unicode: "e3a1"
}
{
id: "autorenew"
unicode: "e863"
}
{
id: "av_timer"
unicode: "e01b"
}
{
id: "backspace"
unicode: "e14a"
}
{
id: "backup"
unicode: "e864"
}
{
id: "battery_alert"
unicode: "e19c"
}
{
id: "battery_charging_full"
unicode: "e1a3"
}
{
id: "battery_full"
unicode: "e1a4"
}
{
id: "battery_std"
unicode: "e1a5"
}
{
id: "battery_unknown"
unicode: "e1a6"
}
{
id: "beach_access"
unicode: "eb3e"
}
{
id: "beenhere"
unicode: "e52d"
}
{
id: "block"
unicode: "e14b"
}
{
id: "bluetooth"
unicode: "e1a7"
}
{
id: "bluetooth_audio"
unicode: "e60f"
}
{
id: "bluetooth_connected"
unicode: "e1a8"
}
{
id: "bluetooth_disabled"
unicode: "e1a9"
}
{
id: "bluetooth_searching"
unicode: "e1aa"
}
{
id: "blur_circular"
unicode: "e3a2"
}
{
id: "blur_linear"
unicode: "e3a3"
}
{
id: "blur_off"
unicode: "e3a4"
}
{
id: "blur_on"
unicode: "e3a5"
}
{
id: "book"
unicode: "e865"
}
{
id: "bookmark"
unicode: "e866"
}
{
id: "bookmark_border"
unicode: "e867"
}
{
id: "border_all"
unicode: "e228"
}
{
id: "border_bottom"
unicode: "e229"
}
{
id: "border_clear"
unicode: "e22a"
}
{
id: "border_color"
unicode: "e22b"
}
{
id: "border_horizontal"
unicode: "e22c"
}
{
id: "border_inner"
unicode: "e22d"
}
{
id: "border_left"
unicode: "e22e"
}
{
id: "border_outer"
unicode: "e22f"
}
{
id: "border_right"
unicode: "e230"
}
{
id: "border_style"
unicode: "e231"
}
{
id: "border_top"
unicode: "e232"
}
{
id: "border_vertical"
unicode: "e233"
}
{
id: "branding_watermark"
unicode: "e06b"
}
{
id: "brightness_1"
unicode: "e3a6"
}
{
id: "brightness_2"
unicode: "e3a7"
}
{
id: "brightness_3"
unicode: "e3a8"
}
{
id: "brightness_4"
unicode: "e3a9"
}
{
id: "brightness_5"
unicode: "e3aa"
}
{
id: "brightness_6"
unicode: "e3ab"
}
{
id: "brightness_7"
unicode: "e3ac"
}
{
id: "brightness_auto"
unicode: "e1ab"
}
{
id: "brightness_high"
unicode: "e1ac"
}
{
id: "brightness_low"
unicode: "e1ad"
}
{
id: "brightness_medium"
unicode: "e1ae"
}
{
id: "broken_image"
unicode: "e3ad"
}
{
id: "brush"
unicode: "e3ae"
}
{
id: "bubble_chart"
unicode: "e6dd"
}
{
id: "bug_report"
unicode: "e868"
}
{
id: "build"
unicode: "e869"
}
{
id: "burst_mode"
unicode: "e43c"
}
{
id: "business"
unicode: "e0af"
}
{
id: "business_center"
unicode: "eb3f"
}
{
id: "cached"
unicode: "e86a"
}
{
id: "cake"
unicode: "e7e9"
}
{
id: "call"
unicode: "e0b0"
}
{
id: "call_end"
unicode: "e0b1"
}
{
id: "call_made"
unicode: "e0b2"
}
{
id: "call_merge"
unicode: "e0b3"
}
{
id: "call_missed"
unicode: "e0b4"
}
{
id: "call_missed_outgoing"
unicode: "e0e4"
}
{
id: "call_received"
unicode: "e0b5"
}
{
id: "call_split"
unicode: "e0b6"
}
{
id: "call_to_action"
unicode: "e06c"
}
{
id: "camera"
unicode: "e3af"
}
{
id: "camera_alt"
unicode: "e3b0"
}
{
id: "camera_enhance"
unicode: "e8fc"
}
{
id: "camera_front"
unicode: "e3b1"
}
{
id: "camera_rear"
unicode: "e3b2"
}
{
id: "camera_roll"
unicode: "e3b3"
}
{
id: "cancel"
unicode: "e5c9"
}
{
id: "card_giftcard"
unicode: "e8f6"
}
{
id: "card_membership"
unicode: "e8f7"
}
{
id: "card_travel"
unicode: "e8f8"
}
{
id: "PI:NAME:<NAME>END_PI"
unicode: "eb40"
}
{
id: "cast"
unicode: "e307"
}
{
id: "cast_connected"
unicode: "e308"
}
{
id: "center_focus_strong"
unicode: "e3b4"
}
{
id: "center_focus_weak"
unicode: "e3b5"
}
{
id: "change_history"
unicode: "e86b"
}
{
id: "chat"
unicode: "e0b7"
}
{
id: "chat_bubble"
unicode: "e0ca"
}
{
id: "chat_bubble_outline"
unicode: "e0cb"
}
{
id: "check"
unicode: "e5ca"
}
{
id: "check_box"
unicode: "e834"
}
{
id: "check_box_outline_blank"
unicode: "e835"
}
{
id: "check_circle"
unicode: "e86c"
}
{
id: "chevron_left"
unicode: "e5cb"
}
{
id: "chevron_right"
unicode: "e5cc"
}
{
id: "child_care"
unicode: "eb41"
}
{
id: "child_friendly"
unicode: "eb42"
}
{
id: "chrome_reader_mode"
unicode: "e86d"
}
{
id: "class"
unicode: "e86e"
}
{
id: "clear"
unicode: "e14c"
}
{
id: "clear_all"
unicode: "e0b8"
}
{
id: "close"
unicode: "e5cd"
}
{
id: "closed_caption"
unicode: "e01c"
}
{
id: "cloud"
unicode: "e2bd"
}
{
id: "cloud_circle"
unicode: "e2be"
}
{
id: "cloud_done"
unicode: "e2bf"
}
{
id: "cloud_download"
unicode: "e2c0"
}
{
id: "cloud_off"
unicode: "e2c1"
}
{
id: "cloud_queue"
unicode: "e2c2"
}
{
id: "cloud_upload"
unicode: "e2c3"
}
{
id: "code"
unicode: "e86f"
}
{
id: "collections"
unicode: "e3b6"
}
{
id: "collections_bookmark"
unicode: "e431"
}
{
id: "color_lens"
unicode: "e3b7"
}
{
id: "colorize"
unicode: "e3b8"
}
{
id: "comment"
unicode: "e0b9"
}
{
id: "compare"
unicode: "e3b9"
}
{
id: "compare_arrows"
unicode: "e915"
}
{
id: "computer"
unicode: "e30a"
}
{
id: "confirmation_number"
unicode: "e638"
}
{
id: "contact_mail"
unicode: "e0d0"
}
{
id: "contact_phone"
unicode: "e0cf"
}
{
id: "contacts"
unicode: "e0ba"
}
{
id: "content_copy"
unicode: "e14d"
}
{
id: "content_cut"
unicode: "e14e"
}
{
id: "content_paste"
unicode: "e14f"
}
{
id: "control_point"
unicode: "e3ba"
}
{
id: "control_point_duplicate"
unicode: "e3bb"
}
{
id: "copyright"
unicode: "e90c"
}
{
id: "create"
unicode: "e150"
}
{
id: "create_new_folder"
unicode: "e2cc"
}
{
id: "credit_card"
unicode: "e870"
}
{
id: "crop"
unicode: "e3be"
}
{
id: "crop_16_9"
unicode: "e3bc"
}
{
id: "crop_3_2"
unicode: "e3bd"
}
{
id: "crop_5_4"
unicode: "e3bf"
}
{
id: "crop_7_5"
unicode: "e3c0"
}
{
id: "crop_din"
unicode: "e3c1"
}
{
id: "crop_free"
unicode: "e3c2"
}
{
id: "crop_landscape"
unicode: "e3c3"
}
{
id: "crop_original"
unicode: "e3c4"
}
{
id: "crop_portrait"
unicode: "e3c5"
}
{
id: "crop_rotate"
unicode: "e437"
}
{
id: "crop_square"
unicode: "e3c6"
}
{
id: "dashboard"
unicode: "e871"
}
{
id: "data_usage"
unicode: "e1af"
}
{
id: "date_range"
unicode: "e916"
}
{
id: "dehaze"
unicode: "e3c7"
}
{
id: "delete"
unicode: "e872"
}
{
id: "delete_forever"
unicode: "e92b"
}
{
id: "delete_sweep"
unicode: "e16c"
}
{
id: "description"
unicode: "e873"
}
{
id: "desktop_mac"
unicode: "e30b"
}
{
id: "desktop_windows"
unicode: "e30c"
}
{
id: "details"
unicode: "e3c8"
}
{
id: "developer_board"
unicode: "e30d"
}
{
id: "developer_mode"
unicode: "e1b0"
}
{
id: "device_hub"
unicode: "e335"
}
{
id: "devices"
unicode: "e1b1"
}
{
id: "devices_other"
unicode: "e337"
}
{
id: "dialer_sip"
unicode: "e0bb"
}
{
id: "dialpad"
unicode: "e0bc"
}
{
id: "directions"
unicode: "e52e"
}
{
id: "directions_bike"
unicode: "e52f"
}
{
id: "directions_boat"
unicode: "e532"
}
{
id: "directions_bus"
unicode: "e530"
}
{
id: "directions_car"
unicode: "e531"
}
{
id: "directions_railway"
unicode: "e534"
}
{
id: "directions_run"
unicode: "e566"
}
{
id: "directions_subway"
unicode: "e533"
}
{
id: "directions_transit"
unicode: "e535"
}
{
id: "directions_walk"
unicode: "e536"
}
{
id: "disc_full"
unicode: "e610"
}
{
id: "dns"
unicode: "e875"
}
{
id: "do_not_disturb"
unicode: "e612"
}
{
id: "do_not_disturb_alt"
unicode: "e611"
}
{
id: "do_not_disturb_off"
unicode: "e643"
}
{
id: "do_not_disturb_on"
unicode: "e644"
}
{
id: "dock"
unicode: "e30e"
}
{
id: "domain"
unicode: "e7ee"
}
{
id: "done"
unicode: "e876"
}
{
id: "done_all"
unicode: "e877"
}
{
id: "donut_large"
unicode: "e917"
}
{
id: "donut_small"
unicode: "e918"
}
{
id: "drafts"
unicode: "e151"
}
{
id: "drag_handle"
unicode: "e25d"
}
{
id: "drive_eta"
unicode: "e613"
}
{
id: "dvr"
unicode: "e1b2"
}
{
id: "edit"
unicode: "e3c9"
}
{
id: "edit_location"
unicode: "e568"
}
{
id: "eject"
unicode: "e8fb"
}
{
id: "email"
unicode: "e0be"
}
{
id: "enhanced_encryption"
unicode: "e63f"
}
{
id: "equalizer"
unicode: "e01d"
}
{
id: "error"
unicode: "e000"
}
{
id: "error_outline"
unicode: "e001"
}
{
id: "euro_symbol"
unicode: "e926"
}
{
id: "ev_station"
unicode: "e56d"
}
{
id: "event"
unicode: "e878"
}
{
id: "event_available"
unicode: "e614"
}
{
id: "event_busy"
unicode: "e615"
}
{
id: "event_note"
unicode: "e616"
}
{
id: "event_seat"
unicode: "e903"
}
{
id: "exit_to_app"
unicode: "e879"
}
{
id: "expand_less"
unicode: "e5ce"
}
{
id: "expand_more"
unicode: "e5cf"
}
{
id: "explicit"
unicode: "e01e"
}
{
id: "explore"
unicode: "e87a"
}
{
id: "exposure"
unicode: "e3ca"
}
{
id: "exposure_neg_1"
unicode: "e3cb"
}
{
id: "exposure_neg_2"
unicode: "e3cc"
}
{
id: "exposure_plus_1"
unicode: "e3cd"
}
{
id: "exposure_plus_2"
unicode: "e3ce"
}
{
id: "exposure_zero"
unicode: "e3cf"
}
{
id: "extension"
unicode: "e87b"
}
{
id: "face"
unicode: "e87c"
}
{
id: "fast_forward"
unicode: "e01f"
}
{
id: "fast_rewind"
unicode: "e020"
}
{
id: "favorite"
unicode: "e87d"
}
{
id: "favorite_border"
unicode: "e87e"
}
{
id: "featured_play_list"
unicode: "e06d"
}
{
id: "featured_video"
unicode: "e06e"
}
{
id: "feedback"
unicode: "e87f"
}
{
id: "fiber_dvr"
unicode: "e05d"
}
{
id: "fiber_manual_record"
unicode: "e061"
}
{
id: "fiber_new"
unicode: "e05e"
}
{
id: "fiber_pin"
unicode: "e06a"
}
{
id: "fiber_smart_record"
unicode: "e062"
}
{
id: "file_download"
unicode: "e2c4"
}
{
id: "file_upload"
unicode: "e2c6"
}
{
id: "filter"
unicode: "e3d3"
}
{
id: "filter_1"
unicode: "e3d0"
}
{
id: "filter_2"
unicode: "e3d1"
}
{
id: "filter_3"
unicode: "e3d2"
}
{
id: "filter_4"
unicode: "e3d4"
}
{
id: "filter_5"
unicode: "e3d5"
}
{
id: "filter_6"
unicode: "e3d6"
}
{
id: "filter_7"
unicode: "e3d7"
}
{
id: "filter_8"
unicode: "e3d8"
}
{
id: "filter_9"
unicode: "e3d9"
}
{
id: "filter_9_plus"
unicode: "e3da"
}
{
id: "filter_b_and_w"
unicode: "e3db"
}
{
id: "filter_center_focus"
unicode: "e3dc"
}
{
id: "filter_drama"
unicode: "e3dd"
}
{
id: "filter_frames"
unicode: "e3de"
}
{
id: "filter_hdr"
unicode: "e3df"
}
{
id: "filter_list"
unicode: "e152"
}
{
id: "filter_none"
unicode: "e3e0"
}
{
id: "filter_tilt_shift"
unicode: "e3e2"
}
{
id: "filter_vintage"
unicode: "e3e3"
}
{
id: "find_in_page"
unicode: "e880"
}
{
id: "find_replace"
unicode: "e881"
}
{
id: "fingerprint"
unicode: "e90d"
}
{
id: "first_page"
unicode: "e5dc"
}
{
id: "fitness_center"
unicode: "eb43"
}
{
id: "flag"
unicode: "e153"
}
{
id: "flare"
unicode: "e3e4"
}
{
id: "flash_auto"
unicode: "e3e5"
}
{
id: "flash_off"
unicode: "e3e6"
}
{
id: "flash_on"
unicode: "e3e7"
}
{
id: "flight"
unicode: "e539"
}
{
id: "flight_land"
unicode: "e904"
}
{
id: "flight_takeoff"
unicode: "e905"
}
{
id: "flip"
unicode: "e3e8"
}
{
id: "flip_to_back"
unicode: "e882"
}
{
id: "flip_to_front"
unicode: "e883"
}
{
id: "folder"
unicode: "e2c7"
}
{
id: "folder_open"
unicode: "e2c8"
}
{
id: "folder_shared"
unicode: "e2c9"
}
{
id: "folder_special"
unicode: "e617"
}
{
id: "font_download"
unicode: "e167"
}
{
id: "format_align_center"
unicode: "e234"
}
{
id: "format_align_justify"
unicode: "e235"
}
{
id: "format_align_left"
unicode: "e236"
}
{
id: "format_align_right"
unicode: "e237"
}
{
id: "format_bold"
unicode: "e238"
}
{
id: "format_clear"
unicode: "e239"
}
{
id: "format_color_fill"
unicode: "e23a"
}
{
id: "format_color_reset"
unicode: "e23b"
}
{
id: "format_color_text"
unicode: "e23c"
}
{
id: "format_indent_decrease"
unicode: "e23d"
}
{
id: "format_indent_increase"
unicode: "e23e"
}
{
id: "format_italic"
unicode: "e23f"
}
{
id: "format_line_spacing"
unicode: "e240"
}
{
id: "format_list_bulleted"
unicode: "e241"
}
{
id: "format_list_numbered"
unicode: "e242"
}
{
id: "format_paint"
unicode: "e243"
}
{
id: "format_quote"
unicode: "e244"
}
{
id: "format_shapes"
unicode: "e25e"
}
{
id: "format_size"
unicode: "e245"
}
{
id: "format_strikethrough"
unicode: "e246"
}
{
id: "format_textdirection_l_to_r"
unicode: "e247"
}
{
id: "format_textdirection_r_to_l"
unicode: "e248"
}
{
id: "format_underlined"
unicode: "e249"
}
{
id: "forum"
unicode: "e0bf"
}
{
id: "forward"
unicode: "e154"
}
{
id: "forward_10"
unicode: "e056"
}
{
id: "forward_30"
unicode: "e057"
}
{
id: "forward_5"
unicode: "e058"
}
{
id: "free_breakfast"
unicode: "eb44"
}
{
id: "fullscreen"
unicode: "e5d0"
}
{
id: "fullscreen_exit"
unicode: "e5d1"
}
{
id: "functions"
unicode: "e24a"
}
{
id: "g_translate"
unicode: "e927"
}
{
id: "gamepad"
unicode: "e30f"
}
{
id: "games"
unicode: "e021"
}
{
id: "gavel"
unicode: "e90e"
}
{
id: "gesture"
unicode: "e155"
}
{
id: "get_app"
unicode: "e884"
}
{
id: "gif"
unicode: "e908"
}
{
id: "golf_course"
unicode: "eb45"
}
{
id: "gps_fixed"
unicode: "e1b3"
}
{
id: "gps_not_fixed"
unicode: "e1b4"
}
{
id: "gps_off"
unicode: "e1b5"
}
{
id: "grade"
unicode: "e885"
}
{
id: "gradient"
unicode: "e3e9"
}
{
id: "grain"
unicode: "e3ea"
}
{
id: "graphic_eq"
unicode: "e1b8"
}
{
id: "grid_off"
unicode: "e3eb"
}
{
id: "grid_on"
unicode: "e3ec"
}
{
id: "group"
unicode: "e7ef"
}
{
id: "group_add"
unicode: "e7f0"
}
{
id: "group_work"
unicode: "e886"
}
{
id: "hd"
unicode: "e052"
}
{
id: "hdr_off"
unicode: "e3ed"
}
{
id: "hdr_on"
unicode: "e3ee"
}
{
id: "hdr_strong"
unicode: "e3f1"
}
{
id: "hdr_weak"
unicode: "e3f2"
}
{
id: "headset"
unicode: "e310"
}
{
id: "headset_mic"
unicode: "e311"
}
{
id: "healing"
unicode: "e3f3"
}
{
id: "hearing"
unicode: "e023"
}
{
id: "help"
unicode: "e887"
}
{
id: "help_outline"
unicode: "e8fd"
}
{
id: "high_quality"
unicode: "e024"
}
{
id: "highlight"
unicode: "e25f"
}
{
id: "highlight_off"
unicode: "e888"
}
{
id: "history"
unicode: "e889"
}
{
id: "home"
unicode: "e88a"
}
{
id: "hot_tub"
unicode: "eb46"
}
{
id: "hotel"
unicode: "e53a"
}
{
id: "hourglass_empty"
unicode: "e88b"
}
{
id: "hourglass_full"
unicode: "e88c"
}
{
id: "http"
unicode: "e902"
}
{
id: "https"
unicode: "e88d"
}
{
id: "image"
unicode: "e3f4"
}
{
id: "image_aspect_ratio"
unicode: "e3f5"
}
{
id: "import_contacts"
unicode: "e0e0"
}
{
id: "import_export"
unicode: "e0c3"
}
{
id: "important_devices"
unicode: "e912"
}
{
id: "inbox"
unicode: "e156"
}
{
id: "indeterminate_check_box"
unicode: "e909"
}
{
id: "info"
unicode: "e88e"
}
{
id: "info_outline"
unicode: "e88f"
}
{
id: "input"
unicode: "e890"
}
{
id: "insert_chart"
unicode: "e24b"
}
{
id: "insert_comment"
unicode: "e24c"
}
{
id: "insert_drive_file"
unicode: "e24d"
}
{
id: "insert_emoticon"
unicode: "e24e"
}
{
id: "insert_invitation"
unicode: "e24f"
}
{
id: "insert_link"
unicode: "e250"
}
{
id: "insert_photo"
unicode: "e251"
}
{
id: "invert_colors"
unicode: "e891"
}
{
id: "invert_colors_off"
unicode: "e0c4"
}
{
id: "iso"
unicode: "e3f6"
}
{
id: "keyboard"
unicode: "e312"
}
{
id: "keyboard_arrow_down"
unicode: "e313"
}
{
id: "keyboard_arrow_left"
unicode: "e314"
}
{
id: "keyboard_arrow_right"
unicode: "e315"
}
{
id: "keyboard_arrow_up"
unicode: "e316"
}
{
id: "keyboard_backspace"
unicode: "e317"
}
{
id: "keyboard_capslock"
unicode: "e318"
}
{
id: "keyboard_hide"
unicode: "e31a"
}
{
id: "keyboard_return"
unicode: "e31b"
}
{
id: "keyboard_tab"
unicode: "e31c"
}
{
id: "keyboard_voice"
unicode: "e31d"
}
{
id: "kitchen"
unicode: "eb47"
}
{
id: "label"
unicode: "e892"
}
{
id: "label_outline"
unicode: "e893"
}
{
id: "landscape"
unicode: "e3f7"
}
{
id: "language"
unicode: "e894"
}
{
id: "laptop"
unicode: "e31e"
}
{
id: "laptop_chromebook"
unicode: "e31f"
}
{
id: "laptop_mac"
unicode: "e320"
}
{
id: "laptop_windows"
unicode: "e321"
}
{
id: "last_page"
unicode: "e5dd"
}
{
id: "launch"
unicode: "e895"
}
{
id: "layers"
unicode: "e53b"
}
{
id: "layers_clear"
unicode: "e53c"
}
{
id: "leak_add"
unicode: "e3f8"
}
{
id: "leak_remove"
unicode: "e3f9"
}
{
id: "lens"
unicode: "e3fa"
}
{
id: "library_add"
unicode: "e02e"
}
{
id: "library_books"
unicode: "e02f"
}
{
id: "library_music"
unicode: "e030"
}
{
id: "lightbulb_outline"
unicode: "e90f"
}
{
id: "line_style"
unicode: "e919"
}
{
id: "line_weight"
unicode: "e91a"
}
{
id: "linear_scale"
unicode: "e260"
}
{
id: "link"
unicode: "e157"
}
{
id: "linked_camera"
unicode: "e438"
}
{
id: "list"
unicode: "e896"
}
{
id: "live_help"
unicode: "e0c6"
}
{
id: "live_tv"
unicode: "e639"
}
{
id: "local_activity"
unicode: "e53f"
}
{
id: "local_airport"
unicode: "e53d"
}
{
id: "local_atm"
unicode: "e53e"
}
{
id: "local_bar"
unicode: "e540"
}
{
id: "local_cafe"
unicode: "e541"
}
{
id: "local_car_wash"
unicode: "e542"
}
{
id: "local_convenience_store"
unicode: "e543"
}
{
id: "local_dining"
unicode: "e556"
}
{
id: "local_drink"
unicode: "e544"
}
{
id: "local_florist"
unicode: "e545"
}
{
id: "local_gas_station"
unicode: "e546"
}
{
id: "local_grocery_store"
unicode: "e547"
}
{
id: "local_hospital"
unicode: "e548"
}
{
id: "local_hotel"
unicode: "e549"
}
{
id: "local_laundry_service"
unicode: "e54a"
}
{
id: "local_library"
unicode: "e54b"
}
{
id: "local_mall"
unicode: "e54c"
}
{
id: "local_movies"
unicode: "e54d"
}
{
id: "local_offer"
unicode: "e54e"
}
{
id: "local_parking"
unicode: "e54f"
}
{
id: "local_pharmacy"
unicode: "e550"
}
{
id: "local_phone"
unicode: "e551"
}
{
id: "local_pizza"
unicode: "e552"
}
{
id: "local_play"
unicode: "e553"
}
{
id: "local_post_office"
unicode: "e554"
}
{
id: "local_printshop"
unicode: "e555"
}
{
id: "local_see"
unicode: "e557"
}
{
id: "local_shipping"
unicode: "e558"
}
{
id: "local_taxi"
unicode: "e559"
}
{
id: "location_city"
unicode: "e7f1"
}
{
id: "location_disabled"
unicode: "e1b6"
}
{
id: "location_off"
unicode: "e0c7"
}
{
id: "location_on"
unicode: "e0c8"
}
{
id: "location_searching"
unicode: "e1b7"
}
{
id: "lock"
unicode: "e897"
}
{
id: "lock_open"
unicode: "e898"
}
{
id: "lock_outline"
unicode: "e899"
}
{
id: "looks"
unicode: "e3fc"
}
{
id: "looks_3"
unicode: "e3fb"
}
{
id: "looks_4"
unicode: "e3fd"
}
{
id: "looks_5"
unicode: "e3fe"
}
{
id: "looks_6"
unicode: "e3ff"
}
{
id: "looks_one"
unicode: "e400"
}
{
id: "looks_two"
unicode: "e401"
}
{
id: "loop"
unicode: "e028"
}
{
id: "loupe"
unicode: "e402"
}
{
id: "low_priority"
unicode: "e16d"
}
{
id: "loyalty"
unicode: "e89a"
}
{
id: "mail"
unicode: "e158"
}
{
id: "mail_outline"
unicode: "e0e1"
}
{
id: "map"
unicode: "e55b"
}
{
id: "markunread"
unicode: "e159"
}
{
id: "markunread_mailbox"
unicode: "e89b"
}
{
id: "memory"
unicode: "e322"
}
{
id: "menu"
unicode: "e5d2"
}
{
id: "merge_type"
unicode: "e252"
}
{
id: "message"
unicode: "e0c9"
}
{
id: "mic"
unicode: "e029"
}
{
id: "mic_none"
unicode: "e02a"
}
{
id: "mic_off"
unicode: "e02b"
}
{
id: "mms"
unicode: "e618"
}
{
id: "mode_comment"
unicode: "e253"
}
{
id: "mode_edit"
unicode: "e254"
}
{
id: "monetization_on"
unicode: "e263"
}
{
id: "money_off"
unicode: "e25c"
}
{
id: "monochrome_photos"
unicode: "e403"
}
{
id: "mood"
unicode: "e7f2"
}
{
id: "mood_bad"
unicode: "e7f3"
}
{
id: "more"
unicode: "e619"
}
{
id: "more_horiz"
unicode: "e5d3"
}
{
id: "more_vert"
unicode: "e5d4"
}
{
id: "motorcycle"
unicode: "e91b"
}
{
id: "mouse"
unicode: "e323"
}
{
id: "move_to_inbox"
unicode: "e168"
}
{
id: "movie"
unicode: "e02c"
}
{
id: "movie_creation"
unicode: "e404"
}
{
id: "movie_filter"
unicode: "e43a"
}
{
id: "multiline_chart"
unicode: "e6df"
}
{
id: "music_note"
unicode: "e405"
}
{
id: "music_video"
unicode: "e063"
}
{
id: "my_location"
unicode: "e55c"
}
{
id: "nature"
unicode: "e406"
}
{
id: "nature_people"
unicode: "e407"
}
{
id: "navigate_before"
unicode: "e408"
}
{
id: "navigate_next"
unicode: "e409"
}
{
id: "navigation"
unicode: "e55d"
}
{
id: "near_me"
unicode: "e569"
}
{
id: "network_cell"
unicode: "e1b9"
}
{
id: "network_check"
unicode: "e640"
}
{
id: "network_locked"
unicode: "e61a"
}
{
id: "network_wifi"
unicode: "e1ba"
}
{
id: "new_releases"
unicode: "e031"
}
{
id: "next_week"
unicode: "e16a"
}
{
id: "nfc"
unicode: "e1bb"
}
{
id: "no_encryption"
unicode: "e641"
}
{
id: "no_sim"
unicode: "e0cc"
}
{
id: "not_interested"
unicode: "e033"
}
{
id: "note"
unicode: "e06f"
}
{
id: "note_add"
unicode: "e89c"
}
{
id: "notifications"
unicode: "e7f4"
}
{
id: "notifications_active"
unicode: "e7f7"
}
{
id: "notifications_none"
unicode: "e7f5"
}
{
id: "notifications_off"
unicode: "e7f6"
}
{
id: "notifications_paused"
unicode: "e7f8"
}
{
id: "offline_pin"
unicode: "e90a"
}
{
id: "ondemand_video"
unicode: "e63a"
}
{
id: "opacity"
unicode: "e91c"
}
{
id: "open_in_browser"
unicode: "e89d"
}
{
id: "open_in_new"
unicode: "e89e"
}
{
id: "open_with"
unicode: "e89f"
}
{
id: "pages"
unicode: "e7f9"
}
{
id: "pageview"
unicode: "e8a0"
}
{
id: "palette"
unicode: "e40a"
}
{
id: "pan_tool"
unicode: "e925"
}
{
id: "panorama"
unicode: "e40b"
}
{
id: "panorama_fish_eye"
unicode: "e40c"
}
{
id: "panorama_horizontal"
unicode: "e40d"
}
{
id: "panorama_vertical"
unicode: "e40e"
}
{
id: "panorama_wide_angle"
unicode: "e40f"
}
{
id: "party_mode"
unicode: "e7fa"
}
{
id: "pause"
unicode: "e034"
}
{
id: "pause_circle_filled"
unicode: "e035"
}
{
id: "pause_circle_outline"
unicode: "e036"
}
{
id: "payment"
unicode: "e8a1"
}
{
id: "people"
unicode: "e7fb"
}
{
id: "people_outline"
unicode: "e7fc"
}
{
id: "perm_camera_mic"
unicode: "e8a2"
}
{
id: "perm_contact_calendar"
unicode: "e8a3"
}
{
id: "perm_data_setting"
unicode: "e8a4"
}
{
id: "perm_device_information"
unicode: "e8a5"
}
{
id: "perm_identity"
unicode: "e8a6"
}
{
id: "perm_media"
unicode: "e8a7"
}
{
id: "perm_phone_msg"
unicode: "e8a8"
}
{
id: "perm_scan_wifi"
unicode: "e8a9"
}
{
id: "person"
unicode: "e7fd"
}
{
id: "person_add"
unicode: "e7fe"
}
{
id: "person_outline"
unicode: "e7ff"
}
{
id: "person_pin"
unicode: "e55a"
}
{
id: "person_pin_circle"
unicode: "e56a"
}
{
id: "personal_video"
unicode: "e63b"
}
{
id: "pets"
unicode: "e91d"
}
{
id: "phone"
unicode: "e0cd"
}
{
id: "phone_android"
unicode: "e324"
}
{
id: "phone_bluetooth_speaker"
unicode: "e61b"
}
{
id: "phone_forwarded"
unicode: "e61c"
}
{
id: "phone_in_talk"
unicode: "e61d"
}
{
id: "phone_iphone"
unicode: "e325"
}
{
id: "phone_locked"
unicode: "e61e"
}
{
id: "phone_missed"
unicode: "e61f"
}
{
id: "phone_paused"
unicode: "e620"
}
{
id: "phonelink"
unicode: "e326"
}
{
id: "phonelink_erase"
unicode: "e0db"
}
{
id: "phonelink_lock"
unicode: "e0dc"
}
{
id: "phonelink_off"
unicode: "e327"
}
{
id: "phonelink_ring"
unicode: "e0dd"
}
{
id: "phonelink_setup"
unicode: "e0de"
}
{
id: "photo"
unicode: "e410"
}
{
id: "photo_album"
unicode: "e411"
}
{
id: "photo_camera"
unicode: "e412"
}
{
id: "photo_filter"
unicode: "e43b"
}
{
id: "photo_library"
unicode: "e413"
}
{
id: "photo_size_select_actual"
unicode: "e432"
}
{
id: "photo_size_select_large"
unicode: "e433"
}
{
id: "photo_size_select_small"
unicode: "e434"
}
{
id: "picture_as_pdf"
unicode: "e415"
}
{
id: "picture_in_picture"
unicode: "e8aa"
}
{
id: "picture_in_picture_alt"
unicode: "e911"
}
{
id: "pie_chart"
unicode: "e6c4"
}
{
id: "pie_chart_outlined"
unicode: "e6c5"
}
{
id: "pin_drop"
unicode: "e55e"
}
{
id: "place"
unicode: "e55f"
}
{
id: "play_arrow"
unicode: "e037"
}
{
id: "play_circle_filled"
unicode: "e038"
}
{
id: "play_circle_outline"
unicode: "e039"
}
{
id: "play_for_work"
unicode: "e906"
}
{
id: "playlist_add"
unicode: "e03b"
}
{
id: "playlist_add_check"
unicode: "e065"
}
{
id: "playlist_play"
unicode: "e05f"
}
{
id: "plus_one"
unicode: "e800"
}
{
id: "poll"
unicode: "e801"
}
{
id: "polymer"
unicode: "e8ab"
}
{
id: "pool"
unicode: "eb48"
}
{
id: "portable_wifi_off"
unicode: "e0ce"
}
{
id: "portrait"
unicode: "e416"
}
{
id: "power"
unicode: "e63c"
}
{
id: "power_input"
unicode: "e336"
}
{
id: "power_settings_new"
unicode: "e8ac"
}
{
id: "pregnant_woman"
unicode: "e91e"
}
{
id: "present_to_all"
unicode: "e0df"
}
{
id: "print"
unicode: "e8ad"
}
{
id: "priority_high"
unicode: "e645"
}
{
id: "public"
unicode: "e80b"
}
{
id: "publish"
unicode: "e255"
}
{
id: "query_builder"
unicode: "e8ae"
}
{
id: "question_answer"
unicode: "e8af"
}
{
id: "queue"
unicode: "e03c"
}
{
id: "queue_music"
unicode: "e03d"
}
{
id: "queue_play_next"
unicode: "e066"
}
{
id: "radio"
unicode: "e03e"
}
{
id: "radio_button_checked"
unicode: "e837"
}
{
id: "radio_button_unchecked"
unicode: "e836"
}
{
id: "rate_review"
unicode: "e560"
}
{
id: "receipt"
unicode: "e8b0"
}
{
id: "recent_actors"
unicode: "e03f"
}
{
id: "record_voice_over"
unicode: "e91f"
}
{
id: "redeem"
unicode: "e8b1"
}
{
id: "redo"
unicode: "e15a"
}
{
id: "refresh"
unicode: "e5d5"
}
{
id: "remove"
unicode: "e15b"
}
{
id: "remove_circle"
unicode: "e15c"
}
{
id: "remove_circle_outline"
unicode: "e15d"
}
{
id: "remove_from_queue"
unicode: "e067"
}
{
id: "remove_red_eye"
unicode: "e417"
}
{
id: "remove_shopping_cart"
unicode: "e928"
}
{
id: "reorder"
unicode: "e8fe"
}
{
id: "repeat"
unicode: "e040"
}
{
id: "repeat_one"
unicode: "e041"
}
{
id: "replay"
unicode: "e042"
}
{
id: "replay_10"
unicode: "e059"
}
{
id: "replay_30"
unicode: "e05a"
}
{
id: "replay_5"
unicode: "e05b"
}
{
id: "reply"
unicode: "e15e"
}
{
id: "reply_all"
unicode: "e15f"
}
{
id: "report"
unicode: "e160"
}
{
id: "report_problem"
unicode: "e8b2"
}
{
id: "restaurant"
unicode: "e56c"
}
{
id: "restaurant_menu"
unicode: "e561"
}
{
id: "restore"
unicode: "e8b3"
}
{
id: "restore_page"
unicode: "e929"
}
{
id: "ring_volume"
unicode: "e0d1"
}
{
id: "room"
unicode: "e8b4"
}
{
id: "room_service"
unicode: "eb49"
}
{
id: "rotate_90_degrees_ccw"
unicode: "e418"
}
{
id: "rotate_left"
unicode: "e419"
}
{
id: "rotate_right"
unicode: "e41a"
}
{
id: "rounded_corner"
unicode: "e920"
}
{
id: "router"
unicode: "e328"
}
{
id: "rowing"
unicode: "e921"
}
{
id: "rss_feed"
unicode: "e0e5"
}
{
id: "rv_hookup"
unicode: "e642"
}
{
id: "satellite"
unicode: "e562"
}
{
id: "save"
unicode: "e161"
}
{
id: "scanner"
unicode: "e329"
}
{
id: "schedule"
unicode: "e8b5"
}
{
id: "school"
unicode: "e80c"
}
{
id: "screen_lock_landscape"
unicode: "e1be"
}
{
id: "screen_lock_portrait"
unicode: "e1bf"
}
{
id: "screen_lock_rotation"
unicode: "e1c0"
}
{
id: "screen_rotation"
unicode: "e1c1"
}
{
id: "screen_share"
unicode: "e0e2"
}
{
id: "sd_card"
unicode: "e623"
}
{
id: "sd_storage"
unicode: "e1c2"
}
{
id: "search"
unicode: "e8b6"
}
{
id: "security"
unicode: "e32a"
}
{
id: "select_all"
unicode: "e162"
}
{
id: "send"
unicode: "e163"
}
{
id: "sentiment_dissatisfied"
unicode: "e811"
}
{
id: "sentiment_neutral"
unicode: "e812"
}
{
id: "sentiment_satisfied"
unicode: "e813"
}
{
id: "sentiment_very_dissatisfied"
unicode: "e814"
}
{
id: "sentiment_very_satisfied"
unicode: "e815"
}
{
id: "settings"
unicode: "e8b8"
}
{
id: "settings_applications"
unicode: "e8b9"
}
{
id: "settings_backup_restore"
unicode: "e8ba"
}
{
id: "settings_bluetooth"
unicode: "e8bb"
}
{
id: "settings_brightness"
unicode: "e8bd"
}
{
id: "settings_cell"
unicode: "e8bc"
}
{
id: "settings_ethernet"
unicode: "e8be"
}
{
id: "settings_input_antenna"
unicode: "e8bf"
}
{
id: "settings_input_component"
unicode: "e8c0"
}
{
id: "settings_input_composite"
unicode: "e8c1"
}
{
id: "settings_input_hdmi"
unicode: "e8c2"
}
{
id: "settings_input_svideo"
unicode: "e8c3"
}
{
id: "settings_overscan"
unicode: "e8c4"
}
{
id: "settings_phone"
unicode: "e8c5"
}
{
id: "settings_power"
unicode: "e8c6"
}
{
id: "settings_remote"
unicode: "e8c7"
}
{
id: "settings_system_daydream"
unicode: "e1c3"
}
{
id: "settings_voice"
unicode: "e8c8"
}
{
id: "share"
unicode: "e80d"
}
{
id: "shop"
unicode: "e8c9"
}
{
id: "shop_two"
unicode: "e8ca"
}
{
id: "shopping_basket"
unicode: "e8cb"
}
{
id: "shopping_cart"
unicode: "e8cc"
}
{
id: "short_text"
unicode: "e261"
}
{
id: "show_chart"
unicode: "e6e1"
}
{
id: "shuffle"
unicode: "e043"
}
{
id: "signal_cellular_4_bar"
unicode: "e1c8"
}
{
id: "signal_cellular_connected_no_internet_4_bar"
unicode: "e1cd"
}
{
id: "signal_cellular_no_sim"
unicode: "e1ce"
}
{
id: "signal_cellular_null"
unicode: "e1cf"
}
{
id: "signal_cellular_off"
unicode: "e1d0"
}
{
id: "signal_wifi_4_bar"
unicode: "e1d8"
}
{
id: "signal_wifi_4_bar_lock"
unicode: "e1d9"
}
{
id: "signal_wifi_off"
unicode: "e1da"
}
{
id: "sim_card"
unicode: "e32b"
}
{
id: "sim_card_alert"
unicode: "e624"
}
{
id: "skip_next"
unicode: "e044"
}
{
id: "skip_previous"
unicode: "e045"
}
{
id: "slideshow"
unicode: "e41b"
}
{
id: "slow_motion_video"
unicode: "e068"
}
{
id: "smartphone"
unicode: "e32c"
}
{
id: "smoke_free"
unicode: "eb4a"
}
{
id: "smoking_rooms"
unicode: "eb4b"
}
{
id: "sms"
unicode: "e625"
}
{
id: "sms_failed"
unicode: "e626"
}
{
id: "snooze"
unicode: "e046"
}
{
id: "sort"
unicode: "e164"
}
{
id: "sort_by_alpha"
unicode: "e053"
}
{
id: "spa"
unicode: "eb4c"
}
{
id: "space_bar"
unicode: "e256"
}
{
id: "speaker"
unicode: "e32d"
}
{
id: "speaker_group"
unicode: "e32e"
}
{
id: "speaker_notes"
unicode: "e8cd"
}
{
id: "speaker_notes_off"
unicode: "e92a"
}
{
id: "speaker_phone"
unicode: "e0d2"
}
{
id: "spellcheck"
unicode: "e8ce"
}
{
id: "star"
unicode: "e838"
}
{
id: "star_border"
unicode: "e83a"
}
{
id: "star_half"
unicode: "e839"
}
{
id: "stars"
unicode: "e8d0"
}
{
id: "stay_current_landscape"
unicode: "e0d3"
}
{
id: "stay_current_portrait"
unicode: "e0d4"
}
{
id: "stay_primary_landscape"
unicode: "e0d5"
}
{
id: "stay_primary_portrait"
unicode: "e0d6"
}
{
id: "stop"
unicode: "e047"
}
{
id: "stop_screen_share"
unicode: "e0e3"
}
{
id: "storage"
unicode: "e1db"
}
{
id: "store"
unicode: "e8d1"
}
{
id: "store_mall_directory"
unicode: "e563"
}
{
id: "straighten"
unicode: "e41c"
}
{
id: "streetview"
unicode: "e56e"
}
{
id: "strikethrough_s"
unicode: "e257"
}
{
id: "style"
unicode: "e41d"
}
{
id: "subdirectory_arrow_left"
unicode: "e5d9"
}
{
id: "subdirectory_arrow_right"
unicode: "e5da"
}
{
id: "subject"
unicode: "e8d2"
}
{
id: "subscriptions"
unicode: "e064"
}
{
id: "subtitles"
unicode: "e048"
}
{
id: "subway"
unicode: "e56f"
}
{
id: "supervisor_account"
unicode: "e8d3"
}
{
id: "surround_sound"
unicode: "e049"
}
{
id: "swap_calls"
unicode: "e0d7"
}
{
id: "swap_horiz"
unicode: "e8d4"
}
{
id: "swap_vert"
unicode: "e8d5"
}
{
id: "swap_vertical_circle"
unicode: "e8d6"
}
{
id: "switch_camera"
unicode: "e41e"
}
{
id: "switch_video"
unicode: "e41f"
}
{
id: "sync"
unicode: "e627"
}
{
id: "sync_disabled"
unicode: "e628"
}
{
id: "sync_problem"
unicode: "e629"
}
{
id: "system_update"
unicode: "e62a"
}
{
id: "system_update_alt"
unicode: "e8d7"
}
{
id: "tab"
unicode: "e8d8"
}
{
id: "tab_unselected"
unicode: "e8d9"
}
{
id: "tablet"
unicode: "e32f"
}
{
id: "tablet_android"
unicode: "e330"
}
{
id: "tablet_mac"
unicode: "e331"
}
{
id: "tag_faces"
unicode: "e420"
}
{
id: "tap_and_play"
unicode: "e62b"
}
{
id: "terrain"
unicode: "e564"
}
{
id: "text_fields"
unicode: "e262"
}
{
id: "text_format"
unicode: "e165"
}
{
id: "textsms"
unicode: "e0d8"
}
{
id: "texture"
unicode: "e421"
}
{
id: "theaters"
unicode: "e8da"
}
{
id: "thumb_down"
unicode: "e8db"
}
{
id: "thumb_up"
unicode: "e8dc"
}
{
id: "thumbs_up_down"
unicode: "e8dd"
}
{
id: "time_to_leave"
unicode: "e62c"
}
{
id: "timelapse"
unicode: "e422"
}
{
id: "timeline"
unicode: "e922"
}
{
id: "timer"
unicode: "e425"
}
{
id: "timer_10"
unicode: "e423"
}
{
id: "timer_3"
unicode: "e424"
}
{
id: "timer_off"
unicode: "e426"
}
{
id: "title"
unicode: "e264"
}
{
id: "toc"
unicode: "e8de"
}
{
id: "today"
unicode: "e8df"
}
{
id: "toll"
unicode: "e8e0"
}
{
id: "tonality"
unicode: "e427"
}
{
id: "touch_app"
unicode: "e913"
}
{
id: "toys"
unicode: "e332"
}
{
id: "track_changes"
unicode: "e8e1"
}
{
id: "traffic"
unicode: "e565"
}
{
id: "train"
unicode: "e570"
}
{
id: "tram"
unicode: "e571"
}
{
id: "transfer_within_a_station"
unicode: "e572"
}
{
id: "transform"
unicode: "e428"
}
{
id: "translate"
unicode: "e8e2"
}
{
id: "trending_down"
unicode: "e8e3"
}
{
id: "trending_flat"
unicode: "e8e4"
}
{
id: "trending_up"
unicode: "e8e5"
}
{
id: "tune"
unicode: "e429"
}
{
id: "turned_in"
unicode: "e8e6"
}
{
id: "turned_in_not"
unicode: "e8e7"
}
{
id: "tv"
unicode: "e333"
}
{
id: "unarchive"
unicode: "e169"
}
{
id: "undo"
unicode: "e166"
}
{
id: "unfold_less"
unicode: "e5d6"
}
{
id: "unfold_more"
unicode: "e5d7"
}
{
id: "update"
unicode: "e923"
}
{
id: "usb"
unicode: "e1e0"
}
{
id: "verified_user"
unicode: "e8e8"
}
{
id: "vertical_align_bottom"
unicode: "e258"
}
{
id: "vertical_align_center"
unicode: "e259"
}
{
id: "vertical_align_top"
unicode: "e25a"
}
{
id: "vibration"
unicode: "e62d"
}
{
id: "video_call"
unicode: "e070"
}
{
id: "video_label"
unicode: "e071"
}
{
id: "video_library"
unicode: "e04a"
}
{
id: "videocam"
unicode: "e04b"
}
{
id: "videocam_off"
unicode: "e04c"
}
{
id: "videogame_asset"
unicode: "e338"
}
{
id: "view_agenda"
unicode: "e8e9"
}
{
id: "view_array"
unicode: "e8ea"
}
{
id: "view_carousel"
unicode: "e8eb"
}
{
id: "view_column"
unicode: "e8ec"
}
{
id: "view_comfy"
unicode: "e42a"
}
{
id: "view_compact"
unicode: "e42b"
}
{
id: "view_day"
unicode: "e8ed"
}
{
id: "view_headline"
unicode: "e8ee"
}
{
id: "view_list"
unicode: "e8ef"
}
{
id: "view_module"
unicode: "e8f0"
}
{
id: "view_quilt"
unicode: "e8f1"
}
{
id: "view_stream"
unicode: "e8f2"
}
{
id: "view_week"
unicode: "e8f3"
}
{
id: "vignette"
unicode: "e435"
}
{
id: "visibility"
unicode: "e8f4"
}
{
id: "visibility_off"
unicode: "e8f5"
}
{
id: "voice_chat"
unicode: "e62e"
}
{
id: "voicemail"
unicode: "e0d9"
}
{
id: "volume_down"
unicode: "e04d"
}
{
id: "volume_mute"
unicode: "e04e"
}
{
id: "volume_off"
unicode: "e04f"
}
{
id: "volume_up"
unicode: "e050"
}
{
id: "vpn_key"
unicode: "e0da"
}
{
id: "vpn_lock"
unicode: "e62f"
}
{
id: "wallpaper"
unicode: "e1bc"
}
{
id: "warning"
unicode: "e002"
}
{
id: "watch"
unicode: "e334"
}
{
id: "watch_later"
unicode: "e924"
}
{
id: "wb_auto"
unicode: "e42c"
}
{
id: "wb_cloudy"
unicode: "e42d"
}
{
id: "wb_incandescent"
unicode: "e42e"
}
{
id: "wb_iridescent"
unicode: "e436"
}
{
id: "wb_sunny"
unicode: "e430"
}
{
id: "wc"
unicode: "e63d"
}
{
id: "web"
unicode: "e051"
}
{
id: "web_asset"
unicode: "e069"
}
{
id: "weekend"
unicode: "e16b"
}
{
id: "whatshot"
unicode: "e80e"
}
{
id: "widgets"
unicode: "e1bd"
}
{
id: "wifi"
unicode: "e63e"
}
{
id: "wifi_lock"
unicode: "e1e1"
}
{
id: "wifi_tethering"
unicode: "e1e2"
}
{
id: "work"
unicode: "e8f9"
}
{
id: "wrap_text"
unicode: "e25b"
}
{
id: "youtube_searched_for"
unicode: "e8fa"
}
{
id: "zoom_in"
unicode: "e8ff"
}
{
id: "zoom_out"
unicode: "e900"
}
{
id: "zoom_out_map"
unicode: "e56b"
}
] |
[
{
"context": "ler\"\nPAGES: \"Sayfalar\"\nPOSTS: \"Yazılar\"\nAUTHORS: \"Yazarlar\"\nSEARCH: \"Ara\"\nSEARCH_START: \"Type a keyword\"\nSOC",
"end": 357,
"score": 0.9980228543281555,
"start": 349,
"tag": "NAME",
"value": "Yazarlar"
}
] | src/i18n/tr.cson | caiocrd/politicaemfoco-ionic | 772 | PULL_TO_REFRESH: "Yenilemek için çekin!"
RETRY: "Tekrar Dene"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Geri"
ERROR: "Bir şeyler ters gitti, lütfen tekrar deneyin."
ATTEMPT_TO_CONNECT: "Tekrar Bağlanılıyor"
OK: "Ok"
YES: "Evet"
NO: "Hayır"
EMPTY_LIST: "Burada bir şey yok!"
MENU: "Menü"
TAGS: "Etiketler"
PAGES: "Sayfalar"
POSTS: "Yazılar"
AUTHORS: "Yazarlar"
SEARCH: "Ara"
SEARCH_START: "Type a keyword"
SOCIAL_NETWORKS: "Sosyal Medya"
CATEGORIES: "Kategoriler"
SETTINGS: "Ayarlar"
ZOOM: "Zoom"
FEATURED: "Öne çıkan"
OPEN_IN_BROWSER: "Tarayıcıda aç"
ABOUT: "Hakkımızda"
COMMENTS: "Yorumlar"
CUSTOM_POSTS: "Özel Gönderiler"
CUSTOM_TAXO: "Özel Taksonomi"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push Bildirimleri"
PUSH_NOTIF_TITLE: "Yeni Yazı Yayımlandı!"
PUSH_NOTIF_TEXT: "Yeni Yazı/Sayfa: '{{postTitle}}' yayımlandı, açmak ister misiniz?"
BOOKMARKS: "Favoriler"
BOOKMARKS_EMPTY: "Henüz favori yazı yok!"
BOOKMARK_ADDED: "Favorilere eklendi!"
BOOKMARK_REMOVED: "Favorilerden kaldırıldı!"
CACHE_CLEAR: "Clear cache"
CACHE_CLEAR_PROMPT: "This cannot be undone!"
CACHE_CLEARED: "Cache cleared"
TITLE_TAGS: "Etiketler"
TITLE_TAG: "Etiket: {{name}}"
TITLE_CATEGORIES: "Kategoriler"
TITLE_CATEGORY: "Kategori: {{name}}"
TITLE_HOME: "Ana sayfa"
TITLE_SEARCH: "Ara"
TITLE_PAGES: "Sayfalar"
TITLE_POSTS: "Yazılar"
TITLE_USERS: "Yazarlar"
TITLE_USER: "Yazar"
TITLE_USER_POSTS: "Yazar: {{name}}"
SHARE_SUCCESS: "Paylaşıldı!"
SHARE_ERROR: "Sharing failed" | 209646 | PULL_TO_REFRESH: "Yenilemek için çekin!"
RETRY: "Tekrar Dene"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Geri"
ERROR: "Bir şeyler ters gitti, lütfen tekrar deneyin."
ATTEMPT_TO_CONNECT: "Tekrar Bağlanılıyor"
OK: "Ok"
YES: "Evet"
NO: "Hayır"
EMPTY_LIST: "Burada bir şey yok!"
MENU: "Menü"
TAGS: "Etiketler"
PAGES: "Sayfalar"
POSTS: "Yazılar"
AUTHORS: "<NAME>"
SEARCH: "Ara"
SEARCH_START: "Type a keyword"
SOCIAL_NETWORKS: "Sosyal Medya"
CATEGORIES: "Kategoriler"
SETTINGS: "Ayarlar"
ZOOM: "Zoom"
FEATURED: "Öne çıkan"
OPEN_IN_BROWSER: "Tarayıcıda aç"
ABOUT: "Hakkımızda"
COMMENTS: "Yorumlar"
CUSTOM_POSTS: "Özel Gönderiler"
CUSTOM_TAXO: "Özel Taksonomi"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push Bildirimleri"
PUSH_NOTIF_TITLE: "Yeni Yazı Yayımlandı!"
PUSH_NOTIF_TEXT: "Yeni Yazı/Sayfa: '{{postTitle}}' yayımlandı, açmak ister misiniz?"
BOOKMARKS: "Favoriler"
BOOKMARKS_EMPTY: "Henüz favori yazı yok!"
BOOKMARK_ADDED: "Favorilere eklendi!"
BOOKMARK_REMOVED: "Favorilerden kaldırıldı!"
CACHE_CLEAR: "Clear cache"
CACHE_CLEAR_PROMPT: "This cannot be undone!"
CACHE_CLEARED: "Cache cleared"
TITLE_TAGS: "Etiketler"
TITLE_TAG: "Etiket: {{name}}"
TITLE_CATEGORIES: "Kategoriler"
TITLE_CATEGORY: "Kategori: {{name}}"
TITLE_HOME: "Ana sayfa"
TITLE_SEARCH: "Ara"
TITLE_PAGES: "Sayfalar"
TITLE_POSTS: "Yazılar"
TITLE_USERS: "Yazarlar"
TITLE_USER: "Yazar"
TITLE_USER_POSTS: "Yazar: {{name}}"
SHARE_SUCCESS: "Paylaşıldı!"
SHARE_ERROR: "Sharing failed" | true | PULL_TO_REFRESH: "Yenilemek için çekin!"
RETRY: "Tekrar Dene"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Geri"
ERROR: "Bir şeyler ters gitti, lütfen tekrar deneyin."
ATTEMPT_TO_CONNECT: "Tekrar Bağlanılıyor"
OK: "Ok"
YES: "Evet"
NO: "Hayır"
EMPTY_LIST: "Burada bir şey yok!"
MENU: "Menü"
TAGS: "Etiketler"
PAGES: "Sayfalar"
POSTS: "Yazılar"
AUTHORS: "PI:NAME:<NAME>END_PI"
SEARCH: "Ara"
SEARCH_START: "Type a keyword"
SOCIAL_NETWORKS: "Sosyal Medya"
CATEGORIES: "Kategoriler"
SETTINGS: "Ayarlar"
ZOOM: "Zoom"
FEATURED: "Öne çıkan"
OPEN_IN_BROWSER: "Tarayıcıda aç"
ABOUT: "Hakkımızda"
COMMENTS: "Yorumlar"
CUSTOM_POSTS: "Özel Gönderiler"
CUSTOM_TAXO: "Özel Taksonomi"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push Bildirimleri"
PUSH_NOTIF_TITLE: "Yeni Yazı Yayımlandı!"
PUSH_NOTIF_TEXT: "Yeni Yazı/Sayfa: '{{postTitle}}' yayımlandı, açmak ister misiniz?"
BOOKMARKS: "Favoriler"
BOOKMARKS_EMPTY: "Henüz favori yazı yok!"
BOOKMARK_ADDED: "Favorilere eklendi!"
BOOKMARK_REMOVED: "Favorilerden kaldırıldı!"
CACHE_CLEAR: "Clear cache"
CACHE_CLEAR_PROMPT: "This cannot be undone!"
CACHE_CLEARED: "Cache cleared"
TITLE_TAGS: "Etiketler"
TITLE_TAG: "Etiket: {{name}}"
TITLE_CATEGORIES: "Kategoriler"
TITLE_CATEGORY: "Kategori: {{name}}"
TITLE_HOME: "Ana sayfa"
TITLE_SEARCH: "Ara"
TITLE_PAGES: "Sayfalar"
TITLE_POSTS: "Yazılar"
TITLE_USERS: "Yazarlar"
TITLE_USER: "Yazar"
TITLE_USER_POSTS: "Yazar: {{name}}"
SHARE_SUCCESS: "Paylaşıldı!"
SHARE_ERROR: "Sharing failed" |
[
{
"context": "ersion 1.0.0\n@file Ajax.js\n@author Welington Sampaio (http://welington.zaez.net/)\n@contact http://",
"end": 145,
"score": 0.9999040961265564,
"start": 128,
"tag": "NAME",
"value": "Welington Sampaio"
},
{
"context": "n.zaez.net/site/contato\n\n@co... | vendor/assets/javascripts/lol_framework/Ajax.coffee | welingtonsampaio/lol-framework | 1 | ###
@summary Lol Framework
@description Framework of RIAs applications
@version 1.0.0
@file Ajax.js
@author Welington Sampaio (http://welington.zaez.net/)
@contact http://welington.zaez.net/site/contato
@copyright Copyright 2012 Welington Sampaio, all rights reserved.
This source file is free software, under the license MIT, available at:
http://lolframework.zaez.net/license
This source file 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 license files for details.
For details please refer to: http://welington.zaez.net
###
###
Create a new instance of Ajax.
@classDescription This class creates a new Ajax.
@param {Object} Receives configuration to create the Ajax, @see Lol.ajax.defaults
@return {Ajax} Returns a new Ajax.
@type {Object}
@example
*-* Manual Configuration *-*
var lol_ajax = new Lol.Ajax({
autoExecute: true,
useLoader : true,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url : 'http://www.google.com/',
method : 'GET',
data : {},
dataType : 'html',
callbacks: {
beforeSend: function(jqXHR, settings){},
complete: function(jqXHR, textStatus){},
error: function(jqXHR, textStatus, errorThrown){},
success: function(data, textStatus, jqXHR){}
}
});
###
class Lol.Ajax extends Lol.Core
# declaration of variables
debugPrefix : 'Lol_Ajax'
namespace : '.ajax'
# the methods
constructor: (args={})->
return false unless @verifyJQuery()
@settings = jQuery.extend true, {}, Lol.ajax.defaults, args
@generateId()
@execute() if @settings.autoExecute
###
Get all the configuration data
sent and configures sending
@see http://api.jquery.com/jQuery.ajax/
###
execute: ->
@debug 'Executing the ajax requisition', @
if not @settings.url or not @settings.callbacks.error or not @settings.callbacks.success
throw 'Fields requireds not setting'
_this = @
Lol.Loader.show() if @settings.userLoader
jQuery.ajax
contentType: @settings.contentType
url : @settings.url
type : @settings.method
data : jQuery.param @settings.data
dataType : @settings.dataType
beforeSend : _this.settings.callbacks.beforeSend
complete : _this.settings.callbacks.complete
error : (jqXHR, textStatus, errorThrown)->
Lol.Loader.remove()
_this.settings.callbacks.error(jqXHR, textStatus, errorThrown)
success : (data, textStatus, jqXHR)->
Lol.Loader.remove()
_this.settings.callbacks.success(data, textStatus, jqXHR)
###
Set a new ContentType
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setContentType: (value)-> @settings.contentType = value
###
Indicates whether to lock the screen with a loader
@param {Boolean}
@return {Boolean}
###
setUseLoader: (value)-> @settings.useLoader = value
###
Set a new Url
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setUrl: (value)-> @settings.url = value
###
Set a new Method
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setMethod: (value)-> @settings.method = value
###
Set a new Data content
@see http://api.jquery.com/jQuery.ajax/
@param {Object}
@return {Object}
###
setData: (value)-> @settings.data = value
###
Set a new DataType
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setDataType: (value)-> @settings.dataType = value
###
Contains the definitions of standards Lol.Ajax
@type {Object}
###
Lol.ajax =
defaults:
###
Indicates whether the object should
be executed at the end of its creation
@type {Boolean}
###
autoExecute: true
###
Indicates whether the object should use
a loader to stop, until the completion
of the request
@type {Boolean}
###
useLoader : true
###
Indicates the content type of the request
@type {String}
###
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
###
Indicates the url of the request
@type {String}
###
url : null
###
Indicates the method of the request
options : GET | POST | PUT | DELETE
@type {String}
###
method : 'GET'
###
Indicates the content of the request
@type {Object}
###
data : {}
###
Indicates the type of expected return
after the completion of request
@type {String}
###
dataType : 'json'
###
Callbacks run through the requisition
@see http://api.jquery.com/jQuery.ajax/
###
callbacks:
beforeSend: (jqXHR, settings)->
complete: (jqXHR, textStatus)->
error: (jqXHR, textStatus, errorThrown)->
success: (data, textStatus, jqXHR)->
# if is rails application and using csrf-token
jQuery ->
jQuery(document).ajaxSend (e, xhr, options)->
token = $("meta[name='csrf-token']").attr "content"
xhr.setRequestHeader("X-CSRF-Token", token) | 138938 | ###
@summary Lol Framework
@description Framework of RIAs applications
@version 1.0.0
@file Ajax.js
@author <NAME> (http://welington.zaez.net/)
@contact http://welington.zaez.net/site/contato
@copyright Copyright 2012 <NAME>, all rights reserved.
This source file is free software, under the license MIT, available at:
http://lolframework.zaez.net/license
This source file 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 license files for details.
For details please refer to: http://welington.zaez.net
###
###
Create a new instance of Ajax.
@classDescription This class creates a new Ajax.
@param {Object} Receives configuration to create the Ajax, @see Lol.ajax.defaults
@return {Ajax} Returns a new Ajax.
@type {Object}
@example
*-* Manual Configuration *-*
var lol_ajax = new Lol.Ajax({
autoExecute: true,
useLoader : true,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url : 'http://www.google.com/',
method : 'GET',
data : {},
dataType : 'html',
callbacks: {
beforeSend: function(jqXHR, settings){},
complete: function(jqXHR, textStatus){},
error: function(jqXHR, textStatus, errorThrown){},
success: function(data, textStatus, jqXHR){}
}
});
###
class Lol.Ajax extends Lol.Core
# declaration of variables
debugPrefix : 'Lol_Ajax'
namespace : '.ajax'
# the methods
constructor: (args={})->
return false unless @verifyJQuery()
@settings = jQuery.extend true, {}, Lol.ajax.defaults, args
@generateId()
@execute() if @settings.autoExecute
###
Get all the configuration data
sent and configures sending
@see http://api.jquery.com/jQuery.ajax/
###
execute: ->
@debug 'Executing the ajax requisition', @
if not @settings.url or not @settings.callbacks.error or not @settings.callbacks.success
throw 'Fields requireds not setting'
_this = @
Lol.Loader.show() if @settings.userLoader
jQuery.ajax
contentType: @settings.contentType
url : @settings.url
type : @settings.method
data : jQuery.param @settings.data
dataType : @settings.dataType
beforeSend : _this.settings.callbacks.beforeSend
complete : _this.settings.callbacks.complete
error : (jqXHR, textStatus, errorThrown)->
Lol.Loader.remove()
_this.settings.callbacks.error(jqXHR, textStatus, errorThrown)
success : (data, textStatus, jqXHR)->
Lol.Loader.remove()
_this.settings.callbacks.success(data, textStatus, jqXHR)
###
Set a new ContentType
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setContentType: (value)-> @settings.contentType = value
###
Indicates whether to lock the screen with a loader
@param {Boolean}
@return {Boolean}
###
setUseLoader: (value)-> @settings.useLoader = value
###
Set a new Url
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setUrl: (value)-> @settings.url = value
###
Set a new Method
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setMethod: (value)-> @settings.method = value
###
Set a new Data content
@see http://api.jquery.com/jQuery.ajax/
@param {Object}
@return {Object}
###
setData: (value)-> @settings.data = value
###
Set a new DataType
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setDataType: (value)-> @settings.dataType = value
###
Contains the definitions of standards Lol.Ajax
@type {Object}
###
Lol.ajax =
defaults:
###
Indicates whether the object should
be executed at the end of its creation
@type {Boolean}
###
autoExecute: true
###
Indicates whether the object should use
a loader to stop, until the completion
of the request
@type {Boolean}
###
useLoader : true
###
Indicates the content type of the request
@type {String}
###
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
###
Indicates the url of the request
@type {String}
###
url : null
###
Indicates the method of the request
options : GET | POST | PUT | DELETE
@type {String}
###
method : 'GET'
###
Indicates the content of the request
@type {Object}
###
data : {}
###
Indicates the type of expected return
after the completion of request
@type {String}
###
dataType : 'json'
###
Callbacks run through the requisition
@see http://api.jquery.com/jQuery.ajax/
###
callbacks:
beforeSend: (jqXHR, settings)->
complete: (jqXHR, textStatus)->
error: (jqXHR, textStatus, errorThrown)->
success: (data, textStatus, jqXHR)->
# if is rails application and using csrf-token
jQuery ->
jQuery(document).ajaxSend (e, xhr, options)->
token = $("meta[name='csrf-token']").attr "content"
xhr.setRequestHeader("X-CSRF-Token", token) | true | ###
@summary Lol Framework
@description Framework of RIAs applications
@version 1.0.0
@file Ajax.js
@author PI:NAME:<NAME>END_PI (http://welington.zaez.net/)
@contact http://welington.zaez.net/site/contato
@copyright Copyright 2012 PI:NAME:<NAME>END_PI, all rights reserved.
This source file is free software, under the license MIT, available at:
http://lolframework.zaez.net/license
This source file 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 license files for details.
For details please refer to: http://welington.zaez.net
###
###
Create a new instance of Ajax.
@classDescription This class creates a new Ajax.
@param {Object} Receives configuration to create the Ajax, @see Lol.ajax.defaults
@return {Ajax} Returns a new Ajax.
@type {Object}
@example
*-* Manual Configuration *-*
var lol_ajax = new Lol.Ajax({
autoExecute: true,
useLoader : true,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url : 'http://www.google.com/',
method : 'GET',
data : {},
dataType : 'html',
callbacks: {
beforeSend: function(jqXHR, settings){},
complete: function(jqXHR, textStatus){},
error: function(jqXHR, textStatus, errorThrown){},
success: function(data, textStatus, jqXHR){}
}
});
###
class Lol.Ajax extends Lol.Core
# declaration of variables
debugPrefix : 'Lol_Ajax'
namespace : '.ajax'
# the methods
constructor: (args={})->
return false unless @verifyJQuery()
@settings = jQuery.extend true, {}, Lol.ajax.defaults, args
@generateId()
@execute() if @settings.autoExecute
###
Get all the configuration data
sent and configures sending
@see http://api.jquery.com/jQuery.ajax/
###
execute: ->
@debug 'Executing the ajax requisition', @
if not @settings.url or not @settings.callbacks.error or not @settings.callbacks.success
throw 'Fields requireds not setting'
_this = @
Lol.Loader.show() if @settings.userLoader
jQuery.ajax
contentType: @settings.contentType
url : @settings.url
type : @settings.method
data : jQuery.param @settings.data
dataType : @settings.dataType
beforeSend : _this.settings.callbacks.beforeSend
complete : _this.settings.callbacks.complete
error : (jqXHR, textStatus, errorThrown)->
Lol.Loader.remove()
_this.settings.callbacks.error(jqXHR, textStatus, errorThrown)
success : (data, textStatus, jqXHR)->
Lol.Loader.remove()
_this.settings.callbacks.success(data, textStatus, jqXHR)
###
Set a new ContentType
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setContentType: (value)-> @settings.contentType = value
###
Indicates whether to lock the screen with a loader
@param {Boolean}
@return {Boolean}
###
setUseLoader: (value)-> @settings.useLoader = value
###
Set a new Url
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setUrl: (value)-> @settings.url = value
###
Set a new Method
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setMethod: (value)-> @settings.method = value
###
Set a new Data content
@see http://api.jquery.com/jQuery.ajax/
@param {Object}
@return {Object}
###
setData: (value)-> @settings.data = value
###
Set a new DataType
@see http://api.jquery.com/jQuery.ajax/
@param {String}
@return {String}
###
setDataType: (value)-> @settings.dataType = value
###
Contains the definitions of standards Lol.Ajax
@type {Object}
###
Lol.ajax =
defaults:
###
Indicates whether the object should
be executed at the end of its creation
@type {Boolean}
###
autoExecute: true
###
Indicates whether the object should use
a loader to stop, until the completion
of the request
@type {Boolean}
###
useLoader : true
###
Indicates the content type of the request
@type {String}
###
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
###
Indicates the url of the request
@type {String}
###
url : null
###
Indicates the method of the request
options : GET | POST | PUT | DELETE
@type {String}
###
method : 'GET'
###
Indicates the content of the request
@type {Object}
###
data : {}
###
Indicates the type of expected return
after the completion of request
@type {String}
###
dataType : 'json'
###
Callbacks run through the requisition
@see http://api.jquery.com/jQuery.ajax/
###
callbacks:
beforeSend: (jqXHR, settings)->
complete: (jqXHR, textStatus)->
error: (jqXHR, textStatus, errorThrown)->
success: (data, textStatus, jqXHR)->
# if is rails application and using csrf-token
jQuery ->
jQuery(document).ajaxSend (e, xhr, options)->
token = $("meta[name='csrf-token']").attr "content"
xhr.setRequestHeader("X-CSRF-Token", token) |
[
{
"context": "module.exports =\n appToken: 'your application token'\n apiHost: 'https://jianliao.com'\n",
"end": 52,
"score": 0.9897672533988953,
"start": 30,
"tag": "PASSWORD",
"value": "your application token"
}
] | src/config.coffee | jianliaoim/talk-node-sdk | 4 | module.exports =
appToken: 'your application token'
apiHost: 'https://jianliao.com'
| 104155 | module.exports =
appToken: '<PASSWORD>'
apiHost: 'https://jianliao.com'
| true | module.exports =
appToken: 'PI:PASSWORD:<PASSWORD>END_PI'
apiHost: 'https://jianliao.com'
|
[
{
"context": "# ## Widget fillgauge\n# @author Alex Suslov <suslov@me.com>\n'use strict'\nangular.module('widg",
"end": 43,
"score": 0.9997655749320984,
"start": 32,
"tag": "NAME",
"value": "Alex Suslov"
},
{
"context": "# ## Widget fillgauge\n# @author Alex Suslov <suslov@me.com>\n'... | index.coffee | alexsuslov/im-fillgauge | 0 | # ## Widget fillgauge
# @author Alex Suslov <suslov@me.com>
'use strict'
angular.module('widgets')
.directive 'fillgauge', ->
# ### template
template = '''
<div ng-class="'{{cfg.class2}}'" style="{{cfg.style2}}">
{{cfg.descr}}
</div>
<div ng-class="'{{cfg.class3}}'" style="{{cfg.style3}}">
<burble id='fg-{{cfg.id}}' value='{{percentage}}' ng-model='cfg' ></burble>
</div>'''
# console.log 'template', template
# ### link
link = (scope) ->
# widget model
widget = scope.ngModel
scope.cfg = scope.ngModel.data()
scope.percentage = scope.cfg.value.status if scope.cfg?.value?.status
# ### controller
controller = ($scope) ->
widget = $scope.ngModel
widget.on 'change', ->
link $scope
$scope.$apply()
directive =
restrict: 'E'
priority: 10
template: template
controller: controller
link: link
| 175805 | # ## Widget fillgauge
# @author <NAME> <<EMAIL>>
'use strict'
angular.module('widgets')
.directive 'fillgauge', ->
# ### template
template = '''
<div ng-class="'{{cfg.class2}}'" style="{{cfg.style2}}">
{{cfg.descr}}
</div>
<div ng-class="'{{cfg.class3}}'" style="{{cfg.style3}}">
<burble id='fg-{{cfg.id}}' value='{{percentage}}' ng-model='cfg' ></burble>
</div>'''
# console.log 'template', template
# ### link
link = (scope) ->
# widget model
widget = scope.ngModel
scope.cfg = scope.ngModel.data()
scope.percentage = scope.cfg.value.status if scope.cfg?.value?.status
# ### controller
controller = ($scope) ->
widget = $scope.ngModel
widget.on 'change', ->
link $scope
$scope.$apply()
directive =
restrict: 'E'
priority: 10
template: template
controller: controller
link: link
| true | # ## Widget fillgauge
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
'use strict'
angular.module('widgets')
.directive 'fillgauge', ->
# ### template
template = '''
<div ng-class="'{{cfg.class2}}'" style="{{cfg.style2}}">
{{cfg.descr}}
</div>
<div ng-class="'{{cfg.class3}}'" style="{{cfg.style3}}">
<burble id='fg-{{cfg.id}}' value='{{percentage}}' ng-model='cfg' ></burble>
</div>'''
# console.log 'template', template
# ### link
link = (scope) ->
# widget model
widget = scope.ngModel
scope.cfg = scope.ngModel.data()
scope.percentage = scope.cfg.value.status if scope.cfg?.value?.status
# ### controller
controller = ($scope) ->
widget = $scope.ngModel
widget.on 'change', ->
link $scope
$scope.$apply()
directive =
restrict: 'E'
priority: 10
template: template
controller: controller
link: link
|
[
{
"context": "5,3,7,5]\nUPLOAD_PATH = \"http://res.cloudinary.com/test123/image/upload\"\nCache = cloudinary.Cache\n\nsrcRegExp",
"end": 347,
"score": 0.9799435138702393,
"start": 340,
"tag": "USERNAME",
"value": "test123"
},
{
"context": "mmonTrans =\n effect: 'sepia',\n cloud... | test/image_spec.coffee | optune/cloudinary | 0 | expect = require('expect.js')
cloudinary = require('../cloudinary')
utils = cloudinary.utils
helper = require("./spechelper")
sharedContext = helper.sharedContext
sharedExamples = helper.sharedExamples
includeContext = helper.includeContext
extend = require('lodash/extend')
BREAKPOINTS = [5,3,7,5]
UPLOAD_PATH = "http://res.cloudinary.com/test123/image/upload"
Cache = cloudinary.Cache
srcRegExp = (name, path)->
RegExp("#{name}=[\"']#{UPLOAD_PATH}/#{path}[\"']".replace("/", "\/"))
describe 'image helper', ->
commonTrans =
effect: 'sepia',
cloud_name: 'test123',
client_hints: false
commonTransformationStr = 'e_sepia'
customAttributes = custom_attr1: 'custom_value1', custom_attr2: 'custom_value2'
beforeEach ->
cloudinary.config(true) # Reset
cloudinary.config(cloud_name: "test123", api_secret: "1234")
it "should generate image", ->
expect(cloudinary.image("hello", format: "png")).to.eql("<img src='#{UPLOAD_PATH}/hello.png' />")
it "should accept scale crop and pass width/height to image tag ", ->
expect(cloudinary.image("hello", format: "png", crop: 'scale', width: 100, height: 100)).to.eql("<img src='#{UPLOAD_PATH}/c_scale,h_100,w_100/hello.png' height='100' width='100'/>")
it "should add responsive width transformation", ->
expect(cloudinary.image("hello", format: "png", responsive_width: true)).to.eql("<img class='cld-responsive' data-src='#{UPLOAD_PATH}/c_limit,w_auto/hello.png'/>")
it "should support width auto transformation", ->
expect(cloudinary.image("hello", format: "png", width: "auto", crop: "limit")).to.eql("<img class='cld-responsive' data-src='#{UPLOAD_PATH}/c_limit,w_auto/hello.png'/>")
it "should support dpr auto transformation", ->
expect(cloudinary.image("hello", format: "png", dpr: "auto")).to.eql("<img class='cld-hidpi' data-src='#{UPLOAD_PATH}/dpr_auto/hello.png'/>")
it "should support e_art:incognito transformation", ->
expect(cloudinary.image("hello", format: "png", effect: "art:incognito")).to.eql("<img src='#{UPLOAD_PATH}/e_art:incognito/hello.png' />")
it "should not mutate the options argument", ->
options =
fetch_format: 'auto'
flags: 'progressive'
cloudinary.image('hello', options)
expect(options.fetch_format).to.eql('auto')
expect(options.flags).to.eql('progressive')
it "Should consume custom attributes from 'attributes' key", ->
tag = cloudinary.image('sample.jpg', utils.extend({attributes: customAttributes}, commonTrans))
Object.entries(customAttributes).forEach ([key, value])->
expect(tag).to.contain("#{key}='#{value}'")
it "Should consume custom attributes as is from options", ->
options = utils.extend({}, commonTrans, customAttributes)
tag = cloudinary.image('sample.jpg', options)
Object.entries(customAttributes).forEach ([key, value])->
expect(tag).to.contain("#{key}='#{value}'")
it "Attributes from 'attributes' dict should override existing attributes", ->
options = utils.extend({}, commonTrans, {alt: "original alt", attributes: {alt: "updated alt"}})
tag = cloudinary.image('sample.jpg', options)
expect(tag).to.contain("alt='updated alt'")
sharedExamples "client_hints", (options)->
it "should not use data-src or set responsive class", ->
tag = cloudinary.image('sample.jpg', options)
expect(tag).to.match( /<img.*>/)
expect(tag).not.to.match(/<.*class.*>/)
expect(tag).not.to.match(/\bdata-src\b/)
expect(tag).to.match( srcRegExp("src", "c_scale,dpr_auto,w_auto/sample.jpg"))
it "should override responsive", ->
cloudinary.config(responsive: true)
tag = cloudinary.image('sample.jpg', options)
expect(tag).to.match( /<img.*>/)
expect(tag).not.to.match(/<.*class.*>/)
expect(tag).not.to.match(/\bdata-src\b/)
expect(tag).to.match( srcRegExp("src", "c_scale,dpr_auto,w_auto/sample.jpg"))
describe ":client_hints", ->
describe "as option", ->
includeContext "client_hints", {dpr: "auto", cloud_name: "test123", width: "auto", crop: "scale", client_hints: true}
describe "as global configuration", ->
beforeEach ->
cloudinary.config().client_hints = true
includeContext "client_hints", {dpr: "auto", cloud_name: "test123", width: "auto", crop: "scale"}
describe "false", ->
it "should use normal responsive behaviour", ->
cloudinary.config().responsive = true
tag = cloudinary.image('sample.jpg', {width: "auto", crop: "scale", cloud_name: "test123", client_hints: false})
expect(tag).to.match( /<img.*>/)
expect(tag).to.match( /class=["']cld-responsive["']/)
expect(tag).to.match( srcRegExp("data-src", "c_scale,w_auto/sample.jpg"))
describe "width", ->
it "supports auto width", ->
tag = cloudinary.image( 'sample.jpg', {crop: "scale", dpr: "auto", cloud_name: "test123", width: "auto:breakpoints", client_hints: true})
expect(tag).to.match( srcRegExp("src", "c_scale,dpr_auto,w_auto:breakpoints/sample.jpg"))
describe "srcset", ->
lastBreakpoint = 399
breakpoints = [100, 200, 300, lastBreakpoint]
before ->
helper.setupCache()
it "Should create srcset attribute with provided breakpoints", ->
tagWithBreakpoints = cloudinary.image('sample.jpg', utils.extend({}, commonTrans, srcset: breakpoints: breakpoints ) )
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', breakpoints)
expect(tagWithBreakpoints).to.eql(expected)
it "Support srcset attribute defined by min width max width and max images", ->
tag = cloudinary.image 'sample.jpg', extend({}, commonTrans,
srcset:
min_width: breakpoints[0],
max_width: lastBreakpoint,
max_images: breakpoints.length
)
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', breakpoints)
expect(tag).to.eql(expected)
it "should support a single srcset image", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset: {
min_width: breakpoints[0],
max_width: lastBreakpoint,
max_images: 1
}))
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', [lastBreakpoint])
expect(tag).to.eql(expected)
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset: breakpoints: [lastBreakpoint]
))
expect(tag).to.eql(expected)
it "Should support custom transformation for srcset items", ->
custom = {transformation: {crop: "crop", width: 10, height: 20}}
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset:
breakpoints: breakpoints,
transformation: {crop: "crop", width: 10, height: 20}
))
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, 'c_crop,h_20,w_10', breakpoints)
expect(tag).to.eql(expected)
it "Should populate sizes attribute", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset:
breakpoints: breakpoints,
sizes: true
))
expectedSizesAttr = '(max-width: 100px) 100px, (max-width: 200px) 200px, ' +
'(max-width: 300px) 300px, (max-width: 399px) 399px'
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', breakpoints, sizes: expectedSizesAttr)
expect(tag).to.eql(expected)
it "Should support srcset string value", ->
rawSrcSet = "some srcset data as is"
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset: rawSrcSet
))
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', [], srcset: rawSrcSet)
expect(tag).to.eql(expected)
it "Should remove width and height attributes in case srcset is specified, but passed to transformation", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
{width: 500, height: 500},
srcset: {breakpoints}
))
expected = getExpectedSrcsetTag('sample.jpg', 'e_sepia,h_500,w_500', '', breakpoints)
expect(tag).to.eql(expected)
it "should use cached breakpoints", ->
Cache.set('sample.jpg', {}, BREAKPOINTS)
tag = cloudinary.image('sample.jpg', srcset: useCache: true)
srcset = tag.match(/srcset=['"]([^"']+)['"]/)[1]
expect(srcset).to.be.ok()
srcset = srcset.split(/, /)
expect(srcset.length).to.be(BREAKPOINTS.length)
BREAKPOINTS.forEach((bp,i)->expect(srcset[i].slice(-2)).to.eql("#{bp}w"))
describe "errors", ->
invalidBreakpoints= [
[{sizes: true}, "srcset data not provided"],
[{max_width: 300, max_images: 3}, "no min_width"],
[{min_width: 100, max_images: 3}, "no max_width"],
[{min_width: 200, max_width: 100, max_images: 3}, "min_width > max_width"],
[{min_width: 100, max_width: 300}, "no max_images"],
[{min_width: 100, max_width: 300, max_images: 0}, "invalid max_images"],
[{min_width: 100, max_width: 300, max_images: -17}, "invalid max_images"],
[{min_width: 100, max_width: 300, max_images: null}, "invalid max_images"],
].forEach ([srcset, subject])=>
it "Should throw an exception when " + subject, ->
expect(()->
cloudinary.image('sample.jpg', utils.extend(srcset: srcset, commonTrans))
).to.throwException()
it "Should throw InvalidArgumentException on invalid values", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
{width: 500, height: 500},
srcset: {breakpoints}
))
expected = getExpectedSrcsetTag('sample.jpg', 'e_sepia,h_500,w_500', '', breakpoints)
expect(tag).to.eql(expected)
getExpectedSrcsetTag = (publicId, commonTrans, customTrans, breakpoints, attributes = {})->
if(!customTrans)
customTrans = commonTrans
if(!utils.isEmpty(breakpoints))
attributes.srcset = breakpoints.map((width)->
"#{UPLOAD_PATH}/#{customTrans}/c_scale,w_#{width}/#{publicId} #{width}w").join(', ');
tag = "<img src='#{UPLOAD_PATH}/#{commonTrans}/#{publicId}'"
attrs = Object.entries(attributes).map(([key, value])-> "#{key}='#{value}'").join(' ')
if(attrs)
tag += ' ' + attrs
tag += "/>"
| 201184 | expect = require('expect.js')
cloudinary = require('../cloudinary')
utils = cloudinary.utils
helper = require("./spechelper")
sharedContext = helper.sharedContext
sharedExamples = helper.sharedExamples
includeContext = helper.includeContext
extend = require('lodash/extend')
BREAKPOINTS = [5,3,7,5]
UPLOAD_PATH = "http://res.cloudinary.com/test123/image/upload"
Cache = cloudinary.Cache
srcRegExp = (name, path)->
RegExp("#{name}=[\"']#{UPLOAD_PATH}/#{path}[\"']".replace("/", "\/"))
describe 'image helper', ->
commonTrans =
effect: 'sepia',
cloud_name: 'test123',
client_hints: false
commonTransformationStr = 'e_sepia'
customAttributes = custom_attr1: 'custom_value1', custom_attr2: 'custom_value2'
beforeEach ->
cloudinary.config(true) # Reset
cloudinary.config(cloud_name: "test123", api_secret: "<KEY>")
it "should generate image", ->
expect(cloudinary.image("hello", format: "png")).to.eql("<img src='#{UPLOAD_PATH}/hello.png' />")
it "should accept scale crop and pass width/height to image tag ", ->
expect(cloudinary.image("hello", format: "png", crop: 'scale', width: 100, height: 100)).to.eql("<img src='#{UPLOAD_PATH}/c_scale,h_100,w_100/hello.png' height='100' width='100'/>")
it "should add responsive width transformation", ->
expect(cloudinary.image("hello", format: "png", responsive_width: true)).to.eql("<img class='cld-responsive' data-src='#{UPLOAD_PATH}/c_limit,w_auto/hello.png'/>")
it "should support width auto transformation", ->
expect(cloudinary.image("hello", format: "png", width: "auto", crop: "limit")).to.eql("<img class='cld-responsive' data-src='#{UPLOAD_PATH}/c_limit,w_auto/hello.png'/>")
it "should support dpr auto transformation", ->
expect(cloudinary.image("hello", format: "png", dpr: "auto")).to.eql("<img class='cld-hidpi' data-src='#{UPLOAD_PATH}/dpr_auto/hello.png'/>")
it "should support e_art:incognito transformation", ->
expect(cloudinary.image("hello", format: "png", effect: "art:incognito")).to.eql("<img src='#{UPLOAD_PATH}/e_art:incognito/hello.png' />")
it "should not mutate the options argument", ->
options =
fetch_format: 'auto'
flags: 'progressive'
cloudinary.image('hello', options)
expect(options.fetch_format).to.eql('auto')
expect(options.flags).to.eql('progressive')
it "Should consume custom attributes from 'attributes' key", ->
tag = cloudinary.image('sample.jpg', utils.extend({attributes: customAttributes}, commonTrans))
Object.entries(customAttributes).forEach ([key, value])->
expect(tag).to.contain("#{key}='#{value}'")
it "Should consume custom attributes as is from options", ->
options = utils.extend({}, commonTrans, customAttributes)
tag = cloudinary.image('sample.jpg', options)
Object.entries(customAttributes).forEach ([key, value])->
expect(tag).to.contain("#{key}='#{value}'")
it "Attributes from 'attributes' dict should override existing attributes", ->
options = utils.extend({}, commonTrans, {alt: "original alt", attributes: {alt: "updated alt"}})
tag = cloudinary.image('sample.jpg', options)
expect(tag).to.contain("alt='updated alt'")
sharedExamples "client_hints", (options)->
it "should not use data-src or set responsive class", ->
tag = cloudinary.image('sample.jpg', options)
expect(tag).to.match( /<img.*>/)
expect(tag).not.to.match(/<.*class.*>/)
expect(tag).not.to.match(/\bdata-src\b/)
expect(tag).to.match( srcRegExp("src", "c_scale,dpr_auto,w_auto/sample.jpg"))
it "should override responsive", ->
cloudinary.config(responsive: true)
tag = cloudinary.image('sample.jpg', options)
expect(tag).to.match( /<img.*>/)
expect(tag).not.to.match(/<.*class.*>/)
expect(tag).not.to.match(/\bdata-src\b/)
expect(tag).to.match( srcRegExp("src", "c_scale,dpr_auto,w_auto/sample.jpg"))
describe ":client_hints", ->
describe "as option", ->
includeContext "client_hints", {dpr: "auto", cloud_name: "test123", width: "auto", crop: "scale", client_hints: true}
describe "as global configuration", ->
beforeEach ->
cloudinary.config().client_hints = true
includeContext "client_hints", {dpr: "auto", cloud_name: "test123", width: "auto", crop: "scale"}
describe "false", ->
it "should use normal responsive behaviour", ->
cloudinary.config().responsive = true
tag = cloudinary.image('sample.jpg', {width: "auto", crop: "scale", cloud_name: "test123", client_hints: false})
expect(tag).to.match( /<img.*>/)
expect(tag).to.match( /class=["']cld-responsive["']/)
expect(tag).to.match( srcRegExp("data-src", "c_scale,w_auto/sample.jpg"))
describe "width", ->
it "supports auto width", ->
tag = cloudinary.image( 'sample.jpg', {crop: "scale", dpr: "auto", cloud_name: "test123", width: "auto:breakpoints", client_hints: true})
expect(tag).to.match( srcRegExp("src", "c_scale,dpr_auto,w_auto:breakpoints/sample.jpg"))
describe "srcset", ->
lastBreakpoint = 399
breakpoints = [100, 200, 300, lastBreakpoint]
before ->
helper.setupCache()
it "Should create srcset attribute with provided breakpoints", ->
tagWithBreakpoints = cloudinary.image('sample.jpg', utils.extend({}, commonTrans, srcset: breakpoints: breakpoints ) )
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', breakpoints)
expect(tagWithBreakpoints).to.eql(expected)
it "Support srcset attribute defined by min width max width and max images", ->
tag = cloudinary.image 'sample.jpg', extend({}, commonTrans,
srcset:
min_width: breakpoints[0],
max_width: lastBreakpoint,
max_images: breakpoints.length
)
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', breakpoints)
expect(tag).to.eql(expected)
it "should support a single srcset image", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset: {
min_width: breakpoints[0],
max_width: lastBreakpoint,
max_images: 1
}))
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', [lastBreakpoint])
expect(tag).to.eql(expected)
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset: breakpoints: [lastBreakpoint]
))
expect(tag).to.eql(expected)
it "Should support custom transformation for srcset items", ->
custom = {transformation: {crop: "crop", width: 10, height: 20}}
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset:
breakpoints: breakpoints,
transformation: {crop: "crop", width: 10, height: 20}
))
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, 'c_crop,h_20,w_10', breakpoints)
expect(tag).to.eql(expected)
it "Should populate sizes attribute", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset:
breakpoints: breakpoints,
sizes: true
))
expectedSizesAttr = '(max-width: 100px) 100px, (max-width: 200px) 200px, ' +
'(max-width: 300px) 300px, (max-width: 399px) 399px'
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', breakpoints, sizes: expectedSizesAttr)
expect(tag).to.eql(expected)
it "Should support srcset string value", ->
rawSrcSet = "some srcset data as is"
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset: rawSrcSet
))
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', [], srcset: rawSrcSet)
expect(tag).to.eql(expected)
it "Should remove width and height attributes in case srcset is specified, but passed to transformation", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
{width: 500, height: 500},
srcset: {breakpoints}
))
expected = getExpectedSrcsetTag('sample.jpg', 'e_sepia,h_500,w_500', '', breakpoints)
expect(tag).to.eql(expected)
it "should use cached breakpoints", ->
Cache.set('sample.jpg', {}, BREAKPOINTS)
tag = cloudinary.image('sample.jpg', srcset: useCache: true)
srcset = tag.match(/srcset=['"]([^"']+)['"]/)[1]
expect(srcset).to.be.ok()
srcset = srcset.split(/, /)
expect(srcset.length).to.be(BREAKPOINTS.length)
BREAKPOINTS.forEach((bp,i)->expect(srcset[i].slice(-2)).to.eql("#{bp}w"))
describe "errors", ->
invalidBreakpoints= [
[{sizes: true}, "srcset data not provided"],
[{max_width: 300, max_images: 3}, "no min_width"],
[{min_width: 100, max_images: 3}, "no max_width"],
[{min_width: 200, max_width: 100, max_images: 3}, "min_width > max_width"],
[{min_width: 100, max_width: 300}, "no max_images"],
[{min_width: 100, max_width: 300, max_images: 0}, "invalid max_images"],
[{min_width: 100, max_width: 300, max_images: -17}, "invalid max_images"],
[{min_width: 100, max_width: 300, max_images: null}, "invalid max_images"],
].forEach ([srcset, subject])=>
it "Should throw an exception when " + subject, ->
expect(()->
cloudinary.image('sample.jpg', utils.extend(srcset: srcset, commonTrans))
).to.throwException()
it "Should throw InvalidArgumentException on invalid values", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
{width: 500, height: 500},
srcset: {breakpoints}
))
expected = getExpectedSrcsetTag('sample.jpg', 'e_sepia,h_500,w_500', '', breakpoints)
expect(tag).to.eql(expected)
getExpectedSrcsetTag = (publicId, commonTrans, customTrans, breakpoints, attributes = {})->
if(!customTrans)
customTrans = commonTrans
if(!utils.isEmpty(breakpoints))
attributes.srcset = breakpoints.map((width)->
"#{UPLOAD_PATH}/#{customTrans}/c_scale,w_#{width}/#{publicId} #{width}w").join(', ');
tag = "<img src='#{UPLOAD_PATH}/#{commonTrans}/#{publicId}'"
attrs = Object.entries(attributes).map(([key, value])-> "#{key}='#{value}'").join(' ')
if(attrs)
tag += ' ' + attrs
tag += "/>"
| true | expect = require('expect.js')
cloudinary = require('../cloudinary')
utils = cloudinary.utils
helper = require("./spechelper")
sharedContext = helper.sharedContext
sharedExamples = helper.sharedExamples
includeContext = helper.includeContext
extend = require('lodash/extend')
BREAKPOINTS = [5,3,7,5]
UPLOAD_PATH = "http://res.cloudinary.com/test123/image/upload"
Cache = cloudinary.Cache
srcRegExp = (name, path)->
RegExp("#{name}=[\"']#{UPLOAD_PATH}/#{path}[\"']".replace("/", "\/"))
describe 'image helper', ->
commonTrans =
effect: 'sepia',
cloud_name: 'test123',
client_hints: false
commonTransformationStr = 'e_sepia'
customAttributes = custom_attr1: 'custom_value1', custom_attr2: 'custom_value2'
beforeEach ->
cloudinary.config(true) # Reset
cloudinary.config(cloud_name: "test123", api_secret: "PI:KEY:<KEY>END_PI")
it "should generate image", ->
expect(cloudinary.image("hello", format: "png")).to.eql("<img src='#{UPLOAD_PATH}/hello.png' />")
it "should accept scale crop and pass width/height to image tag ", ->
expect(cloudinary.image("hello", format: "png", crop: 'scale', width: 100, height: 100)).to.eql("<img src='#{UPLOAD_PATH}/c_scale,h_100,w_100/hello.png' height='100' width='100'/>")
it "should add responsive width transformation", ->
expect(cloudinary.image("hello", format: "png", responsive_width: true)).to.eql("<img class='cld-responsive' data-src='#{UPLOAD_PATH}/c_limit,w_auto/hello.png'/>")
it "should support width auto transformation", ->
expect(cloudinary.image("hello", format: "png", width: "auto", crop: "limit")).to.eql("<img class='cld-responsive' data-src='#{UPLOAD_PATH}/c_limit,w_auto/hello.png'/>")
it "should support dpr auto transformation", ->
expect(cloudinary.image("hello", format: "png", dpr: "auto")).to.eql("<img class='cld-hidpi' data-src='#{UPLOAD_PATH}/dpr_auto/hello.png'/>")
it "should support e_art:incognito transformation", ->
expect(cloudinary.image("hello", format: "png", effect: "art:incognito")).to.eql("<img src='#{UPLOAD_PATH}/e_art:incognito/hello.png' />")
it "should not mutate the options argument", ->
options =
fetch_format: 'auto'
flags: 'progressive'
cloudinary.image('hello', options)
expect(options.fetch_format).to.eql('auto')
expect(options.flags).to.eql('progressive')
it "Should consume custom attributes from 'attributes' key", ->
tag = cloudinary.image('sample.jpg', utils.extend({attributes: customAttributes}, commonTrans))
Object.entries(customAttributes).forEach ([key, value])->
expect(tag).to.contain("#{key}='#{value}'")
it "Should consume custom attributes as is from options", ->
options = utils.extend({}, commonTrans, customAttributes)
tag = cloudinary.image('sample.jpg', options)
Object.entries(customAttributes).forEach ([key, value])->
expect(tag).to.contain("#{key}='#{value}'")
it "Attributes from 'attributes' dict should override existing attributes", ->
options = utils.extend({}, commonTrans, {alt: "original alt", attributes: {alt: "updated alt"}})
tag = cloudinary.image('sample.jpg', options)
expect(tag).to.contain("alt='updated alt'")
sharedExamples "client_hints", (options)->
it "should not use data-src or set responsive class", ->
tag = cloudinary.image('sample.jpg', options)
expect(tag).to.match( /<img.*>/)
expect(tag).not.to.match(/<.*class.*>/)
expect(tag).not.to.match(/\bdata-src\b/)
expect(tag).to.match( srcRegExp("src", "c_scale,dpr_auto,w_auto/sample.jpg"))
it "should override responsive", ->
cloudinary.config(responsive: true)
tag = cloudinary.image('sample.jpg', options)
expect(tag).to.match( /<img.*>/)
expect(tag).not.to.match(/<.*class.*>/)
expect(tag).not.to.match(/\bdata-src\b/)
expect(tag).to.match( srcRegExp("src", "c_scale,dpr_auto,w_auto/sample.jpg"))
describe ":client_hints", ->
describe "as option", ->
includeContext "client_hints", {dpr: "auto", cloud_name: "test123", width: "auto", crop: "scale", client_hints: true}
describe "as global configuration", ->
beforeEach ->
cloudinary.config().client_hints = true
includeContext "client_hints", {dpr: "auto", cloud_name: "test123", width: "auto", crop: "scale"}
describe "false", ->
it "should use normal responsive behaviour", ->
cloudinary.config().responsive = true
tag = cloudinary.image('sample.jpg', {width: "auto", crop: "scale", cloud_name: "test123", client_hints: false})
expect(tag).to.match( /<img.*>/)
expect(tag).to.match( /class=["']cld-responsive["']/)
expect(tag).to.match( srcRegExp("data-src", "c_scale,w_auto/sample.jpg"))
describe "width", ->
it "supports auto width", ->
tag = cloudinary.image( 'sample.jpg', {crop: "scale", dpr: "auto", cloud_name: "test123", width: "auto:breakpoints", client_hints: true})
expect(tag).to.match( srcRegExp("src", "c_scale,dpr_auto,w_auto:breakpoints/sample.jpg"))
describe "srcset", ->
lastBreakpoint = 399
breakpoints = [100, 200, 300, lastBreakpoint]
before ->
helper.setupCache()
it "Should create srcset attribute with provided breakpoints", ->
tagWithBreakpoints = cloudinary.image('sample.jpg', utils.extend({}, commonTrans, srcset: breakpoints: breakpoints ) )
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', breakpoints)
expect(tagWithBreakpoints).to.eql(expected)
it "Support srcset attribute defined by min width max width and max images", ->
tag = cloudinary.image 'sample.jpg', extend({}, commonTrans,
srcset:
min_width: breakpoints[0],
max_width: lastBreakpoint,
max_images: breakpoints.length
)
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', breakpoints)
expect(tag).to.eql(expected)
it "should support a single srcset image", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset: {
min_width: breakpoints[0],
max_width: lastBreakpoint,
max_images: 1
}))
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', [lastBreakpoint])
expect(tag).to.eql(expected)
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset: breakpoints: [lastBreakpoint]
))
expect(tag).to.eql(expected)
it "Should support custom transformation for srcset items", ->
custom = {transformation: {crop: "crop", width: 10, height: 20}}
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset:
breakpoints: breakpoints,
transformation: {crop: "crop", width: 10, height: 20}
))
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, 'c_crop,h_20,w_10', breakpoints)
expect(tag).to.eql(expected)
it "Should populate sizes attribute", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset:
breakpoints: breakpoints,
sizes: true
))
expectedSizesAttr = '(max-width: 100px) 100px, (max-width: 200px) 200px, ' +
'(max-width: 300px) 300px, (max-width: 399px) 399px'
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', breakpoints, sizes: expectedSizesAttr)
expect(tag).to.eql(expected)
it "Should support srcset string value", ->
rawSrcSet = "some srcset data as is"
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
srcset: rawSrcSet
))
expected = getExpectedSrcsetTag('sample.jpg', commonTransformationStr, '', [], srcset: rawSrcSet)
expect(tag).to.eql(expected)
it "Should remove width and height attributes in case srcset is specified, but passed to transformation", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
{width: 500, height: 500},
srcset: {breakpoints}
))
expected = getExpectedSrcsetTag('sample.jpg', 'e_sepia,h_500,w_500', '', breakpoints)
expect(tag).to.eql(expected)
it "should use cached breakpoints", ->
Cache.set('sample.jpg', {}, BREAKPOINTS)
tag = cloudinary.image('sample.jpg', srcset: useCache: true)
srcset = tag.match(/srcset=['"]([^"']+)['"]/)[1]
expect(srcset).to.be.ok()
srcset = srcset.split(/, /)
expect(srcset.length).to.be(BREAKPOINTS.length)
BREAKPOINTS.forEach((bp,i)->expect(srcset[i].slice(-2)).to.eql("#{bp}w"))
describe "errors", ->
invalidBreakpoints= [
[{sizes: true}, "srcset data not provided"],
[{max_width: 300, max_images: 3}, "no min_width"],
[{min_width: 100, max_images: 3}, "no max_width"],
[{min_width: 200, max_width: 100, max_images: 3}, "min_width > max_width"],
[{min_width: 100, max_width: 300}, "no max_images"],
[{min_width: 100, max_width: 300, max_images: 0}, "invalid max_images"],
[{min_width: 100, max_width: 300, max_images: -17}, "invalid max_images"],
[{min_width: 100, max_width: 300, max_images: null}, "invalid max_images"],
].forEach ([srcset, subject])=>
it "Should throw an exception when " + subject, ->
expect(()->
cloudinary.image('sample.jpg', utils.extend(srcset: srcset, commonTrans))
).to.throwException()
it "Should throw InvalidArgumentException on invalid values", ->
tag = cloudinary.image('sample.jpg', extend({}, commonTrans,
{width: 500, height: 500},
srcset: {breakpoints}
))
expected = getExpectedSrcsetTag('sample.jpg', 'e_sepia,h_500,w_500', '', breakpoints)
expect(tag).to.eql(expected)
getExpectedSrcsetTag = (publicId, commonTrans, customTrans, breakpoints, attributes = {})->
if(!customTrans)
customTrans = commonTrans
if(!utils.isEmpty(breakpoints))
attributes.srcset = breakpoints.map((width)->
"#{UPLOAD_PATH}/#{customTrans}/c_scale,w_#{width}/#{publicId} #{width}w").join(', ');
tag = "<img src='#{UPLOAD_PATH}/#{commonTrans}/#{publicId}'"
attrs = Object.entries(attributes).map(([key, value])-> "#{key}='#{value}'").join(' ')
if(attrs)
tag += ' ' + attrs
tag += "/>"
|
[
{
"context": "erties\", ->\n obj =\n name:\n first: 'Valtid'\n last : 'Caushi'\n\n schema = new Schema",
"end": 104,
"score": 0.9995574951171875,
"start": 98,
"tag": "NAME",
"value": "Valtid"
},
{
"context": " name:\n first: 'Valtid'\n last :... | test/unit/schema.coffee | valtido/ason-js | 0 | describe "schemas: ", ->
it "should have properties", ->
obj =
name:
first: 'Valtid'
last : 'Caushi'
schema = new Schema "user", obj
expect(schema.name).toBeDefined()
expect(schema.description).toBeDefined()
expect(schema.tree).toBeDefined()
| 223040 | describe "schemas: ", ->
it "should have properties", ->
obj =
name:
first: '<NAME>'
last : '<NAME>'
schema = new Schema "user", obj
expect(schema.name).toBeDefined()
expect(schema.description).toBeDefined()
expect(schema.tree).toBeDefined()
| true | describe "schemas: ", ->
it "should have properties", ->
obj =
name:
first: 'PI:NAME:<NAME>END_PI'
last : 'PI:NAME:<NAME>END_PI'
schema = new Schema "user", obj
expect(schema.name).toBeDefined()
expect(schema.description).toBeDefined()
expect(schema.tree).toBeDefined()
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9992483258247375,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-stream2-pipe-error-handling.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
stream = require("stream")
(testErrorListenerCatches = ->
count = 1000
source = new stream.Readable()
source._read = (n) ->
n = Math.min(count, n)
count -= n
source.push new Buffer(n)
return
unpipedDest = undefined
source.unpipe = (dest) ->
unpipedDest = dest
stream.Readable::unpipe.call this, dest
return
dest = new stream.Writable()
dest._write = (chunk, encoding, cb) ->
cb()
return
source.pipe dest
gotErr = null
dest.on "error", (err) ->
gotErr = err
return
unpipedSource = undefined
dest.on "unpipe", (src) ->
unpipedSource = src
return
err = new Error("This stream turned into bacon.")
dest.emit "error", err
assert.strictEqual gotErr, err
assert.strictEqual unpipedSource, source
assert.strictEqual unpipedDest, dest
return
)()
(testErrorWithoutListenerThrows = ->
count = 1000
source = new stream.Readable()
source._read = (n) ->
n = Math.min(count, n)
count -= n
source.push new Buffer(n)
return
unpipedDest = undefined
source.unpipe = (dest) ->
unpipedDest = dest
stream.Readable::unpipe.call this, dest
return
dest = new stream.Writable()
dest._write = (chunk, encoding, cb) ->
cb()
return
source.pipe dest
unpipedSource = undefined
dest.on "unpipe", (src) ->
unpipedSource = src
return
err = new Error("This stream turned into bacon.")
gotErr = null
try
dest.emit "error", err
catch e
gotErr = e
assert.strictEqual gotErr, err
assert.strictEqual unpipedSource, source
assert.strictEqual unpipedDest, dest
return
)()
| 91402 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
stream = require("stream")
(testErrorListenerCatches = ->
count = 1000
source = new stream.Readable()
source._read = (n) ->
n = Math.min(count, n)
count -= n
source.push new Buffer(n)
return
unpipedDest = undefined
source.unpipe = (dest) ->
unpipedDest = dest
stream.Readable::unpipe.call this, dest
return
dest = new stream.Writable()
dest._write = (chunk, encoding, cb) ->
cb()
return
source.pipe dest
gotErr = null
dest.on "error", (err) ->
gotErr = err
return
unpipedSource = undefined
dest.on "unpipe", (src) ->
unpipedSource = src
return
err = new Error("This stream turned into bacon.")
dest.emit "error", err
assert.strictEqual gotErr, err
assert.strictEqual unpipedSource, source
assert.strictEqual unpipedDest, dest
return
)()
(testErrorWithoutListenerThrows = ->
count = 1000
source = new stream.Readable()
source._read = (n) ->
n = Math.min(count, n)
count -= n
source.push new Buffer(n)
return
unpipedDest = undefined
source.unpipe = (dest) ->
unpipedDest = dest
stream.Readable::unpipe.call this, dest
return
dest = new stream.Writable()
dest._write = (chunk, encoding, cb) ->
cb()
return
source.pipe dest
unpipedSource = undefined
dest.on "unpipe", (src) ->
unpipedSource = src
return
err = new Error("This stream turned into bacon.")
gotErr = null
try
dest.emit "error", err
catch e
gotErr = e
assert.strictEqual gotErr, err
assert.strictEqual unpipedSource, source
assert.strictEqual unpipedDest, dest
return
)()
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
stream = require("stream")
(testErrorListenerCatches = ->
count = 1000
source = new stream.Readable()
source._read = (n) ->
n = Math.min(count, n)
count -= n
source.push new Buffer(n)
return
unpipedDest = undefined
source.unpipe = (dest) ->
unpipedDest = dest
stream.Readable::unpipe.call this, dest
return
dest = new stream.Writable()
dest._write = (chunk, encoding, cb) ->
cb()
return
source.pipe dest
gotErr = null
dest.on "error", (err) ->
gotErr = err
return
unpipedSource = undefined
dest.on "unpipe", (src) ->
unpipedSource = src
return
err = new Error("This stream turned into bacon.")
dest.emit "error", err
assert.strictEqual gotErr, err
assert.strictEqual unpipedSource, source
assert.strictEqual unpipedDest, dest
return
)()
(testErrorWithoutListenerThrows = ->
count = 1000
source = new stream.Readable()
source._read = (n) ->
n = Math.min(count, n)
count -= n
source.push new Buffer(n)
return
unpipedDest = undefined
source.unpipe = (dest) ->
unpipedDest = dest
stream.Readable::unpipe.call this, dest
return
dest = new stream.Writable()
dest._write = (chunk, encoding, cb) ->
cb()
return
source.pipe dest
unpipedSource = undefined
dest.on "unpipe", (src) ->
unpipedSource = src
return
err = new Error("This stream turned into bacon.")
gotErr = null
try
dest.emit "error", err
catch e
gotErr = e
assert.strictEqual gotErr, err
assert.strictEqual unpipedSource, source
assert.strictEqual unpipedDest, dest
return
)()
|
[
{
"context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o",
"end": 67,
"score": 0.6130756139755249,
"start": 62,
"tag": "NAME",
"value": "Hatio"
},
{
"context": "ementation lifted from underscore.js (c) 2009-2012 Jerem... | src/utils.coffee | heartyoh/dou | 1 | # ==========================================
# Copyright 2014 Hatio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [], ->
"use strict"
DEFAULT_INTERVAL = 100
idCounter = 0
{
# returns new object representing multiple objects merged together
# optional final argument is boolean which specifies if merge is recursive
# original objects are unmodified
#
# usage:
# var base = {a:2, b:6};
# var extra = {b:3, c:4};
# merge(base, extra); //{a:2, b:3, c:4}
# base; //{a:2, b:6}
#
# var base = {a:2, b:6};
# var extra = {b:3, c:4};
# var extraExtra = {a:4, d:9};
# merge(base, extra, extraExtra); //{a:4, b:3, c:4. d: 9}
# base; //{a:2, b:6}
#
# var base = {a:2, b:{bb:4, cc:5}};
# var extra = {a:4, b:{cc:7, dd:1}};
# merge(base, extra, true); //{a:4, b:{bb:4, cc:7, dd:1}}
# base; //{a:4, b:{bb:4, cc:7, dd:1}}
#
merge: (target, extenders...) ->
target = {} if not target or typeof target is not "object"
for other in extenders
for own key, val of other
if typeof val isnt "object"
target[key] = val
else
target[key] = this.merge target[key], val
target
shallow_merge: (extenders...) ->
result = {}
for extender in extenders
for own key, val of extender
result[key] = val
result
# updates base in place by copying properties of extra to it
# optionally clobber protected
# usage:
# var base = {a:2, b:6};
# var extra = {c:4};
# push(base, extra); //{a:2, b:6, c:4}
# base; //{a:2, b:6, c:4}
#
# var base = {a:2, b:6};
# var extra = {b: 4 c:4};
# push(base, extra, true); //Error ("utils.push attempted to overwrite 'b' while running in protected mode")
# base; //{a:2, b:6}
#
# objects with the same key will merge recursively when protect is false
# eg:
# var base = {a:16, b:{bb:4, cc:10}};
# var extra = {b:{cc:25, dd:19}, c:5};
# push(base, extra); //{a:16, {bb:4, cc:25, dd:19}, c:5}
#
push: (base, extra, protect) ->
return base if not base or not extra
for own key, val of extra
throw new Error "utils.push attempted to overwrite \"#{key}\" while running in protected mode" if base[key] and protect
if typeof base[key] is "object" and typeof extra[key] is "object"
this.push base[key], extra[key]
else
base[key] = extra[key]
base
isEnumerable: (obj, property) -> Object.keys(obj).indexOf(property) > -1
# build a function from other function(s)
# utils.compose(a,b,c) -> a(b(c()));
# implementation lifted from underscore.js (c) 2009-2012 Jeremy Ashkenas
compose: ->
funcs = arguments
->
args = arguments
args = funcs[i].apply(this, args) for i in [(funcs.length - 1) .. 0]
args[0]
# Can only unique arrays of homogeneous primitives,
# e.g. an array of only strings, an array of only booleans, or an array of only numerics
uniqueArray: (array) ->
u = {}
a = []
for item in array
continue if u.hasOwnProperty(item)
a.push(item);
u[item] = 1
a
debounce: (func, wait, immediate) ->
wait = DEFAULT_INTERVAL if typeof wait isnt 'number'
timeout = 0
result = null
->
context = this
args = arguments
later = ->
timeout = null
result = func.apply(context, args) if !immediate
callNow = immediate and !timeout
clearTimeout timeout
timeout = setTimeout later, wait
result = func.apply context, args if callNow
result
throttle: (func, wait) ->
wait = DEFAULT_INTERVAL if typeof wait isnt 'number'
context = args = timeout = throttling = more = result = null
whenDone = this.debounce ->
more = throttling = false
, wait
->
context = this
args = arguments
later = ->
timeout = null
result = func.apply context, args if more
whenDone()
timeout = setTimeout later, wait if !timeout
if throttling
more = true
else
throttling = true
result = func.apply context, args
whenDone()
result
countThen: (num, base) ->
-> base.apply this, arguments if !--num
delegate: (rules) ->
(e, data) ->
target = $(e.target)
parent = null
for own selector of rules
if !e.isPropagationStopped() and (parent = target.closest(selector)).length
data = data || {}
data.el = parent[0]
return rules[selector].apply this, [e, data]
# ensures that a function will only be called once.
# usage:
# will only create the application once
# var initialize = utils.once(createApplication)
# initialize();
# initialize();
#
# will only delete a record once
# var myHanlder = function () {
# $.ajax({type: 'DELETE', url: 'someurl.com', data: {id: 1}});
# };
# this.on('click', utils.once(myHandler));
#
once: (func) ->
ran = false
result = null
->
return result if ran
result = func.apply this, arguments
ran = true
result
# Generate a unique integer id (unique within the entire client session).
# Useful for temporary DOM ids.
uniqueId: (prefix) ->
id = (++idCounter) + ''
if prefix then prefix + id else id
clone: (obj) ->
return obj if not obj? or typeof obj isnt 'object'
return obj.slice() if obj instanceof Array
@shallow_merge obj
}
| 10024 | # ==========================================
# Copyright 2014 <NAME>, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [], ->
"use strict"
DEFAULT_INTERVAL = 100
idCounter = 0
{
# returns new object representing multiple objects merged together
# optional final argument is boolean which specifies if merge is recursive
# original objects are unmodified
#
# usage:
# var base = {a:2, b:6};
# var extra = {b:3, c:4};
# merge(base, extra); //{a:2, b:3, c:4}
# base; //{a:2, b:6}
#
# var base = {a:2, b:6};
# var extra = {b:3, c:4};
# var extraExtra = {a:4, d:9};
# merge(base, extra, extraExtra); //{a:4, b:3, c:4. d: 9}
# base; //{a:2, b:6}
#
# var base = {a:2, b:{bb:4, cc:5}};
# var extra = {a:4, b:{cc:7, dd:1}};
# merge(base, extra, true); //{a:4, b:{bb:4, cc:7, dd:1}}
# base; //{a:4, b:{bb:4, cc:7, dd:1}}
#
merge: (target, extenders...) ->
target = {} if not target or typeof target is not "object"
for other in extenders
for own key, val of other
if typeof val isnt "object"
target[key] = val
else
target[key] = this.merge target[key], val
target
shallow_merge: (extenders...) ->
result = {}
for extender in extenders
for own key, val of extender
result[key] = val
result
# updates base in place by copying properties of extra to it
# optionally clobber protected
# usage:
# var base = {a:2, b:6};
# var extra = {c:4};
# push(base, extra); //{a:2, b:6, c:4}
# base; //{a:2, b:6, c:4}
#
# var base = {a:2, b:6};
# var extra = {b: 4 c:4};
# push(base, extra, true); //Error ("utils.push attempted to overwrite 'b' while running in protected mode")
# base; //{a:2, b:6}
#
# objects with the same key will merge recursively when protect is false
# eg:
# var base = {a:16, b:{bb:4, cc:10}};
# var extra = {b:{cc:25, dd:19}, c:5};
# push(base, extra); //{a:16, {bb:4, cc:25, dd:19}, c:5}
#
push: (base, extra, protect) ->
return base if not base or not extra
for own key, val of extra
throw new Error "utils.push attempted to overwrite \"#{key}\" while running in protected mode" if base[key] and protect
if typeof base[key] is "object" and typeof extra[key] is "object"
this.push base[key], extra[key]
else
base[key] = extra[key]
base
isEnumerable: (obj, property) -> Object.keys(obj).indexOf(property) > -1
# build a function from other function(s)
# utils.compose(a,b,c) -> a(b(c()));
# implementation lifted from underscore.js (c) 2009-2012 <NAME>
compose: ->
funcs = arguments
->
args = arguments
args = funcs[i].apply(this, args) for i in [(funcs.length - 1) .. 0]
args[0]
# Can only unique arrays of homogeneous primitives,
# e.g. an array of only strings, an array of only booleans, or an array of only numerics
uniqueArray: (array) ->
u = {}
a = []
for item in array
continue if u.hasOwnProperty(item)
a.push(item);
u[item] = 1
a
debounce: (func, wait, immediate) ->
wait = DEFAULT_INTERVAL if typeof wait isnt 'number'
timeout = 0
result = null
->
context = this
args = arguments
later = ->
timeout = null
result = func.apply(context, args) if !immediate
callNow = immediate and !timeout
clearTimeout timeout
timeout = setTimeout later, wait
result = func.apply context, args if callNow
result
throttle: (func, wait) ->
wait = DEFAULT_INTERVAL if typeof wait isnt 'number'
context = args = timeout = throttling = more = result = null
whenDone = this.debounce ->
more = throttling = false
, wait
->
context = this
args = arguments
later = ->
timeout = null
result = func.apply context, args if more
whenDone()
timeout = setTimeout later, wait if !timeout
if throttling
more = true
else
throttling = true
result = func.apply context, args
whenDone()
result
countThen: (num, base) ->
-> base.apply this, arguments if !--num
delegate: (rules) ->
(e, data) ->
target = $(e.target)
parent = null
for own selector of rules
if !e.isPropagationStopped() and (parent = target.closest(selector)).length
data = data || {}
data.el = parent[0]
return rules[selector].apply this, [e, data]
# ensures that a function will only be called once.
# usage:
# will only create the application once
# var initialize = utils.once(createApplication)
# initialize();
# initialize();
#
# will only delete a record once
# var myHanlder = function () {
# $.ajax({type: 'DELETE', url: 'someurl.com', data: {id: 1}});
# };
# this.on('click', utils.once(myHandler));
#
once: (func) ->
ran = false
result = null
->
return result if ran
result = func.apply this, arguments
ran = true
result
# Generate a unique integer id (unique within the entire client session).
# Useful for temporary DOM ids.
uniqueId: (prefix) ->
id = (++idCounter) + ''
if prefix then prefix + id else id
clone: (obj) ->
return obj if not obj? or typeof obj isnt 'object'
return obj.slice() if obj instanceof Array
@shallow_merge obj
}
| true | # ==========================================
# Copyright 2014 PI:NAME:<NAME>END_PI, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [], ->
"use strict"
DEFAULT_INTERVAL = 100
idCounter = 0
{
# returns new object representing multiple objects merged together
# optional final argument is boolean which specifies if merge is recursive
# original objects are unmodified
#
# usage:
# var base = {a:2, b:6};
# var extra = {b:3, c:4};
# merge(base, extra); //{a:2, b:3, c:4}
# base; //{a:2, b:6}
#
# var base = {a:2, b:6};
# var extra = {b:3, c:4};
# var extraExtra = {a:4, d:9};
# merge(base, extra, extraExtra); //{a:4, b:3, c:4. d: 9}
# base; //{a:2, b:6}
#
# var base = {a:2, b:{bb:4, cc:5}};
# var extra = {a:4, b:{cc:7, dd:1}};
# merge(base, extra, true); //{a:4, b:{bb:4, cc:7, dd:1}}
# base; //{a:4, b:{bb:4, cc:7, dd:1}}
#
merge: (target, extenders...) ->
target = {} if not target or typeof target is not "object"
for other in extenders
for own key, val of other
if typeof val isnt "object"
target[key] = val
else
target[key] = this.merge target[key], val
target
shallow_merge: (extenders...) ->
result = {}
for extender in extenders
for own key, val of extender
result[key] = val
result
# updates base in place by copying properties of extra to it
# optionally clobber protected
# usage:
# var base = {a:2, b:6};
# var extra = {c:4};
# push(base, extra); //{a:2, b:6, c:4}
# base; //{a:2, b:6, c:4}
#
# var base = {a:2, b:6};
# var extra = {b: 4 c:4};
# push(base, extra, true); //Error ("utils.push attempted to overwrite 'b' while running in protected mode")
# base; //{a:2, b:6}
#
# objects with the same key will merge recursively when protect is false
# eg:
# var base = {a:16, b:{bb:4, cc:10}};
# var extra = {b:{cc:25, dd:19}, c:5};
# push(base, extra); //{a:16, {bb:4, cc:25, dd:19}, c:5}
#
push: (base, extra, protect) ->
return base if not base or not extra
for own key, val of extra
throw new Error "utils.push attempted to overwrite \"#{key}\" while running in protected mode" if base[key] and protect
if typeof base[key] is "object" and typeof extra[key] is "object"
this.push base[key], extra[key]
else
base[key] = extra[key]
base
isEnumerable: (obj, property) -> Object.keys(obj).indexOf(property) > -1
# build a function from other function(s)
# utils.compose(a,b,c) -> a(b(c()));
# implementation lifted from underscore.js (c) 2009-2012 PI:NAME:<NAME>END_PI
compose: ->
funcs = arguments
->
args = arguments
args = funcs[i].apply(this, args) for i in [(funcs.length - 1) .. 0]
args[0]
# Can only unique arrays of homogeneous primitives,
# e.g. an array of only strings, an array of only booleans, or an array of only numerics
uniqueArray: (array) ->
u = {}
a = []
for item in array
continue if u.hasOwnProperty(item)
a.push(item);
u[item] = 1
a
debounce: (func, wait, immediate) ->
wait = DEFAULT_INTERVAL if typeof wait isnt 'number'
timeout = 0
result = null
->
context = this
args = arguments
later = ->
timeout = null
result = func.apply(context, args) if !immediate
callNow = immediate and !timeout
clearTimeout timeout
timeout = setTimeout later, wait
result = func.apply context, args if callNow
result
throttle: (func, wait) ->
wait = DEFAULT_INTERVAL if typeof wait isnt 'number'
context = args = timeout = throttling = more = result = null
whenDone = this.debounce ->
more = throttling = false
, wait
->
context = this
args = arguments
later = ->
timeout = null
result = func.apply context, args if more
whenDone()
timeout = setTimeout later, wait if !timeout
if throttling
more = true
else
throttling = true
result = func.apply context, args
whenDone()
result
countThen: (num, base) ->
-> base.apply this, arguments if !--num
delegate: (rules) ->
(e, data) ->
target = $(e.target)
parent = null
for own selector of rules
if !e.isPropagationStopped() and (parent = target.closest(selector)).length
data = data || {}
data.el = parent[0]
return rules[selector].apply this, [e, data]
# ensures that a function will only be called once.
# usage:
# will only create the application once
# var initialize = utils.once(createApplication)
# initialize();
# initialize();
#
# will only delete a record once
# var myHanlder = function () {
# $.ajax({type: 'DELETE', url: 'someurl.com', data: {id: 1}});
# };
# this.on('click', utils.once(myHandler));
#
once: (func) ->
ran = false
result = null
->
return result if ran
result = func.apply this, arguments
ran = true
result
# Generate a unique integer id (unique within the entire client session).
# Useful for temporary DOM ids.
uniqueId: (prefix) ->
id = (++idCounter) + ''
if prefix then prefix + id else id
clone: (obj) ->
return obj if not obj? or typeof obj isnt 'object'
return obj.slice() if obj instanceof Array
@shallow_merge obj
}
|
[
{
"context": " file: @file.path\n name: @name\n getter: @getter\n setter: ",
"end": 2517,
"score": 0.8613112568855286,
"start": 2517,
"tag": "NAME",
"value": ""
}
] | lib/entities/property.coffee | koding/codo | 210 | Entity = require '../entity'
Entities = require '../_entities'
Winston = require 'winston'
#
# Supported formats:
#
# foo: []
#
# get foo: ->
# set foo: (value) ->
#
# @property 'foo'
# @property 'foo', ->
# @property 'foo',
# get: ->
# set: (value) ->
#
module.exports = class Entities.Property extends Entity
@name: "Property"
@looksLike: (node) ->
(node.constructor.name == 'Assign' && node.value?.constructor.name == 'Value') ||
(node.constructor.name == 'Call' && node.variable?.base?.value == 'this') ||
(
node.constructor.name == 'Call' &&
node.args?[0]?.base?.properties?[0]?.variable?.base?.value &&
(node.variable?.base?.value == 'set' || node.variable?.base?.value == 'get')
)
@is: (node) ->
super(node) && (
node.documentation?.property ||
(node.constructor.name == 'Call' && node.variable?.base?.value != 'this')
)
constructor: (@environment, @file, @node) ->
if @node.constructor.name == 'Call' && @node.variable?.base?.value != 'this'
@name = @node.args[0].base.properties[0].variable.base.value
@setter = @node.variable.base.value == 'set'
@getter = @node.variable.base.value == 'get'
else if @node.constructor.name == 'Call' && @node.variable?.base?.value == 'this'
@name = @node.args[0].base.value.replace(/["']/g, '')
if @node.args.length > 1
if @node.args[1].constructor.name == 'Value'
# @property 'test', {set: ->, get: ->}
@setter = false
@getter = false
for property in @node.args[1].base?.properties
@setter = true if property.variable?.base.value == 'set'
@getter = true if property.variable?.base.value == 'get'
else
# @property 'test', ->
@setter = false
@getter = true
else
# @property 'test'
@setter = true
@getter = true
else
[@name, @selfish] = @fetchVariableName()
@setter = true
@getter = true
@documentation = @node.documentation
if @environment.options.debug
Winston.info "Creating new Property Entity"
Winston.info " name: " + @name
Winston.info " documentation: " + @documentation
fetchVariableName: ->
@fetchName()
unite: (property) ->
for attribute in ['documentation', 'getter', 'setter']
property[attribute] = @[attribute] = property[attribute] || @[attribute]
inspect: ->
{
file: @file.path
name: @name
getter: @getter
setter: @setter
documentation: @documentation?.inspect()
}
| 176632 | Entity = require '../entity'
Entities = require '../_entities'
Winston = require 'winston'
#
# Supported formats:
#
# foo: []
#
# get foo: ->
# set foo: (value) ->
#
# @property 'foo'
# @property 'foo', ->
# @property 'foo',
# get: ->
# set: (value) ->
#
module.exports = class Entities.Property extends Entity
@name: "Property"
@looksLike: (node) ->
(node.constructor.name == 'Assign' && node.value?.constructor.name == 'Value') ||
(node.constructor.name == 'Call' && node.variable?.base?.value == 'this') ||
(
node.constructor.name == 'Call' &&
node.args?[0]?.base?.properties?[0]?.variable?.base?.value &&
(node.variable?.base?.value == 'set' || node.variable?.base?.value == 'get')
)
@is: (node) ->
super(node) && (
node.documentation?.property ||
(node.constructor.name == 'Call' && node.variable?.base?.value != 'this')
)
constructor: (@environment, @file, @node) ->
if @node.constructor.name == 'Call' && @node.variable?.base?.value != 'this'
@name = @node.args[0].base.properties[0].variable.base.value
@setter = @node.variable.base.value == 'set'
@getter = @node.variable.base.value == 'get'
else if @node.constructor.name == 'Call' && @node.variable?.base?.value == 'this'
@name = @node.args[0].base.value.replace(/["']/g, '')
if @node.args.length > 1
if @node.args[1].constructor.name == 'Value'
# @property 'test', {set: ->, get: ->}
@setter = false
@getter = false
for property in @node.args[1].base?.properties
@setter = true if property.variable?.base.value == 'set'
@getter = true if property.variable?.base.value == 'get'
else
# @property 'test', ->
@setter = false
@getter = true
else
# @property 'test'
@setter = true
@getter = true
else
[@name, @selfish] = @fetchVariableName()
@setter = true
@getter = true
@documentation = @node.documentation
if @environment.options.debug
Winston.info "Creating new Property Entity"
Winston.info " name: " + @name
Winston.info " documentation: " + @documentation
fetchVariableName: ->
@fetchName()
unite: (property) ->
for attribute in ['documentation', 'getter', 'setter']
property[attribute] = @[attribute] = property[attribute] || @[attribute]
inspect: ->
{
file: @file.path
name: <NAME> @name
getter: @getter
setter: @setter
documentation: @documentation?.inspect()
}
| true | Entity = require '../entity'
Entities = require '../_entities'
Winston = require 'winston'
#
# Supported formats:
#
# foo: []
#
# get foo: ->
# set foo: (value) ->
#
# @property 'foo'
# @property 'foo', ->
# @property 'foo',
# get: ->
# set: (value) ->
#
module.exports = class Entities.Property extends Entity
@name: "Property"
@looksLike: (node) ->
(node.constructor.name == 'Assign' && node.value?.constructor.name == 'Value') ||
(node.constructor.name == 'Call' && node.variable?.base?.value == 'this') ||
(
node.constructor.name == 'Call' &&
node.args?[0]?.base?.properties?[0]?.variable?.base?.value &&
(node.variable?.base?.value == 'set' || node.variable?.base?.value == 'get')
)
@is: (node) ->
super(node) && (
node.documentation?.property ||
(node.constructor.name == 'Call' && node.variable?.base?.value != 'this')
)
constructor: (@environment, @file, @node) ->
if @node.constructor.name == 'Call' && @node.variable?.base?.value != 'this'
@name = @node.args[0].base.properties[0].variable.base.value
@setter = @node.variable.base.value == 'set'
@getter = @node.variable.base.value == 'get'
else if @node.constructor.name == 'Call' && @node.variable?.base?.value == 'this'
@name = @node.args[0].base.value.replace(/["']/g, '')
if @node.args.length > 1
if @node.args[1].constructor.name == 'Value'
# @property 'test', {set: ->, get: ->}
@setter = false
@getter = false
for property in @node.args[1].base?.properties
@setter = true if property.variable?.base.value == 'set'
@getter = true if property.variable?.base.value == 'get'
else
# @property 'test', ->
@setter = false
@getter = true
else
# @property 'test'
@setter = true
@getter = true
else
[@name, @selfish] = @fetchVariableName()
@setter = true
@getter = true
@documentation = @node.documentation
if @environment.options.debug
Winston.info "Creating new Property Entity"
Winston.info " name: " + @name
Winston.info " documentation: " + @documentation
fetchVariableName: ->
@fetchName()
unite: (property) ->
for attribute in ['documentation', 'getter', 'setter']
property[attribute] = @[attribute] = property[attribute] || @[attribute]
inspect: ->
{
file: @file.path
name: PI:NAME:<NAME>END_PI @name
getter: @getter
setter: @setter
documentation: @documentation?.inspect()
}
|
[
{
"context": "should be encoded\", ->\n p = new @Product {name: \"Cool Snowboard\", cost: 12.99}\n deepEqual p.toJSON(), {name: \"Co",
"end": 379,
"score": 0.7404192090034485,
"start": 365,
"tag": "NAME",
"value": "Cool Snowboard"
},
{
"context": "rd\", cost: 12.99}\n deepEqual p.... | tests/batman/model/encoders_test.coffee | amco/batman | 0 | QUnit.module "Batman.Model: encoding/decoding to/from JSON",
setup: ->
class @Product extends Batman.Model
@encode 'name', 'cost'
@accessor 'excitingName',
get: -> @get('name').toUpperCase()
class @FlakyProduct extends @Product
@encode 'broken?'
test "keys marked for encoding should be encoded", ->
p = new @Product {name: "Cool Snowboard", cost: 12.99}
deepEqual p.toJSON(), {name: "Cool Snowboard", cost: 12.99}
test "undefined keys marked for encoding shouldn't be encoded", ->
p = new @Product {name: "Cool Snowboard"}
deepEqual p.toJSON(), {name: "Cool Snowboard"}
test "accessor keys marked for encoding should be encoded", ->
class TestProduct extends @Product
@encode 'excitingName'
p = new TestProduct {name: "Cool Snowboard", cost: 12.99}
deepEqual p.toJSON(), {name: "Cool Snowboard", cost: 12.99, excitingName: 'COOL SNOWBOARD'}
test "keys marked for decoding should be decoded", ->
p = new @Product
json = {name: "Cool Snowboard", cost: 12.99}
p.fromJSON(json)
equal p.get('name'), "Cool Snowboard"
equal p.get('cost'), 12.99
test "falsy keys marked for decoding should be decoded", ->
p = new @Product
json = {cost: 0}
p.fromJSON(json)
equal p.get('cost'), 0
test "keys not marked for encoding shouldn't be encoded", ->
p = new @Product {name: "Cool Snowboard", cost: 12.99, wibble: 'wobble'}
deepEqual p.toJSON(), {name: "Cool Snowboard", cost: 12.99}
test "keys not marked for decoding shouldn't be decoded", ->
p = new @Product
json = {name: "Cool Snowboard", cost: 12.99, wibble: 'wobble'}
p.fromJSON(json)
equal p.get('name'), "Cool Snowboard"
equal p.get('cost'), 12.99
equal p.get('wibble'), undefined
test "models shouldn't encode their primary keys by default", ->
p = new @Product {id: 10, name: "Cool snowboard"}
deepEqual p.toJSON(), {name: "Cool snowboard"}
test "models without any decoders should decode all keys", ->
class TestProduct extends Batman.Model
# No encoders.
oldDecoders = Batman.Model::_batman.encoders
Batman.Model::_batman.encoders = new Batman.SimpleHash
p = new TestProduct
Batman.developer.suppress ->
p.fromJSON {name: "Cool Snowboard", cost: 12.99, rails_is_silly: "yup"}
equal p.get('name'), "Cool Snowboard"
equal p.get('cost'), 12.99
equal p.get('rails_is_silly'), 'yup'
Batman.Model::_batman.encoders = oldDecoders
test "key ending with ? marked for encoding should be encoded", ->
p = new @FlakyProduct {name: "Vintage Snowboard", cost: 122.99, "broken?": true}
deepEqual p.toJSON(), {name: "Vintage Snowboard", cost: 122.99, "broken?": true}
test "key ending with ? marked for decoding should be decoded", ->
p = new @FlakyProduct
json = {name: "Vintage Snowboard", cost: 122.99, "broken?": true}
p.fromJSON(json)
ok p.get('broken?'), "Cool Snowboard"
QUnit.module "Batman.Model: encoding/decoding to/from JSON with custom primary Key",
setup: ->
class @Product extends Batman.Model
@set 'primaryKey', '_id'
test "undefined primaryKey shouldn't be encoded", ->
p = new @Product
deepEqual p.toJSON(), {}
test "defined primaryKey shouldn't be encoded", ->
p = new @Product("deadbeef")
deepEqual p.toJSON(), {}
test "defined primaryKey should be decoded", ->
json = {_id: "deadbeef"}
p = new @Product()
p.fromJSON(json)
equal p.get('id'), "deadbeef"
equal p.get('_id'), "deadbeef"
test "the old primaryKey should not be decoded", ->
json = {id: 10}
p = new @Product()
p.fromJSON(json)
equal p.get('id'), undefined
equal p.get('_id'), undefined
test "primary key encoding can be opted into", ->
@Product.encode '_id' # Tell the product to both encode and decode '_id'
p = new @Product("deadbeef")
deepEqual p.toJSON(), {_id: "deadbeef"}
QUnit.module "Batman.Model: encoding: custom encoders/decoders",
setup: ->
class @Product extends Batman.Model
@encode 'name', (unencoded) -> unencoded.toUpperCase()
@encode 'date',
encode: (unencoded) -> "zzz"
decode: (encoded) -> "yyy"
test "custom encoders with an encode and a decode implementation should be recognized", ->
p = new @Product(date: "clobbered")
deepEqual p.toJSON(), {date: "zzz"}
json = p = new @Product
p.fromJSON({date: "clobbered"})
equal p.get('date'), "yyy"
test "custom encoders should receive the value to be encoded, the key it's from, the JSON being built, and the source object", 4, ->
@Product.encode 'date',
encode: (val, key, object, record) ->
equal val, "some date"
equal key, "date"
deepEqual object, {}
equal record, p
return 'foo bar'
p = new @Product(date: "some date")
p.toJSON()
test "custom decoders should receive the value to decode, the key in the data it's from, the JSON being decoded, the object about to be mixed in, and the record", 5, ->
@Product.encode 'date',
decode: (val, key, json, object, record) ->
equal val, "some date"
equal key, 'date'
deepEqual json, {date: "some date"}
deepEqual object, {}
equal record, p
p = new @Product()
p.fromJSON(date: "some date")
test "passing a function should shortcut to passing an encoder", ->
p = new @Product(name: "snowboard")
deepEqual p.toJSON(), {name: "SNOWBOARD"}
test "passing false should not attach an encoder or decoder for that key", ->
class TestProduct extends Batman.Model
@encode 'name',
encode: false
decode: (x) -> x
@encode 'date',
encode: (x) -> x
decode: false
decoded = new TestProduct()
decoded.fromJSON(name: "snowboard", date: "10/10/2010")
equal decoded.get('date'), undefined
equal decoded.get('name'), "snowboard"
encoded = new TestProduct(name: "snowboard", date: "10/10/2010")
deepEqual encoded.toJSON(), {date: "10/10/2010"}
test "passing false for an encoder should never do a get on the property", ->
getSpy = createSpy()
class TestProduct extends Batman.Model
@encode 'name',
encode: false
decode: (x) -> x
@accessor 'name',
get: getSpy
encoded = new TestProduct(name: "snowboard", date: "10/10/2010")
encoded.toJSON()
ok !getSpy.called
test "passing an as option should put the encoded value in that key in the outgoing json", ->
class TestProduct extends Batman.Model
@encode 'shouldDestroy', {as: '_destroy'}
p = new TestProduct(shouldDestroy: true)
deepEqual p.toJSON(), {_destroy: true}
test "passing an as option should put the dencoded value in that key on the record", ->
class TestProduct extends Batman.Model
@encode 'shouldDestroy', {as: '_destroy'}
p = new TestProduct()
p.fromJSON({_destroy: true})
equal p.get('shouldDestroy'), true
| 19891 | QUnit.module "Batman.Model: encoding/decoding to/from JSON",
setup: ->
class @Product extends Batman.Model
@encode 'name', 'cost'
@accessor 'excitingName',
get: -> @get('name').toUpperCase()
class @FlakyProduct extends @Product
@encode 'broken?'
test "keys marked for encoding should be encoded", ->
p = new @Product {name: "<NAME>", cost: 12.99}
deepEqual p.toJSON(), {name: "<NAME>", cost: 12.99}
test "undefined keys marked for encoding shouldn't be encoded", ->
p = new @Product {name: "<NAME>"}
deepEqual p.toJSON(), {name: "<NAME>"}
test "accessor keys marked for encoding should be encoded", ->
class TestProduct extends @Product
@encode 'excitingName'
p = new TestProduct {name: "<NAME>", cost: 12.99}
deepEqual p.toJSON(), {name: "<NAME>", cost: 12.99, excitingName: '<NAME>'}
test "keys marked for decoding should be decoded", ->
p = new @Product
json = {name: "<NAME>", cost: 12.99}
p.fromJSON(json)
equal p.get('name'), "<NAME>"
equal p.get('cost'), 12.99
test "falsy keys marked for decoding should be decoded", ->
p = new @Product
json = {cost: 0}
p.fromJSON(json)
equal p.get('cost'), 0
test "keys not marked for encoding shouldn't be encoded", ->
p = new @Product {name: "<NAME>", cost: 12.99, wibble: 'wobble'}
deepEqual p.toJSON(), {name: "<NAME>", cost: 12.99}
test "keys not marked for decoding shouldn't be decoded", ->
p = new @Product
json = {name: "<NAME>", cost: 12.99, wibble: 'wobble'}
p.fromJSON(json)
equal p.get('name'), "Cool Snowboard"
equal p.get('cost'), 12.99
equal p.get('wibble'), undefined
test "models shouldn't encode their primary keys by default", ->
p = new @Product {id: 10, name: "Cool snowboard"}
deepEqual p.toJSON(), {name: "Cool snowboard"}
test "models without any decoders should decode all keys", ->
class TestProduct extends Batman.Model
# No encoders.
oldDecoders = Batman.Model::_batman.encoders
Batman.Model::_batman.encoders = new Batman.SimpleHash
p = new TestProduct
Batman.developer.suppress ->
p.fromJSON {name: "Cool Snowboard", cost: 12.99, rails_is_silly: "yup"}
equal p.get('name'), "Cool Snowboard"
equal p.get('cost'), 12.99
equal p.get('rails_is_silly'), 'yup'
Batman.Model::_batman.encoders = oldDecoders
test "key ending with ? marked for encoding should be encoded", ->
p = new @FlakyProduct {name: "Vintage Snowboard", cost: 122.99, "broken?": true}
deepEqual p.toJSON(), {name: "Vintage Snowboard", cost: 122.99, "broken?": true}
test "key ending with ? marked for decoding should be decoded", ->
p = new @FlakyProduct
json = {name: "Vintage Snowboard", cost: 122.99, "broken?": true}
p.fromJSON(json)
ok p.get('broken?'), "Cool Snowboard"
QUnit.module "Batman.Model: encoding/decoding to/from JSON with custom primary Key",
setup: ->
class @Product extends Batman.Model
@set 'primaryKey', '_id'
test "undefined primaryKey shouldn't be encoded", ->
p = new @Product
deepEqual p.toJSON(), {}
test "defined primaryKey shouldn't be encoded", ->
p = new @Product("deadbeef")
deepEqual p.toJSON(), {}
test "defined primaryKey should be decoded", ->
json = {_id: "deadbeef"}
p = new @Product()
p.fromJSON(json)
equal p.get('id'), "deadbeef"
equal p.get('_id'), "deadbeef"
test "the old primaryKey should not be decoded", ->
json = {id: 10}
p = new @Product()
p.fromJSON(json)
equal p.get('id'), undefined
equal p.get('_id'), undefined
test "primary key encoding can be opted into", ->
@Product.encode '_id' # Tell the product to both encode and decode '_id'
p = new @Product("deadbeef")
deepEqual p.toJSON(), {_id: "deadbeef"}
QUnit.module "Batman.Model: encoding: custom encoders/decoders",
setup: ->
class @Product extends Batman.Model
@encode 'name', (unencoded) -> unencoded.toUpperCase()
@encode 'date',
encode: (unencoded) -> "zzz"
decode: (encoded) -> "yyy"
test "custom encoders with an encode and a decode implementation should be recognized", ->
p = new @Product(date: "clobbered")
deepEqual p.toJSON(), {date: "zzz"}
json = p = new @Product
p.fromJSON({date: "clobbered"})
equal p.get('date'), "yyy"
test "custom encoders should receive the value to be encoded, the key it's from, the JSON being built, and the source object", 4, ->
@Product.encode 'date',
encode: (val, key, object, record) ->
equal val, "some date"
equal key, "date"
deepEqual object, {}
equal record, p
return 'foo bar'
p = new @Product(date: "some date")
p.toJSON()
test "custom decoders should receive the value to decode, the key in the data it's from, the JSON being decoded, the object about to be mixed in, and the record", 5, ->
@Product.encode 'date',
decode: (val, key, json, object, record) ->
equal val, "some date"
equal key, 'date'
deepEqual json, {date: "some date"}
deepEqual object, {}
equal record, p
p = new @Product()
p.fromJSON(date: "some date")
test "passing a function should shortcut to passing an encoder", ->
p = new @Product(name: "snowboard")
deepEqual p.toJSON(), {name: "SNOWBOARD"}
test "passing false should not attach an encoder or decoder for that key", ->
class TestProduct extends Batman.Model
@encode 'name',
encode: false
decode: (x) -> x
@encode 'date',
encode: (x) -> x
decode: false
decoded = new TestProduct()
decoded.fromJSON(name: "snowboard", date: "10/10/2010")
equal decoded.get('date'), undefined
equal decoded.get('name'), "snowboard"
encoded = new TestProduct(name: "snowboard", date: "10/10/2010")
deepEqual encoded.toJSON(), {date: "10/10/2010"}
test "passing false for an encoder should never do a get on the property", ->
getSpy = createSpy()
class TestProduct extends Batman.Model
@encode 'name',
encode: false
decode: (x) -> x
@accessor 'name',
get: getSpy
encoded = new TestProduct(name: "snowboard", date: "10/10/2010")
encoded.toJSON()
ok !getSpy.called
test "passing an as option should put the encoded value in that key in the outgoing json", ->
class TestProduct extends Batman.Model
@encode 'shouldDestroy', {as: '_destroy'}
p = new TestProduct(shouldDestroy: true)
deepEqual p.toJSON(), {_destroy: true}
test "passing an as option should put the dencoded value in that key on the record", ->
class TestProduct extends Batman.Model
@encode 'shouldDestroy', {as: '_destroy'}
p = new TestProduct()
p.fromJSON({_destroy: true})
equal p.get('shouldDestroy'), true
| true | QUnit.module "Batman.Model: encoding/decoding to/from JSON",
setup: ->
class @Product extends Batman.Model
@encode 'name', 'cost'
@accessor 'excitingName',
get: -> @get('name').toUpperCase()
class @FlakyProduct extends @Product
@encode 'broken?'
test "keys marked for encoding should be encoded", ->
p = new @Product {name: "PI:NAME:<NAME>END_PI", cost: 12.99}
deepEqual p.toJSON(), {name: "PI:NAME:<NAME>END_PI", cost: 12.99}
test "undefined keys marked for encoding shouldn't be encoded", ->
p = new @Product {name: "PI:NAME:<NAME>END_PI"}
deepEqual p.toJSON(), {name: "PI:NAME:<NAME>END_PI"}
test "accessor keys marked for encoding should be encoded", ->
class TestProduct extends @Product
@encode 'excitingName'
p = new TestProduct {name: "PI:NAME:<NAME>END_PI", cost: 12.99}
deepEqual p.toJSON(), {name: "PI:NAME:<NAME>END_PI", cost: 12.99, excitingName: 'PI:NAME:<NAME>END_PI'}
test "keys marked for decoding should be decoded", ->
p = new @Product
json = {name: "PI:NAME:<NAME>END_PI", cost: 12.99}
p.fromJSON(json)
equal p.get('name'), "PI:NAME:<NAME>END_PI"
equal p.get('cost'), 12.99
test "falsy keys marked for decoding should be decoded", ->
p = new @Product
json = {cost: 0}
p.fromJSON(json)
equal p.get('cost'), 0
test "keys not marked for encoding shouldn't be encoded", ->
p = new @Product {name: "PI:NAME:<NAME>END_PI", cost: 12.99, wibble: 'wobble'}
deepEqual p.toJSON(), {name: "PI:NAME:<NAME>END_PI", cost: 12.99}
test "keys not marked for decoding shouldn't be decoded", ->
p = new @Product
json = {name: "PI:NAME:<NAME>END_PI", cost: 12.99, wibble: 'wobble'}
p.fromJSON(json)
equal p.get('name'), "Cool Snowboard"
equal p.get('cost'), 12.99
equal p.get('wibble'), undefined
test "models shouldn't encode their primary keys by default", ->
p = new @Product {id: 10, name: "Cool snowboard"}
deepEqual p.toJSON(), {name: "Cool snowboard"}
test "models without any decoders should decode all keys", ->
class TestProduct extends Batman.Model
# No encoders.
oldDecoders = Batman.Model::_batman.encoders
Batman.Model::_batman.encoders = new Batman.SimpleHash
p = new TestProduct
Batman.developer.suppress ->
p.fromJSON {name: "Cool Snowboard", cost: 12.99, rails_is_silly: "yup"}
equal p.get('name'), "Cool Snowboard"
equal p.get('cost'), 12.99
equal p.get('rails_is_silly'), 'yup'
Batman.Model::_batman.encoders = oldDecoders
test "key ending with ? marked for encoding should be encoded", ->
p = new @FlakyProduct {name: "Vintage Snowboard", cost: 122.99, "broken?": true}
deepEqual p.toJSON(), {name: "Vintage Snowboard", cost: 122.99, "broken?": true}
test "key ending with ? marked for decoding should be decoded", ->
p = new @FlakyProduct
json = {name: "Vintage Snowboard", cost: 122.99, "broken?": true}
p.fromJSON(json)
ok p.get('broken?'), "Cool Snowboard"
QUnit.module "Batman.Model: encoding/decoding to/from JSON with custom primary Key",
setup: ->
class @Product extends Batman.Model
@set 'primaryKey', '_id'
test "undefined primaryKey shouldn't be encoded", ->
p = new @Product
deepEqual p.toJSON(), {}
test "defined primaryKey shouldn't be encoded", ->
p = new @Product("deadbeef")
deepEqual p.toJSON(), {}
test "defined primaryKey should be decoded", ->
json = {_id: "deadbeef"}
p = new @Product()
p.fromJSON(json)
equal p.get('id'), "deadbeef"
equal p.get('_id'), "deadbeef"
test "the old primaryKey should not be decoded", ->
json = {id: 10}
p = new @Product()
p.fromJSON(json)
equal p.get('id'), undefined
equal p.get('_id'), undefined
test "primary key encoding can be opted into", ->
@Product.encode '_id' # Tell the product to both encode and decode '_id'
p = new @Product("deadbeef")
deepEqual p.toJSON(), {_id: "deadbeef"}
QUnit.module "Batman.Model: encoding: custom encoders/decoders",
setup: ->
class @Product extends Batman.Model
@encode 'name', (unencoded) -> unencoded.toUpperCase()
@encode 'date',
encode: (unencoded) -> "zzz"
decode: (encoded) -> "yyy"
test "custom encoders with an encode and a decode implementation should be recognized", ->
p = new @Product(date: "clobbered")
deepEqual p.toJSON(), {date: "zzz"}
json = p = new @Product
p.fromJSON({date: "clobbered"})
equal p.get('date'), "yyy"
test "custom encoders should receive the value to be encoded, the key it's from, the JSON being built, and the source object", 4, ->
@Product.encode 'date',
encode: (val, key, object, record) ->
equal val, "some date"
equal key, "date"
deepEqual object, {}
equal record, p
return 'foo bar'
p = new @Product(date: "some date")
p.toJSON()
test "custom decoders should receive the value to decode, the key in the data it's from, the JSON being decoded, the object about to be mixed in, and the record", 5, ->
@Product.encode 'date',
decode: (val, key, json, object, record) ->
equal val, "some date"
equal key, 'date'
deepEqual json, {date: "some date"}
deepEqual object, {}
equal record, p
p = new @Product()
p.fromJSON(date: "some date")
test "passing a function should shortcut to passing an encoder", ->
p = new @Product(name: "snowboard")
deepEqual p.toJSON(), {name: "SNOWBOARD"}
test "passing false should not attach an encoder or decoder for that key", ->
class TestProduct extends Batman.Model
@encode 'name',
encode: false
decode: (x) -> x
@encode 'date',
encode: (x) -> x
decode: false
decoded = new TestProduct()
decoded.fromJSON(name: "snowboard", date: "10/10/2010")
equal decoded.get('date'), undefined
equal decoded.get('name'), "snowboard"
encoded = new TestProduct(name: "snowboard", date: "10/10/2010")
deepEqual encoded.toJSON(), {date: "10/10/2010"}
test "passing false for an encoder should never do a get on the property", ->
getSpy = createSpy()
class TestProduct extends Batman.Model
@encode 'name',
encode: false
decode: (x) -> x
@accessor 'name',
get: getSpy
encoded = new TestProduct(name: "snowboard", date: "10/10/2010")
encoded.toJSON()
ok !getSpy.called
test "passing an as option should put the encoded value in that key in the outgoing json", ->
class TestProduct extends Batman.Model
@encode 'shouldDestroy', {as: '_destroy'}
p = new TestProduct(shouldDestroy: true)
deepEqual p.toJSON(), {_destroy: true}
test "passing an as option should put the dencoded value in that key on the record", ->
class TestProduct extends Batman.Model
@encode 'shouldDestroy', {as: '_destroy'}
p = new TestProduct()
p.fromJSON({_destroy: true})
equal p.get('shouldDestroy'), true
|
[
{
"context": "N.PASSWORD': 'Password'\n 'APP.LOGIN.REPEAT_PASSWORD': ",
"end": 9242,
"score": 0.9946271777153015,
"start": 9234,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "N.REPEAT_PASSWORD': ... | frontend/common/translations/en-us.coffee | Contactis/translation-manager | 0 | # Translation en-US
# =================
translationApp.config( [
'$translateProvider'
($translateProvider) ->
$translateProvider.translations('en-us', {
# ## Pluralizations
# **Pluralization** according to current language.
# More info on how to translate (what formats are available for current language) you'll find in
# [THIS WEBSITE](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
# If nothing set it'll show default strings in HTML templates
# ### Common phrases
# This section contains general phrases used in project
'PROJECT.FULL_NAME': 'Translation manager'
'GENERAL.PROJECT': 'Project'
'GENERAL.CHANGE_PROJECT': 'Change project'
'GENERAL.LOGIN': 'Login'
'GENERAL.LOG_IN': 'Log in'
'GENERAL.LOG_OUT': 'Log out'
'GENERAL.SAVE': 'Save'
'GENERAL.SAVE_AND_CLOSE': 'Save and colose'
'GENERAL.REMOVE': 'Remove'
'GENERAL.CREATE': 'Create'
'GENERAL.CANCEL': 'Cancel'
'GENERAL.CLEAN_FORM': 'Clean form'
'GENERAL.PENDING': 'Pending'
'GENERAL.LOADING': 'Loading'
'GENERAL.SETTINGS': 'Settings'
'GENERAL.MODIFY': 'Modify'
'GENERAL.VERIFIED': 'Verified'
'GENERAL.VERIFY': 'Verify'
'GENERAL.NOT_VERIFIED': 'Not verified'
'GENERAL.DELETE': 'Delete'
'GENERAL.CLEAR': 'Clear'
'GENERAL.YES': 'Yes'
'GENERAL.NO': 'No'
'GENERAL.TRY_AGAIN': 'Try again'
'GENERAL.USER_UNKNOWN': 'User unknown'
'GENERAL.CHANGE': 'Change'
'GENERAL.SAVE_CHANGES': 'Save changes'
'GENERAL.NOT_DEFINED': 'Not defined'
'GENERAL.NAME_NOT_DEFINED': 'Name not defined'
'GENERAL.EDIT': 'Edit'
# ### Page naming
'PAGE.404.TITLE': '404'
'PAGE.LOGIN.TITLE': 'Login'
'PAGE.HELP.TITLE': 'Help'
'PAGE.DASHBOARD.TITLE': 'Dashboard'
'PAGE.TRANSLATOR.TITLE': 'Translator view'
'PAGE.PROGRAMMER.TITLE': 'Programmer view'
'PAGE.MANAGER.TITLE': 'Manager view'
'PAGE.PROJECT_MANAGEMENT.TITLE': 'Project management'
'PAGE.PROJECT_MANAGEMENT.NEW_PROJECT.TITLE': 'New project'
'PAGE.PROJECT_MANAGEMENT.PROJECT_SETTINGS.TITLE': 'Project settings'
'PAGE.PROJECT_MANAGEMENT.USER_ASSIGNMENT.TITLE': 'User assignment'
'PAGE.PROJECT_MANAGEMENT.PROJECT_EXPORTER.TITLE': 'Project exporter'
# ### Backend messages
# ## Frontend messages
'APP.FRONTEND_MESSAGES.THIS_FEATURE_IS_NOT_YET_READY':
'This feature is not yet ready. Apologize for any inconvenience.'
'APP.FRONTEND_MESSAGES.INFO': 'Info'
'APP.FRONTEND_MESSAGES.SUCCESSFULLY_SAVED_THE_DATA': 'Successfully saved the data.'
'APP.FRONTEND_MESSAGES.ERROR_OCCURED_WHILE_SAVING_THE_DATA': 'Error occured while saving the data.'
'APP.FRONTEND_MESSAGES.ERROR_OCCURED_WHILE_GETTING_LANGUAGES_DATA':
'Error occured while getting languages data.'
'APP.FRONTEND_MESSAGES.TRY_AGAIN_LATER': 'Try again later'
'APP.FRONTEND_MESSAGES.WAITING_FOR_LOADING_DATA': 'Waiting for loading data'
'APP.FRONTEND_MESSAGES.EXPECTED_PROVIDING_THE_FUNCTIONALITY_IS_@_MILESTONE':
'Expected providing the functionality is for {{name}} milestone.'
# authorization
'APP.FRONTEND_MESSAGES.AUTHORIZATION.YOU_HAD_BEEN_LOGGED_OUT':
'You had been logged out.'
'APP.FRONTEND_MESSAGES.AUTHORIZATION.ACCESS_UNDEFINED_FOR_THIS_STATE':
'Access undefined for this state'
'APP.FRONTEND_MESSAGES.AUTHORIZATION.SEEMS_LIKE_YOU_DONT_HAVE_PERMISSIONS':
'Seems like you don\'t have permissions to access that page.'
# login
'APP.FRONTEND_MESSAGES.LOGIN.WELCOME': 'Welcome!'
'APP.FRONTEND_MESSAGES.LOGIN.REGISTRATION_ERROR': 'Registration error'
'APP.FRONTEND_MESSAGES.LOGIN.LOGGING_ERROR': 'Logging error'
'APP.FRONTEND_MESSAGES.LOGIN.PASSWORDS_DONT_MATCH': 'Passwords don\'t match. Try again'
# userAssignment
'APP.FRONTEND_MESSAGES.USER_ASSIGNMENT.REMOVED_ENTITIES_SUCCESSFULLY':
'All related entities removed successfully'
'APP.FRONTEND_MESSAGES.USER_ASSIGNMENT.REMOVED_ENTITIES_FAILED':
'Removing entities failed'
# programming-view
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.LOADING_TRANSLATION_KEYS_FAILED':
'Problem with loading translation keys'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.INDEX_KEY_NAME': 'Index key name'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.IS_PLURAL': 'Is plural'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.BASIC_TRANSLATION': 'Basic translation'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.CONTEXT_DESCRIPTION': 'Context description'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.ADD_NEW_TRANSLATION_KEY': 'Add new translation key'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.NO_INDEX_KEYS_AVAILABLE_FOR_CURRENT_PROJECT':
'No index keys available for current project'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.ADD_NEW_INDEX_KEY':
'Add new index key, to see results.'
# project-exporter
'APP.FRONTEND_MESSAGES.PROJECT_EXPORTER.SUCCESSFULLY_GENERATE_LIST' : 'Successfully generate list'
# new project (view)
'APP.FRONTEND_MESSAGES.NEW_PROJECT.PROJECT_REMOVED_SUCCESSFULLY' : 'Project removed successfully'
'APP.FRONTEND_MESSAGES.NEW_PROJECT.ERROR_OCCURED_WHILE_REMOVING_PROJECT' : 'Error occured while removeing project'
# dialog addNewProject
'APP.FRONTEND_MESSAGES.ADD_NEW_PROJECT.PROJECT_CREATED_SUCCESSFULLY' : 'Project created successfully'
'APP.FRONTEND_MESSAGES.ERROR_OCCURED_WHILE_GETTING_PROJECTS_DATA' :
'Error occured while getting projects data'
'APP.FRONTEND_MESSAGES.ADD_NEW_PROJECT.PROBLEM_OCCURED_WHILE_CREATING_NEW_PROJECT' :
'Problem occured while creating new project'
'APP.FRONTEND_MESSAGES.ADD_NEW_PROJECT.PROBLEM_OCCURED_WHILE_CREATING_PROJECT_LANGUAGE_ENTRY':
'Problem occured while creating project-language entry'
# ## dialogs
# ### common/templates/dialog/translation.jade
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.ADD_NEW_TRANSLATION_KEY':
'Add new translation key'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.KEY_INDEX_TYPE':
'Key index type'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.STRING':
'String'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.PLURAL':
'Plural'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.PLURAL_FORMS':
'Plural forms'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.NAMESPACE':
'Namespace'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.KEY_INDEX':
'Key index'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.DEFAULT_TRANSLATION':
'Default translation'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.LIVE_PREVIEW_RESULT':
'Live preview result'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.CONTEXT_DESCRIPTION':
'Context description'
# common/templates/dialog/addNewProject.jade
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.ADD_NEW_PROJECT': 'Add new project'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAME': 'Project name'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAME_PLACEHOLDER': 'ex: Supersonic cars'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAMESPACE':
'Project namespace'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAMESPACE_PLACEHOLDER':
'This prefix will be pasted before each one key-index\'s namespace for this project'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_DESCRIPTION': 'Project description'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_DESCRIPTION_PLACEHOLDER':
'Simple description better describing this project'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.DEFAULT_LANGUAGE' : 'Default language'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.SELECT_LANGUAGE': '<< Select a language >>'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.VALIDATION.PROJECT_NAME_REQUIRED':
'Project name required'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.VALIDATION.PROJECT_DEFAULT_LANGUAGE_REQUIRED' :
'Project default language required'
# ## app/dashboard.jade
# ## app/login.jade
'APP.LOGIN.SING_IN': 'Sing in'
'APP.LOGIN.REGISTER': 'Register'
'APP.LOGIN.EMAIL': 'E-mail'
'APP.LOGIN.PASSWORD': 'Password'
'APP.LOGIN.REPEAT_PASSWORD': 'Repeat password'
'APP.LOGIN.FIRST_NAME': 'First name'
'APP.LOGIN.LAST_NAME': 'Last name'
'APP.LOGIN.REGISTER': 'Register'
'APP.LOGIN.COMPLETE': 'Complete'
'APP.LOGIN.REMEMBER_ME': 'Remember me'
'APP.LOGIN.LOGIN_WITH_YOUR_TRANSLATION_MANAGER_ACCOUNT': 'Login with your translation manager account'
'APP.LOGIN.USERNAME': 'Username'
# ## app/project-manager/programmer-view/programmer-view.coffee
'APP.PROJECT_MANAGER.PROGRAMMER_VIEW.': 'Nothing yet'
# ## app/project-manager/admin/userAssignment.jade
'APP.ADMIN.USER_ASSIGNMENT.GENETAL_DESCRIPTION': 'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS': 'Project users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS_GENERAL_DESCRIPTION':
'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.AVAILABLE_USERS': 'Available users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.ASSIGNED_USERS': 'Assigned Users'
# ## app/project-manager/admin/projectExporter.jade
'APP.ADMIN.PROJECT_EXPORTER.TITLE': 'Project Exporter'
'APP.ADMIN.PROJECT_EXPORTER.GENETAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_EXPORTER.EXPORTER.TITLE': 'Exporter'
'APP.ADMIN.PROJECT_EXPORTER.EXPORTER.GENETAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_EXPORTER.EXPORTER.WHICH_LANGUAGE_EXPORT': \
'Which language you want to export for current project',
# ## 2app/project-manager/admin/newProject/newProject.jade
'APP.ADMIN.NEW_PROJECT.TITLE': 'Add new project',
'APP.ADMIN.NEW_PROJECT.GENETAL_DESCRIPTION': 'Manage of adding or removing projects'
'APP.ADMIN.NEW_PROJECT.FRONTEND_MESSAGES.NO_PROJECTS_AVAILABLE': 'No projects available',
'APP.ADMIN.NEW_PROJECT.FRONTEND_MESSAGES.ADD_NEW_PROJECT': 'Add new project'
'APP.ADMIN.NEW_PROJECT.TABLE.ID': 'Id'
'APP.ADMIN.NEW_PROJECT.TABLE.PROJECT_NAME': 'Project name'
'APP.ADMIN.NEW_PROJECT.TABLE.PROJECT_DESCRIPTION': 'Project description'
'APP.ADMIN.NEW_PROJECT.TABLE.PREFIX_NAMESPACE': 'Prefix namespace'
'APP.ADMIN.NEW_PROJECT.TABLE.DEFAULT_LANGUAGE': 'Default language'
'APP.ADMIN.NEW_PROJECT.TABLE.DELETE_PROJECT': 'Delete project'
'APP.ADMIN.NEW_PROJECT.DELETE': 'Delete'
# ## app/project-manager/admin/projectSettings.jade
'APP.ADMIN.PROJECT_SETTINGS.GENETAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_ABOUT': 'About'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_DATE_AND_TIME': 'Date & Time'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_WORKFLOW': 'Workflow'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_OUTPUT_CASE_TYPE_LABEL': 'Output Case type'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_NAMESPACE_LABEL': 'Separator for namespaces'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_NAMESPACE_PLACEHOLDER': 'Type a namespace separator character'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_REQUIRED': 'Namespace field is required'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_IS_NOT_VALID': 'Namespace field is not valid'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_IS_VALID': 'Namespace field is valid'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_MIN_CHARACTER': 'Namespace field must contain minimum 1 character'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_NAME_LABEL': 'Project name'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_NAME_PLACEHOLDER': 'Type name for the project'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DESCRITPION_LABEL': 'Project description'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DESCRITPION_PLACEHOLDER':
'Type short description about what is the project'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_PREFIX_NAMESPACE_LABEL': 'Prefix namespace'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_PREFIX_NAMESPACE_PLACEHOLDER':
'This prefix will be pasted before each one key-index\'s namespace for this project'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DEFAULT_LANGUAGE_LABEL': 'Project default language'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DEFAULT_LANGUAGE_PLACEHOLDER':
'Select or search default language for the project'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_ABOUT_GENERAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_DATE_AND_TIME_GENERAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_WORKFLOW_GENERAL_DESCRIPTION':
'All stuff related to building translations'
# app/project-manager/admin/userAssignment.jade
'APP.ADMIN.USER_ASSIGNMENT.GENETAL_DESCRIPTION': 'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS': 'Project users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS_GENERAL_DESCRIPTION':
'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.AVAILABLE_USERS': 'Available users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.ASSIGNED_USERS': 'Assigned Users'
# common/directives/trWaitingSpinnerDiv/trWaitingSpinnerDiv.jade
})
])
| 107878 | # Translation en-US
# =================
translationApp.config( [
'$translateProvider'
($translateProvider) ->
$translateProvider.translations('en-us', {
# ## Pluralizations
# **Pluralization** according to current language.
# More info on how to translate (what formats are available for current language) you'll find in
# [THIS WEBSITE](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
# If nothing set it'll show default strings in HTML templates
# ### Common phrases
# This section contains general phrases used in project
'PROJECT.FULL_NAME': 'Translation manager'
'GENERAL.PROJECT': 'Project'
'GENERAL.CHANGE_PROJECT': 'Change project'
'GENERAL.LOGIN': 'Login'
'GENERAL.LOG_IN': 'Log in'
'GENERAL.LOG_OUT': 'Log out'
'GENERAL.SAVE': 'Save'
'GENERAL.SAVE_AND_CLOSE': 'Save and colose'
'GENERAL.REMOVE': 'Remove'
'GENERAL.CREATE': 'Create'
'GENERAL.CANCEL': 'Cancel'
'GENERAL.CLEAN_FORM': 'Clean form'
'GENERAL.PENDING': 'Pending'
'GENERAL.LOADING': 'Loading'
'GENERAL.SETTINGS': 'Settings'
'GENERAL.MODIFY': 'Modify'
'GENERAL.VERIFIED': 'Verified'
'GENERAL.VERIFY': 'Verify'
'GENERAL.NOT_VERIFIED': 'Not verified'
'GENERAL.DELETE': 'Delete'
'GENERAL.CLEAR': 'Clear'
'GENERAL.YES': 'Yes'
'GENERAL.NO': 'No'
'GENERAL.TRY_AGAIN': 'Try again'
'GENERAL.USER_UNKNOWN': 'User unknown'
'GENERAL.CHANGE': 'Change'
'GENERAL.SAVE_CHANGES': 'Save changes'
'GENERAL.NOT_DEFINED': 'Not defined'
'GENERAL.NAME_NOT_DEFINED': 'Name not defined'
'GENERAL.EDIT': 'Edit'
# ### Page naming
'PAGE.404.TITLE': '404'
'PAGE.LOGIN.TITLE': 'Login'
'PAGE.HELP.TITLE': 'Help'
'PAGE.DASHBOARD.TITLE': 'Dashboard'
'PAGE.TRANSLATOR.TITLE': 'Translator view'
'PAGE.PROGRAMMER.TITLE': 'Programmer view'
'PAGE.MANAGER.TITLE': 'Manager view'
'PAGE.PROJECT_MANAGEMENT.TITLE': 'Project management'
'PAGE.PROJECT_MANAGEMENT.NEW_PROJECT.TITLE': 'New project'
'PAGE.PROJECT_MANAGEMENT.PROJECT_SETTINGS.TITLE': 'Project settings'
'PAGE.PROJECT_MANAGEMENT.USER_ASSIGNMENT.TITLE': 'User assignment'
'PAGE.PROJECT_MANAGEMENT.PROJECT_EXPORTER.TITLE': 'Project exporter'
# ### Backend messages
# ## Frontend messages
'APP.FRONTEND_MESSAGES.THIS_FEATURE_IS_NOT_YET_READY':
'This feature is not yet ready. Apologize for any inconvenience.'
'APP.FRONTEND_MESSAGES.INFO': 'Info'
'APP.FRONTEND_MESSAGES.SUCCESSFULLY_SAVED_THE_DATA': 'Successfully saved the data.'
'APP.FRONTEND_MESSAGES.ERROR_OCCURED_WHILE_SAVING_THE_DATA': 'Error occured while saving the data.'
'APP.FRONTEND_MESSAGES.ERROR_OCCURED_WHILE_GETTING_LANGUAGES_DATA':
'Error occured while getting languages data.'
'APP.FRONTEND_MESSAGES.TRY_AGAIN_LATER': 'Try again later'
'APP.FRONTEND_MESSAGES.WAITING_FOR_LOADING_DATA': 'Waiting for loading data'
'APP.FRONTEND_MESSAGES.EXPECTED_PROVIDING_THE_FUNCTIONALITY_IS_@_MILESTONE':
'Expected providing the functionality is for {{name}} milestone.'
# authorization
'APP.FRONTEND_MESSAGES.AUTHORIZATION.YOU_HAD_BEEN_LOGGED_OUT':
'You had been logged out.'
'APP.FRONTEND_MESSAGES.AUTHORIZATION.ACCESS_UNDEFINED_FOR_THIS_STATE':
'Access undefined for this state'
'APP.FRONTEND_MESSAGES.AUTHORIZATION.SEEMS_LIKE_YOU_DONT_HAVE_PERMISSIONS':
'Seems like you don\'t have permissions to access that page.'
# login
'APP.FRONTEND_MESSAGES.LOGIN.WELCOME': 'Welcome!'
'APP.FRONTEND_MESSAGES.LOGIN.REGISTRATION_ERROR': 'Registration error'
'APP.FRONTEND_MESSAGES.LOGIN.LOGGING_ERROR': 'Logging error'
'APP.FRONTEND_MESSAGES.LOGIN.PASSWORDS_DONT_MATCH': 'Passwords don\'t match. Try again'
# userAssignment
'APP.FRONTEND_MESSAGES.USER_ASSIGNMENT.REMOVED_ENTITIES_SUCCESSFULLY':
'All related entities removed successfully'
'APP.FRONTEND_MESSAGES.USER_ASSIGNMENT.REMOVED_ENTITIES_FAILED':
'Removing entities failed'
# programming-view
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.LOADING_TRANSLATION_KEYS_FAILED':
'Problem with loading translation keys'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.INDEX_KEY_NAME': 'Index key name'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.IS_PLURAL': 'Is plural'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.BASIC_TRANSLATION': 'Basic translation'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.CONTEXT_DESCRIPTION': 'Context description'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.ADD_NEW_TRANSLATION_KEY': 'Add new translation key'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.NO_INDEX_KEYS_AVAILABLE_FOR_CURRENT_PROJECT':
'No index keys available for current project'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.ADD_NEW_INDEX_KEY':
'Add new index key, to see results.'
# project-exporter
'APP.FRONTEND_MESSAGES.PROJECT_EXPORTER.SUCCESSFULLY_GENERATE_LIST' : 'Successfully generate list'
# new project (view)
'APP.FRONTEND_MESSAGES.NEW_PROJECT.PROJECT_REMOVED_SUCCESSFULLY' : 'Project removed successfully'
'APP.FRONTEND_MESSAGES.NEW_PROJECT.ERROR_OCCURED_WHILE_REMOVING_PROJECT' : 'Error occured while removeing project'
# dialog addNewProject
'APP.FRONTEND_MESSAGES.ADD_NEW_PROJECT.PROJECT_CREATED_SUCCESSFULLY' : 'Project created successfully'
'APP.FRONTEND_MESSAGES.ERROR_OCCURED_WHILE_GETTING_PROJECTS_DATA' :
'Error occured while getting projects data'
'APP.FRONTEND_MESSAGES.ADD_NEW_PROJECT.PROBLEM_OCCURED_WHILE_CREATING_NEW_PROJECT' :
'Problem occured while creating new project'
'APP.FRONTEND_MESSAGES.ADD_NEW_PROJECT.PROBLEM_OCCURED_WHILE_CREATING_PROJECT_LANGUAGE_ENTRY':
'Problem occured while creating project-language entry'
# ## dialogs
# ### common/templates/dialog/translation.jade
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.ADD_NEW_TRANSLATION_KEY':
'Add new translation key'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.KEY_INDEX_TYPE':
'Key index type'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.STRING':
'String'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.PLURAL':
'Plural'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.PLURAL_FORMS':
'Plural forms'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.NAMESPACE':
'Namespace'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.KEY_INDEX':
'Key index'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.DEFAULT_TRANSLATION':
'Default translation'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.LIVE_PREVIEW_RESULT':
'Live preview result'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.CONTEXT_DESCRIPTION':
'Context description'
# common/templates/dialog/addNewProject.jade
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.ADD_NEW_PROJECT': 'Add new project'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAME': 'Project name'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAME_PLACEHOLDER': 'ex: Supersonic cars'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAMESPACE':
'Project namespace'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAMESPACE_PLACEHOLDER':
'This prefix will be pasted before each one key-index\'s namespace for this project'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_DESCRIPTION': 'Project description'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_DESCRIPTION_PLACEHOLDER':
'Simple description better describing this project'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.DEFAULT_LANGUAGE' : 'Default language'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.SELECT_LANGUAGE': '<< Select a language >>'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.VALIDATION.PROJECT_NAME_REQUIRED':
'Project name required'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.VALIDATION.PROJECT_DEFAULT_LANGUAGE_REQUIRED' :
'Project default language required'
# ## app/dashboard.jade
# ## app/login.jade
'APP.LOGIN.SING_IN': 'Sing in'
'APP.LOGIN.REGISTER': 'Register'
'APP.LOGIN.EMAIL': 'E-mail'
'APP.LOGIN.PASSWORD': '<PASSWORD>'
'APP.LOGIN.REPEAT_PASSWORD': '<PASSWORD>'
'APP.LOGIN.FIRST_NAME': 'First name'
'APP.LOGIN.LAST_NAME': 'Last name'
'APP.LOGIN.REGISTER': 'Register'
'APP.LOGIN.COMPLETE': 'Complete'
'APP.LOGIN.REMEMBER_ME': 'Remember me'
'APP.LOGIN.LOGIN_WITH_YOUR_TRANSLATION_MANAGER_ACCOUNT': 'Login with your translation manager account'
'APP.LOGIN.USERNAME': 'Username'
# ## app/project-manager/programmer-view/programmer-view.coffee
'APP.PROJECT_MANAGER.PROGRAMMER_VIEW.': 'Nothing yet'
# ## app/project-manager/admin/userAssignment.jade
'APP.ADMIN.USER_ASSIGNMENT.GENETAL_DESCRIPTION': 'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS': 'Project users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS_GENERAL_DESCRIPTION':
'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.AVAILABLE_USERS': 'Available users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.ASSIGNED_USERS': 'Assigned Users'
# ## app/project-manager/admin/projectExporter.jade
'APP.ADMIN.PROJECT_EXPORTER.TITLE': 'Project Exporter'
'APP.ADMIN.PROJECT_EXPORTER.GENETAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_EXPORTER.EXPORTER.TITLE': 'Exporter'
'APP.ADMIN.PROJECT_EXPORTER.EXPORTER.GENETAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_EXPORTER.EXPORTER.WHICH_LANGUAGE_EXPORT': \
'Which language you want to export for current project',
# ## 2app/project-manager/admin/newProject/newProject.jade
'APP.ADMIN.NEW_PROJECT.TITLE': 'Add new project',
'APP.ADMIN.NEW_PROJECT.GENETAL_DESCRIPTION': 'Manage of adding or removing projects'
'APP.ADMIN.NEW_PROJECT.FRONTEND_MESSAGES.NO_PROJECTS_AVAILABLE': 'No projects available',
'APP.ADMIN.NEW_PROJECT.FRONTEND_MESSAGES.ADD_NEW_PROJECT': 'Add new project'
'APP.ADMIN.NEW_PROJECT.TABLE.ID': 'Id'
'APP.ADMIN.NEW_PROJECT.TABLE.PROJECT_NAME': 'Project name'
'APP.ADMIN.NEW_PROJECT.TABLE.PROJECT_DESCRIPTION': 'Project description'
'APP.ADMIN.NEW_PROJECT.TABLE.PREFIX_NAMESPACE': 'Prefix namespace'
'APP.ADMIN.NEW_PROJECT.TABLE.DEFAULT_LANGUAGE': 'Default language'
'APP.ADMIN.NEW_PROJECT.TABLE.DELETE_PROJECT': 'Delete project'
'APP.ADMIN.NEW_PROJECT.DELETE': 'Delete'
# ## app/project-manager/admin/projectSettings.jade
'APP.ADMIN.PROJECT_SETTINGS.GENETAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_ABOUT': 'About'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_DATE_AND_TIME': 'Date & Time'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_WORKFLOW': 'Workflow'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_OUTPUT_CASE_TYPE_LABEL': 'Output Case type'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_NAMESPACE_LABEL': 'Separator for namespaces'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_NAMESPACE_PLACEHOLDER': 'Type a namespace separator character'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_REQUIRED': 'Namespace field is required'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_IS_NOT_VALID': 'Namespace field is not valid'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_IS_VALID': 'Namespace field is valid'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_MIN_CHARACTER': 'Namespace field must contain minimum 1 character'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_NAME_LABEL': 'Project name'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_NAME_PLACEHOLDER': 'Type name for the project'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DESCRITPION_LABEL': 'Project description'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DESCRITPION_PLACEHOLDER':
'Type short description about what is the project'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_PREFIX_NAMESPACE_LABEL': 'Prefix namespace'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_PREFIX_NAMESPACE_PLACEHOLDER':
'This prefix will be pasted before each one key-index\'s namespace for this project'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DEFAULT_LANGUAGE_LABEL': 'Project default language'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DEFAULT_LANGUAGE_PLACEHOLDER':
'Select or search default language for the project'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_ABOUT_GENERAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_DATE_AND_TIME_GENERAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_WORKFLOW_GENERAL_DESCRIPTION':
'All stuff related to building translations'
# app/project-manager/admin/userAssignment.jade
'APP.ADMIN.USER_ASSIGNMENT.GENETAL_DESCRIPTION': 'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS': 'Project users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS_GENERAL_DESCRIPTION':
'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.AVAILABLE_USERS': 'Available users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.ASSIGNED_USERS': 'Assigned Users'
# common/directives/trWaitingSpinnerDiv/trWaitingSpinnerDiv.jade
})
])
| true | # Translation en-US
# =================
translationApp.config( [
'$translateProvider'
($translateProvider) ->
$translateProvider.translations('en-us', {
# ## Pluralizations
# **Pluralization** according to current language.
# More info on how to translate (what formats are available for current language) you'll find in
# [THIS WEBSITE](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
# If nothing set it'll show default strings in HTML templates
# ### Common phrases
# This section contains general phrases used in project
'PROJECT.FULL_NAME': 'Translation manager'
'GENERAL.PROJECT': 'Project'
'GENERAL.CHANGE_PROJECT': 'Change project'
'GENERAL.LOGIN': 'Login'
'GENERAL.LOG_IN': 'Log in'
'GENERAL.LOG_OUT': 'Log out'
'GENERAL.SAVE': 'Save'
'GENERAL.SAVE_AND_CLOSE': 'Save and colose'
'GENERAL.REMOVE': 'Remove'
'GENERAL.CREATE': 'Create'
'GENERAL.CANCEL': 'Cancel'
'GENERAL.CLEAN_FORM': 'Clean form'
'GENERAL.PENDING': 'Pending'
'GENERAL.LOADING': 'Loading'
'GENERAL.SETTINGS': 'Settings'
'GENERAL.MODIFY': 'Modify'
'GENERAL.VERIFIED': 'Verified'
'GENERAL.VERIFY': 'Verify'
'GENERAL.NOT_VERIFIED': 'Not verified'
'GENERAL.DELETE': 'Delete'
'GENERAL.CLEAR': 'Clear'
'GENERAL.YES': 'Yes'
'GENERAL.NO': 'No'
'GENERAL.TRY_AGAIN': 'Try again'
'GENERAL.USER_UNKNOWN': 'User unknown'
'GENERAL.CHANGE': 'Change'
'GENERAL.SAVE_CHANGES': 'Save changes'
'GENERAL.NOT_DEFINED': 'Not defined'
'GENERAL.NAME_NOT_DEFINED': 'Name not defined'
'GENERAL.EDIT': 'Edit'
# ### Page naming
'PAGE.404.TITLE': '404'
'PAGE.LOGIN.TITLE': 'Login'
'PAGE.HELP.TITLE': 'Help'
'PAGE.DASHBOARD.TITLE': 'Dashboard'
'PAGE.TRANSLATOR.TITLE': 'Translator view'
'PAGE.PROGRAMMER.TITLE': 'Programmer view'
'PAGE.MANAGER.TITLE': 'Manager view'
'PAGE.PROJECT_MANAGEMENT.TITLE': 'Project management'
'PAGE.PROJECT_MANAGEMENT.NEW_PROJECT.TITLE': 'New project'
'PAGE.PROJECT_MANAGEMENT.PROJECT_SETTINGS.TITLE': 'Project settings'
'PAGE.PROJECT_MANAGEMENT.USER_ASSIGNMENT.TITLE': 'User assignment'
'PAGE.PROJECT_MANAGEMENT.PROJECT_EXPORTER.TITLE': 'Project exporter'
# ### Backend messages
# ## Frontend messages
'APP.FRONTEND_MESSAGES.THIS_FEATURE_IS_NOT_YET_READY':
'This feature is not yet ready. Apologize for any inconvenience.'
'APP.FRONTEND_MESSAGES.INFO': 'Info'
'APP.FRONTEND_MESSAGES.SUCCESSFULLY_SAVED_THE_DATA': 'Successfully saved the data.'
'APP.FRONTEND_MESSAGES.ERROR_OCCURED_WHILE_SAVING_THE_DATA': 'Error occured while saving the data.'
'APP.FRONTEND_MESSAGES.ERROR_OCCURED_WHILE_GETTING_LANGUAGES_DATA':
'Error occured while getting languages data.'
'APP.FRONTEND_MESSAGES.TRY_AGAIN_LATER': 'Try again later'
'APP.FRONTEND_MESSAGES.WAITING_FOR_LOADING_DATA': 'Waiting for loading data'
'APP.FRONTEND_MESSAGES.EXPECTED_PROVIDING_THE_FUNCTIONALITY_IS_@_MILESTONE':
'Expected providing the functionality is for {{name}} milestone.'
# authorization
'APP.FRONTEND_MESSAGES.AUTHORIZATION.YOU_HAD_BEEN_LOGGED_OUT':
'You had been logged out.'
'APP.FRONTEND_MESSAGES.AUTHORIZATION.ACCESS_UNDEFINED_FOR_THIS_STATE':
'Access undefined for this state'
'APP.FRONTEND_MESSAGES.AUTHORIZATION.SEEMS_LIKE_YOU_DONT_HAVE_PERMISSIONS':
'Seems like you don\'t have permissions to access that page.'
# login
'APP.FRONTEND_MESSAGES.LOGIN.WELCOME': 'Welcome!'
'APP.FRONTEND_MESSAGES.LOGIN.REGISTRATION_ERROR': 'Registration error'
'APP.FRONTEND_MESSAGES.LOGIN.LOGGING_ERROR': 'Logging error'
'APP.FRONTEND_MESSAGES.LOGIN.PASSWORDS_DONT_MATCH': 'Passwords don\'t match. Try again'
# userAssignment
'APP.FRONTEND_MESSAGES.USER_ASSIGNMENT.REMOVED_ENTITIES_SUCCESSFULLY':
'All related entities removed successfully'
'APP.FRONTEND_MESSAGES.USER_ASSIGNMENT.REMOVED_ENTITIES_FAILED':
'Removing entities failed'
# programming-view
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.LOADING_TRANSLATION_KEYS_FAILED':
'Problem with loading translation keys'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.INDEX_KEY_NAME': 'Index key name'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.IS_PLURAL': 'Is plural'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.BASIC_TRANSLATION': 'Basic translation'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.CONTEXT_DESCRIPTION': 'Context description'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.ADD_NEW_TRANSLATION_KEY': 'Add new translation key'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.NO_INDEX_KEYS_AVAILABLE_FOR_CURRENT_PROJECT':
'No index keys available for current project'
'APP.FRONTEND_MESSAGES.PROGRAMMER_VIEW.ADD_NEW_INDEX_KEY':
'Add new index key, to see results.'
# project-exporter
'APP.FRONTEND_MESSAGES.PROJECT_EXPORTER.SUCCESSFULLY_GENERATE_LIST' : 'Successfully generate list'
# new project (view)
'APP.FRONTEND_MESSAGES.NEW_PROJECT.PROJECT_REMOVED_SUCCESSFULLY' : 'Project removed successfully'
'APP.FRONTEND_MESSAGES.NEW_PROJECT.ERROR_OCCURED_WHILE_REMOVING_PROJECT' : 'Error occured while removeing project'
# dialog addNewProject
'APP.FRONTEND_MESSAGES.ADD_NEW_PROJECT.PROJECT_CREATED_SUCCESSFULLY' : 'Project created successfully'
'APP.FRONTEND_MESSAGES.ERROR_OCCURED_WHILE_GETTING_PROJECTS_DATA' :
'Error occured while getting projects data'
'APP.FRONTEND_MESSAGES.ADD_NEW_PROJECT.PROBLEM_OCCURED_WHILE_CREATING_NEW_PROJECT' :
'Problem occured while creating new project'
'APP.FRONTEND_MESSAGES.ADD_NEW_PROJECT.PROBLEM_OCCURED_WHILE_CREATING_PROJECT_LANGUAGE_ENTRY':
'Problem occured while creating project-language entry'
# ## dialogs
# ### common/templates/dialog/translation.jade
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.ADD_NEW_TRANSLATION_KEY':
'Add new translation key'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.KEY_INDEX_TYPE':
'Key index type'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.STRING':
'String'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.PLURAL':
'Plural'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.PLURAL_FORMS':
'Plural forms'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.NAMESPACE':
'Namespace'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.KEY_INDEX':
'Key index'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.DEFAULT_TRANSLATION':
'Default translation'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.LIVE_PREVIEW_RESULT':
'Live preview result'
'COMMON.TEMPALTES.DIALOG.ADD_TRANSLATION_KEY_MODAL.CONTEXT_DESCRIPTION':
'Context description'
# common/templates/dialog/addNewProject.jade
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.ADD_NEW_PROJECT': 'Add new project'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAME': 'Project name'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAME_PLACEHOLDER': 'ex: Supersonic cars'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAMESPACE':
'Project namespace'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_NAMESPACE_PLACEHOLDER':
'This prefix will be pasted before each one key-index\'s namespace for this project'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_DESCRIPTION': 'Project description'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.PROJECT_DESCRIPTION_PLACEHOLDER':
'Simple description better describing this project'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.DEFAULT_LANGUAGE' : 'Default language'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.SELECT_LANGUAGE': '<< Select a language >>'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.VALIDATION.PROJECT_NAME_REQUIRED':
'Project name required'
'COMMON.TEMPALTES.DIALOG.ADD_NEW_PROJECT.VALIDATION.PROJECT_DEFAULT_LANGUAGE_REQUIRED' :
'Project default language required'
# ## app/dashboard.jade
# ## app/login.jade
'APP.LOGIN.SING_IN': 'Sing in'
'APP.LOGIN.REGISTER': 'Register'
'APP.LOGIN.EMAIL': 'E-mail'
'APP.LOGIN.PASSWORD': 'PI:PASSWORD:<PASSWORD>END_PI'
'APP.LOGIN.REPEAT_PASSWORD': 'PI:PASSWORD:<PASSWORD>END_PI'
'APP.LOGIN.FIRST_NAME': 'First name'
'APP.LOGIN.LAST_NAME': 'Last name'
'APP.LOGIN.REGISTER': 'Register'
'APP.LOGIN.COMPLETE': 'Complete'
'APP.LOGIN.REMEMBER_ME': 'Remember me'
'APP.LOGIN.LOGIN_WITH_YOUR_TRANSLATION_MANAGER_ACCOUNT': 'Login with your translation manager account'
'APP.LOGIN.USERNAME': 'Username'
# ## app/project-manager/programmer-view/programmer-view.coffee
'APP.PROJECT_MANAGER.PROGRAMMER_VIEW.': 'Nothing yet'
# ## app/project-manager/admin/userAssignment.jade
'APP.ADMIN.USER_ASSIGNMENT.GENETAL_DESCRIPTION': 'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS': 'Project users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS_GENERAL_DESCRIPTION':
'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.AVAILABLE_USERS': 'Available users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.ASSIGNED_USERS': 'Assigned Users'
# ## app/project-manager/admin/projectExporter.jade
'APP.ADMIN.PROJECT_EXPORTER.TITLE': 'Project Exporter'
'APP.ADMIN.PROJECT_EXPORTER.GENETAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_EXPORTER.EXPORTER.TITLE': 'Exporter'
'APP.ADMIN.PROJECT_EXPORTER.EXPORTER.GENETAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_EXPORTER.EXPORTER.WHICH_LANGUAGE_EXPORT': \
'Which language you want to export for current project',
# ## 2app/project-manager/admin/newProject/newProject.jade
'APP.ADMIN.NEW_PROJECT.TITLE': 'Add new project',
'APP.ADMIN.NEW_PROJECT.GENETAL_DESCRIPTION': 'Manage of adding or removing projects'
'APP.ADMIN.NEW_PROJECT.FRONTEND_MESSAGES.NO_PROJECTS_AVAILABLE': 'No projects available',
'APP.ADMIN.NEW_PROJECT.FRONTEND_MESSAGES.ADD_NEW_PROJECT': 'Add new project'
'APP.ADMIN.NEW_PROJECT.TABLE.ID': 'Id'
'APP.ADMIN.NEW_PROJECT.TABLE.PROJECT_NAME': 'Project name'
'APP.ADMIN.NEW_PROJECT.TABLE.PROJECT_DESCRIPTION': 'Project description'
'APP.ADMIN.NEW_PROJECT.TABLE.PREFIX_NAMESPACE': 'Prefix namespace'
'APP.ADMIN.NEW_PROJECT.TABLE.DEFAULT_LANGUAGE': 'Default language'
'APP.ADMIN.NEW_PROJECT.TABLE.DELETE_PROJECT': 'Delete project'
'APP.ADMIN.NEW_PROJECT.DELETE': 'Delete'
# ## app/project-manager/admin/projectSettings.jade
'APP.ADMIN.PROJECT_SETTINGS.GENETAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_ABOUT': 'About'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_DATE_AND_TIME': 'Date & Time'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_WORKFLOW': 'Workflow'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_OUTPUT_CASE_TYPE_LABEL': 'Output Case type'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_NAMESPACE_LABEL': 'Separator for namespaces'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_NAMESPACE_PLACEHOLDER': 'Type a namespace separator character'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_REQUIRED': 'Namespace field is required'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_IS_NOT_VALID': 'Namespace field is not valid'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_IS_VALID': 'Namespace field is valid'
'APP.ADMIN.PROJECT_SETTINGS.VALIDATION_NAMESPACE_MIN_CHARACTER': 'Namespace field must contain minimum 1 character'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_NAME_LABEL': 'Project name'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_NAME_PLACEHOLDER': 'Type name for the project'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DESCRITPION_LABEL': 'Project description'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DESCRITPION_PLACEHOLDER':
'Type short description about what is the project'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_PREFIX_NAMESPACE_LABEL': 'Prefix namespace'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_PREFIX_NAMESPACE_PLACEHOLDER':
'This prefix will be pasted before each one key-index\'s namespace for this project'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DEFAULT_LANGUAGE_LABEL': 'Project default language'
'APP.ADMIN.PROJECT_SETTINGS.FIELD_PROJECT_DEFAULT_LANGUAGE_PLACEHOLDER':
'Select or search default language for the project'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_ABOUT_GENERAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_DATE_AND_TIME_GENERAL_DESCRIPTION': 'Nothing here yet'
'APP.ADMIN.PROJECT_SETTINGS.SECTION_WORKFLOW_GENERAL_DESCRIPTION':
'All stuff related to building translations'
# app/project-manager/admin/userAssignment.jade
'APP.ADMIN.USER_ASSIGNMENT.GENETAL_DESCRIPTION': 'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS': 'Project users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS_GENERAL_DESCRIPTION':
'Nothing yet'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.AVAILABLE_USERS': 'Available users'
'APP.ADMIN.USER_ASSIGNMENT.SECTION_PROJECT_USERS.ASSIGNED_USERS': 'Assigned Users'
# common/directives/trWaitingSpinnerDiv/trWaitingSpinnerDiv.jade
})
])
|
[
{
"context": " AccessKeyId: 'KEY'\n SecretAccessKey: 'SECRET'\n SessionToken: 'TOKEN'\n Expirati",
"end": 445,
"score": 0.9252411127090454,
"start": 439,
"tag": "KEY",
"value": "SECRET"
},
{
"context": " AccessKeyId: 'KEY'\n SecretAccessKey: 'SEC... | test/services/sts.spec.coffee | daguej/aws-sdk-js | 28 | helpers = require('../helpers')
AWS = helpers.AWS
describe 'AWS.STS', ->
sts = null
beforeEach ->
sts = new AWS.STS()
describe 'credentialsFrom', ->
it 'returns null if no data is provided', ->
expect(sts.credentialsFrom(null)).to.equal(null)
it 'creates a TemporaryCredentials object with hydrated data', ->
creds = sts.credentialsFrom Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'SECRET'
SessionToken: 'TOKEN'
Expiration: new Date(0)
expect(creds instanceof AWS.TemporaryCredentials)
expect(creds.accessKeyId).to.equal('KEY')
expect(creds.secretAccessKey).to.equal('SECRET')
expect(creds.sessionToken).to.equal('TOKEN')
expect(creds.expireTime).to.eql(new Date(0))
expect(creds.expired).to.equal(false)
it 'updates an existing Credentials object with hydrated data', ->
data = Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'SECRET'
SessionToken: 'TOKEN'
Expiration: new Date(0)
creds = new AWS.Credentials
sts.credentialsFrom(data, creds)
expect(creds).to.be.instanceOf(AWS.Credentials)
expect(creds.accessKeyId).to.equal('KEY')
expect(creds.secretAccessKey).to.equal('SECRET')
expect(creds.sessionToken).to.equal('TOKEN')
expect(creds.expireTime).to.eql(new Date(0))
expect(creds.expired).to.equal(false)
describe 'assumeRoleWithWebIdentity', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', RoleSessionName: 'NAME', WebIdentityToken: 'TOK'
service.assumeRoleWithWebIdentity params, ->
hr = this.request.httpRequest
expect(hr.method).to.equal('GET')
expect(hr.body).to.equal('')
expect(hr.headers['Authorization']).to.equal(undefined)
expect(hr.headers['Content-Type']).to.equal(undefined)
expect(hr.path).to.equal('/?Action=AssumeRoleWithWebIdentity&' +
'RoleArn=ARN&RoleSessionName=NAME&Version=' +
service.api.apiVersion + '&WebIdentityToken=TOK')
it 'can build a get request on a mounted path (custom endpoint)', ->
helpers.mockHttpResponse 200, {}, '{}'
service = new AWS.STS(endpoint: 'http://localhost/foo/bar')
params = RoleArn: 'ARN', RoleSessionName: 'NAME', WebIdentityToken: 'TOK'
service.assumeRoleWithWebIdentity params, ->
hr = this.request.httpRequest
expect(hr.path).to.equal('/foo/bar?Action=AssumeRoleWithWebIdentity&' +
'RoleArn=ARN&RoleSessionName=NAME&Version=' +
service.api.apiVersion + '&WebIdentityToken=TOK')
describe 'assumeRoleWithSAML', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', PrincipalArn: 'PARN', SAMLAssertion: 'OK'
service.assumeRoleWithSAML params, ->
hr = this.request.httpRequest
expect(hr.method).to.equal('GET')
expect(hr.body).to.equal('')
expect(hr.headers['Authorization']).to.equal(undefined)
expect(hr.headers['Content-Type']).to.equal(undefined)
expect(hr.path).to.equal('/?Action=AssumeRoleWithSAML&' +
'PrincipalArn=PARN&RoleArn=ARN&SAMLAssertion=OK&' +
'Version=' + service.api.apiVersion)
| 187916 | helpers = require('../helpers')
AWS = helpers.AWS
describe 'AWS.STS', ->
sts = null
beforeEach ->
sts = new AWS.STS()
describe 'credentialsFrom', ->
it 'returns null if no data is provided', ->
expect(sts.credentialsFrom(null)).to.equal(null)
it 'creates a TemporaryCredentials object with hydrated data', ->
creds = sts.credentialsFrom Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: '<KEY>'
SessionToken: 'TOKEN'
Expiration: new Date(0)
expect(creds instanceof AWS.TemporaryCredentials)
expect(creds.accessKeyId).to.equal('KEY')
expect(creds.secretAccessKey).to.equal('SECRET')
expect(creds.sessionToken).to.equal('TOKEN')
expect(creds.expireTime).to.eql(new Date(0))
expect(creds.expired).to.equal(false)
it 'updates an existing Credentials object with hydrated data', ->
data = Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: '<KEY>'
SessionToken: 'TOKEN'
Expiration: new Date(0)
creds = new AWS.Credentials
sts.credentialsFrom(data, creds)
expect(creds).to.be.instanceOf(AWS.Credentials)
expect(creds.accessKeyId).to.equal('KEY')
expect(creds.secretAccessKey).to.equal('SECRET')
expect(creds.sessionToken).to.equal('TOKEN')
expect(creds.expireTime).to.eql(new Date(0))
expect(creds.expired).to.equal(false)
describe 'assumeRoleWithWebIdentity', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', RoleSessionName: 'NAME', WebIdentityToken: '<PASSWORD>'
service.assumeRoleWithWebIdentity params, ->
hr = this.request.httpRequest
expect(hr.method).to.equal('GET')
expect(hr.body).to.equal('')
expect(hr.headers['Authorization']).to.equal(undefined)
expect(hr.headers['Content-Type']).to.equal(undefined)
expect(hr.path).to.equal('/?Action=AssumeRoleWithWebIdentity&' +
'RoleArn=ARN&RoleSessionName=NAME&Version=' +
service.api.apiVersion + '&WebIdentityToken=TOK')
it 'can build a get request on a mounted path (custom endpoint)', ->
helpers.mockHttpResponse 200, {}, '{}'
service = new AWS.STS(endpoint: 'http://localhost/foo/bar')
params = RoleArn: 'ARN', RoleSessionName: 'NAME', WebIdentityToken: '<PASSWORD>'
service.assumeRoleWithWebIdentity params, ->
hr = this.request.httpRequest
expect(hr.path).to.equal('/foo/bar?Action=AssumeRoleWithWebIdentity&' +
'RoleArn=ARN&RoleSessionName=NAME&Version=' +
service.api.apiVersion + '&WebIdentityToken=TOK')
describe 'assumeRoleWithSAML', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', PrincipalArn: 'PARN', SAMLAssertion: 'OK'
service.assumeRoleWithSAML params, ->
hr = this.request.httpRequest
expect(hr.method).to.equal('GET')
expect(hr.body).to.equal('')
expect(hr.headers['Authorization']).to.equal(undefined)
expect(hr.headers['Content-Type']).to.equal(undefined)
expect(hr.path).to.equal('/?Action=AssumeRoleWithSAML&' +
'PrincipalArn=PARN&RoleArn=ARN&SAMLAssertion=OK&' +
'Version=' + service.api.apiVersion)
| true | helpers = require('../helpers')
AWS = helpers.AWS
describe 'AWS.STS', ->
sts = null
beforeEach ->
sts = new AWS.STS()
describe 'credentialsFrom', ->
it 'returns null if no data is provided', ->
expect(sts.credentialsFrom(null)).to.equal(null)
it 'creates a TemporaryCredentials object with hydrated data', ->
creds = sts.credentialsFrom Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'PI:KEY:<KEY>END_PI'
SessionToken: 'TOKEN'
Expiration: new Date(0)
expect(creds instanceof AWS.TemporaryCredentials)
expect(creds.accessKeyId).to.equal('KEY')
expect(creds.secretAccessKey).to.equal('SECRET')
expect(creds.sessionToken).to.equal('TOKEN')
expect(creds.expireTime).to.eql(new Date(0))
expect(creds.expired).to.equal(false)
it 'updates an existing Credentials object with hydrated data', ->
data = Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'PI:KEY:<KEY>END_PI'
SessionToken: 'TOKEN'
Expiration: new Date(0)
creds = new AWS.Credentials
sts.credentialsFrom(data, creds)
expect(creds).to.be.instanceOf(AWS.Credentials)
expect(creds.accessKeyId).to.equal('KEY')
expect(creds.secretAccessKey).to.equal('SECRET')
expect(creds.sessionToken).to.equal('TOKEN')
expect(creds.expireTime).to.eql(new Date(0))
expect(creds.expired).to.equal(false)
describe 'assumeRoleWithWebIdentity', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', RoleSessionName: 'NAME', WebIdentityToken: 'PI:PASSWORD:<PASSWORD>END_PI'
service.assumeRoleWithWebIdentity params, ->
hr = this.request.httpRequest
expect(hr.method).to.equal('GET')
expect(hr.body).to.equal('')
expect(hr.headers['Authorization']).to.equal(undefined)
expect(hr.headers['Content-Type']).to.equal(undefined)
expect(hr.path).to.equal('/?Action=AssumeRoleWithWebIdentity&' +
'RoleArn=ARN&RoleSessionName=NAME&Version=' +
service.api.apiVersion + '&WebIdentityToken=TOK')
it 'can build a get request on a mounted path (custom endpoint)', ->
helpers.mockHttpResponse 200, {}, '{}'
service = new AWS.STS(endpoint: 'http://localhost/foo/bar')
params = RoleArn: 'ARN', RoleSessionName: 'NAME', WebIdentityToken: 'PI:PASSWORD:<PASSWORD>END_PI'
service.assumeRoleWithWebIdentity params, ->
hr = this.request.httpRequest
expect(hr.path).to.equal('/foo/bar?Action=AssumeRoleWithWebIdentity&' +
'RoleArn=ARN&RoleSessionName=NAME&Version=' +
service.api.apiVersion + '&WebIdentityToken=TOK')
describe 'assumeRoleWithSAML', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', PrincipalArn: 'PARN', SAMLAssertion: 'OK'
service.assumeRoleWithSAML params, ->
hr = this.request.httpRequest
expect(hr.method).to.equal('GET')
expect(hr.body).to.equal('')
expect(hr.headers['Authorization']).to.equal(undefined)
expect(hr.headers['Content-Type']).to.equal(undefined)
expect(hr.path).to.equal('/?Action=AssumeRoleWithSAML&' +
'PrincipalArn=PARN&RoleArn=ARN&SAMLAssertion=OK&' +
'Version=' + service.api.apiVersion)
|
[
{
"context": " $(':checkbox').radiocheck()\n\n user = Utl.getLs('USERNAME')\n if user is null\n $('#modal_change_user').m",
"end": 709,
"score": 0.9960615634918213,
"start": 701,
"tag": "USERNAME",
"value": "USERNAME"
},
{
"context": "').hide()\n\nwindow.setUser = (user)->\n Ut... | coffee/index.coffee | rev84/shogiwars_getter | 0 | window.db = null
window.isGettingList = false
window.gType = null
window.getKifuData = {}
window.url = null
# 終局表現
window.ENDING =
TIME_UP: [
'SENTE_WIN_DISCONNECT'
'SENTE_WIN_TIMEOUT'
'GOTE_WIN_DISCONNECT'
'GOTE_WIN_TIMEOUT'
]
SENTE_ILLEGAL_MOVE:[
'GOTE_WIN_OUTE_SENNICHI'
]
GOTE_ILLEGAL_MOVE:[
'SENTE_WIN_OUTE_SENNICHI'
]
SENNICHITE:[
'DRAW_SENNICHI'
]
TORYO:[
'SENTE_WIN_TORYO'
'GOTE_WIN_TORYO'
]
TSUMI:[
'SENTE_WIN_CHECKMATE'
'GOTE_WIN_CHECKMATE'
]
KACHI:[
'SENTE_WIN_ENTERINGKING'
'GOTE_WIN_ENTERINGKING'
]
$().ready ->
# DB
window.db = new Utl.IndexedDB()
$(':checkbox').radiocheck()
user = Utl.getLs('USERNAME')
if user is null
$('#modal_change_user').modal()
else
$('#user_name_input').val(user)
window.getIndexes(user)
$('#start').on 'click', ->
window.setUser $('#user_name_input').val()
$('#open_user').on 'click', ->
$('#modal_change_user').modal() unless window.isGettingList
# チェック状態の保存
onCheckboxChange = ->
Utl.setLs 'CHECKED_'+$(@).attr('id'), $(@).prop('checked')
await window.draw()
$('#10m, #sb, #s1').on 'change', onCheckboxChange
# 復元
for id in ['10m', 'sb', 's1']
checked = Utl.getLs 'CHECKED_'+id
if checked isnt null
$('#'+id).prop('checked', checked)
onCheckboxChange($('#'+id))
# メッセージ内の×ボタンクリックでメッセージを非表示にする
$('.alert .close').on 'click', ->
$(@).parents('.alert').hide()
window.setUser = (user)->
Utl.setLs 'USERNAME', user
window.getIndexes(user)
window.getKifu = (url)->
console.log(url)
$.getJSON('http://localhost:7777/'+url).done((r)-> window.getKifuCallbackSuccess(r)).fail(-> window.getKifuCallbackFail(url))
window.getKifuCallbackFail = (url)->
window.getKifu(url)
window.getKifuCallbackSuccess = (response)->
url = response['url']
res = response['response']
kifuName = window.url2kifuName(url)
sw = res.match(/receiveMove\("([^"]+)"\);/)[1].split("\t")
# DBに保存
dbrec = await window.db.get kifuName
csa = window.sw2csa(sw, dbrec)
dbrec.csa = csa
await window.db.set kifuName, dbrec
window.sw2csa = (sw, dbrec)->
game_type = switch dbrec.game_type
when 's1' then '10秒'
when 'sb' then '3分'
else '10分'
buf = ''
# バージョン
buf += 'V2.2'+"\n"
# 対局者名
buf += 'N+'+dbrec.sente.name+'('+dbrec.sente.rank+")\n"
buf += 'N-'+dbrec.gote.name+'('+dbrec.gote.rank+")\n"
# 対局場所
buf += '$SITE:将棋ウォーズ('+game_type+')'+"\n"
# 持ち時間
buf += '$TIME_LIMIT:'
buf += switch game_type
when '10秒' then '00:00+10'
when '3分' then '00:03+00'
else '00:10+00'
buf += "\n"
# 平手の局面
buf += 'PI'+"\n"
# 先手番
buf += "+\n"
# 指し手と消費時間
restTime = switch game_type
when '10秒' then 60*60
when '3分' then 60*3
else 60*10
restTimes =
sente: restTime
gote: restTime
for s in sw
if window.ENDING.TIME_UP.indexOf(s) >= 0
buf += "%TIME_UP\n"
else if window.ENDING.SENTE_ILLEGAL_MOVE.indexOf(s) >= 0
buf += "%-ILLEGAL_ACTION\n"
else if window.ENDING.GOTE_ILLEGAL_MOVE.indexOf(s) >= 0
buf += "%+ILLEGAL_ACTION\n"
else if window.ENDING.SENNICHITE.indexOf(s) >= 0
buf += "%+ILLEGAL_ACTION\n"
else if window.ENDING.TORYO.indexOf(s) >= 0
buf += "%TORYO\n"
else if window.ENDING.KACHI.indexOf(s) >= 0
buf += "%KACHI\n"
else if window.ENDING.TSUMI.indexOf(s) >= 0
buf += "%TSUMI\n"
else
#console.log(s)
[te, rest] = s.split(',')
isFirst = te.substr(0, 1) is '+'
rest = Number(rest.substr(1))
buf += te+"\n"
name = if isFirst then 'sente' else 'gote'
buf += 'T'+(restTimes[name] - rest)+"\n"
restTimes[name] = rest
buf
window.finish = ->
console.log 'finished.'
window.draw()
window.isGettingList = false
window.draw = ->
results = await window.getMine()
results.sort (a, b)->
b.date - a.date
$('#user_name').html(window.myName)
tbody = $('#result').find('table').find('tbody')
tbody.html('')
for res in results
if res.sente.name is window.myName
is_win = if res.win is 0 then 1 else 0
is_first = true
my_rank = res.sente.rank
my_name = res.sente.name
op_rank = res.gote.rank
op_name = res.gote.name
else
is_win = if res.win is 1 then 1 else 0
is_first = false
my_rank = res.gote.rank
my_name = res.gote.name
op_rank = res.sente.rank
op_name = res.sente.name
if res.win is 2
is_win = 2
is_friend = res.is_friend
url = res.url
game_type = switch res.game_type
when 'sb' then '3分'
when 's1' then '10秒'
else '10分'
game_type_class = switch res.game_type
when 'sb' then 'm3'
when 's1' then 'm10'
else 's10'
dt = window.dateFormat(res.date)
tagTd = $('<td>')
for t in res.tags
tagTd.append $('<span>').addClass('senkei label label-default').html(t)
tr = $('<tr>').append(
$('<td>').addClass(if is_win is 1 then 'win' else if is_win is 0 then 'lose' else 'draw').html(my_name)
).append(
$('<td>').addClass('center').html(my_rank)
).append(
$('<td>').addClass(if is_first then 'sente' else 'gote').html(if is_first then '先' else '')
).append(
$('<td>').addClass(if is_first then 'gote' else 'sente').html(if is_first then '' else '先')
).append(
$('<td>').addClass('center').html(op_rank+(if is_friend then '<br><span class="label label-danger">友達</span>' else ''))
).append(
$('<td>').addClass(if is_win is 1 then 'lose' else if is_win is 0 then 'win' else 'draw').html(op_name)
).append(
tagTd
).append(
$('<td>').addClass(game_type_class).html(game_type)
).append(
$('<td>').addClass('center').html(dt)
).append(
$('<td>').addClass('center').append(
$('<button>')
.addClass('btn btn-sm btn-primary')
.attr('dt-key', res.kifu_name)
.html('コピー')
.on('click', ->
rec = await window.db.get($(@).attr('dt-key'))
window.execCopy(rec.csa)
)
).append(
$('<a>')
.addClass('btn btn-sm btn-info')
.attr('href', res.url)
.attr('target', 'wars')
.html('棋譜')
)
)
tbody.append tr
window.getIndexes = (userName)->
return if window.isGettingList
window.isGettingList = true
window.myName = userName
window.gTypes = ['', 'sb', 's1']
window.getIndex()
window.getIndex = ->
return window.finish() if window.gTypes.length <= 0
window.gType = window.gTypes.pop()
url = 'https://shogiwars.heroz.jp/users/history/'+window.myName+'/web_app?locale=ja'
url += '>ype='+gType if gType isnt ''
window.getIndexCall('http://localhost:7777/'+url)
window.getIndexCall = (url = null)->
window.url = url unless url is null
console.log(window.url)
$.getJSON(window.url).done((r)-> window.getIndexCallbackSuccess(r)).fail(-> window.getIndexCallbackFail())
window.getIndexCallbackFail = ->
window.getIndexCall()
window.getIndexCallbackSuccess = (response)->
# 既に取得した棋譜があるか
isExistAlreadyGot = false
parser = new DOMParser();
doc = parser.parseFromString(response['response'], "text/html");
# 対戦結果の取得
for content in doc.getElementsByClassName('contents')
result = {}
# 千日手パターン
result.win = 2
# 対戦者の情報
isFirst = true
for player in content.getElementsByClassName('players')[0].getElementsByTagName('div')
[name, rank] = window.trim(player.getElementsByTagName('a')[0].innerText).split(" ")
isWin = player.getElementsByTagName('a')[0].classList.contains('win_player')
if isFirst
result.sente =
name: name
rank: rank
else
result.gote =
name: name
rank: rank
if isWin
result.win = if isFirst then 0 else 1
isFirst = false
# 時刻
dateStr = trim(content.getElementsByClassName('game_date')[0].innerText)
matchRes = dateStr.match(/\((.+)\)/)
if matchRes
result.date = new Date(matchRes[1])
else
result.date = new Date(dateStr)
# 棋譜のURL
result.url = 'https:'+content.getElementsByClassName('game_replay')[0].getElementsByTagName('a')[0].getAttribute('href')
# 友達対戦であるか
result.is_friend = !!content.getElementsByClassName('game_category')[0].innerText.match(/友達/)
# 持ち時間タイプ
result.game_type = window.gType
# 戦型
result.tags = []
for span in content.getElementsByClassName('game_params')[0].getElementsByClassName('hashtag_badge')
result.tags.push span.innerText.replace('#', '')
# IndexedDBにあるか見る
key = window.url2kifuName(result.url)
stored = await window.db.get key
if stored is null
await window.db.set key, result
# 棋譜も取ってしまう
window.getKifu result.url
else
# 取得済みの棋譜がある
isExistAlreadyGot = true
# 次のページがあればそれも取得
isNext = false
for a in doc.getElementsByTagName('a')
if not($('#only1page').prop('checked')) and (a.innerText is '次へ>>' or a.innerText is '次へ>>')
# 取得済みの棋譜がないなら次のページも見る
unless isExistAlreadyGot
url = 'https://shogiwars.heroz.jp'+$(a).attr('href')
window.getIndexCall('http://localhost:7777/'+url)
isNext = true
break
# 次のページがなければ次のゲームモード
window.getIndex() unless isNext
window.dateFormat = (dt)->
dt = new Date(dt) if typeof(dt) is 'string'
y = dt.getFullYear()
m = dt.getMonth() + 1
d = dt.getDate()
w = dt.getDay()
h = dt.getHours()
i = dt.getMinutes()
s = dt.getSeconds()
wNames = ['日', '月', '火', '水', '木', '金', '土']
###
m = ('0' + m).slice(-2)
d = ('0' + d).slice(-2)
###
h = ('0' + h).slice(-2)
i = ('0' + i).slice(-2)
s = ('0' + s).slice(-2)
m + '/' + d + ' ' + h + ':' + i
window.execCopy = (string) ->
temp = document.createElement('div')
temp.appendChild(document.createElement('pre')).textContent = string
s = temp.style
s.position = 'fixed'
s.left = '-100%'
document.body.appendChild temp
document.getSelection().selectAllChildren temp
result = document.execCommand('copy')
document.body.removeChild temp
$('.alert').fadeIn(500).delay(1000).fadeOut(1000)
window.url2kifuName = (url)->
spl = url.split('/')
spl[spl.length-1].replace(/\?.*$/g, '')
window.getMine = ->
results = []
keys = await window.db.getAllKeys()
count = 0
###
for key in keys
res = await window.db.get key
console.log(''+count+'件ロード') if ++count % 10 is 0
res.date = new Date(res.date)
res.kifu_name = key
results.push res if [res.sente.name, res.gote.name].indexOf(window.myName) >= 0
results
###
res = await window.db.gets keys
is10m = $('#10m').prop('checked')
is3m = $('#sb').prop('checked')
is10s = $('#s1').prop('checked')
for k, v of res
v.date = new Date(v.date)
v.kifu_name = k
if [v.sente.name, v.gote.name].indexOf(window.myName) >= 0
if (is10m and v.game_type is '') or (is3m and v.game_type is 'sb') or (is10s and v.game_type is 's1')
results.push v
results
window.trim = (string)->
string.replace(/^\s+/g, "").replace(/\s+$/g, "") | 186459 | window.db = null
window.isGettingList = false
window.gType = null
window.getKifuData = {}
window.url = null
# 終局表現
window.ENDING =
TIME_UP: [
'SENTE_WIN_DISCONNECT'
'SENTE_WIN_TIMEOUT'
'GOTE_WIN_DISCONNECT'
'GOTE_WIN_TIMEOUT'
]
SENTE_ILLEGAL_MOVE:[
'GOTE_WIN_OUTE_SENNICHI'
]
GOTE_ILLEGAL_MOVE:[
'SENTE_WIN_OUTE_SENNICHI'
]
SENNICHITE:[
'DRAW_SENNICHI'
]
TORYO:[
'SENTE_WIN_TORYO'
'GOTE_WIN_TORYO'
]
TSUMI:[
'SENTE_WIN_CHECKMATE'
'GOTE_WIN_CHECKMATE'
]
KACHI:[
'SENTE_WIN_ENTERINGKING'
'GOTE_WIN_ENTERINGKING'
]
$().ready ->
# DB
window.db = new Utl.IndexedDB()
$(':checkbox').radiocheck()
user = Utl.getLs('USERNAME')
if user is null
$('#modal_change_user').modal()
else
$('#user_name_input').val(user)
window.getIndexes(user)
$('#start').on 'click', ->
window.setUser $('#user_name_input').val()
$('#open_user').on 'click', ->
$('#modal_change_user').modal() unless window.isGettingList
# チェック状態の保存
onCheckboxChange = ->
Utl.setLs 'CHECKED_'+$(@).attr('id'), $(@).prop('checked')
await window.draw()
$('#10m, #sb, #s1').on 'change', onCheckboxChange
# 復元
for id in ['10m', 'sb', 's1']
checked = Utl.getLs 'CHECKED_'+id
if checked isnt null
$('#'+id).prop('checked', checked)
onCheckboxChange($('#'+id))
# メッセージ内の×ボタンクリックでメッセージを非表示にする
$('.alert .close').on 'click', ->
$(@).parents('.alert').hide()
window.setUser = (user)->
Utl.setLs 'USERNAME', user
window.getIndexes(user)
window.getKifu = (url)->
console.log(url)
$.getJSON('http://localhost:7777/'+url).done((r)-> window.getKifuCallbackSuccess(r)).fail(-> window.getKifuCallbackFail(url))
window.getKifuCallbackFail = (url)->
window.getKifu(url)
window.getKifuCallbackSuccess = (response)->
url = response['url']
res = response['response']
kifuName = window.url2kifuName(url)
sw = res.match(/receiveMove\("([^"]+)"\);/)[1].split("\t")
# DBに保存
dbrec = await window.db.get kifuName
csa = window.sw2csa(sw, dbrec)
dbrec.csa = csa
await window.db.set kifuName, dbrec
window.sw2csa = (sw, dbrec)->
game_type = switch dbrec.game_type
when 's1' then '10秒'
when 'sb' then '3分'
else '10分'
buf = ''
# バージョン
buf += 'V2.2'+"\n"
# 対局者名
buf += 'N+'+dbrec.sente.name+'('+dbrec.sente.rank+")\n"
buf += 'N-'+dbrec.gote.name+'('+dbrec.gote.rank+")\n"
# 対局場所
buf += '$SITE:将棋ウォーズ('+game_type+')'+"\n"
# 持ち時間
buf += '$TIME_LIMIT:'
buf += switch game_type
when '10秒' then '00:00+10'
when '3分' then '00:03+00'
else '00:10+00'
buf += "\n"
# 平手の局面
buf += 'PI'+"\n"
# 先手番
buf += "+\n"
# 指し手と消費時間
restTime = switch game_type
when '10秒' then 60*60
when '3分' then 60*3
else 60*10
restTimes =
sente: restTime
gote: restTime
for s in sw
if window.ENDING.TIME_UP.indexOf(s) >= 0
buf += "%TIME_UP\n"
else if window.ENDING.SENTE_ILLEGAL_MOVE.indexOf(s) >= 0
buf += "%-ILLEGAL_ACTION\n"
else if window.ENDING.GOTE_ILLEGAL_MOVE.indexOf(s) >= 0
buf += "%+ILLEGAL_ACTION\n"
else if window.ENDING.SENNICHITE.indexOf(s) >= 0
buf += "%+ILLEGAL_ACTION\n"
else if window.ENDING.TORYO.indexOf(s) >= 0
buf += "%TORYO\n"
else if window.ENDING.KACHI.indexOf(s) >= 0
buf += "%KACHI\n"
else if window.ENDING.TSUMI.indexOf(s) >= 0
buf += "%TSUMI\n"
else
#console.log(s)
[te, rest] = s.split(',')
isFirst = te.substr(0, 1) is '+'
rest = Number(rest.substr(1))
buf += te+"\n"
name = if isFirst then 'sente' else 'gote'
buf += 'T'+(restTimes[name] - rest)+"\n"
restTimes[name] = rest
buf
window.finish = ->
console.log 'finished.'
window.draw()
window.isGettingList = false
window.draw = ->
results = await window.getMine()
results.sort (a, b)->
b.date - a.date
$('#user_name').html(window.myName)
tbody = $('#result').find('table').find('tbody')
tbody.html('')
for res in results
if res.sente.name is window.myName
is_win = if res.win is 0 then 1 else 0
is_first = true
my_rank = res.sente.rank
my_name = res.sente.name
op_rank = res.gote.rank
op_name = res.gote.name
else
is_win = if res.win is 1 then 1 else 0
is_first = false
my_rank = res.gote.rank
my_name = res.gote.name
op_rank = res.sente.rank
op_name = res.sente.name
if res.win is 2
is_win = 2
is_friend = res.is_friend
url = res.url
game_type = switch res.game_type
when 'sb' then '3分'
when 's1' then '10秒'
else '10分'
game_type_class = switch res.game_type
when 'sb' then 'm3'
when 's1' then 'm10'
else 's10'
dt = window.dateFormat(res.date)
tagTd = $('<td>')
for t in res.tags
tagTd.append $('<span>').addClass('senkei label label-default').html(t)
tr = $('<tr>').append(
$('<td>').addClass(if is_win is 1 then 'win' else if is_win is 0 then 'lose' else 'draw').html(my_name)
).append(
$('<td>').addClass('center').html(my_rank)
).append(
$('<td>').addClass(if is_first then 'sente' else 'gote').html(if is_first then '先' else '')
).append(
$('<td>').addClass(if is_first then 'gote' else 'sente').html(if is_first then '' else '先')
).append(
$('<td>').addClass('center').html(op_rank+(if is_friend then '<br><span class="label label-danger">友達</span>' else ''))
).append(
$('<td>').addClass(if is_win is 1 then 'lose' else if is_win is 0 then 'win' else 'draw').html(op_name)
).append(
tagTd
).append(
$('<td>').addClass(game_type_class).html(game_type)
).append(
$('<td>').addClass('center').html(dt)
).append(
$('<td>').addClass('center').append(
$('<button>')
.addClass('btn btn-sm btn-primary')
.attr('dt-key', res.kifu_name)
.html('コピー')
.on('click', ->
rec = await window.db.get($(@).attr('dt-key'))
window.execCopy(rec.csa)
)
).append(
$('<a>')
.addClass('btn btn-sm btn-info')
.attr('href', res.url)
.attr('target', 'wars')
.html('棋譜')
)
)
tbody.append tr
window.getIndexes = (userName)->
return if window.isGettingList
window.isGettingList = true
window.myName = userName
window.gTypes = ['', 'sb', 's1']
window.getIndex()
window.getIndex = ->
return window.finish() if window.gTypes.length <= 0
window.gType = window.gTypes.pop()
url = 'https://shogiwars.heroz.jp/users/history/'+window.myName+'/web_app?locale=ja'
url += '>ype='+gType if gType isnt ''
window.getIndexCall('http://localhost:7777/'+url)
window.getIndexCall = (url = null)->
window.url = url unless url is null
console.log(window.url)
$.getJSON(window.url).done((r)-> window.getIndexCallbackSuccess(r)).fail(-> window.getIndexCallbackFail())
window.getIndexCallbackFail = ->
window.getIndexCall()
window.getIndexCallbackSuccess = (response)->
# 既に取得した棋譜があるか
isExistAlreadyGot = false
parser = new DOMParser();
doc = parser.parseFromString(response['response'], "text/html");
# 対戦結果の取得
for content in doc.getElementsByClassName('contents')
result = {}
# 千日手パターン
result.win = 2
# 対戦者の情報
isFirst = true
for player in content.getElementsByClassName('players')[0].getElementsByTagName('div')
[name, rank] = window.trim(player.getElementsByTagName('a')[0].innerText).split(" ")
isWin = player.getElementsByTagName('a')[0].classList.contains('win_player')
if isFirst
result.sente =
name: <NAME>
rank: rank
else
result.gote =
name: <NAME>
rank: rank
if isWin
result.win = if isFirst then 0 else 1
isFirst = false
# 時刻
dateStr = trim(content.getElementsByClassName('game_date')[0].innerText)
matchRes = dateStr.match(/\((.+)\)/)
if matchRes
result.date = new Date(matchRes[1])
else
result.date = new Date(dateStr)
# 棋譜のURL
result.url = 'https:'+content.getElementsByClassName('game_replay')[0].getElementsByTagName('a')[0].getAttribute('href')
# 友達対戦であるか
result.is_friend = !!content.getElementsByClassName('game_category')[0].innerText.match(/友達/)
# 持ち時間タイプ
result.game_type = window.gType
# 戦型
result.tags = []
for span in content.getElementsByClassName('game_params')[0].getElementsByClassName('hashtag_badge')
result.tags.push span.innerText.replace('#', '')
# IndexedDBにあるか見る
key = <KEY>(result.url)
stored = await window.db.get key
if stored is null
await window.db.set key, result
# 棋譜も取ってしまう
window.getKifu result.url
else
# 取得済みの棋譜がある
isExistAlreadyGot = true
# 次のページがあればそれも取得
isNext = false
for a in doc.getElementsByTagName('a')
if not($('#only1page').prop('checked')) and (a.innerText is '次へ>>' or a.innerText is '次へ>>')
# 取得済みの棋譜がないなら次のページも見る
unless isExistAlreadyGot
url = 'https://shogiwars.heroz.jp'+$(a).attr('href')
window.getIndexCall('http://localhost:7777/'+url)
isNext = true
break
# 次のページがなければ次のゲームモード
window.getIndex() unless isNext
window.dateFormat = (dt)->
dt = new Date(dt) if typeof(dt) is 'string'
y = dt.getFullYear()
m = dt.getMonth() + 1
d = dt.getDate()
w = dt.getDay()
h = dt.getHours()
i = dt.getMinutes()
s = dt.getSeconds()
wNames = ['日', '月', '火', '水', '木', '金', '土']
###
m = ('0' + m).slice(-2)
d = ('0' + d).slice(-2)
###
h = ('0' + h).slice(-2)
i = ('0' + i).slice(-2)
s = ('0' + s).slice(-2)
m + '/' + d + ' ' + h + ':' + i
window.execCopy = (string) ->
temp = document.createElement('div')
temp.appendChild(document.createElement('pre')).textContent = string
s = temp.style
s.position = 'fixed'
s.left = '-100%'
document.body.appendChild temp
document.getSelection().selectAllChildren temp
result = document.execCommand('copy')
document.body.removeChild temp
$('.alert').fadeIn(500).delay(1000).fadeOut(1000)
window.url2kifuName = (url)->
spl = url.split('/')
spl[spl.length-1].replace(/\?.*$/g, '')
window.getMine = ->
results = []
keys = await window.db.getAllKeys()
count = 0
###
for key in keys
res = await window.db.get key
console.log(''+count+'件ロード') if ++count % 10 is 0
res.date = new Date(res.date)
res.kifu_name = key
results.push res if [res.sente.name, res.gote.name].indexOf(window.myName) >= 0
results
###
res = await window.db.gets keys
is10m = $('#10m').prop('checked')
is3m = $('#sb').prop('checked')
is10s = $('#s1').prop('checked')
for k, v of res
v.date = new Date(v.date)
v.kifu_name = k
if [v.sente.name, v.gote.name].indexOf(window.myName) >= 0
if (is10m and v.game_type is '') or (is3m and v.game_type is 'sb') or (is10s and v.game_type is 's1')
results.push v
results
window.trim = (string)->
string.replace(/^\s+/g, "").replace(/\s+$/g, "") | true | window.db = null
window.isGettingList = false
window.gType = null
window.getKifuData = {}
window.url = null
# 終局表現
window.ENDING =
TIME_UP: [
'SENTE_WIN_DISCONNECT'
'SENTE_WIN_TIMEOUT'
'GOTE_WIN_DISCONNECT'
'GOTE_WIN_TIMEOUT'
]
SENTE_ILLEGAL_MOVE:[
'GOTE_WIN_OUTE_SENNICHI'
]
GOTE_ILLEGAL_MOVE:[
'SENTE_WIN_OUTE_SENNICHI'
]
SENNICHITE:[
'DRAW_SENNICHI'
]
TORYO:[
'SENTE_WIN_TORYO'
'GOTE_WIN_TORYO'
]
TSUMI:[
'SENTE_WIN_CHECKMATE'
'GOTE_WIN_CHECKMATE'
]
KACHI:[
'SENTE_WIN_ENTERINGKING'
'GOTE_WIN_ENTERINGKING'
]
$().ready ->
# DB
window.db = new Utl.IndexedDB()
$(':checkbox').radiocheck()
user = Utl.getLs('USERNAME')
if user is null
$('#modal_change_user').modal()
else
$('#user_name_input').val(user)
window.getIndexes(user)
$('#start').on 'click', ->
window.setUser $('#user_name_input').val()
$('#open_user').on 'click', ->
$('#modal_change_user').modal() unless window.isGettingList
# チェック状態の保存
onCheckboxChange = ->
Utl.setLs 'CHECKED_'+$(@).attr('id'), $(@).prop('checked')
await window.draw()
$('#10m, #sb, #s1').on 'change', onCheckboxChange
# 復元
for id in ['10m', 'sb', 's1']
checked = Utl.getLs 'CHECKED_'+id
if checked isnt null
$('#'+id).prop('checked', checked)
onCheckboxChange($('#'+id))
# メッセージ内の×ボタンクリックでメッセージを非表示にする
$('.alert .close').on 'click', ->
$(@).parents('.alert').hide()
window.setUser = (user)->
Utl.setLs 'USERNAME', user
window.getIndexes(user)
window.getKifu = (url)->
console.log(url)
$.getJSON('http://localhost:7777/'+url).done((r)-> window.getKifuCallbackSuccess(r)).fail(-> window.getKifuCallbackFail(url))
window.getKifuCallbackFail = (url)->
window.getKifu(url)
window.getKifuCallbackSuccess = (response)->
url = response['url']
res = response['response']
kifuName = window.url2kifuName(url)
sw = res.match(/receiveMove\("([^"]+)"\);/)[1].split("\t")
# DBに保存
dbrec = await window.db.get kifuName
csa = window.sw2csa(sw, dbrec)
dbrec.csa = csa
await window.db.set kifuName, dbrec
window.sw2csa = (sw, dbrec)->
game_type = switch dbrec.game_type
when 's1' then '10秒'
when 'sb' then '3分'
else '10分'
buf = ''
# バージョン
buf += 'V2.2'+"\n"
# 対局者名
buf += 'N+'+dbrec.sente.name+'('+dbrec.sente.rank+")\n"
buf += 'N-'+dbrec.gote.name+'('+dbrec.gote.rank+")\n"
# 対局場所
buf += '$SITE:将棋ウォーズ('+game_type+')'+"\n"
# 持ち時間
buf += '$TIME_LIMIT:'
buf += switch game_type
when '10秒' then '00:00+10'
when '3分' then '00:03+00'
else '00:10+00'
buf += "\n"
# 平手の局面
buf += 'PI'+"\n"
# 先手番
buf += "+\n"
# 指し手と消費時間
restTime = switch game_type
when '10秒' then 60*60
when '3分' then 60*3
else 60*10
restTimes =
sente: restTime
gote: restTime
for s in sw
if window.ENDING.TIME_UP.indexOf(s) >= 0
buf += "%TIME_UP\n"
else if window.ENDING.SENTE_ILLEGAL_MOVE.indexOf(s) >= 0
buf += "%-ILLEGAL_ACTION\n"
else if window.ENDING.GOTE_ILLEGAL_MOVE.indexOf(s) >= 0
buf += "%+ILLEGAL_ACTION\n"
else if window.ENDING.SENNICHITE.indexOf(s) >= 0
buf += "%+ILLEGAL_ACTION\n"
else if window.ENDING.TORYO.indexOf(s) >= 0
buf += "%TORYO\n"
else if window.ENDING.KACHI.indexOf(s) >= 0
buf += "%KACHI\n"
else if window.ENDING.TSUMI.indexOf(s) >= 0
buf += "%TSUMI\n"
else
#console.log(s)
[te, rest] = s.split(',')
isFirst = te.substr(0, 1) is '+'
rest = Number(rest.substr(1))
buf += te+"\n"
name = if isFirst then 'sente' else 'gote'
buf += 'T'+(restTimes[name] - rest)+"\n"
restTimes[name] = rest
buf
window.finish = ->
console.log 'finished.'
window.draw()
window.isGettingList = false
window.draw = ->
results = await window.getMine()
results.sort (a, b)->
b.date - a.date
$('#user_name').html(window.myName)
tbody = $('#result').find('table').find('tbody')
tbody.html('')
for res in results
if res.sente.name is window.myName
is_win = if res.win is 0 then 1 else 0
is_first = true
my_rank = res.sente.rank
my_name = res.sente.name
op_rank = res.gote.rank
op_name = res.gote.name
else
is_win = if res.win is 1 then 1 else 0
is_first = false
my_rank = res.gote.rank
my_name = res.gote.name
op_rank = res.sente.rank
op_name = res.sente.name
if res.win is 2
is_win = 2
is_friend = res.is_friend
url = res.url
game_type = switch res.game_type
when 'sb' then '3分'
when 's1' then '10秒'
else '10分'
game_type_class = switch res.game_type
when 'sb' then 'm3'
when 's1' then 'm10'
else 's10'
dt = window.dateFormat(res.date)
tagTd = $('<td>')
for t in res.tags
tagTd.append $('<span>').addClass('senkei label label-default').html(t)
tr = $('<tr>').append(
$('<td>').addClass(if is_win is 1 then 'win' else if is_win is 0 then 'lose' else 'draw').html(my_name)
).append(
$('<td>').addClass('center').html(my_rank)
).append(
$('<td>').addClass(if is_first then 'sente' else 'gote').html(if is_first then '先' else '')
).append(
$('<td>').addClass(if is_first then 'gote' else 'sente').html(if is_first then '' else '先')
).append(
$('<td>').addClass('center').html(op_rank+(if is_friend then '<br><span class="label label-danger">友達</span>' else ''))
).append(
$('<td>').addClass(if is_win is 1 then 'lose' else if is_win is 0 then 'win' else 'draw').html(op_name)
).append(
tagTd
).append(
$('<td>').addClass(game_type_class).html(game_type)
).append(
$('<td>').addClass('center').html(dt)
).append(
$('<td>').addClass('center').append(
$('<button>')
.addClass('btn btn-sm btn-primary')
.attr('dt-key', res.kifu_name)
.html('コピー')
.on('click', ->
rec = await window.db.get($(@).attr('dt-key'))
window.execCopy(rec.csa)
)
).append(
$('<a>')
.addClass('btn btn-sm btn-info')
.attr('href', res.url)
.attr('target', 'wars')
.html('棋譜')
)
)
tbody.append tr
window.getIndexes = (userName)->
return if window.isGettingList
window.isGettingList = true
window.myName = userName
window.gTypes = ['', 'sb', 's1']
window.getIndex()
window.getIndex = ->
return window.finish() if window.gTypes.length <= 0
window.gType = window.gTypes.pop()
url = 'https://shogiwars.heroz.jp/users/history/'+window.myName+'/web_app?locale=ja'
url += '>ype='+gType if gType isnt ''
window.getIndexCall('http://localhost:7777/'+url)
window.getIndexCall = (url = null)->
window.url = url unless url is null
console.log(window.url)
$.getJSON(window.url).done((r)-> window.getIndexCallbackSuccess(r)).fail(-> window.getIndexCallbackFail())
window.getIndexCallbackFail = ->
window.getIndexCall()
window.getIndexCallbackSuccess = (response)->
# 既に取得した棋譜があるか
isExistAlreadyGot = false
parser = new DOMParser();
doc = parser.parseFromString(response['response'], "text/html");
# 対戦結果の取得
for content in doc.getElementsByClassName('contents')
result = {}
# 千日手パターン
result.win = 2
# 対戦者の情報
isFirst = true
for player in content.getElementsByClassName('players')[0].getElementsByTagName('div')
[name, rank] = window.trim(player.getElementsByTagName('a')[0].innerText).split(" ")
isWin = player.getElementsByTagName('a')[0].classList.contains('win_player')
if isFirst
result.sente =
name: PI:NAME:<NAME>END_PI
rank: rank
else
result.gote =
name: PI:NAME:<NAME>END_PI
rank: rank
if isWin
result.win = if isFirst then 0 else 1
isFirst = false
# 時刻
dateStr = trim(content.getElementsByClassName('game_date')[0].innerText)
matchRes = dateStr.match(/\((.+)\)/)
if matchRes
result.date = new Date(matchRes[1])
else
result.date = new Date(dateStr)
# 棋譜のURL
result.url = 'https:'+content.getElementsByClassName('game_replay')[0].getElementsByTagName('a')[0].getAttribute('href')
# 友達対戦であるか
result.is_friend = !!content.getElementsByClassName('game_category')[0].innerText.match(/友達/)
# 持ち時間タイプ
result.game_type = window.gType
# 戦型
result.tags = []
for span in content.getElementsByClassName('game_params')[0].getElementsByClassName('hashtag_badge')
result.tags.push span.innerText.replace('#', '')
# IndexedDBにあるか見る
key = PI:KEY:<KEY>END_PI(result.url)
stored = await window.db.get key
if stored is null
await window.db.set key, result
# 棋譜も取ってしまう
window.getKifu result.url
else
# 取得済みの棋譜がある
isExistAlreadyGot = true
# 次のページがあればそれも取得
isNext = false
for a in doc.getElementsByTagName('a')
if not($('#only1page').prop('checked')) and (a.innerText is '次へ>>' or a.innerText is '次へ>>')
# 取得済みの棋譜がないなら次のページも見る
unless isExistAlreadyGot
url = 'https://shogiwars.heroz.jp'+$(a).attr('href')
window.getIndexCall('http://localhost:7777/'+url)
isNext = true
break
# 次のページがなければ次のゲームモード
window.getIndex() unless isNext
window.dateFormat = (dt)->
dt = new Date(dt) if typeof(dt) is 'string'
y = dt.getFullYear()
m = dt.getMonth() + 1
d = dt.getDate()
w = dt.getDay()
h = dt.getHours()
i = dt.getMinutes()
s = dt.getSeconds()
wNames = ['日', '月', '火', '水', '木', '金', '土']
###
m = ('0' + m).slice(-2)
d = ('0' + d).slice(-2)
###
h = ('0' + h).slice(-2)
i = ('0' + i).slice(-2)
s = ('0' + s).slice(-2)
m + '/' + d + ' ' + h + ':' + i
window.execCopy = (string) ->
temp = document.createElement('div')
temp.appendChild(document.createElement('pre')).textContent = string
s = temp.style
s.position = 'fixed'
s.left = '-100%'
document.body.appendChild temp
document.getSelection().selectAllChildren temp
result = document.execCommand('copy')
document.body.removeChild temp
$('.alert').fadeIn(500).delay(1000).fadeOut(1000)
window.url2kifuName = (url)->
spl = url.split('/')
spl[spl.length-1].replace(/\?.*$/g, '')
window.getMine = ->
results = []
keys = await window.db.getAllKeys()
count = 0
###
for key in keys
res = await window.db.get key
console.log(''+count+'件ロード') if ++count % 10 is 0
res.date = new Date(res.date)
res.kifu_name = key
results.push res if [res.sente.name, res.gote.name].indexOf(window.myName) >= 0
results
###
res = await window.db.gets keys
is10m = $('#10m').prop('checked')
is3m = $('#sb').prop('checked')
is10s = $('#s1').prop('checked')
for k, v of res
v.date = new Date(v.date)
v.kifu_name = k
if [v.sente.name, v.gote.name].indexOf(window.myName) >= 0
if (is10m and v.game_type is '') or (is3m and v.game_type is 'sb') or (is10s and v.game_type is 's1')
results.push v
results
window.trim = (string)->
string.replace(/^\s+/g, "").replace(/\s+$/g, "") |
[
{
"context": " 'somata'\nconfig = require '../config'\n\nSENDER = 'blockwoods-roulette'\nNEXUS_ACCOUNT_ID = config.nexus.account_id\nnexus",
"end": 85,
"score": 0.9820669293403625,
"start": 66,
"tag": "USERNAME",
"value": "blockwoods-roulette"
},
{
"context": "sender\n when 's... | services/roulette-bot.coffee | brynwaldwick/blockwoods | 0 | somata = require 'somata'
config = require '../config'
SENDER = 'blockwoods-roulette'
NEXUS_ACCOUNT_ID = config.nexus.account_id
nexus_client = new somata.Client {registry_host: config.nexus.host}
client = new somata.Client()
announce = require('nexus-announce')(config.announce)
ContractsService = new somata.Client().bindRemote 'ethereum:contracts'
BlockwoodsEngine = client.bindRemote 'blockwoods:engine'
table_address = config.table_address
topic_base = "blockwoods:roulette:#{table_address}"
MAX_BET = 100000000000000000
wei_to_ether = 1000000000000000000
pending_spins = {}
parseSender = (event) ->
return event.sender.username
validateBetAmount = (amount) ->
if amount > MAX_BET
return false
else
return true
sendNexusMessage = (body, type='message') ->
response_message = {sender: SENDER, body, type}
nexus_client.remote 'nexus:events', 'send', NEXUS_ACCOUNT_ID, response_message, -> # ...
nexus_client.subscribe 'nexus:events', "event:#{NEXUS_ACCOUNT_ID}:#{SENDER}", (event) ->
console.log event
sender = parseSender event
switch sender
when 'sean'
account = '0xdde8f1b7a03a0135cec39e495d653f6ecfc305df'
when 'chad'
account = '0xaba83a7b118ecc13147151cf7c57e6c24f25e59f'
when 'bryn'
account = '0x82d1fb5b04f9280e3bfd816b4f5bde2f84fbdc0a'
else
return
split_body = event.body.split(' ')
if split_body[0] == 'balance'
ContractsService 'getBalance', account, (err, resp) ->
if resp?
number = Number(resp) / wei_to_ether
sendNexusMessage number.toString()
else if split_body[0][0..2] == 'bet'
bet_amount = Number(split_body[1]) * wei_to_ether
bet_arg = split_body[2]
valid = validateBetAmount bet_amount
if !valid
return sendNexusMessage "Please bet below #{MAX_BET/wei_to_ether} ether."
bet_fn = split_body[0]
bet_kind = split_body[0][3..]
finishRoute = (err, resp) ->
sendNexusMessage 'Betting...'
data = {txid: resp}
data.bet_kind = bet_kind
data.amount = bet_amount
data.amount_str = (bet_amount/wei_to_ether + ' eth')
data.bet_fn = bet_fn
data.bet_arg = bet_arg
announce {type: 'bet', game: 'roulette', project: 'blockwoods', topic: topic_base, data}
# wait for result and then broadcast result
client.on 'blockwoods:engine', "tx:#{resp}:done", (result) ->
sendNexusMessage "#{sender}, your #{bet_kind} bet was placed"
# resolve pull
console.log "tx:#{result.outcome_tx}:done"
if bet_fn in ['betBlack', 'betOdd', 'betBlack', 'betLow']
# TODO: validate bool
ContractsService 'callFunction', 'RouletteTable', table_address, bet_fn, bet_arg, {account, value: bet_amount.toString(), gas: '220000'}, finishRoute
else if bet_fn in ['betStraightUp', 'betStreet', 'betColumn', 'betSixLine', 'betDozen']
ContractsService 'callFunction', 'RouletteTable', table_address, bet_fn, bet_arg, {account, value: bet_amount.toString(), gas: '220000'}, finishRoute
else if split_body[0] == 'spin'
ContractsService 'callFunction', 'RouletteTable', table_address, 'spinWheel', {account, value: '0', gas: '100000'}, (err, resp) ->
sendNexusMessage 'Spinning...'
# wait for result and then broadcast result
client.on 'blockwoods:engine', "tx:#{resp}:done", (result) ->
sendNexusMessage "#{sender}, your result was #{result.n}"
announce {type: 'play', game: 'roulette', project: 'blockwoods', topic: topic_base, data: {result, txid: result.outcome_tx}}
# resolve pull
console.log "tx:#{result.outcome_tx}:done"
client.on 'blockwoods:engine', "tx:#{result.outcome_tx}:done", (result) ->
console.log 'the result was', result
if result.result > 0
sendNexusMessage "WINNER! #{sender}, your bet was settled, paying #{result.result}:1"
else
sendNexusMessage "#{sender}, you lost. Keep gambling to try and win your money back."
else if split_body[0] == 'pays'
# query "pays" to see how much could be disbursed
ContractsService 'callFunction', 'RouletteTable', table_address, 'pays', account, {account}, (err, resp) ->
console.log err, resp
number = Number(resp) / wei_to_ether
console.log number
sendNexusMessage number.toString()
else if split_body[0] == 'disburse'
# do disbursal (send disburse from user's account)
ContractsService 'callFunction', 'RouletteTable', table_address, 'disburse', {account, gas: '75000'}, (err, resp) ->
console.log err, Number(resp)/wei_to_ether
if !err?
sendNexusMessage 'Disbursing...'
else if split_body[0] == 'man'
sendNexusMessage "balance - report the balance of your eve account \n" +
"betStraightUp amount, uint - bet on an exact number 0-37 (currently only allows one bet) \n" +
"betBlack amount, bool - bet on black numbers according to https://en.wikipedia.org/wiki/Roulette#Bet_odds_table\n" +
"betOdd amount, bool - bet on odd numbers \n" +
"betLow amount, bool - bet on low numbers 1-18 (vs 19-36) \n" +
"betColumn amount, uint - bet on column 1 (4, 7, 10...), 2 (5, 8, 11...), or 3 (6, 9, 12...) \n" +
"betStreet amount, uint - bet on street 1 (2, 3), 4 (5, 6), 7 (8, 9), .... \n" +
"betDozen amount, uint - bet on the 1st, 2nd or 3rd dozen (out of 36) \n" +
"spin - spin the wheel \n" +
"pays - report the amount available to disburse \n" +
"disburse - send your winnings to your address \n" +
"man - man"
else
return
# doThing event.body, (err, response) ->
# sendNexusMessage err || response | 12652 | somata = require 'somata'
config = require '../config'
SENDER = 'blockwoods-roulette'
NEXUS_ACCOUNT_ID = config.nexus.account_id
nexus_client = new somata.Client {registry_host: config.nexus.host}
client = new somata.Client()
announce = require('nexus-announce')(config.announce)
ContractsService = new somata.Client().bindRemote 'ethereum:contracts'
BlockwoodsEngine = client.bindRemote 'blockwoods:engine'
table_address = config.table_address
topic_base = "blockwoods:roulette:#{table_address}"
MAX_BET = 100000000000000000
wei_to_ether = 1000000000000000000
pending_spins = {}
parseSender = (event) ->
return event.sender.username
validateBetAmount = (amount) ->
if amount > MAX_BET
return false
else
return true
sendNexusMessage = (body, type='message') ->
response_message = {sender: SENDER, body, type}
nexus_client.remote 'nexus:events', 'send', NEXUS_ACCOUNT_ID, response_message, -> # ...
nexus_client.subscribe 'nexus:events', "event:#{NEXUS_ACCOUNT_ID}:#{SENDER}", (event) ->
console.log event
sender = parseSender event
switch sender
when 'sean'
account = '<KEY>'
when 'chad'
account = '<KEY>'
when 'bryn'
account = '<KEY>'
else
return
split_body = event.body.split(' ')
if split_body[0] == 'balance'
ContractsService 'getBalance', account, (err, resp) ->
if resp?
number = Number(resp) / wei_to_ether
sendNexusMessage number.toString()
else if split_body[0][0..2] == 'bet'
bet_amount = Number(split_body[1]) * wei_to_ether
bet_arg = split_body[2]
valid = validateBetAmount bet_amount
if !valid
return sendNexusMessage "Please bet below #{MAX_BET/wei_to_ether} ether."
bet_fn = split_body[0]
bet_kind = split_body[0][3..]
finishRoute = (err, resp) ->
sendNexusMessage 'Betting...'
data = {txid: resp}
data.bet_kind = bet_kind
data.amount = bet_amount
data.amount_str = (bet_amount/wei_to_ether + ' eth')
data.bet_fn = bet_fn
data.bet_arg = bet_arg
announce {type: 'bet', game: 'roulette', project: 'blockwoods', topic: topic_base, data}
# wait for result and then broadcast result
client.on 'blockwoods:engine', "tx:#{resp}:done", (result) ->
sendNexusMessage "#{sender}, your #{bet_kind} bet was placed"
# resolve pull
console.log "tx:#{result.outcome_tx}:done"
if bet_fn in ['betBlack', 'betOdd', 'betBlack', 'betLow']
# TODO: validate bool
ContractsService 'callFunction', 'RouletteTable', table_address, bet_fn, bet_arg, {account, value: bet_amount.toString(), gas: '220000'}, finishRoute
else if bet_fn in ['betStraightUp', 'betStreet', 'betColumn', 'betSixLine', 'betDozen']
ContractsService 'callFunction', 'RouletteTable', table_address, bet_fn, bet_arg, {account, value: bet_amount.toString(), gas: '220000'}, finishRoute
else if split_body[0] == 'spin'
ContractsService 'callFunction', 'RouletteTable', table_address, 'spinWheel', {account, value: '0', gas: '100000'}, (err, resp) ->
sendNexusMessage 'Spinning...'
# wait for result and then broadcast result
client.on 'blockwoods:engine', "tx:#{resp}:done", (result) ->
sendNexusMessage "#{sender}, your result was #{result.n}"
announce {type: 'play', game: 'roulette', project: 'blockwoods', topic: topic_base, data: {result, txid: result.outcome_tx}}
# resolve pull
console.log "tx:#{result.outcome_tx}:done"
client.on 'blockwoods:engine', "tx:#{result.outcome_tx}:done", (result) ->
console.log 'the result was', result
if result.result > 0
sendNexusMessage "WINNER! #{sender}, your bet was settled, paying #{result.result}:1"
else
sendNexusMessage "#{sender}, you lost. Keep gambling to try and win your money back."
else if split_body[0] == 'pays'
# query "pays" to see how much could be disbursed
ContractsService 'callFunction', 'RouletteTable', table_address, 'pays', account, {account}, (err, resp) ->
console.log err, resp
number = Number(resp) / wei_to_ether
console.log number
sendNexusMessage number.toString()
else if split_body[0] == 'disburse'
# do disbursal (send disburse from user's account)
ContractsService 'callFunction', 'RouletteTable', table_address, 'disburse', {account, gas: '75000'}, (err, resp) ->
console.log err, Number(resp)/wei_to_ether
if !err?
sendNexusMessage 'Disbursing...'
else if split_body[0] == 'man'
sendNexusMessage "balance - report the balance of your eve account \n" +
"betStraightUp amount, uint - bet on an exact number 0-37 (currently only allows one bet) \n" +
"betBlack amount, bool - bet on black numbers according to https://en.wikipedia.org/wiki/Roulette#Bet_odds_table\n" +
"betOdd amount, bool - bet on odd numbers \n" +
"betLow amount, bool - bet on low numbers 1-18 (vs 19-36) \n" +
"betColumn amount, uint - bet on column 1 (4, 7, 10...), 2 (5, 8, 11...), or 3 (6, 9, 12...) \n" +
"betStreet amount, uint - bet on street 1 (2, 3), 4 (5, 6), 7 (8, 9), .... \n" +
"betDozen amount, uint - bet on the 1st, 2nd or 3rd dozen (out of 36) \n" +
"spin - spin the wheel \n" +
"pays - report the amount available to disburse \n" +
"disburse - send your winnings to your address \n" +
"man - man"
else
return
# doThing event.body, (err, response) ->
# sendNexusMessage err || response | true | somata = require 'somata'
config = require '../config'
SENDER = 'blockwoods-roulette'
NEXUS_ACCOUNT_ID = config.nexus.account_id
nexus_client = new somata.Client {registry_host: config.nexus.host}
client = new somata.Client()
announce = require('nexus-announce')(config.announce)
ContractsService = new somata.Client().bindRemote 'ethereum:contracts'
BlockwoodsEngine = client.bindRemote 'blockwoods:engine'
table_address = config.table_address
topic_base = "blockwoods:roulette:#{table_address}"
MAX_BET = 100000000000000000
wei_to_ether = 1000000000000000000
pending_spins = {}
parseSender = (event) ->
return event.sender.username
validateBetAmount = (amount) ->
if amount > MAX_BET
return false
else
return true
sendNexusMessage = (body, type='message') ->
response_message = {sender: SENDER, body, type}
nexus_client.remote 'nexus:events', 'send', NEXUS_ACCOUNT_ID, response_message, -> # ...
nexus_client.subscribe 'nexus:events', "event:#{NEXUS_ACCOUNT_ID}:#{SENDER}", (event) ->
console.log event
sender = parseSender event
switch sender
when 'sean'
account = 'PI:KEY:<KEY>END_PI'
when 'chad'
account = 'PI:KEY:<KEY>END_PI'
when 'bryn'
account = 'PI:KEY:<KEY>END_PI'
else
return
split_body = event.body.split(' ')
if split_body[0] == 'balance'
ContractsService 'getBalance', account, (err, resp) ->
if resp?
number = Number(resp) / wei_to_ether
sendNexusMessage number.toString()
else if split_body[0][0..2] == 'bet'
bet_amount = Number(split_body[1]) * wei_to_ether
bet_arg = split_body[2]
valid = validateBetAmount bet_amount
if !valid
return sendNexusMessage "Please bet below #{MAX_BET/wei_to_ether} ether."
bet_fn = split_body[0]
bet_kind = split_body[0][3..]
finishRoute = (err, resp) ->
sendNexusMessage 'Betting...'
data = {txid: resp}
data.bet_kind = bet_kind
data.amount = bet_amount
data.amount_str = (bet_amount/wei_to_ether + ' eth')
data.bet_fn = bet_fn
data.bet_arg = bet_arg
announce {type: 'bet', game: 'roulette', project: 'blockwoods', topic: topic_base, data}
# wait for result and then broadcast result
client.on 'blockwoods:engine', "tx:#{resp}:done", (result) ->
sendNexusMessage "#{sender}, your #{bet_kind} bet was placed"
# resolve pull
console.log "tx:#{result.outcome_tx}:done"
if bet_fn in ['betBlack', 'betOdd', 'betBlack', 'betLow']
# TODO: validate bool
ContractsService 'callFunction', 'RouletteTable', table_address, bet_fn, bet_arg, {account, value: bet_amount.toString(), gas: '220000'}, finishRoute
else if bet_fn in ['betStraightUp', 'betStreet', 'betColumn', 'betSixLine', 'betDozen']
ContractsService 'callFunction', 'RouletteTable', table_address, bet_fn, bet_arg, {account, value: bet_amount.toString(), gas: '220000'}, finishRoute
else if split_body[0] == 'spin'
ContractsService 'callFunction', 'RouletteTable', table_address, 'spinWheel', {account, value: '0', gas: '100000'}, (err, resp) ->
sendNexusMessage 'Spinning...'
# wait for result and then broadcast result
client.on 'blockwoods:engine', "tx:#{resp}:done", (result) ->
sendNexusMessage "#{sender}, your result was #{result.n}"
announce {type: 'play', game: 'roulette', project: 'blockwoods', topic: topic_base, data: {result, txid: result.outcome_tx}}
# resolve pull
console.log "tx:#{result.outcome_tx}:done"
client.on 'blockwoods:engine', "tx:#{result.outcome_tx}:done", (result) ->
console.log 'the result was', result
if result.result > 0
sendNexusMessage "WINNER! #{sender}, your bet was settled, paying #{result.result}:1"
else
sendNexusMessage "#{sender}, you lost. Keep gambling to try and win your money back."
else if split_body[0] == 'pays'
# query "pays" to see how much could be disbursed
ContractsService 'callFunction', 'RouletteTable', table_address, 'pays', account, {account}, (err, resp) ->
console.log err, resp
number = Number(resp) / wei_to_ether
console.log number
sendNexusMessage number.toString()
else if split_body[0] == 'disburse'
# do disbursal (send disburse from user's account)
ContractsService 'callFunction', 'RouletteTable', table_address, 'disburse', {account, gas: '75000'}, (err, resp) ->
console.log err, Number(resp)/wei_to_ether
if !err?
sendNexusMessage 'Disbursing...'
else if split_body[0] == 'man'
sendNexusMessage "balance - report the balance of your eve account \n" +
"betStraightUp amount, uint - bet on an exact number 0-37 (currently only allows one bet) \n" +
"betBlack amount, bool - bet on black numbers according to https://en.wikipedia.org/wiki/Roulette#Bet_odds_table\n" +
"betOdd amount, bool - bet on odd numbers \n" +
"betLow amount, bool - bet on low numbers 1-18 (vs 19-36) \n" +
"betColumn amount, uint - bet on column 1 (4, 7, 10...), 2 (5, 8, 11...), or 3 (6, 9, 12...) \n" +
"betStreet amount, uint - bet on street 1 (2, 3), 4 (5, 6), 7 (8, 9), .... \n" +
"betDozen amount, uint - bet on the 1st, 2nd or 3rd dozen (out of 36) \n" +
"spin - spin the wheel \n" +
"pays - report the amount available to disburse \n" +
"disburse - send your winnings to your address \n" +
"man - man"
else
return
# doThing event.body, (err, response) ->
# sendNexusMessage err || response |
[
{
"context": "sCollection\n) ->\n\n ###*\n # @author David Bouman\n # @module App\n # @submodule ",
"end": 495,
"score": 0.9997977614402771,
"start": 483,
"tag": "NAME",
"value": "David Bouman"
}
] | generators/app/templates/src/apis/env.coffee | marviq/generator-bat | 3 | 'use strict'
( ( factory ) ->
if typeof exports is 'object'
module.exports = factory(
require( 'madlib-settings' )
require( './../collections/api-services.coffee' )
)
else if typeof define is 'function' and define.amd
define( [
'madlib-settings'
'./../collections/api-services.coffee'
], factory )
return
)((
settings
ApiServicesCollection
) ->
###*
# @author David Bouman
# @module App
# @submodule Apis
###
###*
# A collection of services' endpoints available on the app's target-environment's API.
#
# @class EnvApi
# @static
###
new ApiServicesCollection(
[
###*
# Service API endpoint for retrieving the app's current build's {{#crossLink 'BuildBrief'}}briefing data{{/crossLink}}.
#
# This data includes:
#
# * `buildNumber`
# * `buildId`
# * `revision`
# * `grunted`
# * `environment`
# * `debugging`
# * `name`
# * `version`
# * `timestamp`
#
# @attribute buildBrief
# @type ApiServiceModel
# @final
#
# @default '<EnvApi.url>/build.json'
###
id: 'buildBrief'
urlPath: 'build.json'
,
###*
# Service API endpoint for retrieving the app's {{#crossLink 'SettingsEnvironment'}}target-environment settings{{/crossLink}}.
#
# These settings include:
#
# * `api`
# * `environment`<% if ( i18n ) { %>
# * `locales`<% } %>
#
# Once retrieved these can be referenced through the {{#crossLink 'Settings/environment:property'}}`environment` setting{{/crossLink}}.
#
# @attribute settingsEnvironment
# @type ApiServiceModel
# @final
#
# @default '<EnvApi.url>/settings.json'
###
id: 'settingsEnvironment'
urlPath: 'settings.json'
,
]
,
###*
# The `EnvApi`'s base url.
#
# Defined through the {{#crossLink 'Settings/appBaseUrl:property'}}`appBaseUrl` setting{{/crossLink}}.
#
# @property url
# @type String
# @final
#
# @default settings.get( 'appBaseUrl' )
###
url: settings.get( 'appBaseUrl' )
)
)
| 38808 | 'use strict'
( ( factory ) ->
if typeof exports is 'object'
module.exports = factory(
require( 'madlib-settings' )
require( './../collections/api-services.coffee' )
)
else if typeof define is 'function' and define.amd
define( [
'madlib-settings'
'./../collections/api-services.coffee'
], factory )
return
)((
settings
ApiServicesCollection
) ->
###*
# @author <NAME>
# @module App
# @submodule Apis
###
###*
# A collection of services' endpoints available on the app's target-environment's API.
#
# @class EnvApi
# @static
###
new ApiServicesCollection(
[
###*
# Service API endpoint for retrieving the app's current build's {{#crossLink 'BuildBrief'}}briefing data{{/crossLink}}.
#
# This data includes:
#
# * `buildNumber`
# * `buildId`
# * `revision`
# * `grunted`
# * `environment`
# * `debugging`
# * `name`
# * `version`
# * `timestamp`
#
# @attribute buildBrief
# @type ApiServiceModel
# @final
#
# @default '<EnvApi.url>/build.json'
###
id: 'buildBrief'
urlPath: 'build.json'
,
###*
# Service API endpoint for retrieving the app's {{#crossLink 'SettingsEnvironment'}}target-environment settings{{/crossLink}}.
#
# These settings include:
#
# * `api`
# * `environment`<% if ( i18n ) { %>
# * `locales`<% } %>
#
# Once retrieved these can be referenced through the {{#crossLink 'Settings/environment:property'}}`environment` setting{{/crossLink}}.
#
# @attribute settingsEnvironment
# @type ApiServiceModel
# @final
#
# @default '<EnvApi.url>/settings.json'
###
id: 'settingsEnvironment'
urlPath: 'settings.json'
,
]
,
###*
# The `EnvApi`'s base url.
#
# Defined through the {{#crossLink 'Settings/appBaseUrl:property'}}`appBaseUrl` setting{{/crossLink}}.
#
# @property url
# @type String
# @final
#
# @default settings.get( 'appBaseUrl' )
###
url: settings.get( 'appBaseUrl' )
)
)
| true | 'use strict'
( ( factory ) ->
if typeof exports is 'object'
module.exports = factory(
require( 'madlib-settings' )
require( './../collections/api-services.coffee' )
)
else if typeof define is 'function' and define.amd
define( [
'madlib-settings'
'./../collections/api-services.coffee'
], factory )
return
)((
settings
ApiServicesCollection
) ->
###*
# @author PI:NAME:<NAME>END_PI
# @module App
# @submodule Apis
###
###*
# A collection of services' endpoints available on the app's target-environment's API.
#
# @class EnvApi
# @static
###
new ApiServicesCollection(
[
###*
# Service API endpoint for retrieving the app's current build's {{#crossLink 'BuildBrief'}}briefing data{{/crossLink}}.
#
# This data includes:
#
# * `buildNumber`
# * `buildId`
# * `revision`
# * `grunted`
# * `environment`
# * `debugging`
# * `name`
# * `version`
# * `timestamp`
#
# @attribute buildBrief
# @type ApiServiceModel
# @final
#
# @default '<EnvApi.url>/build.json'
###
id: 'buildBrief'
urlPath: 'build.json'
,
###*
# Service API endpoint for retrieving the app's {{#crossLink 'SettingsEnvironment'}}target-environment settings{{/crossLink}}.
#
# These settings include:
#
# * `api`
# * `environment`<% if ( i18n ) { %>
# * `locales`<% } %>
#
# Once retrieved these can be referenced through the {{#crossLink 'Settings/environment:property'}}`environment` setting{{/crossLink}}.
#
# @attribute settingsEnvironment
# @type ApiServiceModel
# @final
#
# @default '<EnvApi.url>/settings.json'
###
id: 'settingsEnvironment'
urlPath: 'settings.json'
,
]
,
###*
# The `EnvApi`'s base url.
#
# Defined through the {{#crossLink 'Settings/appBaseUrl:property'}}`appBaseUrl` setting{{/crossLink}}.
#
# @property url
# @type String
# @final
#
# @default settings.get( 'appBaseUrl' )
###
url: settings.get( 'appBaseUrl' )
)
)
|
[
{
"context": "\nvorarlbergData = [\n {\n doctorName: 'Dr. Elmar Studer'\n stationName: ''\n address: '6700 B",
"end": 123,
"score": 0.999890923500061,
"start": 111,
"tag": "NAME",
"value": "Elmar Studer"
},
{
"context": "dContent: ''\n },\n {\n do... | source/auskunft/auskunftdata.coffee | JhonnyJason/gefaesse-website-sources | 0 | ############################################################
vorarlbergData = [
{
doctorName: 'Dr. Elmar Studer'
stationName: ''
address: '6700 Bludenz, Bahnhofplatz 1a'
phoneNumber: '<a href="tel:0555269096">05552 690 96</a>'
emailAddress: ''
website: ''
cardContent: ''
},
{
doctorName: 'Dr. Rainer Mathies'
stationName: 'Ordination/LKH Feldkirch'
address: '6800 Feldkirch, Carinagasse 47'
phoneNumber: '<a href="tel:+4355223034640">+43 552 2303 4640</a>'
emailAddress: '<a href="mailto:rainer.mathies@lkhf.at">rainer.mathies@lkhf.at</a>'
website: ''
cardContent: ''
}
]
############################################################
tirolData = [
{
doctorName: 'Ao.Univ.-Prof. Dr. Peter Marschang'
stationName: 'Universitätsklinik für Innere Medizin III (Kardiologie und Angiologie)'
address: '6020 Innsbruck, Anichstrass 35'
phoneNumber: '<a href="tel:+4351250481414">+43 5125 048 1414</a>'
emailAddress: '<a href="mailto:Peter.Marschang@i-med.ac.at">Peter.Marschang@i-med.ac.at</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. Elisabeth Strasser-Wozak'
stationName: 'FÄ f. Interne Medizin, Additivfach Angiologie'
address: '6060 Hall in Tirol, MEDZENTRUM Hall i T Behaimstrasse 2b, Haus B, 1. Stock'
phoneNumber: '<a href="tel:+435223 22443">+43 5223 22443</a>'
emailAddress: '<a href="mailto:strasser-wozak@angio-interne.at">strasser-wozak@angio-interne.at</a>'
website: '<a href="https://www.angio-interne.at">www.angio-interne.at</a>'
cardContent: ''
}
]
############################################################
salzburgData = []
############################################################
kaerntenData = []
############################################################
oberoesterreichData = [
{
doctorName: 'Prof. Dr. Josef Friedrich Hofer'
stationName: 'Praxis Dr. Hofer'
address: '4240 Freistadt, Etrichstraße 9-13'
phoneNumber: '<a href="tel:+43194273844">+ 43 1 794 273844</a>'
emailAddress: '<a href="mailto:internist@frei-stadt.at">internist@frei-stadt.at</a> (Fachärztezentrum Freistadt)'
website: ''
cardContent: ''
},
{
doctorName: 'OA. Dr. Gertraud Lang'
stationName: 'LKH Freistadt'
address: '4240 Freistadt, Krankenhausstrasse 1'
phoneNumber: '<a href="tel:+43794270024207">+43 7942 700 24207</a>'
emailAddress: '<a href="mailto:gertraud.lang@gespag.at">gertraud.lang@gespag.at</a>'
website: '<a href="https://www.lkh-freistadt.at">www.lkh-freistadt.at</a>'
cardContent: ''
}
]
############################################################
steiermarkData = [
{
doctorName: 'Univ. Prof. Dr. Ernst Pilger'
stationName: 'Kontaktperson Frau Andrea Schober'
address: '8010 Graz, Rosenberggasse 1'
phoneNumber: '<a href="tel:+43316830193">+43 316 830 193</a>'
emailAddress: '<a href="mailto:ordination@pilger-pilger.at">ordination@pilger-pilger.at</a>'
website: '<a href="https://www.pilger-pilger.at">www.pilger-pilger.at</a>'
cardContent: ''
},
{
doctorName: 'Prof. Rabl'
stationName: 'Privatordination Prof. Rabl'
address: '8700 Leoben, Peter Tunner Strasse 4/1'
phoneNumber: '<a href="tel:06765850693">0676 5850 693</a>'
emailAddress: '<a href="mailto:rabl@inode.at">rabl@inode.at</a>'
website: ''
cardContent: '''
<p class="detail-owner">Prof. Rabl</p>
<p class="detail-name">
Privatordination Prof. Rabl
</p>
<p>
8700 Leoben, Peter Tunner Strasse 4/1<br>
<a href="tel:06765850693">0676 5850 693</a><br>
<a href="mailto:rabl@inode.at">rabl@inode.at</a>
</p>
<p>
Und<br>
8010 Graz, Körblergasse 42<br>
Tel: <a href="tel:03163600997">0316 3600 997</a>
</p>
'''
},
{
doctorName: 'PD Dr. Franz Hafner'
stationName: 'Facharzt für Innere Medizin und Angiologie'
address: '8010 Graz, Elisabethstraße 54'
phoneNumber: '<a href="tel:066488188568">066488188568</a>'
emailAddress: '<a href="mailto:hafner@angiologe-graz.at">hafner@angiologe-graz.at</a>'
website: '<a href="https://www.angiologe-graz.at">www.angiologe-graz.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. Andreas Dorr'
stationName: ''
address: '8010 Graz, Hugo-Wolf-Gasse 6a'
phoneNumber: '<a href="tel:+436605391521">+ 43 660 539 1521</a>'
emailAddress: '<a href="mailto:ordination@docdorr.at">ordination@docdorr.at</a>'
website: '<a href="https://www.docdorr.at">www.docdorr.at</a>'
cardContent: ''
},
{
doctorName: 'Prim. Dr. Andreas Spary'
stationName: 'Zentrum für ambulante Rehabilitation Graz, Pensionsversicherung'
address: '8020 Graz, Eggenberger Straße 7'
phoneNumber: '<a href="tel:+435030384900">+ 43 503 03 84900</a>'
emailAddress: '<a href="mailto:andreas.spary@pensionsversicherung.at">andreas.spary@pensionsversicherung.at</a>'
website: '<a href="https://www.pv-rehabzentrum-graz.at">www.pv-rehabzentrum-graz.at</a>'
cardContent: ''
},
{
doctorName: ''
stationName: 'LKH-Univ. Klinikum Graz - Univ. Klinik für Innere Medizin'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: ''
emailAddress: ''
website: ''
cardContent: '''
<p class="detail-name">
LKH-Univ. Klinikum Graz - Univ. Klinik für Innere Medizin
</p>
<p>
suppl. Abteilungsleiter<br>
ao. Univ. Prof. Dr. Marianne Brodmann<br>
Angela Kroboth /Abteilungssekretariat<br>
Priska Hirschmann/Abteilungssekretariat<br>
</p>
<p>
Klin. Abteilung für Angiologie<br>
8036 Graz, Auenbruggerplatz 15<br>
Tel: <a href="tel:+4331638512911">+43 (316) 385-12911</a><br>
Fax: <a href="tel:+4331638513788">+43 (316) 385-13788</a><br>
E-mail: <a href="mailto:angela.kroboth@klinikum-graz.at">angela.kroboth@klinikum-graz.at</a><br>
E-mail: <a href="mailto:priska.hirschmann@klinikum-graz.at">priska.hirschmann@klinikum-graz.at</a>
<p>
<div class="further-details">
<h3>
Fachärzte Innere Medizin mit Zusatzfach Angiologie
</h3>
<p>
Ao. Univ. Prof. Dr. Marianne <b>BRODMANN</b><br>
Assoz. Prof. Priv.-Doz. Dr. Thomas <b>GARY</b><br>
Priv. Doz. Dr. Franz <b>HAFNER</b><br>
Ao. Univ. Prof. Dr. Andrea Obernosterer <b>OBERNOSTERER</b><br>
Dipl.-Ing. DDr. Ingrid <b>OSPRIAN</b><br>
Ass.-Prof. Dr.med.univ.et scient.med. Günther <b>SILBERNALGEL</b><br>
Ao. Univ. Prof. Dr. Gerald Seinost <b>STEINOST</b><br>
</p>
</div>
'''
},
{
doctorName: 'Ao. Univ. Prof. Dr. Marianne Brodmann'
stationName: 'Landeskrankenhaus-Universitätsklinikum Graz<br>Klinische Abteilung f. Angiologie'
address: '8036 Graz, Auenbruggerplatz 27'
phoneNumber: '<a href="tel:+4331638512911"> + 43 316 385 12911</a>'
emailAddress: '<a href="mailto:marianne.brodmann@medunigraz.at">marianne.brodmann@medunigraz.at</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Assoc. Prof. Priv.-Doz. Dr. Thomas Gary'
stationName: 'Medizinische Universitätsklinik Graz'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: '<a href="tel:+4331638512911">+43 316 385 12911</a>'
emailAddress: '<a href="mailto:thomas.gary@medunigraz.at">thomas.gary@medunigraz.at</a>'
website: '<a href="https://www.medunigraz.at">www.medunigraz.at</a>'
cardContent: ''
},
{
doctorName: 'PD Dr. Franz Hafner'
stationName: 'LKH Universitätsklinikum Graz<br>Univ. Klinik für Innere Medizin, Klinische Abteilung für Angiologie'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: '<a href="tel:+4331638512911">+43 316 385 12911</a>'
emailAddress: '<a href="mailto:franz.hafner@klinikum-graz.at">franz.hafner@klinikum-graz.at</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. Peter Rief'
stationName: 'Universitätsklinikum Graz, Innere Medizin, Angiologie'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: '<a href="tel:+4331638512911">+ 43 316 385 12911</a>'
emailAddress: '<a href="mailto:peter.rief@medunigraz.at">peter.rief@medunigraz.at</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. Edmund Pabst'
stationName: 'Facharzt ür Innere Medizin/Angiologie/Intensivmedizin'
address: '8530 Deutschlandsberg, Dr. Edmund Pabst Soloplatz 2'
phoneNumber: '<a href="tel:+4334623533">+43 3462 3533</a>'
emailAddress: '<a href="mailto:internist@drpabst.at">internist@drpabst.at</a>'
website: '<a href="https://www.drpabst.at">www.drpabst.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Ing. Dr. Gerhard Stark'
stationName: ''
address: '8562 Mooskirchen, Marktplatz 1'
phoneNumber: '<a href="tel:+43131373797">+ 43 1 313 73797</a>'
emailAddress: '<a href="mailto:gerhard.stark@a1.net">gerhard.stark@a1.net</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Prof. Rabl'
stationName: 'Privatordination Prof. Rabl'
address: '8010 Graz, Körblergasse 42'
phoneNumber: '<a href="tel:03163600997">0316 3600 997</a>'
emailAddress: '<a href="mailto:rabl@inode.at">rabl@inode.at</a>'
website: ''
cardContent: '''
<p class="detail-owner">Prof. Rabl</p>
<p class="detail-name">
Privatordination Prof. Rabl
</p>
<p>
8700 Leoben, Peter Tunner Strasse 4/1<br>
<a href="tel:06765850693">0676 5850 693</a><br>
<a href="mailto:rabl@inode.at">rabl@inode.at</a>
</p>
<p>
Und<br>
8010 Graz, Körblergasse 42<br>
Tel: <a href="tel:03163600997">0316 3600 997</a>
</p>
'''
}
]
############################################################
niederoesterreichData = [
{
doctorName: 'Dr. Sabine Hofmann'
stationName: 'Ordination Dr. Hofmann'
address: '2201 Gerasdorf bei Wien, Leopoldauerstraße 9'
phoneNumber: '<a href="tel:+43224628008">+43 224 628 008</a>'
emailAddress: '<a href="mailto:ordination@internist-gerasdorf.at">ordination@internist-gerasdorf.at</a>'
website: '<a href="https://www.internist-gerasdorf.at">www.internist-gerasdorf.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. Ybinger Christian'
stationName: '"Haus mit Herz"'
address: '2320 Schwechat, Mannswörtherstr 59-61/21'
phoneNumber: '<a href="tel:+43 706 86 00">+43 706 86 00</a>'
emailAddress: '<a href="mailto:christianybinger@yahoo.de">christianybinger@yahoo.de</a>'
website: '<a href="https://www.hausmitherz.at">www.hausmitherz.at</a>'
cardContent: ''
}
]
############################################################
wienData = [
{
doctorName: 'ao. Univ.-Prof. Dr. Wolfgang Mlekusch'
stationName: 'Gefäßspezialist'
address: '1010 Wien, Weihburggasse 18-20/linke Stiege/41'
phoneNumber: '<a href="tel:+4369910622695">+43 699 106 22695</a>'
emailAddress: '<a href="mailto:ordination@gefaessarzt.at">ordination@gefaessarzt.at</a>'
website: '<a href="https://www.gefaessarzt.at">www.gefaessarzt.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Dr. Andrea Willfort-Ehringer'
stationName: 'Health Consult'
address: '1010 Wien, Freyung 6'
phoneNumber: '<a href="tel:+431795808000">+43 1 795 80 8000</a>'
emailAddress: '<a href="mailto:andrea.willfort-ehringer@willfort-ehringer.at">andrea.willfort-ehringer@willfort-ehringer.at</a>'
website: '<a href="https://www.willfort-ehringer.at">www.willfort-ehringer.at</a>'
cardContent: ''
},
{
doctorName: 'Assoc. Prof. Priv.-Doz. Dr. Sophie Brunner-Ziegler'
stationName: 'MPH Wahlarztordination'
address: '1030 Wien, Neulinggasse 10'
phoneNumber: '<a href="tel:+4317144111">+ 43 1 714 4111</a>'
emailAddress: '<a href="mailto:sophie.ziegler@meduniwien.ac.at">sophie.ziegler@meduniwien.ac.at</a>'
website: '<a href="https://versuch-22.webnode.at/">versuch-22.webnode.at/</a>'
cardContent: ''
},
{
doctorName: 'Prim. Univ.Prof. Dr. Mirko Hirschl'
stationName: 'FA für innere Medizin und Angiologie M. Hirschl'
address: '1050 Wien, Blechturmgasse 14/6'
phoneNumber: '<a href="tel:+436508604387">+43 650 860 4387</a>'
emailAddress: '<a href="mailto:mirkohirschl@chello.at">mirkohirschl@chello.at</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Univ. Doz. Dr. M. Reza Mehrabi'
stationName: 'Ordination Ordination für Innere Medizin, Angiologie, Kardiologie'
address: '1050 Wien, Arbeitergasse 9/3'
phoneNumber: '<a href="tel:+4319203259">+43 1 920 3259</a>'
emailAddress: ''
website: '<a href="https://www.mehrabi.at">www.mehrabi.at</a>'
cardContent: ''
},
{
doctorName: 'Univ.-Prof. Dr. Gerald SEINOST'
stationName: 'Act now Präventivmedizin'
address: '1050 Wien, Strobachgasse 7-9'
phoneNumber: '<a href="tel:+4369910907060">+43 699 1090 7060</a>'
emailAddress: '<a href="mailto:gerald.seinost@act-now.at">gerald.seinost@act-now.at</a>'
website: '<a href="https://www.act-now.at">www.act-now.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. Michael Jung'
stationName: 'Dr. Jung und Partner Innere Medizin OG'
address: '1080 Wien, Strozzigasse 10'
phoneNumber: ''
emailAddress: '<a href="mailto:info@michael-jung.at">info@michael-jung.at</a>'
website: '<a href="https://">www.michael-jung.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Dr. Ronald Karnik'
stationName: ''
address: '1080 Wien, Zeltgasse 3-5/11'
phoneNumber: '<a href="tel:+4314067269">+43 1 406 7269</a>'
emailAddress: '<a href="mailto:ronald.karnik@aon.at">ronald.karnik@aon.at</a>'
website: '<a href="https://www.herzkatheter.at">www.herzkatheter.at</a>'
cardContent: ''
},
{
doctorName: 'Prim. Univ. Doz. Dr. Reinhold Katzenschlager'
stationName: ''
address: '1080 Wien, Skodagasse 32'
phoneNumber: '<a href="tel:+431401145701">+43 1 40114 5701</a>'
emailAddress: '<a href="mailto:reinhold.katzenschlager@gmx.at">reinhold.katzenschlager@gmx.at</a>'
website: ''
cardContent: ''
},
{
doctorName: ''
stationName: 'AKH Universitätsklinik für Innere Medizin II - Klinische Abteilung für Angiologie'
address: '1090 Wien, Währinger Gürtel 18-20'
phoneNumber: ''
emailAddress: ''
website: ''
cardContent: '''
<p class="detail-name">
AKH Universitätsklinik für Innere Medizin II - Klinische Abteilung für Angiologie
</p>
<p>
Univ. Prof. Dr. Renate Koppensteiner<br>
Barbara Stumpf-Fekete/Abteilungssekretariat
</p>
<p>
1090 Wien, Währinger Gürtel 18-20<br>
Tel: <a href="tel:+4314040046700">+43 (0)1 40400-46700</a><br>
Fax: <a href="tel:+4314040046650">+43 (0)1 40400-46650</a><br>
E-mail: <a href="mailto:barbara.stumpf-fekete@meduniwien.ac.at">barbara.stumpf-fekete@meduniwien.ac.at</a>
<p>
<div class="further-details">
<h3>
Fachärzte Innere Medizin mit Zusatzfach Angiologie
</h3>
<p>
Priv.-Doz. Dr. Jasmin <b>AMIGHI-KNAPP</b><br>
Assoc.-Prof. Priv.-Doz. Dr. Sophie <b>BRUNNER-ZIEGLER</b><br>
Dr. Georgiana-Aura <b>GIURGEA</b><br>
Assoc.-Prof. Priv.-Doz. Dr. Thomas <b>GREMMEL</b><br>
Ao.Univ.-Prof. Dr. Michael <b>GSCHWANDTNER</b><br>
Ass.-Prof. Priv.-Doz. Dr. Matthias <b>HOKE</b><br>
Ao.Univ.-Prof. Dr. Christoph <b>KOPP</b><br>
o. Univ.-Prof. Dr. Renate <b>KOPPENSTEINER</b><br>
Ao.Univ.-Prof. Dr. Erich <b>MINAR</b><br>
Ao.Univ.-Prof. Dr. Wolfgang <b>MLEKUSCH</b><br>
Priv.-Doz. Dr. Schila <b>SABETI-SANDOR</b><br>
Ao.Univ.-Prof. Dr. Gerit-Holger <b>SCHERNTHANER</b><br>
Assoc.-Prof. Priv.-Doz. Dr. Oliver <b>SCHLAGER</b><br>
Ao.Univ.-Prof. Dr. Andrea <b>WILLFORT-EHRINGER</b><br>
</p>
</div>
'''
},
{
doctorName: 'Univ.-Prof. Dr. Michael Gschwandtner'
stationName: 'Medizinische Universität Wien'
address: '1090 Wien, Währinger Gürtel 18-20'
phoneNumber: '<a href="tel:+4314040046700">+43 1 40400 46 700</a>'
emailAddress: '<a href="mailto:michael.gschwandtner@meduniwien.ac.at">michael.gschwandtner@meduniwien.ac.at</a>'
website: '<a href="https://innere-med-2.meduniwien.ac.at/angiologie/">innere-med-2.meduniwien.ac.at/angiologie/</a>'
cardContent: ''
},
{
doctorName: 'Prof. Dr. Erich Minar'
stationName: '(Neue Wiener Privatklinik)'
address: '1090 Wien, Pelikangasse 15'
phoneNumber: '<a href="tel:+431401802310">+43 1 401 802310</a>'
emailAddress: '<a href="mailto:erich.minar@meduniwien.ac.at">erich.minar@meduniwien.ac.at</a>'
website: '<a href="https://www.gefaesserkrankung.at">www.gefaesserkrankung.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Gerit-Holger Schernthaner'
stationName: ''
address: '1090 Wien, Schwarzspanierstrasse 15/9/9'
phoneNumber: '<a href="tel:+4314055196">+ 43 1 405 51 96</a>'
emailAddress: ''
website: ''
cardContent: ''
},
{
doctorName: 'Dr. Andreas Strümpflen'
stationName: 'FA f. Innere Medizin & Angiologie'
address: '1090 Wien, Alser Straße 18/35'
phoneNumber: '<a href="tel:+436643324078">+43 664 3324078</a>'
emailAddress: '<a href="mailto:stuempflen@aon.at">stuempflen@aon.at</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. Andrea-Eva Bartok-Heinrich'
stationName: 'Gesundheitszentrum Wien-Süd, Angiologie-Ambulanz'
address: '1100 Wien, Wienerbergstrasse 13'
phoneNumber: '<a href="tel:+431601224254">+43 1 60122 4254</a>'
emailAddress: '<a href="mailto:GEF10-2@wgkk.at">GEF10-2@wgkk.at</a>'
website: '<a href="https://www.wgkk.at">www.wgkk.at</a>'
cardContent: ''
},
{
doctorName: 'Prof. Dr. Thomas Gremmel'
stationName: 'Facharzt für Innere Medizin und Angiologie Prof. Dr. Thomas Gremmel'
address: '1130 Wien, Amalienstraße 53A/22'
phoneNumber: '<a href="tel:+4369910459023">+ 43 699 104 59023</a>'
emailAddress: '<a href="mailto:thomas.gremmel@meduniwien.ac.at">thomas.gremmel@meduniwien.ac.at</a>'
website: ''
cardContent: ''
},
{
doctorName: ''
stationName: 'Angiologie Hanuschkrankenhaus<br>angiologisches Sekretariat'
address: '1140 Wien, Heinrich Collinstrasse 30'
phoneNumber: '<a href="tel:+431910218611">+43 1 910 218 611</a>'
emailAddress: '<a href="mailto:petra.geritz@wgkk.at">petra.geritz@wgkk.at</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Prim. Univ. Prof. Dr. Mirko Hirschl'
stationName: 'Hanusch-Krankenhaus<br>Wiener Gebietskrankenkasse'
address: '1140 Wien, Heinrich-Collin-Straße 30'
phoneNumber: '<a href="tel:+4319102186130">+43 1 910 21-86130</a>'
emailAddress: '<a href="mailto:hkh.angiologische.amb@wgkk.at">hkh.angiologische.amb@wgkk.at</a>'
website: ''
cardContent: ''
},
{
doctorName: ''
stationName: 'Krankenhaus Göttlicher Heiland'
address: '1170 Wien, Dornbacher Strasse 20-28'
phoneNumber: '<a href="tel:"></a>'
emailAddress: '<a href="mailto:"></a>'
website: '<a href="https://"></a>'
cardContent: '''
<p>
Krankenhaus Göttlicher Heiland<br>
1 Interne Abteilung<br>
Vorstand: Prim. Univ.Doz. Dr. Reinhold Katzenschlager
</p>
<p>
1170 Wien, Dornbacher Strasse 20-28<br>
Tel: <a href="tel:+431400881110">+43 1 40088 1110</a><br>
E-Mail: <a href="mailto:interne1@khgh.at">interne1@khgh.at</a><br>
Webseite: <a href="https://www.khgh.at">www.khgh.at</a>
</p>
'''
},
{
doctorName: ''
stationName: 'Ambulatorium Döbling'
address: '1190 Wien, Billrothstrasse 49a'
phoneNumber: '<a href="tel:+431360665575">+43 1 36066 5575</a>'
emailAddress: ''
website: '<a href="https://www.ambulatorium-doebling.at/de/ambulanzen-institute-zentren/innere-medizin.html">www.ambulatorium-doebling.at/de/ambulanzen-institute-zentren/innere-medizin.html</a>'
cardContent: ''
},
{
doctorName: 'Univ.-Prof. Dr. Michael Gschwandtner'
stationName: 'Angiologie, Innere Medizin'
address: '1190 Wien, Heiligenstädter Straße 69 / Top 12'
phoneNumber: '<a href="tel:06802477278">0680 / 24 77 278</a>'
emailAddress: '<a href="mailto:ordination@gschwandtner-angiologie.at">ordination@gschwandtner-angiologie.at</a>'
website: '<a href="https://www.gschwandtner-angiologie.at">www.gschwandtner-angiologie.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. Gerhard Bonner'
stationName: ''
address: '1190 Wien, Obkirchergasse 43/8'
phoneNumber: '<a href="tel:+4313204141">+43 1 320 41 41</a>'
emailAddress: '<a href="mailto:gerhard.bonner@chello.at">gerhard.bonner@chello.at</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. med. Elisabeth Singer'
stationName: 'Praxis für Venenheilkunde'
address: '1190 Wien, Billrothstrasse 49a'
phoneNumber: '<a href="tel:+436506919779">+43 650 691 9779</a>'
emailAddress: ''
website: '<a href="https://www.drsinger.at">www.drsinger.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. Gerald Schnürer'
stationName: 'Schnürer & Fritsch Gruppenpraxis für Innere Medizin'
address: '1230 Wien, Geßlgasse 19/1'
phoneNumber: '<a href="tel:+43188813790">+ 43 1 888 13790</a>'
emailAddress: '<a href="mailto:office@kardio23.at">office@kardio23.at</a>'
website: '<a href="https://www.kardio23.at">www.kardio23.at</a>'
cardContent: ''
}
]
############################################################
burgenlandData = []
############################################################
allData =
vorarlberg: vorarlbergData
tirol: tirolData
salzburg: salzburgData
kaernten: kaerntenData
oberoesterreich: oberoesterreichData
steiermark: steiermarkData
niederoesterreich: niederoesterreichData
wien: wienData
burgenland: burgenlandData
module.exports = allData | 137888 | ############################################################
vorarlbergData = [
{
doctorName: 'Dr. <NAME>'
stationName: ''
address: '6700 Bludenz, Bahnhofplatz 1a'
phoneNumber: '<a href="tel:0555269096">05552 690 96</a>'
emailAddress: ''
website: ''
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: 'Ordination/LKH Feldkirch'
address: '6800 Feldkirch, Carinagasse 47'
phoneNumber: '<a href="tel:+4355223034640">+43 552 2303 4640</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
}
]
############################################################
tirolData = [
{
doctorName: 'Ao.Univ.-Prof. Dr. <NAME>'
stationName: 'Universitätsklinik für Innere Medizin III (Kardiologie und Angiologie)'
address: '6020 Innsbruck, Anichstrass 35'
phoneNumber: '<a href="tel:+4351250481414">+43 5125 048 1414</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: 'FÄ f. Interne Medizin, Additivfach Angiologie'
address: '6060 Hall in Tirol, MEDZENTRUM Hall i T Behaimstrasse 2b, Haus B, 1. Stock'
phoneNumber: '<a href="tel:+435223 22443">+43 5223 22443</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.angio-interne.at">www.angio-interne.at</a>'
cardContent: ''
}
]
############################################################
salzburgData = []
############################################################
kaerntenData = []
############################################################
oberoesterreichData = [
{
doctorName: 'Prof. Dr. <NAME>'
stationName: 'Praxis Dr. Hofer'
address: '4240 Freistadt, Etrichstraße 9-13'
phoneNumber: '<a href="tel:+43194273844">+ 43 1 794 273844</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a> (Fachärztezentrum Freistadt)'
website: ''
cardContent: ''
},
{
doctorName: 'OA. Dr. <NAME>'
stationName: 'LKH Freistadt'
address: '4240 Freistadt, Krankenhausstrasse 1'
phoneNumber: '<a href="tel:+43794270024207">+43 7942 700 24207</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.lkh-freistadt.at">www.lkh-freistadt.at</a>'
cardContent: ''
}
]
############################################################
steiermarkData = [
{
doctorName: 'Univ. Prof. Dr. <NAME>'
stationName: 'Kontaktperson <NAME>ra<NAME> <NAME>'
address: '8010 Graz, Rosenberggasse 1'
phoneNumber: '<a href="tel:+43316830193">+43 316 830 193</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.pilger-pilger.at">www.pilger-pilger.at</a>'
cardContent: ''
},
{
doctorName: '<NAME>. <NAME>'
stationName: 'Privatordination Prof. Rabl'
address: '8700 Leoben, Peter Tunner Strasse 4/1'
phoneNumber: '<a href="tel:06765850693">0676 5850 693</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: '''
<p class="detail-owner">Prof. <NAME></p>
<p class="detail-name">
Privatordination Prof. <NAME>
</p>
<p>
8700 Leoben, Peter Tunner Strasse 4/1<br>
<a href="tel:06765850693">0676 5850 693</a><br>
<a href="mailto:<EMAIL>"><EMAIL></a>
</p>
<p>
Und<br>
8010 Graz, Körblergasse 42<br>
Tel: <a href="tel:03163600997">0316 3600 997</a>
</p>
'''
},
{
doctorName: 'PD Dr. <NAME>'
stationName: 'Facharzt für Innere Medizin und Angiologie'
address: '8010 Graz, Elisabethstraße 54'
phoneNumber: '<a href="tel:066488188568">066488188568</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.angiologe-graz.at">www.angiologe-graz.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: ''
address: '8010 Graz, Hugo-Wolf-Gasse 6a'
phoneNumber: '<a href="tel:+436605391521">+ 43 660 539 1521</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.docdorr.at">www.docdorr.at</a>'
cardContent: ''
},
{
doctorName: 'Prim. Dr. <NAME>'
stationName: 'Zentrum für ambulante Rehabilitation Graz, Pensionsversicherung'
address: '8020 Graz, Eggenberger Straße 7'
phoneNumber: '<a href="tel:+435030384900">+ 43 503 03 84900</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.pv-rehabzentrum-graz.at">www.pv-rehabzentrum-graz.at</a>'
cardContent: ''
},
{
doctorName: ''
stationName: 'LKH-Univ. Klinikum Graz - Univ. Klinik für Innere Medizin'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: ''
emailAddress: ''
website: ''
cardContent: '''
<p class="detail-name">
LKH-Univ. Klinikum Graz - Univ. Klinik für Innere Medizin
</p>
<p>
suppl. Abteilungsleiter<br>
ao. Univ. Prof. Dr. <NAME><br>
<NAME> /Abteilungssekretariat<br>
<NAME>/Abteilungssekretariat<br>
</p>
<p>
Klin. Abteilung für Angiologie<br>
8036 Graz, Auenbruggerplatz 15<br>
Tel: <a href="tel:+4331638512911">+43 (316) 385-12911</a><br>
Fax: <a href="tel:+4331638513788">+43 (316) 385-13788</a><br>
E-mail: <a href="mailto:<EMAIL>"><EMAIL></a><br>
E-mail: <a href="mailto:<EMAIL>"><EMAIL></a>
<p>
<div class="further-details">
<h3>
Fachärzte Innere Medizin mit Zusatzfach Angiologie
</h3>
<p>
Ao. Univ. Prof. Dr. <NAME> <b><NAME></b><br>
Assoz. Prof. Priv.-Doz. Dr. <NAME> <b><NAME></b><br>
Priv. Doz. Dr. <NAME> <b><NAME></b><br>
Ao. Univ. Prof. Dr. <NAME> <b>OBERNOSTERER</b><br>
Dipl.-Ing. DDr. Ingrid <b>OSPRIAN</b><br>
Ass.-Prof. Dr.med.univ.et scient.med. Günther <b>SILBERNALGEL</b><br>
Ao. Univ. Prof. Dr. <NAME> <b>STEINOST</b><br>
</p>
</div>
'''
},
{
doctorName: 'Ao. Univ. Prof. Dr. <NAME>'
stationName: 'Landeskrankenhaus-Universitätsklinikum Graz<br>Klinische Abteilung f. Angiologie'
address: '8036 Graz, Auenbruggerplatz 27'
phoneNumber: '<a href="tel:+4331638512911"> + 43 316 385 12911</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: 'Assoc. Prof. Priv.-Doz. Dr. <NAME>'
stationName: 'Medizinische Universitätsklinik Graz'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: '<a href="tel:+4331638512911">+43 316 385 12911</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.medunigraz.at">www.medunigraz.at</a>'
cardContent: ''
},
{
doctorName: 'PD Dr. <NAME>'
stationName: 'LKH Universitätsklinikum Graz<br>Univ. Klinik für Innere Medizin, Klinische Abteilung für Angiologie'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: '<a href="tel:+4331638512911">+43 316 385 12911</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: 'Universitätsklinikum Graz, Innere Medizin, Angiologie'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: '<a href="tel:+4331638512911">+ 43 316 385 12911</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: 'Facharzt ür Innere Medizin/Angiologie/Intensivmedizin'
address: '8530 Deutschlandsberg, Dr. Edmund Pabst Soloplatz 2'
phoneNumber: '<a href="tel:+4334623533">+43 3462 3533</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.drpabst.at">www.drpabst.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Ing. Dr. <NAME>'
stationName: ''
address: '8562 Mooskirchen, Marktplatz 1'
phoneNumber: '<a href="tel:+43131373797">+ 43 1 313 73797</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: '<NAME>. <NAME>'
stationName: 'Privatordination Prof. Rabl'
address: '8010 Graz, Körblergasse 42'
phoneNumber: '<a href="tel:03163600997">0316 3600 997</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: '''
<p class="detail-owner">Prof. <NAME></p>
<p class="detail-name">
Privatordination Prof. <NAME>
</p>
<p>
8700 Leoben, <NAME> Strasse 4/1<br>
<a href="tel:06765850693">0676 5850 693</a><br>
<a href="mailto:<EMAIL>"><EMAIL></a>
</p>
<p>
Und<br>
8010 Graz, Körblergasse 42<br>
Tel: <a href="tel:03163600997">0316 3600 997</a>
</p>
'''
}
]
############################################################
niederoesterreichData = [
{
doctorName: 'Dr. <NAME>'
stationName: 'Ordination Dr. Hofmann'
address: '2201 Gerasdorf bei Wien, Leopoldauerstraße 9'
phoneNumber: '<a href="tel:+43224628008">+43 224 628 008</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.internist-gerasdorf.at">www.internist-gerasdorf.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: '"Haus mit Herz"'
address: '2320 Schwechat, Mannswörtherstr 59-61/21'
phoneNumber: '<a href="tel:+43 706 86 00">+43 706 86 00</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.hausmitherz.at">www.hausmitherz.at</a>'
cardContent: ''
}
]
############################################################
wienData = [
{
doctorName: 'ao. Univ.-Prof. Dr. <NAME>'
stationName: 'Gefäßspezialist'
address: '1010 Wien, Weihburggasse 18-20/linke Stiege/41'
phoneNumber: '<a href="tel:+4369910622695">+43 699 106 22695</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.gefaessarzt.at">www.gefaessarzt.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Dr. <NAME>'
stationName: 'Health Consult'
address: '1010 Wien, Freyung 6'
phoneNumber: '<a href="tel:+431795808000">+43 1 795 80 8000</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.willfort-ehringer.at">www.willfort-ehringer.at</a>'
cardContent: ''
},
{
doctorName: 'Assoc. Prof. Priv.-Doz. Dr. <NAME>'
stationName: 'MPH Wahlarztordination'
address: '1030 Wien, Neulinggasse 10'
phoneNumber: '<a href="tel:+4317144111">+ 43 1 714 4111</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://versuch-22.webnode.at/">versuch-22.webnode.at/</a>'
cardContent: ''
},
{
doctorName: 'Prim. Univ.Prof. Dr. <NAME>'
stationName: 'FA für innere Medizin und Angiologie M. Hirschl'
address: '1050 Wien, Blechturmgasse 14/6'
phoneNumber: '<a href="tel:+436508604387">+43 650 860 4387</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: 'Univ. <NAME>z. Dr. <NAME>'
stationName: 'Ordination Ordination für Innere Medizin, Angiologie, Kardiologie'
address: '1050 Wien, Arbeitergasse 9/3'
phoneNumber: '<a href="tel:+4319203259">+43 1 920 3259</a>'
emailAddress: ''
website: '<a href="https://www.mehrabi.at">www.mehrabi.at</a>'
cardContent: ''
},
{
doctorName: 'Univ.-Prof. Dr. <NAME>'
stationName: 'Act now Präventivmedizin'
address: '1050 Wien, Strobachgasse 7-9'
phoneNumber: '<a href="tel:+4369910907060">+43 699 1090 7060</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.act-now.at">www.act-now.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: 'Dr. Jung und Partner Innere Medizin OG'
address: '1080 Wien, Strozzigasse 10'
phoneNumber: ''
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://">www.michael-jung.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Dr. <NAME>'
stationName: ''
address: '1080 Wien, Zeltgasse 3-5/11'
phoneNumber: '<a href="tel:+4314067269">+43 1 406 7269</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.herzkatheter.at">www.herzkatheter.at</a>'
cardContent: ''
},
{
doctorName: 'Prim. Univ. Doz. Dr. <NAME>'
stationName: ''
address: '1080 Wien, Skodagasse 32'
phoneNumber: '<a href="tel:+431401145701">+43 1 40114 5701</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: ''
stationName: 'AKH Universitätsklinik für Innere Medizin II - Klinische Abteilung für Angiologie'
address: '1090 Wien, Währinger Gürtel 18-20'
phoneNumber: ''
emailAddress: ''
website: ''
cardContent: '''
<p class="detail-name">
AKH Universitätsklinik für Innere Medizin II - Klinische Abteilung für Angiologie
</p>
<p>
Univ. Prof. Dr. <NAME><br>
<NAME>-Fekete/Abteilungssekretariat
</p>
<p>
1090 Wien, Währinger Gürtel 18-20<br>
Tel: <a href="tel:+4314040046700">+43 (0)1 40400-46700</a><br>
Fax: <a href="tel:+4314040046650">+43 (0)1 40400-46650</a><br>
E-mail: <a href="mailto:<EMAIL>"><EMAIL></a>
<p>
<div class="further-details">
<h3>
Fachärzte Innere Medizin mit Zusatzfach Angiologie
</h3>
<p>
Priv.-Doz. Dr. <NAME> <b>AMIGHI-KNAPP</b><br>
Assoc.-Prof. Priv.-Doz. Dr. <NAME> <b>BRUNNER-ZIEGLER</b><br>
Dr. <NAME> <b>GIURGEA</b><br>
Assoc.-Prof. Priv.-Doz. Dr. <NAME> <b>GREMMEL</b><br>
Ao.Univ.-Prof. Dr. <NAME> <b><NAME></b><br>
Ass.-Prof. Priv.-Doz. Dr. <NAME> <b><NAME></b><br>
Ao.Univ.-Prof. Dr. <NAME> <b>KOPP</b><br>
o. Univ.-Prof. Dr. <NAME> <b>KOPPENSTEINER</b><br>
Ao.Univ.-Prof. Dr. <NAME> <b>MINAR</b><br>
Ao.Univ.-Prof. Dr. Wol<NAME> <b>MLEKUSCH</b><br>
Priv.-Doz. Dr. <NAME>ila <b>SABETI-SANDOR</b><br>
Ao.Univ.-Prof. Dr. <NAME>-<NAME> <b>SCHERNTHANER</b><br>
Assoc.-Prof. Priv.-Doz. Dr. <NAME> <b>SCHLAGER</b><br>
Ao.Univ.-Prof. Dr. <NAME> <b>WILLFORT-EHRINGER</b><br>
</p>
</div>
'''
},
{
doctorName: 'Univ.-Prof. Dr. <NAME>'
stationName: 'Medizinische Universität Wien'
address: '1090 Wien, Währinger Gürtel 18-20'
phoneNumber: '<a href="tel:+4314040046700">+43 1 40400 46 700</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://innere-med-2.meduniwien.ac.at/angiologie/">innere-med-2.meduniwien.ac.at/angiologie/</a>'
cardContent: ''
},
{
doctorName: 'Prof. Dr. <NAME>'
stationName: '(Neue Wiener Privatklinik)'
address: '1090 Wien, Pelikangasse 15'
phoneNumber: '<a href="tel:+431401802310">+43 1 401 802310</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.gefaesserkrankung.at">www.gefaesserkrankung.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. <NAME>'
stationName: ''
address: '1090 Wien, Schwarzspanierstrasse 15/9/9'
phoneNumber: '<a href="tel:+4314055196">+ 43 1 405 51 96</a>'
emailAddress: ''
website: ''
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: 'FA f. Innere Medizin & Angiologie'
address: '1090 Wien, Alser Straße 18/35'
phoneNumber: '<a href="tel:+436643324078">+43 664 3324078</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: 'Gesundheitszentrum Wien-Süd, Angiologie-Ambulanz'
address: '1100 Wien, Wienerbergstrasse 13'
phoneNumber: '<a href="tel:+431601224254">+43 1 60122 4254</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.wgkk.at">www.wgkk.at</a>'
cardContent: ''
},
{
doctorName: 'Prof. Dr. <NAME>'
stationName: 'Facharzt für Innere Medizin und Angiologie Prof. Dr. <NAME>'
address: '1130 Wien, Amalienstraße 53A/22'
phoneNumber: '<a href="tel:+4369910459023">+ 43 699 104 59023</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: ''
stationName: 'Angiologie Hanuschkrankenhaus<br>angiologisches Sekretariat'
address: '1140 Wien, Heinrich Collinstrasse 30'
phoneNumber: '<a href="tel:+431910218611">+43 1 910 218 611</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: 'Prim. Univ. Prof. Dr. <NAME>'
stationName: '<NAME>-K<NAME>kenhaus<br><NAME>'
address: '1140 Wien, Heinrich-Collin-Straße 30'
phoneNumber: '<a href="tel:+4319102186130">+43 1 910 21-86130</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: ''
stationName: '<NAME>'
address: '1170 Wien, Dornbacher Strasse 20-28'
phoneNumber: '<a href="tel:"></a>'
emailAddress: '<a href="mailto:"></a>'
website: '<a href="https://"></a>'
cardContent: '''
<p>
<NAME><br>
1 Interne Abteilung<br>
Vorstand: Prim. Univ.Doz. Dr. <NAME>ens<NAME>
</p>
<p>
1170 Wien, Dornbacher Strasse 20-28<br>
Tel: <a href="tel:+431400881110">+43 1 40088 1110</a><br>
E-Mail: <a href="mailto:<EMAIL>"><EMAIL></a><br>
Webseite: <a href="https://www.khgh.at">www.khgh.at</a>
</p>
'''
},
{
doctorName: ''
stationName: 'Ambulatorium Döbling'
address: '1190 Wien, Billrothstrasse 49a'
phoneNumber: '<a href="tel:+431360665575">+43 1 36066 5575</a>'
emailAddress: ''
website: '<a href="https://www.ambulatorium-doebling.at/de/ambulanzen-institute-zentren/innere-medizin.html">www.ambulatorium-doebling.at/de/ambulanzen-institute-zentren/innere-medizin.html</a>'
cardContent: ''
},
{
doctorName: 'Univ.-Prof. Dr. <NAME>'
stationName: 'Angiologie, Innere Medizin'
address: '1190 Wien, Heiligenstädter Straße 69 / Top 12'
phoneNumber: '<a href="tel:06802477278">0680 / 24 77 278</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.gschwandtner-angiologie.at">www.gschwandtner-angiologie.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: ''
address: '1190 Wien, Obkirchergasse 43/8'
phoneNumber: '<a href="tel:+4313204141">+43 1 320 41 41</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. med. <NAME>'
stationName: 'Praxis für Venenheilkunde'
address: '1190 Wien, Billrothstrasse 49a'
phoneNumber: '<a href="tel:+436506919779">+43 650 691 9779</a>'
emailAddress: ''
website: '<a href="https://www.drsinger.at">www.drsinger.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. <NAME>'
stationName: 'Schnürer & Fritsch Gruppenpraxis für Innere Medizin'
address: '1230 Wien, Geßlgasse 19/1'
phoneNumber: '<a href="tel:+43188813790">+ 43 1 888 13790</a>'
emailAddress: '<a href="mailto:<EMAIL>"><EMAIL></a>'
website: '<a href="https://www.kardio23.at">www.kardio23.at</a>'
cardContent: ''
}
]
############################################################
burgenlandData = []
############################################################
allData =
vorarlberg: vorarlbergData
tirol: tirolData
salzburg: salzburgData
kaernten: kaerntenData
oberoesterreich: oberoesterreichData
steiermark: steiermarkData
niederoesterreich: niederoesterreichData
wien: wienData
burgenland: burgenlandData
module.exports = allData | true | ############################################################
vorarlbergData = [
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: ''
address: '6700 Bludenz, Bahnhofplatz 1a'
phoneNumber: '<a href="tel:0555269096">05552 690 96</a>'
emailAddress: ''
website: ''
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: 'Ordination/LKH Feldkirch'
address: '6800 Feldkirch, Carinagasse 47'
phoneNumber: '<a href="tel:+4355223034640">+43 552 2303 4640</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
}
]
############################################################
tirolData = [
{
doctorName: 'Ao.Univ.-Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Universitätsklinik für Innere Medizin III (Kardiologie und Angiologie)'
address: '6020 Innsbruck, Anichstrass 35'
phoneNumber: '<a href="tel:+4351250481414">+43 5125 048 1414</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: 'FÄ f. Interne Medizin, Additivfach Angiologie'
address: '6060 Hall in Tirol, MEDZENTRUM Hall i T Behaimstrasse 2b, Haus B, 1. Stock'
phoneNumber: '<a href="tel:+435223 22443">+43 5223 22443</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.angio-interne.at">www.angio-interne.at</a>'
cardContent: ''
}
]
############################################################
salzburgData = []
############################################################
kaerntenData = []
############################################################
oberoesterreichData = [
{
doctorName: 'Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Praxis Dr. Hofer'
address: '4240 Freistadt, Etrichstraße 9-13'
phoneNumber: '<a href="tel:+43194273844">+ 43 1 794 273844</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a> (Fachärztezentrum Freistadt)'
website: ''
cardContent: ''
},
{
doctorName: 'OA. Dr. PI:NAME:<NAME>END_PI'
stationName: 'LKH Freistadt'
address: '4240 Freistadt, Krankenhausstrasse 1'
phoneNumber: '<a href="tel:+43794270024207">+43 7942 700 24207</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.lkh-freistadt.at">www.lkh-freistadt.at</a>'
cardContent: ''
}
]
############################################################
steiermarkData = [
{
doctorName: 'Univ. Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Kontaktperson PI:NAME:<NAME>END_PIraPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
address: '8010 Graz, Rosenberggasse 1'
phoneNumber: '<a href="tel:+43316830193">+43 316 830 193</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.pilger-pilger.at">www.pilger-pilger.at</a>'
cardContent: ''
},
{
doctorName: 'PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI'
stationName: 'Privatordination Prof. Rabl'
address: '8700 Leoben, Peter Tunner Strasse 4/1'
phoneNumber: '<a href="tel:06765850693">0676 5850 693</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: '''
<p class="detail-owner">Prof. PI:NAME:<NAME>END_PI</p>
<p class="detail-name">
Privatordination Prof. PI:NAME:<NAME>END_PI
</p>
<p>
8700 Leoben, Peter Tunner Strasse 4/1<br>
<a href="tel:06765850693">0676 5850 693</a><br>
<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>
</p>
<p>
Und<br>
8010 Graz, Körblergasse 42<br>
Tel: <a href="tel:03163600997">0316 3600 997</a>
</p>
'''
},
{
doctorName: 'PD Dr. PI:NAME:<NAME>END_PI'
stationName: 'Facharzt für Innere Medizin und Angiologie'
address: '8010 Graz, Elisabethstraße 54'
phoneNumber: '<a href="tel:066488188568">066488188568</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.angiologe-graz.at">www.angiologe-graz.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: ''
address: '8010 Graz, Hugo-Wolf-Gasse 6a'
phoneNumber: '<a href="tel:+436605391521">+ 43 660 539 1521</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.docdorr.at">www.docdorr.at</a>'
cardContent: ''
},
{
doctorName: 'Prim. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Zentrum für ambulante Rehabilitation Graz, Pensionsversicherung'
address: '8020 Graz, Eggenberger Straße 7'
phoneNumber: '<a href="tel:+435030384900">+ 43 503 03 84900</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.pv-rehabzentrum-graz.at">www.pv-rehabzentrum-graz.at</a>'
cardContent: ''
},
{
doctorName: ''
stationName: 'LKH-Univ. Klinikum Graz - Univ. Klinik für Innere Medizin'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: ''
emailAddress: ''
website: ''
cardContent: '''
<p class="detail-name">
LKH-Univ. Klinikum Graz - Univ. Klinik für Innere Medizin
</p>
<p>
suppl. Abteilungsleiter<br>
ao. Univ. Prof. Dr. PI:NAME:<NAME>END_PI<br>
PI:NAME:<NAME>END_PI /Abteilungssekretariat<br>
PI:NAME:<NAME>END_PI/Abteilungssekretariat<br>
</p>
<p>
Klin. Abteilung für Angiologie<br>
8036 Graz, Auenbruggerplatz 15<br>
Tel: <a href="tel:+4331638512911">+43 (316) 385-12911</a><br>
Fax: <a href="tel:+4331638513788">+43 (316) 385-13788</a><br>
E-mail: <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a><br>
E-mail: <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>
<p>
<div class="further-details">
<h3>
Fachärzte Innere Medizin mit Zusatzfach Angiologie
</h3>
<p>
Ao. Univ. Prof. Dr. PI:NAME:<NAME>END_PI <b>PI:NAME:<NAME>END_PI</b><br>
Assoz. Prof. Priv.-Doz. Dr. PI:NAME:<NAME>END_PI <b>PI:NAME:<NAME>END_PI</b><br>
Priv. Doz. Dr. PI:NAME:<NAME>END_PI <b>PI:NAME:<NAME>END_PI</b><br>
Ao. Univ. Prof. Dr. PI:NAME:<NAME>END_PI <b>OBERNOSTERER</b><br>
Dipl.-Ing. DDr. Ingrid <b>OSPRIAN</b><br>
Ass.-Prof. Dr.med.univ.et scient.med. Günther <b>SILBERNALGEL</b><br>
Ao. Univ. Prof. Dr. PI:NAME:<NAME>END_PI <b>STEINOST</b><br>
</p>
</div>
'''
},
{
doctorName: 'Ao. Univ. Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Landeskrankenhaus-Universitätsklinikum Graz<br>Klinische Abteilung f. Angiologie'
address: '8036 Graz, Auenbruggerplatz 27'
phoneNumber: '<a href="tel:+4331638512911"> + 43 316 385 12911</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Assoc. Prof. Priv.-Doz. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Medizinische Universitätsklinik Graz'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: '<a href="tel:+4331638512911">+43 316 385 12911</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.medunigraz.at">www.medunigraz.at</a>'
cardContent: ''
},
{
doctorName: 'PD Dr. PI:NAME:<NAME>END_PI'
stationName: 'LKH Universitätsklinikum Graz<br>Univ. Klinik für Innere Medizin, Klinische Abteilung für Angiologie'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: '<a href="tel:+4331638512911">+43 316 385 12911</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: 'Universitätsklinikum Graz, Innere Medizin, Angiologie'
address: '8036 Graz, Auenbruggerplatz 15'
phoneNumber: '<a href="tel:+4331638512911">+ 43 316 385 12911</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: 'Facharzt ür Innere Medizin/Angiologie/Intensivmedizin'
address: '8530 Deutschlandsberg, Dr. Edmund Pabst Soloplatz 2'
phoneNumber: '<a href="tel:+4334623533">+43 3462 3533</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.drpabst.at">www.drpabst.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Ing. Dr. PI:NAME:<NAME>END_PI'
stationName: ''
address: '8562 Mooskirchen, Marktplatz 1'
phoneNumber: '<a href="tel:+43131373797">+ 43 1 313 73797</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: 'PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI'
stationName: 'Privatordination Prof. Rabl'
address: '8010 Graz, Körblergasse 42'
phoneNumber: '<a href="tel:03163600997">0316 3600 997</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: '''
<p class="detail-owner">Prof. PI:NAME:<NAME>END_PI</p>
<p class="detail-name">
Privatordination Prof. PI:NAME:<NAME>END_PI
</p>
<p>
8700 Leoben, PI:NAME:<NAME>END_PI Strasse 4/1<br>
<a href="tel:06765850693">0676 5850 693</a><br>
<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>
</p>
<p>
Und<br>
8010 Graz, Körblergasse 42<br>
Tel: <a href="tel:03163600997">0316 3600 997</a>
</p>
'''
}
]
############################################################
niederoesterreichData = [
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: 'Ordination Dr. Hofmann'
address: '2201 Gerasdorf bei Wien, Leopoldauerstraße 9'
phoneNumber: '<a href="tel:+43224628008">+43 224 628 008</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.internist-gerasdorf.at">www.internist-gerasdorf.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: '"Haus mit Herz"'
address: '2320 Schwechat, Mannswörtherstr 59-61/21'
phoneNumber: '<a href="tel:+43 706 86 00">+43 706 86 00</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.hausmitherz.at">www.hausmitherz.at</a>'
cardContent: ''
}
]
############################################################
wienData = [
{
doctorName: 'ao. Univ.-Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Gefäßspezialist'
address: '1010 Wien, Weihburggasse 18-20/linke Stiege/41'
phoneNumber: '<a href="tel:+4369910622695">+43 699 106 22695</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.gefaessarzt.at">www.gefaessarzt.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Health Consult'
address: '1010 Wien, Freyung 6'
phoneNumber: '<a href="tel:+431795808000">+43 1 795 80 8000</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.willfort-ehringer.at">www.willfort-ehringer.at</a>'
cardContent: ''
},
{
doctorName: 'Assoc. Prof. Priv.-Doz. Dr. PI:NAME:<NAME>END_PI'
stationName: 'MPH Wahlarztordination'
address: '1030 Wien, Neulinggasse 10'
phoneNumber: '<a href="tel:+4317144111">+ 43 1 714 4111</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://versuch-22.webnode.at/">versuch-22.webnode.at/</a>'
cardContent: ''
},
{
doctorName: 'Prim. Univ.Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'FA für innere Medizin und Angiologie M. Hirschl'
address: '1050 Wien, Blechturmgasse 14/6'
phoneNumber: '<a href="tel:+436508604387">+43 650 860 4387</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Univ. PI:NAME:<NAME>END_PIz. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Ordination Ordination für Innere Medizin, Angiologie, Kardiologie'
address: '1050 Wien, Arbeitergasse 9/3'
phoneNumber: '<a href="tel:+4319203259">+43 1 920 3259</a>'
emailAddress: ''
website: '<a href="https://www.mehrabi.at">www.mehrabi.at</a>'
cardContent: ''
},
{
doctorName: 'Univ.-Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Act now Präventivmedizin'
address: '1050 Wien, Strobachgasse 7-9'
phoneNumber: '<a href="tel:+4369910907060">+43 699 1090 7060</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.act-now.at">www.act-now.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: 'Dr. Jung und Partner Innere Medizin OG'
address: '1080 Wien, Strozzigasse 10'
phoneNumber: ''
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://">www.michael-jung.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: ''
address: '1080 Wien, Zeltgasse 3-5/11'
phoneNumber: '<a href="tel:+4314067269">+43 1 406 7269</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.herzkatheter.at">www.herzkatheter.at</a>'
cardContent: ''
},
{
doctorName: 'Prim. Univ. Doz. Dr. PI:NAME:<NAME>END_PI'
stationName: ''
address: '1080 Wien, Skodagasse 32'
phoneNumber: '<a href="tel:+431401145701">+43 1 40114 5701</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: ''
stationName: 'AKH Universitätsklinik für Innere Medizin II - Klinische Abteilung für Angiologie'
address: '1090 Wien, Währinger Gürtel 18-20'
phoneNumber: ''
emailAddress: ''
website: ''
cardContent: '''
<p class="detail-name">
AKH Universitätsklinik für Innere Medizin II - Klinische Abteilung für Angiologie
</p>
<p>
Univ. Prof. Dr. PI:NAME:<NAME>END_PI<br>
PI:NAME:<NAME>END_PI-Fekete/Abteilungssekretariat
</p>
<p>
1090 Wien, Währinger Gürtel 18-20<br>
Tel: <a href="tel:+4314040046700">+43 (0)1 40400-46700</a><br>
Fax: <a href="tel:+4314040046650">+43 (0)1 40400-46650</a><br>
E-mail: <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>
<p>
<div class="further-details">
<h3>
Fachärzte Innere Medizin mit Zusatzfach Angiologie
</h3>
<p>
Priv.-Doz. Dr. PI:NAME:<NAME>END_PI <b>AMIGHI-KNAPP</b><br>
Assoc.-Prof. Priv.-Doz. Dr. PI:NAME:<NAME>END_PI <b>BRUNNER-ZIEGLER</b><br>
Dr. PI:NAME:<NAME>END_PI <b>GIURGEA</b><br>
Assoc.-Prof. Priv.-Doz. Dr. PI:NAME:<NAME>END_PI <b>GREMMEL</b><br>
Ao.Univ.-Prof. Dr. PI:NAME:<NAME>END_PI <b>PI:NAME:<NAME>END_PI</b><br>
Ass.-Prof. Priv.-Doz. Dr. PI:NAME:<NAME>END_PI <b>PI:NAME:<NAME>END_PI</b><br>
Ao.Univ.-Prof. Dr. PI:NAME:<NAME>END_PI <b>KOPP</b><br>
o. Univ.-Prof. Dr. PI:NAME:<NAME>END_PI <b>KOPPENSTEINER</b><br>
Ao.Univ.-Prof. Dr. PI:NAME:<NAME>END_PI <b>MINAR</b><br>
Ao.Univ.-Prof. Dr. WolPI:NAME:<NAME>END_PI <b>MLEKUSCH</b><br>
Priv.-Doz. Dr. PI:NAME:<NAME>END_PIila <b>SABETI-SANDOR</b><br>
Ao.Univ.-Prof. Dr. PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI <b>SCHERNTHANER</b><br>
Assoc.-Prof. Priv.-Doz. Dr. PI:NAME:<NAME>END_PI <b>SCHLAGER</b><br>
Ao.Univ.-Prof. Dr. PI:NAME:<NAME>END_PI <b>WILLFORT-EHRINGER</b><br>
</p>
</div>
'''
},
{
doctorName: 'Univ.-Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Medizinische Universität Wien'
address: '1090 Wien, Währinger Gürtel 18-20'
phoneNumber: '<a href="tel:+4314040046700">+43 1 40400 46 700</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://innere-med-2.meduniwien.ac.at/angiologie/">innere-med-2.meduniwien.ac.at/angiologie/</a>'
cardContent: ''
},
{
doctorName: 'Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: '(Neue Wiener Privatklinik)'
address: '1090 Wien, Pelikangasse 15'
phoneNumber: '<a href="tel:+431401802310">+43 1 401 802310</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.gefaesserkrankung.at">www.gefaesserkrankung.at</a>'
cardContent: ''
},
{
doctorName: 'Univ. Prof. PI:NAME:<NAME>END_PI'
stationName: ''
address: '1090 Wien, Schwarzspanierstrasse 15/9/9'
phoneNumber: '<a href="tel:+4314055196">+ 43 1 405 51 96</a>'
emailAddress: ''
website: ''
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: 'FA f. Innere Medizin & Angiologie'
address: '1090 Wien, Alser Straße 18/35'
phoneNumber: '<a href="tel:+436643324078">+43 664 3324078</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: 'Gesundheitszentrum Wien-Süd, Angiologie-Ambulanz'
address: '1100 Wien, Wienerbergstrasse 13'
phoneNumber: '<a href="tel:+431601224254">+43 1 60122 4254</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.wgkk.at">www.wgkk.at</a>'
cardContent: ''
},
{
doctorName: 'Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Facharzt für Innere Medizin und Angiologie Prof. Dr. PI:NAME:<NAME>END_PI'
address: '1130 Wien, Amalienstraße 53A/22'
phoneNumber: '<a href="tel:+4369910459023">+ 43 699 104 59023</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: ''
stationName: 'Angiologie Hanuschkrankenhaus<br>angiologisches Sekretariat'
address: '1140 Wien, Heinrich Collinstrasse 30'
phoneNumber: '<a href="tel:+431910218611">+43 1 910 218 611</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Prim. Univ. Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'PI:NAME:<NAME>END_PI-KPI:NAME:<NAME>END_PIkenhaus<br>PI:NAME:<NAME>END_PI'
address: '1140 Wien, Heinrich-Collin-Straße 30'
phoneNumber: '<a href="tel:+4319102186130">+43 1 910 21-86130</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: ''
stationName: 'PI:NAME:<NAME>END_PI'
address: '1170 Wien, Dornbacher Strasse 20-28'
phoneNumber: '<a href="tel:"></a>'
emailAddress: '<a href="mailto:"></a>'
website: '<a href="https://"></a>'
cardContent: '''
<p>
PI:NAME:<NAME>END_PI<br>
1 Interne Abteilung<br>
Vorstand: Prim. Univ.Doz. Dr. PI:NAME:<NAME>END_PIensPI:NAME:<NAME>END_PI
</p>
<p>
1170 Wien, Dornbacher Strasse 20-28<br>
Tel: <a href="tel:+431400881110">+43 1 40088 1110</a><br>
E-Mail: <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a><br>
Webseite: <a href="https://www.khgh.at">www.khgh.at</a>
</p>
'''
},
{
doctorName: ''
stationName: 'Ambulatorium Döbling'
address: '1190 Wien, Billrothstrasse 49a'
phoneNumber: '<a href="tel:+431360665575">+43 1 36066 5575</a>'
emailAddress: ''
website: '<a href="https://www.ambulatorium-doebling.at/de/ambulanzen-institute-zentren/innere-medizin.html">www.ambulatorium-doebling.at/de/ambulanzen-institute-zentren/innere-medizin.html</a>'
cardContent: ''
},
{
doctorName: 'Univ.-Prof. Dr. PI:NAME:<NAME>END_PI'
stationName: 'Angiologie, Innere Medizin'
address: '1190 Wien, Heiligenstädter Straße 69 / Top 12'
phoneNumber: '<a href="tel:06802477278">0680 / 24 77 278</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.gschwandtner-angiologie.at">www.gschwandtner-angiologie.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: ''
address: '1190 Wien, Obkirchergasse 43/8'
phoneNumber: '<a href="tel:+4313204141">+43 1 320 41 41</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: ''
cardContent: ''
},
{
doctorName: 'Dr. med. PI:NAME:<NAME>END_PI'
stationName: 'Praxis für Venenheilkunde'
address: '1190 Wien, Billrothstrasse 49a'
phoneNumber: '<a href="tel:+436506919779">+43 650 691 9779</a>'
emailAddress: ''
website: '<a href="https://www.drsinger.at">www.drsinger.at</a>'
cardContent: ''
},
{
doctorName: 'Dr. PI:NAME:<NAME>END_PI'
stationName: 'Schnürer & Fritsch Gruppenpraxis für Innere Medizin'
address: '1230 Wien, Geßlgasse 19/1'
phoneNumber: '<a href="tel:+43188813790">+ 43 1 888 13790</a>'
emailAddress: '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
website: '<a href="https://www.kardio23.at">www.kardio23.at</a>'
cardContent: ''
}
]
############################################################
burgenlandData = []
############################################################
allData =
vorarlberg: vorarlbergData
tirol: tirolData
salzburg: salzburgData
kaernten: kaerntenData
oberoesterreich: oberoesterreichData
steiermark: steiermarkData
niederoesterreich: niederoesterreichData
wien: wienData
burgenland: burgenlandData
module.exports = allData |
[
{
"context": "key: 'link-text'\npatterns: [\n {\n name: 'text.link.string.md'\n",
"end": 15,
"score": 0.9914301037788391,
"start": 6,
"tag": "KEY",
"value": "link-text"
}
] | grammars/repositories/inlines/link-text.cson | doc22940/language-markdown | 138 | key: 'link-text'
patterns: [
{
name: 'text.link.string.md'
match: '(?x)
^(\\[)
(
(
(?:!\\[)
(?:[^\\[\\]]*)
(?:\\])
)
(\\()
([^ [:cntrl:]]+)?
(?:
(?:\\s+)
(
(?:["\'\\(])
.*?
(?:["\'\\)])
)
(?:\\s*)
)?
(\\))
(\\{[[:ascii:]]*\\})?
)
(\\])
'
captures:
1: name: 'punctuation.md'
2: name: 'link.markup.md'
3: patterns: [{ include: '#link-text' }]
4: name: 'punctuation.md'
5: patterns: [{ include: '#link-destination' }]
6: patterns: [{ include: '#link-title' }]
7: name: 'punctuation.md'
8: patterns: [{ include: '#special-attributes' }]
9: name: 'punctuation.md'
}
{
name: 'image.link.string.md'
match: '^(!\\[)(.*)(\\])$'
captures:
1: name: 'punctuation.md'
2: patterns: [
{ include: '#emphasis' }
{ include: '#code' }
]
3: name: 'punctuation.md'
}
{
name: 'text.link.string.md'
match: '^(\\[)(.*)(\\])$'
captures:
1: name: 'punctuation.md'
2: patterns: [
{ include: '#emphasis' }
{ include: '#code' }
]
3: name: 'punctuation.md'
}
]
| 1359 | key: '<KEY>'
patterns: [
{
name: 'text.link.string.md'
match: '(?x)
^(\\[)
(
(
(?:!\\[)
(?:[^\\[\\]]*)
(?:\\])
)
(\\()
([^ [:cntrl:]]+)?
(?:
(?:\\s+)
(
(?:["\'\\(])
.*?
(?:["\'\\)])
)
(?:\\s*)
)?
(\\))
(\\{[[:ascii:]]*\\})?
)
(\\])
'
captures:
1: name: 'punctuation.md'
2: name: 'link.markup.md'
3: patterns: [{ include: '#link-text' }]
4: name: 'punctuation.md'
5: patterns: [{ include: '#link-destination' }]
6: patterns: [{ include: '#link-title' }]
7: name: 'punctuation.md'
8: patterns: [{ include: '#special-attributes' }]
9: name: 'punctuation.md'
}
{
name: 'image.link.string.md'
match: '^(!\\[)(.*)(\\])$'
captures:
1: name: 'punctuation.md'
2: patterns: [
{ include: '#emphasis' }
{ include: '#code' }
]
3: name: 'punctuation.md'
}
{
name: 'text.link.string.md'
match: '^(\\[)(.*)(\\])$'
captures:
1: name: 'punctuation.md'
2: patterns: [
{ include: '#emphasis' }
{ include: '#code' }
]
3: name: 'punctuation.md'
}
]
| true | key: 'PI:KEY:<KEY>END_PI'
patterns: [
{
name: 'text.link.string.md'
match: '(?x)
^(\\[)
(
(
(?:!\\[)
(?:[^\\[\\]]*)
(?:\\])
)
(\\()
([^ [:cntrl:]]+)?
(?:
(?:\\s+)
(
(?:["\'\\(])
.*?
(?:["\'\\)])
)
(?:\\s*)
)?
(\\))
(\\{[[:ascii:]]*\\})?
)
(\\])
'
captures:
1: name: 'punctuation.md'
2: name: 'link.markup.md'
3: patterns: [{ include: '#link-text' }]
4: name: 'punctuation.md'
5: patterns: [{ include: '#link-destination' }]
6: patterns: [{ include: '#link-title' }]
7: name: 'punctuation.md'
8: patterns: [{ include: '#special-attributes' }]
9: name: 'punctuation.md'
}
{
name: 'image.link.string.md'
match: '^(!\\[)(.*)(\\])$'
captures:
1: name: 'punctuation.md'
2: patterns: [
{ include: '#emphasis' }
{ include: '#code' }
]
3: name: 'punctuation.md'
}
{
name: 'text.link.string.md'
match: '^(\\[)(.*)(\\])$'
captures:
1: name: 'punctuation.md'
2: patterns: [
{ include: '#emphasis' }
{ include: '#code' }
]
3: name: 'punctuation.md'
}
]
|
[
{
"context": "h /https:\\/\\/[^\\/]+\\// # e.g., https://github.com/foo/bar.git\n url.replace(/\\.git$/, '')\n else ",
"end": 2261,
"score": 0.9986473917961121,
"start": 2258,
"tag": "USERNAME",
"value": "foo"
},
{
"context": " '')\n else if url.match /git@[^:]+:/ # e.g... | lib/SimpleGitHubFile.coffee | nakajima/atom-branch-status | 0 | Shell = require 'shell'
{Range} = require 'atom'
module.exports =
class SimpleGitHubFile
# Public
@fromPath: (filePath) ->
new GitHubFile(filePath)
# Internal
constructor: (@filePath) ->
@repo = atom.project.getRepositories()?[0]
# Public
open: ->
if @isOpenable()
@openUrlInBrowser(@blobUrl())
else
@reportValidationErrors()
# Public
blame: (lineRange) ->
if @isOpenable()
@openUrlInBrowser(@blameUrl() + @getLineRangeSuffix(lineRange))
else
@reportValidationErrors()
history: (lineRange) ->
if @isOpenable()
@openUrlInBrowser(@historyUrl() + @getLineRangeSuffix(lineRange))
else
@reportValidationErrors()
copyUrl: (lineRange) ->
if @isOpenable()
url = @blobUrl()
atom.clipboard.write(url + @getLineRangeSuffix(lineRange))
else
@reportValidationErrors()
getLineRangeSuffix: (lineRange) ->
if lineRange and atom.config.get('open-on-github.includeLineNumbersInUrls')
lineRange = Range.fromObject(lineRange)
startRow = lineRange.start.row + 1
endRow = lineRange.end.row + 1
if startRow is endRow
"#L#{startRow}"
else
"#L#{startRow}-L#{endRow}"
else
''
# Public
isOpenable: ->
@validationErrors().length == 0
# Public
validationErrors: ->
unless @gitUrl()
return ["No URL defined for remote (#{@remoteName()})"]
unless @githubRepoUrl()
return ["Remote URL is not hosted on GitHub.com (#{@gitUrl()})"]
[]
# Internal
reportValidationErrors: ->
atom.beep()
console.warn error for error in @validationErrors()
# Internal
openUrlInBrowser: (url) ->
Shell.openExternal url
# Internal
blobUrl: ->
"#{@githubRepoUrl()}/blob/#{@branch()}/#{@repoRelativePath()}"
# Internal
blameUrl: ->
"#{@githubRepoUrl()}/blame/#{@branch()}/#{@repoRelativePath()}"
# Internal
historyUrl: ->
"#{@githubRepoUrl()}/commits/#{@branch()}/#{@repoRelativePath()}"
# Internal
gitUrl: ->
remoteOrBestGuess = @remoteName() ? 'origin'
@repo.getConfigValue("remote.#{remoteOrBestGuess}.url")
# Internal
githubRepoUrl: ->
url = @gitUrl()
if url.match /https:\/\/[^\/]+\// # e.g., https://github.com/foo/bar.git
url.replace(/\.git$/, '')
else if url.match /git@[^:]+:/ # e.g., git@github.com:foo/bar.git
url.replace /^git@([^:]+):(.+)$/, (match, host, repoPath) ->
"http://#{host}/#{repoPath}".replace(/\.git$/, '')
else if url.match /^git:\/\/[^\/]+\// # e.g., git://github.com/foo/bar.git
"http#{url.substring(3).replace(/\.git$/, '')}"
# Internal
repoRelativePath: ->
@repo.relativize(@filePath)
# Internal
remoteName: ->
refName = @repo.getUpstreamBranch() # e.g., "refs/remotes/origin/master"
refName?.match(/^refs\/remotes\/(.+)\/.*$/)?[1] ? null
# Internal
branch: ->
refName = @repo.getUpstreamBranch() # e.g., "refs/remotes/origin/master"
refName?.match(/^refs\/remotes\/.*\/(.+)$/)?[1] ? @repo.getShortHead()
| 20962 | Shell = require 'shell'
{Range} = require 'atom'
module.exports =
class SimpleGitHubFile
# Public
@fromPath: (filePath) ->
new GitHubFile(filePath)
# Internal
constructor: (@filePath) ->
@repo = atom.project.getRepositories()?[0]
# Public
open: ->
if @isOpenable()
@openUrlInBrowser(@blobUrl())
else
@reportValidationErrors()
# Public
blame: (lineRange) ->
if @isOpenable()
@openUrlInBrowser(@blameUrl() + @getLineRangeSuffix(lineRange))
else
@reportValidationErrors()
history: (lineRange) ->
if @isOpenable()
@openUrlInBrowser(@historyUrl() + @getLineRangeSuffix(lineRange))
else
@reportValidationErrors()
copyUrl: (lineRange) ->
if @isOpenable()
url = @blobUrl()
atom.clipboard.write(url + @getLineRangeSuffix(lineRange))
else
@reportValidationErrors()
getLineRangeSuffix: (lineRange) ->
if lineRange and atom.config.get('open-on-github.includeLineNumbersInUrls')
lineRange = Range.fromObject(lineRange)
startRow = lineRange.start.row + 1
endRow = lineRange.end.row + 1
if startRow is endRow
"#L#{startRow}"
else
"#L#{startRow}-L#{endRow}"
else
''
# Public
isOpenable: ->
@validationErrors().length == 0
# Public
validationErrors: ->
unless @gitUrl()
return ["No URL defined for remote (#{@remoteName()})"]
unless @githubRepoUrl()
return ["Remote URL is not hosted on GitHub.com (#{@gitUrl()})"]
[]
# Internal
reportValidationErrors: ->
atom.beep()
console.warn error for error in @validationErrors()
# Internal
openUrlInBrowser: (url) ->
Shell.openExternal url
# Internal
blobUrl: ->
"#{@githubRepoUrl()}/blob/#{@branch()}/#{@repoRelativePath()}"
# Internal
blameUrl: ->
"#{@githubRepoUrl()}/blame/#{@branch()}/#{@repoRelativePath()}"
# Internal
historyUrl: ->
"#{@githubRepoUrl()}/commits/#{@branch()}/#{@repoRelativePath()}"
# Internal
gitUrl: ->
remoteOrBestGuess = @remoteName() ? 'origin'
@repo.getConfigValue("remote.#{remoteOrBestGuess}.url")
# Internal
githubRepoUrl: ->
url = @gitUrl()
if url.match /https:\/\/[^\/]+\// # e.g., https://github.com/foo/bar.git
url.replace(/\.git$/, '')
else if url.match /git@[^:]+:/ # e.g., <EMAIL>:foo/bar.git
url.replace /^git@([^:]+):(.+)$/, (match, host, repoPath) ->
"http://#{host}/#{repoPath}".replace(/\.git$/, '')
else if url.match /^git:\/\/[^\/]+\// # e.g., git://github.com/foo/bar.git
"http#{url.substring(3).replace(/\.git$/, '')}"
# Internal
repoRelativePath: ->
@repo.relativize(@filePath)
# Internal
remoteName: ->
refName = @repo.getUpstreamBranch() # e.g., "refs/remotes/origin/master"
refName?.match(/^refs\/remotes\/(.+)\/.*$/)?[1] ? null
# Internal
branch: ->
refName = @repo.getUpstreamBranch() # e.g., "refs/remotes/origin/master"
refName?.match(/^refs\/remotes\/.*\/(.+)$/)?[1] ? @repo.getShortHead()
| true | Shell = require 'shell'
{Range} = require 'atom'
module.exports =
class SimpleGitHubFile
# Public
@fromPath: (filePath) ->
new GitHubFile(filePath)
# Internal
constructor: (@filePath) ->
@repo = atom.project.getRepositories()?[0]
# Public
open: ->
if @isOpenable()
@openUrlInBrowser(@blobUrl())
else
@reportValidationErrors()
# Public
blame: (lineRange) ->
if @isOpenable()
@openUrlInBrowser(@blameUrl() + @getLineRangeSuffix(lineRange))
else
@reportValidationErrors()
history: (lineRange) ->
if @isOpenable()
@openUrlInBrowser(@historyUrl() + @getLineRangeSuffix(lineRange))
else
@reportValidationErrors()
copyUrl: (lineRange) ->
if @isOpenable()
url = @blobUrl()
atom.clipboard.write(url + @getLineRangeSuffix(lineRange))
else
@reportValidationErrors()
getLineRangeSuffix: (lineRange) ->
if lineRange and atom.config.get('open-on-github.includeLineNumbersInUrls')
lineRange = Range.fromObject(lineRange)
startRow = lineRange.start.row + 1
endRow = lineRange.end.row + 1
if startRow is endRow
"#L#{startRow}"
else
"#L#{startRow}-L#{endRow}"
else
''
# Public
isOpenable: ->
@validationErrors().length == 0
# Public
validationErrors: ->
unless @gitUrl()
return ["No URL defined for remote (#{@remoteName()})"]
unless @githubRepoUrl()
return ["Remote URL is not hosted on GitHub.com (#{@gitUrl()})"]
[]
# Internal
reportValidationErrors: ->
atom.beep()
console.warn error for error in @validationErrors()
# Internal
openUrlInBrowser: (url) ->
Shell.openExternal url
# Internal
blobUrl: ->
"#{@githubRepoUrl()}/blob/#{@branch()}/#{@repoRelativePath()}"
# Internal
blameUrl: ->
"#{@githubRepoUrl()}/blame/#{@branch()}/#{@repoRelativePath()}"
# Internal
historyUrl: ->
"#{@githubRepoUrl()}/commits/#{@branch()}/#{@repoRelativePath()}"
# Internal
gitUrl: ->
remoteOrBestGuess = @remoteName() ? 'origin'
@repo.getConfigValue("remote.#{remoteOrBestGuess}.url")
# Internal
githubRepoUrl: ->
url = @gitUrl()
if url.match /https:\/\/[^\/]+\// # e.g., https://github.com/foo/bar.git
url.replace(/\.git$/, '')
else if url.match /git@[^:]+:/ # e.g., PI:EMAIL:<EMAIL>END_PI:foo/bar.git
url.replace /^git@([^:]+):(.+)$/, (match, host, repoPath) ->
"http://#{host}/#{repoPath}".replace(/\.git$/, '')
else if url.match /^git:\/\/[^\/]+\// # e.g., git://github.com/foo/bar.git
"http#{url.substring(3).replace(/\.git$/, '')}"
# Internal
repoRelativePath: ->
@repo.relativize(@filePath)
# Internal
remoteName: ->
refName = @repo.getUpstreamBranch() # e.g., "refs/remotes/origin/master"
refName?.match(/^refs\/remotes\/(.+)\/.*$/)?[1] ? null
# Internal
branch: ->
refName = @repo.getUpstreamBranch() # e.g., "refs/remotes/origin/master"
refName?.match(/^refs\/remotes\/.*\/(.+)$/)?[1] ? @repo.getShortHead()
|
[
{
"context": "ie mortified over their unraveled work.<br/>\n george washington died mortally wounded in his depression... realiz",
"end": 4201,
"score": 0.924205482006073,
"start": 4184,
"tag": "NAME",
"value": "george washington"
}
] | app/components/Fruit/Now/index.coffee | samerce/purplerepublic.us | 1 | import React from 'react'
import WordRolodex from '../../WordRolodex'
import FloatingMousePal from '../../FloatingMousePal/index.coffee'
import TalkingBubbles from '../../TalkingBubbles'
import {
Root, FaerieRoot, NamasteRoot,
} from './styled'
import {connect} from 'react-redux'
import resizable from '../../hocs/resizable'
import laganja from '../../hocs/laganja'
import {SRC_URL} from '../../../global/constants'
import {View} from '../../../containers/start/reducer.coffee'
GIF_ROOT_URL = SRC_URL + 'portals/gifs/'
export default connect((d) =>
view: d.get('start').get('view'),
) laganja() resizable() class Portal extends React.PureComponent
constructor: (props) ->
super(props)
@laganja = props.laganja
@state =
showFaerie: false,
# styles: getStyles(props),
onResize: =>
# this.setState({styles: getStyles(this.props)})
componentDidUpdate: (prevProps) =>
if prevProps.view is View.quark and @props.view isnt View.quark
@stopLaganja()
else if prevProps.view isnt View.quark and @props.view is View.quark
@startLaganja()
startLaganja: () =>
@rolodex.start()
@laganja.start (lg) =>
# lg.timer(3000, () => this.setState({showFaerie: true}))
# lg.timer(13000, () => this.setState({showFaerie: false}))
lg.scrollListener (scroll) =>
@setState
showFaerie: scroll > 800 && scroll < 1000
lg.scrollListener (scroll) =>
@setState
showNamaste: scroll > 1840
stopLaganja: () =>
@rolodex.stop()
@laganja.stop()
setRolodex: (r) => @rolodex = r
render: =>
{showFaerie, showNamaste} = @state
<Root className={@props.className}>
<NamasteRoot className={'show' if showNamaste}>
<img src={GIF_ROOT_URL + 'namastehehe.gif'} />
</NamasteRoot>
<FaerieRoot className={'show' if showFaerie}>
🧚<TalkingBubbles delay={1} show={showFaerie} phrase="you are here now!" />
</FaerieRoot>
this is the place. this is the time. now.<br/>
this life is for you.<br/>
to tinker away your blinks.<br/>
toy with your knobs.<br/>
nothing else matters.
<WordRolodex
ref={@setRolodex}
isPlaying={no}
className='wordRolodex'
words={['not money.', 'not memories.', 'not lovers.', 'not children.', 'not health.', 'not trump.']}
/><br/>
ditch the need to be rich and behold what riches present themselves before you.<br/>
exiting the world of acquisitions requires acquiring freedom, which doesn't cost and costs everything.<br/>
purposely seek out things of low monetary value; spirit lives there.<br/>
legacy and possession are fear's sentiment; weaponry to keep you in shackles.<br/>
life is movement. settle and you're dead.<br/>
vacuous thought loops and a pulse don't signify aliveness.<br/>
all great things come from freedom. including freedom. freedom begets freedom.<br/>
all change is birthed in freedom.<br/>
fear or freedom. that's it.<br/><br/>
<div className='fear'>
<FloatingMousePal className='floater' offsets={{top: -120}}>
<img src={GIF_ROOT_URL + 'fishypop.gif'} />
</FloatingMousePal>
fear, fear, fear, fear, fear, fear, fear.
</div> is the only enemy.<br/>
root it out.<br/>
then you, too, can make freaky as fuck drama with your few moments on this planet.<br/>
the only other choice is fearfully regurgitating pre-chewed food into other sleeping mouths.<br/>
all is cleared away when one is self-freed to be a person over a persona.<br/>
isness over a walking, talking societal prognosis.<br/>
benevolence reigns supreme in consciousness.<br/>
it is only in sleeping ignorance can the binary exist.<br/>
waking up frees the soul to be.<br/><br/>
there are only two types of people... those who have set down their ego/fear and experienced a psychedelic trip.... and those who have not.<br/>
there’s no enemy to fight so take some acid.<br/>
exit the world of pre-chewed food. <br/>
most heroes die mortified over their unraveled work.<br/>
george washington died mortally wounded in his depression... realizing all his human work did and can do nothing to save his fellow man.<br/>
the binary of heroes and villains / good and evil / richness and poverty ... is a mindset to break free from.<br/>
to see with god's eyes/i.e. to have experienced the true nature of our collective reality... to know what is possible ...<br/>
even on an earth full of incurable evil. . .<br/>
helps to sit with it: there is no enemy to fight. . . except the fear locked in life itself. . .<br/>
freedom comes with a specific melancholy. namely the knowledge that earth isn't ours to save.<br/>
& that life is for two reasons: free the soul and enjoy playing conscious witness to triangulating spacetime.<br/>
there are only two ways reality materializes: exploitation of fear or enjoyment of freed expression.<br/>
i choose the conscious baptism of expansion. and am daily becoming freer and freer as a result.<br/>
benevolent coexistence, boys.<br/>
conveying beauty. being beauty. witnessing beauty.<br/>
in conclusion - all business schools should be immediately closed down for spiritual renovations.<br/>
</Root>
| 160116 | import React from 'react'
import WordRolodex from '../../WordRolodex'
import FloatingMousePal from '../../FloatingMousePal/index.coffee'
import TalkingBubbles from '../../TalkingBubbles'
import {
Root, FaerieRoot, NamasteRoot,
} from './styled'
import {connect} from 'react-redux'
import resizable from '../../hocs/resizable'
import laganja from '../../hocs/laganja'
import {SRC_URL} from '../../../global/constants'
import {View} from '../../../containers/start/reducer.coffee'
GIF_ROOT_URL = SRC_URL + 'portals/gifs/'
export default connect((d) =>
view: d.get('start').get('view'),
) laganja() resizable() class Portal extends React.PureComponent
constructor: (props) ->
super(props)
@laganja = props.laganja
@state =
showFaerie: false,
# styles: getStyles(props),
onResize: =>
# this.setState({styles: getStyles(this.props)})
componentDidUpdate: (prevProps) =>
if prevProps.view is View.quark and @props.view isnt View.quark
@stopLaganja()
else if prevProps.view isnt View.quark and @props.view is View.quark
@startLaganja()
startLaganja: () =>
@rolodex.start()
@laganja.start (lg) =>
# lg.timer(3000, () => this.setState({showFaerie: true}))
# lg.timer(13000, () => this.setState({showFaerie: false}))
lg.scrollListener (scroll) =>
@setState
showFaerie: scroll > 800 && scroll < 1000
lg.scrollListener (scroll) =>
@setState
showNamaste: scroll > 1840
stopLaganja: () =>
@rolodex.stop()
@laganja.stop()
setRolodex: (r) => @rolodex = r
render: =>
{showFaerie, showNamaste} = @state
<Root className={@props.className}>
<NamasteRoot className={'show' if showNamaste}>
<img src={GIF_ROOT_URL + 'namastehehe.gif'} />
</NamasteRoot>
<FaerieRoot className={'show' if showFaerie}>
🧚<TalkingBubbles delay={1} show={showFaerie} phrase="you are here now!" />
</FaerieRoot>
this is the place. this is the time. now.<br/>
this life is for you.<br/>
to tinker away your blinks.<br/>
toy with your knobs.<br/>
nothing else matters.
<WordRolodex
ref={@setRolodex}
isPlaying={no}
className='wordRolodex'
words={['not money.', 'not memories.', 'not lovers.', 'not children.', 'not health.', 'not trump.']}
/><br/>
ditch the need to be rich and behold what riches present themselves before you.<br/>
exiting the world of acquisitions requires acquiring freedom, which doesn't cost and costs everything.<br/>
purposely seek out things of low monetary value; spirit lives there.<br/>
legacy and possession are fear's sentiment; weaponry to keep you in shackles.<br/>
life is movement. settle and you're dead.<br/>
vacuous thought loops and a pulse don't signify aliveness.<br/>
all great things come from freedom. including freedom. freedom begets freedom.<br/>
all change is birthed in freedom.<br/>
fear or freedom. that's it.<br/><br/>
<div className='fear'>
<FloatingMousePal className='floater' offsets={{top: -120}}>
<img src={GIF_ROOT_URL + 'fishypop.gif'} />
</FloatingMousePal>
fear, fear, fear, fear, fear, fear, fear.
</div> is the only enemy.<br/>
root it out.<br/>
then you, too, can make freaky as fuck drama with your few moments on this planet.<br/>
the only other choice is fearfully regurgitating pre-chewed food into other sleeping mouths.<br/>
all is cleared away when one is self-freed to be a person over a persona.<br/>
isness over a walking, talking societal prognosis.<br/>
benevolence reigns supreme in consciousness.<br/>
it is only in sleeping ignorance can the binary exist.<br/>
waking up frees the soul to be.<br/><br/>
there are only two types of people... those who have set down their ego/fear and experienced a psychedelic trip.... and those who have not.<br/>
there’s no enemy to fight so take some acid.<br/>
exit the world of pre-chewed food. <br/>
most heroes die mortified over their unraveled work.<br/>
<NAME> died mortally wounded in his depression... realizing all his human work did and can do nothing to save his fellow man.<br/>
the binary of heroes and villains / good and evil / richness and poverty ... is a mindset to break free from.<br/>
to see with god's eyes/i.e. to have experienced the true nature of our collective reality... to know what is possible ...<br/>
even on an earth full of incurable evil. . .<br/>
helps to sit with it: there is no enemy to fight. . . except the fear locked in life itself. . .<br/>
freedom comes with a specific melancholy. namely the knowledge that earth isn't ours to save.<br/>
& that life is for two reasons: free the soul and enjoy playing conscious witness to triangulating spacetime.<br/>
there are only two ways reality materializes: exploitation of fear or enjoyment of freed expression.<br/>
i choose the conscious baptism of expansion. and am daily becoming freer and freer as a result.<br/>
benevolent coexistence, boys.<br/>
conveying beauty. being beauty. witnessing beauty.<br/>
in conclusion - all business schools should be immediately closed down for spiritual renovations.<br/>
</Root>
| true | import React from 'react'
import WordRolodex from '../../WordRolodex'
import FloatingMousePal from '../../FloatingMousePal/index.coffee'
import TalkingBubbles from '../../TalkingBubbles'
import {
Root, FaerieRoot, NamasteRoot,
} from './styled'
import {connect} from 'react-redux'
import resizable from '../../hocs/resizable'
import laganja from '../../hocs/laganja'
import {SRC_URL} from '../../../global/constants'
import {View} from '../../../containers/start/reducer.coffee'
GIF_ROOT_URL = SRC_URL + 'portals/gifs/'
export default connect((d) =>
view: d.get('start').get('view'),
) laganja() resizable() class Portal extends React.PureComponent
constructor: (props) ->
super(props)
@laganja = props.laganja
@state =
showFaerie: false,
# styles: getStyles(props),
onResize: =>
# this.setState({styles: getStyles(this.props)})
componentDidUpdate: (prevProps) =>
if prevProps.view is View.quark and @props.view isnt View.quark
@stopLaganja()
else if prevProps.view isnt View.quark and @props.view is View.quark
@startLaganja()
startLaganja: () =>
@rolodex.start()
@laganja.start (lg) =>
# lg.timer(3000, () => this.setState({showFaerie: true}))
# lg.timer(13000, () => this.setState({showFaerie: false}))
lg.scrollListener (scroll) =>
@setState
showFaerie: scroll > 800 && scroll < 1000
lg.scrollListener (scroll) =>
@setState
showNamaste: scroll > 1840
stopLaganja: () =>
@rolodex.stop()
@laganja.stop()
setRolodex: (r) => @rolodex = r
render: =>
{showFaerie, showNamaste} = @state
<Root className={@props.className}>
<NamasteRoot className={'show' if showNamaste}>
<img src={GIF_ROOT_URL + 'namastehehe.gif'} />
</NamasteRoot>
<FaerieRoot className={'show' if showFaerie}>
🧚<TalkingBubbles delay={1} show={showFaerie} phrase="you are here now!" />
</FaerieRoot>
this is the place. this is the time. now.<br/>
this life is for you.<br/>
to tinker away your blinks.<br/>
toy with your knobs.<br/>
nothing else matters.
<WordRolodex
ref={@setRolodex}
isPlaying={no}
className='wordRolodex'
words={['not money.', 'not memories.', 'not lovers.', 'not children.', 'not health.', 'not trump.']}
/><br/>
ditch the need to be rich and behold what riches present themselves before you.<br/>
exiting the world of acquisitions requires acquiring freedom, which doesn't cost and costs everything.<br/>
purposely seek out things of low monetary value; spirit lives there.<br/>
legacy and possession are fear's sentiment; weaponry to keep you in shackles.<br/>
life is movement. settle and you're dead.<br/>
vacuous thought loops and a pulse don't signify aliveness.<br/>
all great things come from freedom. including freedom. freedom begets freedom.<br/>
all change is birthed in freedom.<br/>
fear or freedom. that's it.<br/><br/>
<div className='fear'>
<FloatingMousePal className='floater' offsets={{top: -120}}>
<img src={GIF_ROOT_URL + 'fishypop.gif'} />
</FloatingMousePal>
fear, fear, fear, fear, fear, fear, fear.
</div> is the only enemy.<br/>
root it out.<br/>
then you, too, can make freaky as fuck drama with your few moments on this planet.<br/>
the only other choice is fearfully regurgitating pre-chewed food into other sleeping mouths.<br/>
all is cleared away when one is self-freed to be a person over a persona.<br/>
isness over a walking, talking societal prognosis.<br/>
benevolence reigns supreme in consciousness.<br/>
it is only in sleeping ignorance can the binary exist.<br/>
waking up frees the soul to be.<br/><br/>
there are only two types of people... those who have set down their ego/fear and experienced a psychedelic trip.... and those who have not.<br/>
there’s no enemy to fight so take some acid.<br/>
exit the world of pre-chewed food. <br/>
most heroes die mortified over their unraveled work.<br/>
PI:NAME:<NAME>END_PI died mortally wounded in his depression... realizing all his human work did and can do nothing to save his fellow man.<br/>
the binary of heroes and villains / good and evil / richness and poverty ... is a mindset to break free from.<br/>
to see with god's eyes/i.e. to have experienced the true nature of our collective reality... to know what is possible ...<br/>
even on an earth full of incurable evil. . .<br/>
helps to sit with it: there is no enemy to fight. . . except the fear locked in life itself. . .<br/>
freedom comes with a specific melancholy. namely the knowledge that earth isn't ours to save.<br/>
& that life is for two reasons: free the soul and enjoy playing conscious witness to triangulating spacetime.<br/>
there are only two ways reality materializes: exploitation of fear or enjoyment of freed expression.<br/>
i choose the conscious baptism of expansion. and am daily becoming freer and freer as a result.<br/>
benevolent coexistence, boys.<br/>
conveying beauty. being beauty. witnessing beauty.<br/>
in conclusion - all business schools should be immediately closed down for spiritual renovations.<br/>
</Root>
|
[
{
"context": "f )\n\t\t//guiInputHelper.pressed( false )\n\t})\n\n\n\t// Daddy, what happens when we die?\n\n\tcontroller.addEv",
"end": 32164,
"score": 0.9984436631202698,
"start": 32163,
"tag": "NAME",
"value": "D"
},
{
"context": ")\n\t\t//guiInputHelper.pressed( false )\n\t})\n\... | rba/www/aa3d/aa3d.coffee | tamasgal/rba | 0 |
# this is the aa3d event display for antares and km3net
# object that will hold all the user-modifiable parameters (and then some)
pars = {}
defpars = {}
# physics-domain data
clight = 0.299792458 # m/ns
evt = {"hits": [], "trks":[]};
det = {"doms": [{"id": 1, "dir": {"y":0, "x": 0, "z": 0}, "pos": {"y": 0, "x": 0, "z": 0} }] };
# three.js objects
scene= camera= renderer= raycaster= mouseVector= controls = null;
geometry= material= mesh= null
container= stats= gui = null
containerWidth= containerHeight= null
eventtime = 0.0;
light= null
gui = null
effect = null
train = null
selectedHit = null
ii = null#
dus = 42
callbacks = {}
selected = null
dbg_cam = false
evil = ( code ) -> eval ( code ) # eval's evil brother (to access scope)
#-----------------------------------------
# Simple Vector functions and math utils
#-----------------------------------------
isvec = ( obj ) -> typeof(obj) == 'object' and 'x' of obj and 'y' of obj and 'z' of obj
vadd = ( v1, v2 ) -> { x : v1.x + v2.x, y: v1.y + v2.y , z: v1.z + v2. z }
vsub = ( v1, v2 ) -> { x : v1.x - v2.x, y: v1.y - v2.y , z: v1.z - v2. z }
vmul = ( v1, a ) ->
if typeof v1 == 'number' then return vmul( a, v1 )
return { x: v1.x * a, y: v1.y * a, z : v1.z * a }
vlen = ( v1, v2 = {x:0,y:0,z:0} ) ->
Math.sqrt( (v1.x-v2.x)*(v1.x-v2.x) + (v1.y-v2.y)*(v1.y-v2.y) + (v1.z-v2.z)*(v1.z-v2.z) )
tovec = (obj) ->
new THREE.Vector3 obj.y, obj.z, obj.x
clamp = ( x, min=0, max=1 ) ->
if x <= min then return min
if x >= max then return max
return x
getUrlPar = (name, url ) ->
url ?= window.location.href
name = name.replace(/[\[\]]/g, "\\$&")
regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
results = regex.exec(url);
if !results then return null
if !results[2] then return ''
return decodeURIComponent(results[2].replace(/\+/g, " "));
getCylinderMesh = ( startpoint, endpoint, width , material , width2 ) ->
l = vlen( endpoint, startpoint )
width2 ?= width
geom = new THREE.CylinderGeometry( width, width2 , l );
geom.translate(0, l/2 ,0);
geom.rotateX( Math.PI / 2 );
mesh = new THREE.Mesh( geom , material.clone() );
mesh.position.set( startpoint.y, startpoint.z, startpoint.x );
mesh.lookAt( tovec(endpoint) );
return mesh;
getConeMesh = ( startpoint, endpoint, width, material ) ->
getCylinderMesh( startpoint, endpoint, width, material, 0 )
callbacks.setBackgroundColor = ->
scene.background = new THREE.Color( pars.bgColor )
callbacks.screenshot = ->
dt = renderer.domElement.toDataURL( 'image/png' );
window.open( dt, 'screenshot')
callbacks.screenshot360 = ->
console.log("screenshot360")
X = new CubemapToEquirectangular( renderer, true );
X.update( camera, scene )
callbacks.write_screenshot = (fn) ->
url = "uploadimg.php"
params = "fn="+fn+".png&payload="+renderer.domElement.toDataURL( 'image/png' );
console.log(params)
http = new XMLHttpRequest()
http.open("POST", url , false )
#Send the proper header information along with the request
http.send( params )
if http.readyState == 4 && http.status == 200 then console.log(http.responseText)
else console.log('error sending screenshot')
callbacks.addCamera =->
camera ?= new THREE.PerspectiveCamera( 75,window.innerWidth / window.innerHeight, 0.01, 10000 );
camera.position.x = 0
camera.position.y = pars.camHeight
camera.position.z = pars.camDistance
callbacks.addOrbitControls =->
controls = new THREE.OrbitControls( camera , renderer.domElement )
cg = det.cg or {x:0, y:0, z:0} # det may not exist yet
controls.center = new THREE.Vector3(cg.z, cg.y, cg.x) or new THREE.Vector3( camera.position.x, camera.position.y, 0.0 )
controls.update()
controls.addEventListener( 'change', render )
return controls
getSceneObj = ( name ) ->
while obj = scene.getObjectByName( name )
scene.remove( obj )
obj = new THREE.Object3D()
obj.name = name
scene.add( obj )
return obj
isNeutrino = (track) -> Math.abs( track.type ) in [12,14,16]
isLepton = (track) -> Math.abs( track.type ) in [11,13,15]
isMuon = (track) -> Math.abs( track.type ) == 13
trackColor = ( track ) ->
if track.type == 0
return new THREE.Color( pars.trackColor )
if isNeutrino( track )
return new THREE.Color( pars.neuColor )
if isMuon( track)
return new THREE.Color( pars.muColor )
return new THREE.Color( pars.mcTrackColor )
trackLength = ( track ) ->
#if isNeutrino( track ) then return pars.neuLen
if isMuon(track)
if track.len? != 0 then return Math.abs(track.len)
if track.E?
l = track.E * 5
if l<20 then l = 20;
if l>4000 then l = 4000;
return l
if track.len > 0 then return track.len
return pars.trackLen
addDoms_mergedgeomery = ->
return unless pars.showDoms
doms = getSceneObj( "doms" )
geo = new THREE.SphereGeometry( pars.domSize,2*pars.domDetail, pars.domDetail )
mat = new THREE.MeshLambertMaterial( { color: new THREE.Color( pars.domColor )} )
mesh = new THREE.Mesh( geo );
mergedGeo = new THREE.Geometry();
for id, dom of det.doms
if dom.dir? then d = vmul( pars.domFactor, dom.dir)
else d = {x:0,y:0,z:1}
mesh.position.set( dom.pos.y + d.y, dom.pos.z + d.z, dom.pos.x + d.x);
mesh.updateMatrix()
mergedGeo.merge( mesh.geometry, mesh.matrix )
group = new THREE.Mesh( mergedGeo, mat );
doms.add(group)
addDoms_shader = ->
return unless pars.showDoms
doms = getSceneObj( "doms" )
geo = new THREE.InstancedBufferGeometry()
sphere = new THREE.SphereGeometry( pars.domSize,2*pars.domDetail, pars.domDetail )
sphere.rotateX( Math.PI )
geo.fromGeometry( sphere )
ndoms = 0
ndoms++ for id, dom of det.doms
offsets = new THREE.InstancedBufferAttribute( new Float32Array( ndoms * 3 ), 3, 1 );
orientations = new THREE.InstancedBufferAttribute( new Float32Array( ndoms * 3 ), 3, 1 )
i= 0
for id, dom of det.doms
if not dom.dir? or dom.dir.z > 0 # for antares it will be <0
dom.dir = {x:0,y:0,z:1}
d = {x:0,y:0,z:0}
else # for antares
d = vmul( pars.domFactor, dom.dir)
offsets.setXYZ( i, dom.pos.y + d.y , dom.pos.z + d.z , dom.pos.x + d.x )
orientations.setXYZ( i, dom.dir.y, dom.dir.z, dom.dir.x )
#console.log( dom.pos, dom.dir )
i+=1
geo.addAttribute( 'offset', offsets ); # per mesh translation (i.e. dom-position)
geo.addAttribute( 'orientation', orientations );
uniforms_ = THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "ambient" ],
THREE.UniformsLib[ "lights" ] ] );
material = new THREE.RawShaderMaterial
uniforms : uniforms_
vertexShader : vertexshader_glsl
fragmentShader : window[pars.domFragmentShader]
side : THREE.DoubleSide
lights : true
transparent : false
group = new THREE.Mesh( geo, material );
group.frustumCulled = false;
doms.add( group );
callbacks.addDoms = addDoms_shader
callbacks.addFloor = ->
floor = getSceneObj("floor")
det.floor_z = det.floor_z or Math.min( dom.pos.z for id,dom of det.doms... )-100
console.log( "addFloor" , det.floor_z);
texture = new THREE.TextureLoader().load( 'textures/image.png' );
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 100, 100 );
geo = new THREE.PlaneGeometry(20000,20000,1,1);
mat = new THREE.MeshBasicMaterial( {
color: pars.floorColor,
side: THREE.DoubleSide,
opacity : pars.floorOpacity,
transparent: false,
map: texture
} )
mesh = new THREE.Mesh( geo, mat );
mesh.rotation.x = 0.5*Math.PI;
mesh.position.y = det.floor_z;
floor.add( mesh );
callbacks.addStrings = ->
return unless pars.showStrings
return unless det.strings
strings = getSceneObj( "strings" )
mat = new THREE.MeshLambertMaterial ( color: new THREE.Color( pars.stringColor ) )
endpos = null
for stringpos in det.strings
startpos = tovec( stringpos )
if endpos
mesh = getCylinderMesh( startpos, endpos , pars.stringWidth, mat );
strings.add(mesh)
endpos = startpos
timeParameter= ( hit, track ) ->
switch pars.colScheme
when 'time' then hit.t
when 'track' then hit.t - time_track( track, hit.pos )
when 'shower' then hit.t - time_shower( track, hit.pos )
getHitColor = ( time , timerange, track ) ->
[mint, maxt] = timerange
aa = ( time - mint) / ( maxt - mint );
col = new THREE.Color()
if pars.palette == 'hue'
col.setHSL( aa , 1.0, 0.5 );
if pars.palette == 'doppler'
col.setRGB( 1-clamp( aa*aa ) , 0 , clamp( aa*2-1 ) )
return col
addHits_manymeshes = ->
hits = getSceneObj( "hits" )
hitarray = evt[ pars.hitSet ]
if !hitarray then return
if pars.hitStyle == 'sphere'
geo = new THREE.SphereGeometry( 2, 2*pars.hitDetail, pars.hitDetail )
if pars.hitStyle == 'disk'
geo = new THREE.CylinderGeometry( 2, 2 , 0.1 , pars.hitDetail , 1 ) # z-component will be scaled later
geo.translate(0, 0.05 ,0)
geo.rotateX( Math.PI / 2 )
have_direction = true
# min/max time for collormapping
evt.timerange = evt.timerange || [ Math.min( hit.t for hit in hitarray... ), Math.max( hit.t for hit in hitarray... ) ]
eval ('ampfun = function(hit) { return '+pars.ampFunc+';};')
for hit in hitarray
if pars.animate and hit.t > eventtime then continue
col = getHitColor( hit.t , evt.timerange )
mat = new THREE.MeshLambertMaterial( color: col );
mesh = new THREE.Mesh( geo , mat );
mesh.t = hit.t
d = hit.dir || {x:0,y:0,z:0}
a = pars.domFactor
mesh.position.set(
hit.pos.y + a * d.y
hit.pos.z + a * d.z
hit.pos.x + a * d.x )
a *= 2
if have_direction then mesh.lookAt( new THREE.Vector3(
hit.pos.y + a * d.y
hit.pos.z + a * d.z
hit.pos.x + a * d.x ) )
amp = ampfun( hit ) * pars.hitLength
mesh.scale.set( amp, amp, amp) if pars.hitStyle == 'sphere'
mesh.scale.set( 1,1,amp ) if pars.hitStyle == 'disk'
hits.add( mesh )
callbacks.animateHits_manymeshes = ->
#console.log( eventtime )
hits = scene.getObjectByName( "hits" ).children
for mesh in hits
mesh.visible = mesh.t > eventtime and mesh.t < (eventtime+200)
distFromCamera = ( pos ) ->
x = pos.y - camera.position.x
y = pos.z - camera.position.y
z = pos.x - camera.position.z
r = (x*x + y*y + z*z)
return r
# tovec( obj.pos).project( camera ).z
#----------------------------------------------------------
populateHitInstanceBuffers = ->
window.alert("populateHitInstanceBuffers cannot be called before addHits_shader");
make_hitcol = ( hitlist ) ->
X = {}
( X[ hit.dom_id ] ?= [] ).push( hit ) for hit in hitlist
hitcol = (v for k,v of X)
hitcol.doms_are_sorted = (verbose ) ->
olddepth = 1e10
r = true
for hitsondom in this
h = hitsondom[0]
h.depth = distFromCamera( h.pos )
if verbose then console.log( h.depth )
if h.depth > olddepth then r = false
olddepth = h.depth
return r
hitcol.dbg = ->
for lst,i in this
console.log( i, lst[0].depth )
if i > 10 then break
hitcol.sort_doms = ->
this.sort( (lst1, lst2) -> lst1[0].depth < lst2[0].depth )
hitcol.sort_within_doms = ->
for lst in this
h.depth = distFromCamera( h.pos ) for h in lst
lst.sort( (h1,h2) -> h1.depth < h2.depth )
hitcol.sort_all = ->
unless this.doms_are_sorted()
this.sort_doms()
this.sort_within_doms()
populateHitInstanceBuffers()
return hitcol
callbacks.depthSort = ->
t0 = (new Date()).getTime()
evt.sorted_hits.sort_all()
t1 = (new Date()).getTime()
console.log("depthSort took", t1-t0 )
callbacks.onNewEvent = ->
evt.tag = "evt"
evt.sorted_hits = make_hitcol( evt.hits )
evt.sorted_mc_hits = make_hitcol( evt.mc_hits )
for trk in evt.mc_trks
if isNeutrino( trk )
# move neutrino back 10 km
vv = vmul( 10000.0 , trk.dir )
trk.pos = vsub( trk.pos , vv )
trk.len = 10000
trk.t = trk.t - trk.len / clight
if scene?
callbacks.addHits()
callbacks.addTracks()
callbacks.onNewDetector = ->
console.log 'onNewDetector'
if det.name == "antares" then antares_mode()
det.tag = "det"
det.cg = {x:0,y:0,z:0}
det.ndoms = 0
for id, dom of det.doms
det.ndoms += 1
det.cg = vadd( det.cg, dom.pos )
addHits_shader = ->
hits = getSceneObj( "hits" )
hitarray = evt[ pars.hitSet ]
if !hitarray then return
console.log('addHits', hitarray.length );
evt.timerange = [ Math.min( hit.t for hit in hitarray... ), Math.max( hit.t for hit in hitarray... ) ]
geo = new THREE.InstancedBufferGeometry()
disk = new THREE.CylinderGeometry( pars.hitWidth,
3*pars.hitWidth , 0.1 , pars.hitDetail , 1 ) # z-component will be scaled later
disk.translate(0, -0.05 ,0)
disk.rotateZ( Math.PI / 2 )
geo.fromGeometry( disk )
nhits = hitarray.length
offsets = new THREE.InstancedBufferAttribute( new Float32Array( nhits * 3 ), 3, 1 ).setDynamic( true );
orientations = new THREE.InstancedBufferAttribute( new Float32Array( nhits * 3 ), 3, 1 ).setDynamic( true );
colors = new THREE.InstancedBufferAttribute( new Float32Array( nhits * 3 ), 3, 1 ).setDynamic( true );
amplitudes = new THREE.InstancedBufferAttribute( new Float32Array( nhits ), 1, 1 ).setDynamic( true );
times = new THREE.InstancedBufferAttribute( new Float32Array( nhits ), 1, 1 ).setDynamic( true );
tots = new THREE.InstancedBufferAttribute( new Float32Array( nhits ), 1, 1 ).setDynamic( true );
geo.addAttribute( 'offset', offsets );
geo.addAttribute( 'orientation', orientations );
geo.addAttribute( 'color', colors );
geo.addAttribute( 'amplitude', amplitudes );
geo.addAttribute( 'time', times );
geo.addAttribute( 'tot', tots );
a = pars.domFactor
populateHitInstanceBuffers = ->
eval ('ampfun = function(hit) { return '+pars.ampFunc+';};')
t1 = (new Date()).getTime()
i = 0
for domhits in evt.sorted_hits
for hit in domhits
col = getHitColor( hit.t , evt.timerange )
d = hit.dir || {x:0,y:0,z:1}
offsets.setXYZ( i, hit.pos.y + a * d.y, hit.pos.z + a * d.z, hit.pos.x + a * d.x )
orientations.setXYZ( i, hit.dir.y, hit.dir.z, hit.dir.x ); # todo and to think-about
colors.setXYZ(i, col.r, col.g, col.b )
amplitudes.setX(i, ampfun(hit)* pars.hitLength );
times.setX(i, hit.t );
tots.setX(i, hit.tot * pars['aniTotFactor']);
i+=1
t2 = (new Date()).getTime()
offsets.needsUpdate = true
orientations.needsUpdate = true
colors.needsUpdate = true
amplitudes.needsUpdate = true
times.needsUpdate = true
tots.needsUpdate = true
# console.log("polulating buffers took", t2-t1 )
populateHitInstanceBuffers()
material = new THREE.RawShaderMaterial( {
uniforms: { "eventtime": { type: "1f", value: 0 }
},
vertexShader : hit_vertexshader_glsl,
fragmentShader : hit_fragmentshader_glsl,
side : THREE.BackSide ,
transparent : true } );
mesh = new THREE.Mesh( geo, material );
mesh.frustumCulled = false;
hits.add( mesh );
callbacks['addHits'] = ->
if pars.hitStyle == 'cone' then addHits_shader()
else addHits_manymeshes()
callbacks.addTracks = ->
trks = getSceneObj 'trks'
if typeof t == 'undefined' then t = 1e10
trkcol = evt[pars.tracks] or []
for trk in trkcol
trklen = trackLength( trk )
startpos = trk.pos
endpos = vadd( trk.pos, vmul( trk.dir, trklen ) )
startt = trk.t
if isNeutrino( trk )
startpos = vadd( trk.pos, vmul( trk.dir, -trklen ) );
endpos = trk.pos
startt -= trklen / clight
mat = new THREE.MeshPhongMaterial ( {
emissive: new THREE.Color( trackColor(trk) ),
transparent: false ,
opacity: 0.5 } )
mesh = getCylinderMesh( startpos, endpos, pars.trackWidth, mat )
mesh.t0 = startt
mesh.t1 = startt + trklen / clight;
console.log("track", startpos, endpos , trklen )
trks.add (mesh)
callbacks.animateTracks = ( t ) ->
trks = scene.getObjectByName( 'trks' )
for mesh in trks.children
f = clamp ( (t - mesh.t0 ) / ( mesh.t1 - mesh.t0 ) )
mesh.scale.set( 1,1,f )
#console.log('anim trka', mesh.t0, mesh.t1, t , f)
callbacks.addEvt = ->
callbacks.addHits()
callbacks.addTracks()
callbacks.addDet = ->
callbacks.addFloor()
callbacks.addStrings()
callbacks.addDoms()
handlefile= ( e ) -> console.log( "filetje:", e.target.files )
callbacks.loadLocalFile = ->
element = document.createElement('div')
element.innerHTML = '<input type="file">'
fileInput = element.firstChild
fileInput.addEventListener('change', handlefile )
fileInput.click()
# At this point, all callbacks are defined and we
# can initialze the dat.gui. Note that the callbacks
# use the parameters defined in pars by buildmenu.
gui = window.buildmenu( pars , callbacks )
callbacks.vr_demo = (tnow) ->
window[pars.demo]?( tnow )
vr_demo1 = (tnow) ->
train.position.y = 500 + 400 * Math.sin( tnow/10000.0 )
addVRButton = ->
WEBVR.getVRDisplay( (display) ->
if not display?
console.log("no vr display found")
return
renderer.vr.setDevice( display )
gui.add( { "VR_mode" : ->
console.log("toggling vr mode!");
controls = new THREE.VRControls( camera );
effect = new THREE.VREffect( renderer );
if display.isPresenting then display.exitPresent() # crashes
else : display.requestPresent( [ { source: renderer.domElement } ] );
#callbacks.vr_demo = vr_demo1
} , "VR_mode" )
)
init = ->
t1 = (new Date()).getTime();
scene = new THREE.Scene()
console.log("bg col = ", pars.bgColor)
renderer = new THREE.WebGLRenderer
preserveDrawingBuffer : true
antialias : true
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight )
container.appendChild( renderer.domElement )
# --stats box-
stats = new Stats()
container.appendChild( stats.dom );
window.addEventListener( 'resize', onWindowResize, false );
light = new THREE.PointLight(0xffffff)
light.position.set(500,1000,0)
scene.add(light)
al = new THREE.AmbientLight(0x444444);
scene.add(al);
pars[attrname] = defpars[attrname] for attrname of defpars
console.log('call addcontrols', renderer)
callbacks.setBackgroundColor()
callbacks.addCamera()
callbacks.addStrings()
callbacks.addDoms()
callbacks.addTracks()
callbacks.addHits()
callbacks.addFloor()
callbacks.addOrbitControls()
# If we are not in VR mode, then the 'train' does not do anything
# otherwise it defines a sort of platform for the 'player' to stand on
train = new THREE.Object3D()
train.position.set( 0,0,0)
scene.add( train );
train.add( camera )
addVRButton();
raycaster = new THREE.Raycaster();
mouseVector = new THREE.Vector2();
showSelectionInfo( evt );
t2 = (new Date()).getTime();
console.log("init took (ms) : ", t2-t1 );
websock = new WebSocket("ws://www.cherenkov.nl:8181", "protocolOne");
websock.onmessage = (event) ->
console.oldlog("get wesocket message:", event.data);
s = eval( event.data )
console.log( JSON.stringify(s) )
websock.onopen = () -> # replace console.log
console.oldlog = console.log
console.log = () ->
a = Array.prototype.slice.call(arguments)
console.oldlog( arguments )
websock.send( a.toString() )
showSelectionInfo = ->
selected ?= evt
infodiv = document.getElementById("info")
if not infodiv
infodiv = document.createElement 'div'
infodiv.id = 'info'
infodiv.big = false
infodiv.addEventListener "click", ->
console.log 'click'
infodiv.big = !infodiv.big
showSelectionInfo()
document.body.appendChild infodiv
M = {'trk':'Track', 'hit':'Hit', 'evt':'Event'}
html = """ <h3> #{M[selected.tag]} #{selected.id} </h3> <table style="width:100%"><tr> """
if infodiv.big # list all attributes of 'selected' object
for key, val of selected
if Array.isArray(val) then val = val.length.toString() + "entries"
if isvec( val ) then val = val.x.toFixed(3) +', ' + val.y.toFixed(3) + ', ' + val.z.toFixed(3);
html += '<tr><td> '+key+' </td><td> '+val+'</td></tr>'
html += '</table>'
infodiv.innerHTML = html
`
function onMouseMove( e )
{
console.log ("mousemove")
mouseVector.x = 2 * (e.clientX / window.innerWidth ) - 1;
mouseVector.y = 1 - 2 * ( e.clientY / window.innerHeight );
raycaster.setFromCamera( mouseVector, camera );
var searchObjects = ["hits","trks"];
flag = false;
if ( selectedHit)
{
selectedHit.material.emissive.setHex( selectedHit.oldHex);
}
for ( var ii = 0; ii<searchObjects.length; ii++ )
{
var collection = scene.getObjectByName( searchObjects[ii] );
console.log( collection );
var intersects = raycaster.intersectObjects( collection.children );
console.log("intersects", intersects );
if ( intersects.length > 0 )
{
var sel = intersects[ 0 ].object;
if ( sel.hasOwnProperty("aaobj") )
{
selectedHit = sel;
sel.oldHex = sel.material.emissive.getHex();
sel.material.emissive.setHex( 0xff0000 );
sel.aaobj.tag = searchObjects[ii].substring(0,3);
showSelectionInfo( sel.aaobj );
flag = true;
}
}
}
evt.tag = "evt";
if (!flag) showSelectionInfo( evt );
}
function onWindowResize()
{
//windowHalfX = window.innerWidth / 2;
//windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
//
if (effect)
{
setSize( window.innerWidth, window.innerHeight );
}
else
{
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}
//render();
}
function animate()
{
// schedule next one
if (effect)
{
effect.requestAnimationFrame( animate );
}
else
{
requestAnimationFrame( animate );
}
var tnow = (new Date()).getTime();
if (!pars.animate)
{
scene.getObjectByName( 'hits' ).children[0].material.uniforms.eventtime.value = eventtime;
eventtime = 2e100;
}
else
{
// --- animation time ---
var slowdown = pars.ns_per_s /1000.0 ;
var tx = tnow * slowdown;
var t1 = evt.timerange[0] - pars.introTime;
var t2 = evt.timerange[1] + 255.0 * pars.aniTotFactor + pars.outroTime
eventtime = ( tx % (t2-t1)) + t1 ;
callbacks.animateTracks( eventtime );
if (pars.hitStyle == 'cone')
{
scene.getObjectByName( 'hits' ).children[0].material.uniforms.eventtime.value = eventtime;
}
else
{
if (pars.animate) {callbacks.animateHits_manymeshes()};
}
}
if ( typeof animate.tthen == 'undefined' ) animate.tthen = tnow;
var dt = animate.tthen-tnow;
animate.tthen = tnow;
callbacks.vr_demo( tnow )
if ( pars.rotate )
{
var ax = new THREE.Vector3( 0, 1, 0 );
camera.position.applyAxisAngle( ax , 0.00001* pars.rotationSpeed * dt );
}
controls.update();
stats.update();
render();
}
`
render = ->
#console.log(render)
render.n ?= 0
render.n+=1
THREE.VRController.update()
#if pars.depthSortEvery > 0 and render.n % pars.depthSortEvery == 0 then callbacks.depthSort()
if effect
effect.render( scene, camera )
else
renderer.render( scene, camera )
newwindow = -> window.new_window_ref = window.open( window.location )
container = document.createElement( 'container' );
container.id = "container";
document.body.appendChild( container );
initdiv = document.createElement( 'div' );
initdiv.id = 'init';
initdiv.innerHTML = '<br>aa3d starting up.</br>';
document.body.appendChild( initdiv );
unzip = ( buf ) ->
words = new Uint8Array( buf )
U = pako.ungzip(words)
console.log(U)
result = "";
for i in [0..U.length-1]
result+= String.fromCharCode(U[i]) ;
return result
# old browsers dont have str.endsWidth
str_endsWith = (s, suffix) ->
s.indexOf(suffix, s.length - suffix.length) != -1;
antares_mode = ->
console.log("antares mode")
pars.set( "domFragmentShader", "fragmentshader_antares_glsl")
pars.set( "camHeight" , 200 )
pars.set( "camDistance", 250 )
pars.set( "domSize", 2.0 )
pars.set( "domFactor", 3 )
pars.set( "hitStyle", "sphere" )
pars.set( "ampFunc", "Math.sqrt(hit.a)" )
pars.set( "palette", "hue" )
pars.set( "hitLength", 1.5 )
pars.set( "depthSortEvery", 0 )
loadFile = ( url , asynch = true , when_done ) ->
console.log( url, when_done, asynch )
gz = str_endsWith( url, ".gz" )
xmlhttp = new XMLHttpRequest()
if gz then xmlhttp.responseType = 'arraybuffer';
process = ( req ) ->
if gz
s = unzip( xmlhttp.response )
eval( s )
else
eval( xmlhttp.responseText )
when_done?()
if asynch
xmlhttp.onprogress = (ev) -> console.log( 'getting file:'+url+' __ '+ ev.loaded/1e6 +' MB')
xmlhttp.onreadystatechange = () ->
return unless xmlhttp.readyState == 4
return unless xmlhttp.status == 200
console.log("done");
process( xmlhttp )
xmlhttp.open("GET", url , asynch );
xmlhttp.send();
if not asynch then process( xmlhttp )
many_screenshots = ( i=0 ) ->
s = """
diffuse2017/detevt_28722_45202_426
diffuse2017/detevt_35473_7183_1050
diffuse2017/detevt_38472_61820_16446
diffuse2017/detevt_38518_41252_24091
diffuse2017/detevt_38519_42310_26116
diffuse2017/detevt_39324_118871_32515
diffuse2017/detevt_45265_79259_997305
diffuse2017/detevt_45835_34256_1041663
diffuse2017/detevt_46852_51708_917709
diffuse2017/detevt_47833_1124_537259
diffuse2017/detevt_49425_32175_104853
diffuse2017/detevt_49821_56923_25516
diffuse2017/detevt_49853_25438_1385
diffuse2017/detevt_53037_101247_36731
diffuse2017/detevt_53060_41698_354601
diffuse2017/detevt_54260_1639_2925759
diffuse2017/detevt_57495_15712_326824
diffuse2017/detevt_60896_68105_494258
diffuse2017/detevt_60907_60252_572415
diffuse2017/detevt_61023_10375_2179659
diffuse2017/detevt_62657_88204_22071
diffuse2017/detevt_62834_30474_384475
diffuse2017/detevt_65811_20990_137527
diffuse2017/detevt_68473_32777_22562
diffuse2017/detevt_68883_33383_1459227
diffuse2017/detevt_70787_9986_323373
diffuse2017/detevt_71534_74641_364543
diffuse2017/detevt_74307_193564_6908522
diffuse2017/detevt_77640_77424_3612
diffuse2017/detevt_80885_49449_12484201
diffuse2017/detevt_81667_163768_2732223
diffuse2017/detevt_82539_9289_2425758
diffuse2017/detevt_82676_118860_167410
""".split("\n")
for fn in s
if not fn then continue
scfile = fn.split("/").pop()
loadFile( fn , false, ->
callbacks.onNewEvent()
#init()
callbacks.onNewDetector()
render()
callbacks.write_screenshot(scfile) )
if window.opener then console.log("we have an opener", window.opener );
`
window.addEventListener( 'vr controller connected', function( event ){
console.log("VR CONTROLLER!!!!!!!!!!!!!!!!!!!!!!!!!");
// Here it is, your VR controller instance.
// It’s really a THREE.Object3D so you can just add it to your scene:
controller = event.detail
train.add( controller )
// HEY HEY HEY! This is important. You need to make sure you do this.
// For standing experiences (not seated) we need to set the standingMatrix
// otherwise you’ll wonder why your controller appears on the floor
// instead of in your hands! And for seated experiences this will have no
// effect, so safe to do either way:
controller.standingMatrix = renderer.vr.getStandingMatrix()
// And for 3DOF (seated) controllers you need to set the controller.head
// to reference your camera. That way we can make an educated guess where
// your hand ought to appear based on the camera’s rotation.
controller.head = window.camera
// Right now your controller has no visual.
// It’s just an empty THREE.Object3D.
// Let’s fix that!
var
meshColorOff = 0xFF4040,
meshColorOn = 0xFFFF00,
controllerMaterial = new THREE.MeshStandardMaterial({
color: meshColorOff,
shading: THREE.FlatShading
}),
controllerMesh = new THREE.Mesh(
new THREE.CylinderGeometry( 0.005, 0.05, 0.1, 6 ),
controllerMaterial
),
handleMesh = new THREE.Mesh(
new THREE.BoxGeometry( 0.03, 0.1, 0.03 ),
controllerMaterial
)
//controllerMesh.scale.set(100,100,100);
controllerMesh.rotation.x = -Math.PI / 2;
handleMesh.position.y = -0.05;
controllerMesh.add( handleMesh );
controller.userData.mesh = controllerMesh;// So we can change the color later.
controller.add( controllerMesh );
// Allow this controller to interact with DAT GUI.
//var guiInputHelper = dat.GUIVR.addInputObject( controller )
//scene.add( guiInputHelper )
// Button events. How easy is this?!
// We’ll just use the “primary” button -- whatever that might be ;)
// Check out the THREE.VRController.supported{} object to see
// all the named buttons we’ve already mapped for you!
controller.addEventListener( 'primary press began', function( event ){
train.position.add( controller.rotation );
event.target.userData.mesh.material.color.setHex( meshColorOn )
//guiInputHelper.pressed( true )
})
controller.addEventListener( 'primary press ended', function( event ){
event.target.userData.mesh.material.color.setHex( meshColorOff )
//guiInputHelper.pressed( false )
})
// Daddy, what happens when we die?
controller.addEventListener( 'disconnected', function( event ){
controller.parent.remove( controller )
})
})
`
url = getUrlPar('f');
if url == "none"
init();
render();
animate();
if !url then url="detevt2_km3.js" #some test file
initdiv.innerHTML = '<br>getting file:'+url+'</br>'
console.log( 'get',url )
loadFile( url, true, ->
callbacks.onNewEvent()
init()
callbacks.onNewDetector()
render()
animate()
)
| 39226 |
# this is the aa3d event display for antares and km3net
# object that will hold all the user-modifiable parameters (and then some)
pars = {}
defpars = {}
# physics-domain data
clight = 0.299792458 # m/ns
evt = {"hits": [], "trks":[]};
det = {"doms": [{"id": 1, "dir": {"y":0, "x": 0, "z": 0}, "pos": {"y": 0, "x": 0, "z": 0} }] };
# three.js objects
scene= camera= renderer= raycaster= mouseVector= controls = null;
geometry= material= mesh= null
container= stats= gui = null
containerWidth= containerHeight= null
eventtime = 0.0;
light= null
gui = null
effect = null
train = null
selectedHit = null
ii = null#
dus = 42
callbacks = {}
selected = null
dbg_cam = false
evil = ( code ) -> eval ( code ) # eval's evil brother (to access scope)
#-----------------------------------------
# Simple Vector functions and math utils
#-----------------------------------------
isvec = ( obj ) -> typeof(obj) == 'object' and 'x' of obj and 'y' of obj and 'z' of obj
vadd = ( v1, v2 ) -> { x : v1.x + v2.x, y: v1.y + v2.y , z: v1.z + v2. z }
vsub = ( v1, v2 ) -> { x : v1.x - v2.x, y: v1.y - v2.y , z: v1.z - v2. z }
vmul = ( v1, a ) ->
if typeof v1 == 'number' then return vmul( a, v1 )
return { x: v1.x * a, y: v1.y * a, z : v1.z * a }
vlen = ( v1, v2 = {x:0,y:0,z:0} ) ->
Math.sqrt( (v1.x-v2.x)*(v1.x-v2.x) + (v1.y-v2.y)*(v1.y-v2.y) + (v1.z-v2.z)*(v1.z-v2.z) )
tovec = (obj) ->
new THREE.Vector3 obj.y, obj.z, obj.x
clamp = ( x, min=0, max=1 ) ->
if x <= min then return min
if x >= max then return max
return x
getUrlPar = (name, url ) ->
url ?= window.location.href
name = name.replace(/[\[\]]/g, "\\$&")
regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
results = regex.exec(url);
if !results then return null
if !results[2] then return ''
return decodeURIComponent(results[2].replace(/\+/g, " "));
getCylinderMesh = ( startpoint, endpoint, width , material , width2 ) ->
l = vlen( endpoint, startpoint )
width2 ?= width
geom = new THREE.CylinderGeometry( width, width2 , l );
geom.translate(0, l/2 ,0);
geom.rotateX( Math.PI / 2 );
mesh = new THREE.Mesh( geom , material.clone() );
mesh.position.set( startpoint.y, startpoint.z, startpoint.x );
mesh.lookAt( tovec(endpoint) );
return mesh;
getConeMesh = ( startpoint, endpoint, width, material ) ->
getCylinderMesh( startpoint, endpoint, width, material, 0 )
callbacks.setBackgroundColor = ->
scene.background = new THREE.Color( pars.bgColor )
callbacks.screenshot = ->
dt = renderer.domElement.toDataURL( 'image/png' );
window.open( dt, 'screenshot')
callbacks.screenshot360 = ->
console.log("screenshot360")
X = new CubemapToEquirectangular( renderer, true );
X.update( camera, scene )
callbacks.write_screenshot = (fn) ->
url = "uploadimg.php"
params = "fn="+fn+".png&payload="+renderer.domElement.toDataURL( 'image/png' );
console.log(params)
http = new XMLHttpRequest()
http.open("POST", url , false )
#Send the proper header information along with the request
http.send( params )
if http.readyState == 4 && http.status == 200 then console.log(http.responseText)
else console.log('error sending screenshot')
callbacks.addCamera =->
camera ?= new THREE.PerspectiveCamera( 75,window.innerWidth / window.innerHeight, 0.01, 10000 );
camera.position.x = 0
camera.position.y = pars.camHeight
camera.position.z = pars.camDistance
callbacks.addOrbitControls =->
controls = new THREE.OrbitControls( camera , renderer.domElement )
cg = det.cg or {x:0, y:0, z:0} # det may not exist yet
controls.center = new THREE.Vector3(cg.z, cg.y, cg.x) or new THREE.Vector3( camera.position.x, camera.position.y, 0.0 )
controls.update()
controls.addEventListener( 'change', render )
return controls
getSceneObj = ( name ) ->
while obj = scene.getObjectByName( name )
scene.remove( obj )
obj = new THREE.Object3D()
obj.name = name
scene.add( obj )
return obj
isNeutrino = (track) -> Math.abs( track.type ) in [12,14,16]
isLepton = (track) -> Math.abs( track.type ) in [11,13,15]
isMuon = (track) -> Math.abs( track.type ) == 13
trackColor = ( track ) ->
if track.type == 0
return new THREE.Color( pars.trackColor )
if isNeutrino( track )
return new THREE.Color( pars.neuColor )
if isMuon( track)
return new THREE.Color( pars.muColor )
return new THREE.Color( pars.mcTrackColor )
trackLength = ( track ) ->
#if isNeutrino( track ) then return pars.neuLen
if isMuon(track)
if track.len? != 0 then return Math.abs(track.len)
if track.E?
l = track.E * 5
if l<20 then l = 20;
if l>4000 then l = 4000;
return l
if track.len > 0 then return track.len
return pars.trackLen
addDoms_mergedgeomery = ->
return unless pars.showDoms
doms = getSceneObj( "doms" )
geo = new THREE.SphereGeometry( pars.domSize,2*pars.domDetail, pars.domDetail )
mat = new THREE.MeshLambertMaterial( { color: new THREE.Color( pars.domColor )} )
mesh = new THREE.Mesh( geo );
mergedGeo = new THREE.Geometry();
for id, dom of det.doms
if dom.dir? then d = vmul( pars.domFactor, dom.dir)
else d = {x:0,y:0,z:1}
mesh.position.set( dom.pos.y + d.y, dom.pos.z + d.z, dom.pos.x + d.x);
mesh.updateMatrix()
mergedGeo.merge( mesh.geometry, mesh.matrix )
group = new THREE.Mesh( mergedGeo, mat );
doms.add(group)
addDoms_shader = ->
return unless pars.showDoms
doms = getSceneObj( "doms" )
geo = new THREE.InstancedBufferGeometry()
sphere = new THREE.SphereGeometry( pars.domSize,2*pars.domDetail, pars.domDetail )
sphere.rotateX( Math.PI )
geo.fromGeometry( sphere )
ndoms = 0
ndoms++ for id, dom of det.doms
offsets = new THREE.InstancedBufferAttribute( new Float32Array( ndoms * 3 ), 3, 1 );
orientations = new THREE.InstancedBufferAttribute( new Float32Array( ndoms * 3 ), 3, 1 )
i= 0
for id, dom of det.doms
if not dom.dir? or dom.dir.z > 0 # for antares it will be <0
dom.dir = {x:0,y:0,z:1}
d = {x:0,y:0,z:0}
else # for antares
d = vmul( pars.domFactor, dom.dir)
offsets.setXYZ( i, dom.pos.y + d.y , dom.pos.z + d.z , dom.pos.x + d.x )
orientations.setXYZ( i, dom.dir.y, dom.dir.z, dom.dir.x )
#console.log( dom.pos, dom.dir )
i+=1
geo.addAttribute( 'offset', offsets ); # per mesh translation (i.e. dom-position)
geo.addAttribute( 'orientation', orientations );
uniforms_ = THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "ambient" ],
THREE.UniformsLib[ "lights" ] ] );
material = new THREE.RawShaderMaterial
uniforms : uniforms_
vertexShader : vertexshader_glsl
fragmentShader : window[pars.domFragmentShader]
side : THREE.DoubleSide
lights : true
transparent : false
group = new THREE.Mesh( geo, material );
group.frustumCulled = false;
doms.add( group );
callbacks.addDoms = addDoms_shader
callbacks.addFloor = ->
floor = getSceneObj("floor")
det.floor_z = det.floor_z or Math.min( dom.pos.z for id,dom of det.doms... )-100
console.log( "addFloor" , det.floor_z);
texture = new THREE.TextureLoader().load( 'textures/image.png' );
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 100, 100 );
geo = new THREE.PlaneGeometry(20000,20000,1,1);
mat = new THREE.MeshBasicMaterial( {
color: pars.floorColor,
side: THREE.DoubleSide,
opacity : pars.floorOpacity,
transparent: false,
map: texture
} )
mesh = new THREE.Mesh( geo, mat );
mesh.rotation.x = 0.5*Math.PI;
mesh.position.y = det.floor_z;
floor.add( mesh );
callbacks.addStrings = ->
return unless pars.showStrings
return unless det.strings
strings = getSceneObj( "strings" )
mat = new THREE.MeshLambertMaterial ( color: new THREE.Color( pars.stringColor ) )
endpos = null
for stringpos in det.strings
startpos = tovec( stringpos )
if endpos
mesh = getCylinderMesh( startpos, endpos , pars.stringWidth, mat );
strings.add(mesh)
endpos = startpos
timeParameter= ( hit, track ) ->
switch pars.colScheme
when 'time' then hit.t
when 'track' then hit.t - time_track( track, hit.pos )
when 'shower' then hit.t - time_shower( track, hit.pos )
getHitColor = ( time , timerange, track ) ->
[mint, maxt] = timerange
aa = ( time - mint) / ( maxt - mint );
col = new THREE.Color()
if pars.palette == 'hue'
col.setHSL( aa , 1.0, 0.5 );
if pars.palette == 'doppler'
col.setRGB( 1-clamp( aa*aa ) , 0 , clamp( aa*2-1 ) )
return col
addHits_manymeshes = ->
hits = getSceneObj( "hits" )
hitarray = evt[ pars.hitSet ]
if !hitarray then return
if pars.hitStyle == 'sphere'
geo = new THREE.SphereGeometry( 2, 2*pars.hitDetail, pars.hitDetail )
if pars.hitStyle == 'disk'
geo = new THREE.CylinderGeometry( 2, 2 , 0.1 , pars.hitDetail , 1 ) # z-component will be scaled later
geo.translate(0, 0.05 ,0)
geo.rotateX( Math.PI / 2 )
have_direction = true
# min/max time for collormapping
evt.timerange = evt.timerange || [ Math.min( hit.t for hit in hitarray... ), Math.max( hit.t for hit in hitarray... ) ]
eval ('ampfun = function(hit) { return '+pars.ampFunc+';};')
for hit in hitarray
if pars.animate and hit.t > eventtime then continue
col = getHitColor( hit.t , evt.timerange )
mat = new THREE.MeshLambertMaterial( color: col );
mesh = new THREE.Mesh( geo , mat );
mesh.t = hit.t
d = hit.dir || {x:0,y:0,z:0}
a = pars.domFactor
mesh.position.set(
hit.pos.y + a * d.y
hit.pos.z + a * d.z
hit.pos.x + a * d.x )
a *= 2
if have_direction then mesh.lookAt( new THREE.Vector3(
hit.pos.y + a * d.y
hit.pos.z + a * d.z
hit.pos.x + a * d.x ) )
amp = ampfun( hit ) * pars.hitLength
mesh.scale.set( amp, amp, amp) if pars.hitStyle == 'sphere'
mesh.scale.set( 1,1,amp ) if pars.hitStyle == 'disk'
hits.add( mesh )
callbacks.animateHits_manymeshes = ->
#console.log( eventtime )
hits = scene.getObjectByName( "hits" ).children
for mesh in hits
mesh.visible = mesh.t > eventtime and mesh.t < (eventtime+200)
distFromCamera = ( pos ) ->
x = pos.y - camera.position.x
y = pos.z - camera.position.y
z = pos.x - camera.position.z
r = (x*x + y*y + z*z)
return r
# tovec( obj.pos).project( camera ).z
#----------------------------------------------------------
populateHitInstanceBuffers = ->
window.alert("populateHitInstanceBuffers cannot be called before addHits_shader");
make_hitcol = ( hitlist ) ->
X = {}
( X[ hit.dom_id ] ?= [] ).push( hit ) for hit in hitlist
hitcol = (v for k,v of X)
hitcol.doms_are_sorted = (verbose ) ->
olddepth = 1e10
r = true
for hitsondom in this
h = hitsondom[0]
h.depth = distFromCamera( h.pos )
if verbose then console.log( h.depth )
if h.depth > olddepth then r = false
olddepth = h.depth
return r
hitcol.dbg = ->
for lst,i in this
console.log( i, lst[0].depth )
if i > 10 then break
hitcol.sort_doms = ->
this.sort( (lst1, lst2) -> lst1[0].depth < lst2[0].depth )
hitcol.sort_within_doms = ->
for lst in this
h.depth = distFromCamera( h.pos ) for h in lst
lst.sort( (h1,h2) -> h1.depth < h2.depth )
hitcol.sort_all = ->
unless this.doms_are_sorted()
this.sort_doms()
this.sort_within_doms()
populateHitInstanceBuffers()
return hitcol
callbacks.depthSort = ->
t0 = (new Date()).getTime()
evt.sorted_hits.sort_all()
t1 = (new Date()).getTime()
console.log("depthSort took", t1-t0 )
callbacks.onNewEvent = ->
evt.tag = "evt"
evt.sorted_hits = make_hitcol( evt.hits )
evt.sorted_mc_hits = make_hitcol( evt.mc_hits )
for trk in evt.mc_trks
if isNeutrino( trk )
# move neutrino back 10 km
vv = vmul( 10000.0 , trk.dir )
trk.pos = vsub( trk.pos , vv )
trk.len = 10000
trk.t = trk.t - trk.len / clight
if scene?
callbacks.addHits()
callbacks.addTracks()
callbacks.onNewDetector = ->
console.log 'onNewDetector'
if det.name == "antares" then antares_mode()
det.tag = "det"
det.cg = {x:0,y:0,z:0}
det.ndoms = 0
for id, dom of det.doms
det.ndoms += 1
det.cg = vadd( det.cg, dom.pos )
addHits_shader = ->
hits = getSceneObj( "hits" )
hitarray = evt[ pars.hitSet ]
if !hitarray then return
console.log('addHits', hitarray.length );
evt.timerange = [ Math.min( hit.t for hit in hitarray... ), Math.max( hit.t for hit in hitarray... ) ]
geo = new THREE.InstancedBufferGeometry()
disk = new THREE.CylinderGeometry( pars.hitWidth,
3*pars.hitWidth , 0.1 , pars.hitDetail , 1 ) # z-component will be scaled later
disk.translate(0, -0.05 ,0)
disk.rotateZ( Math.PI / 2 )
geo.fromGeometry( disk )
nhits = hitarray.length
offsets = new THREE.InstancedBufferAttribute( new Float32Array( nhits * 3 ), 3, 1 ).setDynamic( true );
orientations = new THREE.InstancedBufferAttribute( new Float32Array( nhits * 3 ), 3, 1 ).setDynamic( true );
colors = new THREE.InstancedBufferAttribute( new Float32Array( nhits * 3 ), 3, 1 ).setDynamic( true );
amplitudes = new THREE.InstancedBufferAttribute( new Float32Array( nhits ), 1, 1 ).setDynamic( true );
times = new THREE.InstancedBufferAttribute( new Float32Array( nhits ), 1, 1 ).setDynamic( true );
tots = new THREE.InstancedBufferAttribute( new Float32Array( nhits ), 1, 1 ).setDynamic( true );
geo.addAttribute( 'offset', offsets );
geo.addAttribute( 'orientation', orientations );
geo.addAttribute( 'color', colors );
geo.addAttribute( 'amplitude', amplitudes );
geo.addAttribute( 'time', times );
geo.addAttribute( 'tot', tots );
a = pars.domFactor
populateHitInstanceBuffers = ->
eval ('ampfun = function(hit) { return '+pars.ampFunc+';};')
t1 = (new Date()).getTime()
i = 0
for domhits in evt.sorted_hits
for hit in domhits
col = getHitColor( hit.t , evt.timerange )
d = hit.dir || {x:0,y:0,z:1}
offsets.setXYZ( i, hit.pos.y + a * d.y, hit.pos.z + a * d.z, hit.pos.x + a * d.x )
orientations.setXYZ( i, hit.dir.y, hit.dir.z, hit.dir.x ); # todo and to think-about
colors.setXYZ(i, col.r, col.g, col.b )
amplitudes.setX(i, ampfun(hit)* pars.hitLength );
times.setX(i, hit.t );
tots.setX(i, hit.tot * pars['aniTotFactor']);
i+=1
t2 = (new Date()).getTime()
offsets.needsUpdate = true
orientations.needsUpdate = true
colors.needsUpdate = true
amplitudes.needsUpdate = true
times.needsUpdate = true
tots.needsUpdate = true
# console.log("polulating buffers took", t2-t1 )
populateHitInstanceBuffers()
material = new THREE.RawShaderMaterial( {
uniforms: { "eventtime": { type: "1f", value: 0 }
},
vertexShader : hit_vertexshader_glsl,
fragmentShader : hit_fragmentshader_glsl,
side : THREE.BackSide ,
transparent : true } );
mesh = new THREE.Mesh( geo, material );
mesh.frustumCulled = false;
hits.add( mesh );
callbacks['addHits'] = ->
if pars.hitStyle == 'cone' then addHits_shader()
else addHits_manymeshes()
callbacks.addTracks = ->
trks = getSceneObj 'trks'
if typeof t == 'undefined' then t = 1e10
trkcol = evt[pars.tracks] or []
for trk in trkcol
trklen = trackLength( trk )
startpos = trk.pos
endpos = vadd( trk.pos, vmul( trk.dir, trklen ) )
startt = trk.t
if isNeutrino( trk )
startpos = vadd( trk.pos, vmul( trk.dir, -trklen ) );
endpos = trk.pos
startt -= trklen / clight
mat = new THREE.MeshPhongMaterial ( {
emissive: new THREE.Color( trackColor(trk) ),
transparent: false ,
opacity: 0.5 } )
mesh = getCylinderMesh( startpos, endpos, pars.trackWidth, mat )
mesh.t0 = startt
mesh.t1 = startt + trklen / clight;
console.log("track", startpos, endpos , trklen )
trks.add (mesh)
callbacks.animateTracks = ( t ) ->
trks = scene.getObjectByName( 'trks' )
for mesh in trks.children
f = clamp ( (t - mesh.t0 ) / ( mesh.t1 - mesh.t0 ) )
mesh.scale.set( 1,1,f )
#console.log('anim trka', mesh.t0, mesh.t1, t , f)
callbacks.addEvt = ->
callbacks.addHits()
callbacks.addTracks()
callbacks.addDet = ->
callbacks.addFloor()
callbacks.addStrings()
callbacks.addDoms()
handlefile= ( e ) -> console.log( "filetje:", e.target.files )
callbacks.loadLocalFile = ->
element = document.createElement('div')
element.innerHTML = '<input type="file">'
fileInput = element.firstChild
fileInput.addEventListener('change', handlefile )
fileInput.click()
# At this point, all callbacks are defined and we
# can initialze the dat.gui. Note that the callbacks
# use the parameters defined in pars by buildmenu.
gui = window.buildmenu( pars , callbacks )
callbacks.vr_demo = (tnow) ->
window[pars.demo]?( tnow )
vr_demo1 = (tnow) ->
train.position.y = 500 + 400 * Math.sin( tnow/10000.0 )
addVRButton = ->
WEBVR.getVRDisplay( (display) ->
if not display?
console.log("no vr display found")
return
renderer.vr.setDevice( display )
gui.add( { "VR_mode" : ->
console.log("toggling vr mode!");
controls = new THREE.VRControls( camera );
effect = new THREE.VREffect( renderer );
if display.isPresenting then display.exitPresent() # crashes
else : display.requestPresent( [ { source: renderer.domElement } ] );
#callbacks.vr_demo = vr_demo1
} , "VR_mode" )
)
init = ->
t1 = (new Date()).getTime();
scene = new THREE.Scene()
console.log("bg col = ", pars.bgColor)
renderer = new THREE.WebGLRenderer
preserveDrawingBuffer : true
antialias : true
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight )
container.appendChild( renderer.domElement )
# --stats box-
stats = new Stats()
container.appendChild( stats.dom );
window.addEventListener( 'resize', onWindowResize, false );
light = new THREE.PointLight(0xffffff)
light.position.set(500,1000,0)
scene.add(light)
al = new THREE.AmbientLight(0x444444);
scene.add(al);
pars[attrname] = defpars[attrname] for attrname of defpars
console.log('call addcontrols', renderer)
callbacks.setBackgroundColor()
callbacks.addCamera()
callbacks.addStrings()
callbacks.addDoms()
callbacks.addTracks()
callbacks.addHits()
callbacks.addFloor()
callbacks.addOrbitControls()
# If we are not in VR mode, then the 'train' does not do anything
# otherwise it defines a sort of platform for the 'player' to stand on
train = new THREE.Object3D()
train.position.set( 0,0,0)
scene.add( train );
train.add( camera )
addVRButton();
raycaster = new THREE.Raycaster();
mouseVector = new THREE.Vector2();
showSelectionInfo( evt );
t2 = (new Date()).getTime();
console.log("init took (ms) : ", t2-t1 );
websock = new WebSocket("ws://www.cherenkov.nl:8181", "protocolOne");
websock.onmessage = (event) ->
console.oldlog("get wesocket message:", event.data);
s = eval( event.data )
console.log( JSON.stringify(s) )
websock.onopen = () -> # replace console.log
console.oldlog = console.log
console.log = () ->
a = Array.prototype.slice.call(arguments)
console.oldlog( arguments )
websock.send( a.toString() )
showSelectionInfo = ->
selected ?= evt
infodiv = document.getElementById("info")
if not infodiv
infodiv = document.createElement 'div'
infodiv.id = 'info'
infodiv.big = false
infodiv.addEventListener "click", ->
console.log 'click'
infodiv.big = !infodiv.big
showSelectionInfo()
document.body.appendChild infodiv
M = {'trk':'Track', 'hit':'Hit', 'evt':'Event'}
html = """ <h3> #{M[selected.tag]} #{selected.id} </h3> <table style="width:100%"><tr> """
if infodiv.big # list all attributes of 'selected' object
for key, val of selected
if Array.isArray(val) then val = val.length.toString() + "entries"
if isvec( val ) then val = val.x.toFixed(3) +', ' + val.y.toFixed(3) + ', ' + val.z.toFixed(3);
html += '<tr><td> '+key+' </td><td> '+val+'</td></tr>'
html += '</table>'
infodiv.innerHTML = html
`
function onMouseMove( e )
{
console.log ("mousemove")
mouseVector.x = 2 * (e.clientX / window.innerWidth ) - 1;
mouseVector.y = 1 - 2 * ( e.clientY / window.innerHeight );
raycaster.setFromCamera( mouseVector, camera );
var searchObjects = ["hits","trks"];
flag = false;
if ( selectedHit)
{
selectedHit.material.emissive.setHex( selectedHit.oldHex);
}
for ( var ii = 0; ii<searchObjects.length; ii++ )
{
var collection = scene.getObjectByName( searchObjects[ii] );
console.log( collection );
var intersects = raycaster.intersectObjects( collection.children );
console.log("intersects", intersects );
if ( intersects.length > 0 )
{
var sel = intersects[ 0 ].object;
if ( sel.hasOwnProperty("aaobj") )
{
selectedHit = sel;
sel.oldHex = sel.material.emissive.getHex();
sel.material.emissive.setHex( 0xff0000 );
sel.aaobj.tag = searchObjects[ii].substring(0,3);
showSelectionInfo( sel.aaobj );
flag = true;
}
}
}
evt.tag = "evt";
if (!flag) showSelectionInfo( evt );
}
function onWindowResize()
{
//windowHalfX = window.innerWidth / 2;
//windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
//
if (effect)
{
setSize( window.innerWidth, window.innerHeight );
}
else
{
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}
//render();
}
function animate()
{
// schedule next one
if (effect)
{
effect.requestAnimationFrame( animate );
}
else
{
requestAnimationFrame( animate );
}
var tnow = (new Date()).getTime();
if (!pars.animate)
{
scene.getObjectByName( 'hits' ).children[0].material.uniforms.eventtime.value = eventtime;
eventtime = 2e100;
}
else
{
// --- animation time ---
var slowdown = pars.ns_per_s /1000.0 ;
var tx = tnow * slowdown;
var t1 = evt.timerange[0] - pars.introTime;
var t2 = evt.timerange[1] + 255.0 * pars.aniTotFactor + pars.outroTime
eventtime = ( tx % (t2-t1)) + t1 ;
callbacks.animateTracks( eventtime );
if (pars.hitStyle == 'cone')
{
scene.getObjectByName( 'hits' ).children[0].material.uniforms.eventtime.value = eventtime;
}
else
{
if (pars.animate) {callbacks.animateHits_manymeshes()};
}
}
if ( typeof animate.tthen == 'undefined' ) animate.tthen = tnow;
var dt = animate.tthen-tnow;
animate.tthen = tnow;
callbacks.vr_demo( tnow )
if ( pars.rotate )
{
var ax = new THREE.Vector3( 0, 1, 0 );
camera.position.applyAxisAngle( ax , 0.00001* pars.rotationSpeed * dt );
}
controls.update();
stats.update();
render();
}
`
render = ->
#console.log(render)
render.n ?= 0
render.n+=1
THREE.VRController.update()
#if pars.depthSortEvery > 0 and render.n % pars.depthSortEvery == 0 then callbacks.depthSort()
if effect
effect.render( scene, camera )
else
renderer.render( scene, camera )
newwindow = -> window.new_window_ref = window.open( window.location )
container = document.createElement( 'container' );
container.id = "container";
document.body.appendChild( container );
initdiv = document.createElement( 'div' );
initdiv.id = 'init';
initdiv.innerHTML = '<br>aa3d starting up.</br>';
document.body.appendChild( initdiv );
unzip = ( buf ) ->
words = new Uint8Array( buf )
U = pako.ungzip(words)
console.log(U)
result = "";
for i in [0..U.length-1]
result+= String.fromCharCode(U[i]) ;
return result
# old browsers dont have str.endsWidth
str_endsWith = (s, suffix) ->
s.indexOf(suffix, s.length - suffix.length) != -1;
antares_mode = ->
console.log("antares mode")
pars.set( "domFragmentShader", "fragmentshader_antares_glsl")
pars.set( "camHeight" , 200 )
pars.set( "camDistance", 250 )
pars.set( "domSize", 2.0 )
pars.set( "domFactor", 3 )
pars.set( "hitStyle", "sphere" )
pars.set( "ampFunc", "Math.sqrt(hit.a)" )
pars.set( "palette", "hue" )
pars.set( "hitLength", 1.5 )
pars.set( "depthSortEvery", 0 )
loadFile = ( url , asynch = true , when_done ) ->
console.log( url, when_done, asynch )
gz = str_endsWith( url, ".gz" )
xmlhttp = new XMLHttpRequest()
if gz then xmlhttp.responseType = 'arraybuffer';
process = ( req ) ->
if gz
s = unzip( xmlhttp.response )
eval( s )
else
eval( xmlhttp.responseText )
when_done?()
if asynch
xmlhttp.onprogress = (ev) -> console.log( 'getting file:'+url+' __ '+ ev.loaded/1e6 +' MB')
xmlhttp.onreadystatechange = () ->
return unless xmlhttp.readyState == 4
return unless xmlhttp.status == 200
console.log("done");
process( xmlhttp )
xmlhttp.open("GET", url , asynch );
xmlhttp.send();
if not asynch then process( xmlhttp )
many_screenshots = ( i=0 ) ->
s = """
diffuse2017/detevt_28722_45202_426
diffuse2017/detevt_35473_7183_1050
diffuse2017/detevt_38472_61820_16446
diffuse2017/detevt_38518_41252_24091
diffuse2017/detevt_38519_42310_26116
diffuse2017/detevt_39324_118871_32515
diffuse2017/detevt_45265_79259_997305
diffuse2017/detevt_45835_34256_1041663
diffuse2017/detevt_46852_51708_917709
diffuse2017/detevt_47833_1124_537259
diffuse2017/detevt_49425_32175_104853
diffuse2017/detevt_49821_56923_25516
diffuse2017/detevt_49853_25438_1385
diffuse2017/detevt_53037_101247_36731
diffuse2017/detevt_53060_41698_354601
diffuse2017/detevt_54260_1639_2925759
diffuse2017/detevt_57495_15712_326824
diffuse2017/detevt_60896_68105_494258
diffuse2017/detevt_60907_60252_572415
diffuse2017/detevt_61023_10375_2179659
diffuse2017/detevt_62657_88204_22071
diffuse2017/detevt_62834_30474_384475
diffuse2017/detevt_65811_20990_137527
diffuse2017/detevt_68473_32777_22562
diffuse2017/detevt_68883_33383_1459227
diffuse2017/detevt_70787_9986_323373
diffuse2017/detevt_71534_74641_364543
diffuse2017/detevt_74307_193564_6908522
diffuse2017/detevt_77640_77424_3612
diffuse2017/detevt_80885_49449_12484201
diffuse2017/detevt_81667_163768_2732223
diffuse2017/detevt_82539_9289_2425758
diffuse2017/detevt_82676_118860_167410
""".split("\n")
for fn in s
if not fn then continue
scfile = fn.split("/").pop()
loadFile( fn , false, ->
callbacks.onNewEvent()
#init()
callbacks.onNewDetector()
render()
callbacks.write_screenshot(scfile) )
if window.opener then console.log("we have an opener", window.opener );
`
window.addEventListener( 'vr controller connected', function( event ){
console.log("VR CONTROLLER!!!!!!!!!!!!!!!!!!!!!!!!!");
// Here it is, your VR controller instance.
// It’s really a THREE.Object3D so you can just add it to your scene:
controller = event.detail
train.add( controller )
// HEY HEY HEY! This is important. You need to make sure you do this.
// For standing experiences (not seated) we need to set the standingMatrix
// otherwise you’ll wonder why your controller appears on the floor
// instead of in your hands! And for seated experiences this will have no
// effect, so safe to do either way:
controller.standingMatrix = renderer.vr.getStandingMatrix()
// And for 3DOF (seated) controllers you need to set the controller.head
// to reference your camera. That way we can make an educated guess where
// your hand ought to appear based on the camera’s rotation.
controller.head = window.camera
// Right now your controller has no visual.
// It’s just an empty THREE.Object3D.
// Let’s fix that!
var
meshColorOff = 0xFF4040,
meshColorOn = 0xFFFF00,
controllerMaterial = new THREE.MeshStandardMaterial({
color: meshColorOff,
shading: THREE.FlatShading
}),
controllerMesh = new THREE.Mesh(
new THREE.CylinderGeometry( 0.005, 0.05, 0.1, 6 ),
controllerMaterial
),
handleMesh = new THREE.Mesh(
new THREE.BoxGeometry( 0.03, 0.1, 0.03 ),
controllerMaterial
)
//controllerMesh.scale.set(100,100,100);
controllerMesh.rotation.x = -Math.PI / 2;
handleMesh.position.y = -0.05;
controllerMesh.add( handleMesh );
controller.userData.mesh = controllerMesh;// So we can change the color later.
controller.add( controllerMesh );
// Allow this controller to interact with DAT GUI.
//var guiInputHelper = dat.GUIVR.addInputObject( controller )
//scene.add( guiInputHelper )
// Button events. How easy is this?!
// We’ll just use the “primary” button -- whatever that might be ;)
// Check out the THREE.VRController.supported{} object to see
// all the named buttons we’ve already mapped for you!
controller.addEventListener( 'primary press began', function( event ){
train.position.add( controller.rotation );
event.target.userData.mesh.material.color.setHex( meshColorOn )
//guiInputHelper.pressed( true )
})
controller.addEventListener( 'primary press ended', function( event ){
event.target.userData.mesh.material.color.setHex( meshColorOff )
//guiInputHelper.pressed( false )
})
// <NAME> <NAME>, what happens when we die?
controller.addEventListener( 'disconnected', function( event ){
controller.parent.remove( controller )
})
})
`
url = getUrlPar('f');
if url == "none"
init();
render();
animate();
if !url then url="detevt2_km3.js" #some test file
initdiv.innerHTML = '<br>getting file:'+url+'</br>'
console.log( 'get',url )
loadFile( url, true, ->
callbacks.onNewEvent()
init()
callbacks.onNewDetector()
render()
animate()
)
| true |
# this is the aa3d event display for antares and km3net
# object that will hold all the user-modifiable parameters (and then some)
pars = {}
defpars = {}
# physics-domain data
clight = 0.299792458 # m/ns
evt = {"hits": [], "trks":[]};
det = {"doms": [{"id": 1, "dir": {"y":0, "x": 0, "z": 0}, "pos": {"y": 0, "x": 0, "z": 0} }] };
# three.js objects
scene= camera= renderer= raycaster= mouseVector= controls = null;
geometry= material= mesh= null
container= stats= gui = null
containerWidth= containerHeight= null
eventtime = 0.0;
light= null
gui = null
effect = null
train = null
selectedHit = null
ii = null#
dus = 42
callbacks = {}
selected = null
dbg_cam = false
evil = ( code ) -> eval ( code ) # eval's evil brother (to access scope)
#-----------------------------------------
# Simple Vector functions and math utils
#-----------------------------------------
isvec = ( obj ) -> typeof(obj) == 'object' and 'x' of obj and 'y' of obj and 'z' of obj
vadd = ( v1, v2 ) -> { x : v1.x + v2.x, y: v1.y + v2.y , z: v1.z + v2. z }
vsub = ( v1, v2 ) -> { x : v1.x - v2.x, y: v1.y - v2.y , z: v1.z - v2. z }
vmul = ( v1, a ) ->
if typeof v1 == 'number' then return vmul( a, v1 )
return { x: v1.x * a, y: v1.y * a, z : v1.z * a }
vlen = ( v1, v2 = {x:0,y:0,z:0} ) ->
Math.sqrt( (v1.x-v2.x)*(v1.x-v2.x) + (v1.y-v2.y)*(v1.y-v2.y) + (v1.z-v2.z)*(v1.z-v2.z) )
tovec = (obj) ->
new THREE.Vector3 obj.y, obj.z, obj.x
clamp = ( x, min=0, max=1 ) ->
if x <= min then return min
if x >= max then return max
return x
getUrlPar = (name, url ) ->
url ?= window.location.href
name = name.replace(/[\[\]]/g, "\\$&")
regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
results = regex.exec(url);
if !results then return null
if !results[2] then return ''
return decodeURIComponent(results[2].replace(/\+/g, " "));
getCylinderMesh = ( startpoint, endpoint, width , material , width2 ) ->
l = vlen( endpoint, startpoint )
width2 ?= width
geom = new THREE.CylinderGeometry( width, width2 , l );
geom.translate(0, l/2 ,0);
geom.rotateX( Math.PI / 2 );
mesh = new THREE.Mesh( geom , material.clone() );
mesh.position.set( startpoint.y, startpoint.z, startpoint.x );
mesh.lookAt( tovec(endpoint) );
return mesh;
getConeMesh = ( startpoint, endpoint, width, material ) ->
getCylinderMesh( startpoint, endpoint, width, material, 0 )
callbacks.setBackgroundColor = ->
scene.background = new THREE.Color( pars.bgColor )
callbacks.screenshot = ->
dt = renderer.domElement.toDataURL( 'image/png' );
window.open( dt, 'screenshot')
callbacks.screenshot360 = ->
console.log("screenshot360")
X = new CubemapToEquirectangular( renderer, true );
X.update( camera, scene )
callbacks.write_screenshot = (fn) ->
url = "uploadimg.php"
params = "fn="+fn+".png&payload="+renderer.domElement.toDataURL( 'image/png' );
console.log(params)
http = new XMLHttpRequest()
http.open("POST", url , false )
#Send the proper header information along with the request
http.send( params )
if http.readyState == 4 && http.status == 200 then console.log(http.responseText)
else console.log('error sending screenshot')
callbacks.addCamera =->
camera ?= new THREE.PerspectiveCamera( 75,window.innerWidth / window.innerHeight, 0.01, 10000 );
camera.position.x = 0
camera.position.y = pars.camHeight
camera.position.z = pars.camDistance
callbacks.addOrbitControls =->
controls = new THREE.OrbitControls( camera , renderer.domElement )
cg = det.cg or {x:0, y:0, z:0} # det may not exist yet
controls.center = new THREE.Vector3(cg.z, cg.y, cg.x) or new THREE.Vector3( camera.position.x, camera.position.y, 0.0 )
controls.update()
controls.addEventListener( 'change', render )
return controls
getSceneObj = ( name ) ->
while obj = scene.getObjectByName( name )
scene.remove( obj )
obj = new THREE.Object3D()
obj.name = name
scene.add( obj )
return obj
isNeutrino = (track) -> Math.abs( track.type ) in [12,14,16]
isLepton = (track) -> Math.abs( track.type ) in [11,13,15]
isMuon = (track) -> Math.abs( track.type ) == 13
trackColor = ( track ) ->
if track.type == 0
return new THREE.Color( pars.trackColor )
if isNeutrino( track )
return new THREE.Color( pars.neuColor )
if isMuon( track)
return new THREE.Color( pars.muColor )
return new THREE.Color( pars.mcTrackColor )
trackLength = ( track ) ->
#if isNeutrino( track ) then return pars.neuLen
if isMuon(track)
if track.len? != 0 then return Math.abs(track.len)
if track.E?
l = track.E * 5
if l<20 then l = 20;
if l>4000 then l = 4000;
return l
if track.len > 0 then return track.len
return pars.trackLen
addDoms_mergedgeomery = ->
return unless pars.showDoms
doms = getSceneObj( "doms" )
geo = new THREE.SphereGeometry( pars.domSize,2*pars.domDetail, pars.domDetail )
mat = new THREE.MeshLambertMaterial( { color: new THREE.Color( pars.domColor )} )
mesh = new THREE.Mesh( geo );
mergedGeo = new THREE.Geometry();
for id, dom of det.doms
if dom.dir? then d = vmul( pars.domFactor, dom.dir)
else d = {x:0,y:0,z:1}
mesh.position.set( dom.pos.y + d.y, dom.pos.z + d.z, dom.pos.x + d.x);
mesh.updateMatrix()
mergedGeo.merge( mesh.geometry, mesh.matrix )
group = new THREE.Mesh( mergedGeo, mat );
doms.add(group)
addDoms_shader = ->
return unless pars.showDoms
doms = getSceneObj( "doms" )
geo = new THREE.InstancedBufferGeometry()
sphere = new THREE.SphereGeometry( pars.domSize,2*pars.domDetail, pars.domDetail )
sphere.rotateX( Math.PI )
geo.fromGeometry( sphere )
ndoms = 0
ndoms++ for id, dom of det.doms
offsets = new THREE.InstancedBufferAttribute( new Float32Array( ndoms * 3 ), 3, 1 );
orientations = new THREE.InstancedBufferAttribute( new Float32Array( ndoms * 3 ), 3, 1 )
i= 0
for id, dom of det.doms
if not dom.dir? or dom.dir.z > 0 # for antares it will be <0
dom.dir = {x:0,y:0,z:1}
d = {x:0,y:0,z:0}
else # for antares
d = vmul( pars.domFactor, dom.dir)
offsets.setXYZ( i, dom.pos.y + d.y , dom.pos.z + d.z , dom.pos.x + d.x )
orientations.setXYZ( i, dom.dir.y, dom.dir.z, dom.dir.x )
#console.log( dom.pos, dom.dir )
i+=1
geo.addAttribute( 'offset', offsets ); # per mesh translation (i.e. dom-position)
geo.addAttribute( 'orientation', orientations );
uniforms_ = THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "ambient" ],
THREE.UniformsLib[ "lights" ] ] );
material = new THREE.RawShaderMaterial
uniforms : uniforms_
vertexShader : vertexshader_glsl
fragmentShader : window[pars.domFragmentShader]
side : THREE.DoubleSide
lights : true
transparent : false
group = new THREE.Mesh( geo, material );
group.frustumCulled = false;
doms.add( group );
callbacks.addDoms = addDoms_shader
callbacks.addFloor = ->
floor = getSceneObj("floor")
det.floor_z = det.floor_z or Math.min( dom.pos.z for id,dom of det.doms... )-100
console.log( "addFloor" , det.floor_z);
texture = new THREE.TextureLoader().load( 'textures/image.png' );
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 100, 100 );
geo = new THREE.PlaneGeometry(20000,20000,1,1);
mat = new THREE.MeshBasicMaterial( {
color: pars.floorColor,
side: THREE.DoubleSide,
opacity : pars.floorOpacity,
transparent: false,
map: texture
} )
mesh = new THREE.Mesh( geo, mat );
mesh.rotation.x = 0.5*Math.PI;
mesh.position.y = det.floor_z;
floor.add( mesh );
callbacks.addStrings = ->
return unless pars.showStrings
return unless det.strings
strings = getSceneObj( "strings" )
mat = new THREE.MeshLambertMaterial ( color: new THREE.Color( pars.stringColor ) )
endpos = null
for stringpos in det.strings
startpos = tovec( stringpos )
if endpos
mesh = getCylinderMesh( startpos, endpos , pars.stringWidth, mat );
strings.add(mesh)
endpos = startpos
timeParameter= ( hit, track ) ->
switch pars.colScheme
when 'time' then hit.t
when 'track' then hit.t - time_track( track, hit.pos )
when 'shower' then hit.t - time_shower( track, hit.pos )
getHitColor = ( time , timerange, track ) ->
[mint, maxt] = timerange
aa = ( time - mint) / ( maxt - mint );
col = new THREE.Color()
if pars.palette == 'hue'
col.setHSL( aa , 1.0, 0.5 );
if pars.palette == 'doppler'
col.setRGB( 1-clamp( aa*aa ) , 0 , clamp( aa*2-1 ) )
return col
addHits_manymeshes = ->
hits = getSceneObj( "hits" )
hitarray = evt[ pars.hitSet ]
if !hitarray then return
if pars.hitStyle == 'sphere'
geo = new THREE.SphereGeometry( 2, 2*pars.hitDetail, pars.hitDetail )
if pars.hitStyle == 'disk'
geo = new THREE.CylinderGeometry( 2, 2 , 0.1 , pars.hitDetail , 1 ) # z-component will be scaled later
geo.translate(0, 0.05 ,0)
geo.rotateX( Math.PI / 2 )
have_direction = true
# min/max time for collormapping
evt.timerange = evt.timerange || [ Math.min( hit.t for hit in hitarray... ), Math.max( hit.t for hit in hitarray... ) ]
eval ('ampfun = function(hit) { return '+pars.ampFunc+';};')
for hit in hitarray
if pars.animate and hit.t > eventtime then continue
col = getHitColor( hit.t , evt.timerange )
mat = new THREE.MeshLambertMaterial( color: col );
mesh = new THREE.Mesh( geo , mat );
mesh.t = hit.t
d = hit.dir || {x:0,y:0,z:0}
a = pars.domFactor
mesh.position.set(
hit.pos.y + a * d.y
hit.pos.z + a * d.z
hit.pos.x + a * d.x )
a *= 2
if have_direction then mesh.lookAt( new THREE.Vector3(
hit.pos.y + a * d.y
hit.pos.z + a * d.z
hit.pos.x + a * d.x ) )
amp = ampfun( hit ) * pars.hitLength
mesh.scale.set( amp, amp, amp) if pars.hitStyle == 'sphere'
mesh.scale.set( 1,1,amp ) if pars.hitStyle == 'disk'
hits.add( mesh )
callbacks.animateHits_manymeshes = ->
#console.log( eventtime )
hits = scene.getObjectByName( "hits" ).children
for mesh in hits
mesh.visible = mesh.t > eventtime and mesh.t < (eventtime+200)
distFromCamera = ( pos ) ->
x = pos.y - camera.position.x
y = pos.z - camera.position.y
z = pos.x - camera.position.z
r = (x*x + y*y + z*z)
return r
# tovec( obj.pos).project( camera ).z
#----------------------------------------------------------
populateHitInstanceBuffers = ->
window.alert("populateHitInstanceBuffers cannot be called before addHits_shader");
make_hitcol = ( hitlist ) ->
X = {}
( X[ hit.dom_id ] ?= [] ).push( hit ) for hit in hitlist
hitcol = (v for k,v of X)
hitcol.doms_are_sorted = (verbose ) ->
olddepth = 1e10
r = true
for hitsondom in this
h = hitsondom[0]
h.depth = distFromCamera( h.pos )
if verbose then console.log( h.depth )
if h.depth > olddepth then r = false
olddepth = h.depth
return r
hitcol.dbg = ->
for lst,i in this
console.log( i, lst[0].depth )
if i > 10 then break
hitcol.sort_doms = ->
this.sort( (lst1, lst2) -> lst1[0].depth < lst2[0].depth )
hitcol.sort_within_doms = ->
for lst in this
h.depth = distFromCamera( h.pos ) for h in lst
lst.sort( (h1,h2) -> h1.depth < h2.depth )
hitcol.sort_all = ->
unless this.doms_are_sorted()
this.sort_doms()
this.sort_within_doms()
populateHitInstanceBuffers()
return hitcol
callbacks.depthSort = ->
t0 = (new Date()).getTime()
evt.sorted_hits.sort_all()
t1 = (new Date()).getTime()
console.log("depthSort took", t1-t0 )
callbacks.onNewEvent = ->
evt.tag = "evt"
evt.sorted_hits = make_hitcol( evt.hits )
evt.sorted_mc_hits = make_hitcol( evt.mc_hits )
for trk in evt.mc_trks
if isNeutrino( trk )
# move neutrino back 10 km
vv = vmul( 10000.0 , trk.dir )
trk.pos = vsub( trk.pos , vv )
trk.len = 10000
trk.t = trk.t - trk.len / clight
if scene?
callbacks.addHits()
callbacks.addTracks()
callbacks.onNewDetector = ->
console.log 'onNewDetector'
if det.name == "antares" then antares_mode()
det.tag = "det"
det.cg = {x:0,y:0,z:0}
det.ndoms = 0
for id, dom of det.doms
det.ndoms += 1
det.cg = vadd( det.cg, dom.pos )
addHits_shader = ->
hits = getSceneObj( "hits" )
hitarray = evt[ pars.hitSet ]
if !hitarray then return
console.log('addHits', hitarray.length );
evt.timerange = [ Math.min( hit.t for hit in hitarray... ), Math.max( hit.t for hit in hitarray... ) ]
geo = new THREE.InstancedBufferGeometry()
disk = new THREE.CylinderGeometry( pars.hitWidth,
3*pars.hitWidth , 0.1 , pars.hitDetail , 1 ) # z-component will be scaled later
disk.translate(0, -0.05 ,0)
disk.rotateZ( Math.PI / 2 )
geo.fromGeometry( disk )
nhits = hitarray.length
offsets = new THREE.InstancedBufferAttribute( new Float32Array( nhits * 3 ), 3, 1 ).setDynamic( true );
orientations = new THREE.InstancedBufferAttribute( new Float32Array( nhits * 3 ), 3, 1 ).setDynamic( true );
colors = new THREE.InstancedBufferAttribute( new Float32Array( nhits * 3 ), 3, 1 ).setDynamic( true );
amplitudes = new THREE.InstancedBufferAttribute( new Float32Array( nhits ), 1, 1 ).setDynamic( true );
times = new THREE.InstancedBufferAttribute( new Float32Array( nhits ), 1, 1 ).setDynamic( true );
tots = new THREE.InstancedBufferAttribute( new Float32Array( nhits ), 1, 1 ).setDynamic( true );
geo.addAttribute( 'offset', offsets );
geo.addAttribute( 'orientation', orientations );
geo.addAttribute( 'color', colors );
geo.addAttribute( 'amplitude', amplitudes );
geo.addAttribute( 'time', times );
geo.addAttribute( 'tot', tots );
a = pars.domFactor
populateHitInstanceBuffers = ->
eval ('ampfun = function(hit) { return '+pars.ampFunc+';};')
t1 = (new Date()).getTime()
i = 0
for domhits in evt.sorted_hits
for hit in domhits
col = getHitColor( hit.t , evt.timerange )
d = hit.dir || {x:0,y:0,z:1}
offsets.setXYZ( i, hit.pos.y + a * d.y, hit.pos.z + a * d.z, hit.pos.x + a * d.x )
orientations.setXYZ( i, hit.dir.y, hit.dir.z, hit.dir.x ); # todo and to think-about
colors.setXYZ(i, col.r, col.g, col.b )
amplitudes.setX(i, ampfun(hit)* pars.hitLength );
times.setX(i, hit.t );
tots.setX(i, hit.tot * pars['aniTotFactor']);
i+=1
t2 = (new Date()).getTime()
offsets.needsUpdate = true
orientations.needsUpdate = true
colors.needsUpdate = true
amplitudes.needsUpdate = true
times.needsUpdate = true
tots.needsUpdate = true
# console.log("polulating buffers took", t2-t1 )
populateHitInstanceBuffers()
material = new THREE.RawShaderMaterial( {
uniforms: { "eventtime": { type: "1f", value: 0 }
},
vertexShader : hit_vertexshader_glsl,
fragmentShader : hit_fragmentshader_glsl,
side : THREE.BackSide ,
transparent : true } );
mesh = new THREE.Mesh( geo, material );
mesh.frustumCulled = false;
hits.add( mesh );
callbacks['addHits'] = ->
if pars.hitStyle == 'cone' then addHits_shader()
else addHits_manymeshes()
callbacks.addTracks = ->
trks = getSceneObj 'trks'
if typeof t == 'undefined' then t = 1e10
trkcol = evt[pars.tracks] or []
for trk in trkcol
trklen = trackLength( trk )
startpos = trk.pos
endpos = vadd( trk.pos, vmul( trk.dir, trklen ) )
startt = trk.t
if isNeutrino( trk )
startpos = vadd( trk.pos, vmul( trk.dir, -trklen ) );
endpos = trk.pos
startt -= trklen / clight
mat = new THREE.MeshPhongMaterial ( {
emissive: new THREE.Color( trackColor(trk) ),
transparent: false ,
opacity: 0.5 } )
mesh = getCylinderMesh( startpos, endpos, pars.trackWidth, mat )
mesh.t0 = startt
mesh.t1 = startt + trklen / clight;
console.log("track", startpos, endpos , trklen )
trks.add (mesh)
callbacks.animateTracks = ( t ) ->
trks = scene.getObjectByName( 'trks' )
for mesh in trks.children
f = clamp ( (t - mesh.t0 ) / ( mesh.t1 - mesh.t0 ) )
mesh.scale.set( 1,1,f )
#console.log('anim trka', mesh.t0, mesh.t1, t , f)
callbacks.addEvt = ->
callbacks.addHits()
callbacks.addTracks()
callbacks.addDet = ->
callbacks.addFloor()
callbacks.addStrings()
callbacks.addDoms()
handlefile= ( e ) -> console.log( "filetje:", e.target.files )
callbacks.loadLocalFile = ->
element = document.createElement('div')
element.innerHTML = '<input type="file">'
fileInput = element.firstChild
fileInput.addEventListener('change', handlefile )
fileInput.click()
# At this point, all callbacks are defined and we
# can initialze the dat.gui. Note that the callbacks
# use the parameters defined in pars by buildmenu.
gui = window.buildmenu( pars , callbacks )
callbacks.vr_demo = (tnow) ->
window[pars.demo]?( tnow )
vr_demo1 = (tnow) ->
train.position.y = 500 + 400 * Math.sin( tnow/10000.0 )
addVRButton = ->
WEBVR.getVRDisplay( (display) ->
if not display?
console.log("no vr display found")
return
renderer.vr.setDevice( display )
gui.add( { "VR_mode" : ->
console.log("toggling vr mode!");
controls = new THREE.VRControls( camera );
effect = new THREE.VREffect( renderer );
if display.isPresenting then display.exitPresent() # crashes
else : display.requestPresent( [ { source: renderer.domElement } ] );
#callbacks.vr_demo = vr_demo1
} , "VR_mode" )
)
init = ->
t1 = (new Date()).getTime();
scene = new THREE.Scene()
console.log("bg col = ", pars.bgColor)
renderer = new THREE.WebGLRenderer
preserveDrawingBuffer : true
antialias : true
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight )
container.appendChild( renderer.domElement )
# --stats box-
stats = new Stats()
container.appendChild( stats.dom );
window.addEventListener( 'resize', onWindowResize, false );
light = new THREE.PointLight(0xffffff)
light.position.set(500,1000,0)
scene.add(light)
al = new THREE.AmbientLight(0x444444);
scene.add(al);
pars[attrname] = defpars[attrname] for attrname of defpars
console.log('call addcontrols', renderer)
callbacks.setBackgroundColor()
callbacks.addCamera()
callbacks.addStrings()
callbacks.addDoms()
callbacks.addTracks()
callbacks.addHits()
callbacks.addFloor()
callbacks.addOrbitControls()
# If we are not in VR mode, then the 'train' does not do anything
# otherwise it defines a sort of platform for the 'player' to stand on
train = new THREE.Object3D()
train.position.set( 0,0,0)
scene.add( train );
train.add( camera )
addVRButton();
raycaster = new THREE.Raycaster();
mouseVector = new THREE.Vector2();
showSelectionInfo( evt );
t2 = (new Date()).getTime();
console.log("init took (ms) : ", t2-t1 );
websock = new WebSocket("ws://www.cherenkov.nl:8181", "protocolOne");
websock.onmessage = (event) ->
console.oldlog("get wesocket message:", event.data);
s = eval( event.data )
console.log( JSON.stringify(s) )
websock.onopen = () -> # replace console.log
console.oldlog = console.log
console.log = () ->
a = Array.prototype.slice.call(arguments)
console.oldlog( arguments )
websock.send( a.toString() )
showSelectionInfo = ->
selected ?= evt
infodiv = document.getElementById("info")
if not infodiv
infodiv = document.createElement 'div'
infodiv.id = 'info'
infodiv.big = false
infodiv.addEventListener "click", ->
console.log 'click'
infodiv.big = !infodiv.big
showSelectionInfo()
document.body.appendChild infodiv
M = {'trk':'Track', 'hit':'Hit', 'evt':'Event'}
html = """ <h3> #{M[selected.tag]} #{selected.id} </h3> <table style="width:100%"><tr> """
if infodiv.big # list all attributes of 'selected' object
for key, val of selected
if Array.isArray(val) then val = val.length.toString() + "entries"
if isvec( val ) then val = val.x.toFixed(3) +', ' + val.y.toFixed(3) + ', ' + val.z.toFixed(3);
html += '<tr><td> '+key+' </td><td> '+val+'</td></tr>'
html += '</table>'
infodiv.innerHTML = html
`
function onMouseMove( e )
{
console.log ("mousemove")
mouseVector.x = 2 * (e.clientX / window.innerWidth ) - 1;
mouseVector.y = 1 - 2 * ( e.clientY / window.innerHeight );
raycaster.setFromCamera( mouseVector, camera );
var searchObjects = ["hits","trks"];
flag = false;
if ( selectedHit)
{
selectedHit.material.emissive.setHex( selectedHit.oldHex);
}
for ( var ii = 0; ii<searchObjects.length; ii++ )
{
var collection = scene.getObjectByName( searchObjects[ii] );
console.log( collection );
var intersects = raycaster.intersectObjects( collection.children );
console.log("intersects", intersects );
if ( intersects.length > 0 )
{
var sel = intersects[ 0 ].object;
if ( sel.hasOwnProperty("aaobj") )
{
selectedHit = sel;
sel.oldHex = sel.material.emissive.getHex();
sel.material.emissive.setHex( 0xff0000 );
sel.aaobj.tag = searchObjects[ii].substring(0,3);
showSelectionInfo( sel.aaobj );
flag = true;
}
}
}
evt.tag = "evt";
if (!flag) showSelectionInfo( evt );
}
function onWindowResize()
{
//windowHalfX = window.innerWidth / 2;
//windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
//
if (effect)
{
setSize( window.innerWidth, window.innerHeight );
}
else
{
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}
//render();
}
function animate()
{
// schedule next one
if (effect)
{
effect.requestAnimationFrame( animate );
}
else
{
requestAnimationFrame( animate );
}
var tnow = (new Date()).getTime();
if (!pars.animate)
{
scene.getObjectByName( 'hits' ).children[0].material.uniforms.eventtime.value = eventtime;
eventtime = 2e100;
}
else
{
// --- animation time ---
var slowdown = pars.ns_per_s /1000.0 ;
var tx = tnow * slowdown;
var t1 = evt.timerange[0] - pars.introTime;
var t2 = evt.timerange[1] + 255.0 * pars.aniTotFactor + pars.outroTime
eventtime = ( tx % (t2-t1)) + t1 ;
callbacks.animateTracks( eventtime );
if (pars.hitStyle == 'cone')
{
scene.getObjectByName( 'hits' ).children[0].material.uniforms.eventtime.value = eventtime;
}
else
{
if (pars.animate) {callbacks.animateHits_manymeshes()};
}
}
if ( typeof animate.tthen == 'undefined' ) animate.tthen = tnow;
var dt = animate.tthen-tnow;
animate.tthen = tnow;
callbacks.vr_demo( tnow )
if ( pars.rotate )
{
var ax = new THREE.Vector3( 0, 1, 0 );
camera.position.applyAxisAngle( ax , 0.00001* pars.rotationSpeed * dt );
}
controls.update();
stats.update();
render();
}
`
render = ->
#console.log(render)
render.n ?= 0
render.n+=1
THREE.VRController.update()
#if pars.depthSortEvery > 0 and render.n % pars.depthSortEvery == 0 then callbacks.depthSort()
if effect
effect.render( scene, camera )
else
renderer.render( scene, camera )
newwindow = -> window.new_window_ref = window.open( window.location )
container = document.createElement( 'container' );
container.id = "container";
document.body.appendChild( container );
initdiv = document.createElement( 'div' );
initdiv.id = 'init';
initdiv.innerHTML = '<br>aa3d starting up.</br>';
document.body.appendChild( initdiv );
unzip = ( buf ) ->
words = new Uint8Array( buf )
U = pako.ungzip(words)
console.log(U)
result = "";
for i in [0..U.length-1]
result+= String.fromCharCode(U[i]) ;
return result
# old browsers dont have str.endsWidth
str_endsWith = (s, suffix) ->
s.indexOf(suffix, s.length - suffix.length) != -1;
antares_mode = ->
console.log("antares mode")
pars.set( "domFragmentShader", "fragmentshader_antares_glsl")
pars.set( "camHeight" , 200 )
pars.set( "camDistance", 250 )
pars.set( "domSize", 2.0 )
pars.set( "domFactor", 3 )
pars.set( "hitStyle", "sphere" )
pars.set( "ampFunc", "Math.sqrt(hit.a)" )
pars.set( "palette", "hue" )
pars.set( "hitLength", 1.5 )
pars.set( "depthSortEvery", 0 )
loadFile = ( url , asynch = true , when_done ) ->
console.log( url, when_done, asynch )
gz = str_endsWith( url, ".gz" )
xmlhttp = new XMLHttpRequest()
if gz then xmlhttp.responseType = 'arraybuffer';
process = ( req ) ->
if gz
s = unzip( xmlhttp.response )
eval( s )
else
eval( xmlhttp.responseText )
when_done?()
if asynch
xmlhttp.onprogress = (ev) -> console.log( 'getting file:'+url+' __ '+ ev.loaded/1e6 +' MB')
xmlhttp.onreadystatechange = () ->
return unless xmlhttp.readyState == 4
return unless xmlhttp.status == 200
console.log("done");
process( xmlhttp )
xmlhttp.open("GET", url , asynch );
xmlhttp.send();
if not asynch then process( xmlhttp )
many_screenshots = ( i=0 ) ->
s = """
diffuse2017/detevt_28722_45202_426
diffuse2017/detevt_35473_7183_1050
diffuse2017/detevt_38472_61820_16446
diffuse2017/detevt_38518_41252_24091
diffuse2017/detevt_38519_42310_26116
diffuse2017/detevt_39324_118871_32515
diffuse2017/detevt_45265_79259_997305
diffuse2017/detevt_45835_34256_1041663
diffuse2017/detevt_46852_51708_917709
diffuse2017/detevt_47833_1124_537259
diffuse2017/detevt_49425_32175_104853
diffuse2017/detevt_49821_56923_25516
diffuse2017/detevt_49853_25438_1385
diffuse2017/detevt_53037_101247_36731
diffuse2017/detevt_53060_41698_354601
diffuse2017/detevt_54260_1639_2925759
diffuse2017/detevt_57495_15712_326824
diffuse2017/detevt_60896_68105_494258
diffuse2017/detevt_60907_60252_572415
diffuse2017/detevt_61023_10375_2179659
diffuse2017/detevt_62657_88204_22071
diffuse2017/detevt_62834_30474_384475
diffuse2017/detevt_65811_20990_137527
diffuse2017/detevt_68473_32777_22562
diffuse2017/detevt_68883_33383_1459227
diffuse2017/detevt_70787_9986_323373
diffuse2017/detevt_71534_74641_364543
diffuse2017/detevt_74307_193564_6908522
diffuse2017/detevt_77640_77424_3612
diffuse2017/detevt_80885_49449_12484201
diffuse2017/detevt_81667_163768_2732223
diffuse2017/detevt_82539_9289_2425758
diffuse2017/detevt_82676_118860_167410
""".split("\n")
for fn in s
if not fn then continue
scfile = fn.split("/").pop()
loadFile( fn , false, ->
callbacks.onNewEvent()
#init()
callbacks.onNewDetector()
render()
callbacks.write_screenshot(scfile) )
if window.opener then console.log("we have an opener", window.opener );
`
window.addEventListener( 'vr controller connected', function( event ){
console.log("VR CONTROLLER!!!!!!!!!!!!!!!!!!!!!!!!!");
// Here it is, your VR controller instance.
// It’s really a THREE.Object3D so you can just add it to your scene:
controller = event.detail
train.add( controller )
// HEY HEY HEY! This is important. You need to make sure you do this.
// For standing experiences (not seated) we need to set the standingMatrix
// otherwise you’ll wonder why your controller appears on the floor
// instead of in your hands! And for seated experiences this will have no
// effect, so safe to do either way:
controller.standingMatrix = renderer.vr.getStandingMatrix()
// And for 3DOF (seated) controllers you need to set the controller.head
// to reference your camera. That way we can make an educated guess where
// your hand ought to appear based on the camera’s rotation.
controller.head = window.camera
// Right now your controller has no visual.
// It’s just an empty THREE.Object3D.
// Let’s fix that!
var
meshColorOff = 0xFF4040,
meshColorOn = 0xFFFF00,
controllerMaterial = new THREE.MeshStandardMaterial({
color: meshColorOff,
shading: THREE.FlatShading
}),
controllerMesh = new THREE.Mesh(
new THREE.CylinderGeometry( 0.005, 0.05, 0.1, 6 ),
controllerMaterial
),
handleMesh = new THREE.Mesh(
new THREE.BoxGeometry( 0.03, 0.1, 0.03 ),
controllerMaterial
)
//controllerMesh.scale.set(100,100,100);
controllerMesh.rotation.x = -Math.PI / 2;
handleMesh.position.y = -0.05;
controllerMesh.add( handleMesh );
controller.userData.mesh = controllerMesh;// So we can change the color later.
controller.add( controllerMesh );
// Allow this controller to interact with DAT GUI.
//var guiInputHelper = dat.GUIVR.addInputObject( controller )
//scene.add( guiInputHelper )
// Button events. How easy is this?!
// We’ll just use the “primary” button -- whatever that might be ;)
// Check out the THREE.VRController.supported{} object to see
// all the named buttons we’ve already mapped for you!
controller.addEventListener( 'primary press began', function( event ){
train.position.add( controller.rotation );
event.target.userData.mesh.material.color.setHex( meshColorOn )
//guiInputHelper.pressed( true )
})
controller.addEventListener( 'primary press ended', function( event ){
event.target.userData.mesh.material.color.setHex( meshColorOff )
//guiInputHelper.pressed( false )
})
// PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI, what happens when we die?
controller.addEventListener( 'disconnected', function( event ){
controller.parent.remove( controller )
})
})
`
url = getUrlPar('f');
if url == "none"
init();
render();
animate();
if !url then url="detevt2_km3.js" #some test file
initdiv.innerHTML = '<br>getting file:'+url+'</br>'
console.log( 'get',url )
loadFile( url, true, ->
callbacks.onNewEvent()
init()
callbacks.onNewDetector()
render()
animate()
)
|
[
{
"context": "\nhttp://xmpp.org/extensions/xep-0054.html\n\nAuthor: Nathan Zorn (nathan.zorn@gmail.com)\nCoffeeScript port: Andrea",
"end": 106,
"score": 0.9998942017555237,
"start": 95,
"tag": "NAME",
"value": "Nathan Zorn"
},
{
"context": "rg/extensions/xep-0054.html\n\nAuthor: Nat... | dist/bower_components/strophejs-plugins/vcard/strophe.vcard.coffee | A-StadLabs/labs-002 | 34 | ###
Plugin to implement the vCard extension.
http://xmpp.org/extensions/xep-0054.html
Author: Nathan Zorn (nathan.zorn@gmail.com)
CoffeeScript port: Andreas Guth (guth@dbis.rwth-aachen.de)
###
### jslint configuration: ###
### global document, window, setTimeout, clearTimeout, console,
XMLHttpRequest, ActiveXObject,
Base64, MD5,
Strophe, $build, $msg, $iq, $pres
###
buildIq = (type, jid, vCardEl) ->
iq = $iq if jid then type:type, to:jid else type:type
iq.c "vCard", xmlns:Strophe.NS.VCARD
iq.cnode vCardEl if vCardEl
iq
Strophe.addConnectionPlugin 'vcard',
_connection: null
# Called by Strophe.Connection constructor
init: (conn) ->
this._connection = conn
Strophe.addNamespace 'VCARD', 'vcard-temp'
###Function
Retrieve a vCard for a JID/Entity
Parameters:
(Function) handler_cb - The callback function used to handle the request.
(String) jid - optional - The name of the entity to request the vCard
If no jid is given, this function retrieves the current user's vcard.
###
get: (handler_cb, jid, error_cb) ->
iq = buildIq "get", jid
this._connection.sendIQ iq, handler_cb, error_cb
### Function
Set an entity's vCard.
###
set: (handler_cb, vCardEl, jid, error_cb) ->
iq = buildIq "set", jid, vCardEl
this._connection.sendIQ iq, handler_cb, error_cb
| 77925 | ###
Plugin to implement the vCard extension.
http://xmpp.org/extensions/xep-0054.html
Author: <NAME> (<EMAIL>)
CoffeeScript port: <NAME> (<EMAIL>)
###
### jslint configuration: ###
### global document, window, setTimeout, clearTimeout, console,
XMLHttpRequest, ActiveXObject,
Base64, MD5,
Strophe, $build, $msg, $iq, $pres
###
buildIq = (type, jid, vCardEl) ->
iq = $iq if jid then type:type, to:jid else type:type
iq.c "vCard", xmlns:Strophe.NS.VCARD
iq.cnode vCardEl if vCardEl
iq
Strophe.addConnectionPlugin 'vcard',
_connection: null
# Called by Strophe.Connection constructor
init: (conn) ->
this._connection = conn
Strophe.addNamespace 'VCARD', 'vcard-temp'
###Function
Retrieve a vCard for a JID/Entity
Parameters:
(Function) handler_cb - The callback function used to handle the request.
(String) jid - optional - The name of the entity to request the vCard
If no jid is given, this function retrieves the current user's vcard.
###
get: (handler_cb, jid, error_cb) ->
iq = buildIq "get", jid
this._connection.sendIQ iq, handler_cb, error_cb
### Function
Set an entity's vCard.
###
set: (handler_cb, vCardEl, jid, error_cb) ->
iq = buildIq "set", jid, vCardEl
this._connection.sendIQ iq, handler_cb, error_cb
| true | ###
Plugin to implement the vCard extension.
http://xmpp.org/extensions/xep-0054.html
Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
CoffeeScript port: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
###
### jslint configuration: ###
### global document, window, setTimeout, clearTimeout, console,
XMLHttpRequest, ActiveXObject,
Base64, MD5,
Strophe, $build, $msg, $iq, $pres
###
buildIq = (type, jid, vCardEl) ->
iq = $iq if jid then type:type, to:jid else type:type
iq.c "vCard", xmlns:Strophe.NS.VCARD
iq.cnode vCardEl if vCardEl
iq
Strophe.addConnectionPlugin 'vcard',
_connection: null
# Called by Strophe.Connection constructor
init: (conn) ->
this._connection = conn
Strophe.addNamespace 'VCARD', 'vcard-temp'
###Function
Retrieve a vCard for a JID/Entity
Parameters:
(Function) handler_cb - The callback function used to handle the request.
(String) jid - optional - The name of the entity to request the vCard
If no jid is given, this function retrieves the current user's vcard.
###
get: (handler_cb, jid, error_cb) ->
iq = buildIq "get", jid
this._connection.sendIQ iq, handler_cb, error_cb
### Function
Set an entity's vCard.
###
set: (handler_cb, vCardEl, jid, error_cb) ->
iq = buildIq "set", jid, vCardEl
this._connection.sendIQ iq, handler_cb, error_cb
|
[
{
"context": "de.js EventEmitter.\n#\n# microevent.js is copyright Jerome Etienne, and licensed under the MIT license:\n# https://gi",
"end": 181,
"score": 0.9995471835136414,
"start": 167,
"tag": "NAME",
"value": "Jerome Etienne"
},
{
"context": "ensed under the MIT license:\n# http... | public/coffee/ide/editor/sharejs/vendor/client/microevent.coffee | mickaobrien/web-sharelatex | 88 | # This is a simple port of microevent.js to Coffeescript. I've changed the
# function names to be consistent with node.js EventEmitter.
#
# microevent.js is copyright Jerome Etienne, and licensed under the MIT license:
# https://github.com/jeromeetienne/microevent.js
nextTick = if WEB? then (fn) -> setTimeout fn, 0 else process['nextTick']
class MicroEvent
on: (event, fct) ->
@_events ||= {}
@_events[event] ||= []
@_events[event].push(fct)
this
removeListener: (event, fct) ->
@_events ||= {}
listeners = (@_events[event] ||= [])
# Sadly, there's no IE8- support for indexOf.
i = 0
while i < listeners.length
listeners[i] = undefined if listeners[i] == fct
i++
nextTick => @_events[event] = (x for x in @_events[event] when x)
this
emit: (event, args...) ->
return this unless @_events?[event]
fn.apply this, args for fn in @_events[event] when fn
this
# mixin will delegate all MicroEvent.js function in the destination object
MicroEvent.mixin = (obj) ->
proto = obj.prototype || obj
# Damn closure compiler :/
proto.on = MicroEvent.prototype.on
proto.removeListener = MicroEvent.prototype.removeListener
proto.emit = MicroEvent.prototype.emit
obj
module.exports = MicroEvent unless WEB?
| 182929 | # This is a simple port of microevent.js to Coffeescript. I've changed the
# function names to be consistent with node.js EventEmitter.
#
# microevent.js is copyright <NAME>, and licensed under the MIT license:
# https://github.com/jeromeetienne/microevent.js
nextTick = if WEB? then (fn) -> setTimeout fn, 0 else process['nextTick']
class MicroEvent
on: (event, fct) ->
@_events ||= {}
@_events[event] ||= []
@_events[event].push(fct)
this
removeListener: (event, fct) ->
@_events ||= {}
listeners = (@_events[event] ||= [])
# Sadly, there's no IE8- support for indexOf.
i = 0
while i < listeners.length
listeners[i] = undefined if listeners[i] == fct
i++
nextTick => @_events[event] = (x for x in @_events[event] when x)
this
emit: (event, args...) ->
return this unless @_events?[event]
fn.apply this, args for fn in @_events[event] when fn
this
# mixin will delegate all MicroEvent.js function in the destination object
MicroEvent.mixin = (obj) ->
proto = obj.prototype || obj
# Damn closure compiler :/
proto.on = MicroEvent.prototype.on
proto.removeListener = MicroEvent.prototype.removeListener
proto.emit = MicroEvent.prototype.emit
obj
module.exports = MicroEvent unless WEB?
| true | # This is a simple port of microevent.js to Coffeescript. I've changed the
# function names to be consistent with node.js EventEmitter.
#
# microevent.js is copyright PI:NAME:<NAME>END_PI, and licensed under the MIT license:
# https://github.com/jeromeetienne/microevent.js
nextTick = if WEB? then (fn) -> setTimeout fn, 0 else process['nextTick']
class MicroEvent
on: (event, fct) ->
@_events ||= {}
@_events[event] ||= []
@_events[event].push(fct)
this
removeListener: (event, fct) ->
@_events ||= {}
listeners = (@_events[event] ||= [])
# Sadly, there's no IE8- support for indexOf.
i = 0
while i < listeners.length
listeners[i] = undefined if listeners[i] == fct
i++
nextTick => @_events[event] = (x for x in @_events[event] when x)
this
emit: (event, args...) ->
return this unless @_events?[event]
fn.apply this, args for fn in @_events[event] when fn
this
# mixin will delegate all MicroEvent.js function in the destination object
MicroEvent.mixin = (obj) ->
proto = obj.prototype || obj
# Damn closure compiler :/
proto.on = MicroEvent.prototype.on
proto.removeListener = MicroEvent.prototype.removeListener
proto.emit = MicroEvent.prototype.emit
obj
module.exports = MicroEvent unless WEB?
|
[
{
"context": "= level + '?dev=true'\n if me.get('name') is 'Nick'\n @childWindow = window.open(\"/play/level/",
"end": 22448,
"score": 0.9177384376525879,
"start": 22444,
"tag": "NAME",
"value": "Nick"
}
] | app/views/editor/thang/ThangTypeEditView.coffee | robertkachniarz/codecombat | 0 | require('app/styles/editor/thang/thang-type-edit-view.sass')
ThangType = require 'models/ThangType'
SpriteParser = require 'lib/sprites/SpriteParser'
SpriteBuilder = require 'lib/sprites/SpriteBuilder'
Lank = require 'lib/surface/Lank'
LayerAdapter = require 'lib/surface/LayerAdapter'
Camera = require 'lib/surface/Camera'
DocumentFiles = require 'collections/DocumentFiles'
require 'lib/setupTreema'
createjs = require 'lib/createjs-parts'
LZString = require 'lz-string'
initSlider = require 'lib/initSlider'
spriteanim = require 'spriteanim'
# in the template, but need to require to load them
require 'views/modal/RevertModal'
RootView = require 'views/core/RootView'
ThangComponentsEditView = require 'views/editor/component/ThangComponentsEditView'
ThangTypeVersionsModal = require './ThangTypeVersionsModal'
ThangTypeColorsTabView = require './ThangTypeColorsTabView'
PatchesView = require 'views/editor/PatchesView'
ForkModal = require 'views/editor/ForkModal'
VectorIconSetupModal = require 'views/editor/thang/VectorIconSetupModal'
SaveVersionModal = require 'views/editor/modal/SaveVersionModal'
template = require 'templates/editor/thang/thang-type-edit-view'
storage = require 'core/storage'
ExportThangTypeModal = require './ExportThangTypeModal'
RevertModal = require 'views/modal/RevertModal'
require 'lib/game-libraries'
CENTER = {x: 200, y: 400}
commonTasks = [
'Upload the art.'
'Set up the vector icon.'
]
displayedThangTypeTasks = [
'Configure the idle action.'
'Configure the positions (registration point, etc.).'
'Set shadow diameter to 0 if needed.'
'Set scale to 0.3, 0.5, or whatever is appropriate.'
'Set rotation to isometric if needed.'
'Set accurate Physical size, shape, and default z.'
'Set accurate Collides collision information if needed.'
'Double-check that fixedRotation is accurate, if it collides.'
]
animatedThangTypeTasks = displayedThangTypeTasks.concat [
'Configure the non-idle actions.'
'Configure any per-action registration points needed.'
'Add flipX per action if needed to face to the right.'
'Make sure any death and attack actions do not loop.'
'Add defaultSimlish if needed.'
'Add selection sounds if needed.'
'Add per-action sound triggers.'
'Add team color groups.'
]
containerTasks = displayedThangTypeTasks.concat [
'Select viable terrains if not universal.'
'Set Exists stateless: true if needed.'
]
purchasableTasks = [
'Add a tier, or 10 + desired tier if not ready yet.'
'Add a gem cost.'
'Write a description.'
'Click the Populate i18n button.'
]
defaultTasks =
Unit: commonTasks.concat animatedThangTypeTasks.concat [
'Start a new name category in names.coffee if needed.'
'Set to Allied to correct team (ogres, humans, or neutral).'
'Add AutoTargetsNearest or FightsBack if needed.'
'Add other Components like Shoots or Casts if needed.'
'Configure other Components, like Moves, Attackable, Attacks, etc.'
'Override the HasAPI type if it will not be correctly inferred.'
'Add to Existence System power table.'
]
Hero: commonTasks.concat animatedThangTypeTasks.concat purchasableTasks.concat [
'Set the hero class.'
'Add Extended Hero Name.'
'Add Short Hero Name.'
'Add Hero Gender.'
'Upload Hero Doll Images.'
'Upload Pose Image.'
'Start a new name category in names.coffee.'
'Set up hero stats in Equips, Attackable, Moves.'
'Set Collects collectRange to 2, Sees visualRange to 60.'
'Add any custom hero abilities.'
'Add to ThangTypeConstants hard-coded hero ids/classes list.'
'Add hero gender.'
'Add hero short name.'
]
Floor: commonTasks.concat containerTasks.concat [
'Add 10 x 8.5 snapping.'
'Set fixed rotation.'
'Make sure everything is scaled to tile perfectly.'
'Adjust SingularSprite floor scale list if necessary.'
]
Wall: commonTasks.concat containerTasks.concat [
'Add 4x4 snapping.'
'Set fixed rotation.'
'Set up and tune complicated wall-face actions.'
'Make sure everything is scaled to tile perfectly.'
]
Doodad: commonTasks.concat containerTasks.concat [
'Add to GenerateTerrainModal logic if needed.'
]
Misc: commonTasks.concat [
'Add any misc tasks for this misc ThangType.'
]
Mark: commonTasks.concat [
'Check the animation framerate.'
'Double-check that bottom of mark is just touching registration point.'
]
Item: commonTasks.concat purchasableTasks.concat [
'Set the hero class if class-specific.'
'Upload Paper Doll Images.'
'Configure item stats and abilities.'
]
Missile: commonTasks.concat animatedThangTypeTasks.concat [
'Make sure there is a launch sound trigger.'
'Make sure there is a hit sound trigger.'
'Make sure there is a die animation.'
'Add Arrow, Shell, Beam, or other missile Component.'
'Choose Missile.leadsShots and Missile.shootsAtGround.'
'Choose Moves.maxSpeed and other config.'
'Choose Expires.lifespan config if needed.'
'Set spriteType: singular if needed for proper rendering.'
'Add HasAPI if the missile should show up in findEnemyMissiles.'
]
module.exports = class ThangTypeEditView extends RootView
id: 'thang-type-edit-view'
className: 'editor'
template: template
resolution: 4
scale: 3
mockThang:
health: 10.0
maxHealth: 10.0
hudProperties: ['health']
acts: true
events:
'click #clear-button': 'clearRawData'
'click #upload-button': -> @$el.find('input#real-upload-button').click()
'click #set-vector-icon': 'onClickSetVectorIcon'
'click #animate-to-flash': -> @$el.find('input#real-animate-flash-button').click(),
'change #real-animate-flash-button': 'animateTransformFileChosen'
'change #real-upload-button': 'animationFileChosen'
'change #animations-select': 'showAnimation'
'click #marker-button': 'toggleDots'
'click #stop-button': 'stopAnimation'
'click #play-button': 'playAnimation'
'click #history-button': 'showVersionHistory'
'click li:not(.disabled) > #fork-start-button': 'startForking'
'click #save-button': 'openSaveModal'
'click #patches-tab': -> @patchesView.load()
'click .play-with-level-button': 'onPlayLevel'
'click .play-with-level-parent': 'onPlayLevelSelect'
'keyup .play-with-level-input': 'onPlayLevelKeyUp'
'click li:not(.disabled) > #pop-level-i18n-button': 'onPopulateLevelI18N'
'mousedown #canvas': 'onCanvasMouseDown'
'mouseup #canvas': 'onCanvasMouseUp'
'mousemove #canvas': 'onCanvasMouseMove'
'click #export-sprite-sheet-btn': 'onClickExportSpriteSheetButton'
'click [data-toggle="coco-modal"][data-target="modal/RevertModal"]': 'openRevertModal'
openRevertModal: (e) ->
e.stopPropagation()
@openModalView new RevertModal()
onClickSetVectorIcon: ->
modal = new VectorIconSetupModal({}, @thangType)
@openModalView modal
modal.once 'done', => @treema.set('/', @getThangData())
subscriptions:
'editor:thang-type-color-groups-changed': 'onColorGroupsChanged'
# init / render
constructor: (options, @thangTypeID) ->
super options
@mockThang = $.extend(true, {}, @mockThang)
@thangType = new ThangType(_id: @thangTypeID)
@thangType = @supermodel.loadModel(@thangType).model
@thangType.saveBackups = true
@listenToOnce @thangType, 'sync', ->
@files = @supermodel.loadCollection(new DocumentFiles(@thangType), 'files').model
@updateFileSize()
# @refreshAnimation = _.debounce @refreshAnimation, 500
showLoading: ($el) ->
$el ?= @$el.find('.outer-content')
super($el)
getRenderData: (context={}) ->
context = super(context)
context.thangType = @thangType
context.animations = @getAnimationNames()
context.authorized = not me.get('anonymous')
context.recentlyPlayedLevels = storage.load('recently-played-levels') ? ['items']
context.fileSizeString = @fileSizeString
context
getAnimationNames: ->
_.sortBy _.keys(@thangType.get('actions') or {}), (a) ->
{move: 1, cast: 2, attack: 3, idle: 4, portrait: 6}[a] or 5
afterRender: ->
super()
return unless @supermodel.finished()
@initStage()
@buildTreema()
@initSliders()
@initComponents()
@insertSubView(new ThangTypeColorsTabView(@thangType))
@patchesView = @insertSubView(new PatchesView(@thangType), @$el.find('.patches-view'))
@showReadOnly() if me.get('anonymous')
@updatePortrait()
initComponents: =>
options =
components: @thangType.get('components') ? []
supermodel: @supermodel
@thangComponentEditView = new ThangComponentsEditView options
@listenTo @thangComponentEditView, 'components-changed', @onComponentsChanged
@insertSubView @thangComponentEditView
onComponentsChanged: (components) =>
@thangType.set 'components', components
onColorGroupsChanged: (e) ->
@temporarilyIgnoringChanges = true
@treema.set 'colorGroups', e.colorGroups
@temporarilyIgnoringChanges = false
makeDot: (color) ->
circle = new createjs.Shape()
circle.graphics.beginFill(color).beginStroke('black').drawCircle(0, 0, 5)
circle.scaleY = 0.2
circle.scaleX = 0.5
circle
initStage: ->
canvas = @$el.find('#canvas')
@stage = new createjs.Stage(canvas[0])
@layerAdapter = new LayerAdapter({name:'Default', webGL: true})
@topLayer = new createjs.Container()
@layerAdapter.container.x = @topLayer.x = CENTER.x
@layerAdapter.container.y = @topLayer.y = CENTER.y
@stage.addChild(@layerAdapter.container, @topLayer)
@listenTo @layerAdapter, 'new-spritesheet', @onNewSpriteSheet
@camera?.destroy()
@camera = new Camera canvas
@torsoDot = @makeDot('blue')
@mouthDot = @makeDot('yellow')
@aboveHeadDot = @makeDot('green')
@groundDot = @makeDot('red')
@topLayer.addChild(@groundDot, @torsoDot, @mouthDot, @aboveHeadDot)
@updateGrid()
_.defer @refreshAnimation
@toggleDots(false)
createjs.Ticker.framerate = 30
createjs.Ticker.addEventListener('tick', @stage)
toggleDots: (newShowDots) ->
@showDots = if typeof(newShowDots) is 'boolean' then newShowDots else not @showDots
@updateDots()
updateDots: ->
@topLayer.removeChild(@torsoDot, @mouthDot, @aboveHeadDot, @groundDot)
return unless @currentLank
return unless @showDots
torso = @currentLank.getOffset 'torso'
mouth = @currentLank.getOffset 'mouth'
aboveHead = @currentLank.getOffset 'aboveHead'
@torsoDot.x = torso.x
@torsoDot.y = torso.y
@mouthDot.x = mouth.x
@mouthDot.y = mouth.y
@aboveHeadDot.x = aboveHead.x
@aboveHeadDot.y = aboveHead.y
@topLayer.addChild(@groundDot, @torsoDot, @mouthDot, @aboveHeadDot)
stopAnimation: ->
@currentLank?.queueAction('idle')
playAnimation: ->
@currentLank?.queueAction(@$el.find('#animations-select').val())
updateGrid: ->
grid = new createjs.Container()
line = new createjs.Shape()
width = 1000
line.graphics.beginFill('#666666').drawRect(-width/2, -0.5, width, 0.5)
line.x = CENTER.x
line.y = CENTER.y
y = line.y
step = 10 * @scale
y -= step while y > 0
while y < 500
y += step
newLine = line.clone()
newLine.y = y
grid.addChild(newLine)
x = line.x
x -= step while x > 0
while x < 400
x += step
newLine = line.clone()
newLine.x = x
newLine.rotation = 90
grid.addChild(newLine)
@stage.removeChild(@grid) if @grid
@stage.addChildAt(grid, 0)
@grid = grid
updateSelectBox: ->
names = @getAnimationNames()
select = @$el.find('#animations-select')
return if select.find('option').length is names.length
select.empty()
select.append($('<option></option>').text(name)) for name in names
# upload
animationFileChosen: (e) ->
@file = e.target.files[0]
return unless @file
return unless _.string.endsWith @file.type, 'javascript'
# @$el.find('#upload-button').prop('disabled', true)
@reader = new FileReader()
@reader.onload = @onFileLoad
@reader.readAsText(@file)
onFileLoad: (e) =>
result = @reader.result
parser = new SpriteParser(@thangType)
parser.parse(result)
@treema.set('raw', @thangType.get('raw'))
@updateSelectBox()
@refreshAnimation()
@updateFileSize()
updateFileSize: ->
file = JSON.stringify(@thangType.attributes)
compressed = LZString.compress(file)
size = (file.length / 1024).toFixed(1) + "KB"
compressedSize = (compressed.length / 1024).toFixed(1) + "KB"
gzipCompressedSize = compressedSize * 1.65 # just based on comparing ogre barracks
@fileSizeString = "Size: #{size} (~#{compressedSize} gzipped)"
@$el.find('#thang-type-file-size').text @fileSizeString
# animation select
refreshAnimation: =>
@thangType.resetSpriteSheetCache()
return @showRasterImage() if @thangType.get('raster')
options = @getLankOptions()
console.log 'refresh animation....'
@showAnimation()
@updatePortrait()
showRasterImage: ->
lank = new Lank(@thangType, @getLankOptions())
@showLank(lank)
@updateScale()
onNewSpriteSheet: ->
$('#spritesheets').empty()
for image in @layerAdapter.spriteSheet._images
$('#spritesheets').append(image)
@layerAdapter.container.x = CENTER.x
@layerAdapter.container.y = CENTER.y
@updateScale()
showAnimation: (animationName) ->
animationName = @$el.find('#animations-select').val() unless _.isString animationName
return unless animationName
@mockThang.action = animationName
@showAction(animationName)
@updateRotation()
@updateScale() # must happen after update rotation, because updateRotation calls the sprite update() method.
showMovieClip: (animationName) ->
vectorParser = new SpriteBuilder(@thangType)
movieClip = vectorParser.buildMovieClip(animationName)
return unless movieClip
reg = @thangType.get('positions')?.registration
if reg
movieClip.regX = -reg.x
movieClip.regY = -reg.y
scale = @thangType.get('scale')
if scale
movieClip.scaleX = movieClip.scaleY = scale
@showSprite(movieClip)
getLankOptions: -> {resolutionFactor: @resolution, thang: @mockThang, preloadSounds: false}
showAction: (actionName) ->
options = @getLankOptions()
lank = new Lank(@thangType, options)
@showLank(lank)
lank.queueAction(actionName)
updatePortrait: ->
options = @getLankOptions()
portrait = @thangType.getPortraitImage(options)
return unless portrait
portrait?.attr('id', 'portrait').addClass('img-thumbnail')
portrait.addClass 'img-thumbnail'
$('#portrait').replaceWith(portrait)
showLank: (lank) ->
@clearDisplayObject()
@clearLank()
@layerAdapter.resetSpriteSheet()
@layerAdapter.addLank(lank)
@currentLank = lank
@currentLankOffset = null
showSprite: (sprite) ->
@clearDisplayObject()
@clearLank()
@topLayer.addChild(sprite)
@currentObject = sprite
@updateDots()
clearDisplayObject: ->
@topLayer.removeChild(@currentObject) if @currentObject?
clearLank: ->
@layerAdapter.removeLank(@currentLank) if @currentLank
@currentLank?.destroy()
# sliders
initSliders: ->
@rotationSlider = initSlider $('#rotation-slider', @$el), 50, @updateRotation
@scaleSlider = initSlider $('#scale-slider', @$el), 29, @updateScale
@resolutionSlider = initSlider $('#resolution-slider', @$el), 39, @updateResolution
@healthSlider = initSlider $('#health-slider', @$el), 100, @updateHealth
updateRotation: =>
value = parseInt(180 * (@rotationSlider.slider('value') - 50) / 50)
@$el.find('.rotation-label').text " #{value}° "
if @currentLank
@currentLank.rotation = value
@currentLank.update(true)
updateScale: =>
scaleValue = (@scaleSlider.slider('value') + 1) / 10
@layerAdapter.container.scaleX = @layerAdapter.container.scaleY = @topLayer.scaleX = @topLayer.scaleY = scaleValue
fixed = scaleValue.toFixed(1)
@scale = scaleValue
@$el.find('.scale-label').text " #{fixed}x "
@updateGrid()
updateResolution: =>
value = (@resolutionSlider.slider('value') + 1) / 10
fixed = value.toFixed(1)
@$el.find('.resolution-label').text " #{fixed}x "
@resolution = value
@refreshAnimation()
updateHealth: =>
value = parseInt((@healthSlider.slider('value')) / 10)
@$el.find('.health-label').text " #{value}hp "
@mockThang.health = value
@currentLank?.update()
# save
saveNewThangType: (e) ->
newThangType = if e.major then @thangType.cloneNewMajorVersion() else @thangType.cloneNewMinorVersion()
newThangType.set('commitMessage', e.commitMessage)
newThangType.updateI18NCoverage() if newThangType.get('i18nCoverage')
res = newThangType.save(null, {type: 'POST'}) # Override PUT so we can trigger postNewVersion logic
return unless res
modal = $('#save-version-modal')
@enableModalInProgress(modal)
res.error =>
@disableModalInProgress(modal)
res.success =>
url = "/editor/thang/#{newThangType.get('slug') or newThangType.id}"
portraitSource = null
if @thangType.get('raster')
#image = @currentLank.sprite.image # Doesn't work?
image = @currentLank.sprite.spriteSheet._images[0]
portraitSource = imageToPortrait image
# bit of a hacky way to get that portrait
success = =>
@thangType.clearBackup()
document.location.href = url
newThangType.uploadGenericPortrait success, portraitSource
clearRawData: ->
@thangType.resetRawData()
@thangType.set 'actions', undefined
@clearDisplayObject()
@treema.set('/', @getThangData())
getThangData: ->
data = $.extend(true, {}, @thangType.attributes)
data = _.pick data, (value, key) => not (key in ['components'])
buildTreema: ->
data = @getThangData()
schema = _.cloneDeep ThangType.schema
schema.properties = _.pick schema.properties, (value, key) => not (key in ['components'])
options =
data: data
schema: schema
files: @files
filePath: "db/thang.type/#{@thangType.get('original')}"
readOnly: me.get('anonymous')
callbacks:
change: @pushChangesToPreview
select: @onSelectNode
el = @$el.find('#thang-type-treema')
@treema = @$el.find('#thang-type-treema').treema(options)
@treema.build()
@lastKind = data.kind
pushChangesToPreview: =>
return if @temporarilyIgnoringChanges
keysProcessed = {}
for key of @thangType.attributes
keysProcessed[key] = true
continue if key is 'components'
@thangType.set(key, @treema.data[key])
for key, value of @treema.data when not keysProcessed[key]
@thangType.set(key, value)
@updateSelectBox()
@refreshAnimation()
@updateDots()
@updatePortrait()
if (kind = @treema.data.kind) isnt @lastKind
@lastKind = kind
Backbone.Mediator.publish 'editor:thang-type-kind-changed', kind: kind
if kind in ['Doodad', 'Floor', 'Wall'] and not @treema.data.terrains
@treema.set '/terrains', ['Grass', 'Dungeon', 'Indoor', 'Desert', 'Mountain', 'Glacier', 'Volcano'] # So editors know to set them.
if not @treema.data.tasks
@treema.set '/tasks', (name: t for t in defaultTasks[kind])
onSelectNode: (e, selected) =>
selected = selected[0]
@topLayer.removeChild(@boundsBox) if @boundsBox
return @stopShowingSelectedNode() if not selected
path = selected.getPath()
parts = path.split('/')
return @stopShowingSelectedNode() unless parts.length >= 4 and _.string.startsWith path, '/raw/'
key = parts[3]
type = parts[2]
vectorParser = new SpriteBuilder(@thangType)
obj = vectorParser.buildMovieClip(key) if type is 'animations'
obj = vectorParser.buildContainerFromStore(key) if type is 'containers'
obj = vectorParser.buildShapeFromStore(key) if type is 'shapes'
bounds = obj?.bounds or obj?.nominalBounds
if bounds
@boundsBox = new createjs.Shape()
@boundsBox.graphics.beginFill('#aaaaaa').beginStroke('black').drawRect(bounds.x, bounds.y, bounds.width, bounds.height)
@topLayer.addChild(@boundsBox)
obj.regX = @boundsBox.regX = bounds.x + bounds.width / 2
obj.regY = @boundsBox.regY = bounds.y + bounds.height / 2
@showSprite(obj) if obj
@showingSelectedNode = true
@currentLank?.destroy()
@currentLank = null
@updateScale()
@grid.alpha = 0.0
stopShowingSelectedNode: ->
return unless @showingSelectedNode
@grid.alpha = 1.0
@showAnimation()
@showingSelectedNode = false
showVersionHistory: (e) ->
@openModalView new ThangTypeVersionsModal thangType: @thangType, @thangTypeID
onPopulateLevelI18N: ->
@thangType.populateI18N()
_.delay((-> document.location.reload()), 500)
openSaveModal: ->
modal = new SaveVersionModal model: @thangType
@openModalView modal
@listenToOnce modal, 'save-new-version', @saveNewThangType
@listenToOnce modal, 'hidden', -> @stopListening(modal)
startForking: (e) ->
@openModalView new ForkModal model: @thangType, editorPath: 'thang'
onPlayLevelSelect: (e) ->
if @childWindow and not @childWindow.closed
# We already have a child window open, so we don't need to ask for a level; we'll use its existing level.
e.stopImmediatePropagation()
@onPlayLevel e
_.defer -> $('.play-with-level-input').focus()
onPlayLevelKeyUp: (e) ->
return unless e.keyCode is 13 # return
input = @$el.find('.play-with-level-input')
input.parents('.dropdown').find('.play-with-level-parent').dropdown('toggle')
level = _.string.slugify input.val()
return unless level
@onPlayLevel null, level
recentlyPlayedLevels = storage.load('recently-played-levels') ? []
recentlyPlayedLevels.push level
storage.save 'recently-played-levels', recentlyPlayedLevels
onPlayLevel: (e, level=null) ->
level ?= $(e.target).data('level')
level = _.string.slugify level
if @childWindow and not @childWindow.closed
# Reset the LevelView's world, but leave the rest of the state alone
@childWindow.Backbone.Mediator.publish 'level:reload-thang-type', thangType: @thangType
else
# Create a new Window with a blank LevelView
scratchLevelID = level + '?dev=true'
if me.get('name') is 'Nick'
@childWindow = window.open("/play/level/#{scratchLevelID}", 'child_window', 'width=2560,height=1080,left=0,top=-1600,location=1,menubar=1,scrollbars=1,status=0,titlebar=1,toolbar=1', true)
else
@childWindow = window.open("/play/level/#{scratchLevelID}", 'child_window', 'width=1024,height=560,left=10,top=10,location=0,menubar=0,scrollbars=0,status=0,titlebar=0,toolbar=0', true)
@childWindow.focus()
# Canvas mouse drag handlers
onCanvasMouseMove: (e) ->
return unless p1 = @canvasDragStart
p2 = x: e.offsetX, y: e.offsetY
offset = x: p2.x - p1.x, y: p2.y - p1.y
@currentLank.sprite.x = @currentLankOffset.x + offset.x / @scale
@currentLank.sprite.y = @currentLankOffset.y + offset.y / @scale
@canvasDragOffset = offset
onCanvasMouseDown: (e) ->
return unless @currentLank
@canvasDragStart = x: e.offsetX, y: e.offsetY
@currentLankOffset ?= x: @currentLank.sprite.x, y: @currentLank.sprite.y
onCanvasMouseUp: (e) ->
@canvasDragStart = null
return unless @canvasDragOffset
return unless node = @treema.getLastSelectedTreema()
offset = node.get '/'
offset.x += Math.round @canvasDragOffset.x
offset.y += Math.round @canvasDragOffset.y
@canvasDragOffset = null
node.set '/', offset
onClickExportSpriteSheetButton: ->
modal = new ExportThangTypeModal({}, @thangType)
@openModalView(modal)
animateTransformFileChosen: (e) ->
animateFile = e.target.files[0]
return unless animateFile
return unless _.string.endsWith animateFile.type, 'javascript'
animateReader = new FileReader()
animateReader.onload = @onAnimateFileLoad
animateReader.readAsText(animateFile)
onAnimateFileLoad: (e) ->
animateText = e.target.result
flashText = spriteanim(animateText)
data = new Blob([flashText], {type: 'text/plain'});
# Prevents memory leaks.
if @flashFile != null
window.URL.revokeObjectURL(@flashFile)
@flashFile = window.URL.createObjectURL(data)
fileName = prompt("What do you want to name the file? '.js' will be added to the end.")
if fileName
# Create the file to download.
el = document.createElement('a')
el.href = @flashFile
el.setAttribute('download', "#{fileName}.js")
el.style.display = 'none'
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
destroy: ->
@camera?.destroy()
super()
imageToPortrait = (img) ->
canvas = document.createElement('canvas')
canvas.width = 100
canvas.height = 100
ctx = canvas.getContext('2d')
scaleX = 100 / img.width
scaleY = 100 / img.height
ctx.scale scaleX, scaleY
ctx.drawImage img, 0, 0
canvas.toDataURL('image/png')
| 212525 | require('app/styles/editor/thang/thang-type-edit-view.sass')
ThangType = require 'models/ThangType'
SpriteParser = require 'lib/sprites/SpriteParser'
SpriteBuilder = require 'lib/sprites/SpriteBuilder'
Lank = require 'lib/surface/Lank'
LayerAdapter = require 'lib/surface/LayerAdapter'
Camera = require 'lib/surface/Camera'
DocumentFiles = require 'collections/DocumentFiles'
require 'lib/setupTreema'
createjs = require 'lib/createjs-parts'
LZString = require 'lz-string'
initSlider = require 'lib/initSlider'
spriteanim = require 'spriteanim'
# in the template, but need to require to load them
require 'views/modal/RevertModal'
RootView = require 'views/core/RootView'
ThangComponentsEditView = require 'views/editor/component/ThangComponentsEditView'
ThangTypeVersionsModal = require './ThangTypeVersionsModal'
ThangTypeColorsTabView = require './ThangTypeColorsTabView'
PatchesView = require 'views/editor/PatchesView'
ForkModal = require 'views/editor/ForkModal'
VectorIconSetupModal = require 'views/editor/thang/VectorIconSetupModal'
SaveVersionModal = require 'views/editor/modal/SaveVersionModal'
template = require 'templates/editor/thang/thang-type-edit-view'
storage = require 'core/storage'
ExportThangTypeModal = require './ExportThangTypeModal'
RevertModal = require 'views/modal/RevertModal'
require 'lib/game-libraries'
CENTER = {x: 200, y: 400}
commonTasks = [
'Upload the art.'
'Set up the vector icon.'
]
displayedThangTypeTasks = [
'Configure the idle action.'
'Configure the positions (registration point, etc.).'
'Set shadow diameter to 0 if needed.'
'Set scale to 0.3, 0.5, or whatever is appropriate.'
'Set rotation to isometric if needed.'
'Set accurate Physical size, shape, and default z.'
'Set accurate Collides collision information if needed.'
'Double-check that fixedRotation is accurate, if it collides.'
]
animatedThangTypeTasks = displayedThangTypeTasks.concat [
'Configure the non-idle actions.'
'Configure any per-action registration points needed.'
'Add flipX per action if needed to face to the right.'
'Make sure any death and attack actions do not loop.'
'Add defaultSimlish if needed.'
'Add selection sounds if needed.'
'Add per-action sound triggers.'
'Add team color groups.'
]
containerTasks = displayedThangTypeTasks.concat [
'Select viable terrains if not universal.'
'Set Exists stateless: true if needed.'
]
purchasableTasks = [
'Add a tier, or 10 + desired tier if not ready yet.'
'Add a gem cost.'
'Write a description.'
'Click the Populate i18n button.'
]
defaultTasks =
Unit: commonTasks.concat animatedThangTypeTasks.concat [
'Start a new name category in names.coffee if needed.'
'Set to Allied to correct team (ogres, humans, or neutral).'
'Add AutoTargetsNearest or FightsBack if needed.'
'Add other Components like Shoots or Casts if needed.'
'Configure other Components, like Moves, Attackable, Attacks, etc.'
'Override the HasAPI type if it will not be correctly inferred.'
'Add to Existence System power table.'
]
Hero: commonTasks.concat animatedThangTypeTasks.concat purchasableTasks.concat [
'Set the hero class.'
'Add Extended Hero Name.'
'Add Short Hero Name.'
'Add Hero Gender.'
'Upload Hero Doll Images.'
'Upload Pose Image.'
'Start a new name category in names.coffee.'
'Set up hero stats in Equips, Attackable, Moves.'
'Set Collects collectRange to 2, Sees visualRange to 60.'
'Add any custom hero abilities.'
'Add to ThangTypeConstants hard-coded hero ids/classes list.'
'Add hero gender.'
'Add hero short name.'
]
Floor: commonTasks.concat containerTasks.concat [
'Add 10 x 8.5 snapping.'
'Set fixed rotation.'
'Make sure everything is scaled to tile perfectly.'
'Adjust SingularSprite floor scale list if necessary.'
]
Wall: commonTasks.concat containerTasks.concat [
'Add 4x4 snapping.'
'Set fixed rotation.'
'Set up and tune complicated wall-face actions.'
'Make sure everything is scaled to tile perfectly.'
]
Doodad: commonTasks.concat containerTasks.concat [
'Add to GenerateTerrainModal logic if needed.'
]
Misc: commonTasks.concat [
'Add any misc tasks for this misc ThangType.'
]
Mark: commonTasks.concat [
'Check the animation framerate.'
'Double-check that bottom of mark is just touching registration point.'
]
Item: commonTasks.concat purchasableTasks.concat [
'Set the hero class if class-specific.'
'Upload Paper Doll Images.'
'Configure item stats and abilities.'
]
Missile: commonTasks.concat animatedThangTypeTasks.concat [
'Make sure there is a launch sound trigger.'
'Make sure there is a hit sound trigger.'
'Make sure there is a die animation.'
'Add Arrow, Shell, Beam, or other missile Component.'
'Choose Missile.leadsShots and Missile.shootsAtGround.'
'Choose Moves.maxSpeed and other config.'
'Choose Expires.lifespan config if needed.'
'Set spriteType: singular if needed for proper rendering.'
'Add HasAPI if the missile should show up in findEnemyMissiles.'
]
module.exports = class ThangTypeEditView extends RootView
id: 'thang-type-edit-view'
className: 'editor'
template: template
resolution: 4
scale: 3
mockThang:
health: 10.0
maxHealth: 10.0
hudProperties: ['health']
acts: true
events:
'click #clear-button': 'clearRawData'
'click #upload-button': -> @$el.find('input#real-upload-button').click()
'click #set-vector-icon': 'onClickSetVectorIcon'
'click #animate-to-flash': -> @$el.find('input#real-animate-flash-button').click(),
'change #real-animate-flash-button': 'animateTransformFileChosen'
'change #real-upload-button': 'animationFileChosen'
'change #animations-select': 'showAnimation'
'click #marker-button': 'toggleDots'
'click #stop-button': 'stopAnimation'
'click #play-button': 'playAnimation'
'click #history-button': 'showVersionHistory'
'click li:not(.disabled) > #fork-start-button': 'startForking'
'click #save-button': 'openSaveModal'
'click #patches-tab': -> @patchesView.load()
'click .play-with-level-button': 'onPlayLevel'
'click .play-with-level-parent': 'onPlayLevelSelect'
'keyup .play-with-level-input': 'onPlayLevelKeyUp'
'click li:not(.disabled) > #pop-level-i18n-button': 'onPopulateLevelI18N'
'mousedown #canvas': 'onCanvasMouseDown'
'mouseup #canvas': 'onCanvasMouseUp'
'mousemove #canvas': 'onCanvasMouseMove'
'click #export-sprite-sheet-btn': 'onClickExportSpriteSheetButton'
'click [data-toggle="coco-modal"][data-target="modal/RevertModal"]': 'openRevertModal'
openRevertModal: (e) ->
e.stopPropagation()
@openModalView new RevertModal()
onClickSetVectorIcon: ->
modal = new VectorIconSetupModal({}, @thangType)
@openModalView modal
modal.once 'done', => @treema.set('/', @getThangData())
subscriptions:
'editor:thang-type-color-groups-changed': 'onColorGroupsChanged'
# init / render
constructor: (options, @thangTypeID) ->
super options
@mockThang = $.extend(true, {}, @mockThang)
@thangType = new ThangType(_id: @thangTypeID)
@thangType = @supermodel.loadModel(@thangType).model
@thangType.saveBackups = true
@listenToOnce @thangType, 'sync', ->
@files = @supermodel.loadCollection(new DocumentFiles(@thangType), 'files').model
@updateFileSize()
# @refreshAnimation = _.debounce @refreshAnimation, 500
showLoading: ($el) ->
$el ?= @$el.find('.outer-content')
super($el)
getRenderData: (context={}) ->
context = super(context)
context.thangType = @thangType
context.animations = @getAnimationNames()
context.authorized = not me.get('anonymous')
context.recentlyPlayedLevels = storage.load('recently-played-levels') ? ['items']
context.fileSizeString = @fileSizeString
context
getAnimationNames: ->
_.sortBy _.keys(@thangType.get('actions') or {}), (a) ->
{move: 1, cast: 2, attack: 3, idle: 4, portrait: 6}[a] or 5
afterRender: ->
super()
return unless @supermodel.finished()
@initStage()
@buildTreema()
@initSliders()
@initComponents()
@insertSubView(new ThangTypeColorsTabView(@thangType))
@patchesView = @insertSubView(new PatchesView(@thangType), @$el.find('.patches-view'))
@showReadOnly() if me.get('anonymous')
@updatePortrait()
initComponents: =>
options =
components: @thangType.get('components') ? []
supermodel: @supermodel
@thangComponentEditView = new ThangComponentsEditView options
@listenTo @thangComponentEditView, 'components-changed', @onComponentsChanged
@insertSubView @thangComponentEditView
onComponentsChanged: (components) =>
@thangType.set 'components', components
onColorGroupsChanged: (e) ->
@temporarilyIgnoringChanges = true
@treema.set 'colorGroups', e.colorGroups
@temporarilyIgnoringChanges = false
makeDot: (color) ->
circle = new createjs.Shape()
circle.graphics.beginFill(color).beginStroke('black').drawCircle(0, 0, 5)
circle.scaleY = 0.2
circle.scaleX = 0.5
circle
initStage: ->
canvas = @$el.find('#canvas')
@stage = new createjs.Stage(canvas[0])
@layerAdapter = new LayerAdapter({name:'Default', webGL: true})
@topLayer = new createjs.Container()
@layerAdapter.container.x = @topLayer.x = CENTER.x
@layerAdapter.container.y = @topLayer.y = CENTER.y
@stage.addChild(@layerAdapter.container, @topLayer)
@listenTo @layerAdapter, 'new-spritesheet', @onNewSpriteSheet
@camera?.destroy()
@camera = new Camera canvas
@torsoDot = @makeDot('blue')
@mouthDot = @makeDot('yellow')
@aboveHeadDot = @makeDot('green')
@groundDot = @makeDot('red')
@topLayer.addChild(@groundDot, @torsoDot, @mouthDot, @aboveHeadDot)
@updateGrid()
_.defer @refreshAnimation
@toggleDots(false)
createjs.Ticker.framerate = 30
createjs.Ticker.addEventListener('tick', @stage)
toggleDots: (newShowDots) ->
@showDots = if typeof(newShowDots) is 'boolean' then newShowDots else not @showDots
@updateDots()
updateDots: ->
@topLayer.removeChild(@torsoDot, @mouthDot, @aboveHeadDot, @groundDot)
return unless @currentLank
return unless @showDots
torso = @currentLank.getOffset 'torso'
mouth = @currentLank.getOffset 'mouth'
aboveHead = @currentLank.getOffset 'aboveHead'
@torsoDot.x = torso.x
@torsoDot.y = torso.y
@mouthDot.x = mouth.x
@mouthDot.y = mouth.y
@aboveHeadDot.x = aboveHead.x
@aboveHeadDot.y = aboveHead.y
@topLayer.addChild(@groundDot, @torsoDot, @mouthDot, @aboveHeadDot)
stopAnimation: ->
@currentLank?.queueAction('idle')
playAnimation: ->
@currentLank?.queueAction(@$el.find('#animations-select').val())
updateGrid: ->
grid = new createjs.Container()
line = new createjs.Shape()
width = 1000
line.graphics.beginFill('#666666').drawRect(-width/2, -0.5, width, 0.5)
line.x = CENTER.x
line.y = CENTER.y
y = line.y
step = 10 * @scale
y -= step while y > 0
while y < 500
y += step
newLine = line.clone()
newLine.y = y
grid.addChild(newLine)
x = line.x
x -= step while x > 0
while x < 400
x += step
newLine = line.clone()
newLine.x = x
newLine.rotation = 90
grid.addChild(newLine)
@stage.removeChild(@grid) if @grid
@stage.addChildAt(grid, 0)
@grid = grid
updateSelectBox: ->
names = @getAnimationNames()
select = @$el.find('#animations-select')
return if select.find('option').length is names.length
select.empty()
select.append($('<option></option>').text(name)) for name in names
# upload
animationFileChosen: (e) ->
@file = e.target.files[0]
return unless @file
return unless _.string.endsWith @file.type, 'javascript'
# @$el.find('#upload-button').prop('disabled', true)
@reader = new FileReader()
@reader.onload = @onFileLoad
@reader.readAsText(@file)
onFileLoad: (e) =>
result = @reader.result
parser = new SpriteParser(@thangType)
parser.parse(result)
@treema.set('raw', @thangType.get('raw'))
@updateSelectBox()
@refreshAnimation()
@updateFileSize()
updateFileSize: ->
file = JSON.stringify(@thangType.attributes)
compressed = LZString.compress(file)
size = (file.length / 1024).toFixed(1) + "KB"
compressedSize = (compressed.length / 1024).toFixed(1) + "KB"
gzipCompressedSize = compressedSize * 1.65 # just based on comparing ogre barracks
@fileSizeString = "Size: #{size} (~#{compressedSize} gzipped)"
@$el.find('#thang-type-file-size').text @fileSizeString
# animation select
refreshAnimation: =>
@thangType.resetSpriteSheetCache()
return @showRasterImage() if @thangType.get('raster')
options = @getLankOptions()
console.log 'refresh animation....'
@showAnimation()
@updatePortrait()
showRasterImage: ->
lank = new Lank(@thangType, @getLankOptions())
@showLank(lank)
@updateScale()
onNewSpriteSheet: ->
$('#spritesheets').empty()
for image in @layerAdapter.spriteSheet._images
$('#spritesheets').append(image)
@layerAdapter.container.x = CENTER.x
@layerAdapter.container.y = CENTER.y
@updateScale()
showAnimation: (animationName) ->
animationName = @$el.find('#animations-select').val() unless _.isString animationName
return unless animationName
@mockThang.action = animationName
@showAction(animationName)
@updateRotation()
@updateScale() # must happen after update rotation, because updateRotation calls the sprite update() method.
showMovieClip: (animationName) ->
vectorParser = new SpriteBuilder(@thangType)
movieClip = vectorParser.buildMovieClip(animationName)
return unless movieClip
reg = @thangType.get('positions')?.registration
if reg
movieClip.regX = -reg.x
movieClip.regY = -reg.y
scale = @thangType.get('scale')
if scale
movieClip.scaleX = movieClip.scaleY = scale
@showSprite(movieClip)
getLankOptions: -> {resolutionFactor: @resolution, thang: @mockThang, preloadSounds: false}
showAction: (actionName) ->
options = @getLankOptions()
lank = new Lank(@thangType, options)
@showLank(lank)
lank.queueAction(actionName)
updatePortrait: ->
options = @getLankOptions()
portrait = @thangType.getPortraitImage(options)
return unless portrait
portrait?.attr('id', 'portrait').addClass('img-thumbnail')
portrait.addClass 'img-thumbnail'
$('#portrait').replaceWith(portrait)
showLank: (lank) ->
@clearDisplayObject()
@clearLank()
@layerAdapter.resetSpriteSheet()
@layerAdapter.addLank(lank)
@currentLank = lank
@currentLankOffset = null
showSprite: (sprite) ->
@clearDisplayObject()
@clearLank()
@topLayer.addChild(sprite)
@currentObject = sprite
@updateDots()
clearDisplayObject: ->
@topLayer.removeChild(@currentObject) if @currentObject?
clearLank: ->
@layerAdapter.removeLank(@currentLank) if @currentLank
@currentLank?.destroy()
# sliders
initSliders: ->
@rotationSlider = initSlider $('#rotation-slider', @$el), 50, @updateRotation
@scaleSlider = initSlider $('#scale-slider', @$el), 29, @updateScale
@resolutionSlider = initSlider $('#resolution-slider', @$el), 39, @updateResolution
@healthSlider = initSlider $('#health-slider', @$el), 100, @updateHealth
updateRotation: =>
value = parseInt(180 * (@rotationSlider.slider('value') - 50) / 50)
@$el.find('.rotation-label').text " #{value}° "
if @currentLank
@currentLank.rotation = value
@currentLank.update(true)
updateScale: =>
scaleValue = (@scaleSlider.slider('value') + 1) / 10
@layerAdapter.container.scaleX = @layerAdapter.container.scaleY = @topLayer.scaleX = @topLayer.scaleY = scaleValue
fixed = scaleValue.toFixed(1)
@scale = scaleValue
@$el.find('.scale-label').text " #{fixed}x "
@updateGrid()
updateResolution: =>
value = (@resolutionSlider.slider('value') + 1) / 10
fixed = value.toFixed(1)
@$el.find('.resolution-label').text " #{fixed}x "
@resolution = value
@refreshAnimation()
updateHealth: =>
value = parseInt((@healthSlider.slider('value')) / 10)
@$el.find('.health-label').text " #{value}hp "
@mockThang.health = value
@currentLank?.update()
# save
saveNewThangType: (e) ->
newThangType = if e.major then @thangType.cloneNewMajorVersion() else @thangType.cloneNewMinorVersion()
newThangType.set('commitMessage', e.commitMessage)
newThangType.updateI18NCoverage() if newThangType.get('i18nCoverage')
res = newThangType.save(null, {type: 'POST'}) # Override PUT so we can trigger postNewVersion logic
return unless res
modal = $('#save-version-modal')
@enableModalInProgress(modal)
res.error =>
@disableModalInProgress(modal)
res.success =>
url = "/editor/thang/#{newThangType.get('slug') or newThangType.id}"
portraitSource = null
if @thangType.get('raster')
#image = @currentLank.sprite.image # Doesn't work?
image = @currentLank.sprite.spriteSheet._images[0]
portraitSource = imageToPortrait image
# bit of a hacky way to get that portrait
success = =>
@thangType.clearBackup()
document.location.href = url
newThangType.uploadGenericPortrait success, portraitSource
clearRawData: ->
@thangType.resetRawData()
@thangType.set 'actions', undefined
@clearDisplayObject()
@treema.set('/', @getThangData())
getThangData: ->
data = $.extend(true, {}, @thangType.attributes)
data = _.pick data, (value, key) => not (key in ['components'])
buildTreema: ->
data = @getThangData()
schema = _.cloneDeep ThangType.schema
schema.properties = _.pick schema.properties, (value, key) => not (key in ['components'])
options =
data: data
schema: schema
files: @files
filePath: "db/thang.type/#{@thangType.get('original')}"
readOnly: me.get('anonymous')
callbacks:
change: @pushChangesToPreview
select: @onSelectNode
el = @$el.find('#thang-type-treema')
@treema = @$el.find('#thang-type-treema').treema(options)
@treema.build()
@lastKind = data.kind
pushChangesToPreview: =>
return if @temporarilyIgnoringChanges
keysProcessed = {}
for key of @thangType.attributes
keysProcessed[key] = true
continue if key is 'components'
@thangType.set(key, @treema.data[key])
for key, value of @treema.data when not keysProcessed[key]
@thangType.set(key, value)
@updateSelectBox()
@refreshAnimation()
@updateDots()
@updatePortrait()
if (kind = @treema.data.kind) isnt @lastKind
@lastKind = kind
Backbone.Mediator.publish 'editor:thang-type-kind-changed', kind: kind
if kind in ['Doodad', 'Floor', 'Wall'] and not @treema.data.terrains
@treema.set '/terrains', ['Grass', 'Dungeon', 'Indoor', 'Desert', 'Mountain', 'Glacier', 'Volcano'] # So editors know to set them.
if not @treema.data.tasks
@treema.set '/tasks', (name: t for t in defaultTasks[kind])
onSelectNode: (e, selected) =>
selected = selected[0]
@topLayer.removeChild(@boundsBox) if @boundsBox
return @stopShowingSelectedNode() if not selected
path = selected.getPath()
parts = path.split('/')
return @stopShowingSelectedNode() unless parts.length >= 4 and _.string.startsWith path, '/raw/'
key = parts[3]
type = parts[2]
vectorParser = new SpriteBuilder(@thangType)
obj = vectorParser.buildMovieClip(key) if type is 'animations'
obj = vectorParser.buildContainerFromStore(key) if type is 'containers'
obj = vectorParser.buildShapeFromStore(key) if type is 'shapes'
bounds = obj?.bounds or obj?.nominalBounds
if bounds
@boundsBox = new createjs.Shape()
@boundsBox.graphics.beginFill('#aaaaaa').beginStroke('black').drawRect(bounds.x, bounds.y, bounds.width, bounds.height)
@topLayer.addChild(@boundsBox)
obj.regX = @boundsBox.regX = bounds.x + bounds.width / 2
obj.regY = @boundsBox.regY = bounds.y + bounds.height / 2
@showSprite(obj) if obj
@showingSelectedNode = true
@currentLank?.destroy()
@currentLank = null
@updateScale()
@grid.alpha = 0.0
stopShowingSelectedNode: ->
return unless @showingSelectedNode
@grid.alpha = 1.0
@showAnimation()
@showingSelectedNode = false
showVersionHistory: (e) ->
@openModalView new ThangTypeVersionsModal thangType: @thangType, @thangTypeID
onPopulateLevelI18N: ->
@thangType.populateI18N()
_.delay((-> document.location.reload()), 500)
openSaveModal: ->
modal = new SaveVersionModal model: @thangType
@openModalView modal
@listenToOnce modal, 'save-new-version', @saveNewThangType
@listenToOnce modal, 'hidden', -> @stopListening(modal)
startForking: (e) ->
@openModalView new ForkModal model: @thangType, editorPath: 'thang'
onPlayLevelSelect: (e) ->
if @childWindow and not @childWindow.closed
# We already have a child window open, so we don't need to ask for a level; we'll use its existing level.
e.stopImmediatePropagation()
@onPlayLevel e
_.defer -> $('.play-with-level-input').focus()
onPlayLevelKeyUp: (e) ->
return unless e.keyCode is 13 # return
input = @$el.find('.play-with-level-input')
input.parents('.dropdown').find('.play-with-level-parent').dropdown('toggle')
level = _.string.slugify input.val()
return unless level
@onPlayLevel null, level
recentlyPlayedLevels = storage.load('recently-played-levels') ? []
recentlyPlayedLevels.push level
storage.save 'recently-played-levels', recentlyPlayedLevels
onPlayLevel: (e, level=null) ->
level ?= $(e.target).data('level')
level = _.string.slugify level
if @childWindow and not @childWindow.closed
# Reset the LevelView's world, but leave the rest of the state alone
@childWindow.Backbone.Mediator.publish 'level:reload-thang-type', thangType: @thangType
else
# Create a new Window with a blank LevelView
scratchLevelID = level + '?dev=true'
if me.get('name') is '<NAME>'
@childWindow = window.open("/play/level/#{scratchLevelID}", 'child_window', 'width=2560,height=1080,left=0,top=-1600,location=1,menubar=1,scrollbars=1,status=0,titlebar=1,toolbar=1', true)
else
@childWindow = window.open("/play/level/#{scratchLevelID}", 'child_window', 'width=1024,height=560,left=10,top=10,location=0,menubar=0,scrollbars=0,status=0,titlebar=0,toolbar=0', true)
@childWindow.focus()
# Canvas mouse drag handlers
onCanvasMouseMove: (e) ->
return unless p1 = @canvasDragStart
p2 = x: e.offsetX, y: e.offsetY
offset = x: p2.x - p1.x, y: p2.y - p1.y
@currentLank.sprite.x = @currentLankOffset.x + offset.x / @scale
@currentLank.sprite.y = @currentLankOffset.y + offset.y / @scale
@canvasDragOffset = offset
onCanvasMouseDown: (e) ->
return unless @currentLank
@canvasDragStart = x: e.offsetX, y: e.offsetY
@currentLankOffset ?= x: @currentLank.sprite.x, y: @currentLank.sprite.y
onCanvasMouseUp: (e) ->
@canvasDragStart = null
return unless @canvasDragOffset
return unless node = @treema.getLastSelectedTreema()
offset = node.get '/'
offset.x += Math.round @canvasDragOffset.x
offset.y += Math.round @canvasDragOffset.y
@canvasDragOffset = null
node.set '/', offset
onClickExportSpriteSheetButton: ->
modal = new ExportThangTypeModal({}, @thangType)
@openModalView(modal)
animateTransformFileChosen: (e) ->
animateFile = e.target.files[0]
return unless animateFile
return unless _.string.endsWith animateFile.type, 'javascript'
animateReader = new FileReader()
animateReader.onload = @onAnimateFileLoad
animateReader.readAsText(animateFile)
onAnimateFileLoad: (e) ->
animateText = e.target.result
flashText = spriteanim(animateText)
data = new Blob([flashText], {type: 'text/plain'});
# Prevents memory leaks.
if @flashFile != null
window.URL.revokeObjectURL(@flashFile)
@flashFile = window.URL.createObjectURL(data)
fileName = prompt("What do you want to name the file? '.js' will be added to the end.")
if fileName
# Create the file to download.
el = document.createElement('a')
el.href = @flashFile
el.setAttribute('download', "#{fileName}.js")
el.style.display = 'none'
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
destroy: ->
@camera?.destroy()
super()
imageToPortrait = (img) ->
canvas = document.createElement('canvas')
canvas.width = 100
canvas.height = 100
ctx = canvas.getContext('2d')
scaleX = 100 / img.width
scaleY = 100 / img.height
ctx.scale scaleX, scaleY
ctx.drawImage img, 0, 0
canvas.toDataURL('image/png')
| true | require('app/styles/editor/thang/thang-type-edit-view.sass')
ThangType = require 'models/ThangType'
SpriteParser = require 'lib/sprites/SpriteParser'
SpriteBuilder = require 'lib/sprites/SpriteBuilder'
Lank = require 'lib/surface/Lank'
LayerAdapter = require 'lib/surface/LayerAdapter'
Camera = require 'lib/surface/Camera'
DocumentFiles = require 'collections/DocumentFiles'
require 'lib/setupTreema'
createjs = require 'lib/createjs-parts'
LZString = require 'lz-string'
initSlider = require 'lib/initSlider'
spriteanim = require 'spriteanim'
# in the template, but need to require to load them
require 'views/modal/RevertModal'
RootView = require 'views/core/RootView'
ThangComponentsEditView = require 'views/editor/component/ThangComponentsEditView'
ThangTypeVersionsModal = require './ThangTypeVersionsModal'
ThangTypeColorsTabView = require './ThangTypeColorsTabView'
PatchesView = require 'views/editor/PatchesView'
ForkModal = require 'views/editor/ForkModal'
VectorIconSetupModal = require 'views/editor/thang/VectorIconSetupModal'
SaveVersionModal = require 'views/editor/modal/SaveVersionModal'
template = require 'templates/editor/thang/thang-type-edit-view'
storage = require 'core/storage'
ExportThangTypeModal = require './ExportThangTypeModal'
RevertModal = require 'views/modal/RevertModal'
require 'lib/game-libraries'
CENTER = {x: 200, y: 400}
commonTasks = [
'Upload the art.'
'Set up the vector icon.'
]
displayedThangTypeTasks = [
'Configure the idle action.'
'Configure the positions (registration point, etc.).'
'Set shadow diameter to 0 if needed.'
'Set scale to 0.3, 0.5, or whatever is appropriate.'
'Set rotation to isometric if needed.'
'Set accurate Physical size, shape, and default z.'
'Set accurate Collides collision information if needed.'
'Double-check that fixedRotation is accurate, if it collides.'
]
animatedThangTypeTasks = displayedThangTypeTasks.concat [
'Configure the non-idle actions.'
'Configure any per-action registration points needed.'
'Add flipX per action if needed to face to the right.'
'Make sure any death and attack actions do not loop.'
'Add defaultSimlish if needed.'
'Add selection sounds if needed.'
'Add per-action sound triggers.'
'Add team color groups.'
]
containerTasks = displayedThangTypeTasks.concat [
'Select viable terrains if not universal.'
'Set Exists stateless: true if needed.'
]
purchasableTasks = [
'Add a tier, or 10 + desired tier if not ready yet.'
'Add a gem cost.'
'Write a description.'
'Click the Populate i18n button.'
]
defaultTasks =
Unit: commonTasks.concat animatedThangTypeTasks.concat [
'Start a new name category in names.coffee if needed.'
'Set to Allied to correct team (ogres, humans, or neutral).'
'Add AutoTargetsNearest or FightsBack if needed.'
'Add other Components like Shoots or Casts if needed.'
'Configure other Components, like Moves, Attackable, Attacks, etc.'
'Override the HasAPI type if it will not be correctly inferred.'
'Add to Existence System power table.'
]
Hero: commonTasks.concat animatedThangTypeTasks.concat purchasableTasks.concat [
'Set the hero class.'
'Add Extended Hero Name.'
'Add Short Hero Name.'
'Add Hero Gender.'
'Upload Hero Doll Images.'
'Upload Pose Image.'
'Start a new name category in names.coffee.'
'Set up hero stats in Equips, Attackable, Moves.'
'Set Collects collectRange to 2, Sees visualRange to 60.'
'Add any custom hero abilities.'
'Add to ThangTypeConstants hard-coded hero ids/classes list.'
'Add hero gender.'
'Add hero short name.'
]
Floor: commonTasks.concat containerTasks.concat [
'Add 10 x 8.5 snapping.'
'Set fixed rotation.'
'Make sure everything is scaled to tile perfectly.'
'Adjust SingularSprite floor scale list if necessary.'
]
Wall: commonTasks.concat containerTasks.concat [
'Add 4x4 snapping.'
'Set fixed rotation.'
'Set up and tune complicated wall-face actions.'
'Make sure everything is scaled to tile perfectly.'
]
Doodad: commonTasks.concat containerTasks.concat [
'Add to GenerateTerrainModal logic if needed.'
]
Misc: commonTasks.concat [
'Add any misc tasks for this misc ThangType.'
]
Mark: commonTasks.concat [
'Check the animation framerate.'
'Double-check that bottom of mark is just touching registration point.'
]
Item: commonTasks.concat purchasableTasks.concat [
'Set the hero class if class-specific.'
'Upload Paper Doll Images.'
'Configure item stats and abilities.'
]
Missile: commonTasks.concat animatedThangTypeTasks.concat [
'Make sure there is a launch sound trigger.'
'Make sure there is a hit sound trigger.'
'Make sure there is a die animation.'
'Add Arrow, Shell, Beam, or other missile Component.'
'Choose Missile.leadsShots and Missile.shootsAtGround.'
'Choose Moves.maxSpeed and other config.'
'Choose Expires.lifespan config if needed.'
'Set spriteType: singular if needed for proper rendering.'
'Add HasAPI if the missile should show up in findEnemyMissiles.'
]
module.exports = class ThangTypeEditView extends RootView
id: 'thang-type-edit-view'
className: 'editor'
template: template
resolution: 4
scale: 3
mockThang:
health: 10.0
maxHealth: 10.0
hudProperties: ['health']
acts: true
events:
'click #clear-button': 'clearRawData'
'click #upload-button': -> @$el.find('input#real-upload-button').click()
'click #set-vector-icon': 'onClickSetVectorIcon'
'click #animate-to-flash': -> @$el.find('input#real-animate-flash-button').click(),
'change #real-animate-flash-button': 'animateTransformFileChosen'
'change #real-upload-button': 'animationFileChosen'
'change #animations-select': 'showAnimation'
'click #marker-button': 'toggleDots'
'click #stop-button': 'stopAnimation'
'click #play-button': 'playAnimation'
'click #history-button': 'showVersionHistory'
'click li:not(.disabled) > #fork-start-button': 'startForking'
'click #save-button': 'openSaveModal'
'click #patches-tab': -> @patchesView.load()
'click .play-with-level-button': 'onPlayLevel'
'click .play-with-level-parent': 'onPlayLevelSelect'
'keyup .play-with-level-input': 'onPlayLevelKeyUp'
'click li:not(.disabled) > #pop-level-i18n-button': 'onPopulateLevelI18N'
'mousedown #canvas': 'onCanvasMouseDown'
'mouseup #canvas': 'onCanvasMouseUp'
'mousemove #canvas': 'onCanvasMouseMove'
'click #export-sprite-sheet-btn': 'onClickExportSpriteSheetButton'
'click [data-toggle="coco-modal"][data-target="modal/RevertModal"]': 'openRevertModal'
openRevertModal: (e) ->
e.stopPropagation()
@openModalView new RevertModal()
onClickSetVectorIcon: ->
modal = new VectorIconSetupModal({}, @thangType)
@openModalView modal
modal.once 'done', => @treema.set('/', @getThangData())
subscriptions:
'editor:thang-type-color-groups-changed': 'onColorGroupsChanged'
# init / render
constructor: (options, @thangTypeID) ->
super options
@mockThang = $.extend(true, {}, @mockThang)
@thangType = new ThangType(_id: @thangTypeID)
@thangType = @supermodel.loadModel(@thangType).model
@thangType.saveBackups = true
@listenToOnce @thangType, 'sync', ->
@files = @supermodel.loadCollection(new DocumentFiles(@thangType), 'files').model
@updateFileSize()
# @refreshAnimation = _.debounce @refreshAnimation, 500
showLoading: ($el) ->
$el ?= @$el.find('.outer-content')
super($el)
getRenderData: (context={}) ->
context = super(context)
context.thangType = @thangType
context.animations = @getAnimationNames()
context.authorized = not me.get('anonymous')
context.recentlyPlayedLevels = storage.load('recently-played-levels') ? ['items']
context.fileSizeString = @fileSizeString
context
getAnimationNames: ->
_.sortBy _.keys(@thangType.get('actions') or {}), (a) ->
{move: 1, cast: 2, attack: 3, idle: 4, portrait: 6}[a] or 5
afterRender: ->
super()
return unless @supermodel.finished()
@initStage()
@buildTreema()
@initSliders()
@initComponents()
@insertSubView(new ThangTypeColorsTabView(@thangType))
@patchesView = @insertSubView(new PatchesView(@thangType), @$el.find('.patches-view'))
@showReadOnly() if me.get('anonymous')
@updatePortrait()
initComponents: =>
options =
components: @thangType.get('components') ? []
supermodel: @supermodel
@thangComponentEditView = new ThangComponentsEditView options
@listenTo @thangComponentEditView, 'components-changed', @onComponentsChanged
@insertSubView @thangComponentEditView
onComponentsChanged: (components) =>
@thangType.set 'components', components
onColorGroupsChanged: (e) ->
@temporarilyIgnoringChanges = true
@treema.set 'colorGroups', e.colorGroups
@temporarilyIgnoringChanges = false
makeDot: (color) ->
circle = new createjs.Shape()
circle.graphics.beginFill(color).beginStroke('black').drawCircle(0, 0, 5)
circle.scaleY = 0.2
circle.scaleX = 0.5
circle
initStage: ->
canvas = @$el.find('#canvas')
@stage = new createjs.Stage(canvas[0])
@layerAdapter = new LayerAdapter({name:'Default', webGL: true})
@topLayer = new createjs.Container()
@layerAdapter.container.x = @topLayer.x = CENTER.x
@layerAdapter.container.y = @topLayer.y = CENTER.y
@stage.addChild(@layerAdapter.container, @topLayer)
@listenTo @layerAdapter, 'new-spritesheet', @onNewSpriteSheet
@camera?.destroy()
@camera = new Camera canvas
@torsoDot = @makeDot('blue')
@mouthDot = @makeDot('yellow')
@aboveHeadDot = @makeDot('green')
@groundDot = @makeDot('red')
@topLayer.addChild(@groundDot, @torsoDot, @mouthDot, @aboveHeadDot)
@updateGrid()
_.defer @refreshAnimation
@toggleDots(false)
createjs.Ticker.framerate = 30
createjs.Ticker.addEventListener('tick', @stage)
toggleDots: (newShowDots) ->
@showDots = if typeof(newShowDots) is 'boolean' then newShowDots else not @showDots
@updateDots()
updateDots: ->
@topLayer.removeChild(@torsoDot, @mouthDot, @aboveHeadDot, @groundDot)
return unless @currentLank
return unless @showDots
torso = @currentLank.getOffset 'torso'
mouth = @currentLank.getOffset 'mouth'
aboveHead = @currentLank.getOffset 'aboveHead'
@torsoDot.x = torso.x
@torsoDot.y = torso.y
@mouthDot.x = mouth.x
@mouthDot.y = mouth.y
@aboveHeadDot.x = aboveHead.x
@aboveHeadDot.y = aboveHead.y
@topLayer.addChild(@groundDot, @torsoDot, @mouthDot, @aboveHeadDot)
stopAnimation: ->
@currentLank?.queueAction('idle')
playAnimation: ->
@currentLank?.queueAction(@$el.find('#animations-select').val())
updateGrid: ->
grid = new createjs.Container()
line = new createjs.Shape()
width = 1000
line.graphics.beginFill('#666666').drawRect(-width/2, -0.5, width, 0.5)
line.x = CENTER.x
line.y = CENTER.y
y = line.y
step = 10 * @scale
y -= step while y > 0
while y < 500
y += step
newLine = line.clone()
newLine.y = y
grid.addChild(newLine)
x = line.x
x -= step while x > 0
while x < 400
x += step
newLine = line.clone()
newLine.x = x
newLine.rotation = 90
grid.addChild(newLine)
@stage.removeChild(@grid) if @grid
@stage.addChildAt(grid, 0)
@grid = grid
updateSelectBox: ->
names = @getAnimationNames()
select = @$el.find('#animations-select')
return if select.find('option').length is names.length
select.empty()
select.append($('<option></option>').text(name)) for name in names
# upload
animationFileChosen: (e) ->
@file = e.target.files[0]
return unless @file
return unless _.string.endsWith @file.type, 'javascript'
# @$el.find('#upload-button').prop('disabled', true)
@reader = new FileReader()
@reader.onload = @onFileLoad
@reader.readAsText(@file)
onFileLoad: (e) =>
result = @reader.result
parser = new SpriteParser(@thangType)
parser.parse(result)
@treema.set('raw', @thangType.get('raw'))
@updateSelectBox()
@refreshAnimation()
@updateFileSize()
updateFileSize: ->
file = JSON.stringify(@thangType.attributes)
compressed = LZString.compress(file)
size = (file.length / 1024).toFixed(1) + "KB"
compressedSize = (compressed.length / 1024).toFixed(1) + "KB"
gzipCompressedSize = compressedSize * 1.65 # just based on comparing ogre barracks
@fileSizeString = "Size: #{size} (~#{compressedSize} gzipped)"
@$el.find('#thang-type-file-size').text @fileSizeString
# animation select
refreshAnimation: =>
@thangType.resetSpriteSheetCache()
return @showRasterImage() if @thangType.get('raster')
options = @getLankOptions()
console.log 'refresh animation....'
@showAnimation()
@updatePortrait()
showRasterImage: ->
lank = new Lank(@thangType, @getLankOptions())
@showLank(lank)
@updateScale()
onNewSpriteSheet: ->
$('#spritesheets').empty()
for image in @layerAdapter.spriteSheet._images
$('#spritesheets').append(image)
@layerAdapter.container.x = CENTER.x
@layerAdapter.container.y = CENTER.y
@updateScale()
showAnimation: (animationName) ->
animationName = @$el.find('#animations-select').val() unless _.isString animationName
return unless animationName
@mockThang.action = animationName
@showAction(animationName)
@updateRotation()
@updateScale() # must happen after update rotation, because updateRotation calls the sprite update() method.
showMovieClip: (animationName) ->
vectorParser = new SpriteBuilder(@thangType)
movieClip = vectorParser.buildMovieClip(animationName)
return unless movieClip
reg = @thangType.get('positions')?.registration
if reg
movieClip.regX = -reg.x
movieClip.regY = -reg.y
scale = @thangType.get('scale')
if scale
movieClip.scaleX = movieClip.scaleY = scale
@showSprite(movieClip)
getLankOptions: -> {resolutionFactor: @resolution, thang: @mockThang, preloadSounds: false}
showAction: (actionName) ->
options = @getLankOptions()
lank = new Lank(@thangType, options)
@showLank(lank)
lank.queueAction(actionName)
updatePortrait: ->
options = @getLankOptions()
portrait = @thangType.getPortraitImage(options)
return unless portrait
portrait?.attr('id', 'portrait').addClass('img-thumbnail')
portrait.addClass 'img-thumbnail'
$('#portrait').replaceWith(portrait)
showLank: (lank) ->
@clearDisplayObject()
@clearLank()
@layerAdapter.resetSpriteSheet()
@layerAdapter.addLank(lank)
@currentLank = lank
@currentLankOffset = null
showSprite: (sprite) ->
@clearDisplayObject()
@clearLank()
@topLayer.addChild(sprite)
@currentObject = sprite
@updateDots()
clearDisplayObject: ->
@topLayer.removeChild(@currentObject) if @currentObject?
clearLank: ->
@layerAdapter.removeLank(@currentLank) if @currentLank
@currentLank?.destroy()
# sliders
initSliders: ->
@rotationSlider = initSlider $('#rotation-slider', @$el), 50, @updateRotation
@scaleSlider = initSlider $('#scale-slider', @$el), 29, @updateScale
@resolutionSlider = initSlider $('#resolution-slider', @$el), 39, @updateResolution
@healthSlider = initSlider $('#health-slider', @$el), 100, @updateHealth
updateRotation: =>
value = parseInt(180 * (@rotationSlider.slider('value') - 50) / 50)
@$el.find('.rotation-label').text " #{value}° "
if @currentLank
@currentLank.rotation = value
@currentLank.update(true)
updateScale: =>
scaleValue = (@scaleSlider.slider('value') + 1) / 10
@layerAdapter.container.scaleX = @layerAdapter.container.scaleY = @topLayer.scaleX = @topLayer.scaleY = scaleValue
fixed = scaleValue.toFixed(1)
@scale = scaleValue
@$el.find('.scale-label').text " #{fixed}x "
@updateGrid()
updateResolution: =>
value = (@resolutionSlider.slider('value') + 1) / 10
fixed = value.toFixed(1)
@$el.find('.resolution-label').text " #{fixed}x "
@resolution = value
@refreshAnimation()
updateHealth: =>
value = parseInt((@healthSlider.slider('value')) / 10)
@$el.find('.health-label').text " #{value}hp "
@mockThang.health = value
@currentLank?.update()
# save
saveNewThangType: (e) ->
newThangType = if e.major then @thangType.cloneNewMajorVersion() else @thangType.cloneNewMinorVersion()
newThangType.set('commitMessage', e.commitMessage)
newThangType.updateI18NCoverage() if newThangType.get('i18nCoverage')
res = newThangType.save(null, {type: 'POST'}) # Override PUT so we can trigger postNewVersion logic
return unless res
modal = $('#save-version-modal')
@enableModalInProgress(modal)
res.error =>
@disableModalInProgress(modal)
res.success =>
url = "/editor/thang/#{newThangType.get('slug') or newThangType.id}"
portraitSource = null
if @thangType.get('raster')
#image = @currentLank.sprite.image # Doesn't work?
image = @currentLank.sprite.spriteSheet._images[0]
portraitSource = imageToPortrait image
# bit of a hacky way to get that portrait
success = =>
@thangType.clearBackup()
document.location.href = url
newThangType.uploadGenericPortrait success, portraitSource
clearRawData: ->
@thangType.resetRawData()
@thangType.set 'actions', undefined
@clearDisplayObject()
@treema.set('/', @getThangData())
getThangData: ->
data = $.extend(true, {}, @thangType.attributes)
data = _.pick data, (value, key) => not (key in ['components'])
buildTreema: ->
data = @getThangData()
schema = _.cloneDeep ThangType.schema
schema.properties = _.pick schema.properties, (value, key) => not (key in ['components'])
options =
data: data
schema: schema
files: @files
filePath: "db/thang.type/#{@thangType.get('original')}"
readOnly: me.get('anonymous')
callbacks:
change: @pushChangesToPreview
select: @onSelectNode
el = @$el.find('#thang-type-treema')
@treema = @$el.find('#thang-type-treema').treema(options)
@treema.build()
@lastKind = data.kind
pushChangesToPreview: =>
return if @temporarilyIgnoringChanges
keysProcessed = {}
for key of @thangType.attributes
keysProcessed[key] = true
continue if key is 'components'
@thangType.set(key, @treema.data[key])
for key, value of @treema.data when not keysProcessed[key]
@thangType.set(key, value)
@updateSelectBox()
@refreshAnimation()
@updateDots()
@updatePortrait()
if (kind = @treema.data.kind) isnt @lastKind
@lastKind = kind
Backbone.Mediator.publish 'editor:thang-type-kind-changed', kind: kind
if kind in ['Doodad', 'Floor', 'Wall'] and not @treema.data.terrains
@treema.set '/terrains', ['Grass', 'Dungeon', 'Indoor', 'Desert', 'Mountain', 'Glacier', 'Volcano'] # So editors know to set them.
if not @treema.data.tasks
@treema.set '/tasks', (name: t for t in defaultTasks[kind])
onSelectNode: (e, selected) =>
selected = selected[0]
@topLayer.removeChild(@boundsBox) if @boundsBox
return @stopShowingSelectedNode() if not selected
path = selected.getPath()
parts = path.split('/')
return @stopShowingSelectedNode() unless parts.length >= 4 and _.string.startsWith path, '/raw/'
key = parts[3]
type = parts[2]
vectorParser = new SpriteBuilder(@thangType)
obj = vectorParser.buildMovieClip(key) if type is 'animations'
obj = vectorParser.buildContainerFromStore(key) if type is 'containers'
obj = vectorParser.buildShapeFromStore(key) if type is 'shapes'
bounds = obj?.bounds or obj?.nominalBounds
if bounds
@boundsBox = new createjs.Shape()
@boundsBox.graphics.beginFill('#aaaaaa').beginStroke('black').drawRect(bounds.x, bounds.y, bounds.width, bounds.height)
@topLayer.addChild(@boundsBox)
obj.regX = @boundsBox.regX = bounds.x + bounds.width / 2
obj.regY = @boundsBox.regY = bounds.y + bounds.height / 2
@showSprite(obj) if obj
@showingSelectedNode = true
@currentLank?.destroy()
@currentLank = null
@updateScale()
@grid.alpha = 0.0
stopShowingSelectedNode: ->
return unless @showingSelectedNode
@grid.alpha = 1.0
@showAnimation()
@showingSelectedNode = false
showVersionHistory: (e) ->
@openModalView new ThangTypeVersionsModal thangType: @thangType, @thangTypeID
onPopulateLevelI18N: ->
@thangType.populateI18N()
_.delay((-> document.location.reload()), 500)
openSaveModal: ->
modal = new SaveVersionModal model: @thangType
@openModalView modal
@listenToOnce modal, 'save-new-version', @saveNewThangType
@listenToOnce modal, 'hidden', -> @stopListening(modal)
startForking: (e) ->
@openModalView new ForkModal model: @thangType, editorPath: 'thang'
onPlayLevelSelect: (e) ->
if @childWindow and not @childWindow.closed
# We already have a child window open, so we don't need to ask for a level; we'll use its existing level.
e.stopImmediatePropagation()
@onPlayLevel e
_.defer -> $('.play-with-level-input').focus()
onPlayLevelKeyUp: (e) ->
return unless e.keyCode is 13 # return
input = @$el.find('.play-with-level-input')
input.parents('.dropdown').find('.play-with-level-parent').dropdown('toggle')
level = _.string.slugify input.val()
return unless level
@onPlayLevel null, level
recentlyPlayedLevels = storage.load('recently-played-levels') ? []
recentlyPlayedLevels.push level
storage.save 'recently-played-levels', recentlyPlayedLevels
onPlayLevel: (e, level=null) ->
level ?= $(e.target).data('level')
level = _.string.slugify level
if @childWindow and not @childWindow.closed
# Reset the LevelView's world, but leave the rest of the state alone
@childWindow.Backbone.Mediator.publish 'level:reload-thang-type', thangType: @thangType
else
# Create a new Window with a blank LevelView
scratchLevelID = level + '?dev=true'
if me.get('name') is 'PI:NAME:<NAME>END_PI'
@childWindow = window.open("/play/level/#{scratchLevelID}", 'child_window', 'width=2560,height=1080,left=0,top=-1600,location=1,menubar=1,scrollbars=1,status=0,titlebar=1,toolbar=1', true)
else
@childWindow = window.open("/play/level/#{scratchLevelID}", 'child_window', 'width=1024,height=560,left=10,top=10,location=0,menubar=0,scrollbars=0,status=0,titlebar=0,toolbar=0', true)
@childWindow.focus()
# Canvas mouse drag handlers
onCanvasMouseMove: (e) ->
return unless p1 = @canvasDragStart
p2 = x: e.offsetX, y: e.offsetY
offset = x: p2.x - p1.x, y: p2.y - p1.y
@currentLank.sprite.x = @currentLankOffset.x + offset.x / @scale
@currentLank.sprite.y = @currentLankOffset.y + offset.y / @scale
@canvasDragOffset = offset
onCanvasMouseDown: (e) ->
return unless @currentLank
@canvasDragStart = x: e.offsetX, y: e.offsetY
@currentLankOffset ?= x: @currentLank.sprite.x, y: @currentLank.sprite.y
onCanvasMouseUp: (e) ->
@canvasDragStart = null
return unless @canvasDragOffset
return unless node = @treema.getLastSelectedTreema()
offset = node.get '/'
offset.x += Math.round @canvasDragOffset.x
offset.y += Math.round @canvasDragOffset.y
@canvasDragOffset = null
node.set '/', offset
onClickExportSpriteSheetButton: ->
modal = new ExportThangTypeModal({}, @thangType)
@openModalView(modal)
animateTransformFileChosen: (e) ->
animateFile = e.target.files[0]
return unless animateFile
return unless _.string.endsWith animateFile.type, 'javascript'
animateReader = new FileReader()
animateReader.onload = @onAnimateFileLoad
animateReader.readAsText(animateFile)
onAnimateFileLoad: (e) ->
animateText = e.target.result
flashText = spriteanim(animateText)
data = new Blob([flashText], {type: 'text/plain'});
# Prevents memory leaks.
if @flashFile != null
window.URL.revokeObjectURL(@flashFile)
@flashFile = window.URL.createObjectURL(data)
fileName = prompt("What do you want to name the file? '.js' will be added to the end.")
if fileName
# Create the file to download.
el = document.createElement('a')
el.href = @flashFile
el.setAttribute('download', "#{fileName}.js")
el.style.display = 'none'
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
destroy: ->
@camera?.destroy()
super()
imageToPortrait = (img) ->
canvas = document.createElement('canvas')
canvas.width = 100
canvas.height = 100
ctx = canvas.getContext('2d')
scaleX = 100 / img.width
scaleY = 100 / img.height
ctx.scale scaleX, scaleY
ctx.drawImage img, 0, 0
canvas.toDataURL('image/png')
|
[
{
"context": "# Copyright 2013 Andrey Sitnik <andrey@sitnik.ru>,\n# sponsored by Evil Martians.",
"end": 30,
"score": 0.9998761415481567,
"start": 17,
"tag": "NAME",
"value": "Andrey Sitnik"
},
{
"context": "# Copyright 2013 Andrey Sitnik <andrey@sitnik.ru>,\n# sponsored by Evil Mart... | test/coffee/autoprefixer.coffee | MiguelCastillo/Brackets-InteractiveLinter | 86 | # Copyright 2013 Andrey Sitnik <andrey@sitnik.ru>,
# sponsored by Evil Martians.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http:#www.gnu.org/licenses/>.
parse = require('css-parse')
stringify = require('css-stringify')
Browsers = require('./autoprefixer/browsers')
Prefixes = require('./autoprefixer/prefixes')
CSS = require('./autoprefixer/css')
inspectCache = null
# Parse CSS and add prefixed properties and values by Can I Use database
# for actual browsers.
#
# var prefixed = autoprefixer('> 1%', 'ie 8').compile(css);
#
# If you want to combine Autoprefixer with another Rework filters,
# you can use it as separated filter:
#
# rework(css).
# use(autoprefixer('last 1 version').rework).
# toString();
autoprefixer = (reqs...) ->
if reqs.length == 1 and reqs[0] instanceof Array
reqs = reqs[0]
else if reqs.length == 0 or (reqs.length == 1 and not reqs[0]?)
reqs = undefined
reqs = autoprefixer.default unless reqs?
browsers = new Browsers(autoprefixer.data.browsers, reqs)
prefixes = new Prefixes(autoprefixer.data.prefixes, browsers)
new Autoprefixer(prefixes, autoprefixer.data)
autoprefixer.data =
browsers: require('../data/browsers')
prefixes: require('../data/prefixes')
class Autoprefixer
constructor: (@prefixes, @data) ->
@browsers = @prefixes.browsers.selected
# Parse CSS and add prefixed properties for selected browsers
compile: (str) ->
nodes = @catchParseErrors => parse(@removeBadComments str)
@rework(nodes.stylesheet)
stringify(nodes)
# Return Rework filter, which will add necessary prefixes
rework: (stylesheet) =>
css = new CSS(stylesheet)
@prefixes.processor.add(css)
@prefixes.processor.remove(css)
# Return string, what browsers selected and whar prefixes will be added
inspect: ->
inspectCache ||= require('./autoprefixer/inspect')
inspectCache(@prefixes)
# Catch errors from CSS parsing and throw readable message
catchParseErrors: (callback) ->
try
callback()
catch e
error = new Error("Can't parse CSS: " + e.message)
error.stack = e.stack
error.css = true
throw error
# Remove /**/ in non-IE6 declaration, until CSS parser has this issue
removeBadComments: (css) ->
css.replace(/\/\*[^\*]*\}[^\*]*\*\//g, '')
# Autoprefixer default browsers
autoprefixer.default = ['> 1%', 'last 2 versions', 'ff 17', 'opera 12.1']
# Lazy load for Autoprefixer with default browsers
autoprefixer.loadDefault = ->
@defaultCache ||= autoprefixer(@default)
# Compile with default Autoprefixer
autoprefixer.compile = (str) ->
@loadDefault().compile(str)
# Rework with default Autoprefixer
autoprefixer.rework = (stylesheet) ->
@loadDefault().rework(stylesheet)
# Inspect with default Autoprefixer
autoprefixer.inspect = ->
@loadDefault().inspect()
module.exports = autoprefixer | 122897 | # Copyright 2013 <NAME> <<EMAIL>>,
# sponsored by <NAME>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http:#www.gnu.org/licenses/>.
parse = require('css-parse')
stringify = require('css-stringify')
Browsers = require('./autoprefixer/browsers')
Prefixes = require('./autoprefixer/prefixes')
CSS = require('./autoprefixer/css')
inspectCache = null
# Parse CSS and add prefixed properties and values by Can I Use database
# for actual browsers.
#
# var prefixed = autoprefixer('> 1%', 'ie 8').compile(css);
#
# If you want to combine Autoprefixer with another Rework filters,
# you can use it as separated filter:
#
# rework(css).
# use(autoprefixer('last 1 version').rework).
# toString();
autoprefixer = (reqs...) ->
if reqs.length == 1 and reqs[0] instanceof Array
reqs = reqs[0]
else if reqs.length == 0 or (reqs.length == 1 and not reqs[0]?)
reqs = undefined
reqs = autoprefixer.default unless reqs?
browsers = new Browsers(autoprefixer.data.browsers, reqs)
prefixes = new Prefixes(autoprefixer.data.prefixes, browsers)
new Autoprefixer(prefixes, autoprefixer.data)
autoprefixer.data =
browsers: require('../data/browsers')
prefixes: require('../data/prefixes')
class Autoprefixer
constructor: (@prefixes, @data) ->
@browsers = @prefixes.browsers.selected
# Parse CSS and add prefixed properties for selected browsers
compile: (str) ->
nodes = @catchParseErrors => parse(@removeBadComments str)
@rework(nodes.stylesheet)
stringify(nodes)
# Return Rework filter, which will add necessary prefixes
rework: (stylesheet) =>
css = new CSS(stylesheet)
@prefixes.processor.add(css)
@prefixes.processor.remove(css)
# Return string, what browsers selected and whar prefixes will be added
inspect: ->
inspectCache ||= require('./autoprefixer/inspect')
inspectCache(@prefixes)
# Catch errors from CSS parsing and throw readable message
catchParseErrors: (callback) ->
try
callback()
catch e
error = new Error("Can't parse CSS: " + e.message)
error.stack = e.stack
error.css = true
throw error
# Remove /**/ in non-IE6 declaration, until CSS parser has this issue
removeBadComments: (css) ->
css.replace(/\/\*[^\*]*\}[^\*]*\*\//g, '')
# Autoprefixer default browsers
autoprefixer.default = ['> 1%', 'last 2 versions', 'ff 17', 'opera 12.1']
# Lazy load for Autoprefixer with default browsers
autoprefixer.loadDefault = ->
@defaultCache ||= autoprefixer(@default)
# Compile with default Autoprefixer
autoprefixer.compile = (str) ->
@loadDefault().compile(str)
# Rework with default Autoprefixer
autoprefixer.rework = (stylesheet) ->
@loadDefault().rework(stylesheet)
# Inspect with default Autoprefixer
autoprefixer.inspect = ->
@loadDefault().inspect()
module.exports = autoprefixer | true | # Copyright 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>,
# sponsored by PI:NAME:<NAME>END_PI.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http:#www.gnu.org/licenses/>.
parse = require('css-parse')
stringify = require('css-stringify')
Browsers = require('./autoprefixer/browsers')
Prefixes = require('./autoprefixer/prefixes')
CSS = require('./autoprefixer/css')
inspectCache = null
# Parse CSS and add prefixed properties and values by Can I Use database
# for actual browsers.
#
# var prefixed = autoprefixer('> 1%', 'ie 8').compile(css);
#
# If you want to combine Autoprefixer with another Rework filters,
# you can use it as separated filter:
#
# rework(css).
# use(autoprefixer('last 1 version').rework).
# toString();
autoprefixer = (reqs...) ->
if reqs.length == 1 and reqs[0] instanceof Array
reqs = reqs[0]
else if reqs.length == 0 or (reqs.length == 1 and not reqs[0]?)
reqs = undefined
reqs = autoprefixer.default unless reqs?
browsers = new Browsers(autoprefixer.data.browsers, reqs)
prefixes = new Prefixes(autoprefixer.data.prefixes, browsers)
new Autoprefixer(prefixes, autoprefixer.data)
autoprefixer.data =
browsers: require('../data/browsers')
prefixes: require('../data/prefixes')
class Autoprefixer
constructor: (@prefixes, @data) ->
@browsers = @prefixes.browsers.selected
# Parse CSS and add prefixed properties for selected browsers
compile: (str) ->
nodes = @catchParseErrors => parse(@removeBadComments str)
@rework(nodes.stylesheet)
stringify(nodes)
# Return Rework filter, which will add necessary prefixes
rework: (stylesheet) =>
css = new CSS(stylesheet)
@prefixes.processor.add(css)
@prefixes.processor.remove(css)
# Return string, what browsers selected and whar prefixes will be added
inspect: ->
inspectCache ||= require('./autoprefixer/inspect')
inspectCache(@prefixes)
# Catch errors from CSS parsing and throw readable message
catchParseErrors: (callback) ->
try
callback()
catch e
error = new Error("Can't parse CSS: " + e.message)
error.stack = e.stack
error.css = true
throw error
# Remove /**/ in non-IE6 declaration, until CSS parser has this issue
removeBadComments: (css) ->
css.replace(/\/\*[^\*]*\}[^\*]*\*\//g, '')
# Autoprefixer default browsers
autoprefixer.default = ['> 1%', 'last 2 versions', 'ff 17', 'opera 12.1']
# Lazy load for Autoprefixer with default browsers
autoprefixer.loadDefault = ->
@defaultCache ||= autoprefixer(@default)
# Compile with default Autoprefixer
autoprefixer.compile = (str) ->
@loadDefault().compile(str)
# Rework with default Autoprefixer
autoprefixer.rework = (stylesheet) ->
@loadDefault().rework(stylesheet)
# Inspect with default Autoprefixer
autoprefixer.inspect = ->
@loadDefault().inspect()
module.exports = autoprefixer |
[
{
"context": ", (i) ->\n payloads[\"#{i}\"] =\n key: \"#{i}\"\n value: i * 100\n data: i % 2\n ",
"end": 421,
"score": 0.7109518647193909,
"start": 420,
"tag": "KEY",
"value": "i"
}
] | test/test-raceconditions.coffee | tc-gaurav/gearman-node | 8 | assert = require 'assert'
Gearman = require('../index').Gearman
Client = require('../index').Client
Worker = require('../index').Worker
_ = require 'underscore'
async = require 'async'
options =
host: 'localhost'
port: 4730
debug: false
describe 'slam it', ->
it 'can handle a ton of jobs', (done) ->
@timeout 100000
payloads = {}
_.each [1..100], (i) ->
payloads["#{i}"] =
key: "#{i}"
value: i * 100
data: i % 2
warning: "job #{i} warning"
fail: (Math.random() > 0.5)
duration: (Math.random() * 2000)
worker_fn = (payload, worker) ->
payload = JSON.parse(payload)
assert.equal payload.value, payloads[payload.key].value, "worker #{payload.key} received bad payload.value"
worker.data "#{payload.data}"
setTimeout () ->
worker.done(if payload.fail then payload.warning else null)
, payload.duration
workers = []
workers.push(new Worker 'slammer', worker_fn, options) for i in [1..25]
client = new Client options
async.forEach _(payloads).keys(), (key, cb_fe) ->
payload = payloads[key]
client.submitJob('slammer', JSON.stringify(payload)).on 'data', (handle, data) ->
assert.equal data, payload.data, "expected job #{key} to produce #{payload.data}, got #{data}"
.on 'warning', (handle, warning) ->
assert.equal warning, payload.warning, "expected job #{key} to produce warning #{payload.warning}, got #{warning}"
.on 'fail', (handle) ->
assert payload.fail, 'did not expect job to fail'
cb_fe()
.on 'complete', (handle, data) ->
assert (not payload.fail), 'expected job to fail'
cb_fe()
, () ->
worker.disconnect() for worker in workers
client.disconnect()
done()
| 17194 | assert = require 'assert'
Gearman = require('../index').Gearman
Client = require('../index').Client
Worker = require('../index').Worker
_ = require 'underscore'
async = require 'async'
options =
host: 'localhost'
port: 4730
debug: false
describe 'slam it', ->
it 'can handle a ton of jobs', (done) ->
@timeout 100000
payloads = {}
_.each [1..100], (i) ->
payloads["#{i}"] =
key: "#{<KEY>}"
value: i * 100
data: i % 2
warning: "job #{i} warning"
fail: (Math.random() > 0.5)
duration: (Math.random() * 2000)
worker_fn = (payload, worker) ->
payload = JSON.parse(payload)
assert.equal payload.value, payloads[payload.key].value, "worker #{payload.key} received bad payload.value"
worker.data "#{payload.data}"
setTimeout () ->
worker.done(if payload.fail then payload.warning else null)
, payload.duration
workers = []
workers.push(new Worker 'slammer', worker_fn, options) for i in [1..25]
client = new Client options
async.forEach _(payloads).keys(), (key, cb_fe) ->
payload = payloads[key]
client.submitJob('slammer', JSON.stringify(payload)).on 'data', (handle, data) ->
assert.equal data, payload.data, "expected job #{key} to produce #{payload.data}, got #{data}"
.on 'warning', (handle, warning) ->
assert.equal warning, payload.warning, "expected job #{key} to produce warning #{payload.warning}, got #{warning}"
.on 'fail', (handle) ->
assert payload.fail, 'did not expect job to fail'
cb_fe()
.on 'complete', (handle, data) ->
assert (not payload.fail), 'expected job to fail'
cb_fe()
, () ->
worker.disconnect() for worker in workers
client.disconnect()
done()
| true | assert = require 'assert'
Gearman = require('../index').Gearman
Client = require('../index').Client
Worker = require('../index').Worker
_ = require 'underscore'
async = require 'async'
options =
host: 'localhost'
port: 4730
debug: false
describe 'slam it', ->
it 'can handle a ton of jobs', (done) ->
@timeout 100000
payloads = {}
_.each [1..100], (i) ->
payloads["#{i}"] =
key: "#{PI:KEY:<KEY>END_PI}"
value: i * 100
data: i % 2
warning: "job #{i} warning"
fail: (Math.random() > 0.5)
duration: (Math.random() * 2000)
worker_fn = (payload, worker) ->
payload = JSON.parse(payload)
assert.equal payload.value, payloads[payload.key].value, "worker #{payload.key} received bad payload.value"
worker.data "#{payload.data}"
setTimeout () ->
worker.done(if payload.fail then payload.warning else null)
, payload.duration
workers = []
workers.push(new Worker 'slammer', worker_fn, options) for i in [1..25]
client = new Client options
async.forEach _(payloads).keys(), (key, cb_fe) ->
payload = payloads[key]
client.submitJob('slammer', JSON.stringify(payload)).on 'data', (handle, data) ->
assert.equal data, payload.data, "expected job #{key} to produce #{payload.data}, got #{data}"
.on 'warning', (handle, warning) ->
assert.equal warning, payload.warning, "expected job #{key} to produce warning #{payload.warning}, got #{warning}"
.on 'fail', (handle) ->
assert payload.fail, 'did not expect job to fail'
cb_fe()
.on 'complete', (handle, data) ->
assert (not payload.fail), 'expected job to fail'
cb_fe()
, () ->
worker.disconnect() for worker in workers
client.disconnect()
done()
|
[
{
"context": "ect_abspath 'db/datamill.icql'\n default_key: '^line'\n default_dest: 'main'\n default_realm: '",
"end": 3951,
"score": 0.8876028656959534,
"start": 3945,
"tag": "KEY",
"value": "'^line"
}
] | src/main.coffee | loveencounterflow/datamill | 0 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'DATAMILL/MAIN'
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
info = CND.get_logger 'info', badge
urge = CND.get_logger 'urge', badge
help = CND.get_logger 'help', badge
whisper = CND.get_logger 'whisper', badge
echo = CND.echo.bind CND
{ jr
assign } = CND
#...........................................................................................................
first = Symbol 'first'
last = Symbol 'last'
MIRAGE = require 'mkts-mirage'
#...........................................................................................................
SPX = require './steampipes-extra'
{ $
$watch
$async } = SPX.export()
#...........................................................................................................
DATOM = require 'datom'
{ VNR } = DATOM
{ freeze
thaw
new_datom
is_stamped
select
stamp } = DATOM.export()
#...........................................................................................................
@types = require './types'
{ isa
validate
declare
first_of
last_of
size_of
type_of } = @types
#...........................................................................................................
H = require './helpers'
{ cwd_abspath
cwd_relpath
here_abspath
project_abspath } = H
DATAMILL = @
#===========================================================================================================
#
#-----------------------------------------------------------------------------------------------------------
@run_phase = ( S, settings, transform ) -> new Promise ( resolve, reject ) =>
defaults = { from_realm: S.mirage.default_realm, }
settings = { defaults..., settings..., }
phase_name = S.control.active_phase
validate.datamill_run_phase_settings settings
#.........................................................................................................
# debug 'µ33344', jr S
# debug 'µ33344', jr settings
# source = H.new_db_source S
# pipeline = []
# pipeline.push source
# pipeline.push transform
# pipeline.push H.$feed_db S
# pipeline.push SPX.$drain => resolve()
# R = SPX.pull pipeline...
source = SPX.new_push_source()
pipeline = []
pipeline.push source
pipeline.push transform
pipeline.push SPX.$show { title: "^run_phase@443^ (#{phase_name})", }
pipeline.push H.$feed_db S
pipeline.push SPX.$drain => resolve()
R = SPX.pull pipeline...
H.feed_source S, source, settings.from_realm
return null
#-----------------------------------------------------------------------------------------------------------
### TAINT consider to use dedicated DB module akin to mkts-mirage/src/db.coffee ###
@_create_udfs = ( mirage ) ->
db = mirage.db
### Placeholder function re-defined by `H.copy_realm()`: ###
db.$.function 'datamill_copy_realm_select', { deterministic: false, varargs: false }, ( row ) -> true
return null
#-----------------------------------------------------------------------------------------------------------
@create = ( settings ) ->
### TAINT set active realm ###
defaults =
file_path: null
# db_path: ':memory:'
db_path: H.project_abspath 'db/datamill.db'
icql_path: H.project_abspath 'db/datamill.icql'
default_key: '^line'
default_dest: 'main'
default_realm: 'input'
clear: true
#.........................................................................................................
settings = { defaults..., settings..., }
mirage = await MIRAGE.create settings
#.........................................................................................................
R =
mirage: mirage
control:
active_phase: null
queue: [] ### A queue for flow control messages ###
reprise_nr: 1
reprise:
start_vnr: null
stop_vnr: null
phase: null ### name of phase that queued control messages ###
#.........................................................................................................
### TAINT consider to use dedicated DB module akin to mkts-mirage/src/db.coffee ###
@_create_udfs mirage
return R
#-----------------------------------------------------------------------------------------------------------
@_set_active_phase = ( S, phase_name ) => S.control.active_phase = phase_name
@_cancel_active_phase = ( S ) => S.control.active_phase = null
@_length_of_control_queue = ( S ) => S.control.queue.length
@_control_queue_has_messages = ( S ) => ( @_length_of_control_queue S ) > 0
@_next_control_message_is_from = ( S, phase_name ) => S.control.queue[ 0 ]?.phase is phase_name
@_is_reprising = ( S ) => S.control.reprise.phase?
#-----------------------------------------------------------------------------------------------------------
@_set_to_reprising = ( S, message ) =>
validate.datamill_reprising_message message
assign S.control.reprise.phase, message
S.control.reprise_nr += +1
return null
#-----------------------------------------------------------------------------------------------------------
@_conclude_current_reprise = ( S ) =>
S.control.reprise[ key ] = null for key of S.control.reprise
return null
#-----------------------------------------------------------------------------------------------------------
@_pluck_next_control_message = ( S ) =>
throw new Error "µ11092 queue is empty" unless S.control.queue.length > 0
message = S.control.queue.shift()
assign S.control.reprise, message
return message
#-----------------------------------------------------------------------------------------------------------
@reprise = ( S, region ) =>
validate.datamill_inclusive_region region
validate.nonempty_text S.control.active_phase
### TAINT use explicit datatype to test for additional condition ###
validate.nonempty_text region.ref
{ first_vnr
last_vnr
ref } = region
S.control.queue.push new_datom '~reprise', { first_vnr, last_vnr, phase: S.control.active_phase, ref, }
return null
#-----------------------------------------------------------------------------------------------------------
@render_html = ( S, settings ) -> new Promise ( resolve, reject ) =>
defaults = { phase_names: [ './900-render-html', ], }
settings = { defaults..., settings..., }
resolve await @parse_document S, settings
#-----------------------------------------------------------------------------------------------------------
@parse_document = ( S, settings ) -> new Promise ( resolve, reject ) =>
defaults =
quiet: false
### TAINT use globbing instead of enumeration ###
phase_names: H.get_phase_names S
settings = { defaults..., settings..., }
debug '^44553^', settings.phase_names
validate.datamill_parse_document_settings settings
#.........................................................................................................
msg_1 = ->
return if settings.quiet
nrs_txt = CND.reverse CND.yellow " r#{S.control.reprise_nr} p#{pass} "
help 'µ55567 ' + nrs_txt + ( CND.lime " phase #{phase_name} " )
#.........................................................................................................
msg_2 = ( phase_name ) ->
return if settings.quiet
nrs_txt = CND.reverse CND.yellow " r#{S.control.reprise_nr} "
info 'µ22872', nrs_txt + CND.blue " finished reprise for #{phase_name}"
info()
#.........................................................................................................
msg_2a = ( phase_name ) ->
return if settings.quiet
info 'µ22872', CND.blue "continuing without limits"
info()
#.........................................................................................................
msg_3 = ( message ) ->
return if settings.quiet
nrs_txt = CND.reverse CND.yellow " r#{S.control.reprise_nr} "
info()
info 'µ33324', nrs_txt + CND.blue " reprise for #{message.phase} with fragment #{jr message.first_vnr} <= vnr <= #{jr message.last_vnr} (ref: #{message.ref})"
#.........................................................................................................
loop
try
# ### TAINT use API ###
# S.confine_to = null
# S.confine_from_phase = null
for phase_name in settings.phase_names
@_set_active_phase S, phase_name
# length_of_queue = @_length_of_control_queue S
phase = require phase_name
pass = 1
msg_1()
await @run_phase S, ( phase.settings ? null ), ( phase.$transform S )
#...................................................................................................
if S.control.reprise.phase is phase_name
### Conclude reprise; continue with upcoming phase and entire document ###
### TAINT do we have to stack boundaries? ###
msg_2 phase_name
@_conclude_current_reprise S
#...................................................................................................
if @_next_control_message_is_from S, phase_name
throw @_pluck_next_control_message S
# msg_2a() unless @_control_queue_has_messages S
#...................................................................................................
if H.repeat_phase S, phase
throw new Error "µ33443 phase repeating not implemented (#{rpr phase_name})"
@_cancel_active_phase S
#.......................................................................................................
catch message
throw message unless ( select message, '~reprise' )
@_set_to_reprising S, message
msg_3 message
### TAINT use API ###
continue
break
#.........................................................................................................
resolve()
#.........................................................................................................
return null
#-----------------------------------------------------------------------------------------------------------
@_demo_list_html_rows = ( S ) -> new Promise ( resolve ) =>
#.......................................................................................................
pipeline = []
pipeline.push H.new_db_source S, 'html'
pipeline.push SPX.$show()
pipeline.push SPX.$drain -> resolve()
SPX.pull pipeline...
#-----------------------------------------------------------------------------------------------------------
@_demo = ->
await do => new Promise ( resolve ) =>
#.......................................................................................................
settings =
# file_path: project_abspath 'src/tests/demo-short-headlines.md'
# file_path: project_abspath 'src/tests/demo.md'
file_path: project_abspath 'src/tests/demo-medium.md'
# file_path: project_abspath 'src/tests/demo-simple-paragraphs.md'
#.......................................................................................................
help "using database at #{settings.db_path}"
datamill = await DATAMILL.create settings
# datamill.mirage.dbw.$.run "drop index main_pk;" ### TAINT for testing only ###
quiet = false
quiet = true
await DATAMILL.parse_document datamill, { quiet, }
await @render_html datamill, { quiet, }
# await @_demo_list_html_rows datamill
#.......................................................................................................
await H.show_overview datamill
await H.show_html datamill
HTML = require './900-render-html'
await HTML.write_to_file datamill
resolve()
return null
return null
############################################################################################################
if module is require.main then do =>
await DATAMILL._demo()
| 143471 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'DATAMILL/MAIN'
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
info = CND.get_logger 'info', badge
urge = CND.get_logger 'urge', badge
help = CND.get_logger 'help', badge
whisper = CND.get_logger 'whisper', badge
echo = CND.echo.bind CND
{ jr
assign } = CND
#...........................................................................................................
first = Symbol 'first'
last = Symbol 'last'
MIRAGE = require 'mkts-mirage'
#...........................................................................................................
SPX = require './steampipes-extra'
{ $
$watch
$async } = SPX.export()
#...........................................................................................................
DATOM = require 'datom'
{ VNR } = DATOM
{ freeze
thaw
new_datom
is_stamped
select
stamp } = DATOM.export()
#...........................................................................................................
@types = require './types'
{ isa
validate
declare
first_of
last_of
size_of
type_of } = @types
#...........................................................................................................
H = require './helpers'
{ cwd_abspath
cwd_relpath
here_abspath
project_abspath } = H
DATAMILL = @
#===========================================================================================================
#
#-----------------------------------------------------------------------------------------------------------
@run_phase = ( S, settings, transform ) -> new Promise ( resolve, reject ) =>
defaults = { from_realm: S.mirage.default_realm, }
settings = { defaults..., settings..., }
phase_name = S.control.active_phase
validate.datamill_run_phase_settings settings
#.........................................................................................................
# debug 'µ33344', jr S
# debug 'µ33344', jr settings
# source = H.new_db_source S
# pipeline = []
# pipeline.push source
# pipeline.push transform
# pipeline.push H.$feed_db S
# pipeline.push SPX.$drain => resolve()
# R = SPX.pull pipeline...
source = SPX.new_push_source()
pipeline = []
pipeline.push source
pipeline.push transform
pipeline.push SPX.$show { title: "^run_phase@443^ (#{phase_name})", }
pipeline.push H.$feed_db S
pipeline.push SPX.$drain => resolve()
R = SPX.pull pipeline...
H.feed_source S, source, settings.from_realm
return null
#-----------------------------------------------------------------------------------------------------------
### TAINT consider to use dedicated DB module akin to mkts-mirage/src/db.coffee ###
@_create_udfs = ( mirage ) ->
db = mirage.db
### Placeholder function re-defined by `H.copy_realm()`: ###
db.$.function 'datamill_copy_realm_select', { deterministic: false, varargs: false }, ( row ) -> true
return null
#-----------------------------------------------------------------------------------------------------------
@create = ( settings ) ->
### TAINT set active realm ###
defaults =
file_path: null
# db_path: ':memory:'
db_path: H.project_abspath 'db/datamill.db'
icql_path: H.project_abspath 'db/datamill.icql'
default_key: <KEY>'
default_dest: 'main'
default_realm: 'input'
clear: true
#.........................................................................................................
settings = { defaults..., settings..., }
mirage = await MIRAGE.create settings
#.........................................................................................................
R =
mirage: mirage
control:
active_phase: null
queue: [] ### A queue for flow control messages ###
reprise_nr: 1
reprise:
start_vnr: null
stop_vnr: null
phase: null ### name of phase that queued control messages ###
#.........................................................................................................
### TAINT consider to use dedicated DB module akin to mkts-mirage/src/db.coffee ###
@_create_udfs mirage
return R
#-----------------------------------------------------------------------------------------------------------
@_set_active_phase = ( S, phase_name ) => S.control.active_phase = phase_name
@_cancel_active_phase = ( S ) => S.control.active_phase = null
@_length_of_control_queue = ( S ) => S.control.queue.length
@_control_queue_has_messages = ( S ) => ( @_length_of_control_queue S ) > 0
@_next_control_message_is_from = ( S, phase_name ) => S.control.queue[ 0 ]?.phase is phase_name
@_is_reprising = ( S ) => S.control.reprise.phase?
#-----------------------------------------------------------------------------------------------------------
@_set_to_reprising = ( S, message ) =>
validate.datamill_reprising_message message
assign S.control.reprise.phase, message
S.control.reprise_nr += +1
return null
#-----------------------------------------------------------------------------------------------------------
@_conclude_current_reprise = ( S ) =>
S.control.reprise[ key ] = null for key of S.control.reprise
return null
#-----------------------------------------------------------------------------------------------------------
@_pluck_next_control_message = ( S ) =>
throw new Error "µ11092 queue is empty" unless S.control.queue.length > 0
message = S.control.queue.shift()
assign S.control.reprise, message
return message
#-----------------------------------------------------------------------------------------------------------
@reprise = ( S, region ) =>
validate.datamill_inclusive_region region
validate.nonempty_text S.control.active_phase
### TAINT use explicit datatype to test for additional condition ###
validate.nonempty_text region.ref
{ first_vnr
last_vnr
ref } = region
S.control.queue.push new_datom '~reprise', { first_vnr, last_vnr, phase: S.control.active_phase, ref, }
return null
#-----------------------------------------------------------------------------------------------------------
@render_html = ( S, settings ) -> new Promise ( resolve, reject ) =>
defaults = { phase_names: [ './900-render-html', ], }
settings = { defaults..., settings..., }
resolve await @parse_document S, settings
#-----------------------------------------------------------------------------------------------------------
@parse_document = ( S, settings ) -> new Promise ( resolve, reject ) =>
defaults =
quiet: false
### TAINT use globbing instead of enumeration ###
phase_names: H.get_phase_names S
settings = { defaults..., settings..., }
debug '^44553^', settings.phase_names
validate.datamill_parse_document_settings settings
#.........................................................................................................
msg_1 = ->
return if settings.quiet
nrs_txt = CND.reverse CND.yellow " r#{S.control.reprise_nr} p#{pass} "
help 'µ55567 ' + nrs_txt + ( CND.lime " phase #{phase_name} " )
#.........................................................................................................
msg_2 = ( phase_name ) ->
return if settings.quiet
nrs_txt = CND.reverse CND.yellow " r#{S.control.reprise_nr} "
info 'µ22872', nrs_txt + CND.blue " finished reprise for #{phase_name}"
info()
#.........................................................................................................
msg_2a = ( phase_name ) ->
return if settings.quiet
info 'µ22872', CND.blue "continuing without limits"
info()
#.........................................................................................................
msg_3 = ( message ) ->
return if settings.quiet
nrs_txt = CND.reverse CND.yellow " r#{S.control.reprise_nr} "
info()
info 'µ33324', nrs_txt + CND.blue " reprise for #{message.phase} with fragment #{jr message.first_vnr} <= vnr <= #{jr message.last_vnr} (ref: #{message.ref})"
#.........................................................................................................
loop
try
# ### TAINT use API ###
# S.confine_to = null
# S.confine_from_phase = null
for phase_name in settings.phase_names
@_set_active_phase S, phase_name
# length_of_queue = @_length_of_control_queue S
phase = require phase_name
pass = 1
msg_1()
await @run_phase S, ( phase.settings ? null ), ( phase.$transform S )
#...................................................................................................
if S.control.reprise.phase is phase_name
### Conclude reprise; continue with upcoming phase and entire document ###
### TAINT do we have to stack boundaries? ###
msg_2 phase_name
@_conclude_current_reprise S
#...................................................................................................
if @_next_control_message_is_from S, phase_name
throw @_pluck_next_control_message S
# msg_2a() unless @_control_queue_has_messages S
#...................................................................................................
if H.repeat_phase S, phase
throw new Error "µ33443 phase repeating not implemented (#{rpr phase_name})"
@_cancel_active_phase S
#.......................................................................................................
catch message
throw message unless ( select message, '~reprise' )
@_set_to_reprising S, message
msg_3 message
### TAINT use API ###
continue
break
#.........................................................................................................
resolve()
#.........................................................................................................
return null
#-----------------------------------------------------------------------------------------------------------
@_demo_list_html_rows = ( S ) -> new Promise ( resolve ) =>
#.......................................................................................................
pipeline = []
pipeline.push H.new_db_source S, 'html'
pipeline.push SPX.$show()
pipeline.push SPX.$drain -> resolve()
SPX.pull pipeline...
#-----------------------------------------------------------------------------------------------------------
@_demo = ->
await do => new Promise ( resolve ) =>
#.......................................................................................................
settings =
# file_path: project_abspath 'src/tests/demo-short-headlines.md'
# file_path: project_abspath 'src/tests/demo.md'
file_path: project_abspath 'src/tests/demo-medium.md'
# file_path: project_abspath 'src/tests/demo-simple-paragraphs.md'
#.......................................................................................................
help "using database at #{settings.db_path}"
datamill = await DATAMILL.create settings
# datamill.mirage.dbw.$.run "drop index main_pk;" ### TAINT for testing only ###
quiet = false
quiet = true
await DATAMILL.parse_document datamill, { quiet, }
await @render_html datamill, { quiet, }
# await @_demo_list_html_rows datamill
#.......................................................................................................
await H.show_overview datamill
await H.show_html datamill
HTML = require './900-render-html'
await HTML.write_to_file datamill
resolve()
return null
return null
############################################################################################################
if module is require.main then do =>
await DATAMILL._demo()
| true |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'DATAMILL/MAIN'
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
info = CND.get_logger 'info', badge
urge = CND.get_logger 'urge', badge
help = CND.get_logger 'help', badge
whisper = CND.get_logger 'whisper', badge
echo = CND.echo.bind CND
{ jr
assign } = CND
#...........................................................................................................
first = Symbol 'first'
last = Symbol 'last'
MIRAGE = require 'mkts-mirage'
#...........................................................................................................
SPX = require './steampipes-extra'
{ $
$watch
$async } = SPX.export()
#...........................................................................................................
DATOM = require 'datom'
{ VNR } = DATOM
{ freeze
thaw
new_datom
is_stamped
select
stamp } = DATOM.export()
#...........................................................................................................
@types = require './types'
{ isa
validate
declare
first_of
last_of
size_of
type_of } = @types
#...........................................................................................................
H = require './helpers'
{ cwd_abspath
cwd_relpath
here_abspath
project_abspath } = H
DATAMILL = @
#===========================================================================================================
#
#-----------------------------------------------------------------------------------------------------------
@run_phase = ( S, settings, transform ) -> new Promise ( resolve, reject ) =>
defaults = { from_realm: S.mirage.default_realm, }
settings = { defaults..., settings..., }
phase_name = S.control.active_phase
validate.datamill_run_phase_settings settings
#.........................................................................................................
# debug 'µ33344', jr S
# debug 'µ33344', jr settings
# source = H.new_db_source S
# pipeline = []
# pipeline.push source
# pipeline.push transform
# pipeline.push H.$feed_db S
# pipeline.push SPX.$drain => resolve()
# R = SPX.pull pipeline...
source = SPX.new_push_source()
pipeline = []
pipeline.push source
pipeline.push transform
pipeline.push SPX.$show { title: "^run_phase@443^ (#{phase_name})", }
pipeline.push H.$feed_db S
pipeline.push SPX.$drain => resolve()
R = SPX.pull pipeline...
H.feed_source S, source, settings.from_realm
return null
#-----------------------------------------------------------------------------------------------------------
### TAINT consider to use dedicated DB module akin to mkts-mirage/src/db.coffee ###
@_create_udfs = ( mirage ) ->
db = mirage.db
### Placeholder function re-defined by `H.copy_realm()`: ###
db.$.function 'datamill_copy_realm_select', { deterministic: false, varargs: false }, ( row ) -> true
return null
#-----------------------------------------------------------------------------------------------------------
@create = ( settings ) ->
### TAINT set active realm ###
defaults =
file_path: null
# db_path: ':memory:'
db_path: H.project_abspath 'db/datamill.db'
icql_path: H.project_abspath 'db/datamill.icql'
default_key: PI:KEY:<KEY>END_PI'
default_dest: 'main'
default_realm: 'input'
clear: true
#.........................................................................................................
settings = { defaults..., settings..., }
mirage = await MIRAGE.create settings
#.........................................................................................................
R =
mirage: mirage
control:
active_phase: null
queue: [] ### A queue for flow control messages ###
reprise_nr: 1
reprise:
start_vnr: null
stop_vnr: null
phase: null ### name of phase that queued control messages ###
#.........................................................................................................
### TAINT consider to use dedicated DB module akin to mkts-mirage/src/db.coffee ###
@_create_udfs mirage
return R
#-----------------------------------------------------------------------------------------------------------
@_set_active_phase = ( S, phase_name ) => S.control.active_phase = phase_name
@_cancel_active_phase = ( S ) => S.control.active_phase = null
@_length_of_control_queue = ( S ) => S.control.queue.length
@_control_queue_has_messages = ( S ) => ( @_length_of_control_queue S ) > 0
@_next_control_message_is_from = ( S, phase_name ) => S.control.queue[ 0 ]?.phase is phase_name
@_is_reprising = ( S ) => S.control.reprise.phase?
#-----------------------------------------------------------------------------------------------------------
@_set_to_reprising = ( S, message ) =>
validate.datamill_reprising_message message
assign S.control.reprise.phase, message
S.control.reprise_nr += +1
return null
#-----------------------------------------------------------------------------------------------------------
@_conclude_current_reprise = ( S ) =>
S.control.reprise[ key ] = null for key of S.control.reprise
return null
#-----------------------------------------------------------------------------------------------------------
@_pluck_next_control_message = ( S ) =>
throw new Error "µ11092 queue is empty" unless S.control.queue.length > 0
message = S.control.queue.shift()
assign S.control.reprise, message
return message
#-----------------------------------------------------------------------------------------------------------
@reprise = ( S, region ) =>
validate.datamill_inclusive_region region
validate.nonempty_text S.control.active_phase
### TAINT use explicit datatype to test for additional condition ###
validate.nonempty_text region.ref
{ first_vnr
last_vnr
ref } = region
S.control.queue.push new_datom '~reprise', { first_vnr, last_vnr, phase: S.control.active_phase, ref, }
return null
#-----------------------------------------------------------------------------------------------------------
@render_html = ( S, settings ) -> new Promise ( resolve, reject ) =>
defaults = { phase_names: [ './900-render-html', ], }
settings = { defaults..., settings..., }
resolve await @parse_document S, settings
#-----------------------------------------------------------------------------------------------------------
@parse_document = ( S, settings ) -> new Promise ( resolve, reject ) =>
defaults =
quiet: false
### TAINT use globbing instead of enumeration ###
phase_names: H.get_phase_names S
settings = { defaults..., settings..., }
debug '^44553^', settings.phase_names
validate.datamill_parse_document_settings settings
#.........................................................................................................
msg_1 = ->
return if settings.quiet
nrs_txt = CND.reverse CND.yellow " r#{S.control.reprise_nr} p#{pass} "
help 'µ55567 ' + nrs_txt + ( CND.lime " phase #{phase_name} " )
#.........................................................................................................
msg_2 = ( phase_name ) ->
return if settings.quiet
nrs_txt = CND.reverse CND.yellow " r#{S.control.reprise_nr} "
info 'µ22872', nrs_txt + CND.blue " finished reprise for #{phase_name}"
info()
#.........................................................................................................
msg_2a = ( phase_name ) ->
return if settings.quiet
info 'µ22872', CND.blue "continuing without limits"
info()
#.........................................................................................................
msg_3 = ( message ) ->
return if settings.quiet
nrs_txt = CND.reverse CND.yellow " r#{S.control.reprise_nr} "
info()
info 'µ33324', nrs_txt + CND.blue " reprise for #{message.phase} with fragment #{jr message.first_vnr} <= vnr <= #{jr message.last_vnr} (ref: #{message.ref})"
#.........................................................................................................
loop
try
# ### TAINT use API ###
# S.confine_to = null
# S.confine_from_phase = null
for phase_name in settings.phase_names
@_set_active_phase S, phase_name
# length_of_queue = @_length_of_control_queue S
phase = require phase_name
pass = 1
msg_1()
await @run_phase S, ( phase.settings ? null ), ( phase.$transform S )
#...................................................................................................
if S.control.reprise.phase is phase_name
### Conclude reprise; continue with upcoming phase and entire document ###
### TAINT do we have to stack boundaries? ###
msg_2 phase_name
@_conclude_current_reprise S
#...................................................................................................
if @_next_control_message_is_from S, phase_name
throw @_pluck_next_control_message S
# msg_2a() unless @_control_queue_has_messages S
#...................................................................................................
if H.repeat_phase S, phase
throw new Error "µ33443 phase repeating not implemented (#{rpr phase_name})"
@_cancel_active_phase S
#.......................................................................................................
catch message
throw message unless ( select message, '~reprise' )
@_set_to_reprising S, message
msg_3 message
### TAINT use API ###
continue
break
#.........................................................................................................
resolve()
#.........................................................................................................
return null
#-----------------------------------------------------------------------------------------------------------
@_demo_list_html_rows = ( S ) -> new Promise ( resolve ) =>
#.......................................................................................................
pipeline = []
pipeline.push H.new_db_source S, 'html'
pipeline.push SPX.$show()
pipeline.push SPX.$drain -> resolve()
SPX.pull pipeline...
#-----------------------------------------------------------------------------------------------------------
@_demo = ->
await do => new Promise ( resolve ) =>
#.......................................................................................................
settings =
# file_path: project_abspath 'src/tests/demo-short-headlines.md'
# file_path: project_abspath 'src/tests/demo.md'
file_path: project_abspath 'src/tests/demo-medium.md'
# file_path: project_abspath 'src/tests/demo-simple-paragraphs.md'
#.......................................................................................................
help "using database at #{settings.db_path}"
datamill = await DATAMILL.create settings
# datamill.mirage.dbw.$.run "drop index main_pk;" ### TAINT for testing only ###
quiet = false
quiet = true
await DATAMILL.parse_document datamill, { quiet, }
await @render_html datamill, { quiet, }
# await @_demo_list_html_rows datamill
#.......................................................................................................
await H.show_overview datamill
await H.show_html datamill
HTML = require './900-render-html'
await HTML.write_to_file datamill
resolve()
return null
return null
############################################################################################################
if module is require.main then do =>
await DATAMILL._demo()
|
[
{
"context": "ase stores entries from our json api.\n\n @author Sebastian Sachtleben\n @author Alexander Kong\n###\ndatabase = ",
"end": 98,
"score": 0.9998829960823059,
"start": 78,
"tag": "NAME",
"value": "Sebastian Sachtleben"
},
{
"context": "api.\n\n @author Seba... | app/assets/javascripts/shared/database.coffee | ssachtleben/herowar | 1 | _db = {}
###
The database stores entries from our json api.
@author Sebastian Sachtleben
@author Alexander Kong
###
database =
###
Get list or specific object depending on the second parameter
@param {String} The model name.
@param {Object} The id inside of the collection.
@return {Object} The collection entry.
###
get: (type, obj) ->
@create type unless _db[type]?
if _.isArray obj
return (_db[type].get element for element in obj)
if _.isFunction obj
return _db[type].filter obj
if _.isObject(obj) or _.isNumber(obj) or _.isString obj
return _db[type].get obj
_db[type]
###
Add new db collection or entry.
@param {String} The model name.
@param {Object} The object to add.
@param {Object} The add to collection options.
###
add: (type, obj, options) ->
options = _.extend {merge:true}, options
@create type unless _db[type]
_db[type].add obj, options if obj
###
Create new collection.
@param {String} The collection name.
@param {Object} The attributes if its a model.
###
create: (type, attributes) ->
_db[type] = new (require 'models/' + type)(attributes, name: type)
###
Check if db type exists.
@param {String} The model name.
###
exists: (type) ->
if _db[type] then true else false
return database | 109823 | _db = {}
###
The database stores entries from our json api.
@author <NAME>
@author <NAME>
###
database =
###
Get list or specific object depending on the second parameter
@param {String} The model name.
@param {Object} The id inside of the collection.
@return {Object} The collection entry.
###
get: (type, obj) ->
@create type unless _db[type]?
if _.isArray obj
return (_db[type].get element for element in obj)
if _.isFunction obj
return _db[type].filter obj
if _.isObject(obj) or _.isNumber(obj) or _.isString obj
return _db[type].get obj
_db[type]
###
Add new db collection or entry.
@param {String} The model name.
@param {Object} The object to add.
@param {Object} The add to collection options.
###
add: (type, obj, options) ->
options = _.extend {merge:true}, options
@create type unless _db[type]
_db[type].add obj, options if obj
###
Create new collection.
@param {String} The collection name.
@param {Object} The attributes if its a model.
###
create: (type, attributes) ->
_db[type] = new (require 'models/' + type)(attributes, name: type)
###
Check if db type exists.
@param {String} The model name.
###
exists: (type) ->
if _db[type] then true else false
return database | true | _db = {}
###
The database stores entries from our json api.
@author PI:NAME:<NAME>END_PI
@author PI:NAME:<NAME>END_PI
###
database =
###
Get list or specific object depending on the second parameter
@param {String} The model name.
@param {Object} The id inside of the collection.
@return {Object} The collection entry.
###
get: (type, obj) ->
@create type unless _db[type]?
if _.isArray obj
return (_db[type].get element for element in obj)
if _.isFunction obj
return _db[type].filter obj
if _.isObject(obj) or _.isNumber(obj) or _.isString obj
return _db[type].get obj
_db[type]
###
Add new db collection or entry.
@param {String} The model name.
@param {Object} The object to add.
@param {Object} The add to collection options.
###
add: (type, obj, options) ->
options = _.extend {merge:true}, options
@create type unless _db[type]
_db[type].add obj, options if obj
###
Create new collection.
@param {String} The collection name.
@param {Object} The attributes if its a model.
###
create: (type, attributes) ->
_db[type] = new (require 'models/' + type)(attributes, name: type)
###
Check if db type exists.
@param {String} The model name.
###
exists: (type) ->
if _db[type] then true else false
return database |
[
{
"context": "kefact - get a random pokefact!\r\n#\r\n# Developed by One Mighty Roar (http://github.com/onemightyroar)\r\n\r\nmodule.expor",
"end": 89,
"score": 0.9998566508293152,
"start": 74,
"tag": "NAME",
"value": "One Mighty Roar"
},
{
"context": "# Developed by One Mighty Roar ... | src/scripts/pokefacts.coffee | aroben/hubot-scripts | 1 | # Pokemon fun!
#
# pokefact - get a random pokefact!
#
# Developed by One Mighty Roar (http://github.com/onemightyroar)
module.exports = (robot) ->
robot.respond /pokefact/i, (msg) ->
msg.http('https://api.twitter.com/1/statuses/user_timeline.json')
.query(screen_name: 'pokefacts', count: 100)
.get() (err, res, body) ->
tweets = JSON.parse(body)
msg.send tweets.length
if tweets? and tweets.length > 0
tweet = msg.random tweets
while(tweet.text.toLowerCase().indexOf('#pokefact') == -1)
tweet = msg.random tweets
msg.send "PokeFACT: " + tweet.text.replace(/\#pokefact/i, "");
else
msg.reply "Couldn't find a PokeFACT" | 20545 | # Pokemon fun!
#
# pokefact - get a random pokefact!
#
# Developed by <NAME> (http://github.com/onemightyroar)
module.exports = (robot) ->
robot.respond /pokefact/i, (msg) ->
msg.http('https://api.twitter.com/1/statuses/user_timeline.json')
.query(screen_name: 'pokefacts', count: 100)
.get() (err, res, body) ->
tweets = JSON.parse(body)
msg.send tweets.length
if tweets? and tweets.length > 0
tweet = msg.random tweets
while(tweet.text.toLowerCase().indexOf('#pokefact') == -1)
tweet = msg.random tweets
msg.send "PokeFACT: " + tweet.text.replace(/\#pokefact/i, "");
else
msg.reply "Couldn't find a PokeFACT" | true | # Pokemon fun!
#
# pokefact - get a random pokefact!
#
# Developed by PI:NAME:<NAME>END_PI (http://github.com/onemightyroar)
module.exports = (robot) ->
robot.respond /pokefact/i, (msg) ->
msg.http('https://api.twitter.com/1/statuses/user_timeline.json')
.query(screen_name: 'pokefacts', count: 100)
.get() (err, res, body) ->
tweets = JSON.parse(body)
msg.send tweets.length
if tweets? and tweets.length > 0
tweet = msg.random tweets
while(tweet.text.toLowerCase().indexOf('#pokefact') == -1)
tweet = msg.random tweets
msg.send "PokeFACT: " + tweet.text.replace(/\#pokefact/i, "");
else
msg.reply "Couldn't find a PokeFACT" |
[
{
"context": "uth'\n errors.password = t 'config error auth'\n\n else\n ",
"end": 2844,
"score": 0.9081435203552246,
"start": 2827,
"tag": "PASSWORD",
"value": "config error auth"
},
{
"context": " id: 'mailbox-... | client/app/components/account_config.coffee | cozy-labs/emails | 58 | AccountActionCreator = require '../actions/account_action_creator'
LayoutActions = require '../actions/layout_action_creator'
RouterMixin = require '../mixins/router_mixin'
{Container, Title, Tabs} = require './basic_components'
AccountConfigMain = require './account_config_main'
AccountConfigMailboxes = require './account_config_mailboxes'
AccountConfigSignature = require './account_config_signature'
module.exports = React.createClass
displayName: 'AccountConfig'
_lastDiscovered: ''
mixins: [
RouterMixin
React.addons.LinkedStateMixin # two-way data binding
]
_accountFields: [
'id'
'label'
'name'
'login'
'password'
'imapServer'
'imapPort'
'imapSSL'
'imapTLS'
'imapLogin'
'smtpServer'
'smtpPort'
'smtpSSL'
'smtpTLS'
'smtpLogin'
'smtpPassword'
'smtpMethod'
'accountType'
]
_mailboxesFields: [
'id'
'mailboxes'
'favoriteMailboxes'
'draftMailbox'
'sentMailbox'
'trashMailbox'
]
_accountSchema:
properties:
label: allowEmpty: false
name: allowEmpty: false
login: allowEmpty: false
password: allowEmpty: false
imapServer: allowEmpty: false
imapPort: allowEmpty: false
imapSSL: allowEmpty: true
imapTLS: allowEmpty: true
imapLogin: allowEmpty: true
smtpServer: allowEmpty: false
smtpPort: allowEmpty: false
smtpSSL: allowEmpty: true
smtpTLS: allowEmpty: true
smtpLogin: allowEmpty: true
smtpMethod: allowEmpty: true
smtpPassword: allowEmpty: true
draftMailbox: allowEmpty: true
sentMailbox: allowEmpty: true
trashMailbox: allowEmpty: true
accountType: allowEmpty: true
getInitialState: ->
return @accountToState @props
# Do not update component if nothing has changed.
shouldComponentUpdate: (nextProps, nextState) ->
isNextState = _.isEqual nextState, @state
isNextProps = _.isEqual nextProps, @props
return not (isNextState and isNextProps)
componentWillReceiveProps: (props) ->
# prevents the form from changing during submission
if props.selectedAccount? and not props.isWaiting
@setState @accountToState props
else
if props.error?
if props.error.name is 'AccountConfigError'
errors = {}
field = props.error.field
if field is 'auth'
errors.login = t 'config error auth'
errors.password = t 'config error auth'
else
errors[field] = t 'config error ' + field
@setState errors: errors
else
if not props.isWaiting and not _.isEqual(props, @props)
@setState @accountToState null
render: ->
mainOptions = @buildMainOptions()
mailboxesOptions = @buildMailboxesOptions()
titleLabel = @buildTitleLabel()
tabParams = @buildTabParams()
Container
id: 'mailbox-config'
key: "account-config-#{@props.selectedAccount?.get 'id'}"
,
Title text: titleLabel
if @props.tab?
Tabs tabs: tabParams
if not @props.tab or @props.tab is 'account'
AccountConfigMain mainOptions
else if @props.tab is 'signature'
AccountConfigSignature
account: @props.selectedAccount
editAccount: @editAccount
else
AccountConfigMailboxes mailboxesOptions
# Build options shared by both tabs.
buildMainOptions: (options) ->
options =
isWaiting: @props.isWaiting
selectedAccount: @props.selectedAccount
validateForm: @validateForm
onSubmit: @onSubmit
onBlur: @onFieldBlurred
errors: @state.errors
checking: @state.checking
options[field] = @linkState field for field in @_accountFields
return options
# Build options required by mailbox tab.
buildMailboxesOptions: (options) ->
options =
error: @props.error
errors: @state.errors
onSubmit: @onSubmit
selectedAccount: @props.selectedAccount
# /!\ we cannot use @linkState here because we need to be able
# to call a method after state has been updated
for field in @_mailboxesFields
doChange = (f) =>
return (val, cb) =>
state = {}
state[f] = val
@setState state, cb
options[field] =
value: @state[field]
requestChange: doChange field
return options
# Build tab panel title depending if we show the component for a new
# account or for an edition.
buildTitleLabel: ->
if @state.id
titleLabel = t "account edit"
else
titleLabel = t "account new"
return titleLabel
# Build tab navigation depending if we show the component for a new
# account, for an edition or or changing account signaure
# (no tab navigation if we are in a creation mode).
buildTabParams: ->
tabAccountClass = tabMailboxClass = tabSignatureClass = ''
if not @props.tab or @props.tab is 'account'
tabAccountClass = 'active'
else if @props.tab is 'mailboxes'
tabMailboxClass = 'active'
else if @props.tab is 'signature'
tabSignatureClass = 'active'
tabs = [
class: tabAccountClass
url: @buildUrl
direction: 'first'
action: 'account.config'
parameters: [@state.id, 'account']
text: t "account tab account"
,
class: tabMailboxClass
url: @buildUrl
direction: 'first'
action: 'account.config'
parameters: [@state.id, 'mailboxes']
text: t "account tab mailboxes"
,
class: tabSignatureClass
url: @buildUrl
direction: 'first'
action: 'account.config'
parameters: [@state.id, 'signature']
text: t "account tab signature"
]
return tabs
# When a field changes, if the form was not submitted, nothing happens,
# it the form was submitted on time, we run the whole validation again.
onFieldBlurred: ->
@validateForm() if @state.submitted
# Form submission displays errors if form values are wrong.
# If everything is ok, it runs the checking, the account edition and the
# creation depending on the current state and if the user submitted it
# with the check button.
onSubmit: (event, check) ->
event.preventDefault() if event?
{accountValue, valid, errors} = @validateForm()
if Object.keys(errors).length > 0
LayoutActions.alertError t 'account errors'
if valid.valid
if check is true
@checkAccount accountValue
else if @state.id?
@editAccount accountValue
else
@createAccount accountValue
# Check wether form values are right. Then it displays or remove dispayed
# errors dependning on the result.
# To achieve that, it changes the state of the current component.
# Returns form values and the valid object as result.
validateForm: (event) ->
event.preventDefault() if event?
@setState submitted: true
valid = valid: null
accountValue = null
errors = {}
{accountValue, valid} = @doValidate()
if valid.valid
@setState errors: {}
else
errors = {}
for error in valid.errors
errors[error.property] = t "validate #{error.message}"
@setState errors: errors
return {accountValue, valid, errors}
# Check if all fields are valid. It returns an object with field values and
# an object that lists all errors.
doValidate: ->
accountValue = {}
accountValue[field] = @state[field] for field in @_accountFields
accountValue[field] = @state[field] for field in @_mailboxesFields
validOptions =
additionalProperties: true
schema = @_accountSchema
# password is not required on OAuth accounts
isOauth = @props.selectedAccount?.get('oauthProvider')?
schema.properties.password.allowEmpty = isOauth
valid = validate accountValue, schema, validOptions
return {accountValue, valid}
# Run the account checking operation.
checkAccount: (values) ->
@setState checking: true
AccountActionCreator.check values, @state.id, =>
@setState checking: false
# Save modification to the server.
editAccount: (values, callback) ->
AccountActionCreator.edit values, @state.id, callback
# Create a new account and redirect user to the message list of this
# account.
createAccount: (values) ->
AccountActionCreator.create values, (account) =>
msg = t("account creation ok")
LayoutActions.notify msg,
autoclose: true
@redirect
direction: 'first'
action: 'account.config'
parameters: [
account.get 'id'
'mailboxes'
]
fullWidth: true
# Build state from prop values.
accountToState: (props) ->
state =
errors: {}
if props?
account = props.selectedAccount
@buildErrorState state, props
if account?
@buildAccountState state, props, account
else if Object.keys(state.errors).length is 0
state = @buildDefaultState state
return state
# Set errors at state level.
buildErrorState: (state, props) ->
if props.error?
if props.error.name is 'AccountConfigError'
field = props.error.field
if field is 'auth'
state.errors.login = t 'config error auth'
state.errors.password = t 'config error auth'
else
state.errors[field] = t "config error #{field}"
# Build state based on current account values.
buildAccountState: (state, props, account) ->
if @state?.id isnt account.get('id')
state[field] = account.get field for field in @_accountFields
state.smtpMethod = 'PLAIN' if not state.smtpMethod?
state[field] = account.get field for field in @_mailboxesFields
state.newMailboxParent = null
state.mailboxes = props.mailboxes
state.favoriteMailboxes = props.favoriteMailboxes
props.tab = 'mailboxes' if state.mailboxes.length is 0
# Build default state (required for account creation).
buildDefaultState: ->
state =
errors: {}
state[field] = '' for field in @_accountFields
state[field] = '' for field in @_mailboxesFields
state.id = null
state.smtpPort = 465
state.smtpSSL = true
state.smtpTLS = false
state.smtpMethod = 'PLAIN'
state.imapPort = 993
state.imapSSL = true
state.imapTLS = false
state.accountType = 'IMAP'
state.newMailboxParent = null
state.favoriteMailboxes = null
return state
| 102277 | AccountActionCreator = require '../actions/account_action_creator'
LayoutActions = require '../actions/layout_action_creator'
RouterMixin = require '../mixins/router_mixin'
{Container, Title, Tabs} = require './basic_components'
AccountConfigMain = require './account_config_main'
AccountConfigMailboxes = require './account_config_mailboxes'
AccountConfigSignature = require './account_config_signature'
module.exports = React.createClass
displayName: 'AccountConfig'
_lastDiscovered: ''
mixins: [
RouterMixin
React.addons.LinkedStateMixin # two-way data binding
]
_accountFields: [
'id'
'label'
'name'
'login'
'password'
'imapServer'
'imapPort'
'imapSSL'
'imapTLS'
'imapLogin'
'smtpServer'
'smtpPort'
'smtpSSL'
'smtpTLS'
'smtpLogin'
'smtpPassword'
'smtpMethod'
'accountType'
]
_mailboxesFields: [
'id'
'mailboxes'
'favoriteMailboxes'
'draftMailbox'
'sentMailbox'
'trashMailbox'
]
_accountSchema:
properties:
label: allowEmpty: false
name: allowEmpty: false
login: allowEmpty: false
password: allowEmpty: false
imapServer: allowEmpty: false
imapPort: allowEmpty: false
imapSSL: allowEmpty: true
imapTLS: allowEmpty: true
imapLogin: allowEmpty: true
smtpServer: allowEmpty: false
smtpPort: allowEmpty: false
smtpSSL: allowEmpty: true
smtpTLS: allowEmpty: true
smtpLogin: allowEmpty: true
smtpMethod: allowEmpty: true
smtpPassword: allowEmpty: true
draftMailbox: allowEmpty: true
sentMailbox: allowEmpty: true
trashMailbox: allowEmpty: true
accountType: allowEmpty: true
getInitialState: ->
return @accountToState @props
# Do not update component if nothing has changed.
shouldComponentUpdate: (nextProps, nextState) ->
isNextState = _.isEqual nextState, @state
isNextProps = _.isEqual nextProps, @props
return not (isNextState and isNextProps)
componentWillReceiveProps: (props) ->
# prevents the form from changing during submission
if props.selectedAccount? and not props.isWaiting
@setState @accountToState props
else
if props.error?
if props.error.name is 'AccountConfigError'
errors = {}
field = props.error.field
if field is 'auth'
errors.login = t 'config error auth'
errors.password = t '<PASSWORD>'
else
errors[field] = t 'config error ' + field
@setState errors: errors
else
if not props.isWaiting and not _.isEqual(props, @props)
@setState @accountToState null
render: ->
mainOptions = @buildMainOptions()
mailboxesOptions = @buildMailboxesOptions()
titleLabel = @buildTitleLabel()
tabParams = @buildTabParams()
Container
id: 'mailbox-config'
key: "<KEY>@props.selectedAccount?.get '<KEY>'<KEY>}"
,
Title text: titleLabel
if @props.tab?
Tabs tabs: tabParams
if not @props.tab or @props.tab is 'account'
AccountConfigMain mainOptions
else if @props.tab is 'signature'
AccountConfigSignature
account: @props.selectedAccount
editAccount: @editAccount
else
AccountConfigMailboxes mailboxesOptions
# Build options shared by both tabs.
buildMainOptions: (options) ->
options =
isWaiting: @props.isWaiting
selectedAccount: @props.selectedAccount
validateForm: @validateForm
onSubmit: @onSubmit
onBlur: @onFieldBlurred
errors: @state.errors
checking: @state.checking
options[field] = @linkState field for field in @_accountFields
return options
# Build options required by mailbox tab.
buildMailboxesOptions: (options) ->
options =
error: @props.error
errors: @state.errors
onSubmit: @onSubmit
selectedAccount: @props.selectedAccount
# /!\ we cannot use @linkState here because we need to be able
# to call a method after state has been updated
for field in @_mailboxesFields
doChange = (f) =>
return (val, cb) =>
state = {}
state[f] = val
@setState state, cb
options[field] =
value: @state[field]
requestChange: doChange field
return options
# Build tab panel title depending if we show the component for a new
# account or for an edition.
buildTitleLabel: ->
if @state.id
titleLabel = t "account edit"
else
titleLabel = t "account new"
return titleLabel
# Build tab navigation depending if we show the component for a new
# account, for an edition or or changing account signaure
# (no tab navigation if we are in a creation mode).
buildTabParams: ->
tabAccountClass = tabMailboxClass = tabSignatureClass = ''
if not @props.tab or @props.tab is 'account'
tabAccountClass = 'active'
else if @props.tab is 'mailboxes'
tabMailboxClass = 'active'
else if @props.tab is 'signature'
tabSignatureClass = 'active'
tabs = [
class: tabAccountClass
url: @buildUrl
direction: 'first'
action: 'account.config'
parameters: [@state.id, 'account']
text: t "account tab account"
,
class: tabMailboxClass
url: @buildUrl
direction: 'first'
action: 'account.config'
parameters: [@state.id, 'mailboxes']
text: t "account tab mailboxes"
,
class: tabSignatureClass
url: @buildUrl
direction: 'first'
action: 'account.config'
parameters: [@state.id, 'signature']
text: t "account tab signature"
]
return tabs
# When a field changes, if the form was not submitted, nothing happens,
# it the form was submitted on time, we run the whole validation again.
onFieldBlurred: ->
@validateForm() if @state.submitted
# Form submission displays errors if form values are wrong.
# If everything is ok, it runs the checking, the account edition and the
# creation depending on the current state and if the user submitted it
# with the check button.
onSubmit: (event, check) ->
event.preventDefault() if event?
{accountValue, valid, errors} = @validateForm()
if Object.keys(errors).length > 0
LayoutActions.alertError t 'account errors'
if valid.valid
if check is true
@checkAccount accountValue
else if @state.id?
@editAccount accountValue
else
@createAccount accountValue
# Check wether form values are right. Then it displays or remove dispayed
# errors dependning on the result.
# To achieve that, it changes the state of the current component.
# Returns form values and the valid object as result.
validateForm: (event) ->
event.preventDefault() if event?
@setState submitted: true
valid = valid: null
accountValue = null
errors = {}
{accountValue, valid} = @doValidate()
if valid.valid
@setState errors: {}
else
errors = {}
for error in valid.errors
errors[error.property] = t "validate #{error.message}"
@setState errors: errors
return {accountValue, valid, errors}
# Check if all fields are valid. It returns an object with field values and
# an object that lists all errors.
doValidate: ->
accountValue = {}
accountValue[field] = @state[field] for field in @_accountFields
accountValue[field] = @state[field] for field in @_mailboxesFields
validOptions =
additionalProperties: true
schema = @_accountSchema
# password is not required on OAuth accounts
isOauth = @props.selectedAccount?.get('oauthProvider')?
schema.properties.password.allowEmpty = isOauth
valid = validate accountValue, schema, validOptions
return {accountValue, valid}
# Run the account checking operation.
checkAccount: (values) ->
@setState checking: true
AccountActionCreator.check values, @state.id, =>
@setState checking: false
# Save modification to the server.
editAccount: (values, callback) ->
AccountActionCreator.edit values, @state.id, callback
# Create a new account and redirect user to the message list of this
# account.
createAccount: (values) ->
AccountActionCreator.create values, (account) =>
msg = t("account creation ok")
LayoutActions.notify msg,
autoclose: true
@redirect
direction: 'first'
action: 'account.config'
parameters: [
account.get 'id'
'mailboxes'
]
fullWidth: true
# Build state from prop values.
accountToState: (props) ->
state =
errors: {}
if props?
account = props.selectedAccount
@buildErrorState state, props
if account?
@buildAccountState state, props, account
else if Object.keys(state.errors).length is 0
state = @buildDefaultState state
return state
# Set errors at state level.
buildErrorState: (state, props) ->
if props.error?
if props.error.name is 'AccountConfigError'
field = props.error.field
if field is 'auth'
state.errors.login = t 'config error auth'
state.errors.password = t '<PASSWORD>'
else
state.errors[field] = t "config error #{field}"
# Build state based on current account values.
buildAccountState: (state, props, account) ->
if @state?.id isnt account.get('id')
state[field] = account.get field for field in @_accountFields
state.smtpMethod = 'PLAIN' if not state.smtpMethod?
state[field] = account.get field for field in @_mailboxesFields
state.newMailboxParent = null
state.mailboxes = props.mailboxes
state.favoriteMailboxes = props.favoriteMailboxes
props.tab = 'mailboxes' if state.mailboxes.length is 0
# Build default state (required for account creation).
buildDefaultState: ->
state =
errors: {}
state[field] = '' for field in @_accountFields
state[field] = '' for field in @_mailboxesFields
state.id = null
state.smtpPort = 465
state.smtpSSL = true
state.smtpTLS = false
state.smtpMethod = 'PLAIN'
state.imapPort = 993
state.imapSSL = true
state.imapTLS = false
state.accountType = 'IMAP'
state.newMailboxParent = null
state.favoriteMailboxes = null
return state
| true | AccountActionCreator = require '../actions/account_action_creator'
LayoutActions = require '../actions/layout_action_creator'
RouterMixin = require '../mixins/router_mixin'
{Container, Title, Tabs} = require './basic_components'
AccountConfigMain = require './account_config_main'
AccountConfigMailboxes = require './account_config_mailboxes'
AccountConfigSignature = require './account_config_signature'
module.exports = React.createClass
displayName: 'AccountConfig'
_lastDiscovered: ''
mixins: [
RouterMixin
React.addons.LinkedStateMixin # two-way data binding
]
_accountFields: [
'id'
'label'
'name'
'login'
'password'
'imapServer'
'imapPort'
'imapSSL'
'imapTLS'
'imapLogin'
'smtpServer'
'smtpPort'
'smtpSSL'
'smtpTLS'
'smtpLogin'
'smtpPassword'
'smtpMethod'
'accountType'
]
_mailboxesFields: [
'id'
'mailboxes'
'favoriteMailboxes'
'draftMailbox'
'sentMailbox'
'trashMailbox'
]
_accountSchema:
properties:
label: allowEmpty: false
name: allowEmpty: false
login: allowEmpty: false
password: allowEmpty: false
imapServer: allowEmpty: false
imapPort: allowEmpty: false
imapSSL: allowEmpty: true
imapTLS: allowEmpty: true
imapLogin: allowEmpty: true
smtpServer: allowEmpty: false
smtpPort: allowEmpty: false
smtpSSL: allowEmpty: true
smtpTLS: allowEmpty: true
smtpLogin: allowEmpty: true
smtpMethod: allowEmpty: true
smtpPassword: allowEmpty: true
draftMailbox: allowEmpty: true
sentMailbox: allowEmpty: true
trashMailbox: allowEmpty: true
accountType: allowEmpty: true
getInitialState: ->
return @accountToState @props
# Do not update component if nothing has changed.
shouldComponentUpdate: (nextProps, nextState) ->
isNextState = _.isEqual nextState, @state
isNextProps = _.isEqual nextProps, @props
return not (isNextState and isNextProps)
componentWillReceiveProps: (props) ->
# prevents the form from changing during submission
if props.selectedAccount? and not props.isWaiting
@setState @accountToState props
else
if props.error?
if props.error.name is 'AccountConfigError'
errors = {}
field = props.error.field
if field is 'auth'
errors.login = t 'config error auth'
errors.password = t 'PI:PASSWORD:<PASSWORD>END_PI'
else
errors[field] = t 'config error ' + field
@setState errors: errors
else
if not props.isWaiting and not _.isEqual(props, @props)
@setState @accountToState null
render: ->
mainOptions = @buildMainOptions()
mailboxesOptions = @buildMailboxesOptions()
titleLabel = @buildTitleLabel()
tabParams = @buildTabParams()
Container
id: 'mailbox-config'
key: "PI:KEY:<KEY>END_PI@props.selectedAccount?.get 'PI:KEY:<KEY>END_PI'PI:KEY:<KEY>END_PI}"
,
Title text: titleLabel
if @props.tab?
Tabs tabs: tabParams
if not @props.tab or @props.tab is 'account'
AccountConfigMain mainOptions
else if @props.tab is 'signature'
AccountConfigSignature
account: @props.selectedAccount
editAccount: @editAccount
else
AccountConfigMailboxes mailboxesOptions
# Build options shared by both tabs.
buildMainOptions: (options) ->
options =
isWaiting: @props.isWaiting
selectedAccount: @props.selectedAccount
validateForm: @validateForm
onSubmit: @onSubmit
onBlur: @onFieldBlurred
errors: @state.errors
checking: @state.checking
options[field] = @linkState field for field in @_accountFields
return options
# Build options required by mailbox tab.
buildMailboxesOptions: (options) ->
options =
error: @props.error
errors: @state.errors
onSubmit: @onSubmit
selectedAccount: @props.selectedAccount
# /!\ we cannot use @linkState here because we need to be able
# to call a method after state has been updated
for field in @_mailboxesFields
doChange = (f) =>
return (val, cb) =>
state = {}
state[f] = val
@setState state, cb
options[field] =
value: @state[field]
requestChange: doChange field
return options
# Build tab panel title depending if we show the component for a new
# account or for an edition.
buildTitleLabel: ->
if @state.id
titleLabel = t "account edit"
else
titleLabel = t "account new"
return titleLabel
# Build tab navigation depending if we show the component for a new
# account, for an edition or or changing account signaure
# (no tab navigation if we are in a creation mode).
buildTabParams: ->
tabAccountClass = tabMailboxClass = tabSignatureClass = ''
if not @props.tab or @props.tab is 'account'
tabAccountClass = 'active'
else if @props.tab is 'mailboxes'
tabMailboxClass = 'active'
else if @props.tab is 'signature'
tabSignatureClass = 'active'
tabs = [
class: tabAccountClass
url: @buildUrl
direction: 'first'
action: 'account.config'
parameters: [@state.id, 'account']
text: t "account tab account"
,
class: tabMailboxClass
url: @buildUrl
direction: 'first'
action: 'account.config'
parameters: [@state.id, 'mailboxes']
text: t "account tab mailboxes"
,
class: tabSignatureClass
url: @buildUrl
direction: 'first'
action: 'account.config'
parameters: [@state.id, 'signature']
text: t "account tab signature"
]
return tabs
# When a field changes, if the form was not submitted, nothing happens,
# it the form was submitted on time, we run the whole validation again.
onFieldBlurred: ->
@validateForm() if @state.submitted
# Form submission displays errors if form values are wrong.
# If everything is ok, it runs the checking, the account edition and the
# creation depending on the current state and if the user submitted it
# with the check button.
onSubmit: (event, check) ->
event.preventDefault() if event?
{accountValue, valid, errors} = @validateForm()
if Object.keys(errors).length > 0
LayoutActions.alertError t 'account errors'
if valid.valid
if check is true
@checkAccount accountValue
else if @state.id?
@editAccount accountValue
else
@createAccount accountValue
# Check wether form values are right. Then it displays or remove dispayed
# errors dependning on the result.
# To achieve that, it changes the state of the current component.
# Returns form values and the valid object as result.
validateForm: (event) ->
event.preventDefault() if event?
@setState submitted: true
valid = valid: null
accountValue = null
errors = {}
{accountValue, valid} = @doValidate()
if valid.valid
@setState errors: {}
else
errors = {}
for error in valid.errors
errors[error.property] = t "validate #{error.message}"
@setState errors: errors
return {accountValue, valid, errors}
# Check if all fields are valid. It returns an object with field values and
# an object that lists all errors.
doValidate: ->
accountValue = {}
accountValue[field] = @state[field] for field in @_accountFields
accountValue[field] = @state[field] for field in @_mailboxesFields
validOptions =
additionalProperties: true
schema = @_accountSchema
# password is not required on OAuth accounts
isOauth = @props.selectedAccount?.get('oauthProvider')?
schema.properties.password.allowEmpty = isOauth
valid = validate accountValue, schema, validOptions
return {accountValue, valid}
# Run the account checking operation.
checkAccount: (values) ->
@setState checking: true
AccountActionCreator.check values, @state.id, =>
@setState checking: false
# Save modification to the server.
editAccount: (values, callback) ->
AccountActionCreator.edit values, @state.id, callback
# Create a new account and redirect user to the message list of this
# account.
createAccount: (values) ->
AccountActionCreator.create values, (account) =>
msg = t("account creation ok")
LayoutActions.notify msg,
autoclose: true
@redirect
direction: 'first'
action: 'account.config'
parameters: [
account.get 'id'
'mailboxes'
]
fullWidth: true
# Build state from prop values.
accountToState: (props) ->
state =
errors: {}
if props?
account = props.selectedAccount
@buildErrorState state, props
if account?
@buildAccountState state, props, account
else if Object.keys(state.errors).length is 0
state = @buildDefaultState state
return state
# Set errors at state level.
buildErrorState: (state, props) ->
if props.error?
if props.error.name is 'AccountConfigError'
field = props.error.field
if field is 'auth'
state.errors.login = t 'config error auth'
state.errors.password = t 'PI:PASSWORD:<PASSWORD>END_PI'
else
state.errors[field] = t "config error #{field}"
# Build state based on current account values.
buildAccountState: (state, props, account) ->
if @state?.id isnt account.get('id')
state[field] = account.get field for field in @_accountFields
state.smtpMethod = 'PLAIN' if not state.smtpMethod?
state[field] = account.get field for field in @_mailboxesFields
state.newMailboxParent = null
state.mailboxes = props.mailboxes
state.favoriteMailboxes = props.favoriteMailboxes
props.tab = 'mailboxes' if state.mailboxes.length is 0
# Build default state (required for account creation).
buildDefaultState: ->
state =
errors: {}
state[field] = '' for field in @_accountFields
state[field] = '' for field in @_mailboxesFields
state.id = null
state.smtpPort = 465
state.smtpSSL = true
state.smtpTLS = false
state.smtpMethod = 'PLAIN'
state.imapPort = 993
state.imapSSL = true
state.imapTLS = false
state.accountType = 'IMAP'
state.newMailboxParent = null
state.favoriteMailboxes = null
return state
|
[
{
"context": "###\n * Formatter\n * http://github.com/ingorichter/BracketsExtensionTweetBot\n *\n * Copyright (c) 201",
"end": 49,
"score": 0.9995877742767334,
"start": 38,
"tag": "USERNAME",
"value": "ingorichter"
},
{
"context": "BracketsExtensionTweetBot\n *\n * Copyright (c) 2014... | src/Formatter.coffee | ingorichter/BracketsExtensionTweetBot | 0 | ###
* Formatter
* http://github.com/ingorichter/BracketsExtensionTweetBot
*
* Copyright (c) 2014 Ingo Richter
* Licensed under the MIT license.
###
'use strict'
module.exports =
class Formatter
header = """
| Name | Version | Description | Download |
|------|---------|-------------|----------|
"""
formatUrl: (url) ->
"<a href=\"#{url}\"><div class=\"imageHolder\"><img src=\"images/cloud_download.svg\" class=\"image\"/></div></a>"
formatResult: (newExtensions, updatedExtensions) ->
# format result
result = ""
result += "## #{newExtensions.length} new Extensions" if newExtensions.length
result += "\n" if newExtensions.length
result += "## #{updatedExtensions.length} updated Extensions" if updatedExtensions.length
result += "\n" if updatedExtensions.length
result += "## New Extensions" + "\n" + header + "\n" + newExtensions.join("\n") if newExtensions.length
result += "\n\n" if newExtensions.length and updatedExtensions.length
result += "## Updated Extensions" + "\n" + header + "\n" + updatedExtensions.join("\n") if updatedExtensions.length
| 142757 | ###
* Formatter
* http://github.com/ingorichter/BracketsExtensionTweetBot
*
* Copyright (c) 2014 <NAME>
* Licensed under the MIT license.
###
'use strict'
module.exports =
class Formatter
header = """
| Name | Version | Description | Download |
|------|---------|-------------|----------|
"""
formatUrl: (url) ->
"<a href=\"#{url}\"><div class=\"imageHolder\"><img src=\"images/cloud_download.svg\" class=\"image\"/></div></a>"
formatResult: (newExtensions, updatedExtensions) ->
# format result
result = ""
result += "## #{newExtensions.length} new Extensions" if newExtensions.length
result += "\n" if newExtensions.length
result += "## #{updatedExtensions.length} updated Extensions" if updatedExtensions.length
result += "\n" if updatedExtensions.length
result += "## New Extensions" + "\n" + header + "\n" + newExtensions.join("\n") if newExtensions.length
result += "\n\n" if newExtensions.length and updatedExtensions.length
result += "## Updated Extensions" + "\n" + header + "\n" + updatedExtensions.join("\n") if updatedExtensions.length
| true | ###
* Formatter
* http://github.com/ingorichter/BracketsExtensionTweetBot
*
* Copyright (c) 2014 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
'use strict'
module.exports =
class Formatter
header = """
| Name | Version | Description | Download |
|------|---------|-------------|----------|
"""
formatUrl: (url) ->
"<a href=\"#{url}\"><div class=\"imageHolder\"><img src=\"images/cloud_download.svg\" class=\"image\"/></div></a>"
formatResult: (newExtensions, updatedExtensions) ->
# format result
result = ""
result += "## #{newExtensions.length} new Extensions" if newExtensions.length
result += "\n" if newExtensions.length
result += "## #{updatedExtensions.length} updated Extensions" if updatedExtensions.length
result += "\n" if updatedExtensions.length
result += "## New Extensions" + "\n" + header + "\n" + newExtensions.join("\n") if newExtensions.length
result += "\n\n" if newExtensions.length and updatedExtensions.length
result += "## Updated Extensions" + "\n" + header + "\n" + updatedExtensions.join("\n") if updatedExtensions.length
|
[
{
"context": "{2:arFields} = array(\n 'NAME' => '${3:username}',\n 'LAST_NAME' => '${4:usernamelast}',\n ",
"end": 165,
"score": 0.9892643094062805,
"start": 157,
"tag": "USERNAME",
"value": "username"
},
{
"context": " => '${3:username}',\n 'LAST_NAME' =>... | snippets/cuser.cson | pu6elozed/atom-bitrix-cmf-snippets | 0 | ".source.php":
"CUser.Add":
"prefix": "CUserAdd"
"body": """
$${1:rsUser} = new CUser;
$${2:arFields} = array(
'NAME' => '${3:username}',
'LAST_NAME' => '${4:usernamelast}',
'EMAIL' => '${5:usremail}',
'LOGIN' => '${6:login}',
'ACTIVE' => 'Y',
'GROUP_ID' => array('${7:groups}'),
'PASSWORD' => '${8:userpass}'
);
$${9:id} = $${1:rsUser}->Add($${2:arFields})
if(!$${9:id})
echo $${1:rsUser}->LAST_ERROR;$10
"""
"CUser.Delete":
"prefix": "CUserDelete"
"body": """
CUser::Delete('${1:userID}');$2
"""
"CUser.GetByID":
"prefix": "CUserGetByID"
"body": """
$${1:arUser} = CUser::GetByID('${2:userID}')->Fetch();
if(is_array($${1:arUser}))
var_export($${1:arUser});$3
"""
"CUser.GetByLogin":
"prefix": "CUserGetByLogin"
"body": """
$${1:rsUser} = CUser::GetByLogin("${2:userLogin");
$${3:arUser} = $${1rsUser}->Fetch();
var_export(${3:arUser});$4
"""
"CUser.GetID":
"prefix": "CUserGetID"
"body": """
global $USER;
echo $USER->GetID();$1
"""
"CUser.GetLogin":
"prefix": "CUserGetLogin"
"body": """
global $USER;
echo $USER->GetLogin();$1
"""
"CUser.GetFullName":
"prefix": "CUserGetFullName"
"body": """
global $USER;
echo $USER->GetFullName();$1
"""
"CUser.GetFirstName":
"prefix": "CUserGetFirstName"
"body": """
global $USER;
echo $USER->GetFirstName();$1
"""
"CUser.GetLastName":
"prefix": "CUserGetLastName"
"body": """
global $USER;
echo $USER->GetLastName();$1
"""
"CUser.GetEmail":
"prefix": "CUserGetEmail"
"body": """
global $USER;
echo $USER->GetEmail();$1
"""
"CUser.GetParam":
"prefix": "CUserGetParam"
"body": """
global $USER;
echo $USER->GetParam("${1:paramName}");$2
"""
"CUser.GetUserGroupArray":
"prefix": "CUserGetUserGroupArray"
"body": """
global $USER;
$${1:arGroups} = $USER->GetUserGroupArray();
var_export(${1:arGroups});$2
"""
"CUser.GetUserGroupList":
"prefix": "CUserGetUserGroupList"
"body": """
$${1:res} = CUser::GetUserGroupList(${2:userID});
while ($${3:arGroup} = $${1:res}->Fetch()){
var_export($${3:arGroup});$4
}
"""
"CUser.GetList":
"prefix": "CUserGetList"
"body": """
$${1:arFilter} = array(
'ACTIVE' => 'Y',
'ID' => '${2:userID}'
);
$${3:rsUsers} = CUser::GetList(
($by = "personal_country"),
($order = "desc"),
$${1:arFilter}
);
while($${4:arUsers} = ${3:rsUsers}->Fetch()){
var_export($${4:arUsers});
}$5
"""
"CUser.GetUserGroup":
"prefix": "CUserGetUserGroup"
"body": """
$${1:arGroups} = CUser::GetUserGroup(${2:userID});
var_export($${1:arGroups});$3
"""
"CUser.GetUserGroupString":
"prefix": "CUserGetUserGroupSring"
"body": """
global $USER;
$${1:strGroups} = $USER->GetUserGroupString();
echo $${1:strGroups};$2
"""
"CUser.IsAdmin":
"prefix": "CUserIsAdmin"
"body": """
global $USER;
$USER->IsAdmin();$1
"""
"CUser.IsAuthorized":
"prefix": "CUserIsAuthorized"
"body": """
global $USER;
$USER->IsAuthorized();$1
"""
"CUser.IsOnLine":
"prefix": "CUserIsOnLine"
"body": """
CUser::IsOnLine(${1:userID});$2
"""
"CUser.Login":
"prefix": "CUserLogin"
"body": """
global $USER;
if (!is_object($USER)) $USER = new CUser;
$${1:arAuthResult} = $USER->Login("${2:login}", "${3:pass}", "Y");
$APPLICATION->arAuthResult = $${1:arAuthResult};$4
"""
"CUser.LoginByHash":
"prefix": "CUserLoginByHash"
"body": """
global $USER;
if (!is_object($USER)) $USER = new CUser;
$${1:cookie_login} = ${COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_LOGIN"};
$${2:cookie_md5pass} = ${COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_UIDH"};
$USER->LoginByHash($${1:cookie_login}, $${2:cookie_md5pass});$3
"""
"CUser.SavePasswordHash":
"prefix": "CUserSavePassHash"
"body": """
global $USER;
if ($USER->IsAuthorized()) $USER->SavePasswordHash();$1
"""
"CUser.GetPasswordHash":
"prefix": "CUserGetPassHash"
"body": """
global $USER;
$${1:hash} = CUser::GetPasswordHash($USER->GetParam("PASSWORD_HASH"));$2
"""
"CUser.Authorize":
"prefix": "CUserAuthorize"
"body": """
global $USER;
$USER->Authorize(${1:userID});$2
"""
"CUser.Logout":
"prefix": "CUserLogout"
"body": """
global $USER;
$USER->Logout();$1
"""
"CUser.Register":
"prefix": "CUserRegister"
"body": """
global $USER;
$${1:arResult} = $USER->Register(
"${2:username}",
"${3:firstname}",
"${4:lastname}",
"${5:pass}",
"${6:confirm_pass}",
"${7:email}");
ShowMessage($${1:arResult});
echo $USER->GetID();$8
"""
"CUser.SimpleRegister":
"prefix": "CUserSimpleRegister"
"body": """
global $USER;
$${1:arResult} = $USER->SimpleRegister("${2:email}");
ShowMessage($${1:arResult});
echo $USER->GetID();$3
"""
"CUser.ChangePassword":
"prefix": "CUserChangePass"
"body": """
global $USER;
$${1:arResult} = $USER->ChangePassword(
"${2:username}",
"${3:checkword}",
"${4:password}",
"${4:confirm_pass}");
if($${1:arResult}["TYPE"] == "OK") echo "Password has been changed.";
else ShowMessage($${1:arResult});$5
"""
"CUser.SendPassword":
"prefix": "CUserSendPass"
"body": """
global $USER;
$${1:arResult} = $USER->SendPassword("${2:username}", "${3:email}");
if($${1:arResult}["TYPE"] == "OK") echo "Hash string sended to email.";
else echo "Not found login(email).";$4
"""
"CUser.SendUserInfo":
"prefix": "CUserSendUserInfo"
"body": """
CUser::SendUserInfo(${1:userID}, SITE_ID, "${2:message}");$3
"""
"CUser.GetCount":
"prefix": "CUserGetCount"
"body": """
CUser::GetCount();$1
"""
"CUser.GetExternalAuthList":
"prefix": "CUserGetExAuthList"
"body": """
$${1:rsExtAuth} = CUser::GetExternalAuthList();
if($${2arExtAuth} = $${1:rsExtAuth}->GetNext()):
var_export($${2:arExtAuth});$3
"""
"CUser.SetParam":
"prefix": "CUserSetParam"
"body": """
global $USER;
$USER->SetParam("${1:paramName}", "${2:param}");$3
"""
"CUser.SetUserGroup":
"prefix": "CUserSetGroup"
"body": """
$${1:arGroups} = CUser::GetUserGroup(${2:userID});
$${1:arGroups}[] = ${3:groupId};
CUser::SetUserGroup(${2:userID}, $${1:arGroups});$4
"""
"CUser.SetUserGroupArray":
"prefix": "CUserSetGroupArray"
"body": """
global $USER;
$${1:arGroups} = $USER->GetUserGroupArray();
$${1:arGroups}[] = ${2:groupId};
$USER->SetUserGroupArray($${1:arGroups});
"""
"CUser.SetLastActivityDate":
"prefix": "CUserSetLastActivity"
"body": """
CUser::SetLastActivityDate(${1:userID});$2
"""
"CUser.CanDoFileOperation":
"prefix": "CUserCanDoFileOperation"
"body": """
$${1:arPath} = Array(${2:site}, ${3:path});
$USER->CanDoFileOperation("${4:operation}", $${1:arPath});$5
"""
"CUser.Update":
"prefix": "CUserUpdate",
"body": """
$${1:arFields} = array(
'NAME' => '${2:newusername}',
'EMAIL' => '${3:newusremail}',
....
);
$${4:rsUser} = new CUser;
$${4:rsUser}->Update('${5:usrID}', $${1:arFields});
$6
"""
| 175970 | ".source.php":
"CUser.Add":
"prefix": "CUserAdd"
"body": """
$${1:rsUser} = new CUser;
$${2:arFields} = array(
'NAME' => '${3:username}',
'LAST_NAME' => '${4:usernamelast}',
'EMAIL' => '${5:usremail}',
'LOGIN' => '${6:login}',
'ACTIVE' => 'Y',
'GROUP_ID' => array('${7:groups}'),
'PASSWORD' => <PASSWORD>}'
);
$${9:id} = $${1:rsUser}->Add($${2:arFields})
if(!$${9:id})
echo $${1:rsUser}->LAST_ERROR;$10
"""
"CUser.Delete":
"prefix": "CUserDelete"
"body": """
CUser::Delete('${1:userID}');$2
"""
"CUser.GetByID":
"prefix": "CUserGetByID"
"body": """
$${1:arUser} = CUser::GetByID('${2:userID}')->Fetch();
if(is_array($${1:arUser}))
var_export($${1:arUser});$3
"""
"CUser.GetByLogin":
"prefix": "CUserGetByLogin"
"body": """
$${1:rsUser} = CUser::GetByLogin("${2:userLogin");
$${3:arUser} = $${1rsUser}->Fetch();
var_export(${3:arUser});$4
"""
"CUser.GetID":
"prefix": "CUserGetID"
"body": """
global $USER;
echo $USER->GetID();$1
"""
"CUser.GetLogin":
"prefix": "CUserGetLogin"
"body": """
global $USER;
echo $USER->GetLogin();$1
"""
"CUser.GetFullName":
"prefix": "CUserGetFullName"
"body": """
global $USER;
echo $USER->GetFullName();$1
"""
"CUser.GetFirstName":
"prefix": "CUserGetFirstName"
"body": """
global $USER;
echo $USER->GetFirstName();$1
"""
"CUser.GetLastName":
"prefix": "CUserGetLastName"
"body": """
global $USER;
echo $USER->GetLastName();$1
"""
"CUser.GetEmail":
"prefix": "CUserGetEmail"
"body": """
global $USER;
echo $USER->GetEmail();$1
"""
"CUser.GetParam":
"prefix": "CUserGetParam"
"body": """
global $USER;
echo $USER->GetParam("${1:paramName}");$2
"""
"CUser.GetUserGroupArray":
"prefix": "CUserGetUserGroupArray"
"body": """
global $USER;
$${1:arGroups} = $USER->GetUserGroupArray();
var_export(${1:arGroups});$2
"""
"CUser.GetUserGroupList":
"prefix": "CUserGetUserGroupList"
"body": """
$${1:res} = CUser::GetUserGroupList(${2:userID});
while ($${3:arGroup} = $${1:res}->Fetch()){
var_export($${3:arGroup});$4
}
"""
"CUser.GetList":
"prefix": "CUserGetList"
"body": """
$${1:arFilter} = array(
'ACTIVE' => 'Y',
'ID' => '${2:userID}'
);
$${3:rsUsers} = CUser::GetList(
($by = "personal_country"),
($order = "desc"),
$${1:arFilter}
);
while($${4:arUsers} = ${3:rsUsers}->Fetch()){
var_export($${4:arUsers});
}$5
"""
"CUser.GetUserGroup":
"prefix": "CUserGetUserGroup"
"body": """
$${1:arGroups} = CUser::GetUserGroup(${2:userID});
var_export($${1:arGroups});$3
"""
"CUser.GetUserGroupString":
"prefix": "CUserGetUserGroupSring"
"body": """
global $USER;
$${1:strGroups} = $USER->GetUserGroupString();
echo $${1:strGroups};$2
"""
"CUser.IsAdmin":
"prefix": "CUserIsAdmin"
"body": """
global $USER;
$USER->IsAdmin();$1
"""
"CUser.IsAuthorized":
"prefix": "CUserIsAuthorized"
"body": """
global $USER;
$USER->IsAuthorized();$1
"""
"CUser.IsOnLine":
"prefix": "CUserIsOnLine"
"body": """
CUser::IsOnLine(${1:userID});$2
"""
"CUser.Login":
"prefix": "CUserLogin"
"body": """
global $USER;
if (!is_object($USER)) $USER = new CUser;
$${1:arAuthResult} = $USER->Login("${2:login}", "${3:pass}", "Y");
$APPLICATION->arAuthResult = $${1:arAuthResult};$4
"""
"CUser.LoginByHash":
"prefix": "CUserLoginByHash"
"body": """
global $USER;
if (!is_object($USER)) $USER = new CUser;
$${1:cookie_login} = ${COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_LOGIN"};
$${2:cookie_md5pass} = ${COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_UIDH"};
$USER->LoginByHash($${1:cookie_login}, $${2:cookie_md5pass});$3
"""
"CUser.SavePasswordHash":
"prefix": "CUserSavePassHash"
"body": """
global $USER;
if ($USER->IsAuthorized()) $USER->SavePasswordHash();$1
"""
"CUser.GetPasswordHash":
"prefix": "CUserGetPassHash"
"body": """
global $USER;
$${1:hash} = CUser::GetPasswordHash($USER->GetParam("PASSWORD_HASH"));$2
"""
"CUser.Authorize":
"prefix": "CUserAuthorize"
"body": """
global $USER;
$USER->Authorize(${1:userID});$2
"""
"CUser.Logout":
"prefix": "CUserLogout"
"body": """
global $USER;
$USER->Logout();$1
"""
"CUser.Register":
"prefix": "CUserRegister"
"body": """
global $USER;
$${1:arResult} = $USER->Register(
"${2:username}",
"${3:firstname}",
"${4:lastname}",
"${5:pass}",
"${6:confirm_pass}",
"${7:email}");
ShowMessage($${1:arResult});
echo $USER->GetID();$8
"""
"CUser.SimpleRegister":
"prefix": "CUserSimpleRegister"
"body": """
global $USER;
$${1:arResult} = $USER->SimpleRegister("${2:email}");
ShowMessage($${1:arResult});
echo $USER->GetID();$3
"""
"CUser.ChangePassword":
"prefix": "CUserChangePass"
"body": """
global $USER;
$${1:arResult} = $USER->ChangePassword(
"${2:username}",
"${3:checkword}",
"${4:password}",
"${4:confirm_pass}");
if($${1:arResult}["TYPE"] == "OK") echo "Password has been changed.";
else ShowMessage($${1:arResult});$5
"""
"CUser.SendPassword":
"prefix": "CUserSendPass"
"body": """
global $USER;
$${1:arResult} = $USER->SendPassword("${2:username}", "${3:email}");
if($${1:arResult}["TYPE"] == "OK") echo "Hash string sended to email.";
else echo "Not found login(email).";$4
"""
"CUser.SendUserInfo":
"prefix": "CUserSendUserInfo"
"body": """
CUser::SendUserInfo(${1:userID}, SITE_ID, "${2:message}");$3
"""
"CUser.GetCount":
"prefix": "CUserGetCount"
"body": """
CUser::GetCount();$1
"""
"CUser.GetExternalAuthList":
"prefix": "CUserGetExAuthList"
"body": """
$${1:rsExtAuth} = CUser::GetExternalAuthList();
if($${2arExtAuth} = $${1:rsExtAuth}->GetNext()):
var_export($${2:arExtAuth});$3
"""
"CUser.SetParam":
"prefix": "CUserSetParam"
"body": """
global $USER;
$USER->SetParam("${1:paramName}", "${2:param}");$3
"""
"CUser.SetUserGroup":
"prefix": "CUserSetGroup"
"body": """
$${1:arGroups} = CUser::GetUserGroup(${2:userID});
$${1:arGroups}[] = ${3:groupId};
CUser::SetUserGroup(${2:userID}, $${1:arGroups});$4
"""
"CUser.SetUserGroupArray":
"prefix": "CUserSetGroupArray"
"body": """
global $USER;
$${1:arGroups} = $USER->GetUserGroupArray();
$${1:arGroups}[] = ${2:groupId};
$USER->SetUserGroupArray($${1:arGroups});
"""
"CUser.SetLastActivityDate":
"prefix": "CUserSetLastActivity"
"body": """
CUser::SetLastActivityDate(${1:userID});$2
"""
"CUser.CanDoFileOperation":
"prefix": "CUserCanDoFileOperation"
"body": """
$${1:arPath} = Array(${2:site}, ${3:path});
$USER->CanDoFileOperation("${4:operation}", $${1:arPath});$5
"""
"CUser.Update":
"prefix": "CUserUpdate",
"body": """
$${1:arFields} = array(
'NAME' => '${2:newusername}',
'EMAIL' => '${3:newusremail}',
....
);
$${4:rsUser} = new CUser;
$${4:rsUser}->Update('${5:usrID}', $${1:arFields});
$6
"""
| true | ".source.php":
"CUser.Add":
"prefix": "CUserAdd"
"body": """
$${1:rsUser} = new CUser;
$${2:arFields} = array(
'NAME' => '${3:username}',
'LAST_NAME' => '${4:usernamelast}',
'EMAIL' => '${5:usremail}',
'LOGIN' => '${6:login}',
'ACTIVE' => 'Y',
'GROUP_ID' => array('${7:groups}'),
'PASSWORD' => PI:PASSWORD:<PASSWORD>END_PI}'
);
$${9:id} = $${1:rsUser}->Add($${2:arFields})
if(!$${9:id})
echo $${1:rsUser}->LAST_ERROR;$10
"""
"CUser.Delete":
"prefix": "CUserDelete"
"body": """
CUser::Delete('${1:userID}');$2
"""
"CUser.GetByID":
"prefix": "CUserGetByID"
"body": """
$${1:arUser} = CUser::GetByID('${2:userID}')->Fetch();
if(is_array($${1:arUser}))
var_export($${1:arUser});$3
"""
"CUser.GetByLogin":
"prefix": "CUserGetByLogin"
"body": """
$${1:rsUser} = CUser::GetByLogin("${2:userLogin");
$${3:arUser} = $${1rsUser}->Fetch();
var_export(${3:arUser});$4
"""
"CUser.GetID":
"prefix": "CUserGetID"
"body": """
global $USER;
echo $USER->GetID();$1
"""
"CUser.GetLogin":
"prefix": "CUserGetLogin"
"body": """
global $USER;
echo $USER->GetLogin();$1
"""
"CUser.GetFullName":
"prefix": "CUserGetFullName"
"body": """
global $USER;
echo $USER->GetFullName();$1
"""
"CUser.GetFirstName":
"prefix": "CUserGetFirstName"
"body": """
global $USER;
echo $USER->GetFirstName();$1
"""
"CUser.GetLastName":
"prefix": "CUserGetLastName"
"body": """
global $USER;
echo $USER->GetLastName();$1
"""
"CUser.GetEmail":
"prefix": "CUserGetEmail"
"body": """
global $USER;
echo $USER->GetEmail();$1
"""
"CUser.GetParam":
"prefix": "CUserGetParam"
"body": """
global $USER;
echo $USER->GetParam("${1:paramName}");$2
"""
"CUser.GetUserGroupArray":
"prefix": "CUserGetUserGroupArray"
"body": """
global $USER;
$${1:arGroups} = $USER->GetUserGroupArray();
var_export(${1:arGroups});$2
"""
"CUser.GetUserGroupList":
"prefix": "CUserGetUserGroupList"
"body": """
$${1:res} = CUser::GetUserGroupList(${2:userID});
while ($${3:arGroup} = $${1:res}->Fetch()){
var_export($${3:arGroup});$4
}
"""
"CUser.GetList":
"prefix": "CUserGetList"
"body": """
$${1:arFilter} = array(
'ACTIVE' => 'Y',
'ID' => '${2:userID}'
);
$${3:rsUsers} = CUser::GetList(
($by = "personal_country"),
($order = "desc"),
$${1:arFilter}
);
while($${4:arUsers} = ${3:rsUsers}->Fetch()){
var_export($${4:arUsers});
}$5
"""
"CUser.GetUserGroup":
"prefix": "CUserGetUserGroup"
"body": """
$${1:arGroups} = CUser::GetUserGroup(${2:userID});
var_export($${1:arGroups});$3
"""
"CUser.GetUserGroupString":
"prefix": "CUserGetUserGroupSring"
"body": """
global $USER;
$${1:strGroups} = $USER->GetUserGroupString();
echo $${1:strGroups};$2
"""
"CUser.IsAdmin":
"prefix": "CUserIsAdmin"
"body": """
global $USER;
$USER->IsAdmin();$1
"""
"CUser.IsAuthorized":
"prefix": "CUserIsAuthorized"
"body": """
global $USER;
$USER->IsAuthorized();$1
"""
"CUser.IsOnLine":
"prefix": "CUserIsOnLine"
"body": """
CUser::IsOnLine(${1:userID});$2
"""
"CUser.Login":
"prefix": "CUserLogin"
"body": """
global $USER;
if (!is_object($USER)) $USER = new CUser;
$${1:arAuthResult} = $USER->Login("${2:login}", "${3:pass}", "Y");
$APPLICATION->arAuthResult = $${1:arAuthResult};$4
"""
"CUser.LoginByHash":
"prefix": "CUserLoginByHash"
"body": """
global $USER;
if (!is_object($USER)) $USER = new CUser;
$${1:cookie_login} = ${COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_LOGIN"};
$${2:cookie_md5pass} = ${COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_UIDH"};
$USER->LoginByHash($${1:cookie_login}, $${2:cookie_md5pass});$3
"""
"CUser.SavePasswordHash":
"prefix": "CUserSavePassHash"
"body": """
global $USER;
if ($USER->IsAuthorized()) $USER->SavePasswordHash();$1
"""
"CUser.GetPasswordHash":
"prefix": "CUserGetPassHash"
"body": """
global $USER;
$${1:hash} = CUser::GetPasswordHash($USER->GetParam("PASSWORD_HASH"));$2
"""
"CUser.Authorize":
"prefix": "CUserAuthorize"
"body": """
global $USER;
$USER->Authorize(${1:userID});$2
"""
"CUser.Logout":
"prefix": "CUserLogout"
"body": """
global $USER;
$USER->Logout();$1
"""
"CUser.Register":
"prefix": "CUserRegister"
"body": """
global $USER;
$${1:arResult} = $USER->Register(
"${2:username}",
"${3:firstname}",
"${4:lastname}",
"${5:pass}",
"${6:confirm_pass}",
"${7:email}");
ShowMessage($${1:arResult});
echo $USER->GetID();$8
"""
"CUser.SimpleRegister":
"prefix": "CUserSimpleRegister"
"body": """
global $USER;
$${1:arResult} = $USER->SimpleRegister("${2:email}");
ShowMessage($${1:arResult});
echo $USER->GetID();$3
"""
"CUser.ChangePassword":
"prefix": "CUserChangePass"
"body": """
global $USER;
$${1:arResult} = $USER->ChangePassword(
"${2:username}",
"${3:checkword}",
"${4:password}",
"${4:confirm_pass}");
if($${1:arResult}["TYPE"] == "OK") echo "Password has been changed.";
else ShowMessage($${1:arResult});$5
"""
"CUser.SendPassword":
"prefix": "CUserSendPass"
"body": """
global $USER;
$${1:arResult} = $USER->SendPassword("${2:username}", "${3:email}");
if($${1:arResult}["TYPE"] == "OK") echo "Hash string sended to email.";
else echo "Not found login(email).";$4
"""
"CUser.SendUserInfo":
"prefix": "CUserSendUserInfo"
"body": """
CUser::SendUserInfo(${1:userID}, SITE_ID, "${2:message}");$3
"""
"CUser.GetCount":
"prefix": "CUserGetCount"
"body": """
CUser::GetCount();$1
"""
"CUser.GetExternalAuthList":
"prefix": "CUserGetExAuthList"
"body": """
$${1:rsExtAuth} = CUser::GetExternalAuthList();
if($${2arExtAuth} = $${1:rsExtAuth}->GetNext()):
var_export($${2:arExtAuth});$3
"""
"CUser.SetParam":
"prefix": "CUserSetParam"
"body": """
global $USER;
$USER->SetParam("${1:paramName}", "${2:param}");$3
"""
"CUser.SetUserGroup":
"prefix": "CUserSetGroup"
"body": """
$${1:arGroups} = CUser::GetUserGroup(${2:userID});
$${1:arGroups}[] = ${3:groupId};
CUser::SetUserGroup(${2:userID}, $${1:arGroups});$4
"""
"CUser.SetUserGroupArray":
"prefix": "CUserSetGroupArray"
"body": """
global $USER;
$${1:arGroups} = $USER->GetUserGroupArray();
$${1:arGroups}[] = ${2:groupId};
$USER->SetUserGroupArray($${1:arGroups});
"""
"CUser.SetLastActivityDate":
"prefix": "CUserSetLastActivity"
"body": """
CUser::SetLastActivityDate(${1:userID});$2
"""
"CUser.CanDoFileOperation":
"prefix": "CUserCanDoFileOperation"
"body": """
$${1:arPath} = Array(${2:site}, ${3:path});
$USER->CanDoFileOperation("${4:operation}", $${1:arPath});$5
"""
"CUser.Update":
"prefix": "CUserUpdate",
"body": """
$${1:arFields} = array(
'NAME' => '${2:newusername}',
'EMAIL' => '${3:newusremail}',
....
);
$${4:rsUser} = new CUser;
$${4:rsUser}->Update('${5:usrID}', $${1:arFields});
$6
"""
|
[
{
"context": "-md5\"]\n\nbasic =\n use: 'none',\n http:\n host: '127.0.0.1'\n port: 8099\n socks5:\n host: \"127.0.0.1\",\n",
"end": 527,
"score": 0.9997145533561707,
"start": 518,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": ": '127.0.0.1'\n port: 8099\n ... | views/components/settings/parts/network-config.cjsx | dazzyd/poi | 0 | path = require 'path-extra'
i18n = require 'i18n'
{$, $$, _, React, ReactBootstrap, ROOT, toggleModal} = window
{config} = window
{Input, Grid, Col, Button, Alert} = ReactBootstrap
{__, __n} = i18n
Divider = require './divider'
shadowsocksMethods = ["aes-256-cfb", "aes-192-cfb", "aes-128-cfb", "bf-cfb",
"camellia-256-cfb", "camellia-192-cfb", "camellia-128-cfb",
"cast5-cfb", "des-cfb", "idea-cfb", "rc2-cfb", "rc4", "rc4-md5"]
basic =
use: 'none',
http:
host: '127.0.0.1'
port: 8099
socks5:
host: "127.0.0.1",
port: 1080
shadowsocks:
server:
host: "116.251.209.211",
port: 27017
local:
port: 12451
password: "@_PoiPublic_@",
method: "aes-256-cfb",
timeout: 600000,
port: "@_PoiPublic_@"
retries: config.get 'poi.proxy.retries', 0
NetworkConfig = React.createClass
getInitialState: ->
_.extend basic, Object.remoteClone(config.get 'proxy', {})
handleChangeUse: ->
use = @refs.use.getValue()
@setState {use}
handleSaveConfig: (e) ->
use = @refs.use.getValue()
switch use
when 'http'
config.set 'proxy.use', 'http'
config.set 'proxy.http.host', @refs.httpHost.getValue()
config.set 'proxy.http.port', @refs.httpPort.getValue()
when 'socks5'
config.set 'proxy.use', 'socks5'
config.set 'proxy.socks5.host', @refs.socksHost.getValue()
config.set 'proxy.socks5.port', @refs.socksPort.getValue()
when 'shadowsocks'
config.set 'proxy.use', 'shadowsocks'
config.set 'proxy.shadowsocks.server.host', @refs.shadowsocksServerHost.getValue()
config.set 'proxy.shadowsocks.server.port', @refs.shadowsocksServerPort.getValue()
config.set 'proxy.shadowsocks.password', @refs.shadowsocksPassword.getValue()
config.set 'proxy.shadowsocks.method', @refs.shadowsocksMethod.getValue()
else
config.set 'proxy.use', 'none'
toggleModal __('Proxy setting'), __('Success! It will be available after a restart.')
e.preventDefault()
handleHttpHostChange: (e) ->
{http} = @state
http.host = e.target.value
@setState {http}
handleHttpPortChange: (e) ->
{http} = @state
http.port = e.target.value
@setState {http}
handleSocksHostChange: (e) ->
{socks5} = @state
socks5.host = e.target.value
@setState {socks5}
handleSocksPortChange: (e) ->
{socks5} = @state
socks5.port = e.target.value
@setState {socks5}
handleShadowsocksServerHostChange: (e) ->
{shadowsocks} = @state
shadowsocks.server.host = e.target.value
@setState {shadowsocks}
handleShadowsocksServerPortChange: (e) ->
{shadowsocks} = @state
shadowsocks.server.port = e.target.value
@setState {shadowsocks}
handleShadowsocksPasswordChange: (e) ->
{shadowsocks} = @state
shadowsocks.password = e.target.value
@setState {shadowsocks}
handleShadowsocksMethodChange: (e) ->
{shadowsocks} = @state
shadowsocks.method = e.target.value
@setState {shadowsocks}
handleSetRetries: (e) ->
@setState
retries: e.target.value
r = parseInt(e.target.value)
return if isNaN(r) || r < 0
config.set 'poi.proxy.retries', r
render: ->
<form>
<Divider text={__ 'Proxy protocol'} />
<Grid>
<Col xs={12}>
<Input type="select" ref="use" value={@state.use || "none"} onChange={@handleChangeUse}>
<option key={0} value="http">HTTP {__ "proxy"}</option>
<option key={1} value="socks5">Socks5 {__ "proxy"}</option>
<option key={2} value="shadowsocks">Shadowsocks</option>
<option key={3} value="none">{__ "No proxy"}</option>
</Input>
</Col>
</Grid>
<Divider text={__ 'Proxy server information'} />
{
if @state.use == 'http'
<Grid>
<Col xs={6}>
<Input type="text" ref="httpHost" label={__ 'Proxy server address'} placeholder="输入代理地址" value={@state?.http?.host} onChange={@handleHttpHostChange} />
</Col>
<Col xs={6}>
<Input type="text" ref="httpPort" label={__ 'Proxy server port'} placeholder="输入代理端口" value={@state?.http?.port} onChange={@handleHttpPortChange} />
</Col>
</Grid>
else if @state.use == 'socks5'
<Grid>
<Col xs={6}>
<Input type="text" ref="socksHost" label={__ 'Proxy server address'} placeholder="输入代理地址" value={@state?.socks5?.host} onChange={@handleSocksHostChange} />
</Col>
<Col xs={6}>
<Input type="text" ref="socksPort" label={__ 'Proxy server port'} placeholder="输入代理端口" value={@state?.socks5?.port} onChange={@handleSocksPortChange} />
</Col>
</Grid>
else if @state.use == 'shadowsocks'
<Grid>
<Col xs={6}>
<Input type="text" ref="shadowsocksServerHost" label={__ 'Proxy server address'} placeholder="Shadowsocks 服务器地址" value={@state?.shadowsocks?.server?.host} onChange={@handleShadowsocksServerHostChange} />
</Col>
<Col xs={6}>
<Input type="text" ref="shadowsocksServerPort" label={__ 'Proxy server port'} placeholder="Shadowsocks 服务器端口" value={@state?.shadowsocks?.server?.port} onChange={@handleShadowsocksServerPortChange} />
</Col>
<Col xs={6}>
<Input type="password" ref="shadowsocksPassword" label={__ 'Password'} placeholder="Shadowsocks 密码" value={@state?.shadowsocks?.password} onChange={@handleShadowsocksPasswordChange} />
</Col>
<Col xs={6}>
<Input type="select" ref="shadowsocksMethod" label={__ 'Encryption algorithm'} placeholder="Shadowsocks 加密方式" value={@state?.shadowsocks?.method} onChange={@handleShadowsocksMethodChange}>
{
shadowsocksMethods.map (method, index) ->
<option key={index} value={method}>{method.toUpperCase()}</option>
}
</Input>
</Col>
</Grid>
else
<Grid>
<Col xs={12}>
<center>{__ 'Will connect to server directly.'}</center>
</Col>
</Grid>
}
<Divider text={__ 'Times of reconnect'} />
<Grid>
<Col xs={12}>
<Input type="number" ref="retries" value={@state.retries} onChange={@handleSetRetries} />
</Col>
<Col xs={12}>
<Alert bsStyle='danger'>
{__ 'It may be unsafe!'}
</Alert>
</Col>
</Grid>
<Divider text={__ 'Save settings'} />
<Grid>
<Col xs={12}>
<Button bsStyle="success" onClick={@handleSaveConfig} style={width: '100%'}>{__ 'Save'}</Button>
</Col>
</Grid>
</form>
module.exports = NetworkConfig
| 81577 | path = require 'path-extra'
i18n = require 'i18n'
{$, $$, _, React, ReactBootstrap, ROOT, toggleModal} = window
{config} = window
{Input, Grid, Col, Button, Alert} = ReactBootstrap
{__, __n} = i18n
Divider = require './divider'
shadowsocksMethods = ["aes-256-cfb", "aes-192-cfb", "aes-128-cfb", "bf-cfb",
"camellia-256-cfb", "camellia-192-cfb", "camellia-128-cfb",
"cast5-cfb", "des-cfb", "idea-cfb", "rc2-cfb", "rc4", "rc4-md5"]
basic =
use: 'none',
http:
host: '127.0.0.1'
port: 8099
socks5:
host: "127.0.0.1",
port: 1080
shadowsocks:
server:
host: "172.16.31.10",
port: 27017
local:
port: 12451
password: <PASSWORD>@",
method: "aes-256-cfb",
timeout: 600000,
port: "@_PoiPublic_@"
retries: config.get 'poi.proxy.retries', 0
NetworkConfig = React.createClass
getInitialState: ->
_.extend basic, Object.remoteClone(config.get 'proxy', {})
handleChangeUse: ->
use = @refs.use.getValue()
@setState {use}
handleSaveConfig: (e) ->
use = @refs.use.getValue()
switch use
when 'http'
config.set 'proxy.use', 'http'
config.set 'proxy.http.host', @refs.httpHost.getValue()
config.set 'proxy.http.port', @refs.httpPort.getValue()
when 'socks5'
config.set 'proxy.use', 'socks5'
config.set 'proxy.socks5.host', @refs.socksHost.getValue()
config.set 'proxy.socks5.port', @refs.socksPort.getValue()
when 'shadowsocks'
config.set 'proxy.use', 'shadowsocks'
config.set 'proxy.shadowsocks.server.host', @refs.shadowsocksServerHost.getValue()
config.set 'proxy.shadowsocks.server.port', @refs.shadowsocksServerPort.getValue()
config.set 'proxy.shadowsocks.password', @refs.shadowsocksPassword.getValue()
config.set 'proxy.shadowsocks.method', @refs.shadowsocksMethod.getValue()
else
config.set 'proxy.use', 'none'
toggleModal __('Proxy setting'), __('Success! It will be available after a restart.')
e.preventDefault()
handleHttpHostChange: (e) ->
{http} = @state
http.host = e.target.value
@setState {http}
handleHttpPortChange: (e) ->
{http} = @state
http.port = e.target.value
@setState {http}
handleSocksHostChange: (e) ->
{socks5} = @state
socks5.host = e.target.value
@setState {socks5}
handleSocksPortChange: (e) ->
{socks5} = @state
socks5.port = e.target.value
@setState {socks5}
handleShadowsocksServerHostChange: (e) ->
{shadowsocks} = @state
shadowsocks.server.host = e.target.value
@setState {shadowsocks}
handleShadowsocksServerPortChange: (e) ->
{shadowsocks} = @state
shadowsocks.server.port = e.target.value
@setState {shadowsocks}
handleShadowsocksPasswordChange: (e) ->
{shadowsocks} = @state
shadowsocks.password = e.target.value
@setState {shadowsocks}
handleShadowsocksMethodChange: (e) ->
{shadowsocks} = @state
shadowsocks.method = e.target.value
@setState {shadowsocks}
handleSetRetries: (e) ->
@setState
retries: e.target.value
r = parseInt(e.target.value)
return if isNaN(r) || r < 0
config.set 'poi.proxy.retries', r
render: ->
<form>
<Divider text={__ 'Proxy protocol'} />
<Grid>
<Col xs={12}>
<Input type="select" ref="use" value={@state.use || "none"} onChange={@handleChangeUse}>
<option key={0} value="http">HTTP {__ "proxy"}</option>
<option key={1} value="socks5">Socks5 {__ "proxy"}</option>
<option key={2} value="shadowsocks">Shadowsocks</option>
<option key={3} value="none">{__ "No proxy"}</option>
</Input>
</Col>
</Grid>
<Divider text={__ 'Proxy server information'} />
{
if @state.use == 'http'
<Grid>
<Col xs={6}>
<Input type="text" ref="httpHost" label={__ 'Proxy server address'} placeholder="输入代理地址" value={@state?.http?.host} onChange={@handleHttpHostChange} />
</Col>
<Col xs={6}>
<Input type="text" ref="httpPort" label={__ 'Proxy server port'} placeholder="输入代理端口" value={@state?.http?.port} onChange={@handleHttpPortChange} />
</Col>
</Grid>
else if @state.use == 'socks5'
<Grid>
<Col xs={6}>
<Input type="text" ref="socksHost" label={__ 'Proxy server address'} placeholder="输入代理地址" value={@state?.socks5?.host} onChange={@handleSocksHostChange} />
</Col>
<Col xs={6}>
<Input type="text" ref="socksPort" label={__ 'Proxy server port'} placeholder="输入代理端口" value={@state?.socks5?.port} onChange={@handleSocksPortChange} />
</Col>
</Grid>
else if @state.use == 'shadowsocks'
<Grid>
<Col xs={6}>
<Input type="text" ref="shadowsocksServerHost" label={__ 'Proxy server address'} placeholder="Shadowsocks 服务器地址" value={@state?.shadowsocks?.server?.host} onChange={@handleShadowsocksServerHostChange} />
</Col>
<Col xs={6}>
<Input type="text" ref="shadowsocksServerPort" label={__ 'Proxy server port'} placeholder="Shadowsocks 服务器端口" value={@state?.shadowsocks?.server?.port} onChange={@handleShadowsocksServerPortChange} />
</Col>
<Col xs={6}>
<Input type="password" ref="shadowsocksPassword" label={__ 'Password'} placeholder="Shadowsocks 密码" value={@state?.shadowsocks?.password} onChange={@handleShadowsocksPasswordChange} />
</Col>
<Col xs={6}>
<Input type="select" ref="shadowsocksMethod" label={__ 'Encryption algorithm'} placeholder="Shadowsocks 加密方式" value={@state?.shadowsocks?.method} onChange={@handleShadowsocksMethodChange}>
{
shadowsocksMethods.map (method, index) ->
<option key={index} value={method}>{method.toUpperCase()}</option>
}
</Input>
</Col>
</Grid>
else
<Grid>
<Col xs={12}>
<center>{__ 'Will connect to server directly.'}</center>
</Col>
</Grid>
}
<Divider text={__ 'Times of reconnect'} />
<Grid>
<Col xs={12}>
<Input type="number" ref="retries" value={@state.retries} onChange={@handleSetRetries} />
</Col>
<Col xs={12}>
<Alert bsStyle='danger'>
{__ 'It may be unsafe!'}
</Alert>
</Col>
</Grid>
<Divider text={__ 'Save settings'} />
<Grid>
<Col xs={12}>
<Button bsStyle="success" onClick={@handleSaveConfig} style={width: '100%'}>{__ 'Save'}</Button>
</Col>
</Grid>
</form>
module.exports = NetworkConfig
| true | path = require 'path-extra'
i18n = require 'i18n'
{$, $$, _, React, ReactBootstrap, ROOT, toggleModal} = window
{config} = window
{Input, Grid, Col, Button, Alert} = ReactBootstrap
{__, __n} = i18n
Divider = require './divider'
shadowsocksMethods = ["aes-256-cfb", "aes-192-cfb", "aes-128-cfb", "bf-cfb",
"camellia-256-cfb", "camellia-192-cfb", "camellia-128-cfb",
"cast5-cfb", "des-cfb", "idea-cfb", "rc2-cfb", "rc4", "rc4-md5"]
basic =
use: 'none',
http:
host: '127.0.0.1'
port: 8099
socks5:
host: "127.0.0.1",
port: 1080
shadowsocks:
server:
host: "PI:IP_ADDRESS:172.16.31.10END_PI",
port: 27017
local:
port: 12451
password: PI:PASSWORD:<PASSWORD>END_PI@",
method: "aes-256-cfb",
timeout: 600000,
port: "@_PoiPublic_@"
retries: config.get 'poi.proxy.retries', 0
NetworkConfig = React.createClass
getInitialState: ->
_.extend basic, Object.remoteClone(config.get 'proxy', {})
handleChangeUse: ->
use = @refs.use.getValue()
@setState {use}
handleSaveConfig: (e) ->
use = @refs.use.getValue()
switch use
when 'http'
config.set 'proxy.use', 'http'
config.set 'proxy.http.host', @refs.httpHost.getValue()
config.set 'proxy.http.port', @refs.httpPort.getValue()
when 'socks5'
config.set 'proxy.use', 'socks5'
config.set 'proxy.socks5.host', @refs.socksHost.getValue()
config.set 'proxy.socks5.port', @refs.socksPort.getValue()
when 'shadowsocks'
config.set 'proxy.use', 'shadowsocks'
config.set 'proxy.shadowsocks.server.host', @refs.shadowsocksServerHost.getValue()
config.set 'proxy.shadowsocks.server.port', @refs.shadowsocksServerPort.getValue()
config.set 'proxy.shadowsocks.password', @refs.shadowsocksPassword.getValue()
config.set 'proxy.shadowsocks.method', @refs.shadowsocksMethod.getValue()
else
config.set 'proxy.use', 'none'
toggleModal __('Proxy setting'), __('Success! It will be available after a restart.')
e.preventDefault()
handleHttpHostChange: (e) ->
{http} = @state
http.host = e.target.value
@setState {http}
handleHttpPortChange: (e) ->
{http} = @state
http.port = e.target.value
@setState {http}
handleSocksHostChange: (e) ->
{socks5} = @state
socks5.host = e.target.value
@setState {socks5}
handleSocksPortChange: (e) ->
{socks5} = @state
socks5.port = e.target.value
@setState {socks5}
handleShadowsocksServerHostChange: (e) ->
{shadowsocks} = @state
shadowsocks.server.host = e.target.value
@setState {shadowsocks}
handleShadowsocksServerPortChange: (e) ->
{shadowsocks} = @state
shadowsocks.server.port = e.target.value
@setState {shadowsocks}
handleShadowsocksPasswordChange: (e) ->
{shadowsocks} = @state
shadowsocks.password = e.target.value
@setState {shadowsocks}
handleShadowsocksMethodChange: (e) ->
{shadowsocks} = @state
shadowsocks.method = e.target.value
@setState {shadowsocks}
handleSetRetries: (e) ->
@setState
retries: e.target.value
r = parseInt(e.target.value)
return if isNaN(r) || r < 0
config.set 'poi.proxy.retries', r
render: ->
<form>
<Divider text={__ 'Proxy protocol'} />
<Grid>
<Col xs={12}>
<Input type="select" ref="use" value={@state.use || "none"} onChange={@handleChangeUse}>
<option key={0} value="http">HTTP {__ "proxy"}</option>
<option key={1} value="socks5">Socks5 {__ "proxy"}</option>
<option key={2} value="shadowsocks">Shadowsocks</option>
<option key={3} value="none">{__ "No proxy"}</option>
</Input>
</Col>
</Grid>
<Divider text={__ 'Proxy server information'} />
{
if @state.use == 'http'
<Grid>
<Col xs={6}>
<Input type="text" ref="httpHost" label={__ 'Proxy server address'} placeholder="输入代理地址" value={@state?.http?.host} onChange={@handleHttpHostChange} />
</Col>
<Col xs={6}>
<Input type="text" ref="httpPort" label={__ 'Proxy server port'} placeholder="输入代理端口" value={@state?.http?.port} onChange={@handleHttpPortChange} />
</Col>
</Grid>
else if @state.use == 'socks5'
<Grid>
<Col xs={6}>
<Input type="text" ref="socksHost" label={__ 'Proxy server address'} placeholder="输入代理地址" value={@state?.socks5?.host} onChange={@handleSocksHostChange} />
</Col>
<Col xs={6}>
<Input type="text" ref="socksPort" label={__ 'Proxy server port'} placeholder="输入代理端口" value={@state?.socks5?.port} onChange={@handleSocksPortChange} />
</Col>
</Grid>
else if @state.use == 'shadowsocks'
<Grid>
<Col xs={6}>
<Input type="text" ref="shadowsocksServerHost" label={__ 'Proxy server address'} placeholder="Shadowsocks 服务器地址" value={@state?.shadowsocks?.server?.host} onChange={@handleShadowsocksServerHostChange} />
</Col>
<Col xs={6}>
<Input type="text" ref="shadowsocksServerPort" label={__ 'Proxy server port'} placeholder="Shadowsocks 服务器端口" value={@state?.shadowsocks?.server?.port} onChange={@handleShadowsocksServerPortChange} />
</Col>
<Col xs={6}>
<Input type="password" ref="shadowsocksPassword" label={__ 'Password'} placeholder="Shadowsocks 密码" value={@state?.shadowsocks?.password} onChange={@handleShadowsocksPasswordChange} />
</Col>
<Col xs={6}>
<Input type="select" ref="shadowsocksMethod" label={__ 'Encryption algorithm'} placeholder="Shadowsocks 加密方式" value={@state?.shadowsocks?.method} onChange={@handleShadowsocksMethodChange}>
{
shadowsocksMethods.map (method, index) ->
<option key={index} value={method}>{method.toUpperCase()}</option>
}
</Input>
</Col>
</Grid>
else
<Grid>
<Col xs={12}>
<center>{__ 'Will connect to server directly.'}</center>
</Col>
</Grid>
}
<Divider text={__ 'Times of reconnect'} />
<Grid>
<Col xs={12}>
<Input type="number" ref="retries" value={@state.retries} onChange={@handleSetRetries} />
</Col>
<Col xs={12}>
<Alert bsStyle='danger'>
{__ 'It may be unsafe!'}
</Alert>
</Col>
</Grid>
<Divider text={__ 'Save settings'} />
<Grid>
<Col xs={12}>
<Button bsStyle="success" onClick={@handleSaveConfig} style={width: '100%'}>{__ 'Save'}</Button>
</Col>
</Grid>
</form>
module.exports = NetworkConfig
|
[
{
"context": "_access\n ret.t = @t.clone()\n ret.name = @name\n ret.type = @type.clone() if @type\n re",
"end": 20332,
"score": 0.7975174188613892,
"start": 20332,
"tag": "NAME",
"value": ""
},
{
"context": " # TODO assign_value_list\n \n ctx.var_hash[@name] ... | src/index.coffee | konchunas/ast4gen | 2 | require "fy"
Type = require "type"
module = @
void_type = new Type "void"
@type_actualize = type_actualize = (t, root)->
t = t.clone()
walk = (_t)->
if reg_ret = /^_(\d+)$/.exec _t.main
[_skip, idx] = reg_ret
if !root.nest_list[idx]
# TODO make some test
### !pragma coverage-skip-block ###
throw new Error "can't resolve #{_t} because root type '#{root}' cas no nest_list[#{idx}]"
return root.nest_list[idx].clone()
for v,k in _t.nest_list
_t.nest_list[k] = walk v
for k,v of _t.field_hash
# Прим. пока эта часть еще никем не используется
# TODO make some test
### !pragma coverage-skip-block ###
_t.field_hash[k] = walk v
_t
walk t
type_validate = (t, ctx)->
if !t
throw new Error "Type validation error line=#{@line} pos=#{@pos}. type is missing"
# if !ctx # JUST for debug
# throw new Error "WTF"
switch t.main
when "void", "int", "float", "string", "bool"
if t.nest_list.length != 0
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have nest_list"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
when "array", "hash_int"
if t.nest_list.length != 1
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have nest_list 1"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
when "hash"
if t.nest_list.length != 1
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have nest_list 1"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
when "struct"
if t.nest_list.length != 0
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have nest_list 0"
# if 0 == h_count t.field_hash
# throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have field_hash"
when "function"
if t.nest_list.length == 0
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have at least nest_list 1 (ret type)"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
""
# TODO defined types ...
else
if !ctx.check_type t.main
throw new Error "unknown type '#{t}'"
for v,k in t.nest_list
# continue if k == 0 and t.main == "function" and v.main == "void" # it's ok
type_validate v, ctx
for k,v of t.field_hash
type_validate v, ctx
return
wrap = (_prepared_field2type)->
ret = new module.Class_decl
ret._prepared_field2type = _prepared_field2type
ret
@default_var_hash_gen = ()->
ret =
"true" : new Type "bool"
"false": new Type "bool"
@default_type_hash_gen = ()->
ret =
"array" : wrap
remove_idx : new Type "function<void, int>"
length_get : new Type "function<int>"
length_set : new Type "function<void, int>"
pop : new Type "function<_0>"
push : new Type "function<void,_0>"
slice : new Type "function<array<_0>,int,int>" # + option
remove : new Type "function<void,_0>"
idx : new Type "function<int,_0>"
has : new Type "function<bool,_0>"
append : new Type "function<void,array<_0>>"
clone : new Type "function<array<_0>>"
sort_i : new Type "function<void,function<int,_0,_0>>"
sort_f : new Type "function<void,function<float,_0,_0>>"
sort_by_i : new Type "function<void,function<int,_0>>"
sort_by_f : new Type "function<void,function<float,_0>>"
sort_by_s : new Type "function<void,function<string,_0>>"
"hash_int" : wrap
add : new Type "function<void,int,_0>"
remove_idx : new Type "function<void,int>"
idx : new Type "function<_0,int>"
class @Validation_context
parent : null
executable: false
breakable : false
returnable: false
type_hash : {}
var_hash : {}
line : 0
pos : 0
constructor:()->
@type_hash = module.default_type_hash_gen()
@var_hash = module.default_var_hash_gen()
seek_non_executable_parent : ()->
if @executable
@parent.seek_non_executable_parent()
else
@
mk_nest : (pass_breakable)->
ret = new module.Validation_context
ret.parent = @
ret.returnable= @returnable
ret.executable= @executable
ret.breakable = @breakable if pass_breakable
ret
check_type : (id)->
return found if found = @type_hash[id]
if @parent
return @parent.check_type id
return null
check_id : (id)->
return found if found = @var_hash[id]
if @parent
return @parent.check_id id
return null
check_id_decl : (id)->
@var_hash[id]
# ###################################################################################################
# expr
# ###################################################################################################
# TODO array init
# TODO hash init
# TODO interpolated string init
class @Const
val : ""
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
switch @type.main
when "bool"
unless @val in ["true", "false"]
throw new Error "Const validation error line=#{@line} pos=#{@pos}. '#{@val}' can't be bool"
when "int"
if parseInt(@val).toString() != @val
throw new Error "Const validation error line=#{@line} pos=#{@pos}. '#{@val}' can't be int"
when "float"
val = @val
val = val.replace(/\.0+$/, "")
val = val.replace(/e(\d)/i, "e+$1")
if parseFloat(val).toString() != val
throw new Error "Const validation error line=#{@line} pos=#{@pos}. '#{@val}' can't be float"
when "string"
"nothing"
# string will be quoted and escaped
# when "char"
else
throw new Error "can't implement constant type '#{@type}'"
return
clone : ()->
ret = new module.Const
ret.val = @val
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Array_init
list : []
type : null
line : 0
pos : 0
constructor:()->
@list = []
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if @type.main != "array"
throw new Error "Array_init validation error line=#{@line} pos=#{@pos}. type must be array but '#{@type}' found"
cmp_type = @type.nest_list[0]
for v,k in @list
v.validate(ctx)
if !v.type.cmp cmp_type
throw new Error "Array_init validation error line=#{@line} pos=#{@pos}. key '#{k}' must be type '#{cmp_type}' but '#{v.type}' found"
return
clone : ()->
ret = new module.Array_init
for v in @list
ret.list.push v.clone()
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Hash_init
hash : {}
type : null
line : 0
pos : 0
constructor:()->
@hash = {}
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if @type.main != "hash"
throw new Error "Hash_init validation error line=#{@line} pos=#{@pos}. type must be hash but '#{@type}' found"
for k,v of @hash
v.validate(ctx)
cmp_type = @type.nest_list[0]
for k,v of @hash
if !v.type.cmp cmp_type
throw new Error "Hash_init validation error line=#{@line} pos=#{@pos}. key '#{k}' must be type '#{cmp_type}' but '#{v.type}' found"
return
clone : ()->
ret = new module.Hash_init
for k,v of @hash
ret.hash[k] = v.clone()
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Struct_init
hash : {}
type : null
line : 0
pos : 0
constructor:()->
@hash = {}
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if @type.main != "struct"
throw new Error "Struct_init validation error line=#{@line} pos=#{@pos}. type must be struct but '#{@type}' found"
for k,v of @hash
v.validate(ctx)
if !v.type.cmp cmp_type = @type.field_hash[k]
throw new Error "Struct_init validation error line=#{@line} pos=#{@pos}. key '#{k}' must be type '#{cmp_type}' but '#{v.type}' found"
return
clone : ()->
ret = new module.Struct_init
for k,v of @hash
ret.hash[k] = v.clone()
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Var
name : ""
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !/^[_a-z][_a-z0-9]*$/i.test @name
throw new Error "Var validation error line=#{@line} pos=#{@pos}. invalid identifier '#{@name}'"
type_validate @type, ctx
var_decl = ctx.check_id(@name)
if !var_decl
throw new Error "Var validation error line=#{@line} pos=#{@pos}. Id '#{@name}' not defined"
{type} = var_decl
if !@type.cmp type
throw new Error "Var validation error line=#{@line} pos=#{@pos}. Var type !+ Var_decl type '#{@type}' != #{type}"
return
clone : ()->
ret = new module.Var
ret.name = @name
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
@allowed_bin_op_hash =
ADD : true
SUB : true
MUL : true
DIV : true
DIV_INT: true
MOD : true
POW : true
BIT_AND : true
BIT_OR : true
BIT_XOR : true
BOOL_AND : true
BOOL_OR : true
BOOL_XOR : true
SHR : true
SHL : true
LSR : true # логический сдвиг вправо >>>
ASSIGN : true
ASS_ADD : true
ASS_SUB : true
ASS_MUL : true
ASS_DIV : true
ASS_DIV_INT: true
ASS_MOD : true
ASS_POW : true
ASS_SHR : true
ASS_SHL : true
ASS_LSR : true # логический сдвиг вправо >>>
ASS_BIT_AND : true
ASS_BIT_OR : true
ASS_BIT_XOR : true
ASS_BOOL_AND : true
ASS_BOOL_OR : true
ASS_BOOL_XOR : true
EQ : true
NE : true
GT : true
LT : true
GTE: true
LTE: true
INDEX_ACCESS : true # a[b] как бинарный оператор
@assign_bin_op_hash =
ASSIGN : true
ASS_ADD : true
ASS_SUB : true
ASS_MUL : true
ASS_DIV : true
ASS_MOD : true
ASS_POW : true
ASS_SHR : true
ASS_SHL : true
ASS_LSR : true # логический сдвиг вправо >>>
ASS_BIT_AND : true
ASS_BIT_OR : true
ASS_BIT_XOR : true
ASS_BOOL_AND : true
ASS_BOOL_OR : true
ASS_BOOL_XOR : true
@bin_op_ret_type_hash_list =
DIV : [
["int", "int", "float"]
["int", "float", "float"]
["float", "int", "float"]
["float", "float", "float"]
]
DIV_INT : [
["int", "int", "int"]
["int", "float", "int"]
["float", "int", "int"]
["float", "float", "int"]
]
# mix int float -> higher
for v in "ADD SUB MUL POW".split /\s+/g
@bin_op_ret_type_hash_list[v] = [
["int", "int", "int"]
["int", "float", "float"]
["float", "int", "float"]
["float", "float", "float"]
]
# pure int
for v in "MOD BIT_AND BIT_OR BIT_XOR SHR SHL LSR".split /\s+/g
@bin_op_ret_type_hash_list[v] = [["int", "int", "int"]]
# pure bool
for v in "BOOL_AND BOOL_OR BOOL_XOR".split /\s+/g
@bin_op_ret_type_hash_list[v] = [["bool", "bool", "bool"]]
# special string magic
@bin_op_ret_type_hash_list.ADD.push ["string", "string", "string"]
@bin_op_ret_type_hash_list.MUL.push ["string", "int", "string"]
# equal ops =, cmp
for v in "ASSIGN".split /\s+/g
@bin_op_ret_type_hash_list[v] = [
["int", "int", "int"]
["bool", "bool", "bool"]
["float", "float", "float"]
["string", "string", "string"]
]
for v in "EQ NE GT LT GTE LTE".split /\s+/g
@bin_op_ret_type_hash_list[v] = [
["int", "int", "bool"]
["float", "float", "bool"]
["string", "string", "bool"]
]
str_list = """
ADD
SUB
MUL
DIV
DIV_INT
MOD
POW
SHR
SHL
LSR
BIT_AND
BIT_OR
BIT_XOR
BOOL_AND
BOOL_OR
BOOL_XOR
"""
for v in str_list.split /\s+/g
table = @bin_op_ret_type_hash_list[v]
table = table.filter (row)->row[0] == row[2]
table = table.map (t)-> t.clone() # make safe
@bin_op_ret_type_hash_list["ASS_#{v}"] = table
class @Bin_op
a : null
b : null
op : null
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !@a
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. a missing"
@a.validate(ctx)
if !@b
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. b missing"
@b.validate(ctx)
type_validate @type, ctx
if !module.allowed_bin_op_hash[@op]
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. Invalid op '#{@op}'"
found = false
if list = module.bin_op_ret_type_hash_list[@op]
for v in list
continue if v[0] != @a.type.toString()
continue if v[1] != @b.type.toString()
found = true
if v[2] != @type.toString()
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} with types #{@a.type} #{@b.type} should produce type #{v[2]} but #{@type} found"
break
# extra cases
if !found
if @op == "ASSIGN"
if @a.type.cmp @b.type
if @a.type.cmp @type
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. #{@op} a=b=[#{@a.type}] must have return type '#{@a.type}'"
else if @op in ["EQ", "NE"]
if @a.type.cmp @b.type
if @type.main == "bool"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. #{@op} a=b=[#{@a.type}] must have return type bool"
else if @op == "INDEX_ACCESS"
switch @a.type.main
when "string"
if @b.type.main == "int"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be int"
if @type.main == "string"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be string"
when "array"
if @b.type.main == "int"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be int"
if @type.cmp @a.type.nest_list[0]
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be #{@a.type.nest_list[0]} but #{@type} found"
when "hash"
if @b.type.main == "string"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be string"
if @type.cmp @a.type.nest_list[0]
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be #{@a.type.nest_list[0]} but #{@type} found"
when "hash_int"
if @b.type.main == "int"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be int"
if @type.cmp @a.type.nest_list[0]
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be #{@a.type.nest_list[0]} but #{@type} found"
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. Can't apply bin_op=#{@op} to #{@a.type} #{@b.type}"
if !found
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. Can't apply bin_op=#{@op} to #{@a.type} #{@b.type}"
return
clone : ()->
ret = new module.Bin_op
ret.a = @a.clone()
ret.b = @b.clone()
ret.op = @op
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
@allowed_un_op_hash =
INC_RET : true
RET_INC : true
DEC_RET : true
RET_DEC : true
BOOL_NOT: true
BIT_NOT : true
MINUS : true
PLUS : true # parseFloat
IS_NOT_NULL : true
# new ?
# delete ?
@un_op_ret_type_hash_list =
INC_RET : [
["int", "int"]
]
RET_INC : [
["int", "int"]
]
DEC_RET : [
["int", "int"]
]
RET_DEC : [
["int", "int"]
]
BOOL_NOT : [
["bool", "bool"]
]
BIT_NOT : [
["int", "int"]
]
MINUS : [
["int", "int"]
["float", "float"]
]
PLUS : [
["string", "float"]
]
class @Un_op
a : null
op : null
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !@a
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. a missing"
@a.validate(ctx)
type_validate @type, ctx
if !module.allowed_un_op_hash[@op]
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. Invalid op '#{@op}'"
list = module.un_op_ret_type_hash_list[@op]
found = false
if list
for v in list
continue if v[0] != @a.type.toString()
found = true
if v[1] != @type.toString()
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. un_op=#{@op} with type #{@a.type} should produce type #{v[1]} but #{@type} found"
break
if @op == "IS_NOT_NULL"
if @type.main != "bool"
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. un_op=#{@op} with type #{@a.type} should produce type bool but #{@type} found"
found = true
if !found
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. Can't apply un_op=#{@op} to #{@a.type}"
return
clone : ()->
ret = new module.Un_op
ret.a = @a.clone()
ret.op = @op
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Field_access
t : null
name : ""
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !@t
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Missing target"
@t.validate(ctx)
if !@name
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Missing name"
type_validate @type, ctx
if @name == "new"
if @t.type.main in ["bool", "int", "float", "string"]
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to missing field '#{@name}' in '#{@t.type}'."
nest_type = new Type "function"
nest_type.nest_list[0] = @t.type
else if @t.type.main == "struct"
if !nest_type = @t.type.field_hash[@name]
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to missing field '#{@name}' in '#{@t.type}'. Possible keys [#{Object.keys(@t.type.field_hash).join ', '}]"
else
class_decl = ctx.check_type @t.type.main
if !nest_type = class_decl._prepared_field2type[@name]
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to missing class field '#{@name}' in '#{@t.type}'. Possible keys [#{Object.keys(class_decl._prepared_field2type).join ', '}]"
nest_type = type_actualize nest_type, @t.type
if !@type.cmp nest_type
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to field '#{@name}' with type '#{nest_type}' but result '#{@type}'"
return
clone : ()->
ret = new module.Field_access
ret.t = @t.clone()
ret.name = @name
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Fn_call
fn : null
arg_list : []
splat_fin : false
type : null
line : 0
pos : 0
constructor:()->
@arg_list = []
validate : (ctx = new module.Validation_context)->
if !@fn
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. fn missing"
@fn.validate(ctx)
if @fn.type.main != "function"
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. Can't call type '@fn.type'. You can call only function"
if !@type.cmp void_type
type_validate @type, ctx
if !@type.cmp @fn.type.nest_list[0]
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. Return type and function decl return type doesn't match #{@fn.type.nest_list[0]} != #{@type}"
if @fn.type.nest_list.length-1 != @arg_list.length
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. Expected arg count=#{@fn.type.nest_list.length-1} found=#{@arg_list.length}"
for arg,k in @arg_list
arg.validate(ctx)
if !@fn.type.nest_list[k+1].cmp arg.type
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. arg[#{k}] type mismatch. Expected=#{@fn.type.nest_list[k+1]} found=#{arg.type}"
return
clone : ()->
ret = new module.Fn_call
ret.fn = @fn.clone()
for v in @arg_list
ret.arg_list.push v.clone()
ret.splat_fin = @splat_fin
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
# ###################################################################################################
# stmt
# ###################################################################################################
# TODO var_decl check
class @Scope
list : []
need_nest : true
line : 0
pos : 0
constructor:()->
@list = []
validate : (ctx = new module.Validation_context)->
if @need_nest
ctx_nest = ctx.mk_nest(true)
else
ctx_nest = ctx
for stmt in @list # for Class_decl
stmt.register?(ctx_nest)
for stmt in @list
stmt.validate(ctx_nest)
# на самом деле валидными есть только Fn_call и assign, но мы об этом умолчим
return
clone : ()->
ret = new module.Scope
for v in @list
ret.list.push v.clone()
ret.need_nest = @need_nest
ret.line = @line
ret.pos = @pos
ret
class @If
cond: null
t : null
f : null
line : 0
pos : 0
constructor:()->
@t = new module.Scope
@f = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@cond
throw new Error "If validation error line=#{@line} pos=#{@pos}. cond missing"
@cond.validate(ctx)
unless @cond.type.main in ["bool", "int"]
throw new Error "If validation error line=#{@line} pos=#{@pos}. cond must be bool or int but found '#{@cond.type}'"
@t.validate(ctx)
@f.validate(ctx)
if @t.list.length == 0
perr "Warning. If empty true body"
if @t.list.length == 0 and @f.list.length == 0
throw new Error "If validation error line=#{@line} pos=#{@pos}. Empty true and false sections"
return
clone : ()->
ret = new module.If
ret.cond = @cond.clone()
ret.t = @t.clone()
ret.f = @f.clone()
ret.line = @line
ret.pos = @pos
ret
# есть следующие валидные случаи компилирования switch
# 1. cont типа int. Тогда все hash key трактуются как int. (Но нельзя NaN и Infinity)
# 2. cont типа float.
# 3. cont типа string.
# 4. cont типа char.
class @Switch
cond : null
hash : {}
f : null # scope
line : 0
pos : 0
constructor:()->
@hash = {}
@f = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@cond
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. cond missing"
@cond.validate(ctx)
if 0 == h_count @hash
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. no when conditions found"
switch @cond.type.main
when "int"
for k,v of @hash
if parseInt(k).toString() != k or !isFinite k
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. key '#{k}' can't be int"
# when "float" # не разрешаем switch по float т.к. нельзя сравнивать float'ы через ==
# for k,v of @hash
# if !isFinite k
# throw new Error "Switch validation error line=#{@line} pos=#{@pos}. key '#{k}' can't be float"
when "string"
"nothing"
else
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. Can't implement switch for condition type '#{@cond.type}'"
for k,v of @hash
v.validate(ctx.mk_nest())
@f?.validate(ctx)
return
clone : ()->
ret = new module.Switch
ret.cond = @cond.clone()
for k,v of @hash
ret.hash[k] = v.clone()
ret.f = @f.clone()
ret.line = @line
ret.pos = @pos
ret
class @Loop
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate(ctx_nest)
found = false
walk = (t)->
switch t.constructor.name
when "Scope"
for v in t.list
walk v
when "If"
walk t.t
walk t.f
when "Break", "Ret"
found = true
return
walk @scope
if !found
throw new Error "Loop validation error line=#{@line} pos=#{@pos}. Break or Ret not found"
# Не нужен т.к. все-равно ищем break
# if @scope.list.length == 0
# throw new Error "Loop validation error line=#{@line} pos=#{@pos}. Loop while is not allowed"
return
clone : ()->
ret = new module.Loop
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @Break
line : 0
pos : 0
constructor:()->
validate : (ctx = new module.Validation_context)->
if !ctx.breakable
throw new Error "Break validation error line=#{@line} pos=#{@pos}. You can't use break outside loop, while"
return
clone : ()->
ret = new module.Break
ret.line = @line
ret.pos = @pos
ret
class @Continue
line : 0
pos : 0
constructor:()->
validate : (ctx = new module.Validation_context)->
if !ctx.breakable
throw new Error "Continue validation error line=#{@line} pos=#{@pos}. You can't use continue outside loop, while"
return
clone : ()->
ret = new module.Continue
ret.line = @line
ret.pos = @pos
ret
class @While
cond : null
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@cond
throw new Error "While validation error line=#{@line} pos=#{@pos}. cond missing"
@cond.validate(ctx)
unless @cond.type.main in ["bool", "int"]
throw new Error "While validation error line=#{@line} pos=#{@pos}. cond must be bool or int"
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate(ctx_nest)
if @scope.list.length == 0
throw new Error "While validation error line=#{@line} pos=#{@pos}. Empty while is not allowed"
return
clone : ()->
ret = new module.While
ret.cond = @cond.clone()
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @For_range
exclusive : true
i : null
a : null
b : null
step : null
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@i
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Iterator is missing"
if !@a
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range a is missing"
if !@b
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range b is missing"
@i.validate ctx
@a.validate ctx
@b.validate ctx
@step?.validate ctx
unless @i.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Iterator should be type int or float but '#{@i.type}' found"
unless @a.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range a should be type int or float but '#{@a.type}' found"
unless @b.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range b should be type int or float but '#{@b.type}' found"
if @step
unless @step.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Step should be type int or float but '#{@step.type}' found"
if @i.type.main == "int"
unless @a.type.main == "int"
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range a should be type int because iterator is int but '#{@a.type}' found"
unless @b.type.main == "int"
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range b should be type int because iterator is int but '#{@b.type}' found"
if @step
unless @step.type.main == "int"
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Step should be type int because iterator is int but '#{@step.type}' found"
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate ctx_nest
return
clone : ()->
ret = new module.For_range
ret.exclusive = @exclusive
ret.i = @i.clone()
ret.a = @a.clone()
ret.b = @b.clone()
ret.step = @step.clone() if @step
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @For_col
k : null
v : null
t : null
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@t
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Target is missing"
if !@k and !@v
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Key and value is missing"
@t.validate ctx
@k?.validate ctx
@v?.validate ctx
switch @t.type.main
when "array", "hash_int"
if @k
unless @k.type.main == "int"
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Key must be int for array<t> target but found '#{@k.type}'"
when "hash"
if @k
unless @k.type.main == "string"
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Key must be string for hash<t> target but found '#{@k.type}'"
else
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. For_col accepts types array<t>, hash<t> and hash_int<t> but found '#{@t.type}'"
if @v
unless @v.type.cmp @t.type.nest_list[0]
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Value must be '#{@t.type.nest_list[0]}' but found '#{@v.type}'"
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate ctx_nest
return
clone : ()->
ret = new module.For_col
ret.t = @t.clone()
ret.v = @v.clone() if @v
ret.k = @k.clone() if @k
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @Ret
t : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
@t?.validate(ctx)
if !ctx.returnable
throw new Error "Ret validation error line=#{@line} pos=#{@pos}. ctx must be returnable"
return_type = ctx.check_id "$_return_type"
if @t?
if !@t.type.cmp return_type
throw new Error "Ret validation error line=#{@line} pos=#{@pos}. Ret type must be '#{return_type}' but found '#{@t.type}'"
else
if return_type.main != "void"
throw new Error "Ret validation error line=#{@line} pos=#{@pos}. Ret type must be '#{return_type}' but found void (no return value)"
return
clone : ()->
ret = new module.Ret
ret.t = @t.clone() if @t
ret.line = @line
ret.pos = @pos
ret
# ###################################################################################################
# Exceptions
# ###################################################################################################
class @Try
t : null
c : null
exception_var_name : ""
line : 0
pos : 0
constructor : ()->
@t = new module.Scope
@c = new module.Scope
# TODO validate
clone : ()->
ret = new module.Try
ret.t = @t.clone()
ret.c = @c.clone()
ret.exception_var_name = @exception_var_name
ret.line = @line
ret.pos = @pos
ret
class @Throw
t : null
line : 0
pos : 0
# TODO validate
clone : ()->
ret = new module.Throw
ret.t = @t.clone() if @t
ret.line = @line
ret.pos = @pos
ret
# ###################################################################################################
# decl
# ###################################################################################################
class @Var_decl
name : ""
type : null
size : null
assign_value : null
assign_value_list : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if ctx.check_id_decl(@name)
throw new Error "Var_decl validation error line=#{@line} pos=#{@pos}. Redeclare '#{@name}'"
# TODO size check
# а еще с type связь скорее всего должна быть
# TODO assign_value
# TODO assign_value_list
ctx.var_hash[@name] = @
return
clone : ()->
ret = new module.Var_decl
ret.name = @name
ret.type = @type.clone() if @type
ret.size = @size
ret.assign_value = @assign_value.clone() if @assign_value
if @assign_value_list
ret.assign_value_list = []
for v in @assign_value_list
ret.assign_value_list.push v.clone()
ret.line = @line
ret.pos = @pos
ret
class @Class_decl
name : ""
scope : null
_prepared_field2type : {}
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
@_prepared_field2type = {}
register : (ctx = new module.Validation_context)->
if ctx.check_type @name
throw new Error "Already registered '#{@name}'"
ctx.type_hash[@name] = @
return
validate : (ctx = new module.Validation_context)->
if !@name
throw new Error "Class_decl validation error line=#{@line} pos=#{@pos}. Class should have name"
@_prepared_field2type = {} # ensure reset (some generators rewrite this field)
for v in @scope.list
unless v.constructor.name in ["Var_decl", "Fn_decl"]
throw new Error "Class_decl validation error line=#{@line} pos=#{@pos}. Only Var_decl and Fn_decl allowed at Class_decl, but '#{v.constructor.name}' found"
@_prepared_field2type[v.name] = v.type
ctx_nest = ctx.mk_nest()
# wrapper
var_decl = new module.Var_decl
var_decl.name = "this"
var_decl.type = new Type @name
ctx_nest.var_hash["this"] = var_decl
@scope.validate(ctx_nest)
return
clone : ()->
ret = new module.Class_decl
ret.name = @name
ret.scope = @scope.clone()
for k,v of @_prepared_field2type
ret._prepared_field2type[k] = v.clone()
ret.line = @line
ret.pos = @pos
ret
class @Fn_decl
is_closure : false
name : ""
type : null
arg_name_list : []
scope : null
line : 0
pos : 0
constructor:()->
@arg_name_list = []
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@name and !@is_closure
throw new Error "Fn_decl validation error line=#{@line} pos=#{@pos}. Function should have name"
type_validate @type, ctx
if @type.main != "function"
throw new Error "Fn_decl validation error line=#{@line} pos=#{@pos}. Type must be function but '#{@type}' found"
if @type.nest_list.length-1 != @arg_name_list.length
throw new Error "Fn_decl validation error line=#{@line} pos=#{@pos}. @type.nest_list.length-1 != @arg_name_list #{@type.nest_list.length-1} != #{@arg_name_list.length}"
if @is_closure
ctx_nest = ctx.mk_nest()
else
ctx_nest = ctx.seek_non_executable_parent().mk_nest()
ctx_nest.executable = true
ctx_nest.returnable = true
for name,k in @arg_name_list
decl = new module.Var_decl
decl.name = name
decl.type = @type.nest_list[1+k]
ctx_nest.var_hash[name] = decl
ctx_nest.var_hash["$_return_type"] = @type.nest_list[0]
@scope.validate(ctx_nest)
var_decl = new module.Var_decl
var_decl.name = @name
var_decl.type = @type
ctx.var_hash[@name] = var_decl
return
clone : ()->
ret = new module.Fn_decl
ret.is_closure = @is_closure
ret.name = @name
ret.type = @type.clone() if @type
ret.arg_name_list = @arg_name_list.clone()
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
| 151342 | require "fy"
Type = require "type"
module = @
void_type = new Type "void"
@type_actualize = type_actualize = (t, root)->
t = t.clone()
walk = (_t)->
if reg_ret = /^_(\d+)$/.exec _t.main
[_skip, idx] = reg_ret
if !root.nest_list[idx]
# TODO make some test
### !pragma coverage-skip-block ###
throw new Error "can't resolve #{_t} because root type '#{root}' cas no nest_list[#{idx}]"
return root.nest_list[idx].clone()
for v,k in _t.nest_list
_t.nest_list[k] = walk v
for k,v of _t.field_hash
# Прим. пока эта часть еще никем не используется
# TODO make some test
### !pragma coverage-skip-block ###
_t.field_hash[k] = walk v
_t
walk t
type_validate = (t, ctx)->
if !t
throw new Error "Type validation error line=#{@line} pos=#{@pos}. type is missing"
# if !ctx # JUST for debug
# throw new Error "WTF"
switch t.main
when "void", "int", "float", "string", "bool"
if t.nest_list.length != 0
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have nest_list"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
when "array", "hash_int"
if t.nest_list.length != 1
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have nest_list 1"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
when "hash"
if t.nest_list.length != 1
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have nest_list 1"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
when "struct"
if t.nest_list.length != 0
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have nest_list 0"
# if 0 == h_count t.field_hash
# throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have field_hash"
when "function"
if t.nest_list.length == 0
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have at least nest_list 1 (ret type)"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
""
# TODO defined types ...
else
if !ctx.check_type t.main
throw new Error "unknown type '#{t}'"
for v,k in t.nest_list
# continue if k == 0 and t.main == "function" and v.main == "void" # it's ok
type_validate v, ctx
for k,v of t.field_hash
type_validate v, ctx
return
wrap = (_prepared_field2type)->
ret = new module.Class_decl
ret._prepared_field2type = _prepared_field2type
ret
@default_var_hash_gen = ()->
ret =
"true" : new Type "bool"
"false": new Type "bool"
@default_type_hash_gen = ()->
ret =
"array" : wrap
remove_idx : new Type "function<void, int>"
length_get : new Type "function<int>"
length_set : new Type "function<void, int>"
pop : new Type "function<_0>"
push : new Type "function<void,_0>"
slice : new Type "function<array<_0>,int,int>" # + option
remove : new Type "function<void,_0>"
idx : new Type "function<int,_0>"
has : new Type "function<bool,_0>"
append : new Type "function<void,array<_0>>"
clone : new Type "function<array<_0>>"
sort_i : new Type "function<void,function<int,_0,_0>>"
sort_f : new Type "function<void,function<float,_0,_0>>"
sort_by_i : new Type "function<void,function<int,_0>>"
sort_by_f : new Type "function<void,function<float,_0>>"
sort_by_s : new Type "function<void,function<string,_0>>"
"hash_int" : wrap
add : new Type "function<void,int,_0>"
remove_idx : new Type "function<void,int>"
idx : new Type "function<_0,int>"
class @Validation_context
parent : null
executable: false
breakable : false
returnable: false
type_hash : {}
var_hash : {}
line : 0
pos : 0
constructor:()->
@type_hash = module.default_type_hash_gen()
@var_hash = module.default_var_hash_gen()
seek_non_executable_parent : ()->
if @executable
@parent.seek_non_executable_parent()
else
@
mk_nest : (pass_breakable)->
ret = new module.Validation_context
ret.parent = @
ret.returnable= @returnable
ret.executable= @executable
ret.breakable = @breakable if pass_breakable
ret
check_type : (id)->
return found if found = @type_hash[id]
if @parent
return @parent.check_type id
return null
check_id : (id)->
return found if found = @var_hash[id]
if @parent
return @parent.check_id id
return null
check_id_decl : (id)->
@var_hash[id]
# ###################################################################################################
# expr
# ###################################################################################################
# TODO array init
# TODO hash init
# TODO interpolated string init
class @Const
val : ""
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
switch @type.main
when "bool"
unless @val in ["true", "false"]
throw new Error "Const validation error line=#{@line} pos=#{@pos}. '#{@val}' can't be bool"
when "int"
if parseInt(@val).toString() != @val
throw new Error "Const validation error line=#{@line} pos=#{@pos}. '#{@val}' can't be int"
when "float"
val = @val
val = val.replace(/\.0+$/, "")
val = val.replace(/e(\d)/i, "e+$1")
if parseFloat(val).toString() != val
throw new Error "Const validation error line=#{@line} pos=#{@pos}. '#{@val}' can't be float"
when "string"
"nothing"
# string will be quoted and escaped
# when "char"
else
throw new Error "can't implement constant type '#{@type}'"
return
clone : ()->
ret = new module.Const
ret.val = @val
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Array_init
list : []
type : null
line : 0
pos : 0
constructor:()->
@list = []
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if @type.main != "array"
throw new Error "Array_init validation error line=#{@line} pos=#{@pos}. type must be array but '#{@type}' found"
cmp_type = @type.nest_list[0]
for v,k in @list
v.validate(ctx)
if !v.type.cmp cmp_type
throw new Error "Array_init validation error line=#{@line} pos=#{@pos}. key '#{k}' must be type '#{cmp_type}' but '#{v.type}' found"
return
clone : ()->
ret = new module.Array_init
for v in @list
ret.list.push v.clone()
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Hash_init
hash : {}
type : null
line : 0
pos : 0
constructor:()->
@hash = {}
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if @type.main != "hash"
throw new Error "Hash_init validation error line=#{@line} pos=#{@pos}. type must be hash but '#{@type}' found"
for k,v of @hash
v.validate(ctx)
cmp_type = @type.nest_list[0]
for k,v of @hash
if !v.type.cmp cmp_type
throw new Error "Hash_init validation error line=#{@line} pos=#{@pos}. key '#{k}' must be type '#{cmp_type}' but '#{v.type}' found"
return
clone : ()->
ret = new module.Hash_init
for k,v of @hash
ret.hash[k] = v.clone()
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Struct_init
hash : {}
type : null
line : 0
pos : 0
constructor:()->
@hash = {}
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if @type.main != "struct"
throw new Error "Struct_init validation error line=#{@line} pos=#{@pos}. type must be struct but '#{@type}' found"
for k,v of @hash
v.validate(ctx)
if !v.type.cmp cmp_type = @type.field_hash[k]
throw new Error "Struct_init validation error line=#{@line} pos=#{@pos}. key '#{k}' must be type '#{cmp_type}' but '#{v.type}' found"
return
clone : ()->
ret = new module.Struct_init
for k,v of @hash
ret.hash[k] = v.clone()
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Var
name : ""
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !/^[_a-z][_a-z0-9]*$/i.test @name
throw new Error "Var validation error line=#{@line} pos=#{@pos}. invalid identifier '#{@name}'"
type_validate @type, ctx
var_decl = ctx.check_id(@name)
if !var_decl
throw new Error "Var validation error line=#{@line} pos=#{@pos}. Id '#{@name}' not defined"
{type} = var_decl
if !@type.cmp type
throw new Error "Var validation error line=#{@line} pos=#{@pos}. Var type !+ Var_decl type '#{@type}' != #{type}"
return
clone : ()->
ret = new module.Var
ret.name = @name
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
@allowed_bin_op_hash =
ADD : true
SUB : true
MUL : true
DIV : true
DIV_INT: true
MOD : true
POW : true
BIT_AND : true
BIT_OR : true
BIT_XOR : true
BOOL_AND : true
BOOL_OR : true
BOOL_XOR : true
SHR : true
SHL : true
LSR : true # логический сдвиг вправо >>>
ASSIGN : true
ASS_ADD : true
ASS_SUB : true
ASS_MUL : true
ASS_DIV : true
ASS_DIV_INT: true
ASS_MOD : true
ASS_POW : true
ASS_SHR : true
ASS_SHL : true
ASS_LSR : true # логический сдвиг вправо >>>
ASS_BIT_AND : true
ASS_BIT_OR : true
ASS_BIT_XOR : true
ASS_BOOL_AND : true
ASS_BOOL_OR : true
ASS_BOOL_XOR : true
EQ : true
NE : true
GT : true
LT : true
GTE: true
LTE: true
INDEX_ACCESS : true # a[b] как бинарный оператор
@assign_bin_op_hash =
ASSIGN : true
ASS_ADD : true
ASS_SUB : true
ASS_MUL : true
ASS_DIV : true
ASS_MOD : true
ASS_POW : true
ASS_SHR : true
ASS_SHL : true
ASS_LSR : true # логический сдвиг вправо >>>
ASS_BIT_AND : true
ASS_BIT_OR : true
ASS_BIT_XOR : true
ASS_BOOL_AND : true
ASS_BOOL_OR : true
ASS_BOOL_XOR : true
@bin_op_ret_type_hash_list =
DIV : [
["int", "int", "float"]
["int", "float", "float"]
["float", "int", "float"]
["float", "float", "float"]
]
DIV_INT : [
["int", "int", "int"]
["int", "float", "int"]
["float", "int", "int"]
["float", "float", "int"]
]
# mix int float -> higher
for v in "ADD SUB MUL POW".split /\s+/g
@bin_op_ret_type_hash_list[v] = [
["int", "int", "int"]
["int", "float", "float"]
["float", "int", "float"]
["float", "float", "float"]
]
# pure int
for v in "MOD BIT_AND BIT_OR BIT_XOR SHR SHL LSR".split /\s+/g
@bin_op_ret_type_hash_list[v] = [["int", "int", "int"]]
# pure bool
for v in "BOOL_AND BOOL_OR BOOL_XOR".split /\s+/g
@bin_op_ret_type_hash_list[v] = [["bool", "bool", "bool"]]
# special string magic
@bin_op_ret_type_hash_list.ADD.push ["string", "string", "string"]
@bin_op_ret_type_hash_list.MUL.push ["string", "int", "string"]
# equal ops =, cmp
for v in "ASSIGN".split /\s+/g
@bin_op_ret_type_hash_list[v] = [
["int", "int", "int"]
["bool", "bool", "bool"]
["float", "float", "float"]
["string", "string", "string"]
]
for v in "EQ NE GT LT GTE LTE".split /\s+/g
@bin_op_ret_type_hash_list[v] = [
["int", "int", "bool"]
["float", "float", "bool"]
["string", "string", "bool"]
]
str_list = """
ADD
SUB
MUL
DIV
DIV_INT
MOD
POW
SHR
SHL
LSR
BIT_AND
BIT_OR
BIT_XOR
BOOL_AND
BOOL_OR
BOOL_XOR
"""
for v in str_list.split /\s+/g
table = @bin_op_ret_type_hash_list[v]
table = table.filter (row)->row[0] == row[2]
table = table.map (t)-> t.clone() # make safe
@bin_op_ret_type_hash_list["ASS_#{v}"] = table
class @Bin_op
a : null
b : null
op : null
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !@a
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. a missing"
@a.validate(ctx)
if !@b
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. b missing"
@b.validate(ctx)
type_validate @type, ctx
if !module.allowed_bin_op_hash[@op]
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. Invalid op '#{@op}'"
found = false
if list = module.bin_op_ret_type_hash_list[@op]
for v in list
continue if v[0] != @a.type.toString()
continue if v[1] != @b.type.toString()
found = true
if v[2] != @type.toString()
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} with types #{@a.type} #{@b.type} should produce type #{v[2]} but #{@type} found"
break
# extra cases
if !found
if @op == "ASSIGN"
if @a.type.cmp @b.type
if @a.type.cmp @type
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. #{@op} a=b=[#{@a.type}] must have return type '#{@a.type}'"
else if @op in ["EQ", "NE"]
if @a.type.cmp @b.type
if @type.main == "bool"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. #{@op} a=b=[#{@a.type}] must have return type bool"
else if @op == "INDEX_ACCESS"
switch @a.type.main
when "string"
if @b.type.main == "int"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be int"
if @type.main == "string"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be string"
when "array"
if @b.type.main == "int"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be int"
if @type.cmp @a.type.nest_list[0]
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be #{@a.type.nest_list[0]} but #{@type} found"
when "hash"
if @b.type.main == "string"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be string"
if @type.cmp @a.type.nest_list[0]
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be #{@a.type.nest_list[0]} but #{@type} found"
when "hash_int"
if @b.type.main == "int"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be int"
if @type.cmp @a.type.nest_list[0]
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be #{@a.type.nest_list[0]} but #{@type} found"
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. Can't apply bin_op=#{@op} to #{@a.type} #{@b.type}"
if !found
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. Can't apply bin_op=#{@op} to #{@a.type} #{@b.type}"
return
clone : ()->
ret = new module.Bin_op
ret.a = @a.clone()
ret.b = @b.clone()
ret.op = @op
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
@allowed_un_op_hash =
INC_RET : true
RET_INC : true
DEC_RET : true
RET_DEC : true
BOOL_NOT: true
BIT_NOT : true
MINUS : true
PLUS : true # parseFloat
IS_NOT_NULL : true
# new ?
# delete ?
@un_op_ret_type_hash_list =
INC_RET : [
["int", "int"]
]
RET_INC : [
["int", "int"]
]
DEC_RET : [
["int", "int"]
]
RET_DEC : [
["int", "int"]
]
BOOL_NOT : [
["bool", "bool"]
]
BIT_NOT : [
["int", "int"]
]
MINUS : [
["int", "int"]
["float", "float"]
]
PLUS : [
["string", "float"]
]
class @Un_op
a : null
op : null
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !@a
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. a missing"
@a.validate(ctx)
type_validate @type, ctx
if !module.allowed_un_op_hash[@op]
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. Invalid op '#{@op}'"
list = module.un_op_ret_type_hash_list[@op]
found = false
if list
for v in list
continue if v[0] != @a.type.toString()
found = true
if v[1] != @type.toString()
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. un_op=#{@op} with type #{@a.type} should produce type #{v[1]} but #{@type} found"
break
if @op == "IS_NOT_NULL"
if @type.main != "bool"
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. un_op=#{@op} with type #{@a.type} should produce type bool but #{@type} found"
found = true
if !found
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. Can't apply un_op=#{@op} to #{@a.type}"
return
clone : ()->
ret = new module.Un_op
ret.a = @a.clone()
ret.op = @op
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Field_access
t : null
name : ""
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !@t
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Missing target"
@t.validate(ctx)
if !@name
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Missing name"
type_validate @type, ctx
if @name == "new"
if @t.type.main in ["bool", "int", "float", "string"]
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to missing field '#{@name}' in '#{@t.type}'."
nest_type = new Type "function"
nest_type.nest_list[0] = @t.type
else if @t.type.main == "struct"
if !nest_type = @t.type.field_hash[@name]
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to missing field '#{@name}' in '#{@t.type}'. Possible keys [#{Object.keys(@t.type.field_hash).join ', '}]"
else
class_decl = ctx.check_type @t.type.main
if !nest_type = class_decl._prepared_field2type[@name]
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to missing class field '#{@name}' in '#{@t.type}'. Possible keys [#{Object.keys(class_decl._prepared_field2type).join ', '}]"
nest_type = type_actualize nest_type, @t.type
if !@type.cmp nest_type
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to field '#{@name}' with type '#{nest_type}' but result '#{@type}'"
return
clone : ()->
ret = new module.Field_access
ret.t = @t.clone()
ret.name =<NAME> @name
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Fn_call
fn : null
arg_list : []
splat_fin : false
type : null
line : 0
pos : 0
constructor:()->
@arg_list = []
validate : (ctx = new module.Validation_context)->
if !@fn
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. fn missing"
@fn.validate(ctx)
if @fn.type.main != "function"
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. Can't call type '@fn.type'. You can call only function"
if !@type.cmp void_type
type_validate @type, ctx
if !@type.cmp @fn.type.nest_list[0]
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. Return type and function decl return type doesn't match #{@fn.type.nest_list[0]} != #{@type}"
if @fn.type.nest_list.length-1 != @arg_list.length
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. Expected arg count=#{@fn.type.nest_list.length-1} found=#{@arg_list.length}"
for arg,k in @arg_list
arg.validate(ctx)
if !@fn.type.nest_list[k+1].cmp arg.type
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. arg[#{k}] type mismatch. Expected=#{@fn.type.nest_list[k+1]} found=#{arg.type}"
return
clone : ()->
ret = new module.Fn_call
ret.fn = @fn.clone()
for v in @arg_list
ret.arg_list.push v.clone()
ret.splat_fin = @splat_fin
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
# ###################################################################################################
# stmt
# ###################################################################################################
# TODO var_decl check
class @Scope
list : []
need_nest : true
line : 0
pos : 0
constructor:()->
@list = []
validate : (ctx = new module.Validation_context)->
if @need_nest
ctx_nest = ctx.mk_nest(true)
else
ctx_nest = ctx
for stmt in @list # for Class_decl
stmt.register?(ctx_nest)
for stmt in @list
stmt.validate(ctx_nest)
# на самом деле валидными есть только Fn_call и assign, но мы об этом умолчим
return
clone : ()->
ret = new module.Scope
for v in @list
ret.list.push v.clone()
ret.need_nest = @need_nest
ret.line = @line
ret.pos = @pos
ret
class @If
cond: null
t : null
f : null
line : 0
pos : 0
constructor:()->
@t = new module.Scope
@f = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@cond
throw new Error "If validation error line=#{@line} pos=#{@pos}. cond missing"
@cond.validate(ctx)
unless @cond.type.main in ["bool", "int"]
throw new Error "If validation error line=#{@line} pos=#{@pos}. cond must be bool or int but found '#{@cond.type}'"
@t.validate(ctx)
@f.validate(ctx)
if @t.list.length == 0
perr "Warning. If empty true body"
if @t.list.length == 0 and @f.list.length == 0
throw new Error "If validation error line=#{@line} pos=#{@pos}. Empty true and false sections"
return
clone : ()->
ret = new module.If
ret.cond = @cond.clone()
ret.t = @t.clone()
ret.f = @f.clone()
ret.line = @line
ret.pos = @pos
ret
# есть следующие валидные случаи компилирования switch
# 1. cont типа int. Тогда все hash key трактуются как int. (Но нельзя NaN и Infinity)
# 2. cont типа float.
# 3. cont типа string.
# 4. cont типа char.
class @Switch
cond : null
hash : {}
f : null # scope
line : 0
pos : 0
constructor:()->
@hash = {}
@f = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@cond
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. cond missing"
@cond.validate(ctx)
if 0 == h_count @hash
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. no when conditions found"
switch @cond.type.main
when "int"
for k,v of @hash
if parseInt(k).toString() != k or !isFinite k
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. key '#{k}' can't be int"
# when "float" # не разрешаем switch по float т.к. нельзя сравнивать float'ы через ==
# for k,v of @hash
# if !isFinite k
# throw new Error "Switch validation error line=#{@line} pos=#{@pos}. key '#{k}' can't be float"
when "string"
"nothing"
else
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. Can't implement switch for condition type '#{@cond.type}'"
for k,v of @hash
v.validate(ctx.mk_nest())
@f?.validate(ctx)
return
clone : ()->
ret = new module.Switch
ret.cond = @cond.clone()
for k,v of @hash
ret.hash[k] = v.clone()
ret.f = @f.clone()
ret.line = @line
ret.pos = @pos
ret
class @Loop
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate(ctx_nest)
found = false
walk = (t)->
switch t.constructor.name
when "Scope"
for v in t.list
walk v
when "If"
walk t.t
walk t.f
when "Break", "Ret"
found = true
return
walk @scope
if !found
throw new Error "Loop validation error line=#{@line} pos=#{@pos}. Break or Ret not found"
# Не нужен т.к. все-равно ищем break
# if @scope.list.length == 0
# throw new Error "Loop validation error line=#{@line} pos=#{@pos}. Loop while is not allowed"
return
clone : ()->
ret = new module.Loop
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @Break
line : 0
pos : 0
constructor:()->
validate : (ctx = new module.Validation_context)->
if !ctx.breakable
throw new Error "Break validation error line=#{@line} pos=#{@pos}. You can't use break outside loop, while"
return
clone : ()->
ret = new module.Break
ret.line = @line
ret.pos = @pos
ret
class @Continue
line : 0
pos : 0
constructor:()->
validate : (ctx = new module.Validation_context)->
if !ctx.breakable
throw new Error "Continue validation error line=#{@line} pos=#{@pos}. You can't use continue outside loop, while"
return
clone : ()->
ret = new module.Continue
ret.line = @line
ret.pos = @pos
ret
class @While
cond : null
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@cond
throw new Error "While validation error line=#{@line} pos=#{@pos}. cond missing"
@cond.validate(ctx)
unless @cond.type.main in ["bool", "int"]
throw new Error "While validation error line=#{@line} pos=#{@pos}. cond must be bool or int"
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate(ctx_nest)
if @scope.list.length == 0
throw new Error "While validation error line=#{@line} pos=#{@pos}. Empty while is not allowed"
return
clone : ()->
ret = new module.While
ret.cond = @cond.clone()
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @For_range
exclusive : true
i : null
a : null
b : null
step : null
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@i
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Iterator is missing"
if !@a
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range a is missing"
if !@b
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range b is missing"
@i.validate ctx
@a.validate ctx
@b.validate ctx
@step?.validate ctx
unless @i.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Iterator should be type int or float but '#{@i.type}' found"
unless @a.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range a should be type int or float but '#{@a.type}' found"
unless @b.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range b should be type int or float but '#{@b.type}' found"
if @step
unless @step.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Step should be type int or float but '#{@step.type}' found"
if @i.type.main == "int"
unless @a.type.main == "int"
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range a should be type int because iterator is int but '#{@a.type}' found"
unless @b.type.main == "int"
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range b should be type int because iterator is int but '#{@b.type}' found"
if @step
unless @step.type.main == "int"
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Step should be type int because iterator is int but '#{@step.type}' found"
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate ctx_nest
return
clone : ()->
ret = new module.For_range
ret.exclusive = @exclusive
ret.i = @i.clone()
ret.a = @a.clone()
ret.b = @b.clone()
ret.step = @step.clone() if @step
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @For_col
k : null
v : null
t : null
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@t
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Target is missing"
if !@k and !@v
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Key and value is missing"
@t.validate ctx
@k?.validate ctx
@v?.validate ctx
switch @t.type.main
when "array", "hash_int"
if @k
unless @k.type.main == "int"
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Key must be int for array<t> target but found '#{@k.type}'"
when "hash"
if @k
unless @k.type.main == "string"
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Key must be string for hash<t> target but found '#{@k.type}'"
else
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. For_col accepts types array<t>, hash<t> and hash_int<t> but found '#{@t.type}'"
if @v
unless @v.type.cmp @t.type.nest_list[0]
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Value must be '#{@t.type.nest_list[0]}' but found '#{@v.type}'"
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate ctx_nest
return
clone : ()->
ret = new module.For_col
ret.t = @t.clone()
ret.v = @v.clone() if @v
ret.k = @k.clone() if @k
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @Ret
t : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
@t?.validate(ctx)
if !ctx.returnable
throw new Error "Ret validation error line=#{@line} pos=#{@pos}. ctx must be returnable"
return_type = ctx.check_id "$_return_type"
if @t?
if !@t.type.cmp return_type
throw new Error "Ret validation error line=#{@line} pos=#{@pos}. Ret type must be '#{return_type}' but found '#{@t.type}'"
else
if return_type.main != "void"
throw new Error "Ret validation error line=#{@line} pos=#{@pos}. Ret type must be '#{return_type}' but found void (no return value)"
return
clone : ()->
ret = new module.Ret
ret.t = @t.clone() if @t
ret.line = @line
ret.pos = @pos
ret
# ###################################################################################################
# Exceptions
# ###################################################################################################
class @Try
t : null
c : null
exception_var_name : ""
line : 0
pos : 0
constructor : ()->
@t = new module.Scope
@c = new module.Scope
# TODO validate
clone : ()->
ret = new module.Try
ret.t = @t.clone()
ret.c = @c.clone()
ret.exception_var_name = @exception_var_name
ret.line = @line
ret.pos = @pos
ret
class @Throw
t : null
line : 0
pos : 0
# TODO validate
clone : ()->
ret = new module.Throw
ret.t = @t.clone() if @t
ret.line = @line
ret.pos = @pos
ret
# ###################################################################################################
# decl
# ###################################################################################################
class @Var_decl
name : ""
type : null
size : null
assign_value : null
assign_value_list : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if ctx.check_id_decl(@name)
throw new Error "Var_decl validation error line=#{@line} pos=#{@pos}. Redeclare '#{@name}'"
# TODO size check
# а еще с type связь скорее всего должна быть
# TODO assign_value
# TODO assign_value_list
ctx.var_hash[@name] = @
return
clone : ()->
ret = new module.Var_decl
ret.name = @name
ret.type = @type.clone() if @type
ret.size = @size
ret.assign_value = @assign_value.clone() if @assign_value
if @assign_value_list
ret.assign_value_list = []
for v in @assign_value_list
ret.assign_value_list.push v.clone()
ret.line = @line
ret.pos = @pos
ret
class @Class_decl
name : ""
scope : null
_prepared_field2type : {}
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
@_prepared_field2type = {}
register : (ctx = new module.Validation_context)->
if ctx.check_type @name
throw new Error "Already registered '#{@name}'"
ctx.type_hash[@name] = @
return
validate : (ctx = new module.Validation_context)->
if !@name
throw new Error "Class_decl validation error line=#{@line} pos=#{@pos}. Class should have name"
@_prepared_field2type = {} # ensure reset (some generators rewrite this field)
for v in @scope.list
unless v.constructor.name in ["Var_decl", "Fn_decl"]
throw new Error "Class_decl validation error line=#{@line} pos=#{@pos}. Only Var_decl and Fn_decl allowed at Class_decl, but '#{v.constructor.name}' found"
@_prepared_field2type[v.name] = v.type
ctx_nest = ctx.mk_nest()
# wrapper
var_decl = new module.Var_decl
var_decl.name = "this"
var_decl.type = new Type @name
ctx_nest.var_hash["this"] = var_decl
@scope.validate(ctx_nest)
return
clone : ()->
ret = new module.Class_decl
ret.name = @name
ret.scope = @scope.clone()
for k,v of @_prepared_field2type
ret._prepared_field2type[k] = v.clone()
ret.line = @line
ret.pos = @pos
ret
class @Fn_decl
is_closure : false
name : ""
type : null
arg_name_list : []
scope : null
line : 0
pos : 0
constructor:()->
@arg_name_list = []
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@name and !@is_closure
throw new Error "Fn_decl validation error line=#{@line} pos=#{@pos}. Function should have name"
type_validate @type, ctx
if @type.main != "function"
throw new Error "Fn_decl validation error line=#{@line} pos=#{@pos}. Type must be function but '#{@type}' found"
if @type.nest_list.length-1 != @arg_name_list.length
throw new Error "Fn_decl validation error line=#{@line} pos=#{@pos}. @type.nest_list.length-1 != @arg_name_list #{@type.nest_list.length-1} != #{@arg_name_list.length}"
if @is_closure
ctx_nest = ctx.mk_nest()
else
ctx_nest = ctx.seek_non_executable_parent().mk_nest()
ctx_nest.executable = true
ctx_nest.returnable = true
for name,k in @arg_name_list
decl = new module.Var_decl
decl.name = <NAME>
decl.type = @type.nest_list[1+k]
ctx_nest.var_hash[name] = decl
ctx_nest.var_hash["$_return_type"] = @type.nest_list[0]
@scope.validate(ctx_nest)
var_decl = new module.Var_decl
var_decl.name = @name
var_decl.type = @type
ctx.var_hash[@name] = var_decl
return
clone : ()->
ret = new module.Fn_decl
ret.is_closure = @is_closure
ret.name =<NAME> @name
ret.type = @type.clone() if @type
ret.arg_name_list = @arg_name_list.clone()
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
| true | require "fy"
Type = require "type"
module = @
void_type = new Type "void"
@type_actualize = type_actualize = (t, root)->
t = t.clone()
walk = (_t)->
if reg_ret = /^_(\d+)$/.exec _t.main
[_skip, idx] = reg_ret
if !root.nest_list[idx]
# TODO make some test
### !pragma coverage-skip-block ###
throw new Error "can't resolve #{_t} because root type '#{root}' cas no nest_list[#{idx}]"
return root.nest_list[idx].clone()
for v,k in _t.nest_list
_t.nest_list[k] = walk v
for k,v of _t.field_hash
# Прим. пока эта часть еще никем не используется
# TODO make some test
### !pragma coverage-skip-block ###
_t.field_hash[k] = walk v
_t
walk t
type_validate = (t, ctx)->
if !t
throw new Error "Type validation error line=#{@line} pos=#{@pos}. type is missing"
# if !ctx # JUST for debug
# throw new Error "WTF"
switch t.main
when "void", "int", "float", "string", "bool"
if t.nest_list.length != 0
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have nest_list"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
when "array", "hash_int"
if t.nest_list.length != 1
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have nest_list 1"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
when "hash"
if t.nest_list.length != 1
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have nest_list 1"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
when "struct"
if t.nest_list.length != 0
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have nest_list 0"
# if 0 == h_count t.field_hash
# throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have field_hash"
when "function"
if t.nest_list.length == 0
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} must have at least nest_list 1 (ret type)"
if 0 != h_count t.field_hash
throw new Error "Type validation error line=#{@line} pos=#{@pos}. #{t.main} can't have field_hash"
""
# TODO defined types ...
else
if !ctx.check_type t.main
throw new Error "unknown type '#{t}'"
for v,k in t.nest_list
# continue if k == 0 and t.main == "function" and v.main == "void" # it's ok
type_validate v, ctx
for k,v of t.field_hash
type_validate v, ctx
return
wrap = (_prepared_field2type)->
ret = new module.Class_decl
ret._prepared_field2type = _prepared_field2type
ret
@default_var_hash_gen = ()->
ret =
"true" : new Type "bool"
"false": new Type "bool"
@default_type_hash_gen = ()->
ret =
"array" : wrap
remove_idx : new Type "function<void, int>"
length_get : new Type "function<int>"
length_set : new Type "function<void, int>"
pop : new Type "function<_0>"
push : new Type "function<void,_0>"
slice : new Type "function<array<_0>,int,int>" # + option
remove : new Type "function<void,_0>"
idx : new Type "function<int,_0>"
has : new Type "function<bool,_0>"
append : new Type "function<void,array<_0>>"
clone : new Type "function<array<_0>>"
sort_i : new Type "function<void,function<int,_0,_0>>"
sort_f : new Type "function<void,function<float,_0,_0>>"
sort_by_i : new Type "function<void,function<int,_0>>"
sort_by_f : new Type "function<void,function<float,_0>>"
sort_by_s : new Type "function<void,function<string,_0>>"
"hash_int" : wrap
add : new Type "function<void,int,_0>"
remove_idx : new Type "function<void,int>"
idx : new Type "function<_0,int>"
class @Validation_context
parent : null
executable: false
breakable : false
returnable: false
type_hash : {}
var_hash : {}
line : 0
pos : 0
constructor:()->
@type_hash = module.default_type_hash_gen()
@var_hash = module.default_var_hash_gen()
seek_non_executable_parent : ()->
if @executable
@parent.seek_non_executable_parent()
else
@
mk_nest : (pass_breakable)->
ret = new module.Validation_context
ret.parent = @
ret.returnable= @returnable
ret.executable= @executable
ret.breakable = @breakable if pass_breakable
ret
check_type : (id)->
return found if found = @type_hash[id]
if @parent
return @parent.check_type id
return null
check_id : (id)->
return found if found = @var_hash[id]
if @parent
return @parent.check_id id
return null
check_id_decl : (id)->
@var_hash[id]
# ###################################################################################################
# expr
# ###################################################################################################
# TODO array init
# TODO hash init
# TODO interpolated string init
class @Const
val : ""
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
switch @type.main
when "bool"
unless @val in ["true", "false"]
throw new Error "Const validation error line=#{@line} pos=#{@pos}. '#{@val}' can't be bool"
when "int"
if parseInt(@val).toString() != @val
throw new Error "Const validation error line=#{@line} pos=#{@pos}. '#{@val}' can't be int"
when "float"
val = @val
val = val.replace(/\.0+$/, "")
val = val.replace(/e(\d)/i, "e+$1")
if parseFloat(val).toString() != val
throw new Error "Const validation error line=#{@line} pos=#{@pos}. '#{@val}' can't be float"
when "string"
"nothing"
# string will be quoted and escaped
# when "char"
else
throw new Error "can't implement constant type '#{@type}'"
return
clone : ()->
ret = new module.Const
ret.val = @val
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Array_init
list : []
type : null
line : 0
pos : 0
constructor:()->
@list = []
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if @type.main != "array"
throw new Error "Array_init validation error line=#{@line} pos=#{@pos}. type must be array but '#{@type}' found"
cmp_type = @type.nest_list[0]
for v,k in @list
v.validate(ctx)
if !v.type.cmp cmp_type
throw new Error "Array_init validation error line=#{@line} pos=#{@pos}. key '#{k}' must be type '#{cmp_type}' but '#{v.type}' found"
return
clone : ()->
ret = new module.Array_init
for v in @list
ret.list.push v.clone()
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Hash_init
hash : {}
type : null
line : 0
pos : 0
constructor:()->
@hash = {}
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if @type.main != "hash"
throw new Error "Hash_init validation error line=#{@line} pos=#{@pos}. type must be hash but '#{@type}' found"
for k,v of @hash
v.validate(ctx)
cmp_type = @type.nest_list[0]
for k,v of @hash
if !v.type.cmp cmp_type
throw new Error "Hash_init validation error line=#{@line} pos=#{@pos}. key '#{k}' must be type '#{cmp_type}' but '#{v.type}' found"
return
clone : ()->
ret = new module.Hash_init
for k,v of @hash
ret.hash[k] = v.clone()
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Struct_init
hash : {}
type : null
line : 0
pos : 0
constructor:()->
@hash = {}
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if @type.main != "struct"
throw new Error "Struct_init validation error line=#{@line} pos=#{@pos}. type must be struct but '#{@type}' found"
for k,v of @hash
v.validate(ctx)
if !v.type.cmp cmp_type = @type.field_hash[k]
throw new Error "Struct_init validation error line=#{@line} pos=#{@pos}. key '#{k}' must be type '#{cmp_type}' but '#{v.type}' found"
return
clone : ()->
ret = new module.Struct_init
for k,v of @hash
ret.hash[k] = v.clone()
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Var
name : ""
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !/^[_a-z][_a-z0-9]*$/i.test @name
throw new Error "Var validation error line=#{@line} pos=#{@pos}. invalid identifier '#{@name}'"
type_validate @type, ctx
var_decl = ctx.check_id(@name)
if !var_decl
throw new Error "Var validation error line=#{@line} pos=#{@pos}. Id '#{@name}' not defined"
{type} = var_decl
if !@type.cmp type
throw new Error "Var validation error line=#{@line} pos=#{@pos}. Var type !+ Var_decl type '#{@type}' != #{type}"
return
clone : ()->
ret = new module.Var
ret.name = @name
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
@allowed_bin_op_hash =
ADD : true
SUB : true
MUL : true
DIV : true
DIV_INT: true
MOD : true
POW : true
BIT_AND : true
BIT_OR : true
BIT_XOR : true
BOOL_AND : true
BOOL_OR : true
BOOL_XOR : true
SHR : true
SHL : true
LSR : true # логический сдвиг вправо >>>
ASSIGN : true
ASS_ADD : true
ASS_SUB : true
ASS_MUL : true
ASS_DIV : true
ASS_DIV_INT: true
ASS_MOD : true
ASS_POW : true
ASS_SHR : true
ASS_SHL : true
ASS_LSR : true # логический сдвиг вправо >>>
ASS_BIT_AND : true
ASS_BIT_OR : true
ASS_BIT_XOR : true
ASS_BOOL_AND : true
ASS_BOOL_OR : true
ASS_BOOL_XOR : true
EQ : true
NE : true
GT : true
LT : true
GTE: true
LTE: true
INDEX_ACCESS : true # a[b] как бинарный оператор
@assign_bin_op_hash =
ASSIGN : true
ASS_ADD : true
ASS_SUB : true
ASS_MUL : true
ASS_DIV : true
ASS_MOD : true
ASS_POW : true
ASS_SHR : true
ASS_SHL : true
ASS_LSR : true # логический сдвиг вправо >>>
ASS_BIT_AND : true
ASS_BIT_OR : true
ASS_BIT_XOR : true
ASS_BOOL_AND : true
ASS_BOOL_OR : true
ASS_BOOL_XOR : true
@bin_op_ret_type_hash_list =
DIV : [
["int", "int", "float"]
["int", "float", "float"]
["float", "int", "float"]
["float", "float", "float"]
]
DIV_INT : [
["int", "int", "int"]
["int", "float", "int"]
["float", "int", "int"]
["float", "float", "int"]
]
# mix int float -> higher
for v in "ADD SUB MUL POW".split /\s+/g
@bin_op_ret_type_hash_list[v] = [
["int", "int", "int"]
["int", "float", "float"]
["float", "int", "float"]
["float", "float", "float"]
]
# pure int
for v in "MOD BIT_AND BIT_OR BIT_XOR SHR SHL LSR".split /\s+/g
@bin_op_ret_type_hash_list[v] = [["int", "int", "int"]]
# pure bool
for v in "BOOL_AND BOOL_OR BOOL_XOR".split /\s+/g
@bin_op_ret_type_hash_list[v] = [["bool", "bool", "bool"]]
# special string magic
@bin_op_ret_type_hash_list.ADD.push ["string", "string", "string"]
@bin_op_ret_type_hash_list.MUL.push ["string", "int", "string"]
# equal ops =, cmp
for v in "ASSIGN".split /\s+/g
@bin_op_ret_type_hash_list[v] = [
["int", "int", "int"]
["bool", "bool", "bool"]
["float", "float", "float"]
["string", "string", "string"]
]
for v in "EQ NE GT LT GTE LTE".split /\s+/g
@bin_op_ret_type_hash_list[v] = [
["int", "int", "bool"]
["float", "float", "bool"]
["string", "string", "bool"]
]
str_list = """
ADD
SUB
MUL
DIV
DIV_INT
MOD
POW
SHR
SHL
LSR
BIT_AND
BIT_OR
BIT_XOR
BOOL_AND
BOOL_OR
BOOL_XOR
"""
for v in str_list.split /\s+/g
table = @bin_op_ret_type_hash_list[v]
table = table.filter (row)->row[0] == row[2]
table = table.map (t)-> t.clone() # make safe
@bin_op_ret_type_hash_list["ASS_#{v}"] = table
class @Bin_op
a : null
b : null
op : null
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !@a
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. a missing"
@a.validate(ctx)
if !@b
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. b missing"
@b.validate(ctx)
type_validate @type, ctx
if !module.allowed_bin_op_hash[@op]
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. Invalid op '#{@op}'"
found = false
if list = module.bin_op_ret_type_hash_list[@op]
for v in list
continue if v[0] != @a.type.toString()
continue if v[1] != @b.type.toString()
found = true
if v[2] != @type.toString()
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} with types #{@a.type} #{@b.type} should produce type #{v[2]} but #{@type} found"
break
# extra cases
if !found
if @op == "ASSIGN"
if @a.type.cmp @b.type
if @a.type.cmp @type
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. #{@op} a=b=[#{@a.type}] must have return type '#{@a.type}'"
else if @op in ["EQ", "NE"]
if @a.type.cmp @b.type
if @type.main == "bool"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. #{@op} a=b=[#{@a.type}] must have return type bool"
else if @op == "INDEX_ACCESS"
switch @a.type.main
when "string"
if @b.type.main == "int"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be int"
if @type.main == "string"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be string"
when "array"
if @b.type.main == "int"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be int"
if @type.cmp @a.type.nest_list[0]
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be #{@a.type.nest_list[0]} but #{@type} found"
when "hash"
if @b.type.main == "string"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be string"
if @type.cmp @a.type.nest_list[0]
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be #{@a.type.nest_list[0]} but #{@type} found"
when "hash_int"
if @b.type.main == "int"
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be int"
if @type.cmp @a.type.nest_list[0]
found = true
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. bin_op=#{@op} #{@a.type} #{@b.type} ret type must be #{@a.type.nest_list[0]} but #{@type} found"
else
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. Can't apply bin_op=#{@op} to #{@a.type} #{@b.type}"
if !found
throw new Error "Bin_op validation error line=#{@line} pos=#{@pos}. Can't apply bin_op=#{@op} to #{@a.type} #{@b.type}"
return
clone : ()->
ret = new module.Bin_op
ret.a = @a.clone()
ret.b = @b.clone()
ret.op = @op
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
@allowed_un_op_hash =
INC_RET : true
RET_INC : true
DEC_RET : true
RET_DEC : true
BOOL_NOT: true
BIT_NOT : true
MINUS : true
PLUS : true # parseFloat
IS_NOT_NULL : true
# new ?
# delete ?
@un_op_ret_type_hash_list =
INC_RET : [
["int", "int"]
]
RET_INC : [
["int", "int"]
]
DEC_RET : [
["int", "int"]
]
RET_DEC : [
["int", "int"]
]
BOOL_NOT : [
["bool", "bool"]
]
BIT_NOT : [
["int", "int"]
]
MINUS : [
["int", "int"]
["float", "float"]
]
PLUS : [
["string", "float"]
]
class @Un_op
a : null
op : null
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !@a
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. a missing"
@a.validate(ctx)
type_validate @type, ctx
if !module.allowed_un_op_hash[@op]
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. Invalid op '#{@op}'"
list = module.un_op_ret_type_hash_list[@op]
found = false
if list
for v in list
continue if v[0] != @a.type.toString()
found = true
if v[1] != @type.toString()
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. un_op=#{@op} with type #{@a.type} should produce type #{v[1]} but #{@type} found"
break
if @op == "IS_NOT_NULL"
if @type.main != "bool"
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. un_op=#{@op} with type #{@a.type} should produce type bool but #{@type} found"
found = true
if !found
throw new Error "Un_op validation error line=#{@line} pos=#{@pos}. Can't apply un_op=#{@op} to #{@a.type}"
return
clone : ()->
ret = new module.Un_op
ret.a = @a.clone()
ret.op = @op
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Field_access
t : null
name : ""
type : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
if !@t
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Missing target"
@t.validate(ctx)
if !@name
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Missing name"
type_validate @type, ctx
if @name == "new"
if @t.type.main in ["bool", "int", "float", "string"]
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to missing field '#{@name}' in '#{@t.type}'."
nest_type = new Type "function"
nest_type.nest_list[0] = @t.type
else if @t.type.main == "struct"
if !nest_type = @t.type.field_hash[@name]
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to missing field '#{@name}' in '#{@t.type}'. Possible keys [#{Object.keys(@t.type.field_hash).join ', '}]"
else
class_decl = ctx.check_type @t.type.main
if !nest_type = class_decl._prepared_field2type[@name]
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to missing class field '#{@name}' in '#{@t.type}'. Possible keys [#{Object.keys(class_decl._prepared_field2type).join ', '}]"
nest_type = type_actualize nest_type, @t.type
if !@type.cmp nest_type
throw new Error "Field_access validation error line=#{@line} pos=#{@pos}. Access to field '#{@name}' with type '#{nest_type}' but result '#{@type}'"
return
clone : ()->
ret = new module.Field_access
ret.t = @t.clone()
ret.name =PI:NAME:<NAME>END_PI @name
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
class @Fn_call
fn : null
arg_list : []
splat_fin : false
type : null
line : 0
pos : 0
constructor:()->
@arg_list = []
validate : (ctx = new module.Validation_context)->
if !@fn
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. fn missing"
@fn.validate(ctx)
if @fn.type.main != "function"
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. Can't call type '@fn.type'. You can call only function"
if !@type.cmp void_type
type_validate @type, ctx
if !@type.cmp @fn.type.nest_list[0]
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. Return type and function decl return type doesn't match #{@fn.type.nest_list[0]} != #{@type}"
if @fn.type.nest_list.length-1 != @arg_list.length
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. Expected arg count=#{@fn.type.nest_list.length-1} found=#{@arg_list.length}"
for arg,k in @arg_list
arg.validate(ctx)
if !@fn.type.nest_list[k+1].cmp arg.type
throw new Error "Fn_call validation error line=#{@line} pos=#{@pos}. arg[#{k}] type mismatch. Expected=#{@fn.type.nest_list[k+1]} found=#{arg.type}"
return
clone : ()->
ret = new module.Fn_call
ret.fn = @fn.clone()
for v in @arg_list
ret.arg_list.push v.clone()
ret.splat_fin = @splat_fin
ret.type = @type.clone() if @type
ret.line = @line
ret.pos = @pos
ret
# ###################################################################################################
# stmt
# ###################################################################################################
# TODO var_decl check
class @Scope
list : []
need_nest : true
line : 0
pos : 0
constructor:()->
@list = []
validate : (ctx = new module.Validation_context)->
if @need_nest
ctx_nest = ctx.mk_nest(true)
else
ctx_nest = ctx
for stmt in @list # for Class_decl
stmt.register?(ctx_nest)
for stmt in @list
stmt.validate(ctx_nest)
# на самом деле валидными есть только Fn_call и assign, но мы об этом умолчим
return
clone : ()->
ret = new module.Scope
for v in @list
ret.list.push v.clone()
ret.need_nest = @need_nest
ret.line = @line
ret.pos = @pos
ret
class @If
cond: null
t : null
f : null
line : 0
pos : 0
constructor:()->
@t = new module.Scope
@f = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@cond
throw new Error "If validation error line=#{@line} pos=#{@pos}. cond missing"
@cond.validate(ctx)
unless @cond.type.main in ["bool", "int"]
throw new Error "If validation error line=#{@line} pos=#{@pos}. cond must be bool or int but found '#{@cond.type}'"
@t.validate(ctx)
@f.validate(ctx)
if @t.list.length == 0
perr "Warning. If empty true body"
if @t.list.length == 0 and @f.list.length == 0
throw new Error "If validation error line=#{@line} pos=#{@pos}. Empty true and false sections"
return
clone : ()->
ret = new module.If
ret.cond = @cond.clone()
ret.t = @t.clone()
ret.f = @f.clone()
ret.line = @line
ret.pos = @pos
ret
# есть следующие валидные случаи компилирования switch
# 1. cont типа int. Тогда все hash key трактуются как int. (Но нельзя NaN и Infinity)
# 2. cont типа float.
# 3. cont типа string.
# 4. cont типа char.
class @Switch
cond : null
hash : {}
f : null # scope
line : 0
pos : 0
constructor:()->
@hash = {}
@f = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@cond
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. cond missing"
@cond.validate(ctx)
if 0 == h_count @hash
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. no when conditions found"
switch @cond.type.main
when "int"
for k,v of @hash
if parseInt(k).toString() != k or !isFinite k
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. key '#{k}' can't be int"
# when "float" # не разрешаем switch по float т.к. нельзя сравнивать float'ы через ==
# for k,v of @hash
# if !isFinite k
# throw new Error "Switch validation error line=#{@line} pos=#{@pos}. key '#{k}' can't be float"
when "string"
"nothing"
else
throw new Error "Switch validation error line=#{@line} pos=#{@pos}. Can't implement switch for condition type '#{@cond.type}'"
for k,v of @hash
v.validate(ctx.mk_nest())
@f?.validate(ctx)
return
clone : ()->
ret = new module.Switch
ret.cond = @cond.clone()
for k,v of @hash
ret.hash[k] = v.clone()
ret.f = @f.clone()
ret.line = @line
ret.pos = @pos
ret
class @Loop
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate(ctx_nest)
found = false
walk = (t)->
switch t.constructor.name
when "Scope"
for v in t.list
walk v
when "If"
walk t.t
walk t.f
when "Break", "Ret"
found = true
return
walk @scope
if !found
throw new Error "Loop validation error line=#{@line} pos=#{@pos}. Break or Ret not found"
# Не нужен т.к. все-равно ищем break
# if @scope.list.length == 0
# throw new Error "Loop validation error line=#{@line} pos=#{@pos}. Loop while is not allowed"
return
clone : ()->
ret = new module.Loop
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @Break
line : 0
pos : 0
constructor:()->
validate : (ctx = new module.Validation_context)->
if !ctx.breakable
throw new Error "Break validation error line=#{@line} pos=#{@pos}. You can't use break outside loop, while"
return
clone : ()->
ret = new module.Break
ret.line = @line
ret.pos = @pos
ret
class @Continue
line : 0
pos : 0
constructor:()->
validate : (ctx = new module.Validation_context)->
if !ctx.breakable
throw new Error "Continue validation error line=#{@line} pos=#{@pos}. You can't use continue outside loop, while"
return
clone : ()->
ret = new module.Continue
ret.line = @line
ret.pos = @pos
ret
class @While
cond : null
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@cond
throw new Error "While validation error line=#{@line} pos=#{@pos}. cond missing"
@cond.validate(ctx)
unless @cond.type.main in ["bool", "int"]
throw new Error "While validation error line=#{@line} pos=#{@pos}. cond must be bool or int"
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate(ctx_nest)
if @scope.list.length == 0
throw new Error "While validation error line=#{@line} pos=#{@pos}. Empty while is not allowed"
return
clone : ()->
ret = new module.While
ret.cond = @cond.clone()
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @For_range
exclusive : true
i : null
a : null
b : null
step : null
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@i
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Iterator is missing"
if !@a
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range a is missing"
if !@b
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range b is missing"
@i.validate ctx
@a.validate ctx
@b.validate ctx
@step?.validate ctx
unless @i.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Iterator should be type int or float but '#{@i.type}' found"
unless @a.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range a should be type int or float but '#{@a.type}' found"
unless @b.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range b should be type int or float but '#{@b.type}' found"
if @step
unless @step.type.main in ["int", "float"]
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Step should be type int or float but '#{@step.type}' found"
if @i.type.main == "int"
unless @a.type.main == "int"
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range a should be type int because iterator is int but '#{@a.type}' found"
unless @b.type.main == "int"
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Range b should be type int because iterator is int but '#{@b.type}' found"
if @step
unless @step.type.main == "int"
throw new Error "For_range validation error line=#{@line} pos=#{@pos}. Step should be type int because iterator is int but '#{@step.type}' found"
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate ctx_nest
return
clone : ()->
ret = new module.For_range
ret.exclusive = @exclusive
ret.i = @i.clone()
ret.a = @a.clone()
ret.b = @b.clone()
ret.step = @step.clone() if @step
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @For_col
k : null
v : null
t : null
scope : null
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@t
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Target is missing"
if !@k and !@v
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Key and value is missing"
@t.validate ctx
@k?.validate ctx
@v?.validate ctx
switch @t.type.main
when "array", "hash_int"
if @k
unless @k.type.main == "int"
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Key must be int for array<t> target but found '#{@k.type}'"
when "hash"
if @k
unless @k.type.main == "string"
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Key must be string for hash<t> target but found '#{@k.type}'"
else
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. For_col accepts types array<t>, hash<t> and hash_int<t> but found '#{@t.type}'"
if @v
unless @v.type.cmp @t.type.nest_list[0]
throw new Error "For_col validation error line=#{@line} pos=#{@pos}. Value must be '#{@t.type.nest_list[0]}' but found '#{@v.type}'"
ctx_nest = ctx.mk_nest()
ctx_nest.breakable = true
@scope.validate ctx_nest
return
clone : ()->
ret = new module.For_col
ret.t = @t.clone()
ret.v = @v.clone() if @v
ret.k = @k.clone() if @k
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
class @Ret
t : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
@t?.validate(ctx)
if !ctx.returnable
throw new Error "Ret validation error line=#{@line} pos=#{@pos}. ctx must be returnable"
return_type = ctx.check_id "$_return_type"
if @t?
if !@t.type.cmp return_type
throw new Error "Ret validation error line=#{@line} pos=#{@pos}. Ret type must be '#{return_type}' but found '#{@t.type}'"
else
if return_type.main != "void"
throw new Error "Ret validation error line=#{@line} pos=#{@pos}. Ret type must be '#{return_type}' but found void (no return value)"
return
clone : ()->
ret = new module.Ret
ret.t = @t.clone() if @t
ret.line = @line
ret.pos = @pos
ret
# ###################################################################################################
# Exceptions
# ###################################################################################################
class @Try
t : null
c : null
exception_var_name : ""
line : 0
pos : 0
constructor : ()->
@t = new module.Scope
@c = new module.Scope
# TODO validate
clone : ()->
ret = new module.Try
ret.t = @t.clone()
ret.c = @c.clone()
ret.exception_var_name = @exception_var_name
ret.line = @line
ret.pos = @pos
ret
class @Throw
t : null
line : 0
pos : 0
# TODO validate
clone : ()->
ret = new module.Throw
ret.t = @t.clone() if @t
ret.line = @line
ret.pos = @pos
ret
# ###################################################################################################
# decl
# ###################################################################################################
class @Var_decl
name : ""
type : null
size : null
assign_value : null
assign_value_list : null
line : 0
pos : 0
validate : (ctx = new module.Validation_context)->
type_validate @type, ctx
if ctx.check_id_decl(@name)
throw new Error "Var_decl validation error line=#{@line} pos=#{@pos}. Redeclare '#{@name}'"
# TODO size check
# а еще с type связь скорее всего должна быть
# TODO assign_value
# TODO assign_value_list
ctx.var_hash[@name] = @
return
clone : ()->
ret = new module.Var_decl
ret.name = @name
ret.type = @type.clone() if @type
ret.size = @size
ret.assign_value = @assign_value.clone() if @assign_value
if @assign_value_list
ret.assign_value_list = []
for v in @assign_value_list
ret.assign_value_list.push v.clone()
ret.line = @line
ret.pos = @pos
ret
class @Class_decl
name : ""
scope : null
_prepared_field2type : {}
line : 0
pos : 0
constructor:()->
@scope = new module.Scope
@_prepared_field2type = {}
register : (ctx = new module.Validation_context)->
if ctx.check_type @name
throw new Error "Already registered '#{@name}'"
ctx.type_hash[@name] = @
return
validate : (ctx = new module.Validation_context)->
if !@name
throw new Error "Class_decl validation error line=#{@line} pos=#{@pos}. Class should have name"
@_prepared_field2type = {} # ensure reset (some generators rewrite this field)
for v in @scope.list
unless v.constructor.name in ["Var_decl", "Fn_decl"]
throw new Error "Class_decl validation error line=#{@line} pos=#{@pos}. Only Var_decl and Fn_decl allowed at Class_decl, but '#{v.constructor.name}' found"
@_prepared_field2type[v.name] = v.type
ctx_nest = ctx.mk_nest()
# wrapper
var_decl = new module.Var_decl
var_decl.name = "this"
var_decl.type = new Type @name
ctx_nest.var_hash["this"] = var_decl
@scope.validate(ctx_nest)
return
clone : ()->
ret = new module.Class_decl
ret.name = @name
ret.scope = @scope.clone()
for k,v of @_prepared_field2type
ret._prepared_field2type[k] = v.clone()
ret.line = @line
ret.pos = @pos
ret
class @Fn_decl
is_closure : false
name : ""
type : null
arg_name_list : []
scope : null
line : 0
pos : 0
constructor:()->
@arg_name_list = []
@scope = new module.Scope
validate : (ctx = new module.Validation_context)->
if !@name and !@is_closure
throw new Error "Fn_decl validation error line=#{@line} pos=#{@pos}. Function should have name"
type_validate @type, ctx
if @type.main != "function"
throw new Error "Fn_decl validation error line=#{@line} pos=#{@pos}. Type must be function but '#{@type}' found"
if @type.nest_list.length-1 != @arg_name_list.length
throw new Error "Fn_decl validation error line=#{@line} pos=#{@pos}. @type.nest_list.length-1 != @arg_name_list #{@type.nest_list.length-1} != #{@arg_name_list.length}"
if @is_closure
ctx_nest = ctx.mk_nest()
else
ctx_nest = ctx.seek_non_executable_parent().mk_nest()
ctx_nest.executable = true
ctx_nest.returnable = true
for name,k in @arg_name_list
decl = new module.Var_decl
decl.name = PI:NAME:<NAME>END_PI
decl.type = @type.nest_list[1+k]
ctx_nest.var_hash[name] = decl
ctx_nest.var_hash["$_return_type"] = @type.nest_list[0]
@scope.validate(ctx_nest)
var_decl = new module.Var_decl
var_decl.name = @name
var_decl.type = @type
ctx.var_hash[@name] = var_decl
return
clone : ()->
ret = new module.Fn_decl
ret.is_closure = @is_closure
ret.name =PI:NAME:<NAME>END_PI @name
ret.type = @type.clone() if @type
ret.arg_name_list = @arg_name_list.clone()
ret.scope = @scope.clone()
ret.line = @line
ret.pos = @pos
ret
|
[
{
"context": "input {key:\"field\",className:\"email\",placeholder:\"your@email.com\",@onKeyUp}, @state.email)\n (button {key:\"s",
"end": 1025,
"score": 0.9996916055679321,
"start": 1011,
"tag": "EMAIL",
"value": "your@email.com"
}
] | urb/zod/pub/tree/src/js/components/EmailComponent.coffee | frodwith/urbit | 5 | reactify = require './Reactify.coffee'
recl = React.createClass
{div,p,button,input} = React.DOM
module.exports = recl
displayName: "email"
getInitialState: -> {submit:false,email:""}
onClick: -> @submit()
onKeyUp: (e) ->
email = @$email.val()
valid = (email.indexOf('@') != -1 &&
email.indexOf('.') != -1 &&
email.length > 7 &&
email.split(".")[1].length > 1 &&
email.split("@")[0].length > 0 &&
email.split("@")[1].length > 4)
@$email.toggleClass 'valid',valid
@$email.removeClass 'error'
if e.keyCode is 13
if valid is true
@submit()
e.stopPropagation()
e.preventDefault()
return false
else
@$email.addClass 'error'
submit: ->
$.post @props.dataPath,{email:@$email.val()},() =>
@setState {submit:true}
componentDidMount: -> @$email = $('input.email')
render: ->
if @state.submit is false
cont = [
(input {key:"field",className:"email",placeholder:"your@email.com",@onKeyUp}, @state.email)
(button {key:"submit",className:"submit",@onClick}, "Sign up")
]
else
cont = [(div {className:"submitted"},"Got it. Thanks!")]
(p {className:"email",id:"sign-up"}, cont)
| 159556 | reactify = require './Reactify.coffee'
recl = React.createClass
{div,p,button,input} = React.DOM
module.exports = recl
displayName: "email"
getInitialState: -> {submit:false,email:""}
onClick: -> @submit()
onKeyUp: (e) ->
email = @$email.val()
valid = (email.indexOf('@') != -1 &&
email.indexOf('.') != -1 &&
email.length > 7 &&
email.split(".")[1].length > 1 &&
email.split("@")[0].length > 0 &&
email.split("@")[1].length > 4)
@$email.toggleClass 'valid',valid
@$email.removeClass 'error'
if e.keyCode is 13
if valid is true
@submit()
e.stopPropagation()
e.preventDefault()
return false
else
@$email.addClass 'error'
submit: ->
$.post @props.dataPath,{email:@$email.val()},() =>
@setState {submit:true}
componentDidMount: -> @$email = $('input.email')
render: ->
if @state.submit is false
cont = [
(input {key:"field",className:"email",placeholder:"<EMAIL>",@onKeyUp}, @state.email)
(button {key:"submit",className:"submit",@onClick}, "Sign up")
]
else
cont = [(div {className:"submitted"},"Got it. Thanks!")]
(p {className:"email",id:"sign-up"}, cont)
| true | reactify = require './Reactify.coffee'
recl = React.createClass
{div,p,button,input} = React.DOM
module.exports = recl
displayName: "email"
getInitialState: -> {submit:false,email:""}
onClick: -> @submit()
onKeyUp: (e) ->
email = @$email.val()
valid = (email.indexOf('@') != -1 &&
email.indexOf('.') != -1 &&
email.length > 7 &&
email.split(".")[1].length > 1 &&
email.split("@")[0].length > 0 &&
email.split("@")[1].length > 4)
@$email.toggleClass 'valid',valid
@$email.removeClass 'error'
if e.keyCode is 13
if valid is true
@submit()
e.stopPropagation()
e.preventDefault()
return false
else
@$email.addClass 'error'
submit: ->
$.post @props.dataPath,{email:@$email.val()},() =>
@setState {submit:true}
componentDidMount: -> @$email = $('input.email')
render: ->
if @state.submit is false
cont = [
(input {key:"field",className:"email",placeholder:"PI:EMAIL:<EMAIL>END_PI",@onKeyUp}, @state.email)
(button {key:"submit",className:"submit",@onClick}, "Sign up")
]
else
cont = [(div {className:"submitted"},"Got it. Thanks!")]
(p {className:"email",id:"sign-up"}, cont)
|
[
{
"context": "ers', ->\n beforeEach ->\n @original = 'είμαι ένα αλφαριθμητικό'\n @encoded = 'zrXOr868zrHOuSDOrc69zrEgzrHO",
"end": 822,
"score": 0.9972255229949951,
"start": 799,
"tag": "NAME",
"value": "είμαι ένα αλφαριθμητικό"
},
{
"context": "l = 'είμαι ένα αλφα... | spec/base64_helper_spec.coffee | MrGoumX/analytics.js | 19 | describe 'Base64', ->
before (done) ->
require ['helpers/base64_helper'], (Base64) =>
@Base64 = Base64
done()
beforeEach ->
@original = 'i am a string'
@encoded = 'aSBhbSBhIHN0cmluZw=='
describe 'API', ->
beforeEach ->
@subject = @Base64
it 'responds to encode', ->
expect(@subject).to.respondTo('encode')
it 'responds to encodeURI', ->
expect(@subject).to.respondTo('encodeURI')
it 'responds to decode', ->
expect(@subject).to.respondTo('decode')
describe '.encode', ->
beforeEach ->
@subject = @Base64.encode(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
context 'when string contains non-ascii characters', ->
beforeEach ->
@original = 'είμαι ένα αλφαριθμητικό'
@encoded = 'zrXOr868zrHOuSDOrc69zrEgzrHOu8+GzrHPgc65zrjOvM63z4TOuc66z4w='
@subject = @Base64.encode(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
describe '.encodeURI', ->
beforeEach ->
@encoded = 'aSBhbSBhIHN0cmluZw'
@subject = @Base64.encodeURI(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
context 'when string contains non-ascii characters', ->
beforeEach ->
@original = 'είμαι ένα αλφαριθμητικό'
@encoded = 'zrXOr868zrHOuSDOrc69zrEgzrHOu8-GzrHPgc65zrjOvM63z4TOuc66z4w'
@subject = @Base64.encodeURI(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
describe '.decode', ->
beforeEach ->
@subject = @Base64.decode(@encoded)
it 'decodes the given string properly', ->
expect(@subject).to.eq(@original)
context 'when original string contained non-ascii characters', ->
beforeEach ->
@original = 'είμαι ένα αλφαριθμητικό'
@encoded = 'zrXOr868zrHOuSDOrc69zrEgzrHOu8+GzrHPgc65zrjOvM63z4TOuc66z4w='
@subject = @Base64.decode(@encoded)
it 'decodes the given string properly', ->
expect(@subject).to.eq(@original)
context 'when original string was URI encoded', ->
beforeEach ->
@encoded = 'aSBhbSBhIHN0cmluZw'
@subject = @Base64.decode(@encoded)
it 'decodes the given string properly', ->
expect(@subject).to.eq(@original)
| 20646 | describe 'Base64', ->
before (done) ->
require ['helpers/base64_helper'], (Base64) =>
@Base64 = Base64
done()
beforeEach ->
@original = 'i am a string'
@encoded = 'aSBhbSBhIHN0cmluZw=='
describe 'API', ->
beforeEach ->
@subject = @Base64
it 'responds to encode', ->
expect(@subject).to.respondTo('encode')
it 'responds to encodeURI', ->
expect(@subject).to.respondTo('encodeURI')
it 'responds to decode', ->
expect(@subject).to.respondTo('decode')
describe '.encode', ->
beforeEach ->
@subject = @Base64.encode(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
context 'when string contains non-ascii characters', ->
beforeEach ->
@original = '<NAME>'
@encoded = '<KEY>
@subject = @Base64.encode(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
describe '.encodeURI', ->
beforeEach ->
@encoded = 'aSBhbSBhIHN0cmluZw'
@subject = @Base64.encodeURI(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
context 'when string contains non-ascii characters', ->
beforeEach ->
@original = '<NAME>'
@encoded = '<KEY>'
@subject = @Base64.encodeURI(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
describe '.decode', ->
beforeEach ->
@subject = @Base64.decode(@encoded)
it 'decodes the given string properly', ->
expect(@subject).to.eq(@original)
context 'when original string contained non-ascii characters', ->
beforeEach ->
@original = '<NAME>'
@encoded = 'zrXOr868zrHOuSDOrc69zrEgzrHOu8+GzrHPgc65zrjOvM63z4TOuc66z4w='
@subject = @Base64.decode(@encoded)
it 'decodes the given string properly', ->
expect(@subject).to.eq(@original)
context 'when original string was URI encoded', ->
beforeEach ->
@encoded = 'aSBhbSBhIHN0cmluZw'
@subject = @Base64.decode(@encoded)
it 'decodes the given string properly', ->
expect(@subject).to.eq(@original)
| true | describe 'Base64', ->
before (done) ->
require ['helpers/base64_helper'], (Base64) =>
@Base64 = Base64
done()
beforeEach ->
@original = 'i am a string'
@encoded = 'aSBhbSBhIHN0cmluZw=='
describe 'API', ->
beforeEach ->
@subject = @Base64
it 'responds to encode', ->
expect(@subject).to.respondTo('encode')
it 'responds to encodeURI', ->
expect(@subject).to.respondTo('encodeURI')
it 'responds to decode', ->
expect(@subject).to.respondTo('decode')
describe '.encode', ->
beforeEach ->
@subject = @Base64.encode(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
context 'when string contains non-ascii characters', ->
beforeEach ->
@original = 'PI:NAME:<NAME>END_PI'
@encoded = 'PI:KEY:<KEY>END_PI
@subject = @Base64.encode(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
describe '.encodeURI', ->
beforeEach ->
@encoded = 'aSBhbSBhIHN0cmluZw'
@subject = @Base64.encodeURI(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
context 'when string contains non-ascii characters', ->
beforeEach ->
@original = 'PI:NAME:<NAME>END_PI'
@encoded = 'PI:KEY:<KEY>END_PI'
@subject = @Base64.encodeURI(@original)
it 'encodes the given string properly', ->
expect(@subject).to.eq(@encoded)
describe '.decode', ->
beforeEach ->
@subject = @Base64.decode(@encoded)
it 'decodes the given string properly', ->
expect(@subject).to.eq(@original)
context 'when original string contained non-ascii characters', ->
beforeEach ->
@original = 'PI:NAME:<NAME>END_PI'
@encoded = 'zrXOr868zrHOuSDOrc69zrEgzrHOu8+GzrHPgc65zrjOvM63z4TOuc66z4w='
@subject = @Base64.decode(@encoded)
it 'decodes the given string properly', ->
expect(@subject).to.eq(@original)
context 'when original string was URI encoded', ->
beforeEach ->
@encoded = 'aSBhbSBhIHN0cmluZw'
@subject = @Base64.decode(@encoded)
it 'decodes the given string properly', ->
expect(@subject).to.eq(@original)
|
[
{
"context": "{\n name: 'SimpleMoney'\n author: 'Andrew'\n requires: ['Smithy']\n gain",
"end": 22,
"score": 0.995998740196228,
"start": 11,
"tag": "USERNAME",
"value": "SimpleMoney"
},
{
"context": "{\n name: 'SimpleMoney'\n author: 'Andrew'\n requires: ['Smithy']\n gainPrio... | paper/SimpleMoney.coffee | cronburg/deckbuild-lang | 3 | {
name: 'SimpleMoney'
author: 'Andrew'
requires: ['Smithy']
gainPriority: (state, my) -> [
'Colony',
'Platinum'
'Province',
'Gold',
'Duchy',
'Silver',
'Smithy',
'Estate',
]
}
| 169182 | {
name: 'SimpleMoney'
author: '<NAME>'
requires: ['Smithy']
gainPriority: (state, my) -> [
'Colony',
'Platinum'
'Province',
'Gold',
'Duchy',
'Silver',
'Smithy',
'Estate',
]
}
| true | {
name: 'SimpleMoney'
author: 'PI:NAME:<NAME>END_PI'
requires: ['Smithy']
gainPriority: (state, my) -> [
'Colony',
'Platinum'
'Province',
'Gold',
'Duchy',
'Silver',
'Smithy',
'Estate',
]
}
|
[
{
"context": "luebird'\n require bluebird\n\nSERIALIZATION_KEY = 'NETOX'\nSERIALIZATION_EXPIRE_TIME_MS = 1000 * 10 # 10 se",
"end": 279,
"score": 0.9994889497756958,
"start": 274,
"tag": "KEY",
"value": "NETOX"
}
] | src/index.coffee | Zorium/netox | 1 | _ = require 'lodash'
Rx = require 'rx-lite'
URL = require 'url-parse'
request = require 'clay-request'
Promise = if window?
window.Promise
else
# TODO: remove once v8 is updated
# Avoid webpack include
bluebird = 'bluebird'
require bluebird
SERIALIZATION_KEY = 'NETOX'
SERIALIZATION_EXPIRE_TIME_MS = 1000 * 10 # 10 seconds
safeStringify = (obj) ->
JSON.stringify obj
.replace /<\/script/ig, '<\\/script'
.replace /<!--/g, '<\\!--'
.replace /\u2028/g, '\\u2028'
.replace /\u2029/g, '\\u2029'
module.exports = class Netox
constructor: ({@headers} = {}) ->
@headers ?= {}
@serializationCache = new Rx.BehaviorSubject {}
@timingListeners = []
loadedSerialization = window?[SERIALIZATION_KEY]
expires = loadedSerialization?.expires
if expires? and \
# Because of potential clock skew we check around the value
Math.abs(Date.now() - expires) < SERIALIZATION_EXPIRE_TIME_MS
pageCache = loadedSerialization?.cache or {}
@cache = _.mapValues pageCache, (res, key) ->
[optsString, url] = key.split '__z__'
opts = JSON.parse optsString
requestStreams = new Rx.ReplaySubject(1)
requestStreams.onNext Rx.Observable.just res
stream = requestStreams.switch()
{stream, requestStreams, url, proxyOpts: opts}
else
@cache = {}
_invalidateCache: =>
@serializationCache.onNext {}
@cache = _.transform @cache, (cache, val, key) =>
{stream, requestStreams, url, proxyOpts} = val
cachedSubject = null
requestStreams.onNext @_deferredRequestStream url, proxyOpts, (res) =>
nextCache = _.clone @serializationCache.getValue()
nextCache[key] = res
@serializationCache.onNext nextCache
cache[key] = {stream, requestStreams, url, proxyOpts}
, {}
_mergeHeaders: (opts) =>
# Only forward a subset of headers
_.merge
headers: _.pick @headers, [
'cookie'
'user-agent'
'accept-language'
'x-forwarded-for'
]
, opts
onTiming: (fn) =>
@timingListeners.push fn
_emitTiming: ({url, elapsed}) =>
parsed = new URL(url)
parsed.set 'query', null
parsed.set 'hash', null
_.map @timingListeners, (fn) ->
fn {url: parsed.toString(), elapsed}
_deferredRequestStream: (url, opts, onresult) =>
cachedPromise = null
Rx.Observable.defer =>
unless cachedPromise?
startTime = Date.now()
cachedPromise = request url, opts
.then (res) =>
endTime = Date.now()
elapsed = endTime - startTime
if opts?.isTimed
@_emitTiming {url, elapsed}
onresult res
return res
return cachedPromise
getSerializationStream: =>
@serializationCache
.map (cache) ->
serialization = {
cache: cache
expires: Date.now() + SERIALIZATION_EXPIRE_TIME_MS
}
"window['#{SERIALIZATION_KEY}'] = #{safeStringify(serialization)};"
fetch: (url, opts = {}) =>
proxyOpts = @_mergeHeaders opts
request url, proxyOpts
.then (res) =>
unless opts.isIdempotent
@_invalidateCache()
return res
stream: (url, opts = {}) =>
cacheKey = JSON.stringify(opts) + '__z__' + url
cached = @cache[cacheKey]
if cached?
return cached.stream
proxyOpts = @_mergeHeaders opts
requestStreams = new Rx.ReplaySubject(1)
requestStreams.onNext @_deferredRequestStream url, proxyOpts, (res) =>
nextCache = _.clone @serializationCache.getValue()
nextCache[cacheKey] = res
@serializationCache.onNext nextCache
stream = requestStreams.switch()
@cache[cacheKey] = {stream, requestStreams, url, proxyOpts}
return @cache[cacheKey].stream
| 61206 | _ = require 'lodash'
Rx = require 'rx-lite'
URL = require 'url-parse'
request = require 'clay-request'
Promise = if window?
window.Promise
else
# TODO: remove once v8 is updated
# Avoid webpack include
bluebird = 'bluebird'
require bluebird
SERIALIZATION_KEY = '<KEY>'
SERIALIZATION_EXPIRE_TIME_MS = 1000 * 10 # 10 seconds
safeStringify = (obj) ->
JSON.stringify obj
.replace /<\/script/ig, '<\\/script'
.replace /<!--/g, '<\\!--'
.replace /\u2028/g, '\\u2028'
.replace /\u2029/g, '\\u2029'
module.exports = class Netox
constructor: ({@headers} = {}) ->
@headers ?= {}
@serializationCache = new Rx.BehaviorSubject {}
@timingListeners = []
loadedSerialization = window?[SERIALIZATION_KEY]
expires = loadedSerialization?.expires
if expires? and \
# Because of potential clock skew we check around the value
Math.abs(Date.now() - expires) < SERIALIZATION_EXPIRE_TIME_MS
pageCache = loadedSerialization?.cache or {}
@cache = _.mapValues pageCache, (res, key) ->
[optsString, url] = key.split '__z__'
opts = JSON.parse optsString
requestStreams = new Rx.ReplaySubject(1)
requestStreams.onNext Rx.Observable.just res
stream = requestStreams.switch()
{stream, requestStreams, url, proxyOpts: opts}
else
@cache = {}
_invalidateCache: =>
@serializationCache.onNext {}
@cache = _.transform @cache, (cache, val, key) =>
{stream, requestStreams, url, proxyOpts} = val
cachedSubject = null
requestStreams.onNext @_deferredRequestStream url, proxyOpts, (res) =>
nextCache = _.clone @serializationCache.getValue()
nextCache[key] = res
@serializationCache.onNext nextCache
cache[key] = {stream, requestStreams, url, proxyOpts}
, {}
_mergeHeaders: (opts) =>
# Only forward a subset of headers
_.merge
headers: _.pick @headers, [
'cookie'
'user-agent'
'accept-language'
'x-forwarded-for'
]
, opts
onTiming: (fn) =>
@timingListeners.push fn
_emitTiming: ({url, elapsed}) =>
parsed = new URL(url)
parsed.set 'query', null
parsed.set 'hash', null
_.map @timingListeners, (fn) ->
fn {url: parsed.toString(), elapsed}
_deferredRequestStream: (url, opts, onresult) =>
cachedPromise = null
Rx.Observable.defer =>
unless cachedPromise?
startTime = Date.now()
cachedPromise = request url, opts
.then (res) =>
endTime = Date.now()
elapsed = endTime - startTime
if opts?.isTimed
@_emitTiming {url, elapsed}
onresult res
return res
return cachedPromise
getSerializationStream: =>
@serializationCache
.map (cache) ->
serialization = {
cache: cache
expires: Date.now() + SERIALIZATION_EXPIRE_TIME_MS
}
"window['#{SERIALIZATION_KEY}'] = #{safeStringify(serialization)};"
fetch: (url, opts = {}) =>
proxyOpts = @_mergeHeaders opts
request url, proxyOpts
.then (res) =>
unless opts.isIdempotent
@_invalidateCache()
return res
stream: (url, opts = {}) =>
cacheKey = JSON.stringify(opts) + '__z__' + url
cached = @cache[cacheKey]
if cached?
return cached.stream
proxyOpts = @_mergeHeaders opts
requestStreams = new Rx.ReplaySubject(1)
requestStreams.onNext @_deferredRequestStream url, proxyOpts, (res) =>
nextCache = _.clone @serializationCache.getValue()
nextCache[cacheKey] = res
@serializationCache.onNext nextCache
stream = requestStreams.switch()
@cache[cacheKey] = {stream, requestStreams, url, proxyOpts}
return @cache[cacheKey].stream
| true | _ = require 'lodash'
Rx = require 'rx-lite'
URL = require 'url-parse'
request = require 'clay-request'
Promise = if window?
window.Promise
else
# TODO: remove once v8 is updated
# Avoid webpack include
bluebird = 'bluebird'
require bluebird
SERIALIZATION_KEY = 'PI:KEY:<KEY>END_PI'
SERIALIZATION_EXPIRE_TIME_MS = 1000 * 10 # 10 seconds
safeStringify = (obj) ->
JSON.stringify obj
.replace /<\/script/ig, '<\\/script'
.replace /<!--/g, '<\\!--'
.replace /\u2028/g, '\\u2028'
.replace /\u2029/g, '\\u2029'
module.exports = class Netox
constructor: ({@headers} = {}) ->
@headers ?= {}
@serializationCache = new Rx.BehaviorSubject {}
@timingListeners = []
loadedSerialization = window?[SERIALIZATION_KEY]
expires = loadedSerialization?.expires
if expires? and \
# Because of potential clock skew we check around the value
Math.abs(Date.now() - expires) < SERIALIZATION_EXPIRE_TIME_MS
pageCache = loadedSerialization?.cache or {}
@cache = _.mapValues pageCache, (res, key) ->
[optsString, url] = key.split '__z__'
opts = JSON.parse optsString
requestStreams = new Rx.ReplaySubject(1)
requestStreams.onNext Rx.Observable.just res
stream = requestStreams.switch()
{stream, requestStreams, url, proxyOpts: opts}
else
@cache = {}
_invalidateCache: =>
@serializationCache.onNext {}
@cache = _.transform @cache, (cache, val, key) =>
{stream, requestStreams, url, proxyOpts} = val
cachedSubject = null
requestStreams.onNext @_deferredRequestStream url, proxyOpts, (res) =>
nextCache = _.clone @serializationCache.getValue()
nextCache[key] = res
@serializationCache.onNext nextCache
cache[key] = {stream, requestStreams, url, proxyOpts}
, {}
_mergeHeaders: (opts) =>
# Only forward a subset of headers
_.merge
headers: _.pick @headers, [
'cookie'
'user-agent'
'accept-language'
'x-forwarded-for'
]
, opts
onTiming: (fn) =>
@timingListeners.push fn
_emitTiming: ({url, elapsed}) =>
parsed = new URL(url)
parsed.set 'query', null
parsed.set 'hash', null
_.map @timingListeners, (fn) ->
fn {url: parsed.toString(), elapsed}
_deferredRequestStream: (url, opts, onresult) =>
cachedPromise = null
Rx.Observable.defer =>
unless cachedPromise?
startTime = Date.now()
cachedPromise = request url, opts
.then (res) =>
endTime = Date.now()
elapsed = endTime - startTime
if opts?.isTimed
@_emitTiming {url, elapsed}
onresult res
return res
return cachedPromise
getSerializationStream: =>
@serializationCache
.map (cache) ->
serialization = {
cache: cache
expires: Date.now() + SERIALIZATION_EXPIRE_TIME_MS
}
"window['#{SERIALIZATION_KEY}'] = #{safeStringify(serialization)};"
fetch: (url, opts = {}) =>
proxyOpts = @_mergeHeaders opts
request url, proxyOpts
.then (res) =>
unless opts.isIdempotent
@_invalidateCache()
return res
stream: (url, opts = {}) =>
cacheKey = JSON.stringify(opts) + '__z__' + url
cached = @cache[cacheKey]
if cached?
return cached.stream
proxyOpts = @_mergeHeaders opts
requestStreams = new Rx.ReplaySubject(1)
requestStreams.onNext @_deferredRequestStream url, proxyOpts, (res) =>
nextCache = _.clone @serializationCache.getValue()
nextCache[cacheKey] = res
@serializationCache.onNext nextCache
stream = requestStreams.switch()
@cache[cacheKey] = {stream, requestStreams, url, proxyOpts}
return @cache[cacheKey].stream
|
[
{
"context": "options = Util.makeRndOptions(newQuestion)\n\t\tkey = Util.generateKey(options)\n\t\tDb.shared.set 'rounds', maxRounds,\n",
"end": 1862,
"score": 0.786107063293457,
"start": 1849,
"tag": "KEY",
"value": "Util.generate"
}
] | server.coffee | Nouder123/WhoKnows | 0 | Db = require 'db'
Event = require 'event'
Plugin = require 'plugin'
Timer = require 'timer'
Util = require 'util'
{tr} = require 'i18n'
questions = Util.questions()
exports.onInstall = !->
Db.shared.set 'maxRounds', 0
# exports.onUpgrade = !->
# if !Db.shared.get('rounds')
# newRound()
exports.client_answer = (id, a) !->
log Plugin.userId(), "answered:", a
Db.shared.merge 'rounds', id, 'answers', Plugin.userId(), a
# Count number of people who answered. If it is everyone, we can resolve the question. (Handy for local party mode)
# No, there is no count() function for databased in the backend.
answers = 0
Db.shared.iterate 'rounds', id, 'answers', (a) !->
answers++
if answers is Plugin.userIds().length
log "All users answered the question"
Timer.cancel()
Timer.set 120*1000, 'resolve' # resolve after 2 min
exports.client_vote = (id, votes) !->
Db.shared.set 'rounds', id, 'votes', Plugin.userId(), votes
exports.client_timer = setTimers = !->
log "setTimers called"
time = 0|(Date.now()*.001)
roundDuration = Util.getRoundDuration(time)
Timer.cancel()
# if roundDuration > 3600
Timer.set roundDuration*1000, 'resolve'
Timer.set (roundDuration-120*60)*1000, 'reminder'
Db.shared.set 'next', time+roundDuration
exports.client_newRound = exports.newRound = newRound = !->
log "New Round!"
maxRounds = Db.shared.get 'maxRounds'
# find questions already used, select new one:
used = []
for i in [1..maxRounds]
qid = Db.shared.get 'rounds', i, 'qid'
used.push +qid
available = []
for q, nr in Util.questions()
if +nr not in used and q.q isnt null
available.push +nr
if available.length
maxRounds = Db.shared.incr 'maxRounds', 1
newQuestion = available[Math.floor(Math.random()*available.length)]
time = time = 0|(Date.now()*.001)
options = Util.makeRndOptions(newQuestion)
key = Util.generateKey(options)
Db.shared.set 'rounds', maxRounds,
'qid': newQuestion
'new': true
'time': time
'options': options # provide this in the 'correct' order. The client will rearrange them at random.
'key': key
log "made new question:", newQuestion, "(available", available.length, ") answers:", options, "key:", key
setTimers()
Event.create
text: tr("New question!")
if available.length is 1 # this was the last question
Db.shared.set 'ooq', true # Out Of Question
else
Db.shared.remove 'ooq'
else
log "ran out of questions"
exports.client_resolve = exports.resolve = resolve = (roundId) !->
if !roundId?
roundId = +Db.shared.get('maxRounds')
log "resolveRound", roundId
question = Db.shared.ref 'rounds', roundId
if !question?
log "Question not found"
return
if !question.get('new')?
log "Question already resolved"
# return
answers = question.get('answers')||[]
solution = Util.getSolution(roundId)
for user in Plugin.userIds()
input = (answers[user]||[]).slice(0) # clone array
continue unless input.length
target = solution.slice(0) # clone array
# calc score using the V⁴ Method (van Viegen, van Vliet)
# there are a maximum of 'steps' needed to bring any answer to the correct order. So the point range from 0 to 6
errors = 0
while input.length>0
errors += index = target.indexOf(input[0])
input.splice(0,1)
target.splice(index,1)
score = 6-errors
log "user #{user} answer:", answers[user], "solution:", solution, "errors:", errors, "score:", score
# for each other user
for user2 in Plugin.userIds()
if question.get('votes', user2, user) is true
question.set 'votes', user2, user, (if score>4 then 1 else -1)
log "votes:", user2, question.get('votes', user2, user )
# safe scores
if score then question.set 'scores', user, score # score for this round. Not needed when it's zero
Db.shared.incr 'scores', user, score # global
# for highest score
winners = []
highestScore = -1
# add to score, the result of their who knows comp.
for user in Plugin.userIds()
result = 0
votes = question.get 'votes', user
for k,v of votes
if typeof(v) is 'number'
result+=v
if result then question.set 'results', user, result
# safe to db
Db.shared.incr 'scores', user, result # global
#calc user with highest score
s = (question.get('scores', user)||0) + result
if s > highestScore
highestScore = s
winners = [user]
else if s is highestScore
winners.push user
winners.sort (a, b) ->
(question.get('scores', b)||0) - (question.get('scores', a)||0)
question.set 'winner', winners[0]
question.set 'new', null # flag question as resolved
Event.create
unit: 'round'
text: tr("%1\nResults are in!", Util.getQuestion(question.key()))
exports.reminder = !->
roundId = Db.shared.get('maxRounds')
remind = []
for userId in Plugin.userIds()
remind.push userId unless Db.shared.get('rounds', roundId, 'answers', userId)?
if remind.length
qId = Db.shared.get 'rounds', roundId, 'qid'
time = 0|(Date.now()*.001)
minsLeft = (Db.shared.get('next') - time) / 60
if minsLeft<60
leftText = tr("30 minutes")
else
leftText = tr("2 hours")
Event.create
for: remind
unit: 'remind'
text: tr("A question is waiting for your answer!")
# Old Method of calculating scores
# hits = 0
# for i in [0..3]
# t = input.slice(0) # clone, not point
# t.splice(t.indexOf(i),1)
# tt = target.slice(0) # clone, not point
# tt.splice(tt.indexOf(i),1)
# log 'testing', t, tt
# for j in [0..2]
# if t[j] is tt[j] then hits++
# score = Math.round(hits*10/12) | 53584 | Db = require 'db'
Event = require 'event'
Plugin = require 'plugin'
Timer = require 'timer'
Util = require 'util'
{tr} = require 'i18n'
questions = Util.questions()
exports.onInstall = !->
Db.shared.set 'maxRounds', 0
# exports.onUpgrade = !->
# if !Db.shared.get('rounds')
# newRound()
exports.client_answer = (id, a) !->
log Plugin.userId(), "answered:", a
Db.shared.merge 'rounds', id, 'answers', Plugin.userId(), a
# Count number of people who answered. If it is everyone, we can resolve the question. (Handy for local party mode)
# No, there is no count() function for databased in the backend.
answers = 0
Db.shared.iterate 'rounds', id, 'answers', (a) !->
answers++
if answers is Plugin.userIds().length
log "All users answered the question"
Timer.cancel()
Timer.set 120*1000, 'resolve' # resolve after 2 min
exports.client_vote = (id, votes) !->
Db.shared.set 'rounds', id, 'votes', Plugin.userId(), votes
exports.client_timer = setTimers = !->
log "setTimers called"
time = 0|(Date.now()*.001)
roundDuration = Util.getRoundDuration(time)
Timer.cancel()
# if roundDuration > 3600
Timer.set roundDuration*1000, 'resolve'
Timer.set (roundDuration-120*60)*1000, 'reminder'
Db.shared.set 'next', time+roundDuration
exports.client_newRound = exports.newRound = newRound = !->
log "New Round!"
maxRounds = Db.shared.get 'maxRounds'
# find questions already used, select new one:
used = []
for i in [1..maxRounds]
qid = Db.shared.get 'rounds', i, 'qid'
used.push +qid
available = []
for q, nr in Util.questions()
if +nr not in used and q.q isnt null
available.push +nr
if available.length
maxRounds = Db.shared.incr 'maxRounds', 1
newQuestion = available[Math.floor(Math.random()*available.length)]
time = time = 0|(Date.now()*.001)
options = Util.makeRndOptions(newQuestion)
key = <KEY>Key(options)
Db.shared.set 'rounds', maxRounds,
'qid': newQuestion
'new': true
'time': time
'options': options # provide this in the 'correct' order. The client will rearrange them at random.
'key': key
log "made new question:", newQuestion, "(available", available.length, ") answers:", options, "key:", key
setTimers()
Event.create
text: tr("New question!")
if available.length is 1 # this was the last question
Db.shared.set 'ooq', true # Out Of Question
else
Db.shared.remove 'ooq'
else
log "ran out of questions"
exports.client_resolve = exports.resolve = resolve = (roundId) !->
if !roundId?
roundId = +Db.shared.get('maxRounds')
log "resolveRound", roundId
question = Db.shared.ref 'rounds', roundId
if !question?
log "Question not found"
return
if !question.get('new')?
log "Question already resolved"
# return
answers = question.get('answers')||[]
solution = Util.getSolution(roundId)
for user in Plugin.userIds()
input = (answers[user]||[]).slice(0) # clone array
continue unless input.length
target = solution.slice(0) # clone array
# calc score using the V⁴ Method (van Viegen, van Vliet)
# there are a maximum of 'steps' needed to bring any answer to the correct order. So the point range from 0 to 6
errors = 0
while input.length>0
errors += index = target.indexOf(input[0])
input.splice(0,1)
target.splice(index,1)
score = 6-errors
log "user #{user} answer:", answers[user], "solution:", solution, "errors:", errors, "score:", score
# for each other user
for user2 in Plugin.userIds()
if question.get('votes', user2, user) is true
question.set 'votes', user2, user, (if score>4 then 1 else -1)
log "votes:", user2, question.get('votes', user2, user )
# safe scores
if score then question.set 'scores', user, score # score for this round. Not needed when it's zero
Db.shared.incr 'scores', user, score # global
# for highest score
winners = []
highestScore = -1
# add to score, the result of their who knows comp.
for user in Plugin.userIds()
result = 0
votes = question.get 'votes', user
for k,v of votes
if typeof(v) is 'number'
result+=v
if result then question.set 'results', user, result
# safe to db
Db.shared.incr 'scores', user, result # global
#calc user with highest score
s = (question.get('scores', user)||0) + result
if s > highestScore
highestScore = s
winners = [user]
else if s is highestScore
winners.push user
winners.sort (a, b) ->
(question.get('scores', b)||0) - (question.get('scores', a)||0)
question.set 'winner', winners[0]
question.set 'new', null # flag question as resolved
Event.create
unit: 'round'
text: tr("%1\nResults are in!", Util.getQuestion(question.key()))
exports.reminder = !->
roundId = Db.shared.get('maxRounds')
remind = []
for userId in Plugin.userIds()
remind.push userId unless Db.shared.get('rounds', roundId, 'answers', userId)?
if remind.length
qId = Db.shared.get 'rounds', roundId, 'qid'
time = 0|(Date.now()*.001)
minsLeft = (Db.shared.get('next') - time) / 60
if minsLeft<60
leftText = tr("30 minutes")
else
leftText = tr("2 hours")
Event.create
for: remind
unit: 'remind'
text: tr("A question is waiting for your answer!")
# Old Method of calculating scores
# hits = 0
# for i in [0..3]
# t = input.slice(0) # clone, not point
# t.splice(t.indexOf(i),1)
# tt = target.slice(0) # clone, not point
# tt.splice(tt.indexOf(i),1)
# log 'testing', t, tt
# for j in [0..2]
# if t[j] is tt[j] then hits++
# score = Math.round(hits*10/12) | true | Db = require 'db'
Event = require 'event'
Plugin = require 'plugin'
Timer = require 'timer'
Util = require 'util'
{tr} = require 'i18n'
questions = Util.questions()
exports.onInstall = !->
Db.shared.set 'maxRounds', 0
# exports.onUpgrade = !->
# if !Db.shared.get('rounds')
# newRound()
exports.client_answer = (id, a) !->
log Plugin.userId(), "answered:", a
Db.shared.merge 'rounds', id, 'answers', Plugin.userId(), a
# Count number of people who answered. If it is everyone, we can resolve the question. (Handy for local party mode)
# No, there is no count() function for databased in the backend.
answers = 0
Db.shared.iterate 'rounds', id, 'answers', (a) !->
answers++
if answers is Plugin.userIds().length
log "All users answered the question"
Timer.cancel()
Timer.set 120*1000, 'resolve' # resolve after 2 min
exports.client_vote = (id, votes) !->
Db.shared.set 'rounds', id, 'votes', Plugin.userId(), votes
exports.client_timer = setTimers = !->
log "setTimers called"
time = 0|(Date.now()*.001)
roundDuration = Util.getRoundDuration(time)
Timer.cancel()
# if roundDuration > 3600
Timer.set roundDuration*1000, 'resolve'
Timer.set (roundDuration-120*60)*1000, 'reminder'
Db.shared.set 'next', time+roundDuration
exports.client_newRound = exports.newRound = newRound = !->
log "New Round!"
maxRounds = Db.shared.get 'maxRounds'
# find questions already used, select new one:
used = []
for i in [1..maxRounds]
qid = Db.shared.get 'rounds', i, 'qid'
used.push +qid
available = []
for q, nr in Util.questions()
if +nr not in used and q.q isnt null
available.push +nr
if available.length
maxRounds = Db.shared.incr 'maxRounds', 1
newQuestion = available[Math.floor(Math.random()*available.length)]
time = time = 0|(Date.now()*.001)
options = Util.makeRndOptions(newQuestion)
key = PI:KEY:<KEY>END_PIKey(options)
Db.shared.set 'rounds', maxRounds,
'qid': newQuestion
'new': true
'time': time
'options': options # provide this in the 'correct' order. The client will rearrange them at random.
'key': key
log "made new question:", newQuestion, "(available", available.length, ") answers:", options, "key:", key
setTimers()
Event.create
text: tr("New question!")
if available.length is 1 # this was the last question
Db.shared.set 'ooq', true # Out Of Question
else
Db.shared.remove 'ooq'
else
log "ran out of questions"
exports.client_resolve = exports.resolve = resolve = (roundId) !->
if !roundId?
roundId = +Db.shared.get('maxRounds')
log "resolveRound", roundId
question = Db.shared.ref 'rounds', roundId
if !question?
log "Question not found"
return
if !question.get('new')?
log "Question already resolved"
# return
answers = question.get('answers')||[]
solution = Util.getSolution(roundId)
for user in Plugin.userIds()
input = (answers[user]||[]).slice(0) # clone array
continue unless input.length
target = solution.slice(0) # clone array
# calc score using the V⁴ Method (van Viegen, van Vliet)
# there are a maximum of 'steps' needed to bring any answer to the correct order. So the point range from 0 to 6
errors = 0
while input.length>0
errors += index = target.indexOf(input[0])
input.splice(0,1)
target.splice(index,1)
score = 6-errors
log "user #{user} answer:", answers[user], "solution:", solution, "errors:", errors, "score:", score
# for each other user
for user2 in Plugin.userIds()
if question.get('votes', user2, user) is true
question.set 'votes', user2, user, (if score>4 then 1 else -1)
log "votes:", user2, question.get('votes', user2, user )
# safe scores
if score then question.set 'scores', user, score # score for this round. Not needed when it's zero
Db.shared.incr 'scores', user, score # global
# for highest score
winners = []
highestScore = -1
# add to score, the result of their who knows comp.
for user in Plugin.userIds()
result = 0
votes = question.get 'votes', user
for k,v of votes
if typeof(v) is 'number'
result+=v
if result then question.set 'results', user, result
# safe to db
Db.shared.incr 'scores', user, result # global
#calc user with highest score
s = (question.get('scores', user)||0) + result
if s > highestScore
highestScore = s
winners = [user]
else if s is highestScore
winners.push user
winners.sort (a, b) ->
(question.get('scores', b)||0) - (question.get('scores', a)||0)
question.set 'winner', winners[0]
question.set 'new', null # flag question as resolved
Event.create
unit: 'round'
text: tr("%1\nResults are in!", Util.getQuestion(question.key()))
exports.reminder = !->
roundId = Db.shared.get('maxRounds')
remind = []
for userId in Plugin.userIds()
remind.push userId unless Db.shared.get('rounds', roundId, 'answers', userId)?
if remind.length
qId = Db.shared.get 'rounds', roundId, 'qid'
time = 0|(Date.now()*.001)
minsLeft = (Db.shared.get('next') - time) / 60
if minsLeft<60
leftText = tr("30 minutes")
else
leftText = tr("2 hours")
Event.create
for: remind
unit: 'remind'
text: tr("A question is waiting for your answer!")
# Old Method of calculating scores
# hits = 0
# for i in [0..3]
# t = input.slice(0) # clone, not point
# t.splice(t.indexOf(i),1)
# tt = target.slice(0) # clone, not point
# tt.splice(tt.indexOf(i),1)
# log 'testing', t, tt
# for j in [0..2]
# if t[j] is tt[j] then hits++
# score = Math.round(hits*10/12) |
[
{
"context": "\n\n service.config.credentials.accessKeyId = 'akid'\n service.config.credentials.secretAccessKey",
"end": 2589,
"score": 0.9977707862854004,
"start": 2585,
"tag": "KEY",
"value": "akid"
},
{
"context": "\n expired: false\n accessKeyId: 'INVA... | node_modules/aws-sdk/test/event_listeners.spec.coffee | Nordstrom/banquo-server | 1 | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
helpers = require('./helpers')
AWS = helpers.AWS
MockService = helpers.MockService
describe 'AWS.EventListeners', ->
oldSetTimeout = setTimeout
config = null; service = null; totalWaited = null; delays = []
successHandler = null; errorHandler = null; completeHandler = null
retryHandler = null
beforeEach ->
# Mock the timer manually (jasmine.Clock does not work in node)
`setTimeout = jasmine.createSpy('setTimeout');`
setTimeout.andCallFake (callback, delay) ->
totalWaited += delay
delays.push(delay)
callback()
totalWaited = 0
delays = []
service = new MockService(maxRetries: 3)
service.config.credentials = AWS.util.copy(service.config.credentials)
# Helpful handlers
successHandler = createSpy('success')
errorHandler = createSpy('error')
completeHandler = createSpy('complete')
retryHandler = createSpy('retry')
# Safely tear down setTimeout hack
afterEach -> `setTimeout = oldSetTimeout`
makeRequest = (callback) ->
request = service.makeRequest('mockMethod', foo: 'bar')
request.on('retry', retryHandler)
request.on('error', errorHandler)
request.on('success', successHandler)
request.on('complete', completeHandler)
if callback
request.on 'complete', (resp) ->
callback.call(resp, resp.error, resp.data)
request.send()
else
request
describe 'validate', ->
it 'takes the request object as a parameter', ->
request = makeRequest()
request.on 'validate', (req) ->
expect(req).toBe(request)
throw "ERROR"
response = request.send()
expect(response.error).toEqual("ERROR")
it 'sends error event if credentials are not set', ->
errorHandler = createSpy('errorHandler')
request = makeRequest()
request.on('error', errorHandler)
service.config.credentialProvider = null
service.config.credentials.accessKeyId = null
request.send()
service.config.credentials.accessKeyId = 'akid'
service.config.credentials.secretAccessKey = null
request.send()
expect(errorHandler).toHaveBeenCalled()
AWS.util.arrayEach errorHandler.calls, (call) ->
expect(call.args[0] instanceof Error).toBeTruthy()
expect(call.args[0].code).toEqual('SigningError')
expect(call.args[0].message).toMatch(/Missing credentials in config/)
it 'sends error event if region is not set', ->
service.config.region = null
request = makeRequest(->)
call = errorHandler.calls[0]
expect(errorHandler).toHaveBeenCalled()
expect(call.args[0] instanceof Error).toBeTruthy()
expect(call.args[0].code).toEqual('SigningError')
expect(call.args[0].message).toMatch(/Missing region in config/)
it 'ignores region validation if service has global endpoint', ->
service.config.region = null
service.api.globalEndpoint = 'mock.mockservice.tld'
makeRequest(->)
expect(errorHandler).not.toHaveBeenCalled()
delete service.api.globalEndpoint
describe 'build', ->
it 'takes the request object as a parameter', ->
request = makeRequest()
request.on 'build', (req) ->
expect(req).toBe(request)
throw "ERROR"
response = request.send()
expect(response.error).toEqual("ERROR")
describe 'afterBuild', ->
beforeEach ->
helpers.mockHttpResponse 200, {}, ['DATA']
sendRequest = (body) ->
request = makeRequest()
request.on('build', (req) -> req.httpRequest.body = body)
request.send()
request
contentLength = (body) ->
sendRequest(body).httpRequest.headers['Content-Length']
it 'builds Content-Length in the request headers for string content', ->
expect(contentLength('FOOBAR')).toEqual(6)
it 'builds Content-Length for string "0"', ->
expect(contentLength('0')).toEqual(1)
it 'builds Content-Length for utf-8 string body', ->
expect(contentLength('tï№')).toEqual(6)
it 'builds Content-Length for buffer body', ->
expect(contentLength(new Buffer('tï№'))).toEqual(6)
it 'builds Content-Length for file body', ->
fs = require('fs')
file = fs.createReadStream(__filename)
fileLen = fs.lstatSync(file.path).size
expect(contentLength(file)).toEqual(fileLen)
describe 'sign', ->
it 'takes the request object as a parameter', ->
request = makeRequest()
request.on 'sign', (req) ->
expect(req).toBe(request)
throw "ERROR"
response = request.send()
expect(response.error).toEqual("ERROR")
it 'uses the api.signingName if provided', ->
service.api.signingName = 'SIGNING_NAME'
spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake ->
(req, signingName) -> throw signingName
request = makeRequest()
response = request.send()
expect(response.error).toEqual('SIGNING_NAME')
delete service.api.signingName
it 'uses the api.endpointPrefix if signingName not provided', ->
spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake ->
(req, signingName) -> throw signingName
request = makeRequest()
response = request.send()
expect(response.error).toEqual('mockservice')
describe 'send', ->
it 'passes httpOptions from config', ->
options = {}
spyOn(AWS.HttpClient, 'getInstance').andReturn handleRequest: (req, opts) ->
options = opts
service.config.httpOptions = timeout: 15
service.config.maxRetries = 0
makeRequest(->)
expect(options.timeout).toEqual(15)
describe 'httpData', ->
beforeEach ->
helpers.mockHttpResponse 200, {}, ['FOO', 'BAR', 'BAZ', 'QUX']
it 'emits httpData event on each chunk', ->
calls = []
# register httpData event
request = makeRequest()
request.on('httpData', (chunk) -> calls.push(chunk.toString()))
request.send()
expect(calls).toEqual(['FOO', 'BAR', 'BAZ', 'QUX'])
it 'does not clear default httpData event if another is added', ->
request = makeRequest()
request.on('httpData', ->)
response = request.send()
expect(response.httpResponse.body.toString()).toEqual('FOOBARBAZQUX')
describe 'retry', ->
it 'retries a request with a set maximum retries', ->
sendHandler = createSpy('send')
service.config.maxRetries = 10
# fail every request with a fake networking error
helpers.mockHttpResponse
code: 'NetworkingError', message: 'Cannot connect'
request = makeRequest()
request.on('send', sendHandler)
response = request.send()
expect(retryHandler).toHaveBeenCalled()
expect(errorHandler).toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
expect(successHandler).not.toHaveBeenCalled()
expect(response.retryCount).toEqual(service.config.maxRetries);
expect(sendHandler.calls.length).toEqual(service.config.maxRetries + 1)
it 'retries with falloff', ->
helpers.mockHttpResponse
code: 'NetworkingError', message: 'Cannot connect'
makeRequest(->)
expect(delays).toEqual([30, 60, 120])
it 'retries if status code is >= 500', ->
helpers.mockHttpResponse 500, {}, ''
makeRequest (err) ->
expect(err).toEqual
code: 500,
message: null,
statusCode: 500
retryable: true
expect(@retryCount).
toEqual(service.config.maxRetries)
it 'should not emit error if retried fewer than maxRetries', ->
helpers.mockIntermittentFailureResponse 2, 200, {}, 'foo'
response = makeRequest(->)
expect(totalWaited).toEqual(90)
expect(response.retryCount).toBeLessThan(service.config.maxRetries)
expect(response.data).toEqual('foo')
expect(errorHandler).not.toHaveBeenCalled()
['ExpiredToken', 'ExpiredTokenException', 'RequestExpired'].forEach (name) ->
it 'invalidates expired credentials and retries', ->
spyOn(AWS.HttpClient, 'getInstance')
AWS.HttpClient.getInstance.andReturn handleRequest: (req, opts, cb, errCb) ->
if req.headers.Authorization.match('Credential=INVALIDKEY')
helpers.mockHttpSuccessfulResponse 403, {}, name, cb
else
helpers.mockHttpSuccessfulResponse 200, {}, 'DATA', cb
creds =
numCalls: 0
expired: false
accessKeyId: 'INVALIDKEY'
secretAccessKey: 'INVALIDSECRET'
get: (cb) ->
if @expired
@numCalls += 1
@expired = false
@accessKeyId = 'VALIDKEY' + @numCalls
@secretAccessKey = 'VALIDSECRET' + @numCalls
cb()
service.config.credentials = creds
response = makeRequest(->)
expect(response.retryCount).toEqual(1)
expect(creds.accessKeyId).toEqual('VALIDKEY1')
expect(creds.secretAccessKey).toEqual('VALIDSECRET1')
[301, 307].forEach (code) ->
it 'attempts to redirect on ' + code + ' responses', ->
helpers.mockHttpResponse code, {location: 'http://redirected'}, ''
service.config.maxRetries = 0
service.config.maxRedirects = 5
response = makeRequest(->)
expect(response.request.httpRequest.endpoint.host).toEqual('redirected')
expect(response.error.retryable).toEqual(true)
expect(response.redirectCount).toEqual(service.config.maxRedirects)
expect(delays).toEqual([0, 0, 0, 0, 0])
it 'does not redirect if 3xx is missing location header', ->
helpers.mockHttpResponse 304, {}, ''
service.config.maxRetries = 0
response = makeRequest(->)
expect(response.request.httpRequest.endpoint.host).not.toEqual('redirected')
expect(response.error.retryable).toEqual(false)
describe 'success', ->
it 'emits success on a successful response', ->
# fail every request with a fake networking error
helpers.mockHttpResponse 200, {}, 'Success!'
response = makeRequest(->)
expect(retryHandler).not.toHaveBeenCalled()
expect(errorHandler).not.toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
expect(successHandler).toHaveBeenCalled()
expect(response.retryCount).toEqual(0);
describe 'error', ->
it 'emits error if error found and should not be retrying', ->
# fail every request with a fake networking error
helpers.mockHttpResponse 400, {}, ''
response = makeRequest(->)
expect(retryHandler).not.toHaveBeenCalled()
expect(errorHandler).toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
expect(successHandler).not.toHaveBeenCalled()
expect(response.retryCount).toEqual(0);
it 'emits error if an error is set in extractError', ->
error = code: 'ParseError', message: 'error message'
extractDataHandler = createSpy('extractData')
helpers.mockHttpResponse 400, {}, ''
request = makeRequest()
request.on('extractData', extractDataHandler)
request.on('extractError', (resp) -> resp.error = error)
response = request.send()
expect(response.error).toBe(error)
expect(extractDataHandler).not.toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
expect(errorHandler).toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
describe 'logging', ->
data = null
logger = null
logfn = (d) -> data += d
match = /\[AWS mock 200 .* 0 retries\] mockMethod\(.*foo.*bar.*\)/
beforeEach ->
data = ''
logger = {}
service = new MockService(logger: logger)
it 'does nothing if logging is off', ->
service = new MockService(logger: null)
helpers.mockHttpResponse 200, {}, []
makeRequest().send()
expect(completeHandler).toHaveBeenCalled()
it 'calls .log() on logger if it is available', ->
helpers.mockHttpResponse 200, {}, []
logger.log = logfn
makeRequest().send()
expect(data).toMatch(match)
it 'calls .write() on logger if it is available', ->
helpers.mockHttpResponse 200, {}, []
logger.write = logfn
makeRequest().send()
expect(data).toMatch(match)
describe 'terminal callback error handling', ->
beforeEach ->
spyOn(process, 'exit')
spyOn(console, 'error')
didError = ->
expect(console.error).toHaveBeenCalledWith('ERROR')
expect(process.exit).toHaveBeenCalledWith(1)
describe 'without domains', ->
it 'logs exceptions raised from success event and exits process', ->
helpers.mockHttpResponse 200, {}, []
request = makeRequest()
request.on 'success', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
didError()
it 'logs exceptions raised from complete event and exits process', ->
helpers.mockHttpResponse 200, {}, []
request = makeRequest()
request.on 'complete', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
didError()
it 'logs exceptions raised from error event and exits process', ->
helpers.mockHttpResponse 500, {}, []
request = makeRequest()
request.on 'error', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
didError()
describe 'with domains', ->
it 'sends error raised from complete event to a domain', ->
result = false
d = require('domain').create()
if d.run
d.on('error', (e) -> result = e)
d.run ->
helpers.mockHttpResponse 200, {}, []
request = makeRequest()
request.on 'complete', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
expect(result).toEqual("ERROR")
it 'supports inner domains', ->
helpers.mockHttpResponse 200, {}, []
done = false
err = new Error()
gotOuterError = false
gotInnerError = false
Domain = require("domain")
outerDomain = Domain.create()
outerDomain.on 'error', (err) -> gotOuterError = true
if outerDomain.run
outerDomain.run ->
request = makeRequest()
innerDomain = Domain.create()
innerDomain.add(request)
innerDomain.on 'error', -> gotInnerError = true
runs ->
request.send ->
innerDomain.run -> done = true; throw err
waitsFor -> done
runs ->
expect(gotOuterError).toEqual(false)
expect(gotInnerError).toEqual(true)
expect(err.domainThrown).toEqual(false)
expect(err.domain).toEqual(innerDomain)
| 60957 | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
helpers = require('./helpers')
AWS = helpers.AWS
MockService = helpers.MockService
describe 'AWS.EventListeners', ->
oldSetTimeout = setTimeout
config = null; service = null; totalWaited = null; delays = []
successHandler = null; errorHandler = null; completeHandler = null
retryHandler = null
beforeEach ->
# Mock the timer manually (jasmine.Clock does not work in node)
`setTimeout = jasmine.createSpy('setTimeout');`
setTimeout.andCallFake (callback, delay) ->
totalWaited += delay
delays.push(delay)
callback()
totalWaited = 0
delays = []
service = new MockService(maxRetries: 3)
service.config.credentials = AWS.util.copy(service.config.credentials)
# Helpful handlers
successHandler = createSpy('success')
errorHandler = createSpy('error')
completeHandler = createSpy('complete')
retryHandler = createSpy('retry')
# Safely tear down setTimeout hack
afterEach -> `setTimeout = oldSetTimeout`
makeRequest = (callback) ->
request = service.makeRequest('mockMethod', foo: 'bar')
request.on('retry', retryHandler)
request.on('error', errorHandler)
request.on('success', successHandler)
request.on('complete', completeHandler)
if callback
request.on 'complete', (resp) ->
callback.call(resp, resp.error, resp.data)
request.send()
else
request
describe 'validate', ->
it 'takes the request object as a parameter', ->
request = makeRequest()
request.on 'validate', (req) ->
expect(req).toBe(request)
throw "ERROR"
response = request.send()
expect(response.error).toEqual("ERROR")
it 'sends error event if credentials are not set', ->
errorHandler = createSpy('errorHandler')
request = makeRequest()
request.on('error', errorHandler)
service.config.credentialProvider = null
service.config.credentials.accessKeyId = null
request.send()
service.config.credentials.accessKeyId = '<KEY>'
service.config.credentials.secretAccessKey = null
request.send()
expect(errorHandler).toHaveBeenCalled()
AWS.util.arrayEach errorHandler.calls, (call) ->
expect(call.args[0] instanceof Error).toBeTruthy()
expect(call.args[0].code).toEqual('SigningError')
expect(call.args[0].message).toMatch(/Missing credentials in config/)
it 'sends error event if region is not set', ->
service.config.region = null
request = makeRequest(->)
call = errorHandler.calls[0]
expect(errorHandler).toHaveBeenCalled()
expect(call.args[0] instanceof Error).toBeTruthy()
expect(call.args[0].code).toEqual('SigningError')
expect(call.args[0].message).toMatch(/Missing region in config/)
it 'ignores region validation if service has global endpoint', ->
service.config.region = null
service.api.globalEndpoint = 'mock.mockservice.tld'
makeRequest(->)
expect(errorHandler).not.toHaveBeenCalled()
delete service.api.globalEndpoint
describe 'build', ->
it 'takes the request object as a parameter', ->
request = makeRequest()
request.on 'build', (req) ->
expect(req).toBe(request)
throw "ERROR"
response = request.send()
expect(response.error).toEqual("ERROR")
describe 'afterBuild', ->
beforeEach ->
helpers.mockHttpResponse 200, {}, ['DATA']
sendRequest = (body) ->
request = makeRequest()
request.on('build', (req) -> req.httpRequest.body = body)
request.send()
request
contentLength = (body) ->
sendRequest(body).httpRequest.headers['Content-Length']
it 'builds Content-Length in the request headers for string content', ->
expect(contentLength('FOOBAR')).toEqual(6)
it 'builds Content-Length for string "0"', ->
expect(contentLength('0')).toEqual(1)
it 'builds Content-Length for utf-8 string body', ->
expect(contentLength('tï№')).toEqual(6)
it 'builds Content-Length for buffer body', ->
expect(contentLength(new Buffer('tï№'))).toEqual(6)
it 'builds Content-Length for file body', ->
fs = require('fs')
file = fs.createReadStream(__filename)
fileLen = fs.lstatSync(file.path).size
expect(contentLength(file)).toEqual(fileLen)
describe 'sign', ->
it 'takes the request object as a parameter', ->
request = makeRequest()
request.on 'sign', (req) ->
expect(req).toBe(request)
throw "ERROR"
response = request.send()
expect(response.error).toEqual("ERROR")
it 'uses the api.signingName if provided', ->
service.api.signingName = 'SIGNING_NAME'
spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake ->
(req, signingName) -> throw signingName
request = makeRequest()
response = request.send()
expect(response.error).toEqual('SIGNING_NAME')
delete service.api.signingName
it 'uses the api.endpointPrefix if signingName not provided', ->
spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake ->
(req, signingName) -> throw signingName
request = makeRequest()
response = request.send()
expect(response.error).toEqual('mockservice')
describe 'send', ->
it 'passes httpOptions from config', ->
options = {}
spyOn(AWS.HttpClient, 'getInstance').andReturn handleRequest: (req, opts) ->
options = opts
service.config.httpOptions = timeout: 15
service.config.maxRetries = 0
makeRequest(->)
expect(options.timeout).toEqual(15)
describe 'httpData', ->
beforeEach ->
helpers.mockHttpResponse 200, {}, ['FOO', 'BAR', 'BAZ', 'QUX']
it 'emits httpData event on each chunk', ->
calls = []
# register httpData event
request = makeRequest()
request.on('httpData', (chunk) -> calls.push(chunk.toString()))
request.send()
expect(calls).toEqual(['FOO', 'BAR', 'BAZ', 'QUX'])
it 'does not clear default httpData event if another is added', ->
request = makeRequest()
request.on('httpData', ->)
response = request.send()
expect(response.httpResponse.body.toString()).toEqual('FOOBARBAZQUX')
describe 'retry', ->
it 'retries a request with a set maximum retries', ->
sendHandler = createSpy('send')
service.config.maxRetries = 10
# fail every request with a fake networking error
helpers.mockHttpResponse
code: 'NetworkingError', message: 'Cannot connect'
request = makeRequest()
request.on('send', sendHandler)
response = request.send()
expect(retryHandler).toHaveBeenCalled()
expect(errorHandler).toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
expect(successHandler).not.toHaveBeenCalled()
expect(response.retryCount).toEqual(service.config.maxRetries);
expect(sendHandler.calls.length).toEqual(service.config.maxRetries + 1)
it 'retries with falloff', ->
helpers.mockHttpResponse
code: 'NetworkingError', message: 'Cannot connect'
makeRequest(->)
expect(delays).toEqual([30, 60, 120])
it 'retries if status code is >= 500', ->
helpers.mockHttpResponse 500, {}, ''
makeRequest (err) ->
expect(err).toEqual
code: 500,
message: null,
statusCode: 500
retryable: true
expect(@retryCount).
toEqual(service.config.maxRetries)
it 'should not emit error if retried fewer than maxRetries', ->
helpers.mockIntermittentFailureResponse 2, 200, {}, 'foo'
response = makeRequest(->)
expect(totalWaited).toEqual(90)
expect(response.retryCount).toBeLessThan(service.config.maxRetries)
expect(response.data).toEqual('foo')
expect(errorHandler).not.toHaveBeenCalled()
['ExpiredToken', 'ExpiredTokenException', 'RequestExpired'].forEach (name) ->
it 'invalidates expired credentials and retries', ->
spyOn(AWS.HttpClient, 'getInstance')
AWS.HttpClient.getInstance.andReturn handleRequest: (req, opts, cb, errCb) ->
if req.headers.Authorization.match('Credential=INVALIDKEY')
helpers.mockHttpSuccessfulResponse 403, {}, name, cb
else
helpers.mockHttpSuccessfulResponse 200, {}, 'DATA', cb
creds =
numCalls: 0
expired: false
accessKeyId: '<KEY>'
secretAccessKey: '<KEY>'
get: (cb) ->
if @expired
@numCalls += 1
@expired = false
@accessKeyId = '<KEY>' + @numCalls
@secretAccessKey = '<KEY>' + @numCalls
cb()
service.config.credentials = creds
response = makeRequest(->)
expect(response.retryCount).toEqual(1)
expect(creds.accessKeyId).toEqual('VALID<KEY>1')
expect(creds.secretAccessKey).toEqual('VALID<KEY>1')
[301, 307].forEach (code) ->
it 'attempts to redirect on ' + code + ' responses', ->
helpers.mockHttpResponse code, {location: 'http://redirected'}, ''
service.config.maxRetries = 0
service.config.maxRedirects = 5
response = makeRequest(->)
expect(response.request.httpRequest.endpoint.host).toEqual('redirected')
expect(response.error.retryable).toEqual(true)
expect(response.redirectCount).toEqual(service.config.maxRedirects)
expect(delays).toEqual([0, 0, 0, 0, 0])
it 'does not redirect if 3xx is missing location header', ->
helpers.mockHttpResponse 304, {}, ''
service.config.maxRetries = 0
response = makeRequest(->)
expect(response.request.httpRequest.endpoint.host).not.toEqual('redirected')
expect(response.error.retryable).toEqual(false)
describe 'success', ->
it 'emits success on a successful response', ->
# fail every request with a fake networking error
helpers.mockHttpResponse 200, {}, 'Success!'
response = makeRequest(->)
expect(retryHandler).not.toHaveBeenCalled()
expect(errorHandler).not.toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
expect(successHandler).toHaveBeenCalled()
expect(response.retryCount).toEqual(0);
describe 'error', ->
it 'emits error if error found and should not be retrying', ->
# fail every request with a fake networking error
helpers.mockHttpResponse 400, {}, ''
response = makeRequest(->)
expect(retryHandler).not.toHaveBeenCalled()
expect(errorHandler).toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
expect(successHandler).not.toHaveBeenCalled()
expect(response.retryCount).toEqual(0);
it 'emits error if an error is set in extractError', ->
error = code: 'ParseError', message: 'error message'
extractDataHandler = createSpy('extractData')
helpers.mockHttpResponse 400, {}, ''
request = makeRequest()
request.on('extractData', extractDataHandler)
request.on('extractError', (resp) -> resp.error = error)
response = request.send()
expect(response.error).toBe(error)
expect(extractDataHandler).not.toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
expect(errorHandler).toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
describe 'logging', ->
data = null
logger = null
logfn = (d) -> data += d
match = /\[AWS mock 200 .* 0 retries\] mockMethod\(.*foo.*bar.*\)/
beforeEach ->
data = ''
logger = {}
service = new MockService(logger: logger)
it 'does nothing if logging is off', ->
service = new MockService(logger: null)
helpers.mockHttpResponse 200, {}, []
makeRequest().send()
expect(completeHandler).toHaveBeenCalled()
it 'calls .log() on logger if it is available', ->
helpers.mockHttpResponse 200, {}, []
logger.log = logfn
makeRequest().send()
expect(data).toMatch(match)
it 'calls .write() on logger if it is available', ->
helpers.mockHttpResponse 200, {}, []
logger.write = logfn
makeRequest().send()
expect(data).toMatch(match)
describe 'terminal callback error handling', ->
beforeEach ->
spyOn(process, 'exit')
spyOn(console, 'error')
didError = ->
expect(console.error).toHaveBeenCalledWith('ERROR')
expect(process.exit).toHaveBeenCalledWith(1)
describe 'without domains', ->
it 'logs exceptions raised from success event and exits process', ->
helpers.mockHttpResponse 200, {}, []
request = makeRequest()
request.on 'success', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
didError()
it 'logs exceptions raised from complete event and exits process', ->
helpers.mockHttpResponse 200, {}, []
request = makeRequest()
request.on 'complete', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
didError()
it 'logs exceptions raised from error event and exits process', ->
helpers.mockHttpResponse 500, {}, []
request = makeRequest()
request.on 'error', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
didError()
describe 'with domains', ->
it 'sends error raised from complete event to a domain', ->
result = false
d = require('domain').create()
if d.run
d.on('error', (e) -> result = e)
d.run ->
helpers.mockHttpResponse 200, {}, []
request = makeRequest()
request.on 'complete', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
expect(result).toEqual("ERROR")
it 'supports inner domains', ->
helpers.mockHttpResponse 200, {}, []
done = false
err = new Error()
gotOuterError = false
gotInnerError = false
Domain = require("domain")
outerDomain = Domain.create()
outerDomain.on 'error', (err) -> gotOuterError = true
if outerDomain.run
outerDomain.run ->
request = makeRequest()
innerDomain = Domain.create()
innerDomain.add(request)
innerDomain.on 'error', -> gotInnerError = true
runs ->
request.send ->
innerDomain.run -> done = true; throw err
waitsFor -> done
runs ->
expect(gotOuterError).toEqual(false)
expect(gotInnerError).toEqual(true)
expect(err.domainThrown).toEqual(false)
expect(err.domain).toEqual(innerDomain)
| true | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
helpers = require('./helpers')
AWS = helpers.AWS
MockService = helpers.MockService
describe 'AWS.EventListeners', ->
oldSetTimeout = setTimeout
config = null; service = null; totalWaited = null; delays = []
successHandler = null; errorHandler = null; completeHandler = null
retryHandler = null
beforeEach ->
# Mock the timer manually (jasmine.Clock does not work in node)
`setTimeout = jasmine.createSpy('setTimeout');`
setTimeout.andCallFake (callback, delay) ->
totalWaited += delay
delays.push(delay)
callback()
totalWaited = 0
delays = []
service = new MockService(maxRetries: 3)
service.config.credentials = AWS.util.copy(service.config.credentials)
# Helpful handlers
successHandler = createSpy('success')
errorHandler = createSpy('error')
completeHandler = createSpy('complete')
retryHandler = createSpy('retry')
# Safely tear down setTimeout hack
afterEach -> `setTimeout = oldSetTimeout`
makeRequest = (callback) ->
request = service.makeRequest('mockMethod', foo: 'bar')
request.on('retry', retryHandler)
request.on('error', errorHandler)
request.on('success', successHandler)
request.on('complete', completeHandler)
if callback
request.on 'complete', (resp) ->
callback.call(resp, resp.error, resp.data)
request.send()
else
request
describe 'validate', ->
it 'takes the request object as a parameter', ->
request = makeRequest()
request.on 'validate', (req) ->
expect(req).toBe(request)
throw "ERROR"
response = request.send()
expect(response.error).toEqual("ERROR")
it 'sends error event if credentials are not set', ->
errorHandler = createSpy('errorHandler')
request = makeRequest()
request.on('error', errorHandler)
service.config.credentialProvider = null
service.config.credentials.accessKeyId = null
request.send()
service.config.credentials.accessKeyId = 'PI:KEY:<KEY>END_PI'
service.config.credentials.secretAccessKey = null
request.send()
expect(errorHandler).toHaveBeenCalled()
AWS.util.arrayEach errorHandler.calls, (call) ->
expect(call.args[0] instanceof Error).toBeTruthy()
expect(call.args[0].code).toEqual('SigningError')
expect(call.args[0].message).toMatch(/Missing credentials in config/)
it 'sends error event if region is not set', ->
service.config.region = null
request = makeRequest(->)
call = errorHandler.calls[0]
expect(errorHandler).toHaveBeenCalled()
expect(call.args[0] instanceof Error).toBeTruthy()
expect(call.args[0].code).toEqual('SigningError')
expect(call.args[0].message).toMatch(/Missing region in config/)
it 'ignores region validation if service has global endpoint', ->
service.config.region = null
service.api.globalEndpoint = 'mock.mockservice.tld'
makeRequest(->)
expect(errorHandler).not.toHaveBeenCalled()
delete service.api.globalEndpoint
describe 'build', ->
it 'takes the request object as a parameter', ->
request = makeRequest()
request.on 'build', (req) ->
expect(req).toBe(request)
throw "ERROR"
response = request.send()
expect(response.error).toEqual("ERROR")
describe 'afterBuild', ->
beforeEach ->
helpers.mockHttpResponse 200, {}, ['DATA']
sendRequest = (body) ->
request = makeRequest()
request.on('build', (req) -> req.httpRequest.body = body)
request.send()
request
contentLength = (body) ->
sendRequest(body).httpRequest.headers['Content-Length']
it 'builds Content-Length in the request headers for string content', ->
expect(contentLength('FOOBAR')).toEqual(6)
it 'builds Content-Length for string "0"', ->
expect(contentLength('0')).toEqual(1)
it 'builds Content-Length for utf-8 string body', ->
expect(contentLength('tï№')).toEqual(6)
it 'builds Content-Length for buffer body', ->
expect(contentLength(new Buffer('tï№'))).toEqual(6)
it 'builds Content-Length for file body', ->
fs = require('fs')
file = fs.createReadStream(__filename)
fileLen = fs.lstatSync(file.path).size
expect(contentLength(file)).toEqual(fileLen)
describe 'sign', ->
it 'takes the request object as a parameter', ->
request = makeRequest()
request.on 'sign', (req) ->
expect(req).toBe(request)
throw "ERROR"
response = request.send()
expect(response.error).toEqual("ERROR")
it 'uses the api.signingName if provided', ->
service.api.signingName = 'SIGNING_NAME'
spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake ->
(req, signingName) -> throw signingName
request = makeRequest()
response = request.send()
expect(response.error).toEqual('SIGNING_NAME')
delete service.api.signingName
it 'uses the api.endpointPrefix if signingName not provided', ->
spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake ->
(req, signingName) -> throw signingName
request = makeRequest()
response = request.send()
expect(response.error).toEqual('mockservice')
describe 'send', ->
it 'passes httpOptions from config', ->
options = {}
spyOn(AWS.HttpClient, 'getInstance').andReturn handleRequest: (req, opts) ->
options = opts
service.config.httpOptions = timeout: 15
service.config.maxRetries = 0
makeRequest(->)
expect(options.timeout).toEqual(15)
describe 'httpData', ->
beforeEach ->
helpers.mockHttpResponse 200, {}, ['FOO', 'BAR', 'BAZ', 'QUX']
it 'emits httpData event on each chunk', ->
calls = []
# register httpData event
request = makeRequest()
request.on('httpData', (chunk) -> calls.push(chunk.toString()))
request.send()
expect(calls).toEqual(['FOO', 'BAR', 'BAZ', 'QUX'])
it 'does not clear default httpData event if another is added', ->
request = makeRequest()
request.on('httpData', ->)
response = request.send()
expect(response.httpResponse.body.toString()).toEqual('FOOBARBAZQUX')
describe 'retry', ->
it 'retries a request with a set maximum retries', ->
sendHandler = createSpy('send')
service.config.maxRetries = 10
# fail every request with a fake networking error
helpers.mockHttpResponse
code: 'NetworkingError', message: 'Cannot connect'
request = makeRequest()
request.on('send', sendHandler)
response = request.send()
expect(retryHandler).toHaveBeenCalled()
expect(errorHandler).toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
expect(successHandler).not.toHaveBeenCalled()
expect(response.retryCount).toEqual(service.config.maxRetries);
expect(sendHandler.calls.length).toEqual(service.config.maxRetries + 1)
it 'retries with falloff', ->
helpers.mockHttpResponse
code: 'NetworkingError', message: 'Cannot connect'
makeRequest(->)
expect(delays).toEqual([30, 60, 120])
it 'retries if status code is >= 500', ->
helpers.mockHttpResponse 500, {}, ''
makeRequest (err) ->
expect(err).toEqual
code: 500,
message: null,
statusCode: 500
retryable: true
expect(@retryCount).
toEqual(service.config.maxRetries)
it 'should not emit error if retried fewer than maxRetries', ->
helpers.mockIntermittentFailureResponse 2, 200, {}, 'foo'
response = makeRequest(->)
expect(totalWaited).toEqual(90)
expect(response.retryCount).toBeLessThan(service.config.maxRetries)
expect(response.data).toEqual('foo')
expect(errorHandler).not.toHaveBeenCalled()
['ExpiredToken', 'ExpiredTokenException', 'RequestExpired'].forEach (name) ->
it 'invalidates expired credentials and retries', ->
spyOn(AWS.HttpClient, 'getInstance')
AWS.HttpClient.getInstance.andReturn handleRequest: (req, opts, cb, errCb) ->
if req.headers.Authorization.match('Credential=INVALIDKEY')
helpers.mockHttpSuccessfulResponse 403, {}, name, cb
else
helpers.mockHttpSuccessfulResponse 200, {}, 'DATA', cb
creds =
numCalls: 0
expired: false
accessKeyId: 'PI:KEY:<KEY>END_PI'
secretAccessKey: 'PI:KEY:<KEY>END_PI'
get: (cb) ->
if @expired
@numCalls += 1
@expired = false
@accessKeyId = 'PI:KEY:<KEY>END_PI' + @numCalls
@secretAccessKey = 'PI:KEY:<KEY>END_PI' + @numCalls
cb()
service.config.credentials = creds
response = makeRequest(->)
expect(response.retryCount).toEqual(1)
expect(creds.accessKeyId).toEqual('VALIDPI:KEY:<KEY>END_PI1')
expect(creds.secretAccessKey).toEqual('VALIDPI:KEY:<KEY>END_PI1')
[301, 307].forEach (code) ->
it 'attempts to redirect on ' + code + ' responses', ->
helpers.mockHttpResponse code, {location: 'http://redirected'}, ''
service.config.maxRetries = 0
service.config.maxRedirects = 5
response = makeRequest(->)
expect(response.request.httpRequest.endpoint.host).toEqual('redirected')
expect(response.error.retryable).toEqual(true)
expect(response.redirectCount).toEqual(service.config.maxRedirects)
expect(delays).toEqual([0, 0, 0, 0, 0])
it 'does not redirect if 3xx is missing location header', ->
helpers.mockHttpResponse 304, {}, ''
service.config.maxRetries = 0
response = makeRequest(->)
expect(response.request.httpRequest.endpoint.host).not.toEqual('redirected')
expect(response.error.retryable).toEqual(false)
describe 'success', ->
it 'emits success on a successful response', ->
# fail every request with a fake networking error
helpers.mockHttpResponse 200, {}, 'Success!'
response = makeRequest(->)
expect(retryHandler).not.toHaveBeenCalled()
expect(errorHandler).not.toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
expect(successHandler).toHaveBeenCalled()
expect(response.retryCount).toEqual(0);
describe 'error', ->
it 'emits error if error found and should not be retrying', ->
# fail every request with a fake networking error
helpers.mockHttpResponse 400, {}, ''
response = makeRequest(->)
expect(retryHandler).not.toHaveBeenCalled()
expect(errorHandler).toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
expect(successHandler).not.toHaveBeenCalled()
expect(response.retryCount).toEqual(0);
it 'emits error if an error is set in extractError', ->
error = code: 'ParseError', message: 'error message'
extractDataHandler = createSpy('extractData')
helpers.mockHttpResponse 400, {}, ''
request = makeRequest()
request.on('extractData', extractDataHandler)
request.on('extractError', (resp) -> resp.error = error)
response = request.send()
expect(response.error).toBe(error)
expect(extractDataHandler).not.toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
expect(errorHandler).toHaveBeenCalled()
expect(completeHandler).toHaveBeenCalled()
describe 'logging', ->
data = null
logger = null
logfn = (d) -> data += d
match = /\[AWS mock 200 .* 0 retries\] mockMethod\(.*foo.*bar.*\)/
beforeEach ->
data = ''
logger = {}
service = new MockService(logger: logger)
it 'does nothing if logging is off', ->
service = new MockService(logger: null)
helpers.mockHttpResponse 200, {}, []
makeRequest().send()
expect(completeHandler).toHaveBeenCalled()
it 'calls .log() on logger if it is available', ->
helpers.mockHttpResponse 200, {}, []
logger.log = logfn
makeRequest().send()
expect(data).toMatch(match)
it 'calls .write() on logger if it is available', ->
helpers.mockHttpResponse 200, {}, []
logger.write = logfn
makeRequest().send()
expect(data).toMatch(match)
describe 'terminal callback error handling', ->
beforeEach ->
spyOn(process, 'exit')
spyOn(console, 'error')
didError = ->
expect(console.error).toHaveBeenCalledWith('ERROR')
expect(process.exit).toHaveBeenCalledWith(1)
describe 'without domains', ->
it 'logs exceptions raised from success event and exits process', ->
helpers.mockHttpResponse 200, {}, []
request = makeRequest()
request.on 'success', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
didError()
it 'logs exceptions raised from complete event and exits process', ->
helpers.mockHttpResponse 200, {}, []
request = makeRequest()
request.on 'complete', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
didError()
it 'logs exceptions raised from error event and exits process', ->
helpers.mockHttpResponse 500, {}, []
request = makeRequest()
request.on 'error', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
didError()
describe 'with domains', ->
it 'sends error raised from complete event to a domain', ->
result = false
d = require('domain').create()
if d.run
d.on('error', (e) -> result = e)
d.run ->
helpers.mockHttpResponse 200, {}, []
request = makeRequest()
request.on 'complete', -> throw "ERROR"
expect(-> request.send()).not.toThrow('ERROR')
expect(completeHandler).toHaveBeenCalled()
expect(retryHandler).not.toHaveBeenCalled()
expect(result).toEqual("ERROR")
it 'supports inner domains', ->
helpers.mockHttpResponse 200, {}, []
done = false
err = new Error()
gotOuterError = false
gotInnerError = false
Domain = require("domain")
outerDomain = Domain.create()
outerDomain.on 'error', (err) -> gotOuterError = true
if outerDomain.run
outerDomain.run ->
request = makeRequest()
innerDomain = Domain.create()
innerDomain.add(request)
innerDomain.on 'error', -> gotInnerError = true
runs ->
request.send ->
innerDomain.run -> done = true; throw err
waitsFor -> done
runs ->
expect(gotOuterError).toEqual(false)
expect(gotInnerError).toEqual(true)
expect(err.domainThrown).toEqual(false)
expect(err.domain).toEqual(innerDomain)
|
[
{
"context": "e.addColumn 'value'\n\n table.addRow ['name', 'Jane Doe']\n table.addRow ['age', 30]\n table.addR",
"end": 1820,
"score": 0.9997775554656982,
"start": 1812,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": " [\"name\",\"age\",\"gender\"]\n ... | spec/table-editor-spec.coffee | lionel-rigoux/atom-tablr | 186 | require './helpers/spec-helper'
TableEditor = require '../lib/table-editor'
Table = require '../lib/table'
describe 'TableEditor', ->
[table, displayTable, tableEditor] = []
beforeEach ->
atom.config.set 'tablr.tableEditor.columnWidth', 100
atom.config.set 'tablr.minimuColumnWidth', 10
atom.config.set 'tablr.tableEditor.rowHeight', 20
atom.config.set 'tablr.tableEditor.minimumRowHeight', 10
describe 'when initialized without a table', ->
beforeEach ->
tableEditor = new TableEditor
{table, displayTable} = tableEditor
it 'creates an empty table and its displayTable', ->
expect(table).toBeDefined()
expect(displayTable).toBeDefined()
it 'retains the table', ->
expect(table.isRetained()).toBeTruthy()
it 'has a default empty selection', ->
expect(tableEditor.getLastSelection()).toBeDefined()
expect(tableEditor.getSelections()).toEqual([tableEditor.getLastSelection()])
expect(tableEditor.getLastSelection().getRange()).toEqual([[0,0],[0,0]])
expect(tableEditor.getLastSelection().getCursor()).toEqual(tableEditor.getLastCursor())
it 'has a default cursor position', ->
expect(tableEditor.getCursorPosition()).toEqual([0,0])
expect(tableEditor.getCursorPositions()).toEqual([[0,0]])
expect(tableEditor.getCursorScreenPosition()).toEqual([0,0])
expect(tableEditor.getCursorScreenPositions()).toEqual([[0,0]])
it 'returns undefined when asked for the value at cursor', ->
expect(tableEditor.getCursorValue()).toBeUndefined()
expect(tableEditor.getCursorValues()).toEqual([undefined])
describe 'when initialized with a table', ->
beforeEach ->
table = new Table
table.addColumn 'key'
table.addColumn 'value'
table.addRow ['name', 'Jane Doe']
table.addRow ['age', 30]
table.addRow ['gender', 'female']
tableEditor = new TableEditor({table})
{displayTable} = tableEditor
displayTable.sortBy('key')
it 'uses the passed-in table', ->
expect(displayTable).toBeDefined()
expect(displayTable.table).toBe(table)
expect(tableEditor.table).toBe(table)
it 'retains the table', ->
expect(table.isRetained()).toBeTruthy()
it 'has a default empty selection', ->
expect(tableEditor.getLastSelection()).toBeDefined()
expect(tableEditor.getSelections()).toEqual([tableEditor.getLastSelection()])
expect(tableEditor.getLastSelection().getRange()).toEqual([[0,0],[1,1]])
expect(tableEditor.getLastSelection().getCursor()).toEqual(tableEditor.getLastCursor())
it 'has a default cursor position', ->
expect(tableEditor.getCursorPosition()).toEqual([1,0])
expect(tableEditor.getCursorPositions()).toEqual([[1,0]])
expect(tableEditor.getCursorScreenPosition()).toEqual([0,0])
expect(tableEditor.getCursorScreenPositions()).toEqual([[0,0]])
it 'returns the value at cursor', ->
expect(tableEditor.getCursorValue()).toEqual('age')
expect(tableEditor.getCursorValues()).toEqual(['age'])
describe '::delete', ->
it 'deletes the content of the selected cells', ->
initialValue = tableEditor.getCursorValue()
expect(initialValue).not.toBeUndefined()
tableEditor.delete()
expect(tableEditor.getCursorValue()).toBeUndefined()
tableEditor.undo()
expect(tableEditor.getCursorValue()).toEqual(initialValue)
tableEditor.redo()
expect(tableEditor.getCursorValue()).toBeUndefined()
describe 'when destroyed', ->
beforeEach ->
tableEditor.destroy()
it 'destroys its table and display table', ->
expect(table.isDestroyed()).toBeTruthy()
expect(displayTable.isDestroyed()).toBeTruthy()
it 'is destroyed', ->
expect(tableEditor.isDestroyed()).toBeTruthy()
it 'removes its cursors and selections', ->
expect(tableEditor.getCursors().length).toEqual(0)
expect(tableEditor.getSelections().length).toEqual(0)
## ######## ######## ###### ######## ####### ######## ########
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ##
## ######## ###### ###### ## ## ## ######## ######
## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ######## ###### ## ####### ## ## ########
describe '::serialize', ->
it 'serializes the table editor', ->
expect(tableEditor.serialize()).toEqual({
deserializer: 'TableEditor'
displayTable: tableEditor.displayTable.serialize()
cursors: tableEditor.getCursors().map (cursor) -> cursor.serialize()
selections: tableEditor.getSelections().map (sel) -> sel.serialize()
})
describe '.deserialize', ->
it 'restores a table editor', ->
tableEditor = atom.deserializers.deserialize({
deserializer: 'TableEditor'
displayTable:
deserializer: 'DisplayTable'
rowHeights: [null,null,null,null]
table:
deserializer: 'Table'
modified: true
cachedContents: undefined
columns: [null,null,null]
rows: [
["name","age","gender"]
["Jane","32","female"]
["John","30","male"]
[null,null,null]
]
id: 1
cursors: [[2,2]]
selections: [[[2,2],[3,4]]]
})
expect(tableEditor.isModified()).toBeTruthy()
expect(tableEditor.getScreenRows()).toEqual([
["name","age","gender"]
["Jane","32","female"]
["John","30","male"]
[null,null,null]
])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getSelectedRange()).toEqual([[2,2],[3,4]])
expect(tableEditor.getCursorPosition()).toEqual([2,2])
## ###### ## ## ######## ###### ####### ######## ######
## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ######## ###### ## ## ######## ######
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ###### ####### ## ## ###### ####### ## ## ######
describe 'for an empty table', ->
describe 'adding a column and a row', ->
it 'set the cursor position to 0,0', ->
table = new Table
tableEditor = new TableEditor({table})
tableEditor.initializeAfterSetup()
tableEditor.insertColumnAfter()
tableEditor.insertRowAfter()
expect(tableEditor.getCursorPosition()).toEqual([0,0])
describe '::addCursorAtScreenPosition', ->
it 'adds a cursor', ->
tableEditor.addCursorAtScreenPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getSelections().length).toEqual(2)
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtScreenPosition([0,0])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
it 'dispatch a did-add-cursor event', ->
spy = jasmine.createSpy('did-add-cursor')
tableEditor.onDidAddCursor(spy)
tableEditor.addCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'dispatch a did-add-selection event', ->
spy = jasmine.createSpy('did-add-selection')
tableEditor.onDidAddSelection(spy)
tableEditor.addCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
describe '::addCursorAtPosition', ->
it 'adds a cursor', ->
tableEditor.addCursorAtPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getSelections().length).toEqual(2)
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtPosition([1,0])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
it 'dispatch a did-add-cursor event', ->
spy = jasmine.createSpy('did-add-cursor')
tableEditor.onDidAddCursor(spy)
tableEditor.addCursorAtPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'dispatch a did-add-selection event', ->
spy = jasmine.createSpy('did-add-selection')
tableEditor.onDidAddSelection(spy)
tableEditor.addCursorAtPosition([1,1])
expect(spy).toHaveBeenCalled()
describe '::addCursorBelowLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorBelowLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([5,2])
describe '::addCursorAboveLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorAboveLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([2,2])
describe '::addCursorLeftToLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorLeftToLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([3,1])
describe '::addCursorRightToLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorRightToLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([3,4])
describe '::setCursorAtScreenPosition', ->
it 'sets the cursor position', ->
tableEditor.setCursorAtScreenPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
it 'dispatch a did-change-cursor-position event', ->
spy = jasmine.createSpy('did-change-cursor-position')
tableEditor.onDidChangeCursorPosition(spy)
tableEditor.setCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'dispatch a did-change-selection-range event', ->
spy = jasmine.createSpy('did-change-selection-range')
tableEditor.onDidChangeSelectionRange(spy)
tableEditor.setCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtScreenPosition([2,1])
tableEditor.addCursorAtScreenPosition([1,2])
tableEditor.setCursorAtScreenPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
describe '::setCursorAtPosition', ->
it 'sets the cursor position', ->
tableEditor.setCursorAtPosition([2,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtScreenPosition([2,1])
tableEditor.addCursorAtScreenPosition([1,2])
tableEditor.setCursorAtPosition([2,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
describe '::moveLineDown', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.addCursorAtPosition([2,0])
tableEditor.addCursorAtPosition([4,0])
table.clearUndoStack()
it 'moves the lines at cursors one line down', ->
tableEditor.moveLineDown()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
expect(tableEditor.getScreenRow(0)).toEqual(['row1', 100, 'no'])
expect(tableEditor.getScreenRow(1)).toEqual(['row0', 0, 'yes'])
expect(tableEditor.getScreenRow(2)).toEqual(['row3', 300, 'no'])
expect(tableEditor.getScreenRow(3)).toEqual(['row2', 200, 'yes'])
expect(tableEditor.getScreenRow(4)).toEqual(['row5', 500, 'no'])
expect(tableEditor.getScreenRow(5)).toEqual(['row4', 400, 'yes'])
it 'updates the selections', ->
tableEditor.moveLineDown()
expect(tableEditor.getSelectedRanges()).toEqual([
[[1,0],[2,1]]
[[3,0],[4,1]]
[[5,0],[6,1]]
])
it 'can undo the cursors moves', ->
tableEditor.moveLineDown()
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
describe 'when there is an order defined', ->
beforeEach ->
tableEditor.sortBy('key')
it 'does nothing and creates a notification instead', ->
spyOn(atom.notifications, 'addWarning')
tableEditor.moveLineDown()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
expect(atom.notifications.addWarning).toHaveBeenCalled()
describe '::moveLineUp', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.setCursorAtPosition([1,0])
tableEditor.addCursorAtPosition([3,0])
tableEditor.addCursorAtPosition([5,0])
table.clearUndoStack()
it 'moves the lines at cursors one line up', ->
tableEditor.moveLineUp()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
expect(tableEditor.getScreenRow(0)).toEqual(['row1', 100, 'no'])
expect(tableEditor.getScreenRow(1)).toEqual(['row0', 0, 'yes'])
expect(tableEditor.getScreenRow(2)).toEqual(['row3', 300, 'no'])
expect(tableEditor.getScreenRow(3)).toEqual(['row2', 200, 'yes'])
expect(tableEditor.getScreenRow(4)).toEqual(['row5', 500, 'no'])
expect(tableEditor.getScreenRow(5)).toEqual(['row4', 400, 'yes'])
it 'updates the selections', ->
tableEditor.moveLineUp()
expect(tableEditor.getSelectedRanges()).toEqual([
[[0,0],[1,1]]
[[2,0],[3,1]]
[[4,0],[5,1]]
])
it 'can undo the cursors moves', ->
tableEditor.moveLineUp()
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
describe 'when there is an order defined', ->
beforeEach ->
tableEditor.sortBy('key')
it 'does nothing and creates a notification instead', ->
spyOn(atom.notifications, 'addWarning')
tableEditor.moveLineUp()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
expect(atom.notifications.addWarning).toHaveBeenCalled()
describe '::moveColumnLeft', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.setCursorAtPosition([1,1])
tableEditor.addCursorAtPosition([3,2])
table.clearUndoStack()
it 'moves the column to the left', ->
tableEditor.moveColumnLeft()
expect(tableEditor.getScreenColumn(0).name).toEqual('value')
expect(tableEditor.getScreenColumn(1).name).toEqual('foo')
expect(tableEditor.getScreenColumn(2).name).toEqual('key')
it 'updates the selections', ->
tableEditor.moveColumnLeft()
expect(tableEditor.getSelectedRanges()).toEqual([
[[1,0],[2,1]]
[[3,1],[4,2]]
])
it 'can undo the cursors moves', ->
tableEditor.moveColumnLeft()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,1]
])
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,1]
[3,2]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,1]
])
describe '::moveColumnRight', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.setCursorAtPosition([1,0])
tableEditor.addCursorAtPosition([3,1])
table.clearUndoStack()
it 'moves the column to the right', ->
tableEditor.moveColumnRight()
expect(tableEditor.getScreenColumn(0).name).toEqual('foo')
expect(tableEditor.getScreenColumn(1).name).toEqual('key')
expect(tableEditor.getScreenColumn(2).name).toEqual('value')
it 'updates the selections', ->
tableEditor.moveColumnRight()
expect(tableEditor.getSelectedRanges()).toEqual([
[[1,1],[2,2]]
[[3,2],[4,3]]
])
it 'can undo the cursors moves', ->
tableEditor.moveColumnRight()
expect(tableEditor.getCursorPositions()).toEqual([
[1,1]
[3,2]
])
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,1]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,1]
[3,2]
])
## ###### ######## ## ######## ###### ######## ######
## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ##
## ###### ###### ## ###### ## ## ######
## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ##
## ###### ######## ######## ######## ###### ## ######
describe '::setSelectedRange', ->
it 'sets the selection range', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
expect(tableEditor.getSelectedRange()).toEqual([[0,0], [2,2]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]]])
describe 'when there is many selections', ->
it 'merges every selections into a single one', ->
tableEditor.addCursorAtScreenPosition([2,1])
tableEditor.setSelectedRange([[0,0], [2,2]])
expect(tableEditor.getSelectedRange()).toEqual([[0,0], [2,2]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]]])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursors().length).toEqual(1)
describe '::setSelectedRanges', ->
it 'throws an error if called without argument', ->
expect(-> tableEditor.setSelectedRanges()).toThrow()
it 'throws an error if called with an empty array', ->
expect(-> tableEditor.setSelectedRanges([])).toThrow()
it 'creates new selections based on the passed-in ranges', ->
tableEditor.setSelectedRanges([[[0,0], [2,2]], [[2,2],[3,3]]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]], [[2,2],[3,3]]])
expect(tableEditor.getSelections().length).toEqual(2)
expect(tableEditor.getCursors().length).toEqual(2)
it 'destroys selection when there is less ranges', ->
tableEditor.setSelectedRanges([[[0,0], [2,2]], [[2,2],[3,3]]])
tableEditor.setSelectedRanges([[[1,1], [2,2]]])
expect(tableEditor.getSelectedRanges()).toEqual([[[1,1], [2,2]]])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursors().length).toEqual(1)
describe 'when defining a selection contained in another one', ->
it 'merges the selections', ->
tableEditor.setSelectedRanges([[[0,0], [2,2]], [[1,1],[2,2]]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]]])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursors().length).toEqual(1)
## ###### ####### ######## ## ##
## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ####
## ## ## ## ######## ##
## ## ## ## ## ##
## ## ## ## ## ## ##
## ###### ####### ## ##
describe '::copySelectedCells', ->
it "copies the selected cell value onto the clipboard", ->
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age')
expect(atom.clipboard.readWithMetadata().text).toEqual('age')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age']]])
it 'copies the selected cell values onto the clipboard', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age',30], ['gender','female']]])
it 'copies each selections as metadata', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
clipboard = atom.clipboard.readWithMetadata()
metadata = clipboard.metadata
selections = metadata.selections
expect(clipboard.text).toEqual('age\t30\ngender\tfemale')
expect(metadata.values).toEqual([
[['age',30]]
[['gender','female']]
])
expect(selections).toBeDefined()
expect(selections.length).toEqual(2)
expect(selections[0].text).toEqual('age\t30')
expect(selections[1].text).toEqual('gender\tfemale')
describe 'when the treatEachCellAsASelectionWhenPastingToATextBuffer setting is enabled', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.treatEachCellAsASelectionWhenPastingToABuffer', true
it 'copies each cells as a buffer selection', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
clipboard = atom.clipboard.readWithMetadata()
metadata = clipboard.metadata
selections = metadata.selections
expect(clipboard.text).toEqual('age\t30\ngender\tfemale')
expect(metadata.values).toEqual([
[['age',30]]
[['gender','female']]
])
expect(selections).toBeDefined()
expect(selections.length).toEqual(4)
expect(selections[0].text).toEqual('age')
expect(selections[1].text).toEqual(30)
expect(selections[2].text).toEqual('gender')
expect(selections[3].text).toEqual('female')
## ###### ## ## ########
## ## ## ## ## ##
## ## ## ## ##
## ## ## ## ##
## ## ## ## ##
## ## ## ## ## ##
## ###### ####### ##
describe '::cutSelectedCells', ->
it "cuts the selected cell value onto the clipboard", ->
tableEditor.cutSelectedCells()
expect(atom.clipboard.read()).toEqual('age')
expect(atom.clipboard.readWithMetadata().text).toEqual('age')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age']]])
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual(undefined)
it 'cuts the selected cell values onto the clipboard', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.cutSelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age',30], ['gender','female']]])
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual(undefined)
it 'cuts each selections as metadata', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
tableEditor.cutSelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
clipboard = atom.clipboard.readWithMetadata()
metadata = clipboard.metadata
selections = metadata.selections
expect(clipboard.text).toEqual('age\t30\ngender\tfemale')
expect(metadata.values).toEqual([
[['age',30]]
[['gender','female']]
])
expect(selections).toBeDefined()
expect(selections.length).toEqual(2)
expect(selections[0].text).toEqual('age\t30')
expect(selections[1].text).toEqual('gender\tfemale')
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual(undefined)
## ######## ### ###### ######## ########
## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ##
## ######## ## ## ###### ## ######
## ## ######### ## ## ##
## ## ## ## ## ## ## ##
## ## ## ## ###### ## ########
describe '::pasteClipboard', ->
describe 'when the clipboard only has a text', ->
beforeEach ->
atom.clipboard.write('foo')
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getCursorValue()).toEqual('foo')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
describe 'when there is many selections', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'when the clipboard comes from a text buffer', ->
describe 'and has only one selection', ->
beforeEach ->
atom.clipboard.write('foo', {indentBasis: 0, fullLine: false})
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getCursorValue()).toEqual('foo')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
describe 'when there is many selections', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'and has many selections', ->
describe 'that span one cell', ->
it 'pastes each selection in the corresponding cells', ->
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
tableEditor.setSelectedRanges([[[0,0],[1,1]], [[1,0],[2,1]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
describe 'when flattenBufferMultiSelectionOnPaste option is enabled', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.flattenBufferMultiSelectionOnPaste', true
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getCursorValue()).toEqual('foo\nbar')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo\nbar')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo\nbar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo\nbar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo\nbar')
describe 'when distributeBufferMultiSelectionOnPaste option is set to vertical', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.distributeBufferMultiSelectionOnPaste', 'vertically'
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
describe 'when distributeBufferMultiSelectionOnPaste option is set to horizontal', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.distributeBufferMultiSelectionOnPaste', 'horizontally'
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
describe 'when the clipboard comes from a table', ->
describe 'and has only one selection', ->
beforeEach ->
atom.clipboard.write('foo\nbar', {
values: [[['foo','bar']]]
text: 'foo\tbar'
indentBasis: 0
fullLine: false
})
describe 'when the selection spans only one cell', ->
it 'expands the selection to match the clipboard content', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getSelectedRange()).toEqual([[0,0],[1,2]])
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
describe 'when there is many selections', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'and has many selections', ->
beforeEach ->
atom.clipboard.write('foo\nbar', {
values: [
[['foo', 'oof']]
[['bar', 'rab']]
]
selections: [
{
indentBasis: 0
fullLine: false
text: 'foo\toof'
}
{
indentBasis: 0
fullLine: false
text: 'bar\trab'
}
]
})
describe 'when the selection spans only one cell', ->
it 'pastes only the first selection and expands the table selection', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
describe 'when the selection spans many cells', ->
it 'pastes only the first selection', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('oof')
describe 'when there is many selections', ->
it 'paste each clipboard selection in the corresponding table selection', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('rab')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'when there is more selections in the table', ->
it 'loops over the clipboard selection when needed', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]], [[2,0],[3,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('rab')
expect(tableEditor.getValueAtScreenPosition([2,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([2,1])).toEqual('oof')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
expect(tableEditor.getValueAtScreenPosition([2,0])).toEqual('name')
expect(tableEditor.getValueAtScreenPosition([2,1])).toEqual('Jane Doe')
| 35724 | require './helpers/spec-helper'
TableEditor = require '../lib/table-editor'
Table = require '../lib/table'
describe 'TableEditor', ->
[table, displayTable, tableEditor] = []
beforeEach ->
atom.config.set 'tablr.tableEditor.columnWidth', 100
atom.config.set 'tablr.minimuColumnWidth', 10
atom.config.set 'tablr.tableEditor.rowHeight', 20
atom.config.set 'tablr.tableEditor.minimumRowHeight', 10
describe 'when initialized without a table', ->
beforeEach ->
tableEditor = new TableEditor
{table, displayTable} = tableEditor
it 'creates an empty table and its displayTable', ->
expect(table).toBeDefined()
expect(displayTable).toBeDefined()
it 'retains the table', ->
expect(table.isRetained()).toBeTruthy()
it 'has a default empty selection', ->
expect(tableEditor.getLastSelection()).toBeDefined()
expect(tableEditor.getSelections()).toEqual([tableEditor.getLastSelection()])
expect(tableEditor.getLastSelection().getRange()).toEqual([[0,0],[0,0]])
expect(tableEditor.getLastSelection().getCursor()).toEqual(tableEditor.getLastCursor())
it 'has a default cursor position', ->
expect(tableEditor.getCursorPosition()).toEqual([0,0])
expect(tableEditor.getCursorPositions()).toEqual([[0,0]])
expect(tableEditor.getCursorScreenPosition()).toEqual([0,0])
expect(tableEditor.getCursorScreenPositions()).toEqual([[0,0]])
it 'returns undefined when asked for the value at cursor', ->
expect(tableEditor.getCursorValue()).toBeUndefined()
expect(tableEditor.getCursorValues()).toEqual([undefined])
describe 'when initialized with a table', ->
beforeEach ->
table = new Table
table.addColumn 'key'
table.addColumn 'value'
table.addRow ['name', '<NAME>']
table.addRow ['age', 30]
table.addRow ['gender', 'female']
tableEditor = new TableEditor({table})
{displayTable} = tableEditor
displayTable.sortBy('key')
it 'uses the passed-in table', ->
expect(displayTable).toBeDefined()
expect(displayTable.table).toBe(table)
expect(tableEditor.table).toBe(table)
it 'retains the table', ->
expect(table.isRetained()).toBeTruthy()
it 'has a default empty selection', ->
expect(tableEditor.getLastSelection()).toBeDefined()
expect(tableEditor.getSelections()).toEqual([tableEditor.getLastSelection()])
expect(tableEditor.getLastSelection().getRange()).toEqual([[0,0],[1,1]])
expect(tableEditor.getLastSelection().getCursor()).toEqual(tableEditor.getLastCursor())
it 'has a default cursor position', ->
expect(tableEditor.getCursorPosition()).toEqual([1,0])
expect(tableEditor.getCursorPositions()).toEqual([[1,0]])
expect(tableEditor.getCursorScreenPosition()).toEqual([0,0])
expect(tableEditor.getCursorScreenPositions()).toEqual([[0,0]])
it 'returns the value at cursor', ->
expect(tableEditor.getCursorValue()).toEqual('age')
expect(tableEditor.getCursorValues()).toEqual(['age'])
describe '::delete', ->
it 'deletes the content of the selected cells', ->
initialValue = tableEditor.getCursorValue()
expect(initialValue).not.toBeUndefined()
tableEditor.delete()
expect(tableEditor.getCursorValue()).toBeUndefined()
tableEditor.undo()
expect(tableEditor.getCursorValue()).toEqual(initialValue)
tableEditor.redo()
expect(tableEditor.getCursorValue()).toBeUndefined()
describe 'when destroyed', ->
beforeEach ->
tableEditor.destroy()
it 'destroys its table and display table', ->
expect(table.isDestroyed()).toBeTruthy()
expect(displayTable.isDestroyed()).toBeTruthy()
it 'is destroyed', ->
expect(tableEditor.isDestroyed()).toBeTruthy()
it 'removes its cursors and selections', ->
expect(tableEditor.getCursors().length).toEqual(0)
expect(tableEditor.getSelections().length).toEqual(0)
## ######## ######## ###### ######## ####### ######## ########
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ##
## ######## ###### ###### ## ## ## ######## ######
## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ######## ###### ## ####### ## ## ########
describe '::serialize', ->
it 'serializes the table editor', ->
expect(tableEditor.serialize()).toEqual({
deserializer: 'TableEditor'
displayTable: tableEditor.displayTable.serialize()
cursors: tableEditor.getCursors().map (cursor) -> cursor.serialize()
selections: tableEditor.getSelections().map (sel) -> sel.serialize()
})
describe '.deserialize', ->
it 'restores a table editor', ->
tableEditor = atom.deserializers.deserialize({
deserializer: 'TableEditor'
displayTable:
deserializer: 'DisplayTable'
rowHeights: [null,null,null,null]
table:
deserializer: 'Table'
modified: true
cachedContents: undefined
columns: [null,null,null]
rows: [
["name","age","gender"]
["<NAME>","32","female"]
["<NAME>","30","male"]
[null,null,null]
]
id: 1
cursors: [[2,2]]
selections: [[[2,2],[3,4]]]
})
expect(tableEditor.isModified()).toBeTruthy()
expect(tableEditor.getScreenRows()).toEqual([
["name","age","gender"]
["<NAME>","32","female"]
["<NAME>","30","male"]
[null,null,null]
])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getSelectedRange()).toEqual([[2,2],[3,4]])
expect(tableEditor.getCursorPosition()).toEqual([2,2])
## ###### ## ## ######## ###### ####### ######## ######
## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ######## ###### ## ## ######## ######
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ###### ####### ## ## ###### ####### ## ## ######
describe 'for an empty table', ->
describe 'adding a column and a row', ->
it 'set the cursor position to 0,0', ->
table = new Table
tableEditor = new TableEditor({table})
tableEditor.initializeAfterSetup()
tableEditor.insertColumnAfter()
tableEditor.insertRowAfter()
expect(tableEditor.getCursorPosition()).toEqual([0,0])
describe '::addCursorAtScreenPosition', ->
it 'adds a cursor', ->
tableEditor.addCursorAtScreenPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getSelections().length).toEqual(2)
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtScreenPosition([0,0])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
it 'dispatch a did-add-cursor event', ->
spy = jasmine.createSpy('did-add-cursor')
tableEditor.onDidAddCursor(spy)
tableEditor.addCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'dispatch a did-add-selection event', ->
spy = jasmine.createSpy('did-add-selection')
tableEditor.onDidAddSelection(spy)
tableEditor.addCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
describe '::addCursorAtPosition', ->
it 'adds a cursor', ->
tableEditor.addCursorAtPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getSelections().length).toEqual(2)
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtPosition([1,0])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
it 'dispatch a did-add-cursor event', ->
spy = jasmine.createSpy('did-add-cursor')
tableEditor.onDidAddCursor(spy)
tableEditor.addCursorAtPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'dispatch a did-add-selection event', ->
spy = jasmine.createSpy('did-add-selection')
tableEditor.onDidAddSelection(spy)
tableEditor.addCursorAtPosition([1,1])
expect(spy).toHaveBeenCalled()
describe '::addCursorBelowLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorBelowLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([5,2])
describe '::addCursorAboveLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorAboveLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([2,2])
describe '::addCursorLeftToLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorLeftToLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([3,1])
describe '::addCursorRightToLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorRightToLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([3,4])
describe '::setCursorAtScreenPosition', ->
it 'sets the cursor position', ->
tableEditor.setCursorAtScreenPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
it 'dispatch a did-change-cursor-position event', ->
spy = jasmine.createSpy('did-change-cursor-position')
tableEditor.onDidChangeCursorPosition(spy)
tableEditor.setCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'dispatch a did-change-selection-range event', ->
spy = jasmine.createSpy('did-change-selection-range')
tableEditor.onDidChangeSelectionRange(spy)
tableEditor.setCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtScreenPosition([2,1])
tableEditor.addCursorAtScreenPosition([1,2])
tableEditor.setCursorAtScreenPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
describe '::setCursorAtPosition', ->
it 'sets the cursor position', ->
tableEditor.setCursorAtPosition([2,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtScreenPosition([2,1])
tableEditor.addCursorAtScreenPosition([1,2])
tableEditor.setCursorAtPosition([2,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
describe '::moveLineDown', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.addCursorAtPosition([2,0])
tableEditor.addCursorAtPosition([4,0])
table.clearUndoStack()
it 'moves the lines at cursors one line down', ->
tableEditor.moveLineDown()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
expect(tableEditor.getScreenRow(0)).toEqual(['row1', 100, 'no'])
expect(tableEditor.getScreenRow(1)).toEqual(['row0', 0, 'yes'])
expect(tableEditor.getScreenRow(2)).toEqual(['row3', 300, 'no'])
expect(tableEditor.getScreenRow(3)).toEqual(['row2', 200, 'yes'])
expect(tableEditor.getScreenRow(4)).toEqual(['row5', 500, 'no'])
expect(tableEditor.getScreenRow(5)).toEqual(['row4', 400, 'yes'])
it 'updates the selections', ->
tableEditor.moveLineDown()
expect(tableEditor.getSelectedRanges()).toEqual([
[[1,0],[2,1]]
[[3,0],[4,1]]
[[5,0],[6,1]]
])
it 'can undo the cursors moves', ->
tableEditor.moveLineDown()
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
describe 'when there is an order defined', ->
beforeEach ->
tableEditor.sortBy('key')
it 'does nothing and creates a notification instead', ->
spyOn(atom.notifications, 'addWarning')
tableEditor.moveLineDown()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
expect(atom.notifications.addWarning).toHaveBeenCalled()
describe '::moveLineUp', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.setCursorAtPosition([1,0])
tableEditor.addCursorAtPosition([3,0])
tableEditor.addCursorAtPosition([5,0])
table.clearUndoStack()
it 'moves the lines at cursors one line up', ->
tableEditor.moveLineUp()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
expect(tableEditor.getScreenRow(0)).toEqual(['row1', 100, 'no'])
expect(tableEditor.getScreenRow(1)).toEqual(['row0', 0, 'yes'])
expect(tableEditor.getScreenRow(2)).toEqual(['row3', 300, 'no'])
expect(tableEditor.getScreenRow(3)).toEqual(['row2', 200, 'yes'])
expect(tableEditor.getScreenRow(4)).toEqual(['row5', 500, 'no'])
expect(tableEditor.getScreenRow(5)).toEqual(['row4', 400, 'yes'])
it 'updates the selections', ->
tableEditor.moveLineUp()
expect(tableEditor.getSelectedRanges()).toEqual([
[[0,0],[1,1]]
[[2,0],[3,1]]
[[4,0],[5,1]]
])
it 'can undo the cursors moves', ->
tableEditor.moveLineUp()
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
describe 'when there is an order defined', ->
beforeEach ->
tableEditor.sortBy('key')
it 'does nothing and creates a notification instead', ->
spyOn(atom.notifications, 'addWarning')
tableEditor.moveLineUp()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
expect(atom.notifications.addWarning).toHaveBeenCalled()
describe '::moveColumnLeft', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.setCursorAtPosition([1,1])
tableEditor.addCursorAtPosition([3,2])
table.clearUndoStack()
it 'moves the column to the left', ->
tableEditor.moveColumnLeft()
expect(tableEditor.getScreenColumn(0).name).toEqual('value')
expect(tableEditor.getScreenColumn(1).name).toEqual('foo')
expect(tableEditor.getScreenColumn(2).name).toEqual('key')
it 'updates the selections', ->
tableEditor.moveColumnLeft()
expect(tableEditor.getSelectedRanges()).toEqual([
[[1,0],[2,1]]
[[3,1],[4,2]]
])
it 'can undo the cursors moves', ->
tableEditor.moveColumnLeft()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,1]
])
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,1]
[3,2]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,1]
])
describe '::moveColumnRight', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.setCursorAtPosition([1,0])
tableEditor.addCursorAtPosition([3,1])
table.clearUndoStack()
it 'moves the column to the right', ->
tableEditor.moveColumnRight()
expect(tableEditor.getScreenColumn(0).name).toEqual('foo')
expect(tableEditor.getScreenColumn(1).name).toEqual('key')
expect(tableEditor.getScreenColumn(2).name).toEqual('value')
it 'updates the selections', ->
tableEditor.moveColumnRight()
expect(tableEditor.getSelectedRanges()).toEqual([
[[1,1],[2,2]]
[[3,2],[4,3]]
])
it 'can undo the cursors moves', ->
tableEditor.moveColumnRight()
expect(tableEditor.getCursorPositions()).toEqual([
[1,1]
[3,2]
])
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,1]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,1]
[3,2]
])
## ###### ######## ## ######## ###### ######## ######
## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ##
## ###### ###### ## ###### ## ## ######
## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ##
## ###### ######## ######## ######## ###### ## ######
describe '::setSelectedRange', ->
it 'sets the selection range', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
expect(tableEditor.getSelectedRange()).toEqual([[0,0], [2,2]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]]])
describe 'when there is many selections', ->
it 'merges every selections into a single one', ->
tableEditor.addCursorAtScreenPosition([2,1])
tableEditor.setSelectedRange([[0,0], [2,2]])
expect(tableEditor.getSelectedRange()).toEqual([[0,0], [2,2]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]]])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursors().length).toEqual(1)
describe '::setSelectedRanges', ->
it 'throws an error if called without argument', ->
expect(-> tableEditor.setSelectedRanges()).toThrow()
it 'throws an error if called with an empty array', ->
expect(-> tableEditor.setSelectedRanges([])).toThrow()
it 'creates new selections based on the passed-in ranges', ->
tableEditor.setSelectedRanges([[[0,0], [2,2]], [[2,2],[3,3]]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]], [[2,2],[3,3]]])
expect(tableEditor.getSelections().length).toEqual(2)
expect(tableEditor.getCursors().length).toEqual(2)
it 'destroys selection when there is less ranges', ->
tableEditor.setSelectedRanges([[[0,0], [2,2]], [[2,2],[3,3]]])
tableEditor.setSelectedRanges([[[1,1], [2,2]]])
expect(tableEditor.getSelectedRanges()).toEqual([[[1,1], [2,2]]])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursors().length).toEqual(1)
describe 'when defining a selection contained in another one', ->
it 'merges the selections', ->
tableEditor.setSelectedRanges([[[0,0], [2,2]], [[1,1],[2,2]]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]]])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursors().length).toEqual(1)
## ###### ####### ######## ## ##
## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ####
## ## ## ## ######## ##
## ## ## ## ## ##
## ## ## ## ## ## ##
## ###### ####### ## ##
describe '::copySelectedCells', ->
it "copies the selected cell value onto the clipboard", ->
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age')
expect(atom.clipboard.readWithMetadata().text).toEqual('age')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age']]])
it 'copies the selected cell values onto the clipboard', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age',30], ['gender','female']]])
it 'copies each selections as metadata', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
clipboard = atom.clipboard.readWithMetadata()
metadata = clipboard.metadata
selections = metadata.selections
expect(clipboard.text).toEqual('age\t30\ngender\tfemale')
expect(metadata.values).toEqual([
[['age',30]]
[['gender','female']]
])
expect(selections).toBeDefined()
expect(selections.length).toEqual(2)
expect(selections[0].text).toEqual('age\t30')
expect(selections[1].text).toEqual('gender\tfemale')
describe 'when the treatEachCellAsASelectionWhenPastingToATextBuffer setting is enabled', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.treatEachCellAsASelectionWhenPastingToABuffer', true
it 'copies each cells as a buffer selection', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
clipboard = atom.clipboard.readWithMetadata()
metadata = clipboard.metadata
selections = metadata.selections
expect(clipboard.text).toEqual('age\t30\ngender\tfemale')
expect(metadata.values).toEqual([
[['age',30]]
[['gender','female']]
])
expect(selections).toBeDefined()
expect(selections.length).toEqual(4)
expect(selections[0].text).toEqual('age')
expect(selections[1].text).toEqual(30)
expect(selections[2].text).toEqual('gender')
expect(selections[3].text).toEqual('female')
## ###### ## ## ########
## ## ## ## ## ##
## ## ## ## ##
## ## ## ## ##
## ## ## ## ##
## ## ## ## ## ##
## ###### ####### ##
describe '::cutSelectedCells', ->
it "cuts the selected cell value onto the clipboard", ->
tableEditor.cutSelectedCells()
expect(atom.clipboard.read()).toEqual('age')
expect(atom.clipboard.readWithMetadata().text).toEqual('age')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age']]])
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual(undefined)
it 'cuts the selected cell values onto the clipboard', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.cutSelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age',30], ['gender','female']]])
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual(undefined)
it 'cuts each selections as metadata', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
tableEditor.cutSelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
clipboard = atom.clipboard.readWithMetadata()
metadata = clipboard.metadata
selections = metadata.selections
expect(clipboard.text).toEqual('age\t30\ngender\tfemale')
expect(metadata.values).toEqual([
[['age',30]]
[['gender','female']]
])
expect(selections).toBeDefined()
expect(selections.length).toEqual(2)
expect(selections[0].text).toEqual('age\t30')
expect(selections[1].text).toEqual('gender\tfemale')
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual(undefined)
## ######## ### ###### ######## ########
## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ##
## ######## ## ## ###### ## ######
## ## ######### ## ## ##
## ## ## ## ## ## ## ##
## ## ## ## ###### ## ########
describe '::pasteClipboard', ->
describe 'when the clipboard only has a text', ->
beforeEach ->
atom.clipboard.write('foo')
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getCursorValue()).toEqual('foo')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
describe 'when there is many selections', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'when the clipboard comes from a text buffer', ->
describe 'and has only one selection', ->
beforeEach ->
atom.clipboard.write('foo', {indentBasis: 0, fullLine: false})
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getCursorValue()).toEqual('foo')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
describe 'when there is many selections', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'and has many selections', ->
describe 'that span one cell', ->
it 'pastes each selection in the corresponding cells', ->
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
tableEditor.setSelectedRanges([[[0,0],[1,1]], [[1,0],[2,1]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
describe 'when flattenBufferMultiSelectionOnPaste option is enabled', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.flattenBufferMultiSelectionOnPaste', true
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getCursorValue()).toEqual('foo\nbar')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo\nbar')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo\nbar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo\nbar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo\nbar')
describe 'when distributeBufferMultiSelectionOnPaste option is set to vertical', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.distributeBufferMultiSelectionOnPaste', 'vertically'
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
describe 'when distributeBufferMultiSelectionOnPaste option is set to horizontal', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.distributeBufferMultiSelectionOnPaste', 'horizontally'
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
describe 'when the clipboard comes from a table', ->
describe 'and has only one selection', ->
beforeEach ->
atom.clipboard.write('foo\nbar', {
values: [[['foo','bar']]]
text: 'foo\tbar'
indentBasis: 0
fullLine: false
})
describe 'when the selection spans only one cell', ->
it 'expands the selection to match the clipboard content', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getSelectedRange()).toEqual([[0,0],[1,2]])
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
describe 'when there is many selections', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'and has many selections', ->
beforeEach ->
atom.clipboard.write('foo\nbar', {
values: [
[['foo', 'oof']]
[['bar', 'rab']]
]
selections: [
{
indentBasis: 0
fullLine: false
text: 'foo\toof'
}
{
indentBasis: 0
fullLine: false
text: 'bar\trab'
}
]
})
describe 'when the selection spans only one cell', ->
it 'pastes only the first selection and expands the table selection', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
describe 'when the selection spans many cells', ->
it 'pastes only the first selection', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('oof')
describe 'when there is many selections', ->
it 'paste each clipboard selection in the corresponding table selection', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('rab')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'when there is more selections in the table', ->
it 'loops over the clipboard selection when needed', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]], [[2,0],[3,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('rab')
expect(tableEditor.getValueAtScreenPosition([2,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([2,1])).toEqual('oof')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
expect(tableEditor.getValueAtScreenPosition([2,0])).toEqual('name')
expect(tableEditor.getValueAtScreenPosition([2,1])).toEqual('<NAME>')
| true | require './helpers/spec-helper'
TableEditor = require '../lib/table-editor'
Table = require '../lib/table'
describe 'TableEditor', ->
[table, displayTable, tableEditor] = []
beforeEach ->
atom.config.set 'tablr.tableEditor.columnWidth', 100
atom.config.set 'tablr.minimuColumnWidth', 10
atom.config.set 'tablr.tableEditor.rowHeight', 20
atom.config.set 'tablr.tableEditor.minimumRowHeight', 10
describe 'when initialized without a table', ->
beforeEach ->
tableEditor = new TableEditor
{table, displayTable} = tableEditor
it 'creates an empty table and its displayTable', ->
expect(table).toBeDefined()
expect(displayTable).toBeDefined()
it 'retains the table', ->
expect(table.isRetained()).toBeTruthy()
it 'has a default empty selection', ->
expect(tableEditor.getLastSelection()).toBeDefined()
expect(tableEditor.getSelections()).toEqual([tableEditor.getLastSelection()])
expect(tableEditor.getLastSelection().getRange()).toEqual([[0,0],[0,0]])
expect(tableEditor.getLastSelection().getCursor()).toEqual(tableEditor.getLastCursor())
it 'has a default cursor position', ->
expect(tableEditor.getCursorPosition()).toEqual([0,0])
expect(tableEditor.getCursorPositions()).toEqual([[0,0]])
expect(tableEditor.getCursorScreenPosition()).toEqual([0,0])
expect(tableEditor.getCursorScreenPositions()).toEqual([[0,0]])
it 'returns undefined when asked for the value at cursor', ->
expect(tableEditor.getCursorValue()).toBeUndefined()
expect(tableEditor.getCursorValues()).toEqual([undefined])
describe 'when initialized with a table', ->
beforeEach ->
table = new Table
table.addColumn 'key'
table.addColumn 'value'
table.addRow ['name', 'PI:NAME:<NAME>END_PI']
table.addRow ['age', 30]
table.addRow ['gender', 'female']
tableEditor = new TableEditor({table})
{displayTable} = tableEditor
displayTable.sortBy('key')
it 'uses the passed-in table', ->
expect(displayTable).toBeDefined()
expect(displayTable.table).toBe(table)
expect(tableEditor.table).toBe(table)
it 'retains the table', ->
expect(table.isRetained()).toBeTruthy()
it 'has a default empty selection', ->
expect(tableEditor.getLastSelection()).toBeDefined()
expect(tableEditor.getSelections()).toEqual([tableEditor.getLastSelection()])
expect(tableEditor.getLastSelection().getRange()).toEqual([[0,0],[1,1]])
expect(tableEditor.getLastSelection().getCursor()).toEqual(tableEditor.getLastCursor())
it 'has a default cursor position', ->
expect(tableEditor.getCursorPosition()).toEqual([1,0])
expect(tableEditor.getCursorPositions()).toEqual([[1,0]])
expect(tableEditor.getCursorScreenPosition()).toEqual([0,0])
expect(tableEditor.getCursorScreenPositions()).toEqual([[0,0]])
it 'returns the value at cursor', ->
expect(tableEditor.getCursorValue()).toEqual('age')
expect(tableEditor.getCursorValues()).toEqual(['age'])
describe '::delete', ->
it 'deletes the content of the selected cells', ->
initialValue = tableEditor.getCursorValue()
expect(initialValue).not.toBeUndefined()
tableEditor.delete()
expect(tableEditor.getCursorValue()).toBeUndefined()
tableEditor.undo()
expect(tableEditor.getCursorValue()).toEqual(initialValue)
tableEditor.redo()
expect(tableEditor.getCursorValue()).toBeUndefined()
describe 'when destroyed', ->
beforeEach ->
tableEditor.destroy()
it 'destroys its table and display table', ->
expect(table.isDestroyed()).toBeTruthy()
expect(displayTable.isDestroyed()).toBeTruthy()
it 'is destroyed', ->
expect(tableEditor.isDestroyed()).toBeTruthy()
it 'removes its cursors and selections', ->
expect(tableEditor.getCursors().length).toEqual(0)
expect(tableEditor.getSelections().length).toEqual(0)
## ######## ######## ###### ######## ####### ######## ########
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ##
## ######## ###### ###### ## ## ## ######## ######
## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ######## ###### ## ####### ## ## ########
describe '::serialize', ->
it 'serializes the table editor', ->
expect(tableEditor.serialize()).toEqual({
deserializer: 'TableEditor'
displayTable: tableEditor.displayTable.serialize()
cursors: tableEditor.getCursors().map (cursor) -> cursor.serialize()
selections: tableEditor.getSelections().map (sel) -> sel.serialize()
})
describe '.deserialize', ->
it 'restores a table editor', ->
tableEditor = atom.deserializers.deserialize({
deserializer: 'TableEditor'
displayTable:
deserializer: 'DisplayTable'
rowHeights: [null,null,null,null]
table:
deserializer: 'Table'
modified: true
cachedContents: undefined
columns: [null,null,null]
rows: [
["name","age","gender"]
["PI:NAME:<NAME>END_PI","32","female"]
["PI:NAME:<NAME>END_PI","30","male"]
[null,null,null]
]
id: 1
cursors: [[2,2]]
selections: [[[2,2],[3,4]]]
})
expect(tableEditor.isModified()).toBeTruthy()
expect(tableEditor.getScreenRows()).toEqual([
["name","age","gender"]
["PI:NAME:<NAME>END_PI","32","female"]
["PI:NAME:<NAME>END_PI","30","male"]
[null,null,null]
])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getSelectedRange()).toEqual([[2,2],[3,4]])
expect(tableEditor.getCursorPosition()).toEqual([2,2])
## ###### ## ## ######## ###### ####### ######## ######
## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ######## ###### ## ## ######## ######
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ###### ####### ## ## ###### ####### ## ## ######
describe 'for an empty table', ->
describe 'adding a column and a row', ->
it 'set the cursor position to 0,0', ->
table = new Table
tableEditor = new TableEditor({table})
tableEditor.initializeAfterSetup()
tableEditor.insertColumnAfter()
tableEditor.insertRowAfter()
expect(tableEditor.getCursorPosition()).toEqual([0,0])
describe '::addCursorAtScreenPosition', ->
it 'adds a cursor', ->
tableEditor.addCursorAtScreenPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getSelections().length).toEqual(2)
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtScreenPosition([0,0])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
it 'dispatch a did-add-cursor event', ->
spy = jasmine.createSpy('did-add-cursor')
tableEditor.onDidAddCursor(spy)
tableEditor.addCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'dispatch a did-add-selection event', ->
spy = jasmine.createSpy('did-add-selection')
tableEditor.onDidAddSelection(spy)
tableEditor.addCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
describe '::addCursorAtPosition', ->
it 'adds a cursor', ->
tableEditor.addCursorAtPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getSelections().length).toEqual(2)
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtPosition([1,0])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
it 'dispatch a did-add-cursor event', ->
spy = jasmine.createSpy('did-add-cursor')
tableEditor.onDidAddCursor(spy)
tableEditor.addCursorAtPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'dispatch a did-add-selection event', ->
spy = jasmine.createSpy('did-add-selection')
tableEditor.onDidAddSelection(spy)
tableEditor.addCursorAtPosition([1,1])
expect(spy).toHaveBeenCalled()
describe '::addCursorBelowLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorBelowLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([5,2])
describe '::addCursorAboveLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorAboveLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([2,2])
describe '::addCursorLeftToLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorLeftToLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([3,1])
describe '::addCursorRightToLastSelection', ->
beforeEach ->
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addColumn()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.addRow()
tableEditor.setSelectedRange([
[3,2]
[5,4]
])
it 'creates a new cursor', ->
tableEditor.addCursorRightToLastSelection()
expect(tableEditor.getCursors().length).toEqual(2)
expect(tableEditor.getCursorScreenPosition()).toEqual([3,4])
describe '::setCursorAtScreenPosition', ->
it 'sets the cursor position', ->
tableEditor.setCursorAtScreenPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
it 'dispatch a did-change-cursor-position event', ->
spy = jasmine.createSpy('did-change-cursor-position')
tableEditor.onDidChangeCursorPosition(spy)
tableEditor.setCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'dispatch a did-change-selection-range event', ->
spy = jasmine.createSpy('did-change-selection-range')
tableEditor.onDidChangeSelectionRange(spy)
tableEditor.setCursorAtScreenPosition([1,1])
expect(spy).toHaveBeenCalled()
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtScreenPosition([2,1])
tableEditor.addCursorAtScreenPosition([1,2])
tableEditor.setCursorAtScreenPosition([1,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
describe '::setCursorAtPosition', ->
it 'sets the cursor position', ->
tableEditor.setCursorAtPosition([2,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
it 'removes the duplicates when the new cursor has the same position as a previous cursor', ->
tableEditor.addCursorAtScreenPosition([2,1])
tableEditor.addCursorAtScreenPosition([1,2])
tableEditor.setCursorAtPosition([2,1])
expect(tableEditor.getCursors().length).toEqual(1)
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursorScreenPosition()).toEqual([1,1])
expect(tableEditor.getCursorPosition()).toEqual([2,1])
describe '::moveLineDown', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.addCursorAtPosition([2,0])
tableEditor.addCursorAtPosition([4,0])
table.clearUndoStack()
it 'moves the lines at cursors one line down', ->
tableEditor.moveLineDown()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
expect(tableEditor.getScreenRow(0)).toEqual(['row1', 100, 'no'])
expect(tableEditor.getScreenRow(1)).toEqual(['row0', 0, 'yes'])
expect(tableEditor.getScreenRow(2)).toEqual(['row3', 300, 'no'])
expect(tableEditor.getScreenRow(3)).toEqual(['row2', 200, 'yes'])
expect(tableEditor.getScreenRow(4)).toEqual(['row5', 500, 'no'])
expect(tableEditor.getScreenRow(5)).toEqual(['row4', 400, 'yes'])
it 'updates the selections', ->
tableEditor.moveLineDown()
expect(tableEditor.getSelectedRanges()).toEqual([
[[1,0],[2,1]]
[[3,0],[4,1]]
[[5,0],[6,1]]
])
it 'can undo the cursors moves', ->
tableEditor.moveLineDown()
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
describe 'when there is an order defined', ->
beforeEach ->
tableEditor.sortBy('key')
it 'does nothing and creates a notification instead', ->
spyOn(atom.notifications, 'addWarning')
tableEditor.moveLineDown()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
expect(atom.notifications.addWarning).toHaveBeenCalled()
describe '::moveLineUp', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.setCursorAtPosition([1,0])
tableEditor.addCursorAtPosition([3,0])
tableEditor.addCursorAtPosition([5,0])
table.clearUndoStack()
it 'moves the lines at cursors one line up', ->
tableEditor.moveLineUp()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
expect(tableEditor.getScreenRow(0)).toEqual(['row1', 100, 'no'])
expect(tableEditor.getScreenRow(1)).toEqual(['row0', 0, 'yes'])
expect(tableEditor.getScreenRow(2)).toEqual(['row3', 300, 'no'])
expect(tableEditor.getScreenRow(3)).toEqual(['row2', 200, 'yes'])
expect(tableEditor.getScreenRow(4)).toEqual(['row5', 500, 'no'])
expect(tableEditor.getScreenRow(5)).toEqual(['row4', 400, 'yes'])
it 'updates the selections', ->
tableEditor.moveLineUp()
expect(tableEditor.getSelectedRanges()).toEqual([
[[0,0],[1,1]]
[[2,0],[3,1]]
[[4,0],[5,1]]
])
it 'can undo the cursors moves', ->
tableEditor.moveLineUp()
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[0,0]
[2,0]
[4,0]
])
describe 'when there is an order defined', ->
beforeEach ->
tableEditor.sortBy('key')
it 'does nothing and creates a notification instead', ->
spyOn(atom.notifications, 'addWarning')
tableEditor.moveLineUp()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,0]
[5,0]
])
expect(atom.notifications.addWarning).toHaveBeenCalled()
describe '::moveColumnLeft', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.setCursorAtPosition([1,1])
tableEditor.addCursorAtPosition([3,2])
table.clearUndoStack()
it 'moves the column to the left', ->
tableEditor.moveColumnLeft()
expect(tableEditor.getScreenColumn(0).name).toEqual('value')
expect(tableEditor.getScreenColumn(1).name).toEqual('foo')
expect(tableEditor.getScreenColumn(2).name).toEqual('key')
it 'updates the selections', ->
tableEditor.moveColumnLeft()
expect(tableEditor.getSelectedRanges()).toEqual([
[[1,0],[2,1]]
[[3,1],[4,2]]
])
it 'can undo the cursors moves', ->
tableEditor.moveColumnLeft()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,1]
])
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,1]
[3,2]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,1]
])
describe '::moveColumnRight', ->
beforeEach ->
tableEditor = new TableEditor
tableEditor.addColumn 'key'
tableEditor.addColumn 'value'
tableEditor.addColumn 'foo'
for i in [0...100]
tableEditor.addRow [
"row#{i}"
i * 100
if i % 2 is 0 then 'yes' else 'no'
]
tableEditor.setCursorAtPosition([1,0])
tableEditor.addCursorAtPosition([3,1])
table.clearUndoStack()
it 'moves the column to the right', ->
tableEditor.moveColumnRight()
expect(tableEditor.getScreenColumn(0).name).toEqual('foo')
expect(tableEditor.getScreenColumn(1).name).toEqual('key')
expect(tableEditor.getScreenColumn(2).name).toEqual('value')
it 'updates the selections', ->
tableEditor.moveColumnRight()
expect(tableEditor.getSelectedRanges()).toEqual([
[[1,1],[2,2]]
[[3,2],[4,3]]
])
it 'can undo the cursors moves', ->
tableEditor.moveColumnRight()
expect(tableEditor.getCursorPositions()).toEqual([
[1,1]
[3,2]
])
tableEditor.undo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,0]
[3,1]
])
tableEditor.redo()
expect(tableEditor.getCursorPositions()).toEqual([
[1,1]
[3,2]
])
## ###### ######## ## ######## ###### ######## ######
## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ##
## ###### ###### ## ###### ## ## ######
## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ##
## ###### ######## ######## ######## ###### ## ######
describe '::setSelectedRange', ->
it 'sets the selection range', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
expect(tableEditor.getSelectedRange()).toEqual([[0,0], [2,2]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]]])
describe 'when there is many selections', ->
it 'merges every selections into a single one', ->
tableEditor.addCursorAtScreenPosition([2,1])
tableEditor.setSelectedRange([[0,0], [2,2]])
expect(tableEditor.getSelectedRange()).toEqual([[0,0], [2,2]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]]])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursors().length).toEqual(1)
describe '::setSelectedRanges', ->
it 'throws an error if called without argument', ->
expect(-> tableEditor.setSelectedRanges()).toThrow()
it 'throws an error if called with an empty array', ->
expect(-> tableEditor.setSelectedRanges([])).toThrow()
it 'creates new selections based on the passed-in ranges', ->
tableEditor.setSelectedRanges([[[0,0], [2,2]], [[2,2],[3,3]]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]], [[2,2],[3,3]]])
expect(tableEditor.getSelections().length).toEqual(2)
expect(tableEditor.getCursors().length).toEqual(2)
it 'destroys selection when there is less ranges', ->
tableEditor.setSelectedRanges([[[0,0], [2,2]], [[2,2],[3,3]]])
tableEditor.setSelectedRanges([[[1,1], [2,2]]])
expect(tableEditor.getSelectedRanges()).toEqual([[[1,1], [2,2]]])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursors().length).toEqual(1)
describe 'when defining a selection contained in another one', ->
it 'merges the selections', ->
tableEditor.setSelectedRanges([[[0,0], [2,2]], [[1,1],[2,2]]])
expect(tableEditor.getSelectedRanges()).toEqual([[[0,0], [2,2]]])
expect(tableEditor.getSelections().length).toEqual(1)
expect(tableEditor.getCursors().length).toEqual(1)
## ###### ####### ######## ## ##
## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ####
## ## ## ## ######## ##
## ## ## ## ## ##
## ## ## ## ## ## ##
## ###### ####### ## ##
describe '::copySelectedCells', ->
it "copies the selected cell value onto the clipboard", ->
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age')
expect(atom.clipboard.readWithMetadata().text).toEqual('age')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age']]])
it 'copies the selected cell values onto the clipboard', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age',30], ['gender','female']]])
it 'copies each selections as metadata', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
clipboard = atom.clipboard.readWithMetadata()
metadata = clipboard.metadata
selections = metadata.selections
expect(clipboard.text).toEqual('age\t30\ngender\tfemale')
expect(metadata.values).toEqual([
[['age',30]]
[['gender','female']]
])
expect(selections).toBeDefined()
expect(selections.length).toEqual(2)
expect(selections[0].text).toEqual('age\t30')
expect(selections[1].text).toEqual('gender\tfemale')
describe 'when the treatEachCellAsASelectionWhenPastingToATextBuffer setting is enabled', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.treatEachCellAsASelectionWhenPastingToABuffer', true
it 'copies each cells as a buffer selection', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
tableEditor.copySelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
clipboard = atom.clipboard.readWithMetadata()
metadata = clipboard.metadata
selections = metadata.selections
expect(clipboard.text).toEqual('age\t30\ngender\tfemale')
expect(metadata.values).toEqual([
[['age',30]]
[['gender','female']]
])
expect(selections).toBeDefined()
expect(selections.length).toEqual(4)
expect(selections[0].text).toEqual('age')
expect(selections[1].text).toEqual(30)
expect(selections[2].text).toEqual('gender')
expect(selections[3].text).toEqual('female')
## ###### ## ## ########
## ## ## ## ## ##
## ## ## ## ##
## ## ## ## ##
## ## ## ## ##
## ## ## ## ## ##
## ###### ####### ##
describe '::cutSelectedCells', ->
it "cuts the selected cell value onto the clipboard", ->
tableEditor.cutSelectedCells()
expect(atom.clipboard.read()).toEqual('age')
expect(atom.clipboard.readWithMetadata().text).toEqual('age')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age']]])
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual(undefined)
it 'cuts the selected cell values onto the clipboard', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.cutSelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
expect(atom.clipboard.readWithMetadata().metadata).toEqual(fullLine: false, indentBasis: 0, values: [[['age',30], ['gender','female']]])
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual(undefined)
it 'cuts each selections as metadata', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
tableEditor.cutSelectedCells()
expect(atom.clipboard.read()).toEqual('age\t30\ngender\tfemale')
clipboard = atom.clipboard.readWithMetadata()
metadata = clipboard.metadata
selections = metadata.selections
expect(clipboard.text).toEqual('age\t30\ngender\tfemale')
expect(metadata.values).toEqual([
[['age',30]]
[['gender','female']]
])
expect(selections).toBeDefined()
expect(selections.length).toEqual(2)
expect(selections[0].text).toEqual('age\t30')
expect(selections[1].text).toEqual('gender\tfemale')
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual(undefined)
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual(undefined)
## ######## ### ###### ######## ########
## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ##
## ######## ## ## ###### ## ######
## ## ######### ## ## ##
## ## ## ## ## ## ## ##
## ## ## ## ###### ## ########
describe '::pasteClipboard', ->
describe 'when the clipboard only has a text', ->
beforeEach ->
atom.clipboard.write('foo')
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getCursorValue()).toEqual('foo')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
describe 'when there is many selections', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'when the clipboard comes from a text buffer', ->
describe 'and has only one selection', ->
beforeEach ->
atom.clipboard.write('foo', {indentBasis: 0, fullLine: false})
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getCursorValue()).toEqual('foo')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
describe 'when there is many selections', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'and has many selections', ->
describe 'that span one cell', ->
it 'pastes each selection in the corresponding cells', ->
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
tableEditor.setSelectedRanges([[[0,0],[1,1]], [[1,0],[2,1]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
describe 'when flattenBufferMultiSelectionOnPaste option is enabled', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.flattenBufferMultiSelectionOnPaste', true
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getCursorValue()).toEqual('foo\nbar')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo\nbar')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo\nbar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo\nbar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('foo\nbar')
describe 'when distributeBufferMultiSelectionOnPaste option is set to vertical', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.distributeBufferMultiSelectionOnPaste', 'vertically'
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
describe 'when distributeBufferMultiSelectionOnPaste option is set to horizontal', ->
beforeEach ->
atom.config.set 'tablr.copyPaste.distributeBufferMultiSelectionOnPaste', 'horizontally'
atom.clipboard.write('foo\nbar', selections: [
{indentBasis: 0, fullLine: false, text: 'foo'}
{indentBasis: 0, fullLine: false, text: 'bar'}
])
describe 'when the selection spans only one cell', ->
it 'replaces the cell content with the clipboard text', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
describe 'when the clipboard comes from a table', ->
describe 'and has only one selection', ->
beforeEach ->
atom.clipboard.write('foo\nbar', {
values: [[['foo','bar']]]
text: 'foo\tbar'
indentBasis: 0
fullLine: false
})
describe 'when the selection spans only one cell', ->
it 'expands the selection to match the clipboard content', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getSelectedRange()).toEqual([[0,0],[1,2]])
describe 'when the selection spans many cells', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
describe 'when there is many selections', ->
it 'sets the same value for each cells', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('bar')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'and has many selections', ->
beforeEach ->
atom.clipboard.write('foo\nbar', {
values: [
[['foo', 'oof']]
[['bar', 'rab']]
]
selections: [
{
indentBasis: 0
fullLine: false
text: 'foo\toof'
}
{
indentBasis: 0
fullLine: false
text: 'bar\trab'
}
]
})
describe 'when the selection spans only one cell', ->
it 'pastes only the first selection and expands the table selection', ->
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
describe 'when the selection spans many cells', ->
it 'pastes only the first selection', ->
tableEditor.setSelectedRange([[0,0], [2,2]])
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('oof')
describe 'when there is many selections', ->
it 'paste each clipboard selection in the corresponding table selection', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('rab')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
describe 'when there is more selections in the table', ->
it 'loops over the clipboard selection when needed', ->
tableEditor.setSelectedRanges([[[0,0],[1,2]], [[1,0],[2,2]], [[2,0],[3,2]]])
table.clearUndoStack()
tableEditor.pasteClipboard()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual('oof')
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('bar')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('rab')
expect(tableEditor.getValueAtScreenPosition([2,0])).toEqual('foo')
expect(tableEditor.getValueAtScreenPosition([2,1])).toEqual('oof')
expect(table.undoStack.length).toEqual(1)
table.undo()
expect(tableEditor.getValueAtScreenPosition([0,0])).toEqual('age')
expect(tableEditor.getValueAtScreenPosition([0,1])).toEqual(30)
expect(tableEditor.getValueAtScreenPosition([1,0])).toEqual('gender')
expect(tableEditor.getValueAtScreenPosition([1,1])).toEqual('female')
expect(tableEditor.getValueAtScreenPosition([2,0])).toEqual('name')
expect(tableEditor.getValueAtScreenPosition([2,1])).toEqual('PI:NAME:<NAME>END_PI')
|
[
{
"context": "ed = JSON.parse(res)\n b parsed.params.name, 'joe'\n b parsed.query.q, 't'\n b parsed.query",
"end": 5454,
"score": 0.9993191957473755,
"start": 5451,
"tag": "NAME",
"value": "joe"
},
{
"context": "ed = JSON.parse(res)\n b parsed.params.name, 'joe'\n... | test/browser_xml.coffee | Zolmeister/zock | 3 | b = require 'b-assert'
zock = require '../src'
onComplete = (xmlhttp, fn) ->
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState is 4
fn()
describe 'XMLHttpRequest', ->
it 'should get', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'should fail if syncronous', (done) ->
xmlhttp = zock.XMLHttpRequest()
try
xmlhttp.open('get', 'http://baseurl.com/test', false)
done(new Error 'Expected error')
catch
done()
it 'should get with pathed base', (done) ->
xmlhttp = zock
.base('http://baseurl.com/api')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/api/test')
xmlhttp.send()
it 'supports multiple bases', (done) ->
mock = zock
.base('http://baseurl.com/api')
.get('/test')
.reply(200, {hello: 'world'})
.base('http://somedomain.com')
.get('/test')
.reply(200, {hello: 'world'})
xmlhttpGen = ->
mock.XMLHttpRequest()
xmlhttp = xmlhttpGen()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
xmlhttp = xmlhttpGen()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://somedomain.com/test')
xmlhttp.send()
xmlhttp.open('get', 'http://baseurl.com/api/test')
xmlhttp.send()
it 'should post', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test')
.reply(200, {hello: 'post'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'post'})
done()
xmlhttp.open('post', 'http://baseurl.com/test')
xmlhttp.send()
it 'should post data', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test')
.reply(200, (res) ->
b res.body, {something: 'cool'}
done()
return ''
).XMLHttpRequest()
xmlhttp.open('post', 'http://baseurl.com/test')
xmlhttp.send('{"something": "cool"}')
it 'should put', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.put('/test')
.reply(200, {hello: 'put'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'put'})
done()
xmlhttp.open('put', 'http://baseurl.com/test')
xmlhttp.send()
it 'should put data', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.put('/test')
.reply(200, (res) ->
b res.body, {something: 'cool'}
done()
return ''
).XMLHttpRequest()
xmlhttp.open('put', 'http://baseurl.com/test')
xmlhttp.send('{"something": "cool"}')
it 'should get multiple at the same time', (done) ->
XML = zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'})
.get('/hello')
.reply(200, {test: 'test'}).XMLHttpRequest
resCnt = 0
xmlhttp = new XML()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
resCnt += 1
if resCnt is 2
done()
xmlhttp2 = new XML()
xmlhttp2.onreadystatechange = ->
if xmlhttp2.readyState is 4
res = xmlhttp2.responseText
b res, JSON.stringify({test: 'test'})
resCnt += 1
if resCnt is 2
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp2.open('get', 'http://baseurl.com/hello')
xmlhttp.send()
xmlhttp2.send()
it 'should ignore query params and hashes', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/test?test=123#hash')
xmlhttp.send()
it 'logs', (done) ->
log = 'null'
xmlhttp = zock
.logger (x) -> log = x
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
b log, 'get http://baseurl.com/test?test=123#hash'
done()
xmlhttp.open('get', 'http://baseurl.com/test?test=123#hash')
xmlhttp.send()
it 'has optional status', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply({hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'supports functions for body', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test/:name')
.reply (res) ->
return res
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
parsed = JSON.parse(res)
b parsed.params.name, 'joe'
b parsed.query.q, 't'
b parsed.query.p, 'plumber'
b parsed.headers.h1, 'head'
b parsed.body.x, 'y'
done()
xmlhttp.open('post', 'http://baseurl.com/test/joe?q=t&p=plumber')
xmlhttp.setRequestHeader 'h1', 'head'
xmlhttp.send(JSON.stringify {x: 'y'})
it 'supports promises from functions for body', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test/:name')
.reply (res) ->
Promise.resolve res
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
parsed = JSON.parse(res)
b parsed.params.name, 'joe'
b parsed.body.x, 'y'
done()
xmlhttp.open('post', 'http://baseurl.com/test/joe')
xmlhttp.send(JSON.stringify {x: 'y'})
it 'supports res override (e.g. for statusCode or headers)', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test/:name')
.reply (req, res) ->
res
statusCode: 401
headers:
'User-Agent': 'xxx'
body: JSON.stringify req
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b xmlhttp.status, 401
b xmlhttp.getResponseHeader('User-Agent'), 'xxx'
parsed = JSON.parse(res)
b parsed.params.name, 'joe'
b parsed.body.x, 'y'
done()
xmlhttp.open('post', 'http://baseurl.com/test/joe')
xmlhttp.send(JSON.stringify {x: 'y'})
it 'withOverrides', ->
zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'})
.withOverrides ->
new Promise (resolve) ->
xmlhttp = new window.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
resolve()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'nested withOverrides', ->
zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'})
.withOverrides ->
zock.withOverrides -> null
.then ->
new Promise (resolve) ->
xmlhttp = new window.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
resolve()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'removes override after completion', ->
originalXML = window.XMLHttpRequest
zock
.withOverrides ->
b window.XMLHttpRequest isnt originalXML
.then ->
b window.XMLHttpRequest is originalXML
it 'supports non-JSON responses', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply -> 'abc'
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, 'abc'
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
# TODO: support allowOutbound()
it 'defaults to rejecting outbound requests', ->
xmlhttp = zock
.XMLHttpRequest()
xmlhttp.open('get', 'https://zolmeister.com')
try
xmlhttp.send()
catch err
b err.message, 'Invalid Outbound Request: https://zolmeister.com'
it 'supports JSON array responses', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply -> [{x: 'y'}]
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, '[{"x":"y"}]'
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
| 20885 | b = require 'b-assert'
zock = require '../src'
onComplete = (xmlhttp, fn) ->
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState is 4
fn()
describe 'XMLHttpRequest', ->
it 'should get', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'should fail if syncronous', (done) ->
xmlhttp = zock.XMLHttpRequest()
try
xmlhttp.open('get', 'http://baseurl.com/test', false)
done(new Error 'Expected error')
catch
done()
it 'should get with pathed base', (done) ->
xmlhttp = zock
.base('http://baseurl.com/api')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/api/test')
xmlhttp.send()
it 'supports multiple bases', (done) ->
mock = zock
.base('http://baseurl.com/api')
.get('/test')
.reply(200, {hello: 'world'})
.base('http://somedomain.com')
.get('/test')
.reply(200, {hello: 'world'})
xmlhttpGen = ->
mock.XMLHttpRequest()
xmlhttp = xmlhttpGen()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
xmlhttp = xmlhttpGen()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://somedomain.com/test')
xmlhttp.send()
xmlhttp.open('get', 'http://baseurl.com/api/test')
xmlhttp.send()
it 'should post', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test')
.reply(200, {hello: 'post'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'post'})
done()
xmlhttp.open('post', 'http://baseurl.com/test')
xmlhttp.send()
it 'should post data', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test')
.reply(200, (res) ->
b res.body, {something: 'cool'}
done()
return ''
).XMLHttpRequest()
xmlhttp.open('post', 'http://baseurl.com/test')
xmlhttp.send('{"something": "cool"}')
it 'should put', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.put('/test')
.reply(200, {hello: 'put'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'put'})
done()
xmlhttp.open('put', 'http://baseurl.com/test')
xmlhttp.send()
it 'should put data', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.put('/test')
.reply(200, (res) ->
b res.body, {something: 'cool'}
done()
return ''
).XMLHttpRequest()
xmlhttp.open('put', 'http://baseurl.com/test')
xmlhttp.send('{"something": "cool"}')
it 'should get multiple at the same time', (done) ->
XML = zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'})
.get('/hello')
.reply(200, {test: 'test'}).XMLHttpRequest
resCnt = 0
xmlhttp = new XML()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
resCnt += 1
if resCnt is 2
done()
xmlhttp2 = new XML()
xmlhttp2.onreadystatechange = ->
if xmlhttp2.readyState is 4
res = xmlhttp2.responseText
b res, JSON.stringify({test: 'test'})
resCnt += 1
if resCnt is 2
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp2.open('get', 'http://baseurl.com/hello')
xmlhttp.send()
xmlhttp2.send()
it 'should ignore query params and hashes', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/test?test=123#hash')
xmlhttp.send()
it 'logs', (done) ->
log = 'null'
xmlhttp = zock
.logger (x) -> log = x
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
b log, 'get http://baseurl.com/test?test=123#hash'
done()
xmlhttp.open('get', 'http://baseurl.com/test?test=123#hash')
xmlhttp.send()
it 'has optional status', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply({hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'supports functions for body', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test/:name')
.reply (res) ->
return res
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
parsed = JSON.parse(res)
b parsed.params.name, '<NAME>'
b parsed.query.q, 't'
b parsed.query.p, 'plumber'
b parsed.headers.h1, 'head'
b parsed.body.x, 'y'
done()
xmlhttp.open('post', 'http://baseurl.com/test/joe?q=t&p=plumber')
xmlhttp.setRequestHeader 'h1', 'head'
xmlhttp.send(JSON.stringify {x: 'y'})
it 'supports promises from functions for body', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test/:name')
.reply (res) ->
Promise.resolve res
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
parsed = JSON.parse(res)
b parsed.params.name, '<NAME>'
b parsed.body.x, 'y'
done()
xmlhttp.open('post', 'http://baseurl.com/test/joe')
xmlhttp.send(JSON.stringify {x: 'y'})
it 'supports res override (e.g. for statusCode or headers)', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test/:name')
.reply (req, res) ->
res
statusCode: 401
headers:
'User-Agent': 'xxx'
body: JSON.stringify req
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b xmlhttp.status, 401
b xmlhttp.getResponseHeader('User-Agent'), 'xxx'
parsed = JSON.parse(res)
b parsed.params.name, '<NAME>'
b parsed.body.x, 'y'
done()
xmlhttp.open('post', 'http://baseurl.com/test/joe')
xmlhttp.send(JSON.stringify {x: 'y'})
it 'withOverrides', ->
zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'})
.withOverrides ->
new Promise (resolve) ->
xmlhttp = new window.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
resolve()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'nested withOverrides', ->
zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'})
.withOverrides ->
zock.withOverrides -> null
.then ->
new Promise (resolve) ->
xmlhttp = new window.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
resolve()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'removes override after completion', ->
originalXML = window.XMLHttpRequest
zock
.withOverrides ->
b window.XMLHttpRequest isnt originalXML
.then ->
b window.XMLHttpRequest is originalXML
it 'supports non-JSON responses', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply -> 'abc'
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, 'abc'
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
# TODO: support allowOutbound()
it 'defaults to rejecting outbound requests', ->
xmlhttp = zock
.XMLHttpRequest()
xmlhttp.open('get', 'https://zolmeister.com')
try
xmlhttp.send()
catch err
b err.message, 'Invalid Outbound Request: https://zolmeister.com'
it 'supports JSON array responses', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply -> [{x: 'y'}]
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, '[{"x":"y"}]'
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
| true | b = require 'b-assert'
zock = require '../src'
onComplete = (xmlhttp, fn) ->
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState is 4
fn()
describe 'XMLHttpRequest', ->
it 'should get', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'should fail if syncronous', (done) ->
xmlhttp = zock.XMLHttpRequest()
try
xmlhttp.open('get', 'http://baseurl.com/test', false)
done(new Error 'Expected error')
catch
done()
it 'should get with pathed base', (done) ->
xmlhttp = zock
.base('http://baseurl.com/api')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/api/test')
xmlhttp.send()
it 'supports multiple bases', (done) ->
mock = zock
.base('http://baseurl.com/api')
.get('/test')
.reply(200, {hello: 'world'})
.base('http://somedomain.com')
.get('/test')
.reply(200, {hello: 'world'})
xmlhttpGen = ->
mock.XMLHttpRequest()
xmlhttp = xmlhttpGen()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
xmlhttp = xmlhttpGen()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://somedomain.com/test')
xmlhttp.send()
xmlhttp.open('get', 'http://baseurl.com/api/test')
xmlhttp.send()
it 'should post', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test')
.reply(200, {hello: 'post'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'post'})
done()
xmlhttp.open('post', 'http://baseurl.com/test')
xmlhttp.send()
it 'should post data', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test')
.reply(200, (res) ->
b res.body, {something: 'cool'}
done()
return ''
).XMLHttpRequest()
xmlhttp.open('post', 'http://baseurl.com/test')
xmlhttp.send('{"something": "cool"}')
it 'should put', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.put('/test')
.reply(200, {hello: 'put'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'put'})
done()
xmlhttp.open('put', 'http://baseurl.com/test')
xmlhttp.send()
it 'should put data', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.put('/test')
.reply(200, (res) ->
b res.body, {something: 'cool'}
done()
return ''
).XMLHttpRequest()
xmlhttp.open('put', 'http://baseurl.com/test')
xmlhttp.send('{"something": "cool"}')
it 'should get multiple at the same time', (done) ->
XML = zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'})
.get('/hello')
.reply(200, {test: 'test'}).XMLHttpRequest
resCnt = 0
xmlhttp = new XML()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
resCnt += 1
if resCnt is 2
done()
xmlhttp2 = new XML()
xmlhttp2.onreadystatechange = ->
if xmlhttp2.readyState is 4
res = xmlhttp2.responseText
b res, JSON.stringify({test: 'test'})
resCnt += 1
if resCnt is 2
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp2.open('get', 'http://baseurl.com/hello')
xmlhttp.send()
xmlhttp2.send()
it 'should ignore query params and hashes', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/test?test=123#hash')
xmlhttp.send()
it 'logs', (done) ->
log = 'null'
xmlhttp = zock
.logger (x) -> log = x
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
b log, 'get http://baseurl.com/test?test=123#hash'
done()
xmlhttp.open('get', 'http://baseurl.com/test?test=123#hash')
xmlhttp.send()
it 'has optional status', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply({hello: 'world'}).XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'supports functions for body', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test/:name')
.reply (res) ->
return res
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
parsed = JSON.parse(res)
b parsed.params.name, 'PI:NAME:<NAME>END_PI'
b parsed.query.q, 't'
b parsed.query.p, 'plumber'
b parsed.headers.h1, 'head'
b parsed.body.x, 'y'
done()
xmlhttp.open('post', 'http://baseurl.com/test/joe?q=t&p=plumber')
xmlhttp.setRequestHeader 'h1', 'head'
xmlhttp.send(JSON.stringify {x: 'y'})
it 'supports promises from functions for body', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test/:name')
.reply (res) ->
Promise.resolve res
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
parsed = JSON.parse(res)
b parsed.params.name, 'PI:NAME:<NAME>END_PI'
b parsed.body.x, 'y'
done()
xmlhttp.open('post', 'http://baseurl.com/test/joe')
xmlhttp.send(JSON.stringify {x: 'y'})
it 'supports res override (e.g. for statusCode or headers)', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.post('/test/:name')
.reply (req, res) ->
res
statusCode: 401
headers:
'User-Agent': 'xxx'
body: JSON.stringify req
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b xmlhttp.status, 401
b xmlhttp.getResponseHeader('User-Agent'), 'xxx'
parsed = JSON.parse(res)
b parsed.params.name, 'PI:NAME:<NAME>END_PI'
b parsed.body.x, 'y'
done()
xmlhttp.open('post', 'http://baseurl.com/test/joe')
xmlhttp.send(JSON.stringify {x: 'y'})
it 'withOverrides', ->
zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'})
.withOverrides ->
new Promise (resolve) ->
xmlhttp = new window.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
resolve()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'nested withOverrides', ->
zock
.base('http://baseurl.com')
.get('/test')
.reply(200, {hello: 'world'})
.withOverrides ->
zock.withOverrides -> null
.then ->
new Promise (resolve) ->
xmlhttp = new window.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, JSON.stringify({hello: 'world'})
resolve()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
it 'removes override after completion', ->
originalXML = window.XMLHttpRequest
zock
.withOverrides ->
b window.XMLHttpRequest isnt originalXML
.then ->
b window.XMLHttpRequest is originalXML
it 'supports non-JSON responses', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply -> 'abc'
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, 'abc'
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
# TODO: support allowOutbound()
it 'defaults to rejecting outbound requests', ->
xmlhttp = zock
.XMLHttpRequest()
xmlhttp.open('get', 'https://zolmeister.com')
try
xmlhttp.send()
catch err
b err.message, 'Invalid Outbound Request: https://zolmeister.com'
it 'supports JSON array responses', (done) ->
xmlhttp = zock
.base('http://baseurl.com')
.get('/test')
.reply -> [{x: 'y'}]
.XMLHttpRequest()
onComplete xmlhttp, ->
res = xmlhttp.responseText
b res, '[{"x":"y"}]'
done()
xmlhttp.open('get', 'http://baseurl.com/test')
xmlhttp.send()
|
[
{
"context": "ow.bs.modal', =>\n @cloneTaskModal.task.name(@task.name)\n @cloneTaskModal.task.assignee_id(@tas",
"end": 1764,
"score": 0.5786301493644714,
"start": 1760,
"tag": "USERNAME",
"value": "task"
},
{
"context": ".modal', =>\n @cloneTaskModal.task.name(@task.n... | app/assets/javascripts/tasks/show.coffee | pamelladnanexus/pfda-release-repo | 57 | class SpacesTaskShowView extends Precision.SpacesTasks.PageModel
acceptTasks: () ->
@postAction("/spaces/#{@space_id}/tasks/accept", {
task_ids: [@task.id]
}, 'Task(s) has been marked as accepted!')
completeTasks: () ->
@postAction("/spaces/#{@space_id}/tasks/complete", {
task_ids: [@task.id]
}, 'Task(s) has been marked as completed!')
createTask: () ->
@newTaskModal.createTask()
declineTasks: () ->
@declineTaskModal.declineTask([@task.id])
reopenTasks: () ->
@reopenTaskModal.reopenTasks([@task.id])
makeActiveTasks: () ->
@makeActiveTaskModal.makeActiveTasks([@task.id])
cloneTask: () ->
@cloneTaskModal.cloneTask(@task.id)
editTask: () ->
@editTaskModal.editTask(@task.id)
commentTask: () ->
@newCommentModal.commentTask(@task.id)
replyComment: () ->
@replyCommentModal.commentTask(@task.id)
reassignTask: () ->
@reassignTaskModal.reassignTask(@task.id)
deleteTask: () ->
@deleteTaskModal.deleteTask(@task.id)
constructor: (params) ->
super()
@space_id = params.space_id
@task = params.task
@newCommentModal = new Precision.SpacesTasks.NewCommentModal(params, 'comment_task_modal')
@replyCommentModal = new Precision.SpacesTasks.NewCommentModal(params, 'reply_comment_modal')
@atwhoModals = [@newCommentModal, @replyCommentModal]
@declineTaskModal = new Precision.SpacesTasks.DeclineTaskModal(params, 1)
@reopenTaskModal = new Precision.SpacesTasks.ReopenTaskModal(params, 1)
@makeActiveTaskModal = new Precision.SpacesTasks.MakeActiveTaskModal(params, 1)
@cloneTaskModal = new Precision.SpacesTasks.CloneTaskModal(params)
@cloneTaskModal.modal.on 'show.bs.modal', =>
@cloneTaskModal.task.name(@task.name)
@cloneTaskModal.task.assignee_id(@task.assignee_id)
@cloneTaskModal.task.response_deadline(@task.response_deadline)
@cloneTaskModal.task.completion_deadline(@task.completion_deadline)
@cloneTaskModal.task.description(@task.description)
@editTaskModal = new Precision.SpacesTasks.EditTaskModal(params)
@editTaskModal.modal.on 'show.bs.modal', =>
@editTaskModal.task.name(@task.name)
@editTaskModal.task.assignee_id(@task.assignee_id)
@editTaskModal.task.response_deadline(@task.response_deadline)
@editTaskModal.task.completion_deadline(@task.completion_deadline)
@editTaskModal.task.description(@task.description)
@reassignTaskModal = new Precision.SpacesTasks.ReassignTaskModal(params)
@reassignTaskModal.modal.on 'show.bs.modal', =>
@reassignTaskModal.task.name(@task.name)
@reassignTaskModal.task.assignee_id(@task.assignee_id)
@reassignTaskModal.task.response_deadline(@task.response_deadline_f)
@reassignTaskModal.task.completion_deadline(@task.completion_deadline_f)
@reassignTaskModal.task.description(@task.description)
@deleteTaskModal = new Precision.SpacesTasks.DeleteTaskModal(params)
@deleteTaskModal.modal.on 'show.bs.modal', =>
@deleteTaskModal.task.name(@task.name)
@deleteTaskModal.task.assignee_id(@deleteTaskModal.getUserNameById(@task.assignee_id))
@deleteTaskModal.task.response_deadline(@task.response_deadline_f)
@deleteTaskModal.task.completion_deadline(@task.completion_deadline_f)
@deleteTaskModal.task.description(@task.description)
#########################################################
#
#
# PALOMA CONTROLLER
#
#
#########################################################
TasksController = Paloma.controller('Tasks', {
show: ->
$container = $("body main")
viewModel = new SpacesTaskShowView(@params)
ko.applyBindings(viewModel, $container[0])
viewModel.atwhoModals.map (modal) =>
editable = $(modal.modal).find('.add-atwho')
editable.atwho({
at: "@",
insertTpl: '<a href="/users/${name}" target="_blank">@${name}</a>',
data: @params.users.map (user) -> user.label
})
editable.on 'input', modal.changeCommentText
editable.on 'inserted.atwho', modal.changeCommentText
$(document).ready ->
Precision.nestedComments.initTreads()
commentsBodies = $(".pfda-comment-body p")
regex = Precision.MENTIONS_CONST.regex
replace = Precision.MENTIONS_CONST.replace
commentsBodies.each (index, commentsBody) ->
commentsBody.innerHTML = commentsBody.innerHTML.replace(regex, replace)
$('#task_show_accept').on 'click', (e) ->
viewModel.acceptTasks()
$('#task_show_complete').on 'click', (e) ->
viewModel.completeTasks()
$('#create_task_modal_submit').on 'click', (e) ->
viewModel.createTask()
$('#decline_task_modal_submit').on 'click', (e) ->
viewModel.declineTasks()
$('#reopen_task_modal_submit').on 'click', (e) ->
viewModel.reopenTasks()
$('#make_active_task_modal_submit').on 'click', (e) ->
viewModel.makeActiveTasks()
$('#clone_task_modal_submit').on 'click', (e) ->
viewModel.cloneTask()
$('#edit_task_modal_submit').on 'click', (e) ->
viewModel.editTask()
$('#reassign_task_modal_submit').on 'click', (e) ->
viewModel.reassignTask()
$('#delete_task_modal_submit').on 'click', (e) ->
viewModel.deleteTask()
$('#comment_task_modal_submit').on 'click', (e) ->
viewModel.commentTask()
$('#reply_comment_modal_submit').on 'click', (e) ->
viewModel.replyComment()
$('.nested-comment--show-new-comment').on 'click', (e) ->
e.preventDefault()
parentId = $(e.target).attr('data-parent-id')
viewModel.replyCommentModal.parentId(parentId)
$('#reply_comment_modal').modal('show')
$('.modal').on 'hide.bs.modal', () ->
viewModel.newCommentModal.clear()
viewModel.replyCommentModal.clear()
viewModel.reopenTaskModal.clear()
viewModel.makeActiveTaskModal.clear()
viewModel.declineTaskModal.clear()
viewModel.cloneTaskModal.clear()
viewModel.editTaskModal.clear()
viewModel.reassignTaskModal.clear()
viewModel.deleteTaskModal.clear()
})
| 190969 | class SpacesTaskShowView extends Precision.SpacesTasks.PageModel
acceptTasks: () ->
@postAction("/spaces/#{@space_id}/tasks/accept", {
task_ids: [@task.id]
}, 'Task(s) has been marked as accepted!')
completeTasks: () ->
@postAction("/spaces/#{@space_id}/tasks/complete", {
task_ids: [@task.id]
}, 'Task(s) has been marked as completed!')
createTask: () ->
@newTaskModal.createTask()
declineTasks: () ->
@declineTaskModal.declineTask([@task.id])
reopenTasks: () ->
@reopenTaskModal.reopenTasks([@task.id])
makeActiveTasks: () ->
@makeActiveTaskModal.makeActiveTasks([@task.id])
cloneTask: () ->
@cloneTaskModal.cloneTask(@task.id)
editTask: () ->
@editTaskModal.editTask(@task.id)
commentTask: () ->
@newCommentModal.commentTask(@task.id)
replyComment: () ->
@replyCommentModal.commentTask(@task.id)
reassignTask: () ->
@reassignTaskModal.reassignTask(@task.id)
deleteTask: () ->
@deleteTaskModal.deleteTask(@task.id)
constructor: (params) ->
super()
@space_id = params.space_id
@task = params.task
@newCommentModal = new Precision.SpacesTasks.NewCommentModal(params, 'comment_task_modal')
@replyCommentModal = new Precision.SpacesTasks.NewCommentModal(params, 'reply_comment_modal')
@atwhoModals = [@newCommentModal, @replyCommentModal]
@declineTaskModal = new Precision.SpacesTasks.DeclineTaskModal(params, 1)
@reopenTaskModal = new Precision.SpacesTasks.ReopenTaskModal(params, 1)
@makeActiveTaskModal = new Precision.SpacesTasks.MakeActiveTaskModal(params, 1)
@cloneTaskModal = new Precision.SpacesTasks.CloneTaskModal(params)
@cloneTaskModal.modal.on 'show.bs.modal', =>
@cloneTaskModal.task.name(@task.name)
@cloneTaskModal.task.assignee_id(@task.assignee_id)
@cloneTaskModal.task.response_deadline(@task.response_deadline)
@cloneTaskModal.task.completion_deadline(@task.completion_deadline)
@cloneTaskModal.task.description(@task.description)
@editTaskModal = new Precision.SpacesTasks.EditTaskModal(params)
@editTaskModal.modal.on 'show.bs.modal', =>
@editTaskModal.task.name(@task.name)
@editTaskModal.task.assignee_id(@task.assignee_id)
@editTaskModal.task.response_deadline(@task.response_deadline)
@editTaskModal.task.completion_deadline(@task.completion_deadline)
@editTaskModal.task.description(@task.description)
@reassignTaskModal = new Precision.SpacesTasks.ReassignTaskModal(params)
@reassignTaskModal.modal.on 'show.bs.modal', =>
@reassignTaskModal.task.name<NAME>(@task.name)
@reassignTaskModal.task.assignee_id(@task.assignee_id)
@reassignTaskModal.task.response_deadline(@task.response_deadline_f)
@reassignTaskModal.task.completion_deadline(@task.completion_deadline_f)
@reassignTaskModal.task.description(@task.description)
@deleteTaskModal = new Precision.SpacesTasks.DeleteTaskModal(params)
@deleteTaskModal.modal.on 'show.bs.modal', =>
@deleteTaskModal.task.name<NAME>(@task.name)
@deleteTaskModal.task.assignee_id(@deleteTaskModal.getUserNameById(@task.assignee_id))
@deleteTaskModal.task.response_deadline(@task.response_deadline_f)
@deleteTaskModal.task.completion_deadline(@task.completion_deadline_f)
@deleteTaskModal.task.description(@task.description)
#########################################################
#
#
# PALOMA CONTROLLER
#
#
#########################################################
TasksController = Paloma.controller('Tasks', {
show: ->
$container = $("body main")
viewModel = new SpacesTaskShowView(@params)
ko.applyBindings(viewModel, $container[0])
viewModel.atwhoModals.map (modal) =>
editable = $(modal.modal).find('.add-atwho')
editable.atwho({
at: "@",
insertTpl: '<a href="/users/${name}" target="_blank">@${name}</a>',
data: @params.users.map (user) -> user.label
})
editable.on 'input', modal.changeCommentText
editable.on 'inserted.atwho', modal.changeCommentText
$(document).ready ->
Precision.nestedComments.initTreads()
commentsBodies = $(".pfda-comment-body p")
regex = Precision.MENTIONS_CONST.regex
replace = Precision.MENTIONS_CONST.replace
commentsBodies.each (index, commentsBody) ->
commentsBody.innerHTML = commentsBody.innerHTML.replace(regex, replace)
$('#task_show_accept').on 'click', (e) ->
viewModel.acceptTasks()
$('#task_show_complete').on 'click', (e) ->
viewModel.completeTasks()
$('#create_task_modal_submit').on 'click', (e) ->
viewModel.createTask()
$('#decline_task_modal_submit').on 'click', (e) ->
viewModel.declineTasks()
$('#reopen_task_modal_submit').on 'click', (e) ->
viewModel.reopenTasks()
$('#make_active_task_modal_submit').on 'click', (e) ->
viewModel.makeActiveTasks()
$('#clone_task_modal_submit').on 'click', (e) ->
viewModel.cloneTask()
$('#edit_task_modal_submit').on 'click', (e) ->
viewModel.editTask()
$('#reassign_task_modal_submit').on 'click', (e) ->
viewModel.reassignTask()
$('#delete_task_modal_submit').on 'click', (e) ->
viewModel.deleteTask()
$('#comment_task_modal_submit').on 'click', (e) ->
viewModel.commentTask()
$('#reply_comment_modal_submit').on 'click', (e) ->
viewModel.replyComment()
$('.nested-comment--show-new-comment').on 'click', (e) ->
e.preventDefault()
parentId = $(e.target).attr('data-parent-id')
viewModel.replyCommentModal.parentId(parentId)
$('#reply_comment_modal').modal('show')
$('.modal').on 'hide.bs.modal', () ->
viewModel.newCommentModal.clear()
viewModel.replyCommentModal.clear()
viewModel.reopenTaskModal.clear()
viewModel.makeActiveTaskModal.clear()
viewModel.declineTaskModal.clear()
viewModel.cloneTaskModal.clear()
viewModel.editTaskModal.clear()
viewModel.reassignTaskModal.clear()
viewModel.deleteTaskModal.clear()
})
| true | class SpacesTaskShowView extends Precision.SpacesTasks.PageModel
acceptTasks: () ->
@postAction("/spaces/#{@space_id}/tasks/accept", {
task_ids: [@task.id]
}, 'Task(s) has been marked as accepted!')
completeTasks: () ->
@postAction("/spaces/#{@space_id}/tasks/complete", {
task_ids: [@task.id]
}, 'Task(s) has been marked as completed!')
createTask: () ->
@newTaskModal.createTask()
declineTasks: () ->
@declineTaskModal.declineTask([@task.id])
reopenTasks: () ->
@reopenTaskModal.reopenTasks([@task.id])
makeActiveTasks: () ->
@makeActiveTaskModal.makeActiveTasks([@task.id])
cloneTask: () ->
@cloneTaskModal.cloneTask(@task.id)
editTask: () ->
@editTaskModal.editTask(@task.id)
commentTask: () ->
@newCommentModal.commentTask(@task.id)
replyComment: () ->
@replyCommentModal.commentTask(@task.id)
reassignTask: () ->
@reassignTaskModal.reassignTask(@task.id)
deleteTask: () ->
@deleteTaskModal.deleteTask(@task.id)
constructor: (params) ->
super()
@space_id = params.space_id
@task = params.task
@newCommentModal = new Precision.SpacesTasks.NewCommentModal(params, 'comment_task_modal')
@replyCommentModal = new Precision.SpacesTasks.NewCommentModal(params, 'reply_comment_modal')
@atwhoModals = [@newCommentModal, @replyCommentModal]
@declineTaskModal = new Precision.SpacesTasks.DeclineTaskModal(params, 1)
@reopenTaskModal = new Precision.SpacesTasks.ReopenTaskModal(params, 1)
@makeActiveTaskModal = new Precision.SpacesTasks.MakeActiveTaskModal(params, 1)
@cloneTaskModal = new Precision.SpacesTasks.CloneTaskModal(params)
@cloneTaskModal.modal.on 'show.bs.modal', =>
@cloneTaskModal.task.name(@task.name)
@cloneTaskModal.task.assignee_id(@task.assignee_id)
@cloneTaskModal.task.response_deadline(@task.response_deadline)
@cloneTaskModal.task.completion_deadline(@task.completion_deadline)
@cloneTaskModal.task.description(@task.description)
@editTaskModal = new Precision.SpacesTasks.EditTaskModal(params)
@editTaskModal.modal.on 'show.bs.modal', =>
@editTaskModal.task.name(@task.name)
@editTaskModal.task.assignee_id(@task.assignee_id)
@editTaskModal.task.response_deadline(@task.response_deadline)
@editTaskModal.task.completion_deadline(@task.completion_deadline)
@editTaskModal.task.description(@task.description)
@reassignTaskModal = new Precision.SpacesTasks.ReassignTaskModal(params)
@reassignTaskModal.modal.on 'show.bs.modal', =>
@reassignTaskModal.task.namePI:NAME:<NAME>END_PI(@task.name)
@reassignTaskModal.task.assignee_id(@task.assignee_id)
@reassignTaskModal.task.response_deadline(@task.response_deadline_f)
@reassignTaskModal.task.completion_deadline(@task.completion_deadline_f)
@reassignTaskModal.task.description(@task.description)
@deleteTaskModal = new Precision.SpacesTasks.DeleteTaskModal(params)
@deleteTaskModal.modal.on 'show.bs.modal', =>
@deleteTaskModal.task.namePI:NAME:<NAME>END_PI(@task.name)
@deleteTaskModal.task.assignee_id(@deleteTaskModal.getUserNameById(@task.assignee_id))
@deleteTaskModal.task.response_deadline(@task.response_deadline_f)
@deleteTaskModal.task.completion_deadline(@task.completion_deadline_f)
@deleteTaskModal.task.description(@task.description)
#########################################################
#
#
# PALOMA CONTROLLER
#
#
#########################################################
TasksController = Paloma.controller('Tasks', {
show: ->
$container = $("body main")
viewModel = new SpacesTaskShowView(@params)
ko.applyBindings(viewModel, $container[0])
viewModel.atwhoModals.map (modal) =>
editable = $(modal.modal).find('.add-atwho')
editable.atwho({
at: "@",
insertTpl: '<a href="/users/${name}" target="_blank">@${name}</a>',
data: @params.users.map (user) -> user.label
})
editable.on 'input', modal.changeCommentText
editable.on 'inserted.atwho', modal.changeCommentText
$(document).ready ->
Precision.nestedComments.initTreads()
commentsBodies = $(".pfda-comment-body p")
regex = Precision.MENTIONS_CONST.regex
replace = Precision.MENTIONS_CONST.replace
commentsBodies.each (index, commentsBody) ->
commentsBody.innerHTML = commentsBody.innerHTML.replace(regex, replace)
$('#task_show_accept').on 'click', (e) ->
viewModel.acceptTasks()
$('#task_show_complete').on 'click', (e) ->
viewModel.completeTasks()
$('#create_task_modal_submit').on 'click', (e) ->
viewModel.createTask()
$('#decline_task_modal_submit').on 'click', (e) ->
viewModel.declineTasks()
$('#reopen_task_modal_submit').on 'click', (e) ->
viewModel.reopenTasks()
$('#make_active_task_modal_submit').on 'click', (e) ->
viewModel.makeActiveTasks()
$('#clone_task_modal_submit').on 'click', (e) ->
viewModel.cloneTask()
$('#edit_task_modal_submit').on 'click', (e) ->
viewModel.editTask()
$('#reassign_task_modal_submit').on 'click', (e) ->
viewModel.reassignTask()
$('#delete_task_modal_submit').on 'click', (e) ->
viewModel.deleteTask()
$('#comment_task_modal_submit').on 'click', (e) ->
viewModel.commentTask()
$('#reply_comment_modal_submit').on 'click', (e) ->
viewModel.replyComment()
$('.nested-comment--show-new-comment').on 'click', (e) ->
e.preventDefault()
parentId = $(e.target).attr('data-parent-id')
viewModel.replyCommentModal.parentId(parentId)
$('#reply_comment_modal').modal('show')
$('.modal').on 'hide.bs.modal', () ->
viewModel.newCommentModal.clear()
viewModel.replyCommentModal.clear()
viewModel.reopenTaskModal.clear()
viewModel.makeActiveTaskModal.clear()
viewModel.declineTaskModal.clear()
viewModel.cloneTaskModal.clear()
viewModel.editTaskModal.clear()
viewModel.reassignTaskModal.clear()
viewModel.deleteTaskModal.clear()
})
|
[
{
"context": "o = require '../'\n\ndescribe 'Client', ->\n key = 'fakekey'\n client = new hanzo.Client key: key\n\n it 'shou",
"end": 61,
"score": 0.9980210065841675,
"start": 54,
"tag": "KEY",
"value": "fakekey"
}
] | test/client.coffee | hanzo-io/hanzo.js | 147 | hanzo = require '../'
describe 'Client', ->
key = 'fakekey'
client = new hanzo.Client key: key
it 'should use default endpoint', ->
client.opts.endpoint.should.eq 'https://api.hanzo.io'
| 122585 | hanzo = require '../'
describe 'Client', ->
key = '<KEY>'
client = new hanzo.Client key: key
it 'should use default endpoint', ->
client.opts.endpoint.should.eq 'https://api.hanzo.io'
| true | hanzo = require '../'
describe 'Client', ->
key = 'PI:KEY:<KEY>END_PI'
client = new hanzo.Client key: key
it 'should use default endpoint', ->
client.opts.endpoint.should.eq 'https://api.hanzo.io'
|
[
{
"context": "fileoverview Tests for no-new-func rule.\n# @author Ilya Volodin\n###\n\n'use strict'\n\n#-----------------------------",
"end": 71,
"score": 0.9998286366462708,
"start": 59,
"tag": "NAME",
"value": "Ilya Volodin"
}
] | src/tests/rules/no-new-func.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-new-func rule.
# @author Ilya Volodin
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-new-func'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-new-func', rule,
valid: [
'a = new _function("b", "c", "return b+c")'
'a = _function("b", "c", "return b+c")'
]
invalid: [
code: 'a = new Function("b", "c", "return b+c")'
errors: [
message: 'The Function constructor is eval.', type: 'NewExpression'
]
,
code: 'a = Function("b", "c", "return b+c")'
errors: [
message: 'The Function constructor is eval.', type: 'CallExpression'
]
]
| 99512 | ###*
# @fileoverview Tests for no-new-func rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-new-func'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-new-func', rule,
valid: [
'a = new _function("b", "c", "return b+c")'
'a = _function("b", "c", "return b+c")'
]
invalid: [
code: 'a = new Function("b", "c", "return b+c")'
errors: [
message: 'The Function constructor is eval.', type: 'NewExpression'
]
,
code: 'a = Function("b", "c", "return b+c")'
errors: [
message: 'The Function constructor is eval.', type: 'CallExpression'
]
]
| true | ###*
# @fileoverview Tests for no-new-func rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-new-func'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-new-func', rule,
valid: [
'a = new _function("b", "c", "return b+c")'
'a = _function("b", "c", "return b+c")'
]
invalid: [
code: 'a = new Function("b", "c", "return b+c")'
errors: [
message: 'The Function constructor is eval.', type: 'NewExpression'
]
,
code: 'a = Function("b", "c", "return b+c")'
errors: [
message: 'The Function constructor is eval.', type: 'CallExpression'
]
]
|
[
{
"context": "degit'\nGitHub = require 'github-api'\n\nrepoName = 'galtx-centex/galtx-centex.github.io'\nrepoURL = \"https://github",
"end": 160,
"score": 0.9657365679740906,
"start": 148,
"tag": "USERNAME",
"value": "galtx-centex"
},
{
"context": ", user.email\n committer = Git... | lib/git.coffee | galtx-centex/roobot | 3 | # Git commands
fs = require 'fs'
fse = require 'fs-extra'
path = require 'path'
Git = require 'nodegit'
GitHub = require 'github-api'
repoName = 'galtx-centex/galtx-centex.github.io'
repoURL = "https://github.com/#{repoName}.git"
repoPath = path.join __dirname, 'galtx-centex.org'
auth = (url, username) ->
Git.Cred.userpassPlaintextNew process.env.GITHUB_TOKEN, 'x-oauth-basic'
clone = (clonePath) ->
new Promise (resolve, reject) ->
console.log "clone #{repoURL} to #{clonePath}"
cloneOpts = fetchOpts: callbacks: credentials: auth
Git.Clone.clone repoURL, clonePath, cloneOpts
.then (repo) ->
resolve repo
.catch (err) ->
reject "Clone #{err}"
checkout = (repo, branch) ->
new Promise (resolve, reject) ->
ref = null
repo.getReference branch
.then (reference) ->
ref = reference
console.log "ref checkout #{ref}"
repo.checkoutRef ref
.then () ->
resolve ref
.catch (err) ->
reject "Checkout #{err}"
commit = (repo, user, message) ->
new Promise (resolve, reject) ->
ndx = null
tree = null
repo.refreshIndex()
.then (index) ->
ndx = index
ndx.addAll()
.then () ->
ndx.write()
ndx.writeTree()
.then (treeObj) ->
tree = treeObj
repo.getHeadCommit()
.then (parent) ->
console.log "commit '#{message}' from <#{user.name} #{user.email}>"
author = Git.Signature.now user.name, user.email
committer = Git.Signature.now 'RooBot', 'roobot@galtx-centex.org'
repo.createCommit 'HEAD', author, committer, message, tree, [parent]
.then (oid) ->
resolve oid
.catch (err) ->
reject "Commit #{err}"
tag = (repo, oid) ->
new Promise (resolve, reject) ->
console.log "tag #{oid}"
repo.createLightweightTag oid, "#{oid}-tag"
.then (reference) ->
resolve reference
.catch (err) ->
reject "Tag #{err}"
push = (repo, src, dst) ->
new Promise (resolve, reject) ->
refSpec = "#{src}:#{dst}"
repo.getRemote 'origin'
.then (remote) ->
console.log "push origin #{refSpec}"
pushOpts = callbacks: credentials: auth
remote.push ["#{refSpec}"], pushOpts
.then () ->
resolve()
.catch (err) ->
reject "Push #{err}"
newPullRequest = (title, head) ->
new Promise (resolve, reject) ->
console.log "open PR #{title}"
github = new GitHub {token: process.env.GITHUB_TOKEN}
repo = github.getRepo repoName
repo.createPullRequest {title: title, head: head, base: 'main'}
.then ({data}) ->
resolve data
.catch (err) ->
reject "New PR #{err}"
findPullRequest = (head) ->
new Promise (resolve, reject) ->
console.log "find PR #{head}"
github = new GitHub {token: process.env.GITHUB_TOKEN}
repo = github.getRepo repoName
repo.listPullRequests {state: 'open', head: "galtx-centex:#{head}"}
.then ({data}) ->
resolve data[0] ? null
.catch (err) ->
reject "Find PR #{err}"
module.exports =
review: (action, args..., opts, callback) ->
clonePath = "#{repoPath}-#{opts.branch}-#{Date.now()}"
clone clonePath
.then (repo) ->
opts.repo = repo
findPullRequest opts.branch
.then (pr) ->
opts.pr = pr
opts.head =
if pr?.head?
"origin/#{pr.head.ref}"
else
'origin/main'
checkout opts.repo, opts.head
.then (ref) ->
new Promise (resolve, reject) ->
action clonePath, args..., (err) ->
unless err?
resolve()
else
reject err
.then () ->
commit opts.repo, opts.user, opts.message
.then (oid) ->
tag opts.repo, oid
.then (tag) ->
push opts.repo, tag, "refs/heads/#{opts.branch}"
.then () ->
if opts.pr?
new Promise (resolve, reject) -> resolve(opts.pr)
else
newPullRequest opts.message, opts.branch
.then (pr) ->
callback "Pull Request ready ➜ #{pr.html_url}"
.catch (err) ->
callback err
.finally ->
console.log "Remove #{clonePath}"
fse.remove clonePath
console.log "Done"
update: (action, args..., opts, callback) ->
clonePath = "#{repoPath}-#{opts.branch}-#{Date.now()}"
clone clonePath
.then (repo) ->
opts.repo = repo
checkout opts.repo, 'main'
.then (ref) ->
opts.ref = ref
new Promise (resolve, reject) ->
action clonePath, args..., (err) ->
unless err?
resolve()
else
reject err
.then () ->
commit opts.repo, opts.user, opts.message
.then (oid) ->
push opts.repo, opts.ref, opts.ref
.then () ->
callback null
.catch (err) ->
callback err
.finally ->
console.log "Remove #{clonePath}"
fse.remove clonePath
console.log "Done"
| 62449 | # Git commands
fs = require 'fs'
fse = require 'fs-extra'
path = require 'path'
Git = require 'nodegit'
GitHub = require 'github-api'
repoName = 'galtx-centex/galtx-centex.github.io'
repoURL = "https://github.com/#{repoName}.git"
repoPath = path.join __dirname, 'galtx-centex.org'
auth = (url, username) ->
Git.Cred.userpassPlaintextNew process.env.GITHUB_TOKEN, 'x-oauth-basic'
clone = (clonePath) ->
new Promise (resolve, reject) ->
console.log "clone #{repoURL} to #{clonePath}"
cloneOpts = fetchOpts: callbacks: credentials: auth
Git.Clone.clone repoURL, clonePath, cloneOpts
.then (repo) ->
resolve repo
.catch (err) ->
reject "Clone #{err}"
checkout = (repo, branch) ->
new Promise (resolve, reject) ->
ref = null
repo.getReference branch
.then (reference) ->
ref = reference
console.log "ref checkout #{ref}"
repo.checkoutRef ref
.then () ->
resolve ref
.catch (err) ->
reject "Checkout #{err}"
commit = (repo, user, message) ->
new Promise (resolve, reject) ->
ndx = null
tree = null
repo.refreshIndex()
.then (index) ->
ndx = index
ndx.addAll()
.then () ->
ndx.write()
ndx.writeTree()
.then (treeObj) ->
tree = treeObj
repo.getHeadCommit()
.then (parent) ->
console.log "commit '#{message}' from <#{user.name} #{user.email}>"
author = Git.Signature.now user.name, user.email
committer = Git.Signature.now 'RooBot', '<EMAIL>'
repo.createCommit 'HEAD', author, committer, message, tree, [parent]
.then (oid) ->
resolve oid
.catch (err) ->
reject "Commit #{err}"
tag = (repo, oid) ->
new Promise (resolve, reject) ->
console.log "tag #{oid}"
repo.createLightweightTag oid, "#{oid}-tag"
.then (reference) ->
resolve reference
.catch (err) ->
reject "Tag #{err}"
push = (repo, src, dst) ->
new Promise (resolve, reject) ->
refSpec = "#{src}:#{dst}"
repo.getRemote 'origin'
.then (remote) ->
console.log "push origin #{refSpec}"
pushOpts = callbacks: credentials: auth
remote.push ["#{refSpec}"], pushOpts
.then () ->
resolve()
.catch (err) ->
reject "Push #{err}"
newPullRequest = (title, head) ->
new Promise (resolve, reject) ->
console.log "open PR #{title}"
github = new GitHub {token: process.env.GITHUB_TOKEN}
repo = github.getRepo repoName
repo.createPullRequest {title: title, head: head, base: 'main'}
.then ({data}) ->
resolve data
.catch (err) ->
reject "New PR #{err}"
findPullRequest = (head) ->
new Promise (resolve, reject) ->
console.log "find PR #{head}"
github = new GitHub {token: process.env.GITHUB_TOKEN}
repo = github.getRepo repoName
repo.listPullRequests {state: 'open', head: "galtx-centex:#{head}"}
.then ({data}) ->
resolve data[0] ? null
.catch (err) ->
reject "Find PR #{err}"
module.exports =
review: (action, args..., opts, callback) ->
clonePath = "#{repoPath}-#{opts.branch}-#{Date.now()}"
clone clonePath
.then (repo) ->
opts.repo = repo
findPullRequest opts.branch
.then (pr) ->
opts.pr = pr
opts.head =
if pr?.head?
"origin/#{pr.head.ref}"
else
'origin/main'
checkout opts.repo, opts.head
.then (ref) ->
new Promise (resolve, reject) ->
action clonePath, args..., (err) ->
unless err?
resolve()
else
reject err
.then () ->
commit opts.repo, opts.user, opts.message
.then (oid) ->
tag opts.repo, oid
.then (tag) ->
push opts.repo, tag, "refs/heads/#{opts.branch}"
.then () ->
if opts.pr?
new Promise (resolve, reject) -> resolve(opts.pr)
else
newPullRequest opts.message, opts.branch
.then (pr) ->
callback "Pull Request ready ➜ #{pr.html_url}"
.catch (err) ->
callback err
.finally ->
console.log "Remove #{clonePath}"
fse.remove clonePath
console.log "Done"
update: (action, args..., opts, callback) ->
clonePath = "#{repoPath}-#{opts.branch}-#{Date.now()}"
clone clonePath
.then (repo) ->
opts.repo = repo
checkout opts.repo, 'main'
.then (ref) ->
opts.ref = ref
new Promise (resolve, reject) ->
action clonePath, args..., (err) ->
unless err?
resolve()
else
reject err
.then () ->
commit opts.repo, opts.user, opts.message
.then (oid) ->
push opts.repo, opts.ref, opts.ref
.then () ->
callback null
.catch (err) ->
callback err
.finally ->
console.log "Remove #{clonePath}"
fse.remove clonePath
console.log "Done"
| true | # Git commands
fs = require 'fs'
fse = require 'fs-extra'
path = require 'path'
Git = require 'nodegit'
GitHub = require 'github-api'
repoName = 'galtx-centex/galtx-centex.github.io'
repoURL = "https://github.com/#{repoName}.git"
repoPath = path.join __dirname, 'galtx-centex.org'
auth = (url, username) ->
Git.Cred.userpassPlaintextNew process.env.GITHUB_TOKEN, 'x-oauth-basic'
clone = (clonePath) ->
new Promise (resolve, reject) ->
console.log "clone #{repoURL} to #{clonePath}"
cloneOpts = fetchOpts: callbacks: credentials: auth
Git.Clone.clone repoURL, clonePath, cloneOpts
.then (repo) ->
resolve repo
.catch (err) ->
reject "Clone #{err}"
checkout = (repo, branch) ->
new Promise (resolve, reject) ->
ref = null
repo.getReference branch
.then (reference) ->
ref = reference
console.log "ref checkout #{ref}"
repo.checkoutRef ref
.then () ->
resolve ref
.catch (err) ->
reject "Checkout #{err}"
commit = (repo, user, message) ->
new Promise (resolve, reject) ->
ndx = null
tree = null
repo.refreshIndex()
.then (index) ->
ndx = index
ndx.addAll()
.then () ->
ndx.write()
ndx.writeTree()
.then (treeObj) ->
tree = treeObj
repo.getHeadCommit()
.then (parent) ->
console.log "commit '#{message}' from <#{user.name} #{user.email}>"
author = Git.Signature.now user.name, user.email
committer = Git.Signature.now 'RooBot', 'PI:EMAIL:<EMAIL>END_PI'
repo.createCommit 'HEAD', author, committer, message, tree, [parent]
.then (oid) ->
resolve oid
.catch (err) ->
reject "Commit #{err}"
tag = (repo, oid) ->
new Promise (resolve, reject) ->
console.log "tag #{oid}"
repo.createLightweightTag oid, "#{oid}-tag"
.then (reference) ->
resolve reference
.catch (err) ->
reject "Tag #{err}"
push = (repo, src, dst) ->
new Promise (resolve, reject) ->
refSpec = "#{src}:#{dst}"
repo.getRemote 'origin'
.then (remote) ->
console.log "push origin #{refSpec}"
pushOpts = callbacks: credentials: auth
remote.push ["#{refSpec}"], pushOpts
.then () ->
resolve()
.catch (err) ->
reject "Push #{err}"
newPullRequest = (title, head) ->
new Promise (resolve, reject) ->
console.log "open PR #{title}"
github = new GitHub {token: process.env.GITHUB_TOKEN}
repo = github.getRepo repoName
repo.createPullRequest {title: title, head: head, base: 'main'}
.then ({data}) ->
resolve data
.catch (err) ->
reject "New PR #{err}"
findPullRequest = (head) ->
new Promise (resolve, reject) ->
console.log "find PR #{head}"
github = new GitHub {token: process.env.GITHUB_TOKEN}
repo = github.getRepo repoName
repo.listPullRequests {state: 'open', head: "galtx-centex:#{head}"}
.then ({data}) ->
resolve data[0] ? null
.catch (err) ->
reject "Find PR #{err}"
module.exports =
review: (action, args..., opts, callback) ->
clonePath = "#{repoPath}-#{opts.branch}-#{Date.now()}"
clone clonePath
.then (repo) ->
opts.repo = repo
findPullRequest opts.branch
.then (pr) ->
opts.pr = pr
opts.head =
if pr?.head?
"origin/#{pr.head.ref}"
else
'origin/main'
checkout opts.repo, opts.head
.then (ref) ->
new Promise (resolve, reject) ->
action clonePath, args..., (err) ->
unless err?
resolve()
else
reject err
.then () ->
commit opts.repo, opts.user, opts.message
.then (oid) ->
tag opts.repo, oid
.then (tag) ->
push opts.repo, tag, "refs/heads/#{opts.branch}"
.then () ->
if opts.pr?
new Promise (resolve, reject) -> resolve(opts.pr)
else
newPullRequest opts.message, opts.branch
.then (pr) ->
callback "Pull Request ready ➜ #{pr.html_url}"
.catch (err) ->
callback err
.finally ->
console.log "Remove #{clonePath}"
fse.remove clonePath
console.log "Done"
update: (action, args..., opts, callback) ->
clonePath = "#{repoPath}-#{opts.branch}-#{Date.now()}"
clone clonePath
.then (repo) ->
opts.repo = repo
checkout opts.repo, 'main'
.then (ref) ->
opts.ref = ref
new Promise (resolve, reject) ->
action clonePath, args..., (err) ->
unless err?
resolve()
else
reject err
.then () ->
commit opts.repo, opts.user, opts.message
.then (oid) ->
push opts.repo, opts.ref, opts.ref
.then () ->
callback null
.catch (err) ->
callback err
.finally ->
console.log "Remove #{clonePath}"
fse.remove clonePath
console.log "Done"
|
[
{
"context": "eaders: \n \"X-TrackerToken\": @account.token.guid\n ajaxParams.url = params.url if params",
"end": 2193,
"score": 0.38875845074653625,
"start": 2189,
"tag": "PASSWORD",
"value": "guid"
},
{
"context": " \"name\", initials: \"initials\", \n \"to... | assets/javascripts/pivotaltracker_api.js.coffee | railsware/piro | 3 | root = global ? window
class root.PivotaltrackerApi
v3Url: "https://www.pivotaltracker.com/services/v3"
baseUrl: "https://www.pivotaltracker.com/services/v4"
# templates
projectsTemplate: [ "//project",
{ id: "id", name: "name", created_at: "created_at",
version: "version", iteration_length: "iteration_length", week_start_day: "week_start_day",
point_scale: "point_scale", account: "account", labels: "labels",
public: "public", use_https: "use_https", velocity_scheme: "velocity_scheme",
initial_velocity: "initial_velocity", current_velocity: "current_velocity", allow_attachments: "allow_attachments",
memberships: ["memberships/membership", {id: "id", role: "role",
person: {id: "member/person/id", email: "member/person/email", name: "member/person/name", initials: "member/person/initials"}}]
}]
storiesTemplate: [ "//story",
{ id: "id", project_id: "project_id", story_type: "story_type",
url: "url", estimate: "estimate", current_state: "current_state",
description: "description", name: "name",
requested_by: {id: "requested_by/person/id", name: "requested_by/person/name", initials: "requested_by/person/initials"},
owned_by: {id: "owned_by/person/id", name: "owned_by/person/name", initials: "owned_by/person/initials"},
created_at: "created_at", labels: "labels", deadline: "deadline",
comments: ["comments/comment", {id: "id", text: "text", created_at: "created_at",
author: {id: "author/person/id", name: "author/person/name", initials: "author/person/initials"}}],
tasks: ["tasks/task", {id: "id", description: "description", position: "position", complete: "complete", created_at: "created_at"}],
attachments: ["attachments/attachment", {id: "id", filename: "filename", uploaded_at: "uploaded_at", url: "url",
s3_resource: {url: "s3_resource/url", expires: "s3_resource/expires"},
uploaded_by: {id: "uploaded_by/person/id", name: "uploaded_by/person/name", initials: "uploaded_by/person/initials"}}]
}]
# init
constructor: (@account) ->
# constructor
sendPivotalRequest: (params) =>
ajaxParams =
timeout: 80000
dataType: 'xml'
headers:
"X-TrackerToken": @account.token.guid
ajaxParams.url = params.url if params.url?
ajaxParams.type = params.type if params.type?
ajaxParams.data = params.data if params.data?
ajaxParams.error = params.error if params.error?
ajaxParams.success = params.success if params.success?
ajaxParams.complete = params.complete if params.complete?
ajaxParams.beforeSend = params.beforeSend if params.beforeSend?
ajaxParams.processData = params.processData if params.processData?
ajaxParams.contentType = params.contentType if params.contentType?
$.ajax ajaxParams
getProjects: (params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects"
params.success = (data, textStatus, jqXHR) =>
projects = Jath.parse(@projectsTemplate, data)
successFunction.call(null, projects, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
getStories: (project, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{project.id}/stories"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
successFunction.call(null, project, stories, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
getStory: (storyId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/stories/#{storyId}"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
createStory: (projectId, params = {}) =>
successFunction = params.success
errorFunction = params.error
maxIterator = 8
# worst API (500 on new api)
params.url = "#{@v3Url}/projects/#{projectId}/stories"
#params.url = "#{@baseUrl}/projects/#{projectId}/stories"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
@_getStoryWithTimeout(story, successFunction, errorFunction, maxIterator)
@sendPivotalRequest(params)
updateStory: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}"
params.type = "PUT"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
updateStoryOld: (story, params = {}) =>
successFunction = params.success
params.url = "#{@v3Url}/projects/#{story.project_id}/stories/#{story.id}"
params.type = "PUT"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteStory: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
moveStory: (story, move, targetId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/moves?move[move]=#{move}&move[target]=#{targetId}"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
createTask: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/tasks"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
changeTask: (story, taskId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/tasks/#{taskId}"
params.type = "PUT"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteTask: (story, taskId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/tasks/#{taskId}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
createComment: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/comments"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteComment: (story, commentId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/comments/#{commentId}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
uploadAttachment: (story, formdata, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/attachments"
params.type = "POST"
params.data = formdata
params.processData = false
params.contentType = false
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteAttachment: (story, attachmentId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/attachments/#{attachmentId}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
# private
_getStoryWithTimeout: (story, successFunction, errorFunction, maxIterator) =>
setTimeout(=>
@getStory story.id,
success: (stories, textStatus, jqXHR) =>
successFunction.call(null, stories, textStatus, jqXHR) if successFunction?
error: =>
maxIterator--
if maxIterator > 0
@_getStoryWithTimeout(story, successFunction, errorFunction, maxIterator)
else
errorFunction.call(null) if errorFunction?
, 500)
# pivotal auth lib
class root.PivotaltrackerAuthLib
baseUrl: "https://www.pivotaltracker.com/services/v4"
constructor: (params = {}) ->
ajaxParams =
cache: false
global: false
dataType: 'xml'
url: "#{@baseUrl}/me"
success: (data, textStatus, jqXHR) ->
template = [ "//person",
{ id: "id", email: "email", name: "name", initials: "initials",
"token": {id: "token/id", guid: "token/guid"},
"time_zone": {name: "time_zone/name", code: "time_zone/code", offset: "time_zone/offset"}
}]
persons = Jath.parse(template, data)
person = if persons? && persons.length > 0 then persons[0] else null
params.success.call(null, person, textStatus, jqXHR) if params.success?
error: params.error
beforeSend: params.beforeSend
if params.username? && params.password?
ajaxParams.username = params.username
ajaxParams.password = params.password
ajaxParams.headers =
'Authorization': "Basic #{btoa(params.username + ":" + params.password)}"
else
ajaxParams.headers =
"X-TrackerToken": (params.token || null)
$.ajax ajaxParams | 171588 | root = global ? window
class root.PivotaltrackerApi
v3Url: "https://www.pivotaltracker.com/services/v3"
baseUrl: "https://www.pivotaltracker.com/services/v4"
# templates
projectsTemplate: [ "//project",
{ id: "id", name: "name", created_at: "created_at",
version: "version", iteration_length: "iteration_length", week_start_day: "week_start_day",
point_scale: "point_scale", account: "account", labels: "labels",
public: "public", use_https: "use_https", velocity_scheme: "velocity_scheme",
initial_velocity: "initial_velocity", current_velocity: "current_velocity", allow_attachments: "allow_attachments",
memberships: ["memberships/membership", {id: "id", role: "role",
person: {id: "member/person/id", email: "member/person/email", name: "member/person/name", initials: "member/person/initials"}}]
}]
storiesTemplate: [ "//story",
{ id: "id", project_id: "project_id", story_type: "story_type",
url: "url", estimate: "estimate", current_state: "current_state",
description: "description", name: "name",
requested_by: {id: "requested_by/person/id", name: "requested_by/person/name", initials: "requested_by/person/initials"},
owned_by: {id: "owned_by/person/id", name: "owned_by/person/name", initials: "owned_by/person/initials"},
created_at: "created_at", labels: "labels", deadline: "deadline",
comments: ["comments/comment", {id: "id", text: "text", created_at: "created_at",
author: {id: "author/person/id", name: "author/person/name", initials: "author/person/initials"}}],
tasks: ["tasks/task", {id: "id", description: "description", position: "position", complete: "complete", created_at: "created_at"}],
attachments: ["attachments/attachment", {id: "id", filename: "filename", uploaded_at: "uploaded_at", url: "url",
s3_resource: {url: "s3_resource/url", expires: "s3_resource/expires"},
uploaded_by: {id: "uploaded_by/person/id", name: "uploaded_by/person/name", initials: "uploaded_by/person/initials"}}]
}]
# init
constructor: (@account) ->
# constructor
sendPivotalRequest: (params) =>
ajaxParams =
timeout: 80000
dataType: 'xml'
headers:
"X-TrackerToken": @account.token.<PASSWORD>
ajaxParams.url = params.url if params.url?
ajaxParams.type = params.type if params.type?
ajaxParams.data = params.data if params.data?
ajaxParams.error = params.error if params.error?
ajaxParams.success = params.success if params.success?
ajaxParams.complete = params.complete if params.complete?
ajaxParams.beforeSend = params.beforeSend if params.beforeSend?
ajaxParams.processData = params.processData if params.processData?
ajaxParams.contentType = params.contentType if params.contentType?
$.ajax ajaxParams
getProjects: (params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects"
params.success = (data, textStatus, jqXHR) =>
projects = Jath.parse(@projectsTemplate, data)
successFunction.call(null, projects, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
getStories: (project, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{project.id}/stories"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
successFunction.call(null, project, stories, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
getStory: (storyId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/stories/#{storyId}"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
createStory: (projectId, params = {}) =>
successFunction = params.success
errorFunction = params.error
maxIterator = 8
# worst API (500 on new api)
params.url = "#{@v3Url}/projects/#{projectId}/stories"
#params.url = "#{@baseUrl}/projects/#{projectId}/stories"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
@_getStoryWithTimeout(story, successFunction, errorFunction, maxIterator)
@sendPivotalRequest(params)
updateStory: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}"
params.type = "PUT"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
updateStoryOld: (story, params = {}) =>
successFunction = params.success
params.url = "#{@v3Url}/projects/#{story.project_id}/stories/#{story.id}"
params.type = "PUT"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteStory: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
moveStory: (story, move, targetId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/moves?move[move]=#{move}&move[target]=#{targetId}"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
createTask: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/tasks"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
changeTask: (story, taskId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/tasks/#{taskId}"
params.type = "PUT"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteTask: (story, taskId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/tasks/#{taskId}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
createComment: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/comments"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteComment: (story, commentId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/comments/#{commentId}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
uploadAttachment: (story, formdata, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/attachments"
params.type = "POST"
params.data = formdata
params.processData = false
params.contentType = false
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteAttachment: (story, attachmentId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/attachments/#{attachmentId}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
# private
_getStoryWithTimeout: (story, successFunction, errorFunction, maxIterator) =>
setTimeout(=>
@getStory story.id,
success: (stories, textStatus, jqXHR) =>
successFunction.call(null, stories, textStatus, jqXHR) if successFunction?
error: =>
maxIterator--
if maxIterator > 0
@_getStoryWithTimeout(story, successFunction, errorFunction, maxIterator)
else
errorFunction.call(null) if errorFunction?
, 500)
# pivotal auth lib
class root.PivotaltrackerAuthLib
baseUrl: "https://www.pivotaltracker.com/services/v4"
constructor: (params = {}) ->
ajaxParams =
cache: false
global: false
dataType: 'xml'
url: "#{@baseUrl}/me"
success: (data, textStatus, jqXHR) ->
template = [ "//person",
{ id: "id", email: "email", name: "name", initials: "initials",
"token": {<KEY>: "<KEY>", guid: "token/<PASSWORD>"},
"time_zone": {name: "time_zone/name", code: "time_zone/code", offset: "time_zone/offset"}
}]
persons = Jath.parse(template, data)
person = if persons? && persons.length > 0 then persons[0] else null
params.success.call(null, person, textStatus, jqXHR) if params.success?
error: params.error
beforeSend: params.beforeSend
if params.username? && params.password?
ajaxParams.username = params.username
ajaxParams.password = params.<PASSWORD>
ajaxParams.headers =
'Authorization': "Basic #{btoa(params.username + ":" + params.password)}"
else
ajaxParams.headers =
"X-TrackerToken": (params.token || null)
$.ajax ajaxParams | true | root = global ? window
class root.PivotaltrackerApi
v3Url: "https://www.pivotaltracker.com/services/v3"
baseUrl: "https://www.pivotaltracker.com/services/v4"
# templates
projectsTemplate: [ "//project",
{ id: "id", name: "name", created_at: "created_at",
version: "version", iteration_length: "iteration_length", week_start_day: "week_start_day",
point_scale: "point_scale", account: "account", labels: "labels",
public: "public", use_https: "use_https", velocity_scheme: "velocity_scheme",
initial_velocity: "initial_velocity", current_velocity: "current_velocity", allow_attachments: "allow_attachments",
memberships: ["memberships/membership", {id: "id", role: "role",
person: {id: "member/person/id", email: "member/person/email", name: "member/person/name", initials: "member/person/initials"}}]
}]
storiesTemplate: [ "//story",
{ id: "id", project_id: "project_id", story_type: "story_type",
url: "url", estimate: "estimate", current_state: "current_state",
description: "description", name: "name",
requested_by: {id: "requested_by/person/id", name: "requested_by/person/name", initials: "requested_by/person/initials"},
owned_by: {id: "owned_by/person/id", name: "owned_by/person/name", initials: "owned_by/person/initials"},
created_at: "created_at", labels: "labels", deadline: "deadline",
comments: ["comments/comment", {id: "id", text: "text", created_at: "created_at",
author: {id: "author/person/id", name: "author/person/name", initials: "author/person/initials"}}],
tasks: ["tasks/task", {id: "id", description: "description", position: "position", complete: "complete", created_at: "created_at"}],
attachments: ["attachments/attachment", {id: "id", filename: "filename", uploaded_at: "uploaded_at", url: "url",
s3_resource: {url: "s3_resource/url", expires: "s3_resource/expires"},
uploaded_by: {id: "uploaded_by/person/id", name: "uploaded_by/person/name", initials: "uploaded_by/person/initials"}}]
}]
# init
constructor: (@account) ->
# constructor
sendPivotalRequest: (params) =>
ajaxParams =
timeout: 80000
dataType: 'xml'
headers:
"X-TrackerToken": @account.token.PI:PASSWORD:<PASSWORD>END_PI
ajaxParams.url = params.url if params.url?
ajaxParams.type = params.type if params.type?
ajaxParams.data = params.data if params.data?
ajaxParams.error = params.error if params.error?
ajaxParams.success = params.success if params.success?
ajaxParams.complete = params.complete if params.complete?
ajaxParams.beforeSend = params.beforeSend if params.beforeSend?
ajaxParams.processData = params.processData if params.processData?
ajaxParams.contentType = params.contentType if params.contentType?
$.ajax ajaxParams
getProjects: (params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects"
params.success = (data, textStatus, jqXHR) =>
projects = Jath.parse(@projectsTemplate, data)
successFunction.call(null, projects, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
getStories: (project, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{project.id}/stories"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
successFunction.call(null, project, stories, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
getStory: (storyId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/stories/#{storyId}"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
createStory: (projectId, params = {}) =>
successFunction = params.success
errorFunction = params.error
maxIterator = 8
# worst API (500 on new api)
params.url = "#{@v3Url}/projects/#{projectId}/stories"
#params.url = "#{@baseUrl}/projects/#{projectId}/stories"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
@_getStoryWithTimeout(story, successFunction, errorFunction, maxIterator)
@sendPivotalRequest(params)
updateStory: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}"
params.type = "PUT"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
updateStoryOld: (story, params = {}) =>
successFunction = params.success
params.url = "#{@v3Url}/projects/#{story.project_id}/stories/#{story.id}"
params.type = "PUT"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteStory: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
moveStory: (story, move, targetId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/moves?move[move]=#{move}&move[target]=#{targetId}"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
stories = Jath.parse(@storiesTemplate, data)
story = stories[0] if stories.length > 0
return false unless story.id?
successFunction.call(null, story, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
createTask: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/tasks"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
changeTask: (story, taskId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/tasks/#{taskId}"
params.type = "PUT"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteTask: (story, taskId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/tasks/#{taskId}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
createComment: (story, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/comments"
params.type = "POST"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteComment: (story, commentId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/comments/#{commentId}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
uploadAttachment: (story, formdata, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/attachments"
params.type = "POST"
params.data = formdata
params.processData = false
params.contentType = false
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
deleteAttachment: (story, attachmentId, params = {}) =>
successFunction = params.success
params.url = "#{@baseUrl}/projects/#{story.project_id}/stories/#{story.id}/attachments/#{attachmentId}"
params.type = "DELETE"
params.success = (data, textStatus, jqXHR) =>
successFunction.call(null, data, textStatus, jqXHR) if successFunction?
@sendPivotalRequest(params)
# private
_getStoryWithTimeout: (story, successFunction, errorFunction, maxIterator) =>
setTimeout(=>
@getStory story.id,
success: (stories, textStatus, jqXHR) =>
successFunction.call(null, stories, textStatus, jqXHR) if successFunction?
error: =>
maxIterator--
if maxIterator > 0
@_getStoryWithTimeout(story, successFunction, errorFunction, maxIterator)
else
errorFunction.call(null) if errorFunction?
, 500)
# pivotal auth lib
class root.PivotaltrackerAuthLib
baseUrl: "https://www.pivotaltracker.com/services/v4"
constructor: (params = {}) ->
ajaxParams =
cache: false
global: false
dataType: 'xml'
url: "#{@baseUrl}/me"
success: (data, textStatus, jqXHR) ->
template = [ "//person",
{ id: "id", email: "email", name: "name", initials: "initials",
"token": {PI:KEY:<KEY>END_PI: "PI:KEY:<KEY>END_PI", guid: "token/PI:KEY:<PASSWORD>END_PI"},
"time_zone": {name: "time_zone/name", code: "time_zone/code", offset: "time_zone/offset"}
}]
persons = Jath.parse(template, data)
person = if persons? && persons.length > 0 then persons[0] else null
params.success.call(null, person, textStatus, jqXHR) if params.success?
error: params.error
beforeSend: params.beforeSend
if params.username? && params.password?
ajaxParams.username = params.username
ajaxParams.password = params.PI:PASSWORD:<PASSWORD>END_PI
ajaxParams.headers =
'Authorization': "Basic #{btoa(params.username + ":" + params.password)}"
else
ajaxParams.headers =
"X-TrackerToken": (params.token || null)
$.ajax ajaxParams |
[
{
"context": "ays data from linode longview on the desktop.\n# by telega (tom@telega.org)\n\n# apiKeys should be a comma sep",
"end": 71,
"score": 0.9997286796569824,
"start": 65,
"tag": "USERNAME",
"value": "telega"
},
{
"context": "from linode longview on the desktop.\n# by telega ... | longviewer-widget.coffee | telega/longviewer-widget | 1 | # Widget displays data from linode longview on the desktop.
# by telega (tom@telega.org)
# apiKeys should be a comma separated list of longview api keys, from the longview dashboard (https://manager.linode.com/longview)
# for example:
# apiKeys = ["97777777-BBBB-DDDD-34444444444444","F222222222-BBBB-1111-EEEEEEEEEEEE"]
apiKeys = [""]
commandString = "/usr/local/bin/node ./longviewer-widget.widget/lib/longview-data.js "
# this is the shell command that gets executed every time this widget refreshes
command: commandString+apiKeys.join(' ')+" -j"
# the refresh frequency in milliseconds
refreshFrequency: 30000
render: (output) -> """
<div></div>
"""
update: (output, domEl) ->
el = $(domEl)
el.html ''
data = JSON.parse(output)
for key in data
el.append """
<div class = 'linode'><h2 class='rainbow'>#{key.hostname}</h2><br>
<span class = 'label'>Distro: </span>#{key.dist} #{key.distversion} <br>
<span class = 'label'>Available Updates: </span>#{key.packageUpdates} <br>
<span class = 'label'>Uptime: </span>#{key.uptime}<br>
<span class = 'label'>CPU: </span>#{key.cpuType}<br>
<span class = 'label'>CPU Usage: </span>#{key.cpuTotal} <span class = 'label'> Load: </span> #{key.load} <br>
<span class = 'label'>Memory: </span>#{key.realMemUsed} / #{key.realMem} ( #{key.realMemUsedPercent} )<br>
<span class = 'label'>Disk: </span>#{key.fsUsed} / #{key.fsFree} (#{key.fsUsedPercent})<br>
<span class = 'label'>Network In: </span>#{key.rxBytes} <span class = "label">Out: </span>#{key.txBytes}
"""
if key.lastUpdated != 0
el.append """
<span class = 'warn'>#{key.lastUpdated}</span>
"""
el.append """
</div>
"""
# the CSS style for this widget edit the .rainbow class if you want something simpler!
style: """
top:10px
left:100px
font-family:menlo
color: #fff
-webkit-font-smoothing: antialiased
h2
font-weight: bold
display: inline-block
margin-bottom: 4px
font-size: 22px
.linode
margin-top:10px
.label
font-weight: bold
.warn
color: cyan
.rainbow
background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #ff6b6b), color-stop(0.3, #ecf993), color-stop(0.5, #90f98e), color-stop(0.7, #70a8d3),color-stop(1, #bcaee8) )
color: transparent
-webkit-background-clip: text
""" | 59698 | # Widget displays data from linode longview on the desktop.
# by telega (<EMAIL>)
# apiKeys should be a comma separated list of longview api keys, from the longview dashboard (https://manager.linode.com/longview)
# for example:
# apiKeys = ["<KEY>","<KEY>"]
apiKeys = [""]
commandString = "/usr/local/bin/node ./longviewer-widget.widget/lib/longview-data.js "
# this is the shell command that gets executed every time this widget refreshes
command: commandString+apiKeys.join(' ')+" -j"
# the refresh frequency in milliseconds
refreshFrequency: 30000
render: (output) -> """
<div></div>
"""
update: (output, domEl) ->
el = $(domEl)
el.html ''
data = JSON.parse(output)
for key in data
el.append """
<div class = 'linode'><h2 class='rainbow'>#{key.hostname}</h2><br>
<span class = 'label'>Distro: </span>#{key.dist} #{key.distversion} <br>
<span class = 'label'>Available Updates: </span>#{key.packageUpdates} <br>
<span class = 'label'>Uptime: </span>#{key.uptime}<br>
<span class = 'label'>CPU: </span>#{key.cpuType}<br>
<span class = 'label'>CPU Usage: </span>#{key.cpuTotal} <span class = 'label'> Load: </span> #{key.load} <br>
<span class = 'label'>Memory: </span>#{key.realMemUsed} / #{key.realMem} ( #{key.realMemUsedPercent} )<br>
<span class = 'label'>Disk: </span>#{key.fsUsed} / #{key.fsFree} (#{key.fsUsedPercent})<br>
<span class = 'label'>Network In: </span>#{key.rxBytes} <span class = "label">Out: </span>#{key.txBytes}
"""
if key.lastUpdated != 0
el.append """
<span class = 'warn'>#{key.lastUpdated}</span>
"""
el.append """
</div>
"""
# the CSS style for this widget edit the .rainbow class if you want something simpler!
style: """
top:10px
left:100px
font-family:menlo
color: #fff
-webkit-font-smoothing: antialiased
h2
font-weight: bold
display: inline-block
margin-bottom: 4px
font-size: 22px
.linode
margin-top:10px
.label
font-weight: bold
.warn
color: cyan
.rainbow
background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #ff6b6b), color-stop(0.3, #ecf993), color-stop(0.5, #90f98e), color-stop(0.7, #70a8d3),color-stop(1, #bcaee8) )
color: transparent
-webkit-background-clip: text
""" | true | # Widget displays data from linode longview on the desktop.
# by telega (PI:EMAIL:<EMAIL>END_PI)
# apiKeys should be a comma separated list of longview api keys, from the longview dashboard (https://manager.linode.com/longview)
# for example:
# apiKeys = ["PI:KEY:<KEY>END_PI","PI:KEY:<KEY>END_PI"]
apiKeys = [""]
commandString = "/usr/local/bin/node ./longviewer-widget.widget/lib/longview-data.js "
# this is the shell command that gets executed every time this widget refreshes
command: commandString+apiKeys.join(' ')+" -j"
# the refresh frequency in milliseconds
refreshFrequency: 30000
render: (output) -> """
<div></div>
"""
update: (output, domEl) ->
el = $(domEl)
el.html ''
data = JSON.parse(output)
for key in data
el.append """
<div class = 'linode'><h2 class='rainbow'>#{key.hostname}</h2><br>
<span class = 'label'>Distro: </span>#{key.dist} #{key.distversion} <br>
<span class = 'label'>Available Updates: </span>#{key.packageUpdates} <br>
<span class = 'label'>Uptime: </span>#{key.uptime}<br>
<span class = 'label'>CPU: </span>#{key.cpuType}<br>
<span class = 'label'>CPU Usage: </span>#{key.cpuTotal} <span class = 'label'> Load: </span> #{key.load} <br>
<span class = 'label'>Memory: </span>#{key.realMemUsed} / #{key.realMem} ( #{key.realMemUsedPercent} )<br>
<span class = 'label'>Disk: </span>#{key.fsUsed} / #{key.fsFree} (#{key.fsUsedPercent})<br>
<span class = 'label'>Network In: </span>#{key.rxBytes} <span class = "label">Out: </span>#{key.txBytes}
"""
if key.lastUpdated != 0
el.append """
<span class = 'warn'>#{key.lastUpdated}</span>
"""
el.append """
</div>
"""
# the CSS style for this widget edit the .rainbow class if you want something simpler!
style: """
top:10px
left:100px
font-family:menlo
color: #fff
-webkit-font-smoothing: antialiased
h2
font-weight: bold
display: inline-block
margin-bottom: 4px
font-size: 22px
.linode
margin-top:10px
.label
font-weight: bold
.warn
color: cyan
.rainbow
background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #ff6b6b), color-stop(0.3, #ecf993), color-stop(0.5, #90f98e), color-stop(0.7, #70a8d3),color-stop(1, #bcaee8) )
color: transparent
-webkit-background-clip: text
""" |
[
{
"context": "re start\n\t#after ()->server.close()\n\tuser_= {_id:'5adcefbaed9d970d42d33d65'}\n\n\tdescribe 'should get user goals',()->\n\t\tnum =",
"end": 1324,
"score": 0.9020510315895081,
"start": 1300,
"tag": "PASSWORD",
"value": "5adcefbaed9d970d42d33d65"
}
] | server/DB/user/test/user.coffee | DaniloZZZ/GoalNet | 0 | baseTests = require('../../test/baseNode.coffee')
UserNode =require '../userNode.coffee'
GoalNode =require '../../goal/goalNode.coffee'
chai = require 'chai'
chai.should()
axios = require 'axios'
express = require 'express'
log4js = require 'log4js'
mongoose = require('mongoose')
logger = log4js.getLogger('test')
logger.level = 'debug'
logger.info "hello tester!"
app = express()
app.use express.json()
app.use express.urlencoded()
mongoCred=process.env.MONGO_CREDENTIALS
mongoose.connect "mongodb://"+mongoCred+
"@lykov.tech:27017/goalnet"
user = new UserNode(app)
goal = new GoalNode(app)
port = 3030
host = 'localhost'
endpoint = "http://#{host}:#{port}"
server=null
start=()->
server = app.listen port, ->
logger.info 'Test app is listening '+ endpoint
return
describe 'userNode, basic', ->
before start
after ()->server.close()
user_= {}
it 'should have an appropriate endpoint',->
user.path.should.equal '/user'
it 'should save user',(done)->
baseTests.set(user,props: name:'user',lname:'test')()
.then (u)=>
user_=u
done()
return
it 'should get user',()->
baseTests.get(user,id:user_._id)()
it 'should delete user',()->
baseTests.delete( user,id:user_._id)()
describe.only 'userNode, specific', ->
before start
#after ()->server.close()
user_= {_id:'5adcefbaed9d970d42d33d65'}
describe 'should get user goals',()->
num = 2
it 'saves some goals for user', (done)->
cnt = 0
g=(num_)->
for i in [1..num_]
f = baseTests.set goal,
props:
title:'testgoal'+i
parent: item:user_._id,kind:'user'
f().then ()->
cnt+=1
if cnt==num
logger.warn 'hfalhl'
done()
g num
return
it 'gets the same number of goals', (done)->
axios.get(
endpoint+'/user/goals/'
params:
id:user_._id
)
.then (resp)->
logger.debug resp.data
resp.data.length.should.equal num
done()
.catch (err)=> logger.error err
return
| 137055 | baseTests = require('../../test/baseNode.coffee')
UserNode =require '../userNode.coffee'
GoalNode =require '../../goal/goalNode.coffee'
chai = require 'chai'
chai.should()
axios = require 'axios'
express = require 'express'
log4js = require 'log4js'
mongoose = require('mongoose')
logger = log4js.getLogger('test')
logger.level = 'debug'
logger.info "hello tester!"
app = express()
app.use express.json()
app.use express.urlencoded()
mongoCred=process.env.MONGO_CREDENTIALS
mongoose.connect "mongodb://"+mongoCred+
"@lykov.tech:27017/goalnet"
user = new UserNode(app)
goal = new GoalNode(app)
port = 3030
host = 'localhost'
endpoint = "http://#{host}:#{port}"
server=null
start=()->
server = app.listen port, ->
logger.info 'Test app is listening '+ endpoint
return
describe 'userNode, basic', ->
before start
after ()->server.close()
user_= {}
it 'should have an appropriate endpoint',->
user.path.should.equal '/user'
it 'should save user',(done)->
baseTests.set(user,props: name:'user',lname:'test')()
.then (u)=>
user_=u
done()
return
it 'should get user',()->
baseTests.get(user,id:user_._id)()
it 'should delete user',()->
baseTests.delete( user,id:user_._id)()
describe.only 'userNode, specific', ->
before start
#after ()->server.close()
user_= {_id:'<PASSWORD>'}
describe 'should get user goals',()->
num = 2
it 'saves some goals for user', (done)->
cnt = 0
g=(num_)->
for i in [1..num_]
f = baseTests.set goal,
props:
title:'testgoal'+i
parent: item:user_._id,kind:'user'
f().then ()->
cnt+=1
if cnt==num
logger.warn 'hfalhl'
done()
g num
return
it 'gets the same number of goals', (done)->
axios.get(
endpoint+'/user/goals/'
params:
id:user_._id
)
.then (resp)->
logger.debug resp.data
resp.data.length.should.equal num
done()
.catch (err)=> logger.error err
return
| true | baseTests = require('../../test/baseNode.coffee')
UserNode =require '../userNode.coffee'
GoalNode =require '../../goal/goalNode.coffee'
chai = require 'chai'
chai.should()
axios = require 'axios'
express = require 'express'
log4js = require 'log4js'
mongoose = require('mongoose')
logger = log4js.getLogger('test')
logger.level = 'debug'
logger.info "hello tester!"
app = express()
app.use express.json()
app.use express.urlencoded()
mongoCred=process.env.MONGO_CREDENTIALS
mongoose.connect "mongodb://"+mongoCred+
"@lykov.tech:27017/goalnet"
user = new UserNode(app)
goal = new GoalNode(app)
port = 3030
host = 'localhost'
endpoint = "http://#{host}:#{port}"
server=null
start=()->
server = app.listen port, ->
logger.info 'Test app is listening '+ endpoint
return
describe 'userNode, basic', ->
before start
after ()->server.close()
user_= {}
it 'should have an appropriate endpoint',->
user.path.should.equal '/user'
it 'should save user',(done)->
baseTests.set(user,props: name:'user',lname:'test')()
.then (u)=>
user_=u
done()
return
it 'should get user',()->
baseTests.get(user,id:user_._id)()
it 'should delete user',()->
baseTests.delete( user,id:user_._id)()
describe.only 'userNode, specific', ->
before start
#after ()->server.close()
user_= {_id:'PI:PASSWORD:<PASSWORD>END_PI'}
describe 'should get user goals',()->
num = 2
it 'saves some goals for user', (done)->
cnt = 0
g=(num_)->
for i in [1..num_]
f = baseTests.set goal,
props:
title:'testgoal'+i
parent: item:user_._id,kind:'user'
f().then ()->
cnt+=1
if cnt==num
logger.warn 'hfalhl'
done()
g num
return
it 'gets the same number of goals', (done)->
axios.get(
endpoint+'/user/goals/'
params:
id:user_._id
)
.then (resp)->
logger.debug resp.data
resp.data.length.should.equal num
done()
.catch (err)=> logger.error err
return
|
[
{
"context": "icons/codeship@2x.png'\n\n @_fields.push\n key: 'webhookUrl'\n type: 'text'\n readOnly: true\n descript",
"end": 1648,
"score": 0.8161247968673706,
"start": 1638,
"tag": "KEY",
"value": "webhookUrl"
}
] | src/services/codeship.coffee | jianliaoim/talk-services | 40 | Promise = require 'bluebird'
marked = require 'marked'
util = require '../util'
###*
* Define handler when receive incoming webhook from jenkins
* @param {Object} req Express request object
* @param {Object} res Express response object
* @param {Function} callback
* @return {Promise}
###
_receiveWebhook = ({body}) ->
build = body?.build
return unless build
message = {}
attachment = category: 'quote', data: {}
projectName = if build.project_name then "[#{build.project_name}] " else ''
projectUrl = build.build_url
author = build.committer
authorName = if author then "#{author} " else ''
commitUrl = build.commit_url
status = build.status
switch status
when 'testing'
attachment.data.title = "#{projectName}new commits on testing stage"
when 'success'
attachment.data.title = "#{projectName}new commits on success stage"
else return false
attachment.data.text =
"""
<a href="#{commitUrl}" target="_blank"><code>#{build.commit_id[...6]}:</code></a> #{build.message}<br>
"""
attachment.data.redirectUrl = projectUrl
message.attachments = [attachment]
message
module.exports = ->
@title = 'codeship'
@template = 'webhook'
@summary = util.i18n
zh: '持续集成与部署平台'
en: 'Codeship is a fast and secure hosted Continuous Delivery platform that scales with your needs.'
@description = util.i18n
zh: 'Codeship 是一个持续集成与部署平台,为你的代码提供一站式测试部署服务'
en: 'Codeship is a fast and secure hosted Continuous Delivery platform that scales with your needs.'
@iconUrl = util.static 'images/icons/codeship@2x.png'
@_fields.push
key: 'webhookUrl'
type: 'text'
readOnly: true
description: util.i18n
zh: '复制 web hook 地址到你的 Codeship 当中使用。'
en: 'Copy this web hook to your Codeship server to use it.'
# Apply function on `webhook` event
@registerEvent 'service.webhook', _receiveWebhook
| 22479 | Promise = require 'bluebird'
marked = require 'marked'
util = require '../util'
###*
* Define handler when receive incoming webhook from jenkins
* @param {Object} req Express request object
* @param {Object} res Express response object
* @param {Function} callback
* @return {Promise}
###
_receiveWebhook = ({body}) ->
build = body?.build
return unless build
message = {}
attachment = category: 'quote', data: {}
projectName = if build.project_name then "[#{build.project_name}] " else ''
projectUrl = build.build_url
author = build.committer
authorName = if author then "#{author} " else ''
commitUrl = build.commit_url
status = build.status
switch status
when 'testing'
attachment.data.title = "#{projectName}new commits on testing stage"
when 'success'
attachment.data.title = "#{projectName}new commits on success stage"
else return false
attachment.data.text =
"""
<a href="#{commitUrl}" target="_blank"><code>#{build.commit_id[...6]}:</code></a> #{build.message}<br>
"""
attachment.data.redirectUrl = projectUrl
message.attachments = [attachment]
message
module.exports = ->
@title = 'codeship'
@template = 'webhook'
@summary = util.i18n
zh: '持续集成与部署平台'
en: 'Codeship is a fast and secure hosted Continuous Delivery platform that scales with your needs.'
@description = util.i18n
zh: 'Codeship 是一个持续集成与部署平台,为你的代码提供一站式测试部署服务'
en: 'Codeship is a fast and secure hosted Continuous Delivery platform that scales with your needs.'
@iconUrl = util.static 'images/icons/codeship@2x.png'
@_fields.push
key: '<KEY>'
type: 'text'
readOnly: true
description: util.i18n
zh: '复制 web hook 地址到你的 Codeship 当中使用。'
en: 'Copy this web hook to your Codeship server to use it.'
# Apply function on `webhook` event
@registerEvent 'service.webhook', _receiveWebhook
| true | Promise = require 'bluebird'
marked = require 'marked'
util = require '../util'
###*
* Define handler when receive incoming webhook from jenkins
* @param {Object} req Express request object
* @param {Object} res Express response object
* @param {Function} callback
* @return {Promise}
###
_receiveWebhook = ({body}) ->
build = body?.build
return unless build
message = {}
attachment = category: 'quote', data: {}
projectName = if build.project_name then "[#{build.project_name}] " else ''
projectUrl = build.build_url
author = build.committer
authorName = if author then "#{author} " else ''
commitUrl = build.commit_url
status = build.status
switch status
when 'testing'
attachment.data.title = "#{projectName}new commits on testing stage"
when 'success'
attachment.data.title = "#{projectName}new commits on success stage"
else return false
attachment.data.text =
"""
<a href="#{commitUrl}" target="_blank"><code>#{build.commit_id[...6]}:</code></a> #{build.message}<br>
"""
attachment.data.redirectUrl = projectUrl
message.attachments = [attachment]
message
module.exports = ->
@title = 'codeship'
@template = 'webhook'
@summary = util.i18n
zh: '持续集成与部署平台'
en: 'Codeship is a fast and secure hosted Continuous Delivery platform that scales with your needs.'
@description = util.i18n
zh: 'Codeship 是一个持续集成与部署平台,为你的代码提供一站式测试部署服务'
en: 'Codeship is a fast and secure hosted Continuous Delivery platform that scales with your needs.'
@iconUrl = util.static 'images/icons/codeship@2x.png'
@_fields.push
key: 'PI:KEY:<KEY>END_PI'
type: 'text'
readOnly: true
description: util.i18n
zh: '复制 web hook 地址到你的 Codeship 当中使用。'
en: 'Copy this web hook to your Codeship server to use it.'
# Apply function on `webhook` event
@registerEvent 'service.webhook', _receiveWebhook
|
[
{
"context": "gnored.\n '''\n\n tokens: ['COMPARE', 'UNARY_MATH', '&&', '||']\n\n lintToken: (token, tokenApi) -",
"end": 442,
"score": 0.7672588229179382,
"start": 432,
"tag": "KEY",
"value": "UNARY_MATH"
},
{
"context": "ken, tokenApi) ->\n config = tokenApi... | src/rules/prefer_english_operator.coffee | Vulwsztyn/coffeelint | 709 | module.exports = class PreferEnglishOperator
rule:
name: 'prefer_english_operator'
level: 'ignore'
message: 'Don\'t use &&, ||, ==, !=, or !'
doubleNotLevel: 'ignore'
description: '''
This rule prohibits &&, ||, ==, != and !.
Use and, or, is, isnt, and not instead.
!! for converting to a boolean is ignored.
'''
tokens: ['COMPARE', 'UNARY_MATH', '&&', '||']
lintToken: (token, tokenApi) ->
config = tokenApi.config[@rule.name]
level = config.level
# Compare the actual token with the lexed token.
{ first_column, last_column } = token[2]
line = tokenApi.lines[tokenApi.lineNumber]
actual_token = line[first_column..last_column]
context =
switch actual_token
when '==' then 'Replace "==" with "is"'
when '!=' then 'Replace "!=" with "isnt"'
when '||' then 'Replace "||" with "or"'
when '&&' then 'Replace "&&" with "and"'
when '!'
# `not not expression` seems awkward, so `!!expression`
# gets special handling.
if tokenApi.peek(1)?[0] is 'UNARY_MATH'
level = config.doubleNotLevel
'"?" is usually better than "!!"'
else if tokenApi.peek(-1)?[0] is 'UNARY_MATH'
# Ignore the 2nd half of the double not
undefined
else
'Replace "!" with "not"'
else undefined
if context?
{ level, context }
| 221921 | module.exports = class PreferEnglishOperator
rule:
name: 'prefer_english_operator'
level: 'ignore'
message: 'Don\'t use &&, ||, ==, !=, or !'
doubleNotLevel: 'ignore'
description: '''
This rule prohibits &&, ||, ==, != and !.
Use and, or, is, isnt, and not instead.
!! for converting to a boolean is ignored.
'''
tokens: ['COMPARE', '<KEY>', '&&', '||']
lintToken: (token, tokenApi) ->
config = tokenApi.config[@rule.name]
level = config.level
# Compare the actual token with the lexed token.
{ first_column, last_column } = token[2]
line = tokenApi.lines[tokenApi.lineNumber]
actual_token = line[first_column..last_column]
context =
switch actual_token
when '==' then 'Replace "==" with "is"'
when '!=' then 'Replace "!=" with "isnt"'
when '||' then 'Replace "||" with "or"'
when '&&' then 'Replace "&&" with "and"'
when '!'
# `not not expression` seems awkward, so `!!expression`
# gets special handling.
if tokenApi.peek(1)?[0] is 'UNARY_MATH'
level = config.doubleNotLevel
'"?" is usually better than "!!"'
else if tokenApi.peek(-1)?[0] is 'UNARY_MATH'
# Ignore the 2nd half of the double not
undefined
else
'Replace "!" with "not"'
else undefined
if context?
{ level, context }
| true | module.exports = class PreferEnglishOperator
rule:
name: 'prefer_english_operator'
level: 'ignore'
message: 'Don\'t use &&, ||, ==, !=, or !'
doubleNotLevel: 'ignore'
description: '''
This rule prohibits &&, ||, ==, != and !.
Use and, or, is, isnt, and not instead.
!! for converting to a boolean is ignored.
'''
tokens: ['COMPARE', 'PI:KEY:<KEY>END_PI', '&&', '||']
lintToken: (token, tokenApi) ->
config = tokenApi.config[@rule.name]
level = config.level
# Compare the actual token with the lexed token.
{ first_column, last_column } = token[2]
line = tokenApi.lines[tokenApi.lineNumber]
actual_token = line[first_column..last_column]
context =
switch actual_token
when '==' then 'Replace "==" with "is"'
when '!=' then 'Replace "!=" with "isnt"'
when '||' then 'Replace "||" with "or"'
when '&&' then 'Replace "&&" with "and"'
when '!'
# `not not expression` seems awkward, so `!!expression`
# gets special handling.
if tokenApi.peek(1)?[0] is 'UNARY_MATH'
level = config.doubleNotLevel
'"?" is usually better than "!!"'
else if tokenApi.peek(-1)?[0] is 'UNARY_MATH'
# Ignore the 2nd half of the double not
undefined
else
'Replace "!" with "not"'
else undefined
if context?
{ level, context }
|
[
{
"context": "\n users: -> []\n admins: -> 'Jay Ongg','Mel M'\n authorizedUsers -> ['Jay Ong",
"end": 223,
"score": 0.9992373585700989,
"start": 215,
"tag": "NAME",
"value": "Jay Ongg"
},
{
"context": " users: -> []\n admins: -> 'Jay Ongg'... | mock-robot.coffee | jayongg/TeamsHubot | 1 | class MockRobot
constructor: ->
@name = "robot"
@logger =
info: ->
warn: ->
@brain =
userForId: -> {}
users: -> []
admins: -> 'Jay Ongg','Mel M'
authorizedUsers -> ['Jay Ongg', 'Bob Blue', 'Mel M']
module.exports = MockRobot | 122858 | class MockRobot
constructor: ->
@name = "robot"
@logger =
info: ->
warn: ->
@brain =
userForId: -> {}
users: -> []
admins: -> '<NAME>','<NAME>'
authorizedUsers -> ['<NAME>', '<NAME>', '<NAME>']
module.exports = MockRobot | true | class MockRobot
constructor: ->
@name = "robot"
@logger =
info: ->
warn: ->
@brain =
userForId: -> {}
users: -> []
admins: -> 'PI:NAME:<NAME>END_PI','PI:NAME:<NAME>END_PI'
authorizedUsers -> ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
module.exports = MockRobot |
[
{
"context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @",
"end": 33,
"score": 0.9998965859413147,
"start": 17,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
},
{
"context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki... | src/database/index.coffee | AbdelhakimRafik/Pharmalogy-API | 0 | ###
* @author Abdelhakim RAFIK
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 Abdelhakim RAFIK
* @date Mar 2021
###
Sequelize = require 'sequelize'
###
# establish a connection with given database
# @param config object contains needed configuration for connection
###
module.exports = (config) ->
# export sequelize instance
module.exports.sequelize = new Sequelize config.dbName, config.username, config.password,
host: config.host
dialect: config.dialect
| 68389 | ###
* @author <NAME>
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 <NAME>
* @date Mar 2021
###
Sequelize = require 'sequelize'
###
# establish a connection with given database
# @param config object contains needed configuration for connection
###
module.exports = (config) ->
# export sequelize instance
module.exports.sequelize = new Sequelize config.dbName, config.username, config.password,
host: config.host
dialect: config.dialect
| 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
###
Sequelize = require 'sequelize'
###
# establish a connection with given database
# @param config object contains needed configuration for connection
###
module.exports = (config) ->
# export sequelize instance
module.exports.sequelize = new Sequelize config.dbName, config.username, config.password,
host: config.host
dialect: config.dialect
|
[
{
"context": " initializeSubscription: ->\n routingKey = \"changes.project.#{@scope.projectId}.issues\"\n @events.subscrib",
"end": 10814,
"score": 0.879115879535675,
"start": 10796,
"tag": "KEY",
"value": "changes.project.#{"
},
{
"context": " routingKey = \"changes.p... | app/coffee/modules/issues/list.coffee | threefoldtech/Threefold-Circles-front | 0 | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/issues/list.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
trim = @.taiga.trim
toString = @.taiga.toString
joinStr = @.taiga.joinStr
groupBy = @.taiga.groupBy
bindOnce = @.taiga.bindOnce
debounceLeading = @.taiga.debounceLeading
startswith = @.taiga.startswith
bindMethods = @.taiga.bindMethods
debounceLeading = @.taiga.debounceLeading
module = angular.module("taigaIssues")
#############################################################################
## Issues Controller
#############################################################################
class IssuesController extends mixOf(taiga.Controller, taiga.PageMixin, taiga.FiltersMixin)
@.$inject = [
"$scope",
"$rootScope",
"$tgRepo",
"$tgConfirm",
"$tgResources",
"$tgUrls",
"$routeParams",
"$q",
"$tgLocation",
"tgAppMetaService",
"$tgNavUrls",
"$tgEvents",
"$tgAnalytics",
"$translate",
"tgErrorHandlingService",
"$tgStorage",
"tgFilterRemoteStorageService",
"tgProjectService",
"tgUserActivityService"
]
filtersHashSuffix: "issues-filters"
myFiltersHashSuffix: "issues-my-filters"
excludePrefix: "exclude_"
filterCategories: [
"tags",
"status",
"type",
"severity",
"priority",
"assigned_to",
"owner",
"role",
]
constructor: (@scope, @rootscope, @repo, @confirm, @rs, @urls, @params, @q, @location, @appMetaService,
@navUrls, @events, @analytics, @translate, @errorHandlingService, @storage, @filterRemoteStorageService, @projectService) ->
bindMethods(@)
@scope.sectionName = @translate.instant("PROJECT.SECTION.ISSUES")
@.voting = false
return if @.applyStoredFilters(@params.pslug, @.filtersHashSuffix)
promise = @.loadInitialData()
# On Success
promise.then =>
title = @translate.instant("ISSUES.PAGE_TITLE", {projectName: @scope.project.name})
description = @translate.instant("ISSUES.PAGE_DESCRIPTION", {
projectName: @scope.project.name,
projectDescription: @scope.project.description
})
@appMetaService.setAll(title, description)
# On Error
promise.then null, @.onInitialDataError.bind(@)
@scope.$on "issueform:new:success", =>
@analytics.trackEvent("issue", "create", "create issue on issues list", 1)
@.loadIssues()
@scope.$on "assigned-to:changed", =>
@.generateFilters()
if @.isFilterDataTypeSelected('assigned_to') ||\
@.isFilterDataTypeSelected('role') ||\
@.isOrderedBy('assigned_to') || @.isOrderedBy('modified')
@.loadIssues()
@scope.$on "status:changed", =>
@.generateFilters()
if @.isFilterDataTypeSelected('status') ||\
@.isOrderedBy('status') || @.isOrderedBy('modified')
@.loadIssues()
isOrderedBy: (fieldName) ->
pattern = new RegExp("-*"+fieldName)
return pattern.test(@location.search().order_by)
changeQ: (q) ->
@.unselectFilter("page")
@.replaceFilter("q", q)
@.loadIssues()
@.generateFilters()
removeFilter: (filter) ->
@.unselectFilter("page")
@.unselectFilter(filter.dataType, filter.id, false, filter.mode)
@.loadIssues()
@.generateFilters()
addFilter: (newFilter) ->
@.unselectFilter("page")
@.selectFilter(newFilter.category.dataType, newFilter.filter.id, false, newFilter.mode)
@.loadIssues()
@.generateFilters()
selectCustomFilter: (customFilter) ->
orderBy = @location.search().order_by
if orderBy
customFilter.filter.order_by = orderBy
@.unselectFilter("page")
@.replaceAllFilters(customFilter.filter)
@.loadIssues()
@.generateFilters()
removeCustomFilter: (customFilter) ->
@filterRemoteStorageService.getFilters(@scope.projectId, @.myFiltersHashSuffix).then (userFilters) =>
delete userFilters[customFilter.id]
@filterRemoteStorageService.storeFilters(@scope.projectId, userFilters, @.myFiltersHashSuffix).then(@.generateFilters)
isFilterDataTypeSelected: (filterDataType) ->
for filter in @.selectedFilters
if (filter['dataType'] == filterDataType)
return true
return false
saveCustomFilter: (name) ->
filters = {}
urlfilters = @location.search()
for key in @.filterCategories
excludeKey = @.excludePrefix.concat(key)
filters[key] = urlfilters[key]
filters[excludeKey] = urlfilters[excludeKey]
@filterRemoteStorageService.getFilters(@scope.projectId, @.myFiltersHashSuffix).then (userFilters) =>
userFilters[name] = filters
@filterRemoteStorageService.storeFilters(@scope.projectId, userFilters, @.myFiltersHashSuffix).then(@.generateFilters)
generateFilters: ->
@.storeFilters(@params.pslug, @location.search(), @.filtersHashSuffix)
urlfilters = @location.search()
loadFilters = {}
loadFilters.project = @scope.projectId
loadFilters.q = urlfilters.q
for key in @.filterCategories
excludeKey = @.excludePrefix.concat(key)
loadFilters[key] = urlfilters[key]
loadFilters[excludeKey] = urlfilters[excludeKey]
return @q.all([
@rs.issues.filtersData(loadFilters),
@filterRemoteStorageService.getFilters(@scope.projectId, @.myFiltersHashSuffix)
]).then (result) =>
data = result[0]
customFiltersRaw = result[1]
dataCollection = {}
dataCollection.status = _.map data.statuses, (it) ->
it.id = it.id.toString()
return it
dataCollection.type = _.map data.types, (it) ->
it.id = it.id.toString()
return it
dataCollection.severity = _.map data.severities, (it) ->
it.id = it.id.toString()
return it
dataCollection.priority = _.map data.priorities, (it) ->
it.id = it.id.toString()
return it
dataCollection.tags = _.map data.tags, (it) ->
it.id = it.name
return it
tagsWithAtLeastOneElement = _.filter dataCollection.tags, (tag) ->
return tag.count > 0
dataCollection.assigned_to = _.map data.assigned_to, (it) ->
if it.id
it.id = it.id.toString()
else
it.id = "null"
it.name = it.full_name || "Unassigned"
return it
dataCollection.owner = _.map data.owners, (it) ->
it.id = it.id.toString()
it.name = it.full_name
return it
dataCollection.role = _.map data.roles, (it) ->
if it.id
it.id = it.id.toString()
else
it.id = "null"
it.name = it.name || "Unassigned"
return it
@.selectedFilters = []
for key in @.filterCategories
excludeKey = @.excludePrefix.concat(key)
if loadFilters[key]
selected = @.formatSelectedFilters(key, dataCollection[key], loadFilters[key])
@.selectedFilters = @.selectedFilters.concat(selected)
if loadFilters[excludeKey]
selected = @.formatSelectedFilters(key, dataCollection[key], loadFilters[excludeKey], "exclude")
@.selectedFilters = @.selectedFilters.concat(selected)
@.filterQ = loadFilters.q
@.filters = [
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.TYPE"),
dataType: "type",
content: dataCollection.type
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.SEVERITY"),
dataType: "severity",
content: dataCollection.severity
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.PRIORITIES"),
dataType: "priority",
content: dataCollection.priority
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.STATUS"),
dataType: "status",
content: dataCollection.status
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.TAGS"),
dataType: "tags",
content: dataCollection.tags,
hideEmpty: true,
totalTaggedElements: tagsWithAtLeastOneElement.length
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.ASSIGNED_TO"),
dataType: "assigned_to",
content: dataCollection.assigned_to
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.ROLE"),
dataType: "role",
content: dataCollection.role
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.CREATED_BY"),
dataType: "owner",
content: dataCollection.owner
}
]
@.customFilters = []
_.forOwn customFiltersRaw, (value, key) =>
@.customFilters.push({id: key, name: key, filter: value})
initializeSubscription: ->
routingKey = "changes.project.#{@scope.projectId}.issues"
@events.subscribe @scope, routingKey, debounceLeading(500, (message) =>
@.loadIssues())
loadProject: ->
project = @projectService.project.toJS()
if not project.is_issues_activated
@errorHandlingService.permissionDenied()
@scope.projectId = project.id
@scope.project = project
@scope.$emit('project:loaded', project)
@scope.issueStatusById = groupBy(project.issue_statuses, (x) -> x.id)
@scope.issueStatusList = _.sortBy(project.issue_statuses, "order")
@scope.severityById = groupBy(project.severities, (x) -> x.id)
@scope.severityList = _.sortBy(project.severities, "order")
@scope.priorityById = groupBy(project.priorities, (x) -> x.id)
@scope.priorityList = _.sortBy(project.priorities, "order")
@scope.issueTypes = _.sortBy(project.issue_types, "order")
@scope.issueTypeById = groupBy(project.issue_types, (x) -> x.id)
return project
# We need to guarantee that the last petition done here is the finally used
# When searching by text loadIssues can be called fastly with different parameters and
# can be resolved in a different order than generated
# We count the requests made and only if the callback is for the last one data is updated
loadIssuesRequests: 0
loadIssues: =>
params = @location.search()
promise = @rs.issues.list(@scope.projectId, params)
@.loadIssuesRequests += 1
promise.index = @.loadIssuesRequests
promise.then (data) =>
if promise.index == @.loadIssuesRequests
@scope.issues = data.models
@scope.page = data.current
@scope.count = data.count
@scope.paginatedBy = data.paginatedBy
return data
return promise
loadInitialData: ->
project = @.loadProject()
@.fillUsersAndRoles(project.members, project.roles)
@.initializeSubscription()
@.generateFilters()
return @.loadIssues()
# Functions used from templates
addNewIssue: ->
project = @projectService.project.toJS()
@rootscope.$broadcast("genericform:new", {
'objType': 'issue',
'project': project
})
addIssuesInBulk: ->
@rootscope.$broadcast("issueform:bulk", @scope.projectId)
upVoteIssue: (issueId) ->
@.voting = issueId
onSuccess = =>
@.loadIssues()
@.voting = null
onError = =>
@confirm.notify("error")
@.voting = null
return @rs.issues.upvote(issueId).then(onSuccess, onError)
downVoteIssue: (issueId) ->
@.voting = issueId
onSuccess = =>
@.loadIssues()
@.voting = null
onError = =>
@confirm.notify("error")
@.voting = null
return @rs.issues.downvote(issueId).then(onSuccess, onError)
getOrderBy: ->
if _.isString(@location.search().order_by)
return @location.search().order_by
else
return "created_date"
module.controller("IssuesController", IssuesController)
#############################################################################
## Issues Directive
#############################################################################
IssuesDirective = ($log, $location, $template, $compile) ->
## Issues Pagination
template = $template.get("issue/issue-paginator.html", true)
linkPagination = ($scope, $el, $attrs, $ctrl) ->
# Constants
afterCurrent = 2
beforeCurrent = 4
atBegin = 2
atEnd = 2
$pagEl = $el.find(".issues-paginator")
getNumPages = ->
numPages = $scope.count / $scope.paginatedBy
if parseInt(numPages, 10) < numPages
numPages = parseInt(numPages, 10) + 1
else
numPages = parseInt(numPages, 10)
return numPages
renderPagination = ->
numPages = getNumPages()
if numPages <= 1
$pagEl.hide()
return
$pagEl.show()
pages = []
options = {}
options.pages = pages
options.showPrevious = ($scope.page > 1)
options.showNext = not ($scope.page == numPages)
cpage = $scope.page
for i in [1..numPages]
if i == (cpage + afterCurrent) and numPages > (cpage + afterCurrent + atEnd)
pages.push({classes: "dots", type: "dots"})
else if i == (cpage - beforeCurrent) and cpage > (atBegin + beforeCurrent)
pages.push({classes: "dots", type: "dots"})
else if i > (cpage + afterCurrent) and i <= (numPages - atEnd)
else if i < (cpage - beforeCurrent) and i > atBegin
else if i == cpage
pages.push({classes: "active", num: i, type: "page-active"})
else
pages.push({classes: "page", num: i, type: "page"})
html = template(options)
html = $compile(html)($scope)
$pagEl.html(html)
$scope.$watch "issues", (value) ->
# Do nothing if value is not logical true
return if not value
renderPagination()
$el.on "click", ".issues-paginator a.next", (event) ->
event.preventDefault()
$scope.$apply ->
$ctrl.selectFilter("page", $scope.page + 1)
$ctrl.loadIssues()
$el.on "click", ".issues-paginator a.previous", (event) ->
event.preventDefault()
$scope.$apply ->
$ctrl.selectFilter("page", $scope.page - 1)
$ctrl.loadIssues()
$el.on "click", ".issues-paginator li.page > a", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
pagenum = target.data("pagenum")
$scope.$apply ->
$ctrl.selectFilter("page", pagenum)
$ctrl.loadIssues()
## Issues Filters
linkOrdering = ($scope, $el, $attrs, $ctrl) ->
# Draw the arrow the first time
currentOrder = $ctrl.getOrderBy()
if currentOrder
icon = if startswith(currentOrder, "-") then "icon-arrow-up" else "icon-arrow-down"
colHeadElement = $el.find(".row.title > div[data-fieldname='#{trim(currentOrder, "-")}']")
svg = $("<tg-svg>").attr("svg-icon", icon)
colHeadElement.append(svg)
$compile(colHeadElement.contents())($scope)
$el.on "click", ".row.title > div", (event) ->
target = angular.element(event.currentTarget)
currentOrder = $ctrl.getOrderBy()
newOrder = target.data("fieldname")
if newOrder == 'total_voters' and currentOrder != "-total_voters"
currentOrder = "total_voters"
finalOrder = if currentOrder == newOrder then "-#{newOrder}" else newOrder
$scope.$apply ->
$ctrl.replaceFilter("order_by", finalOrder)
$ctrl.storeFilters($ctrl.params.pslug, $location.search(), $ctrl.filtersHashSuffix)
$ctrl.loadIssues().then ->
# Update the arrow
$el.find(".row.title > div > tg-svg").remove()
icon = if startswith(finalOrder, "-") then "icon-arrow-up" else "icon-arrow-down"
svg = $("<tg-svg>")
.attr("svg-icon", icon)
target.append(svg)
$compile(target.contents())($scope)
## Issues Link
link = ($scope, $el, $attrs) ->
$ctrl = $el.controller()
linkOrdering($scope, $el, $attrs, $ctrl)
linkPagination($scope, $el, $attrs, $ctrl)
$scope.$on "$destroy", ->
$el.off()
return {link:link}
module.directive("tgIssues", ["$log", "$tgLocation", "$tgTemplate", "$compile", IssuesDirective])
#############################################################################
## Issue status Directive (popover for change status)
#############################################################################
IssueStatusInlineEditionDirective = ($repo, $template, $rootscope) ->
###
Print the status of an Issue and a popover to change it.
- tg-issue-status-inline-edition: The issue
Example:
div.status(tg-issue-status-inline-edition="issue")
a.issue-status(href="")
NOTE: This directive need 'issueStatusById' and 'project'.
###
selectionTemplate = $template.get("issue/issue-status-inline-edition-selection.html", true)
updateIssueStatus = ($el, issue, issueStatusById) ->
issueStatusDomParent = $el.find(".issue-status")
issueStatusDom = $el.find(".issue-status .issue-status-bind")
status = issueStatusById[issue.status]
if status
issueStatusDom.text(status.name)
issueStatusDom.prop("title", status.name)
issueStatusDomParent.css('color', status.color)
link = ($scope, $el, $attrs) ->
$ctrl = $el.controller()
issue = $scope.$eval($attrs.tgIssueStatusInlineEdition)
$el.on "click", ".issue-status", (event) ->
event.preventDefault()
event.stopPropagation()
$el.find(".pop-status").popover().open()
$el.on "click", ".status", (event) ->
event.preventDefault()
event.stopPropagation()
target = angular.element(event.currentTarget)
issue.status = target.data("status-id")
$el.find(".pop-status").popover().close()
updateIssueStatus($el, issue, $scope.issueStatusById)
$scope.$apply () ->
$repo.save(issue).then (response) ->
$rootscope.$broadcast("status:changed", response)
taiga.bindOnce $scope, "project", (project) ->
$el.append(selectionTemplate({ 'statuses': project.issue_statuses }))
updateIssueStatus($el, issue, $scope.issueStatusById)
# If the user has not enough permissions the click events are unbinded
if project.my_permissions.indexOf("modify_issue") == -1
$el.unbind("click")
$el.find("a").addClass("not-clickable")
$scope.$watch $attrs.tgIssueStatusInlineEdition, (val) =>
updateIssueStatus($el, val, $scope.issueStatusById)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgIssueStatusInlineEdition", ["$tgRepo", "$tgTemplate", "$rootScope",
IssueStatusInlineEditionDirective])
#############################################################################
## Issue assigned to Directive
#############################################################################
IssueAssignedToInlineEditionDirective = ($repo, $rootscope, $translate, avatarService, $lightboxFactory) ->
template = _.template("""
<img style="background-color: <%- bg %>" src="<%- imgurl %>" alt="<%- name %>"/>
<figcaption><%- name %></figcaption>
""")
link = ($scope, $el, $attrs) ->
updateIssue = (issue) ->
ctx = {
name: $translate.instant("COMMON.ASSIGNED_TO.NOT_ASSIGNED"),
imgurl: "/#{window._version}/images/unnamed.png"
}
member = $scope.usersById[issue.assigned_to]
avatar = avatarService.getAvatar(member)
ctx.imgurl = avatar.url
ctx.bg = null
if member
ctx.name = member.full_name_display
ctx.bg = avatar.bg
$el.find(".avatar").html(template(ctx))
$el.find(".issue-assignedto").attr('title', ctx.name)
$ctrl = $el.controller()
issue = $scope.$eval($attrs.tgIssueAssignedToInlineEdition)
updateIssue(issue)
$el.on "click", ".issue-assignedto", (event) ->
onClose = (assignedUsers) =>
issue.assigned_to = assignedUsers.pop() || null
$repo.save(issue).then ->
updateIssue(issue)
$rootscope.$broadcast("assigned-to:changed", issue)
$lightboxFactory.create(
'tg-lb-select-user',
{
"class": "lightbox lightbox-select-user",
},
{
"currentUsers": [issue.assigned_to],
"activeUsers": $scope.activeUsers,
"onClose": onClose,
"single": true,
"lbTitle": $translate.instant("COMMON.ASSIGNED_USERS.ADD"),
}
)
taiga.bindOnce $scope, "project", (project) ->
# If the user has not enough permissions the click events are unbinded
if project.my_permissions.indexOf("modify_issue") == -1
$el.unbind("click")
$el.find("a").addClass("not-clickable")
$scope.$watch $attrs.tgIssueAssignedToInlineEdition, (val) ->
updateIssue(val)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgIssueAssignedToInlineEdition", ["$tgRepo", "$rootScope", "$translate", "tgAvatarService",
"tgLightboxFactory", IssueAssignedToInlineEditionDirective])
| 96618 | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/issues/list.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
trim = @.taiga.trim
toString = @.taiga.toString
joinStr = @.taiga.joinStr
groupBy = @.taiga.groupBy
bindOnce = @.taiga.bindOnce
debounceLeading = @.taiga.debounceLeading
startswith = @.taiga.startswith
bindMethods = @.taiga.bindMethods
debounceLeading = @.taiga.debounceLeading
module = angular.module("taigaIssues")
#############################################################################
## Issues Controller
#############################################################################
class IssuesController extends mixOf(taiga.Controller, taiga.PageMixin, taiga.FiltersMixin)
@.$inject = [
"$scope",
"$rootScope",
"$tgRepo",
"$tgConfirm",
"$tgResources",
"$tgUrls",
"$routeParams",
"$q",
"$tgLocation",
"tgAppMetaService",
"$tgNavUrls",
"$tgEvents",
"$tgAnalytics",
"$translate",
"tgErrorHandlingService",
"$tgStorage",
"tgFilterRemoteStorageService",
"tgProjectService",
"tgUserActivityService"
]
filtersHashSuffix: "issues-filters"
myFiltersHashSuffix: "issues-my-filters"
excludePrefix: "exclude_"
filterCategories: [
"tags",
"status",
"type",
"severity",
"priority",
"assigned_to",
"owner",
"role",
]
constructor: (@scope, @rootscope, @repo, @confirm, @rs, @urls, @params, @q, @location, @appMetaService,
@navUrls, @events, @analytics, @translate, @errorHandlingService, @storage, @filterRemoteStorageService, @projectService) ->
bindMethods(@)
@scope.sectionName = @translate.instant("PROJECT.SECTION.ISSUES")
@.voting = false
return if @.applyStoredFilters(@params.pslug, @.filtersHashSuffix)
promise = @.loadInitialData()
# On Success
promise.then =>
title = @translate.instant("ISSUES.PAGE_TITLE", {projectName: @scope.project.name})
description = @translate.instant("ISSUES.PAGE_DESCRIPTION", {
projectName: @scope.project.name,
projectDescription: @scope.project.description
})
@appMetaService.setAll(title, description)
# On Error
promise.then null, @.onInitialDataError.bind(@)
@scope.$on "issueform:new:success", =>
@analytics.trackEvent("issue", "create", "create issue on issues list", 1)
@.loadIssues()
@scope.$on "assigned-to:changed", =>
@.generateFilters()
if @.isFilterDataTypeSelected('assigned_to') ||\
@.isFilterDataTypeSelected('role') ||\
@.isOrderedBy('assigned_to') || @.isOrderedBy('modified')
@.loadIssues()
@scope.$on "status:changed", =>
@.generateFilters()
if @.isFilterDataTypeSelected('status') ||\
@.isOrderedBy('status') || @.isOrderedBy('modified')
@.loadIssues()
isOrderedBy: (fieldName) ->
pattern = new RegExp("-*"+fieldName)
return pattern.test(@location.search().order_by)
changeQ: (q) ->
@.unselectFilter("page")
@.replaceFilter("q", q)
@.loadIssues()
@.generateFilters()
removeFilter: (filter) ->
@.unselectFilter("page")
@.unselectFilter(filter.dataType, filter.id, false, filter.mode)
@.loadIssues()
@.generateFilters()
addFilter: (newFilter) ->
@.unselectFilter("page")
@.selectFilter(newFilter.category.dataType, newFilter.filter.id, false, newFilter.mode)
@.loadIssues()
@.generateFilters()
selectCustomFilter: (customFilter) ->
orderBy = @location.search().order_by
if orderBy
customFilter.filter.order_by = orderBy
@.unselectFilter("page")
@.replaceAllFilters(customFilter.filter)
@.loadIssues()
@.generateFilters()
removeCustomFilter: (customFilter) ->
@filterRemoteStorageService.getFilters(@scope.projectId, @.myFiltersHashSuffix).then (userFilters) =>
delete userFilters[customFilter.id]
@filterRemoteStorageService.storeFilters(@scope.projectId, userFilters, @.myFiltersHashSuffix).then(@.generateFilters)
isFilterDataTypeSelected: (filterDataType) ->
for filter in @.selectedFilters
if (filter['dataType'] == filterDataType)
return true
return false
saveCustomFilter: (name) ->
filters = {}
urlfilters = @location.search()
for key in @.filterCategories
excludeKey = @.excludePrefix.concat(key)
filters[key] = urlfilters[key]
filters[excludeKey] = urlfilters[excludeKey]
@filterRemoteStorageService.getFilters(@scope.projectId, @.myFiltersHashSuffix).then (userFilters) =>
userFilters[name] = filters
@filterRemoteStorageService.storeFilters(@scope.projectId, userFilters, @.myFiltersHashSuffix).then(@.generateFilters)
generateFilters: ->
@.storeFilters(@params.pslug, @location.search(), @.filtersHashSuffix)
urlfilters = @location.search()
loadFilters = {}
loadFilters.project = @scope.projectId
loadFilters.q = urlfilters.q
for key in @.filterCategories
excludeKey = @.excludePrefix.concat(key)
loadFilters[key] = urlfilters[key]
loadFilters[excludeKey] = urlfilters[excludeKey]
return @q.all([
@rs.issues.filtersData(loadFilters),
@filterRemoteStorageService.getFilters(@scope.projectId, @.myFiltersHashSuffix)
]).then (result) =>
data = result[0]
customFiltersRaw = result[1]
dataCollection = {}
dataCollection.status = _.map data.statuses, (it) ->
it.id = it.id.toString()
return it
dataCollection.type = _.map data.types, (it) ->
it.id = it.id.toString()
return it
dataCollection.severity = _.map data.severities, (it) ->
it.id = it.id.toString()
return it
dataCollection.priority = _.map data.priorities, (it) ->
it.id = it.id.toString()
return it
dataCollection.tags = _.map data.tags, (it) ->
it.id = it.name
return it
tagsWithAtLeastOneElement = _.filter dataCollection.tags, (tag) ->
return tag.count > 0
dataCollection.assigned_to = _.map data.assigned_to, (it) ->
if it.id
it.id = it.id.toString()
else
it.id = "null"
it.name = it.full_name || "Unassigned"
return it
dataCollection.owner = _.map data.owners, (it) ->
it.id = it.id.toString()
it.name = it.full_name
return it
dataCollection.role = _.map data.roles, (it) ->
if it.id
it.id = it.id.toString()
else
it.id = "null"
it.name = it.name || "Unassigned"
return it
@.selectedFilters = []
for key in @.filterCategories
excludeKey = @.excludePrefix.concat(key)
if loadFilters[key]
selected = @.formatSelectedFilters(key, dataCollection[key], loadFilters[key])
@.selectedFilters = @.selectedFilters.concat(selected)
if loadFilters[excludeKey]
selected = @.formatSelectedFilters(key, dataCollection[key], loadFilters[excludeKey], "exclude")
@.selectedFilters = @.selectedFilters.concat(selected)
@.filterQ = loadFilters.q
@.filters = [
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.TYPE"),
dataType: "type",
content: dataCollection.type
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.SEVERITY"),
dataType: "severity",
content: dataCollection.severity
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.PRIORITIES"),
dataType: "priority",
content: dataCollection.priority
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.STATUS"),
dataType: "status",
content: dataCollection.status
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.TAGS"),
dataType: "tags",
content: dataCollection.tags,
hideEmpty: true,
totalTaggedElements: tagsWithAtLeastOneElement.length
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.ASSIGNED_TO"),
dataType: "assigned_to",
content: dataCollection.assigned_to
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.ROLE"),
dataType: "role",
content: dataCollection.role
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.CREATED_BY"),
dataType: "owner",
content: dataCollection.owner
}
]
@.customFilters = []
_.forOwn customFiltersRaw, (value, key) =>
@.customFilters.push({id: key, name: key, filter: value})
initializeSubscription: ->
routingKey = "<KEY>@scope.projectId}.<KEY>"
@events.subscribe @scope, routingKey, debounceLeading(500, (message) =>
@.loadIssues())
loadProject: ->
project = @projectService.project.toJS()
if not project.is_issues_activated
@errorHandlingService.permissionDenied()
@scope.projectId = project.id
@scope.project = project
@scope.$emit('project:loaded', project)
@scope.issueStatusById = groupBy(project.issue_statuses, (x) -> x.id)
@scope.issueStatusList = _.sortBy(project.issue_statuses, "order")
@scope.severityById = groupBy(project.severities, (x) -> x.id)
@scope.severityList = _.sortBy(project.severities, "order")
@scope.priorityById = groupBy(project.priorities, (x) -> x.id)
@scope.priorityList = _.sortBy(project.priorities, "order")
@scope.issueTypes = _.sortBy(project.issue_types, "order")
@scope.issueTypeById = groupBy(project.issue_types, (x) -> x.id)
return project
# We need to guarantee that the last petition done here is the finally used
# When searching by text loadIssues can be called fastly with different parameters and
# can be resolved in a different order than generated
# We count the requests made and only if the callback is for the last one data is updated
loadIssuesRequests: 0
loadIssues: =>
params = @location.search()
promise = @rs.issues.list(@scope.projectId, params)
@.loadIssuesRequests += 1
promise.index = @.loadIssuesRequests
promise.then (data) =>
if promise.index == @.loadIssuesRequests
@scope.issues = data.models
@scope.page = data.current
@scope.count = data.count
@scope.paginatedBy = data.paginatedBy
return data
return promise
loadInitialData: ->
project = @.loadProject()
@.fillUsersAndRoles(project.members, project.roles)
@.initializeSubscription()
@.generateFilters()
return @.loadIssues()
# Functions used from templates
addNewIssue: ->
project = @projectService.project.toJS()
@rootscope.$broadcast("genericform:new", {
'objType': 'issue',
'project': project
})
addIssuesInBulk: ->
@rootscope.$broadcast("issueform:bulk", @scope.projectId)
upVoteIssue: (issueId) ->
@.voting = issueId
onSuccess = =>
@.loadIssues()
@.voting = null
onError = =>
@confirm.notify("error")
@.voting = null
return @rs.issues.upvote(issueId).then(onSuccess, onError)
downVoteIssue: (issueId) ->
@.voting = issueId
onSuccess = =>
@.loadIssues()
@.voting = null
onError = =>
@confirm.notify("error")
@.voting = null
return @rs.issues.downvote(issueId).then(onSuccess, onError)
getOrderBy: ->
if _.isString(@location.search().order_by)
return @location.search().order_by
else
return "created_date"
module.controller("IssuesController", IssuesController)
#############################################################################
## Issues Directive
#############################################################################
IssuesDirective = ($log, $location, $template, $compile) ->
## Issues Pagination
template = $template.get("issue/issue-paginator.html", true)
linkPagination = ($scope, $el, $attrs, $ctrl) ->
# Constants
afterCurrent = 2
beforeCurrent = 4
atBegin = 2
atEnd = 2
$pagEl = $el.find(".issues-paginator")
getNumPages = ->
numPages = $scope.count / $scope.paginatedBy
if parseInt(numPages, 10) < numPages
numPages = parseInt(numPages, 10) + 1
else
numPages = parseInt(numPages, 10)
return numPages
renderPagination = ->
numPages = getNumPages()
if numPages <= 1
$pagEl.hide()
return
$pagEl.show()
pages = []
options = {}
options.pages = pages
options.showPrevious = ($scope.page > 1)
options.showNext = not ($scope.page == numPages)
cpage = $scope.page
for i in [1..numPages]
if i == (cpage + afterCurrent) and numPages > (cpage + afterCurrent + atEnd)
pages.push({classes: "dots", type: "dots"})
else if i == (cpage - beforeCurrent) and cpage > (atBegin + beforeCurrent)
pages.push({classes: "dots", type: "dots"})
else if i > (cpage + afterCurrent) and i <= (numPages - atEnd)
else if i < (cpage - beforeCurrent) and i > atBegin
else if i == cpage
pages.push({classes: "active", num: i, type: "page-active"})
else
pages.push({classes: "page", num: i, type: "page"})
html = template(options)
html = $compile(html)($scope)
$pagEl.html(html)
$scope.$watch "issues", (value) ->
# Do nothing if value is not logical true
return if not value
renderPagination()
$el.on "click", ".issues-paginator a.next", (event) ->
event.preventDefault()
$scope.$apply ->
$ctrl.selectFilter("page", $scope.page + 1)
$ctrl.loadIssues()
$el.on "click", ".issues-paginator a.previous", (event) ->
event.preventDefault()
$scope.$apply ->
$ctrl.selectFilter("page", $scope.page - 1)
$ctrl.loadIssues()
$el.on "click", ".issues-paginator li.page > a", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
pagenum = target.data("pagenum")
$scope.$apply ->
$ctrl.selectFilter("page", pagenum)
$ctrl.loadIssues()
## Issues Filters
linkOrdering = ($scope, $el, $attrs, $ctrl) ->
# Draw the arrow the first time
currentOrder = $ctrl.getOrderBy()
if currentOrder
icon = if startswith(currentOrder, "-") then "icon-arrow-up" else "icon-arrow-down"
colHeadElement = $el.find(".row.title > div[data-fieldname='#{trim(currentOrder, "-")}']")
svg = $("<tg-svg>").attr("svg-icon", icon)
colHeadElement.append(svg)
$compile(colHeadElement.contents())($scope)
$el.on "click", ".row.title > div", (event) ->
target = angular.element(event.currentTarget)
currentOrder = $ctrl.getOrderBy()
newOrder = target.data("fieldname")
if newOrder == 'total_voters' and currentOrder != "-total_voters"
currentOrder = "total_voters"
finalOrder = if currentOrder == newOrder then "-#{newOrder}" else newOrder
$scope.$apply ->
$ctrl.replaceFilter("order_by", finalOrder)
$ctrl.storeFilters($ctrl.params.pslug, $location.search(), $ctrl.filtersHashSuffix)
$ctrl.loadIssues().then ->
# Update the arrow
$el.find(".row.title > div > tg-svg").remove()
icon = if startswith(finalOrder, "-") then "icon-arrow-up" else "icon-arrow-down"
svg = $("<tg-svg>")
.attr("svg-icon", icon)
target.append(svg)
$compile(target.contents())($scope)
## Issues Link
link = ($scope, $el, $attrs) ->
$ctrl = $el.controller()
linkOrdering($scope, $el, $attrs, $ctrl)
linkPagination($scope, $el, $attrs, $ctrl)
$scope.$on "$destroy", ->
$el.off()
return {link:link}
module.directive("tgIssues", ["$log", "$tgLocation", "$tgTemplate", "$compile", IssuesDirective])
#############################################################################
## Issue status Directive (popover for change status)
#############################################################################
IssueStatusInlineEditionDirective = ($repo, $template, $rootscope) ->
###
Print the status of an Issue and a popover to change it.
- tg-issue-status-inline-edition: The issue
Example:
div.status(tg-issue-status-inline-edition="issue")
a.issue-status(href="")
NOTE: This directive need 'issueStatusById' and 'project'.
###
selectionTemplate = $template.get("issue/issue-status-inline-edition-selection.html", true)
updateIssueStatus = ($el, issue, issueStatusById) ->
issueStatusDomParent = $el.find(".issue-status")
issueStatusDom = $el.find(".issue-status .issue-status-bind")
status = issueStatusById[issue.status]
if status
issueStatusDom.text(status.name)
issueStatusDom.prop("title", status.name)
issueStatusDomParent.css('color', status.color)
link = ($scope, $el, $attrs) ->
$ctrl = $el.controller()
issue = $scope.$eval($attrs.tgIssueStatusInlineEdition)
$el.on "click", ".issue-status", (event) ->
event.preventDefault()
event.stopPropagation()
$el.find(".pop-status").popover().open()
$el.on "click", ".status", (event) ->
event.preventDefault()
event.stopPropagation()
target = angular.element(event.currentTarget)
issue.status = target.data("status-id")
$el.find(".pop-status").popover().close()
updateIssueStatus($el, issue, $scope.issueStatusById)
$scope.$apply () ->
$repo.save(issue).then (response) ->
$rootscope.$broadcast("status:changed", response)
taiga.bindOnce $scope, "project", (project) ->
$el.append(selectionTemplate({ 'statuses': project.issue_statuses }))
updateIssueStatus($el, issue, $scope.issueStatusById)
# If the user has not enough permissions the click events are unbinded
if project.my_permissions.indexOf("modify_issue") == -1
$el.unbind("click")
$el.find("a").addClass("not-clickable")
$scope.$watch $attrs.tgIssueStatusInlineEdition, (val) =>
updateIssueStatus($el, val, $scope.issueStatusById)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgIssueStatusInlineEdition", ["$tgRepo", "$tgTemplate", "$rootScope",
IssueStatusInlineEditionDirective])
#############################################################################
## Issue assigned to Directive
#############################################################################
IssueAssignedToInlineEditionDirective = ($repo, $rootscope, $translate, avatarService, $lightboxFactory) ->
template = _.template("""
<img style="background-color: <%- bg %>" src="<%- imgurl %>" alt="<%- name %>"/>
<figcaption><%- name %></figcaption>
""")
link = ($scope, $el, $attrs) ->
updateIssue = (issue) ->
ctx = {
name: $translate.instant("COMMON.ASSIGNED_TO.NOT_ASSIGNED"),
imgurl: "/#{window._version}/images/unnamed.png"
}
member = $scope.usersById[issue.assigned_to]
avatar = avatarService.getAvatar(member)
ctx.imgurl = avatar.url
ctx.bg = null
if member
ctx.name = member.full_name_display
ctx.bg = avatar.bg
$el.find(".avatar").html(template(ctx))
$el.find(".issue-assignedto").attr('title', ctx.name)
$ctrl = $el.controller()
issue = $scope.$eval($attrs.tgIssueAssignedToInlineEdition)
updateIssue(issue)
$el.on "click", ".issue-assignedto", (event) ->
onClose = (assignedUsers) =>
issue.assigned_to = assignedUsers.pop() || null
$repo.save(issue).then ->
updateIssue(issue)
$rootscope.$broadcast("assigned-to:changed", issue)
$lightboxFactory.create(
'tg-lb-select-user',
{
"class": "lightbox lightbox-select-user",
},
{
"currentUsers": [issue.assigned_to],
"activeUsers": $scope.activeUsers,
"onClose": onClose,
"single": true,
"lbTitle": $translate.instant("COMMON.ASSIGNED_USERS.ADD"),
}
)
taiga.bindOnce $scope, "project", (project) ->
# If the user has not enough permissions the click events are unbinded
if project.my_permissions.indexOf("modify_issue") == -1
$el.unbind("click")
$el.find("a").addClass("not-clickable")
$scope.$watch $attrs.tgIssueAssignedToInlineEdition, (val) ->
updateIssue(val)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgIssueAssignedToInlineEdition", ["$tgRepo", "$rootScope", "$translate", "tgAvatarService",
"tgLightboxFactory", IssueAssignedToInlineEditionDirective])
| true | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/issues/list.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
trim = @.taiga.trim
toString = @.taiga.toString
joinStr = @.taiga.joinStr
groupBy = @.taiga.groupBy
bindOnce = @.taiga.bindOnce
debounceLeading = @.taiga.debounceLeading
startswith = @.taiga.startswith
bindMethods = @.taiga.bindMethods
debounceLeading = @.taiga.debounceLeading
module = angular.module("taigaIssues")
#############################################################################
## Issues Controller
#############################################################################
class IssuesController extends mixOf(taiga.Controller, taiga.PageMixin, taiga.FiltersMixin)
@.$inject = [
"$scope",
"$rootScope",
"$tgRepo",
"$tgConfirm",
"$tgResources",
"$tgUrls",
"$routeParams",
"$q",
"$tgLocation",
"tgAppMetaService",
"$tgNavUrls",
"$tgEvents",
"$tgAnalytics",
"$translate",
"tgErrorHandlingService",
"$tgStorage",
"tgFilterRemoteStorageService",
"tgProjectService",
"tgUserActivityService"
]
filtersHashSuffix: "issues-filters"
myFiltersHashSuffix: "issues-my-filters"
excludePrefix: "exclude_"
filterCategories: [
"tags",
"status",
"type",
"severity",
"priority",
"assigned_to",
"owner",
"role",
]
constructor: (@scope, @rootscope, @repo, @confirm, @rs, @urls, @params, @q, @location, @appMetaService,
@navUrls, @events, @analytics, @translate, @errorHandlingService, @storage, @filterRemoteStorageService, @projectService) ->
bindMethods(@)
@scope.sectionName = @translate.instant("PROJECT.SECTION.ISSUES")
@.voting = false
return if @.applyStoredFilters(@params.pslug, @.filtersHashSuffix)
promise = @.loadInitialData()
# On Success
promise.then =>
title = @translate.instant("ISSUES.PAGE_TITLE", {projectName: @scope.project.name})
description = @translate.instant("ISSUES.PAGE_DESCRIPTION", {
projectName: @scope.project.name,
projectDescription: @scope.project.description
})
@appMetaService.setAll(title, description)
# On Error
promise.then null, @.onInitialDataError.bind(@)
@scope.$on "issueform:new:success", =>
@analytics.trackEvent("issue", "create", "create issue on issues list", 1)
@.loadIssues()
@scope.$on "assigned-to:changed", =>
@.generateFilters()
if @.isFilterDataTypeSelected('assigned_to') ||\
@.isFilterDataTypeSelected('role') ||\
@.isOrderedBy('assigned_to') || @.isOrderedBy('modified')
@.loadIssues()
@scope.$on "status:changed", =>
@.generateFilters()
if @.isFilterDataTypeSelected('status') ||\
@.isOrderedBy('status') || @.isOrderedBy('modified')
@.loadIssues()
isOrderedBy: (fieldName) ->
pattern = new RegExp("-*"+fieldName)
return pattern.test(@location.search().order_by)
changeQ: (q) ->
@.unselectFilter("page")
@.replaceFilter("q", q)
@.loadIssues()
@.generateFilters()
removeFilter: (filter) ->
@.unselectFilter("page")
@.unselectFilter(filter.dataType, filter.id, false, filter.mode)
@.loadIssues()
@.generateFilters()
addFilter: (newFilter) ->
@.unselectFilter("page")
@.selectFilter(newFilter.category.dataType, newFilter.filter.id, false, newFilter.mode)
@.loadIssues()
@.generateFilters()
selectCustomFilter: (customFilter) ->
orderBy = @location.search().order_by
if orderBy
customFilter.filter.order_by = orderBy
@.unselectFilter("page")
@.replaceAllFilters(customFilter.filter)
@.loadIssues()
@.generateFilters()
removeCustomFilter: (customFilter) ->
@filterRemoteStorageService.getFilters(@scope.projectId, @.myFiltersHashSuffix).then (userFilters) =>
delete userFilters[customFilter.id]
@filterRemoteStorageService.storeFilters(@scope.projectId, userFilters, @.myFiltersHashSuffix).then(@.generateFilters)
isFilterDataTypeSelected: (filterDataType) ->
for filter in @.selectedFilters
if (filter['dataType'] == filterDataType)
return true
return false
saveCustomFilter: (name) ->
filters = {}
urlfilters = @location.search()
for key in @.filterCategories
excludeKey = @.excludePrefix.concat(key)
filters[key] = urlfilters[key]
filters[excludeKey] = urlfilters[excludeKey]
@filterRemoteStorageService.getFilters(@scope.projectId, @.myFiltersHashSuffix).then (userFilters) =>
userFilters[name] = filters
@filterRemoteStorageService.storeFilters(@scope.projectId, userFilters, @.myFiltersHashSuffix).then(@.generateFilters)
generateFilters: ->
@.storeFilters(@params.pslug, @location.search(), @.filtersHashSuffix)
urlfilters = @location.search()
loadFilters = {}
loadFilters.project = @scope.projectId
loadFilters.q = urlfilters.q
for key in @.filterCategories
excludeKey = @.excludePrefix.concat(key)
loadFilters[key] = urlfilters[key]
loadFilters[excludeKey] = urlfilters[excludeKey]
return @q.all([
@rs.issues.filtersData(loadFilters),
@filterRemoteStorageService.getFilters(@scope.projectId, @.myFiltersHashSuffix)
]).then (result) =>
data = result[0]
customFiltersRaw = result[1]
dataCollection = {}
dataCollection.status = _.map data.statuses, (it) ->
it.id = it.id.toString()
return it
dataCollection.type = _.map data.types, (it) ->
it.id = it.id.toString()
return it
dataCollection.severity = _.map data.severities, (it) ->
it.id = it.id.toString()
return it
dataCollection.priority = _.map data.priorities, (it) ->
it.id = it.id.toString()
return it
dataCollection.tags = _.map data.tags, (it) ->
it.id = it.name
return it
tagsWithAtLeastOneElement = _.filter dataCollection.tags, (tag) ->
return tag.count > 0
dataCollection.assigned_to = _.map data.assigned_to, (it) ->
if it.id
it.id = it.id.toString()
else
it.id = "null"
it.name = it.full_name || "Unassigned"
return it
dataCollection.owner = _.map data.owners, (it) ->
it.id = it.id.toString()
it.name = it.full_name
return it
dataCollection.role = _.map data.roles, (it) ->
if it.id
it.id = it.id.toString()
else
it.id = "null"
it.name = it.name || "Unassigned"
return it
@.selectedFilters = []
for key in @.filterCategories
excludeKey = @.excludePrefix.concat(key)
if loadFilters[key]
selected = @.formatSelectedFilters(key, dataCollection[key], loadFilters[key])
@.selectedFilters = @.selectedFilters.concat(selected)
if loadFilters[excludeKey]
selected = @.formatSelectedFilters(key, dataCollection[key], loadFilters[excludeKey], "exclude")
@.selectedFilters = @.selectedFilters.concat(selected)
@.filterQ = loadFilters.q
@.filters = [
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.TYPE"),
dataType: "type",
content: dataCollection.type
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.SEVERITY"),
dataType: "severity",
content: dataCollection.severity
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.PRIORITIES"),
dataType: "priority",
content: dataCollection.priority
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.STATUS"),
dataType: "status",
content: dataCollection.status
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.TAGS"),
dataType: "tags",
content: dataCollection.tags,
hideEmpty: true,
totalTaggedElements: tagsWithAtLeastOneElement.length
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.ASSIGNED_TO"),
dataType: "assigned_to",
content: dataCollection.assigned_to
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.ROLE"),
dataType: "role",
content: dataCollection.role
},
{
title: @translate.instant("COMMON.FILTERS.CATEGORIES.CREATED_BY"),
dataType: "owner",
content: dataCollection.owner
}
]
@.customFilters = []
_.forOwn customFiltersRaw, (value, key) =>
@.customFilters.push({id: key, name: key, filter: value})
initializeSubscription: ->
routingKey = "PI:KEY:<KEY>END_PI@scope.projectId}.PI:KEY:<KEY>END_PI"
@events.subscribe @scope, routingKey, debounceLeading(500, (message) =>
@.loadIssues())
loadProject: ->
project = @projectService.project.toJS()
if not project.is_issues_activated
@errorHandlingService.permissionDenied()
@scope.projectId = project.id
@scope.project = project
@scope.$emit('project:loaded', project)
@scope.issueStatusById = groupBy(project.issue_statuses, (x) -> x.id)
@scope.issueStatusList = _.sortBy(project.issue_statuses, "order")
@scope.severityById = groupBy(project.severities, (x) -> x.id)
@scope.severityList = _.sortBy(project.severities, "order")
@scope.priorityById = groupBy(project.priorities, (x) -> x.id)
@scope.priorityList = _.sortBy(project.priorities, "order")
@scope.issueTypes = _.sortBy(project.issue_types, "order")
@scope.issueTypeById = groupBy(project.issue_types, (x) -> x.id)
return project
# We need to guarantee that the last petition done here is the finally used
# When searching by text loadIssues can be called fastly with different parameters and
# can be resolved in a different order than generated
# We count the requests made and only if the callback is for the last one data is updated
loadIssuesRequests: 0
loadIssues: =>
params = @location.search()
promise = @rs.issues.list(@scope.projectId, params)
@.loadIssuesRequests += 1
promise.index = @.loadIssuesRequests
promise.then (data) =>
if promise.index == @.loadIssuesRequests
@scope.issues = data.models
@scope.page = data.current
@scope.count = data.count
@scope.paginatedBy = data.paginatedBy
return data
return promise
loadInitialData: ->
project = @.loadProject()
@.fillUsersAndRoles(project.members, project.roles)
@.initializeSubscription()
@.generateFilters()
return @.loadIssues()
# Functions used from templates
addNewIssue: ->
project = @projectService.project.toJS()
@rootscope.$broadcast("genericform:new", {
'objType': 'issue',
'project': project
})
addIssuesInBulk: ->
@rootscope.$broadcast("issueform:bulk", @scope.projectId)
upVoteIssue: (issueId) ->
@.voting = issueId
onSuccess = =>
@.loadIssues()
@.voting = null
onError = =>
@confirm.notify("error")
@.voting = null
return @rs.issues.upvote(issueId).then(onSuccess, onError)
downVoteIssue: (issueId) ->
@.voting = issueId
onSuccess = =>
@.loadIssues()
@.voting = null
onError = =>
@confirm.notify("error")
@.voting = null
return @rs.issues.downvote(issueId).then(onSuccess, onError)
getOrderBy: ->
if _.isString(@location.search().order_by)
return @location.search().order_by
else
return "created_date"
module.controller("IssuesController", IssuesController)
#############################################################################
## Issues Directive
#############################################################################
IssuesDirective = ($log, $location, $template, $compile) ->
## Issues Pagination
template = $template.get("issue/issue-paginator.html", true)
linkPagination = ($scope, $el, $attrs, $ctrl) ->
# Constants
afterCurrent = 2
beforeCurrent = 4
atBegin = 2
atEnd = 2
$pagEl = $el.find(".issues-paginator")
getNumPages = ->
numPages = $scope.count / $scope.paginatedBy
if parseInt(numPages, 10) < numPages
numPages = parseInt(numPages, 10) + 1
else
numPages = parseInt(numPages, 10)
return numPages
renderPagination = ->
numPages = getNumPages()
if numPages <= 1
$pagEl.hide()
return
$pagEl.show()
pages = []
options = {}
options.pages = pages
options.showPrevious = ($scope.page > 1)
options.showNext = not ($scope.page == numPages)
cpage = $scope.page
for i in [1..numPages]
if i == (cpage + afterCurrent) and numPages > (cpage + afterCurrent + atEnd)
pages.push({classes: "dots", type: "dots"})
else if i == (cpage - beforeCurrent) and cpage > (atBegin + beforeCurrent)
pages.push({classes: "dots", type: "dots"})
else if i > (cpage + afterCurrent) and i <= (numPages - atEnd)
else if i < (cpage - beforeCurrent) and i > atBegin
else if i == cpage
pages.push({classes: "active", num: i, type: "page-active"})
else
pages.push({classes: "page", num: i, type: "page"})
html = template(options)
html = $compile(html)($scope)
$pagEl.html(html)
$scope.$watch "issues", (value) ->
# Do nothing if value is not logical true
return if not value
renderPagination()
$el.on "click", ".issues-paginator a.next", (event) ->
event.preventDefault()
$scope.$apply ->
$ctrl.selectFilter("page", $scope.page + 1)
$ctrl.loadIssues()
$el.on "click", ".issues-paginator a.previous", (event) ->
event.preventDefault()
$scope.$apply ->
$ctrl.selectFilter("page", $scope.page - 1)
$ctrl.loadIssues()
$el.on "click", ".issues-paginator li.page > a", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
pagenum = target.data("pagenum")
$scope.$apply ->
$ctrl.selectFilter("page", pagenum)
$ctrl.loadIssues()
## Issues Filters
linkOrdering = ($scope, $el, $attrs, $ctrl) ->
# Draw the arrow the first time
currentOrder = $ctrl.getOrderBy()
if currentOrder
icon = if startswith(currentOrder, "-") then "icon-arrow-up" else "icon-arrow-down"
colHeadElement = $el.find(".row.title > div[data-fieldname='#{trim(currentOrder, "-")}']")
svg = $("<tg-svg>").attr("svg-icon", icon)
colHeadElement.append(svg)
$compile(colHeadElement.contents())($scope)
$el.on "click", ".row.title > div", (event) ->
target = angular.element(event.currentTarget)
currentOrder = $ctrl.getOrderBy()
newOrder = target.data("fieldname")
if newOrder == 'total_voters' and currentOrder != "-total_voters"
currentOrder = "total_voters"
finalOrder = if currentOrder == newOrder then "-#{newOrder}" else newOrder
$scope.$apply ->
$ctrl.replaceFilter("order_by", finalOrder)
$ctrl.storeFilters($ctrl.params.pslug, $location.search(), $ctrl.filtersHashSuffix)
$ctrl.loadIssues().then ->
# Update the arrow
$el.find(".row.title > div > tg-svg").remove()
icon = if startswith(finalOrder, "-") then "icon-arrow-up" else "icon-arrow-down"
svg = $("<tg-svg>")
.attr("svg-icon", icon)
target.append(svg)
$compile(target.contents())($scope)
## Issues Link
link = ($scope, $el, $attrs) ->
$ctrl = $el.controller()
linkOrdering($scope, $el, $attrs, $ctrl)
linkPagination($scope, $el, $attrs, $ctrl)
$scope.$on "$destroy", ->
$el.off()
return {link:link}
module.directive("tgIssues", ["$log", "$tgLocation", "$tgTemplate", "$compile", IssuesDirective])
#############################################################################
## Issue status Directive (popover for change status)
#############################################################################
IssueStatusInlineEditionDirective = ($repo, $template, $rootscope) ->
###
Print the status of an Issue and a popover to change it.
- tg-issue-status-inline-edition: The issue
Example:
div.status(tg-issue-status-inline-edition="issue")
a.issue-status(href="")
NOTE: This directive need 'issueStatusById' and 'project'.
###
selectionTemplate = $template.get("issue/issue-status-inline-edition-selection.html", true)
updateIssueStatus = ($el, issue, issueStatusById) ->
issueStatusDomParent = $el.find(".issue-status")
issueStatusDom = $el.find(".issue-status .issue-status-bind")
status = issueStatusById[issue.status]
if status
issueStatusDom.text(status.name)
issueStatusDom.prop("title", status.name)
issueStatusDomParent.css('color', status.color)
link = ($scope, $el, $attrs) ->
$ctrl = $el.controller()
issue = $scope.$eval($attrs.tgIssueStatusInlineEdition)
$el.on "click", ".issue-status", (event) ->
event.preventDefault()
event.stopPropagation()
$el.find(".pop-status").popover().open()
$el.on "click", ".status", (event) ->
event.preventDefault()
event.stopPropagation()
target = angular.element(event.currentTarget)
issue.status = target.data("status-id")
$el.find(".pop-status").popover().close()
updateIssueStatus($el, issue, $scope.issueStatusById)
$scope.$apply () ->
$repo.save(issue).then (response) ->
$rootscope.$broadcast("status:changed", response)
taiga.bindOnce $scope, "project", (project) ->
$el.append(selectionTemplate({ 'statuses': project.issue_statuses }))
updateIssueStatus($el, issue, $scope.issueStatusById)
# If the user has not enough permissions the click events are unbinded
if project.my_permissions.indexOf("modify_issue") == -1
$el.unbind("click")
$el.find("a").addClass("not-clickable")
$scope.$watch $attrs.tgIssueStatusInlineEdition, (val) =>
updateIssueStatus($el, val, $scope.issueStatusById)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgIssueStatusInlineEdition", ["$tgRepo", "$tgTemplate", "$rootScope",
IssueStatusInlineEditionDirective])
#############################################################################
## Issue assigned to Directive
#############################################################################
IssueAssignedToInlineEditionDirective = ($repo, $rootscope, $translate, avatarService, $lightboxFactory) ->
template = _.template("""
<img style="background-color: <%- bg %>" src="<%- imgurl %>" alt="<%- name %>"/>
<figcaption><%- name %></figcaption>
""")
link = ($scope, $el, $attrs) ->
updateIssue = (issue) ->
ctx = {
name: $translate.instant("COMMON.ASSIGNED_TO.NOT_ASSIGNED"),
imgurl: "/#{window._version}/images/unnamed.png"
}
member = $scope.usersById[issue.assigned_to]
avatar = avatarService.getAvatar(member)
ctx.imgurl = avatar.url
ctx.bg = null
if member
ctx.name = member.full_name_display
ctx.bg = avatar.bg
$el.find(".avatar").html(template(ctx))
$el.find(".issue-assignedto").attr('title', ctx.name)
$ctrl = $el.controller()
issue = $scope.$eval($attrs.tgIssueAssignedToInlineEdition)
updateIssue(issue)
$el.on "click", ".issue-assignedto", (event) ->
onClose = (assignedUsers) =>
issue.assigned_to = assignedUsers.pop() || null
$repo.save(issue).then ->
updateIssue(issue)
$rootscope.$broadcast("assigned-to:changed", issue)
$lightboxFactory.create(
'tg-lb-select-user',
{
"class": "lightbox lightbox-select-user",
},
{
"currentUsers": [issue.assigned_to],
"activeUsers": $scope.activeUsers,
"onClose": onClose,
"single": true,
"lbTitle": $translate.instant("COMMON.ASSIGNED_USERS.ADD"),
}
)
taiga.bindOnce $scope, "project", (project) ->
# If the user has not enough permissions the click events are unbinded
if project.my_permissions.indexOf("modify_issue") == -1
$el.unbind("click")
$el.find("a").addClass("not-clickable")
$scope.$watch $attrs.tgIssueAssignedToInlineEdition, (val) ->
updateIssue(val)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgIssueAssignedToInlineEdition", ["$tgRepo", "$rootScope", "$translate", "tgAvatarService",
"tgLightboxFactory", IssueAssignedToInlineEditionDirective])
|
[
{
"context": "exp: ///(^|#{bcv_parser::regexps.pre_book})(\n\t\t(?:Yole|Joel)\n\t\t\t)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)\\uff08\\",
"end": 14137,
"score": 0.9772212505340576,
"start": 14133,
"tag": "NAME",
"value": "Yole"
},
{
"context": "///(^|#{bcv_parser::regexps.pre_book})(\... | lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/tl/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]
| (?:titik|pamagat) (?! [a-z] ) #could be followed by a number
| kapitulo | talatang | pangkat | pang | kap | tal | at | k | -
| [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* (?:titik|pamagat)
| \d \W* k (?: [\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 = "(?:Unang|Una|1|I)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Ikalawang|2|II)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:Ikatlong|3|III)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|at|-)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Henesis|Gen(?:esis)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ex(?:o(?:d(?:us|o)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Si[\s\xa0]*Bel[\s\xa0]*at[\s\xa0]*ang[\s\xa0]*Dragon|Bel(?:[\s\xa0]*at[\s\xa0]*ang[\s\xa0]*Dragon)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Le(?:b(?:iti(?:kus|co))?|v(?:itico)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*Bilang|B(?:[ae]midbar|il)|Num|Blg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Karunungan[\s\xa0]*ni[\s\xa0]*Jesus,?[\s\xa0]*Anak[\s\xa0]*ni[\s\xa0]*Sirac|Karunungan[\s\xa0]*ng[\s\xa0]*Anak[\s\xa0]*ni[\s\xa0]*Sirac|E(?:k(?:kles[iy]|les[iy])astik(?:us|o)|c(?:clesiastic(?:us|o)|lesiastico))|Sir(?:\xE1(?:[ck]id[ae]s|[ck]h)|a(?:k(?:id[ae]s|h)|c(?:id[ae]s|h)))|Sir(?:\xE1[ck]id[ae]|a(?:k(?:id[ae])?|cid[ae])|\xE1[ck])?)|(?:Sirac)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Aklat[\s\xa0]*ng[\s\xa0]*Pa(?:nan|gt)aghoy|Mga[\s\xa0]*Lamentasyon|Mga[\s\xa0]*Panaghoy|Panaghoy|Panag|Lam)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Liham[\s\xa0]*ni[\s\xa0]*Jeremias|Liham[\s\xa0]*ni[\s\xa0]*Jeremias|(?:Li(?:[\s\xa0]*ni|h)[\s\xa0]*|Ep)Jer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Apo[ck](?:alipsis(?:[\s\xa0]*ni[\s\xa0]*Juan)?)?|Pahayag[\s\xa0]*kay[\s\xa0]*Juan|Rebelasyon|Pah(?:ayag)?|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Panalangin[\s\xa0]*ni[\s\xa0]*Manases|Panalangin[\s\xa0]*ni[\s\xa0]*Manases|Dalangin[\s\xa0]*ni[\s\xa0]*Manases|Dasal[\s\xa0]*ni[\s\xa0]*Manases|PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:i?yuteronomyo|e(?:yuteronomyo|ut(?:eronom(?:i(?:y[ao]|[ao])?|y?a))?)|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jos(?:h(?:ua)?|u[e\xE9])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*Hukom|Hukom|Judg|Huk)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ruth?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*E(?:sdras|zra)|[\s\xa0]*E(?:sdras|zra))|[1I]\.[\s\xa0]*E(?:sdras|zra)|1(?:[\s\xa0]*Esdras|[\s\xa0]*Ezra|[\s\xa0]*Esd|Esd)|I[\s\xa0]*E(?:sdras|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*E(?:sdras|zra)|I(?:\.[\s\xa0]*E(?:sdras|zra)|[\s\xa0]*E(?:sdras|zra)))|2(?:\.[\s\xa0]*E(?:sdras|zra)|[\s\xa0]*Esdras|[\s\xa0]*Ezra|[\s\xa0]*Esd|Esd))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Is(?:a(?:[i\xED]a[hs]?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang|I\.?)[\s\xa0]*Samuel|2(?:\.[\s\xa0]*Samuel|[\s\xa0]*Samuel|[\s\xa0]*?Sam))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng)?[\s\xa0]*Samuel|[1I]\.[\s\xa0]*Samuel|1(?:[\s\xa0]*Samuel|[\s\xa0]*?Sam)|I[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ka(?:lawang[\s\xa0]*(?:Mga[\s\xa0]*)?|apat[\s\xa0]*Mga[\s\xa0]*)|V\.?[\s\xa0]*Mga[\s\xa0]*|I\.[\s\xa0]*(?:Mga[\s\xa0]*)?|I[\s\xa0]*(?:Mga[\s\xa0]*)?)Hari|(?:4\.|[24])[\s\xa0]*Mga[\s\xa0]*Hari|2\.[\s\xa0]*(?:Mga[\s\xa0]*)?Hari|2(?:[\s\xa0]*Hari|[\s\xa0]*Ha|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:katlong[\s\xa0]*Mga|II\.[\s\xa0]*Mga|II[\s\xa0]*Mga|\.?[\s\xa0]*Mga|\.)?[\s\xa0]*Hari|(?:Unang|Una|1\.|1)[\s\xa0]*Mga[\s\xa0]*Hari|3\.[\s\xa0]*Mga[\s\xa0]*Hari|(?:Unang|Una|1\.)[\s\xa0]*Hari|3[\s\xa0]*Mga[\s\xa0]*Hari|1(?:[\s\xa0]*Hari|[\s\xa0]*Ha|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|I(?:\.[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)))|2(?:\.[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|[\s\xa0]*Paralipomeno|[\s\xa0]*Mga[\s\xa0]*(?:Kronik|Cronic)a|[\s\xa0]*Chronicle|[\s\xa0]*Kronik(?:el|a)|[\s\xa0]*Cronica|[\s\xa0]*Cron?|Chr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica))|[1I]\.[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|1(?:[\s\xa0]*Paralipomeno|[\s\xa0]*Mga[\s\xa0]*(?:Kronik|Cronic)a|[\s\xa0]*Chronicle|[\s\xa0]*Kronik(?:el|a)|[\s\xa0]*Cronica|[\s\xa0]*Cron?|Chr)|I[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:sdras|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:em[i\xED]a[hs])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er[\s\xa0]*(?:\(Gr(?:iy?|y)?ego\)|Gr(?:iy?|y)?ego)|g)|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:h(?:er)?|er)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Job)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Aw(?:it[\s\xa0]*ng[\s\xa0]*(?:Tatlong[\s\xa0]*(?:B(?:anal[\s\xa0]*na[\s\xa0]*Kabataan|inata)|Kabataan(?:g[\s\xa0]*Banal)?)|3[\s\xa0]*Kabataan)|[\s\xa0]*ng[\s\xa0]*3[\s\xa0]*Kab)|Tatlong[\s\xa0]*Kabataan|SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:A(?:ng[\s\xa0]*Awit[\s\xa0]*n(?:g[\s\xa0]*mga[\s\xa0]*Awit|i[\s\xa0]*S[ao]lom[o\xF3]n)|wit[\s\xa0]*n(?:g[\s\xa0]*mga[\s\xa0]*Awit|i[\s\xa0]*S[ao]lom[o\xF3]n)|\.?[\s\xa0]*ng[\s\xa0]*A|w[\s\xa0]*ni[\s\xa0]*S)|Kantik(?:ul)?o|Song)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*(?:Salmo|Awit)|Salmo|Awit|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Karunungan[\s\xa0]*ni[\s\xa0]*S[ao]lom[o\xF3]n|Karunungan[\s\xa0]*ni[\s\xa0]*S[ao]lom[o\xF3]n|Kar(?:unungan)?|S[ao]lom[o\xF3]n|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Panalangin[\s\xa0]*ni[\s\xa0]*Azarias|P(?:analangin[\s\xa0]*ni[\s\xa0]*Azarias|rAzar))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*Kawikaan|Kawikaan|Prov|Kaw)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Mangangaral|E(?:c(?:clesiaste|l(?:es[iy]ast[e\xE9]|is[iy]aste))|kl(?:es[iy]ast[e\xE9]|is[iy]aste))s|Mangangaral|Kohelet|Manga|Ec(?:cl)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Sulat[\s\xa0]*ni[\s\xa0]*Jeremi|H[ei]r[ei]m[iy])as|Aklat[\s\xa0]*ni[\s\xa0]*Jeremia[hs]|Jeremia[hs]|Jer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:ze(?:quiel|k[iy]el|k)?|sek[iy]el))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Dan(?:iel)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hos(?:e(?:ias?|as?))?|Os(?:e(?:ia[hs]|a[hs])|ei?a)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yole|Joel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am[o\xF3]s)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Oba(?:d(?:ia[hs])?)?|Abd[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:[a\xE1][hs]?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mi(?:queas|k(?:ieas|ey?as|a[hs]|a)?|c(?:a[hs]|a)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Nah(?:[u\xFA]m)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:a(?:kk?uk|cuc))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ze(?:p(?:h(?:ania[hs])?|anias)|f(?:anias)?)|S(?:(?:e[fp]ani|ofon[i\xED])as|e[fp]ania))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hag(?:g(?:eo|ai)|eo|ai)?|Ag(?:g?eo|ai))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:ech(?:ariah)?|ac(?:ar[i\xED]as)?)|Sacar[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:a(?:qu[i\xED]as|kias|chi))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:a(?:buting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*)?Mateo|t(?:eo|t)?)|t)|Ebanghelyo[\s\xa0]*(?:ayon[\s\xa0]*kay[\s\xa0]*|ni[\s\xa0]*(?:San[\s\xa0]*)?)Mateo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:a(?:buting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*Mar[ck]|Mar[ck])os|r(?:kos|cos|k)?)|c)|Ebanghelyo[\s\xa0]*(?:ayon[\s\xa0]*kay[\s\xa0]*Marc|ni[\s\xa0]*(?:San[\s\xa0]*Mar[ck]|Mar[ck]))os)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mabuting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*Lu[ck]|Lu[ck])as|Ebanghelyo[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*Lu[ck]|Lu[ck])as|Ebanghelyo[\s\xa0]*ni[\s\xa0]*San[\s\xa0]*Lu[ck]as|Lu(?:[ck]as|ke|c)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:Una(?:ng)?[\s\xa0]*Jua|[1I]\.[\s\xa0]*Jua|1(?:[\s\xa0]*Jua|Joh|[\s\xa0]*J)|I[\s\xa0]*Jua)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:I(?:kalawang|I\.?)[\s\xa0]*Jua|2(?:\.[\s\xa0]*Jua|[\s\xa0]*Jua|Joh|[\s\xa0]*J))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:I(?:katlong|II\.?)[\s\xa0]*Jua|3(?:\.[\s\xa0]*Jua|[\s\xa0]*Jua|Joh|[\s\xa0]*J))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Mabuting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*)?Jua|Ebanghelyo[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*)?Jua|Ebanghelyo[\s\xa0]*ni[\s\xa0]*San[\s\xa0]*Jua|J(?:oh|ua)?)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:abuting[\s\xa0]*Balita[\s\xa0]*(?:ayon[\s\xa0]*sa|ng)[\s\xa0]*Espiritu[\s\xa0]*Santo|ga[\s\xa0]*Gawa(?:[\s\xa0]*ng[\s\xa0]*mga[\s\xa0]*A(?:postoles|lagad)|[\s\xa0]*ng[\s\xa0]*mga[\s\xa0]*Apostol|in)?)|Ebanghelyo[\s\xa0]*ng[\s\xa0]*Espiritu[\s\xa0]*Santo|G(?:awa[\s\xa0]*ng[\s\xa0]*mga[\s\xa0]*Apostol|w)|(?:Gawa[\s\xa0]*ng[\s\xa0]*Apostole|Act)s|Gawa)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Romano|(?:Mga[\s\xa0]*Taga(?:\-?[\s\xa0]*?|[\s\xa0]*)|Taga\-?[\s\xa0]*)?Roma|Rom?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:SECOND[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?o|I(?:ka(?:\-?[\s\xa0]*2[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?|lawang[\s\xa0]*(?:Mga[\s\xa0]*Taga\-?[\s\xa0]*Corint|[CK]orinti?)|[\s\xa0]*2[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?)|I(?:(?:\.[\s\xa0]*Mga[\s\xa0]*Taga\-?|[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corint|(?:\.[\s\xa0]*[CK]|[\s\xa0]*[CK])orinti?))o|2(?:(?:\.[\s\xa0]*Mga[\s\xa0]*Taga\-?|[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corinto|(?:\.[\s\xa0]*[CK]|[\s\xa0]*K)orinti?o|[\s\xa0]*Corinti?o|[\s\xa0]*?Cor))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ka(?:\-?[\s\xa0]*1[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?|[\s\xa0]*1[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?)|\.?[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?|(?:\.[\s\xa0]*Mga[\s\xa0]*Taga\-?|[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corint|(?:\.[\s\xa0]*[CK]|[\s\xa0]*[CK])orinti?)o|(?:Unang|Una|1\.)[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?o|(?:(?:Unang|1\.)[\s\xa0]*Mga[\s\xa0]*Taga\-?|Una[\s\xa0]*Mga[\s\xa0]*Taga\-?|1[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corinto|(?:(?:Unang|1\.)[\s\xa0]*[CK]|Una[\s\xa0]*[CK]|1[\s\xa0]*K)orinti?o|1[\s\xa0]*Corinti?o|1[\s\xa0]*?Cor)|(?:1[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?o)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*(?:taga[\s\xa0]*)?Galacia|Mga[\s\xa0]*Taga\-?[\s\xa0]*Galasya|(?:Mga[\s\xa0]*Taga\-?[\s\xa0]*)?Galacia|Mga[\s\xa0]*Taga\-?Galacia|Taga\-?[\s\xa0]*Galacia|Taga[\s\xa0]*Galacia|Ga(?:lasyano|l)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*E[fp]esi?o|Mga[\s\xa0]*Taga\-?[\s\xa0]*E[fp]esi?o|Mga[\s\xa0]*Taga\-?Efeso|E(?:ph|f))|(?:(?:Taga(?:\-?[\s\xa0]*E[fp]esi?|[\s\xa0]*E[fp]esi?)|Mga[\s\xa0]*E[fp]esi?|E[fp]esi?)o)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*(?:Pilip(?:yano|ense)|Filipense)|Mga[\s\xa0]*Taga(?:\-?(?:[\s\xa0]*[FP]|F)|[\s\xa0]*[FP])ilipos|Taga\-?[\s\xa0]*[FP]ilipos|Mga[\s\xa0]*Pilipyano|Mga[\s\xa0]*Pilipense|Mga[\s\xa0]*Filipense|Filipos|Pilipos|Phil|Fil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*[CK]olon?sense|(?:Mga[\s\xa0]*Taga(?:\-?(?:[\s\xa0]*[CK]|C)|[\s\xa0]*[CK])|Taga\-?[\s\xa0]*C|C|K)olosas|Mga[\s\xa0]*[CK]olon?sense|Col?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|I(?:\.[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))))|2(?:\.[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|[\s\xa0]*Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|[\s\xa0]*Tesalonicense|[\s\xa0]*Tesalonisense|[\s\xa0]*Tesalonica|[\s\xa0]*Tesalonika|(?:Thes|[\s\xa0]*The)s|[\s\xa0]*Tes))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka)))|[1I]\.[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|1(?:[\s\xa0]*Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|[\s\xa0]*Tesalonicense|[\s\xa0]*Tesalonisense|[\s\xa0]*Tesalonica|[\s\xa0]*Tesalonika|(?:Thes|[\s\xa0]*The)s|[\s\xa0]*Tes)|I[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*(?:Kay[\s\xa0]*)?|I(?:\.[\s\xa0]*(?:Kay[\s\xa0]*)?|[\s\xa0]*(?:Kay[\s\xa0]*)?))Timoteo|2(?:\.[\s\xa0]*(?:Kay[\s\xa0]*)?Timoteo|[\s\xa0]*Kay[\s\xa0]*Timoteo|[\s\xa0]*Timoteo|[\s\xa0]*?Tim))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*(?:Kay[\s\xa0]*)?|[\s\xa0]*(?:Kay[\s\xa0]*)?)Timoteo|[1I]\.[\s\xa0]*(?:Kay[\s\xa0]*)?Timoteo|1(?:[\s\xa0]*Kay[\s\xa0]*Timoteo|[\s\xa0]*Timoteo|[\s\xa0]*?Tim)|I[\s\xa0]*(?:Kay[\s\xa0]*)?Timoteo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kay[\s\xa0]*Tito|Tit(?:us|o)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kay[\s\xa0]*Filemon|Filemon|(?:File|(?:Ph|F)l)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*(?:He|E)breo|Heb(?:reo)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:San(?:t(?:iago)?)?|Ja(?:cobo|s))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang|I\.?)[\s\xa0]*Pedro|2(?:\.[\s\xa0]*Pedro|[\s\xa0]*Pedro|[\s\xa0]*Ped|Pet))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng)?[\s\xa0]*Pedro|[1I]\.[\s\xa0]*Pedro|1(?:[\s\xa0]*Pedro|[\s\xa0]*Ped|Pet)|I[\s\xa0]*Pedro)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ju(?:das|de|d)?|Hudas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:\xEDas|i(?:as|t))?|b))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:udith?|dt))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bar(?:u[ck]h?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:i[\s\xa0]*Susana|u(?:sana|s)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|I(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)))|2(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:katlong[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|II(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)))|3(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kaapat[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|V(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)))|4(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?))|[1I]\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|1(?:[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb)|I[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek", "Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez)
)(?:(?=[\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"
| 221453 | 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]
| (?:titik|pamagat) (?! [a-z] ) #could be followed by a number
| kapitulo | talatang | pangkat | pang | kap | tal | at | k | -
| [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* (?:titik|pamagat)
| \d \W* k (?: [\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 = "(?:Unang|Una|1|I)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Ikalawang|2|II)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:Ikatlong|3|III)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|at|-)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Henesis|Gen(?:esis)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ex(?:o(?:d(?:us|o)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Si[\s\xa0]*Bel[\s\xa0]*at[\s\xa0]*ang[\s\xa0]*Dragon|Bel(?:[\s\xa0]*at[\s\xa0]*ang[\s\xa0]*Dragon)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Le(?:b(?:iti(?:kus|co))?|v(?:itico)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*Bilang|B(?:[ae]midbar|il)|Num|Blg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Karunungan[\s\xa0]*ni[\s\xa0]*Jesus,?[\s\xa0]*Anak[\s\xa0]*ni[\s\xa0]*Sirac|Karunungan[\s\xa0]*ng[\s\xa0]*Anak[\s\xa0]*ni[\s\xa0]*Sirac|E(?:k(?:kles[iy]|les[iy])astik(?:us|o)|c(?:clesiastic(?:us|o)|lesiastico))|Sir(?:\xE1(?:[ck]id[ae]s|[ck]h)|a(?:k(?:id[ae]s|h)|c(?:id[ae]s|h)))|Sir(?:\xE1[ck]id[ae]|a(?:k(?:id[ae])?|cid[ae])|\xE1[ck])?)|(?:Sirac)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Aklat[\s\xa0]*ng[\s\xa0]*Pa(?:nan|gt)aghoy|Mga[\s\xa0]*Lamentasyon|Mga[\s\xa0]*Panaghoy|Panaghoy|Panag|Lam)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Liham[\s\xa0]*ni[\s\xa0]*Jeremias|Liham[\s\xa0]*ni[\s\xa0]*Jeremias|(?:Li(?:[\s\xa0]*ni|h)[\s\xa0]*|Ep)Jer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Apo[ck](?:alipsis(?:[\s\xa0]*ni[\s\xa0]*Juan)?)?|Pahayag[\s\xa0]*kay[\s\xa0]*Juan|Rebelasyon|Pah(?:ayag)?|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Panalangin[\s\xa0]*ni[\s\xa0]*Manases|Panalangin[\s\xa0]*ni[\s\xa0]*Manases|Dalangin[\s\xa0]*ni[\s\xa0]*Manases|Dasal[\s\xa0]*ni[\s\xa0]*Manases|PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:i?yuteronomyo|e(?:yuteronomyo|ut(?:eronom(?:i(?:y[ao]|[ao])?|y?a))?)|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jos(?:h(?:ua)?|u[e\xE9])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*Hukom|Hukom|Judg|Huk)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ruth?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*E(?:sdras|zra)|[\s\xa0]*E(?:sdras|zra))|[1I]\.[\s\xa0]*E(?:sdras|zra)|1(?:[\s\xa0]*Esdras|[\s\xa0]*Ezra|[\s\xa0]*Esd|Esd)|I[\s\xa0]*E(?:sdras|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*E(?:sdras|zra)|I(?:\.[\s\xa0]*E(?:sdras|zra)|[\s\xa0]*E(?:sdras|zra)))|2(?:\.[\s\xa0]*E(?:sdras|zra)|[\s\xa0]*Esdras|[\s\xa0]*Ezra|[\s\xa0]*Esd|Esd))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Is(?:a(?:[i\xED]a[hs]?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang|I\.?)[\s\xa0]*Samuel|2(?:\.[\s\xa0]*Samuel|[\s\xa0]*Samuel|[\s\xa0]*?Sam))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng)?[\s\xa0]*Samuel|[1I]\.[\s\xa0]*Samuel|1(?:[\s\xa0]*Samuel|[\s\xa0]*?Sam)|I[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ka(?:lawang[\s\xa0]*(?:Mga[\s\xa0]*)?|apat[\s\xa0]*Mga[\s\xa0]*)|V\.?[\s\xa0]*Mga[\s\xa0]*|I\.[\s\xa0]*(?:Mga[\s\xa0]*)?|I[\s\xa0]*(?:Mga[\s\xa0]*)?)Hari|(?:4\.|[24])[\s\xa0]*Mga[\s\xa0]*Hari|2\.[\s\xa0]*(?:Mga[\s\xa0]*)?Hari|2(?:[\s\xa0]*Hari|[\s\xa0]*Ha|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:katlong[\s\xa0]*Mga|II\.[\s\xa0]*Mga|II[\s\xa0]*Mga|\.?[\s\xa0]*Mga|\.)?[\s\xa0]*Hari|(?:Unang|Una|1\.|1)[\s\xa0]*Mga[\s\xa0]*Hari|3\.[\s\xa0]*Mga[\s\xa0]*Hari|(?:Unang|Una|1\.)[\s\xa0]*Hari|3[\s\xa0]*Mga[\s\xa0]*Hari|1(?:[\s\xa0]*Hari|[\s\xa0]*Ha|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|I(?:\.[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)))|2(?:\.[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|[\s\xa0]*Paralipomeno|[\s\xa0]*Mga[\s\xa0]*(?:Kronik|Cronic)a|[\s\xa0]*Chronicle|[\s\xa0]*Kronik(?:el|a)|[\s\xa0]*Cronica|[\s\xa0]*Cron?|Chr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica))|[1I]\.[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|1(?:[\s\xa0]*Paralipomeno|[\s\xa0]*Mga[\s\xa0]*(?:Kronik|Cronic)a|[\s\xa0]*Chronicle|[\s\xa0]*Kronik(?:el|a)|[\s\xa0]*Cronica|[\s\xa0]*Cron?|Chr)|I[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:sdras|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:em[i\xED]a[hs])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er[\s\xa0]*(?:\(Gr(?:iy?|y)?ego\)|Gr(?:iy?|y)?ego)|g)|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:h(?:er)?|er)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Job)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Aw(?:it[\s\xa0]*ng[\s\xa0]*(?:Tatlong[\s\xa0]*(?:B(?:anal[\s\xa0]*na[\s\xa0]*Kabataan|inata)|Kabataan(?:g[\s\xa0]*Banal)?)|3[\s\xa0]*Kabataan)|[\s\xa0]*ng[\s\xa0]*3[\s\xa0]*Kab)|Tatlong[\s\xa0]*Kabataan|SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:A(?:ng[\s\xa0]*Awit[\s\xa0]*n(?:g[\s\xa0]*mga[\s\xa0]*Awit|i[\s\xa0]*S[ao]lom[o\xF3]n)|wit[\s\xa0]*n(?:g[\s\xa0]*mga[\s\xa0]*Awit|i[\s\xa0]*S[ao]lom[o\xF3]n)|\.?[\s\xa0]*ng[\s\xa0]*A|w[\s\xa0]*ni[\s\xa0]*S)|Kantik(?:ul)?o|Song)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*(?:Salmo|Awit)|Salmo|Awit|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Karunungan[\s\xa0]*ni[\s\xa0]*S[ao]lom[o\xF3]n|Karunungan[\s\xa0]*ni[\s\xa0]*S[ao]lom[o\xF3]n|Kar(?:unungan)?|S[ao]lom[o\xF3]n|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Panalangin[\s\xa0]*ni[\s\xa0]*Azarias|P(?:analangin[\s\xa0]*ni[\s\xa0]*Azarias|rAzar))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*Kawikaan|Kawikaan|Prov|Kaw)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Mangangaral|E(?:c(?:clesiaste|l(?:es[iy]ast[e\xE9]|is[iy]aste))|kl(?:es[iy]ast[e\xE9]|is[iy]aste))s|Mangangaral|Kohelet|Manga|Ec(?:cl)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Sulat[\s\xa0]*ni[\s\xa0]*Jeremi|H[ei]r[ei]m[iy])as|Aklat[\s\xa0]*ni[\s\xa0]*Jeremia[hs]|Jeremia[hs]|Jer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:ze(?:quiel|k[iy]el|k)?|sek[iy]el))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Dan(?:iel)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hos(?:e(?:ias?|as?))?|Os(?:e(?:ia[hs]|a[hs])|ei?a)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:<NAME>|<NAME>)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am[o\xF3]s)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Oba(?:d(?:ia[hs])?)?|Abd[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:[a\xE1][hs]?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mi(?:queas|k(?:ieas|ey?as|a[hs]|a)?|c(?:a[hs]|a)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Nah(?:[u\xFA]m)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:a(?:kk?uk|cuc))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ze(?:p(?:h(?:ania[hs])?|anias)|f(?:anias)?)|S(?:(?:e[fp]ani|ofon[i\xED])as|e[fp]ania))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hag(?:g(?:eo|ai)|eo|ai)?|Ag(?:g?eo|ai))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:ech(?:ariah)?|ac(?:ar[i\xED]as)?)|Sacar[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:a(?:qu[i\xED]as|kias|chi))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:a(?:buting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*)?Mateo|t(?:eo|t)?)|t)|Ebanghelyo[\s\xa0]*(?:ayon[\s\xa0]*kay[\s\xa0]*|ni[\s\xa0]*(?:San[\s\xa0]*)?)Mateo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:a(?:buting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*Mar[ck]|Mar[ck])os|r(?:kos|cos|k)?)|c)|Ebanghelyo[\s\xa0]*(?:ayon[\s\xa0]*kay[\s\xa0]*Marc|ni[\s\xa0]*(?:San[\s\xa0]*Mar[ck]|Mar[ck]))os)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mabuting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*Lu[ck]|Lu[ck])as|Ebanghelyo[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*Lu[ck]|Lu[ck])as|Ebanghelyo[\s\xa0]*ni[\s\xa0]*San[\s\xa0]*Lu[ck]as|Lu(?:[ck]as|ke|c)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:Una(?:ng)?[\s\xa0]*Jua|[1I]\.[\s\xa0]*Jua|1(?:[\s\xa0]*Jua|Joh|[\s\xa0]*J)|I[\s\xa0]*Jua)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2<NAME>"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:I(?:kalawang|I\.?)[\s\xa0]*Jua|2(?:\.[\s\xa0]*Jua|[\s\xa0]*Jua|Joh|[\s\xa0]*J))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3<NAME>"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:I(?:katlong|II\.?)[\s\xa0]*Jua|3(?:\.[\s\xa0]*Jua|[\s\xa0]*Jua|Joh|[\s\xa0]*J))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Mabuting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*)?Jua|Ebanghelyo[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*)?Jua|Ebanghelyo[\s\xa0]*ni[\s\xa0]*San[\s\xa0]*Jua|J(?:oh|ua)?)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:abuting[\s\xa0]*Balita[\s\xa0]*(?:ayon[\s\xa0]*sa|ng)[\s\xa0]*Espiritu[\s\xa0]*Santo|ga[\s\xa0]*Gawa(?:[\s\xa0]*ng[\s\xa0]*mga[\s\xa0]*A(?:postoles|lagad)|[\s\xa0]*ng[\s\xa0]*mga[\s\xa0]*Apostol|in)?)|Ebanghelyo[\s\xa0]*ng[\s\xa0]*Espiritu[\s\xa0]*Santo|G(?:awa[\s\xa0]*ng[\s\xa0]*mga[\s\xa0]*Apostol|w)|(?:Gawa[\s\xa0]*ng[\s\xa0]*Apostole|Act)s|Gawa)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Romano|(?:Mga[\s\xa0]*Taga(?:\-?[\s\xa0]*?|[\s\xa0]*)|Taga\-?[\s\xa0]*)?Roma|Rom?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:SECOND[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?o|I(?:ka(?:\-?[\s\xa0]*2[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?|lawang[\s\xa0]*(?:Mga[\s\xa0]*Taga\-?[\s\xa0]*Corint|[CK]orinti?)|[\s\xa0]*2[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?)|I(?:(?:\.[\s\xa0]*Mga[\s\xa0]*Taga\-?|[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corint|(?:\.[\s\xa0]*[CK]|[\s\xa0]*[CK])orinti?))o|2(?:(?:\.[\s\xa0]*Mga[\s\xa0]*Taga\-?|[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corinto|(?:\.[\s\xa0]*[CK]|[\s\xa0]*K)orinti?o|[\s\xa0]*Corinti?o|[\s\xa0]*?Cor))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ka(?:\-?[\s\xa0]*1[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?|[\s\xa0]*1[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?)|\.?[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?|(?:\.[\s\xa0]*Mga[\s\xa0]*Taga\-?|[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corint|(?:\.[\s\xa0]*[CK]|[\s\xa0]*[CK])orinti?)o|(?:Unang|Una|1\.)[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?o|(?:(?:Unang|1\.)[\s\xa0]*Mga[\s\xa0]*Taga\-?|Una[\s\xa0]*Mga[\s\xa0]*Taga\-?|1[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corinto|(?:(?:Unang|1\.)[\s\xa0]*[CK]|Una[\s\xa0]*[CK]|1[\s\xa0]*K)orinti?o|1[\s\xa0]*Corinti?o|1[\s\xa0]*?Cor)|(?:1[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?o)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*(?:taga[\s\xa0]*)?Galacia|Mga[\s\xa0]*Taga\-?[\s\xa0]*Galasya|(?:Mga[\s\xa0]*Taga\-?[\s\xa0]*)?Galacia|Mga[\s\xa0]*Taga\-?Galacia|Taga\-?[\s\xa0]*Galacia|Taga[\s\xa0]*Galacia|Ga(?:lasyano|l)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*E[fp]esi?o|Mga[\s\xa0]*Taga\-?[\s\xa0]*E[fp]esi?o|Mga[\s\xa0]*Taga\-?Efeso|E(?:ph|f))|(?:(?:Taga(?:\-?[\s\xa0]*E[fp]esi?|[\s\xa0]*E[fp]esi?)|Mga[\s\xa0]*E[fp]esi?|E[fp]esi?)o)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*(?:Pilip(?:yano|ense)|Filipense)|Mga[\s\xa0]*Taga(?:\-?(?:[\s\xa0]*[FP]|F)|[\s\xa0]*[FP])ilipos|Taga\-?[\s\xa0]*[FP]ilipos|Mga[\s\xa0]*Pilipyano|Mga[\s\xa0]*Pilipense|Mga[\s\xa0]*Filipense|Filipos|Pilipos|Phil|Fil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*[CK]olon?sense|(?:Mga[\s\xa0]*Taga(?:\-?(?:[\s\xa0]*[CK]|C)|[\s\xa0]*[CK])|Taga\-?[\s\xa0]*C|C|K)olosas|Mga[\s\xa0]*[CK]olon?sense|Col?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|I(?:\.[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))))|2(?:\.[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|[\s\xa0]*Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|[\s\xa0]*Tesalonicense|[\s\xa0]*Tesalonisense|[\s\xa0]*Tesalonica|[\s\xa0]*Tesalonika|(?:Thes|[\s\xa0]*The)s|[\s\xa0]*Tes))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka)))|[1I]\.[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|1(?:[\s\xa0]*Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|[\s\xa0]*Tesalonicense|[\s\xa0]*Tesalonisense|[\s\xa0]*Tesalonica|[\s\xa0]*Tesalonika|(?:Thes|[\s\xa0]*The)s|[\s\xa0]*Tes)|I[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*(?:Kay[\s\xa0]*)?|I(?:\.[\s\xa0]*(?:Kay[\s\xa0]*)?|[\s\xa0]*(?:Kay[\s\xa0]*)?))Timoteo|2(?:\.[\s\xa0]*(?:Kay[\s\xa0]*)?Timoteo|[\s\xa0]*Kay[\s\xa0]*Timoteo|[\s\xa0]*Timoteo|[\s\xa0]*?Tim))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*(?:Kay[\s\xa0]*)?|[\s\xa0]*(?:Kay[\s\xa0]*)?)Timoteo|[1I]\.[\s\xa0]*(?:Kay[\s\xa0]*)?Timoteo|1(?:[\s\xa0]*Kay[\s\xa0]*Timoteo|[\s\xa0]*Timoteo|[\s\xa0]*?Tim)|I[\s\xa0]*(?:Kay[\s\xa0]*)?Timoteo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kay[\s\xa0]*Tito|Tit(?:us|o)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kay[\s\xa0]*Filemon|Filemon|(?:File|(?:Ph|F)l)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*(?:He|E)breo|Heb(?:reo)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:San(?:t(?:iago)?)?|Ja(?:cobo|s))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang|I\.?)[\s\xa0]*Pedro|2(?:\.[\s\xa0]*Pedro|[\s\xa0]*Pedro|[\s\xa0]*Ped|Pet))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng)?[\s\xa0]*Pedro|[1I]\.[\s\xa0]*Pedro|1(?:[\s\xa0]*Pedro|[\s\xa0]*Ped|Pet)|I[\s\xa0]*Pedro)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ju(?:das|de|d)?|Hudas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:\xEDas|i(?:as|t))?|b))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:udith?|dt))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bar(?:u[ck]h?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:i[\s\xa0]*Susana|u(?:sana|s)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|I(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)))|2(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:katlong[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|II(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)))|3(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kaapat[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|V(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)))|4(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?))|[1I]\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|1(?:[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb)|I[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek", "Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez)
)(?:(?=[\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]
| (?:titik|pamagat) (?! [a-z] ) #could be followed by a number
| kapitulo | talatang | pangkat | pang | kap | tal | at | k | -
| [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* (?:titik|pamagat)
| \d \W* k (?: [\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 = "(?:Unang|Una|1|I)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Ikalawang|2|II)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:Ikatlong|3|III)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|at|-)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Henesis|Gen(?:esis)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ex(?:o(?:d(?:us|o)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Si[\s\xa0]*Bel[\s\xa0]*at[\s\xa0]*ang[\s\xa0]*Dragon|Bel(?:[\s\xa0]*at[\s\xa0]*ang[\s\xa0]*Dragon)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Le(?:b(?:iti(?:kus|co))?|v(?:itico)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*Bilang|B(?:[ae]midbar|il)|Num|Blg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Karunungan[\s\xa0]*ni[\s\xa0]*Jesus,?[\s\xa0]*Anak[\s\xa0]*ni[\s\xa0]*Sirac|Karunungan[\s\xa0]*ng[\s\xa0]*Anak[\s\xa0]*ni[\s\xa0]*Sirac|E(?:k(?:kles[iy]|les[iy])astik(?:us|o)|c(?:clesiastic(?:us|o)|lesiastico))|Sir(?:\xE1(?:[ck]id[ae]s|[ck]h)|a(?:k(?:id[ae]s|h)|c(?:id[ae]s|h)))|Sir(?:\xE1[ck]id[ae]|a(?:k(?:id[ae])?|cid[ae])|\xE1[ck])?)|(?:Sirac)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Aklat[\s\xa0]*ng[\s\xa0]*Pa(?:nan|gt)aghoy|Mga[\s\xa0]*Lamentasyon|Mga[\s\xa0]*Panaghoy|Panaghoy|Panag|Lam)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Liham[\s\xa0]*ni[\s\xa0]*Jeremias|Liham[\s\xa0]*ni[\s\xa0]*Jeremias|(?:Li(?:[\s\xa0]*ni|h)[\s\xa0]*|Ep)Jer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Apo[ck](?:alipsis(?:[\s\xa0]*ni[\s\xa0]*Juan)?)?|Pahayag[\s\xa0]*kay[\s\xa0]*Juan|Rebelasyon|Pah(?:ayag)?|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Panalangin[\s\xa0]*ni[\s\xa0]*Manases|Panalangin[\s\xa0]*ni[\s\xa0]*Manases|Dalangin[\s\xa0]*ni[\s\xa0]*Manases|Dasal[\s\xa0]*ni[\s\xa0]*Manases|PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:i?yuteronomyo|e(?:yuteronomyo|ut(?:eronom(?:i(?:y[ao]|[ao])?|y?a))?)|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jos(?:h(?:ua)?|u[e\xE9])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*Hukom|Hukom|Judg|Huk)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ruth?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*E(?:sdras|zra)|[\s\xa0]*E(?:sdras|zra))|[1I]\.[\s\xa0]*E(?:sdras|zra)|1(?:[\s\xa0]*Esdras|[\s\xa0]*Ezra|[\s\xa0]*Esd|Esd)|I[\s\xa0]*E(?:sdras|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*E(?:sdras|zra)|I(?:\.[\s\xa0]*E(?:sdras|zra)|[\s\xa0]*E(?:sdras|zra)))|2(?:\.[\s\xa0]*E(?:sdras|zra)|[\s\xa0]*Esdras|[\s\xa0]*Ezra|[\s\xa0]*Esd|Esd))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Is(?:a(?:[i\xED]a[hs]?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang|I\.?)[\s\xa0]*Samuel|2(?:\.[\s\xa0]*Samuel|[\s\xa0]*Samuel|[\s\xa0]*?Sam))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng)?[\s\xa0]*Samuel|[1I]\.[\s\xa0]*Samuel|1(?:[\s\xa0]*Samuel|[\s\xa0]*?Sam)|I[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ka(?:lawang[\s\xa0]*(?:Mga[\s\xa0]*)?|apat[\s\xa0]*Mga[\s\xa0]*)|V\.?[\s\xa0]*Mga[\s\xa0]*|I\.[\s\xa0]*(?:Mga[\s\xa0]*)?|I[\s\xa0]*(?:Mga[\s\xa0]*)?)Hari|(?:4\.|[24])[\s\xa0]*Mga[\s\xa0]*Hari|2\.[\s\xa0]*(?:Mga[\s\xa0]*)?Hari|2(?:[\s\xa0]*Hari|[\s\xa0]*Ha|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:katlong[\s\xa0]*Mga|II\.[\s\xa0]*Mga|II[\s\xa0]*Mga|\.?[\s\xa0]*Mga|\.)?[\s\xa0]*Hari|(?:Unang|Una|1\.|1)[\s\xa0]*Mga[\s\xa0]*Hari|3\.[\s\xa0]*Mga[\s\xa0]*Hari|(?:Unang|Una|1\.)[\s\xa0]*Hari|3[\s\xa0]*Mga[\s\xa0]*Hari|1(?:[\s\xa0]*Hari|[\s\xa0]*Ha|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|I(?:\.[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)))|2(?:\.[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|[\s\xa0]*Paralipomeno|[\s\xa0]*Mga[\s\xa0]*(?:Kronik|Cronic)a|[\s\xa0]*Chronicle|[\s\xa0]*Kronik(?:el|a)|[\s\xa0]*Cronica|[\s\xa0]*Cron?|Chr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica))|[1I]\.[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica)|1(?:[\s\xa0]*Paralipomeno|[\s\xa0]*Mga[\s\xa0]*(?:Kronik|Cronic)a|[\s\xa0]*Chronicle|[\s\xa0]*Kronik(?:el|a)|[\s\xa0]*Cronica|[\s\xa0]*Cron?|Chr)|I[\s\xa0]*(?:Paralipomeno|Mga[\s\xa0]*(?:Kronik|Cronic)a|Chronicle|Kronik(?:el|a)|Cronica))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:sdras|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:em[i\xED]a[hs])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er[\s\xa0]*(?:\(Gr(?:iy?|y)?ego\)|Gr(?:iy?|y)?ego)|g)|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:h(?:er)?|er)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Job)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Aw(?:it[\s\xa0]*ng[\s\xa0]*(?:Tatlong[\s\xa0]*(?:B(?:anal[\s\xa0]*na[\s\xa0]*Kabataan|inata)|Kabataan(?:g[\s\xa0]*Banal)?)|3[\s\xa0]*Kabataan)|[\s\xa0]*ng[\s\xa0]*3[\s\xa0]*Kab)|Tatlong[\s\xa0]*Kabataan|SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:A(?:ng[\s\xa0]*Awit[\s\xa0]*n(?:g[\s\xa0]*mga[\s\xa0]*Awit|i[\s\xa0]*S[ao]lom[o\xF3]n)|wit[\s\xa0]*n(?:g[\s\xa0]*mga[\s\xa0]*Awit|i[\s\xa0]*S[ao]lom[o\xF3]n)|\.?[\s\xa0]*ng[\s\xa0]*A|w[\s\xa0]*ni[\s\xa0]*S)|Kantik(?:ul)?o|Song)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*(?:Salmo|Awit)|Salmo|Awit|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Karunungan[\s\xa0]*ni[\s\xa0]*S[ao]lom[o\xF3]n|Karunungan[\s\xa0]*ni[\s\xa0]*S[ao]lom[o\xF3]n|Kar(?:unungan)?|S[ao]lom[o\xF3]n|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Panalangin[\s\xa0]*ni[\s\xa0]*Azarias|P(?:analangin[\s\xa0]*ni[\s\xa0]*Azarias|rAzar))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*Kawikaan|Kawikaan|Prov|Kaw)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ang[\s\xa0]*Mangangaral|E(?:c(?:clesiaste|l(?:es[iy]ast[e\xE9]|is[iy]aste))|kl(?:es[iy]ast[e\xE9]|is[iy]aste))s|Mangangaral|Kohelet|Manga|Ec(?:cl)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Sulat[\s\xa0]*ni[\s\xa0]*Jeremi|H[ei]r[ei]m[iy])as|Aklat[\s\xa0]*ni[\s\xa0]*Jeremia[hs]|Jeremia[hs]|Jer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:ze(?:quiel|k[iy]el|k)?|sek[iy]el))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Dan(?:iel)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hos(?:e(?:ias?|as?))?|Os(?:e(?:ia[hs]|a[hs])|ei?a)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:PI:NAME:<NAME>END_PI|PI:NAME:<NAME>END_PI)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am[o\xF3]s)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Oba(?:d(?:ia[hs])?)?|Abd[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:[a\xE1][hs]?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mi(?:queas|k(?:ieas|ey?as|a[hs]|a)?|c(?:a[hs]|a)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Nah(?:[u\xFA]m)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:a(?:kk?uk|cuc))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ze(?:p(?:h(?:ania[hs])?|anias)|f(?:anias)?)|S(?:(?:e[fp]ani|ofon[i\xED])as|e[fp]ania))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hag(?:g(?:eo|ai)|eo|ai)?|Ag(?:g?eo|ai))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:ech(?:ariah)?|ac(?:ar[i\xED]as)?)|Sacar[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:a(?:qu[i\xED]as|kias|chi))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:a(?:buting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*)?Mateo|t(?:eo|t)?)|t)|Ebanghelyo[\s\xa0]*(?:ayon[\s\xa0]*kay[\s\xa0]*|ni[\s\xa0]*(?:San[\s\xa0]*)?)Mateo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:a(?:buting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*Mar[ck]|Mar[ck])os|r(?:kos|cos|k)?)|c)|Ebanghelyo[\s\xa0]*(?:ayon[\s\xa0]*kay[\s\xa0]*Marc|ni[\s\xa0]*(?:San[\s\xa0]*Mar[ck]|Mar[ck]))os)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mabuting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*Lu[ck]|Lu[ck])as|Ebanghelyo[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*Lu[ck]|Lu[ck])as|Ebanghelyo[\s\xa0]*ni[\s\xa0]*San[\s\xa0]*Lu[ck]as|Lu(?:[ck]as|ke|c)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:Una(?:ng)?[\s\xa0]*Jua|[1I]\.[\s\xa0]*Jua|1(?:[\s\xa0]*Jua|Joh|[\s\xa0]*J)|I[\s\xa0]*Jua)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2PI:NAME:<NAME>END_PI"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:I(?:kalawang|I\.?)[\s\xa0]*Jua|2(?:\.[\s\xa0]*Jua|[\s\xa0]*Jua|Joh|[\s\xa0]*J))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3PI:NAME:<NAME>END_PI"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:I(?:katlong|II\.?)[\s\xa0]*Jua|3(?:\.[\s\xa0]*Jua|[\s\xa0]*Jua|Joh|[\s\xa0]*J))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Mabuting[\s\xa0]*Balita[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*)?Jua|Ebanghelyo[\s\xa0]*ayon[\s\xa0]*kay[\s\xa0]*(?:San[\s\xa0]*)?Jua|Ebanghelyo[\s\xa0]*ni[\s\xa0]*San[\s\xa0]*Jua|J(?:oh|ua)?)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:abuting[\s\xa0]*Balita[\s\xa0]*(?:ayon[\s\xa0]*sa|ng)[\s\xa0]*Espiritu[\s\xa0]*Santo|ga[\s\xa0]*Gawa(?:[\s\xa0]*ng[\s\xa0]*mga[\s\xa0]*A(?:postoles|lagad)|[\s\xa0]*ng[\s\xa0]*mga[\s\xa0]*Apostol|in)?)|Ebanghelyo[\s\xa0]*ng[\s\xa0]*Espiritu[\s\xa0]*Santo|G(?:awa[\s\xa0]*ng[\s\xa0]*mga[\s\xa0]*Apostol|w)|(?:Gawa[\s\xa0]*ng[\s\xa0]*Apostole|Act)s|Gawa)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Romano|(?:Mga[\s\xa0]*Taga(?:\-?[\s\xa0]*?|[\s\xa0]*)|Taga\-?[\s\xa0]*)?Roma|Rom?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:SECOND[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?o|I(?:ka(?:\-?[\s\xa0]*2[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?|lawang[\s\xa0]*(?:Mga[\s\xa0]*Taga\-?[\s\xa0]*Corint|[CK]orinti?)|[\s\xa0]*2[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?)|I(?:(?:\.[\s\xa0]*Mga[\s\xa0]*Taga\-?|[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corint|(?:\.[\s\xa0]*[CK]|[\s\xa0]*[CK])orinti?))o|2(?:(?:\.[\s\xa0]*Mga[\s\xa0]*Taga\-?|[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corinto|(?:\.[\s\xa0]*[CK]|[\s\xa0]*K)orinti?o|[\s\xa0]*Corinti?o|[\s\xa0]*?Cor))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ka(?:\-?[\s\xa0]*1[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?|[\s\xa0]*1[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?)|\.?[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?|(?:\.[\s\xa0]*Mga[\s\xa0]*Taga\-?|[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corint|(?:\.[\s\xa0]*[CK]|[\s\xa0]*[CK])orinti?)o|(?:Unang|Una|1\.)[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?o|(?:(?:Unang|1\.)[\s\xa0]*Mga[\s\xa0]*Taga\-?|Una[\s\xa0]*Mga[\s\xa0]*Taga\-?|1[\s\xa0]*Mga[\s\xa0]*Taga\-?)[\s\xa0]*Corinto|(?:(?:Unang|1\.)[\s\xa0]*[CK]|Una[\s\xa0]*[CK]|1[\s\xa0]*K)orinti?o|1[\s\xa0]*Corinti?o|1[\s\xa0]*?Cor)|(?:1[\s\xa0]*Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*Corinti?o)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*(?:taga[\s\xa0]*)?Galacia|Mga[\s\xa0]*Taga\-?[\s\xa0]*Galasya|(?:Mga[\s\xa0]*Taga\-?[\s\xa0]*)?Galacia|Mga[\s\xa0]*Taga\-?Galacia|Taga\-?[\s\xa0]*Galacia|Taga[\s\xa0]*Galacia|Ga(?:lasyano|l)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*E[fp]esi?o|Mga[\s\xa0]*Taga\-?[\s\xa0]*E[fp]esi?o|Mga[\s\xa0]*Taga\-?Efeso|E(?:ph|f))|(?:(?:Taga(?:\-?[\s\xa0]*E[fp]esi?|[\s\xa0]*E[fp]esi?)|Mga[\s\xa0]*E[fp]esi?|E[fp]esi?)o)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*(?:Pilip(?:yano|ense)|Filipense)|Mga[\s\xa0]*Taga(?:\-?(?:[\s\xa0]*[FP]|F)|[\s\xa0]*[FP])ilipos|Taga\-?[\s\xa0]*[FP]ilipos|Mga[\s\xa0]*Pilipyano|Mga[\s\xa0]*Pilipense|Mga[\s\xa0]*Filipense|Filipos|Pilipos|Phil|Fil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sulat[\s\xa0]*sa[\s\xa0]*mga[\s\xa0]*[CK]olon?sense|(?:Mga[\s\xa0]*Taga(?:\-?(?:[\s\xa0]*[CK]|C)|[\s\xa0]*[CK])|Taga\-?[\s\xa0]*C|C|K)olosas|Mga[\s\xa0]*[CK]olon?sense|Col?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|I(?:\.[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))))|2(?:\.[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|[\s\xa0]*Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|[\s\xa0]*Tesalonicense|[\s\xa0]*Tesalonisense|[\s\xa0]*Tesalonica|[\s\xa0]*Tesalonika|(?:Thes|[\s\xa0]*The)s|[\s\xa0]*Tes))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka)))|[1I]\.[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka))|1(?:[\s\xa0]*Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|[\s\xa0]*Tesalonicense|[\s\xa0]*Tesalonisense|[\s\xa0]*Tesalonica|[\s\xa0]*Tesalonika|(?:Thes|[\s\xa0]*The)s|[\s\xa0]*Tes)|I[\s\xa0]*(?:Mga[\s\xa0]*T(?:aga(?:\-?[\s\xa0]*Tesaloni[ck]|[\s\xa0]*Tesaloni[ck])a|esaloni[cs]ense)|Tesaloni(?:c(?:ense|a)|sense|ka)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*(?:Kay[\s\xa0]*)?|I(?:\.[\s\xa0]*(?:Kay[\s\xa0]*)?|[\s\xa0]*(?:Kay[\s\xa0]*)?))Timoteo|2(?:\.[\s\xa0]*(?:Kay[\s\xa0]*)?Timoteo|[\s\xa0]*Kay[\s\xa0]*Timoteo|[\s\xa0]*Timoteo|[\s\xa0]*?Tim))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*(?:Kay[\s\xa0]*)?|[\s\xa0]*(?:Kay[\s\xa0]*)?)Timoteo|[1I]\.[\s\xa0]*(?:Kay[\s\xa0]*)?Timoteo|1(?:[\s\xa0]*Kay[\s\xa0]*Timoteo|[\s\xa0]*Timoteo|[\s\xa0]*?Tim)|I[\s\xa0]*(?:Kay[\s\xa0]*)?Timoteo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kay[\s\xa0]*Tito|Tit(?:us|o)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kay[\s\xa0]*Filemon|Filemon|(?:File|(?:Ph|F)l)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mga[\s\xa0]*(?:He|E)breo|Heb(?:reo)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:San(?:t(?:iago)?)?|Ja(?:cobo|s))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang|I\.?)[\s\xa0]*Pedro|2(?:\.[\s\xa0]*Pedro|[\s\xa0]*Pedro|[\s\xa0]*Ped|Pet))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng)?[\s\xa0]*Pedro|[1I]\.[\s\xa0]*Pedro|1(?:[\s\xa0]*Pedro|[\s\xa0]*Ped|Pet)|I[\s\xa0]*Pedro)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ju(?:das|de|d)?|Hudas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:\xEDas|i(?:as|t))?|b))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:udith?|dt))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bar(?:u[ck]h?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:i[\s\xa0]*Susana|u(?:sana|s)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kalawang[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|I(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)))|2(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:katlong[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|II(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)))|3(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:kaapat[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|V(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)))|4(?:\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Una(?:ng[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?))|[1I]\.[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?)|1(?:[\s\xa0]*Mga[\s\xa0]*Macabeo|[\s\xa0]*Macabeos|[\s\xa0]*Macabeo|Macc|[\s\xa0]*Mcb)|I[\s\xa0]*M(?:ga[\s\xa0]*Macabeo|acabeos?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek", "Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez)
)(?:(?=[\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": "module, _utils) ->\n ###\n Modify:\n Author: ec.huyinghuan@gmail.com\n Date: 2015.07.16\n Describe:\n 提取",
"end": 131,
"score": 0.9999114274978638,
"start": 108,
"tag": "EMAIL",
"value": "ec.huyinghuan@gmail.com"
}
] | src/js/commit/commit-controllers.coffee | Kiteam/kiteam-angular | 0 | "use strict"
define [
'../ng-module'
'../utils'
], (_module, _utils) ->
###
Modify:
Author: ec.huyinghuan@gmail.com
Date: 2015.07.16
Describe:
提取首次加载数据为一个函数,并且添加一个事件监听器刷新数据
###
_module.controllerModule.
controller('commitListController', ['$rootScope', '$scope', '$stateParams', 'API', ($rootScope, $scope, $stateParams, API)->
cond = pageSize: 20
loadData = ->
API.project($stateParams.project_id).issue(0).commit()
.retrieve(pageSize: 20).then((result)->
$scope.commit = result
)
loadData()
#同步完成,加载数据
$scope.$on("commit:refresh:ready", ->
loadData()
)
$scope.showImportModal = ->
$scope.$broadcast("commit:import:modal:show")
$rootScope.$on 'pagination:change',(event, page, uuid, cb)->
return if uuid isnt 'commit_pagination'
API.project($stateParams.project_id).issue(0).commit().retrieve(pageSize: 20, pageIndex: page).then((result)->
$scope.commit = result
)
])
#因gitlab的iframe策略,无法被引用
.controller('commitDetailsController', ['$scope', '$sce', '$state', ($scope, $sce, $state)->
$scope.url = $sce.trustAsResourceUrl($state.params.url)
]) | 163610 | "use strict"
define [
'../ng-module'
'../utils'
], (_module, _utils) ->
###
Modify:
Author: <EMAIL>
Date: 2015.07.16
Describe:
提取首次加载数据为一个函数,并且添加一个事件监听器刷新数据
###
_module.controllerModule.
controller('commitListController', ['$rootScope', '$scope', '$stateParams', 'API', ($rootScope, $scope, $stateParams, API)->
cond = pageSize: 20
loadData = ->
API.project($stateParams.project_id).issue(0).commit()
.retrieve(pageSize: 20).then((result)->
$scope.commit = result
)
loadData()
#同步完成,加载数据
$scope.$on("commit:refresh:ready", ->
loadData()
)
$scope.showImportModal = ->
$scope.$broadcast("commit:import:modal:show")
$rootScope.$on 'pagination:change',(event, page, uuid, cb)->
return if uuid isnt 'commit_pagination'
API.project($stateParams.project_id).issue(0).commit().retrieve(pageSize: 20, pageIndex: page).then((result)->
$scope.commit = result
)
])
#因gitlab的iframe策略,无法被引用
.controller('commitDetailsController', ['$scope', '$sce', '$state', ($scope, $sce, $state)->
$scope.url = $sce.trustAsResourceUrl($state.params.url)
]) | true | "use strict"
define [
'../ng-module'
'../utils'
], (_module, _utils) ->
###
Modify:
Author: PI:EMAIL:<EMAIL>END_PI
Date: 2015.07.16
Describe:
提取首次加载数据为一个函数,并且添加一个事件监听器刷新数据
###
_module.controllerModule.
controller('commitListController', ['$rootScope', '$scope', '$stateParams', 'API', ($rootScope, $scope, $stateParams, API)->
cond = pageSize: 20
loadData = ->
API.project($stateParams.project_id).issue(0).commit()
.retrieve(pageSize: 20).then((result)->
$scope.commit = result
)
loadData()
#同步完成,加载数据
$scope.$on("commit:refresh:ready", ->
loadData()
)
$scope.showImportModal = ->
$scope.$broadcast("commit:import:modal:show")
$rootScope.$on 'pagination:change',(event, page, uuid, cb)->
return if uuid isnt 'commit_pagination'
API.project($stateParams.project_id).issue(0).commit().retrieve(pageSize: 20, pageIndex: page).then((result)->
$scope.commit = result
)
])
#因gitlab的iframe策略,无法被引用
.controller('commitDetailsController', ['$scope', '$sce', '$state', ($scope, $sce, $state)->
$scope.url = $sce.trustAsResourceUrl($state.params.url)
]) |
[
{
"context": "###\nGulp task clean\n@create 2014-10-07\n@author KoutarouYabe <idolm@ster.pw>\n###\n\nmodule.exports = (gulp, plug",
"end": 59,
"score": 0.9998950362205505,
"start": 47,
"tag": "NAME",
"value": "KoutarouYabe"
},
{
"context": "sk clean\n@create 2014-10-07\n@author Kouta... | tasks/config/clean.coffee | moorvin/Sea-Fight | 1 | ###
Gulp task clean
@create 2014-10-07
@author KoutarouYabe <idolm@ster.pw>
###
module.exports = (gulp, plugins)->
gulp.task "clean", ->
gulp.src [
plugins.config.destPath + "*"
], read: false
.pipe plugins.plumber()
.pipe plugins.rimraf()
| 173595 | ###
Gulp task clean
@create 2014-10-07
@author <NAME> <<EMAIL>>
###
module.exports = (gulp, plugins)->
gulp.task "clean", ->
gulp.src [
plugins.config.destPath + "*"
], read: false
.pipe plugins.plumber()
.pipe plugins.rimraf()
| true | ###
Gulp task clean
@create 2014-10-07
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
module.exports = (gulp, plugins)->
gulp.task "clean", ->
gulp.src [
plugins.config.destPath + "*"
], read: false
.pipe plugins.plumber()
.pipe plugins.rimraf()
|
[
{
"context": "ipt, but also available in Javascript.\n#\n# Author: Philippe Lang [philippe.lang@attiksystem.ch]\n# Version 1.0, 8th",
"end": 348,
"score": 0.9998666644096375,
"start": 335,
"tag": "NAME",
"value": "Philippe Lang"
},
{
"context": "ailable in Javascript.\n#\n# Author: P... | localization.coffee | storagebot/phonegap-l10n | 0 | #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# phonegap-l10n
#
# Tiny l10n localization library for Phonegap/Cordova applications. Can be used for
# localizing your application in a declarative way, or programmatically.
#
# Written in Coffeescript, but also available in Javascript.
#
# Author: Philippe Lang [philippe.lang@attiksystem.ch]
# Version 1.0, 8th may 2013
# Dependencies: jquery
#-----------------------------------------------------------------------------------
# How to use it:
#
# Somewhere in your onDeviceReady() callback, initialize the library:
#
# Localization.initialize
# (
# // Dictionnary
# {
# fr: {
# oui: "Oui",
# non: "Non"
# },
# en: {
# oui: "Yes",
# non: "No"
# }
# },
# // Fallback language
# "fr"
# );
#
# In your HTML code, localize your strings declaratively, by assigning
# a class "l10n-<dictionnary key>" to your elements:
#
# <span class="l10n-oui"></span>
#
# You can also access the dictionnary programmatically:
#
# alert(Localization.for("oui"))
#
# Language is determined by phonegap, by reading the language configured on the
# phone. In case the language is not available in the dictionnary, or if there is
# any problem determining the language, the fallback language is used.
#
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class Localization
#-------------------------------------------------------------------------------
# Initialize
#-------------------------------------------------------------------------------
@initialize: (dictionnary, fallback_language) ->
# Dictionnary is defined in the HTML file as an multilevel associative array.
Localization.dictionnary = dictionnary
# Fallback language is stored for further use.
Localization.fallback_language = fallback_language
# Calling Phonegap Localization API.
navigator.globalization.getPreferredLanguage(
Localization.get_preferred_language_callback,
Localization.get_preferred_language_error_callback
)
#-------------------------------------------------------------------------------
# get_preferred_language_callback
#-------------------------------------------------------------------------------
@get_preferred_language_callback: (language) ->
# Phonegap was able to read the language configured on the phone, so we
# store it for further use.
Localization.language = language.value
console.log("Phone language is " + Localization.language)
# If language is supported, that's fine, ...
if Localization.language of Localization.dictionnary
console.log("It is supported.")
#... otherwise we use the fallback language.
else
Localization.language = Localization.fallback_language
console.log("It is unsupported, so we chose " + Localization.language + " instead.")
# We apply the translations to the current HTML file.
Localization.apply_to_current_html()
#-------------------------------------------------------------------------------
# get_preferred_language_error_callback
#-------------------------------------------------------------------------------
@get_preferred_language_error_callback: () ->
# Phonegap was not able to read the language configured on the phone, so we
# use the fallback language.
Localization.language = Localization.fallback_language
console.log("There was a error determining the language, so we chose " + Localization.language + ".")
# We apply the translations to the current HTML file.
Localization.apply_to_current_html()
#-------------------------------------------------------------------------------
# apply_to_current_html
#-------------------------------------------------------------------------------
@apply_to_current_html: () ->
# Changing the content of all html elements with class "l10n-<key>" for
# current language. Useful for doing localization in a declarative way.
console.log("Localizing HTML file.")
$(".l10n-" + key).html(value) for key, value of Localization.dictionnary[Localization.language]
#-------------------------------------------------------------------------------
# for
#-------------------------------------------------------------------------------
@for: (key) ->
# Returns localized value for key passed as a parameter. Useful for doing
# localization programmatically.
return Localization.dictionnary[Localization.language][key]
| 172640 | #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# phonegap-l10n
#
# Tiny l10n localization library for Phonegap/Cordova applications. Can be used for
# localizing your application in a declarative way, or programmatically.
#
# Written in Coffeescript, but also available in Javascript.
#
# Author: <NAME> [<EMAIL>]
# Version 1.0, 8th may 2013
# Dependencies: jquery
#-----------------------------------------------------------------------------------
# How to use it:
#
# Somewhere in your onDeviceReady() callback, initialize the library:
#
# Localization.initialize
# (
# // Dictionnary
# {
# fr: {
# oui: "Oui",
# non: "Non"
# },
# en: {
# oui: "Yes",
# non: "No"
# }
# },
# // Fallback language
# "fr"
# );
#
# In your HTML code, localize your strings declaratively, by assigning
# a class "l10n-<dictionnary key>" to your elements:
#
# <span class="l10n-oui"></span>
#
# You can also access the dictionnary programmatically:
#
# alert(Localization.for("oui"))
#
# Language is determined by phonegap, by reading the language configured on the
# phone. In case the language is not available in the dictionnary, or if there is
# any problem determining the language, the fallback language is used.
#
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class Localization
#-------------------------------------------------------------------------------
# Initialize
#-------------------------------------------------------------------------------
@initialize: (dictionnary, fallback_language) ->
# Dictionnary is defined in the HTML file as an multilevel associative array.
Localization.dictionnary = dictionnary
# Fallback language is stored for further use.
Localization.fallback_language = fallback_language
# Calling Phonegap Localization API.
navigator.globalization.getPreferredLanguage(
Localization.get_preferred_language_callback,
Localization.get_preferred_language_error_callback
)
#-------------------------------------------------------------------------------
# get_preferred_language_callback
#-------------------------------------------------------------------------------
@get_preferred_language_callback: (language) ->
# Phonegap was able to read the language configured on the phone, so we
# store it for further use.
Localization.language = language.value
console.log("Phone language is " + Localization.language)
# If language is supported, that's fine, ...
if Localization.language of Localization.dictionnary
console.log("It is supported.")
#... otherwise we use the fallback language.
else
Localization.language = Localization.fallback_language
console.log("It is unsupported, so we chose " + Localization.language + " instead.")
# We apply the translations to the current HTML file.
Localization.apply_to_current_html()
#-------------------------------------------------------------------------------
# get_preferred_language_error_callback
#-------------------------------------------------------------------------------
@get_preferred_language_error_callback: () ->
# Phonegap was not able to read the language configured on the phone, so we
# use the fallback language.
Localization.language = Localization.fallback_language
console.log("There was a error determining the language, so we chose " + Localization.language + ".")
# We apply the translations to the current HTML file.
Localization.apply_to_current_html()
#-------------------------------------------------------------------------------
# apply_to_current_html
#-------------------------------------------------------------------------------
@apply_to_current_html: () ->
# Changing the content of all html elements with class "l10n-<key>" for
# current language. Useful for doing localization in a declarative way.
console.log("Localizing HTML file.")
$(".l10n-" + key).html(value) for key, value of Localization.dictionnary[Localization.language]
#-------------------------------------------------------------------------------
# for
#-------------------------------------------------------------------------------
@for: (key) ->
# Returns localized value for key passed as a parameter. Useful for doing
# localization programmatically.
return Localization.dictionnary[Localization.language][key]
| true | #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# phonegap-l10n
#
# Tiny l10n localization library for Phonegap/Cordova applications. Can be used for
# localizing your application in a declarative way, or programmatically.
#
# Written in Coffeescript, but also available in Javascript.
#
# Author: PI:NAME:<NAME>END_PI [PI:EMAIL:<EMAIL>END_PI]
# Version 1.0, 8th may 2013
# Dependencies: jquery
#-----------------------------------------------------------------------------------
# How to use it:
#
# Somewhere in your onDeviceReady() callback, initialize the library:
#
# Localization.initialize
# (
# // Dictionnary
# {
# fr: {
# oui: "Oui",
# non: "Non"
# },
# en: {
# oui: "Yes",
# non: "No"
# }
# },
# // Fallback language
# "fr"
# );
#
# In your HTML code, localize your strings declaratively, by assigning
# a class "l10n-<dictionnary key>" to your elements:
#
# <span class="l10n-oui"></span>
#
# You can also access the dictionnary programmatically:
#
# alert(Localization.for("oui"))
#
# Language is determined by phonegap, by reading the language configured on the
# phone. In case the language is not available in the dictionnary, or if there is
# any problem determining the language, the fallback language is used.
#
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class Localization
#-------------------------------------------------------------------------------
# Initialize
#-------------------------------------------------------------------------------
@initialize: (dictionnary, fallback_language) ->
# Dictionnary is defined in the HTML file as an multilevel associative array.
Localization.dictionnary = dictionnary
# Fallback language is stored for further use.
Localization.fallback_language = fallback_language
# Calling Phonegap Localization API.
navigator.globalization.getPreferredLanguage(
Localization.get_preferred_language_callback,
Localization.get_preferred_language_error_callback
)
#-------------------------------------------------------------------------------
# get_preferred_language_callback
#-------------------------------------------------------------------------------
@get_preferred_language_callback: (language) ->
# Phonegap was able to read the language configured on the phone, so we
# store it for further use.
Localization.language = language.value
console.log("Phone language is " + Localization.language)
# If language is supported, that's fine, ...
if Localization.language of Localization.dictionnary
console.log("It is supported.")
#... otherwise we use the fallback language.
else
Localization.language = Localization.fallback_language
console.log("It is unsupported, so we chose " + Localization.language + " instead.")
# We apply the translations to the current HTML file.
Localization.apply_to_current_html()
#-------------------------------------------------------------------------------
# get_preferred_language_error_callback
#-------------------------------------------------------------------------------
@get_preferred_language_error_callback: () ->
# Phonegap was not able to read the language configured on the phone, so we
# use the fallback language.
Localization.language = Localization.fallback_language
console.log("There was a error determining the language, so we chose " + Localization.language + ".")
# We apply the translations to the current HTML file.
Localization.apply_to_current_html()
#-------------------------------------------------------------------------------
# apply_to_current_html
#-------------------------------------------------------------------------------
@apply_to_current_html: () ->
# Changing the content of all html elements with class "l10n-<key>" for
# current language. Useful for doing localization in a declarative way.
console.log("Localizing HTML file.")
$(".l10n-" + key).html(value) for key, value of Localization.dictionnary[Localization.language]
#-------------------------------------------------------------------------------
# for
#-------------------------------------------------------------------------------
@for: (key) ->
# Returns localized value for key passed as a parameter. Useful for doing
# localization programmatically.
return Localization.dictionnary[Localization.language][key]
|
[
{
"context": "e jquery_ujs\n#= require jwplayer\n\njwplayer.key = \"RMvgim99iIA6JMnO0pelofjf2EOnWZEAelk/zA==\"\n\n@sampler = {}\n\n$ =>\n if document.querySelector(",
"end": 118,
"score": 0.9997645020484924,
"start": 77,
"tag": "KEY",
"value": "RMvgim99iIA6JMnO0pelofjf2EOnWZEAelk/zA==\""
... | app/assets/javascripts/sampler.js.coffee | qrush/skyway | 17 | #= require jquery
#= require jquery_ujs
#= require jwplayer
jwplayer.key = "RMvgim99iIA6JMnO0pelofjf2EOnWZEAelk/zA=="
@sampler = {}
$ =>
if document.querySelector("[data-behavior~=download]")
playlist = ({sources: [{file: download.dataset.songUrl}]} for download in document.querySelectorAll("[data-behavior~=download]"))
else
playlist = ({sources: [{file: item.dataset.track}]} for item in document.querySelectorAll("[data-track]"))
return if playlist.length is 0
@sampler.player = jwplayer('mediaplayer').setup
id: 'playerID'
controls: false
provider: 'rtmp'
streamer: 'rtmp://s2b7mnk1i05p4w.cloudfront.net/cfx/st/'
playlist: playlist
modes: [
{type: 'html5', config: { provider: 'audio' }}
{type: 'flash', src: '/jwplayer.flash.swf'}
]
$("[data-behavior~=download]").on "click", (event) ->
$("[data-behavior~=play][data-song=#{$(this).data('song')}]").click()
$("[data-behavior~=play]").on "click", (event) ->
$track = $(this)
sampler.player.pause()
if $track.attr("data-status") == "pause"
$track.attr("data-status", "")
else
song = $track.data("song")
sampler.player.playlistItem(song - 1)
$track.attr("data-status", "pause")
$("[data-behavior~=play]:not([data-song=#{song}])").attr("data-status", "")
event.preventDefault()
| 68064 | #= require jquery
#= require jquery_ujs
#= require jwplayer
jwplayer.key = "<KEY>
@sampler = {}
$ =>
if document.querySelector("[data-behavior~=download]")
playlist = ({sources: [{file: download.dataset.songUrl}]} for download in document.querySelectorAll("[data-behavior~=download]"))
else
playlist = ({sources: [{file: item.dataset.track}]} for item in document.querySelectorAll("[data-track]"))
return if playlist.length is 0
@sampler.player = jwplayer('mediaplayer').setup
id: 'playerID'
controls: false
provider: 'rtmp'
streamer: 'rtmp://s2b7mnk1i05p4w.cloudfront.net/cfx/st/'
playlist: playlist
modes: [
{type: 'html5', config: { provider: 'audio' }}
{type: 'flash', src: '/jwplayer.flash.swf'}
]
$("[data-behavior~=download]").on "click", (event) ->
$("[data-behavior~=play][data-song=#{$(this).data('song')}]").click()
$("[data-behavior~=play]").on "click", (event) ->
$track = $(this)
sampler.player.pause()
if $track.attr("data-status") == "pause"
$track.attr("data-status", "")
else
song = $track.data("song")
sampler.player.playlistItem(song - 1)
$track.attr("data-status", "pause")
$("[data-behavior~=play]:not([data-song=#{song}])").attr("data-status", "")
event.preventDefault()
| true | #= require jquery
#= require jquery_ujs
#= require jwplayer
jwplayer.key = "PI:KEY:<KEY>END_PI
@sampler = {}
$ =>
if document.querySelector("[data-behavior~=download]")
playlist = ({sources: [{file: download.dataset.songUrl}]} for download in document.querySelectorAll("[data-behavior~=download]"))
else
playlist = ({sources: [{file: item.dataset.track}]} for item in document.querySelectorAll("[data-track]"))
return if playlist.length is 0
@sampler.player = jwplayer('mediaplayer').setup
id: 'playerID'
controls: false
provider: 'rtmp'
streamer: 'rtmp://s2b7mnk1i05p4w.cloudfront.net/cfx/st/'
playlist: playlist
modes: [
{type: 'html5', config: { provider: 'audio' }}
{type: 'flash', src: '/jwplayer.flash.swf'}
]
$("[data-behavior~=download]").on "click", (event) ->
$("[data-behavior~=play][data-song=#{$(this).data('song')}]").click()
$("[data-behavior~=play]").on "click", (event) ->
$track = $(this)
sampler.player.pause()
if $track.attr("data-status") == "pause"
$track.attr("data-status", "")
else
song = $track.data("song")
sampler.player.playlistItem(song - 1)
$track.attr("data-status", "pause")
$("[data-behavior~=play]:not([data-song=#{song}])").attr("data-status", "")
event.preventDefault()
|
[
{
"context": "angePassword.set\n oldPassword : 'secret'\n newPassword : '$ecre8'\n ",
"end": 902,
"score": 0.9995263814926147,
"start": 896,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "d : 'secret'\n newPassword ... | source/TextUml/Scripts/specs/application/models/changepassword.coffee | marufsiddiqui/textuml-dotnet | 1 | define (require) ->
_ = require 'underscore'
ChangePassword = require '../../../application/models/changepassword'
repeatString = require('../../helpers').repeatString
describe 'models/changepassword', ->
changePassword = null
beforeEach -> changePassword = new ChangePassword
describe '#defaults', ->
it 'has #oldPassword', ->
expect(changePassword.defaults()).to.have.property 'oldPassword'
it 'has #newPassword', ->
expect(changePassword.defaults()).to.have.property 'newPassword'
it 'has #confirmPassword', ->
expect(changePassword.defaults()).to.have.property 'confirmPassword'
describe '#url', ->
it 'is set', -> expect(changePassword.url).to.exist
describe 'validation', ->
describe 'valid', ->
beforeEach ->
changePassword.set
oldPassword : 'secret'
newPassword : '$ecre8'
confirmPassword : '$ecre8'
it 'is valid', -> expect(changePassword.isValid()).to.be.ok
describe 'invalid', ->
describe '#oldPassword', ->
describe 'missing', ->
beforeEach ->
changePassword.set
newPassword : '$ecre8'
confirmPassword : '$ecre8'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'oldPassword'
describe 'blank', ->
beforeEach ->
changePassword.set
oldPassword : ''
newPassword : '$ecre8'
confirmPassword : '$ecre8'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'oldPassword'
describe '#newPassword', ->
describe 'missing', ->
beforeEach ->
changePassword.set
oldPassword : 'secret'
confirmPassword : '$ecre8'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe 'blank', ->
beforeEach ->
changePassword.set
oldPassword : 'secret'
newPassword : ''
confirmPassword : '$ecre8'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe 'less than minimum length', ->
beforeEach ->
changePassword.set
oldPassword : 'secret'
newPassword : repeatString 5
confirmPassword : '$ecre8'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe 'more than maximum length', ->
beforeEach ->
changePassword.set
oldPassword : 'secret'
newPassword : repeatString 65
confirmPassword : '$ecre8'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe '#confirmPassword', ->
describe 'missing', ->
beforeEach ->
changePassword.set
oldPassword : 'secret'
newPassword : '$ecre8'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'confirmPassword'
describe 'blank', ->
beforeEach ->
changePassword.set
oldPassword : 'secret'
newPassword : '$ecre8'
confirmPassword : ''
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'confirmPassword'
describe 'do not match', ->
beforeEach ->
changePassword.set
oldPassword : 'secret'
newPassword : '$ecre8'
confirmPassword : 'foo bar'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'confirmPassword' | 99581 | define (require) ->
_ = require 'underscore'
ChangePassword = require '../../../application/models/changepassword'
repeatString = require('../../helpers').repeatString
describe 'models/changepassword', ->
changePassword = null
beforeEach -> changePassword = new ChangePassword
describe '#defaults', ->
it 'has #oldPassword', ->
expect(changePassword.defaults()).to.have.property 'oldPassword'
it 'has #newPassword', ->
expect(changePassword.defaults()).to.have.property 'newPassword'
it 'has #confirmPassword', ->
expect(changePassword.defaults()).to.have.property 'confirmPassword'
describe '#url', ->
it 'is set', -> expect(changePassword.url).to.exist
describe 'validation', ->
describe 'valid', ->
beforeEach ->
changePassword.set
oldPassword : '<PASSWORD>'
newPassword : <PASSWORD>'
confirmPassword : <PASSWORD>'
it 'is valid', -> expect(changePassword.isValid()).to.be.ok
describe 'invalid', ->
describe '#oldPassword', ->
describe 'missing', ->
beforeEach ->
changePassword.set
newPassword : <PASSWORD>'
confirmPassword : <PASSWORD>'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'oldPassword'
describe 'blank', ->
beforeEach ->
changePassword.set
oldPassword : ''
newPassword : <PASSWORD>'
confirmPassword : <PASSWORD>'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'oldPassword'
describe '#newPassword', ->
describe 'missing', ->
beforeEach ->
changePassword.set
oldPassword : '<PASSWORD>'
confirmPassword : <PASSWORD>'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe 'blank', ->
beforeEach ->
changePassword.set
oldPassword : '<PASSWORD>'
newPassword : ''
confirmPassword : <PASSWORD>'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe 'less than minimum length', ->
beforeEach ->
changePassword.set
oldPassword : '<PASSWORD>'
newPassword : repeatString 5
confirmPassword : <PASSWORD>'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe 'more than maximum length', ->
beforeEach ->
changePassword.set
oldPassword : '<PASSWORD>'
newPassword : repeatString 65
confirmPassword : <PASSWORD>'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe '#confirmPassword', ->
describe 'missing', ->
beforeEach ->
changePassword.set
oldPassword : '<PASSWORD>'
newPassword : <PASSWORD>'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'confirmPassword'
describe 'blank', ->
beforeEach ->
changePassword.set
oldPassword : '<PASSWORD>'
newPassword : <PASSWORD>'
confirmPassword : ''
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'confirmPassword'
describe 'do not match', ->
beforeEach ->
changePassword.set
oldPassword : '<PASSWORD>'
newPassword : <PASSWORD>'
confirmPassword : '<PASSWORD>'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'confirmPassword' | true | define (require) ->
_ = require 'underscore'
ChangePassword = require '../../../application/models/changepassword'
repeatString = require('../../helpers').repeatString
describe 'models/changepassword', ->
changePassword = null
beforeEach -> changePassword = new ChangePassword
describe '#defaults', ->
it 'has #oldPassword', ->
expect(changePassword.defaults()).to.have.property 'oldPassword'
it 'has #newPassword', ->
expect(changePassword.defaults()).to.have.property 'newPassword'
it 'has #confirmPassword', ->
expect(changePassword.defaults()).to.have.property 'confirmPassword'
describe '#url', ->
it 'is set', -> expect(changePassword.url).to.exist
describe 'validation', ->
describe 'valid', ->
beforeEach ->
changePassword.set
oldPassword : 'PI:PASSWORD:<PASSWORD>END_PI'
newPassword : PI:PASSWORD:<PASSWORD>END_PI'
confirmPassword : PI:PASSWORD:<PASSWORD>END_PI'
it 'is valid', -> expect(changePassword.isValid()).to.be.ok
describe 'invalid', ->
describe '#oldPassword', ->
describe 'missing', ->
beforeEach ->
changePassword.set
newPassword : PI:PASSWORD:<PASSWORD>END_PI'
confirmPassword : PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'oldPassword'
describe 'blank', ->
beforeEach ->
changePassword.set
oldPassword : ''
newPassword : PI:PASSWORD:<PASSWORD>END_PI'
confirmPassword : PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'oldPassword'
describe '#newPassword', ->
describe 'missing', ->
beforeEach ->
changePassword.set
oldPassword : 'PI:PASSWORD:<PASSWORD>END_PI'
confirmPassword : PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe 'blank', ->
beforeEach ->
changePassword.set
oldPassword : 'PI:PASSWORD:<PASSWORD>END_PI'
newPassword : ''
confirmPassword : PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe 'less than minimum length', ->
beforeEach ->
changePassword.set
oldPassword : 'PI:PASSWORD:<PASSWORD>END_PI'
newPassword : repeatString 5
confirmPassword : PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe 'more than maximum length', ->
beforeEach ->
changePassword.set
oldPassword : 'PI:PASSWORD:<PASSWORD>END_PI'
newPassword : repeatString 65
confirmPassword : PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'newPassword'
describe '#confirmPassword', ->
describe 'missing', ->
beforeEach ->
changePassword.set
oldPassword : 'PI:PASSWORD:<PASSWORD>END_PI'
newPassword : PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'confirmPassword'
describe 'blank', ->
beforeEach ->
changePassword.set
oldPassword : 'PI:PASSWORD:<PASSWORD>END_PI'
newPassword : PI:PASSWORD:<PASSWORD>END_PI'
confirmPassword : ''
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'confirmPassword'
describe 'do not match', ->
beforeEach ->
changePassword.set
oldPassword : 'PI:PASSWORD:<PASSWORD>END_PI'
newPassword : PI:PASSWORD:<PASSWORD>END_PI'
confirmPassword : 'PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(changePassword.isValid()).to.not.be.ok
expect(changePassword.validationError)
.to.have.property 'confirmPassword' |
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9979183673858643,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "common.PORT, ->\n req = https.request(\n host: \"127.0.0.1\"\n port: common.PORT\n a... | test/simple/test-https-req-split.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
# disable strict server certificate validation by the client
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
common = require("../common")
assert = require("assert")
https = require("https")
tls = require("tls")
fs = require("fs")
seen_req = false
options =
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
# Force splitting incoming data
tls.SLAB_BUFFER_SIZE = 1
server = https.createServer(options)
server.on "upgrade", (req, socket, upgrade) ->
socket.on "data", (data) ->
throw new Error("Unexpected data: " + data)return
socket.end "HTTP/1.1 200 Ok\r\n\r\n"
seen_req = true
return
server.listen common.PORT, ->
req = https.request(
host: "127.0.0.1"
port: common.PORT
agent: false
headers:
Connection: "Upgrade"
Upgrade: "Websocket"
, ->
req.socket.destroy()
server.close()
return
)
req.end()
return
process.on "exit", ->
assert seen_req
console.log "ok"
return
| 48113 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
# disable strict server certificate validation by the client
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
common = require("../common")
assert = require("assert")
https = require("https")
tls = require("tls")
fs = require("fs")
seen_req = false
options =
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
# Force splitting incoming data
tls.SLAB_BUFFER_SIZE = 1
server = https.createServer(options)
server.on "upgrade", (req, socket, upgrade) ->
socket.on "data", (data) ->
throw new Error("Unexpected data: " + data)return
socket.end "HTTP/1.1 200 Ok\r\n\r\n"
seen_req = true
return
server.listen common.PORT, ->
req = https.request(
host: "127.0.0.1"
port: common.PORT
agent: false
headers:
Connection: "Upgrade"
Upgrade: "Websocket"
, ->
req.socket.destroy()
server.close()
return
)
req.end()
return
process.on "exit", ->
assert seen_req
console.log "ok"
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
# disable strict server certificate validation by the client
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
common = require("../common")
assert = require("assert")
https = require("https")
tls = require("tls")
fs = require("fs")
seen_req = false
options =
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
# Force splitting incoming data
tls.SLAB_BUFFER_SIZE = 1
server = https.createServer(options)
server.on "upgrade", (req, socket, upgrade) ->
socket.on "data", (data) ->
throw new Error("Unexpected data: " + data)return
socket.end "HTTP/1.1 200 Ok\r\n\r\n"
seen_req = true
return
server.listen common.PORT, ->
req = https.request(
host: "127.0.0.1"
port: common.PORT
agent: false
headers:
Connection: "Upgrade"
Upgrade: "Websocket"
, ->
req.socket.destroy()
server.close()
return
)
req.end()
return
process.on "exit", ->
assert seen_req
console.log "ok"
return
|
[
{
"context": "r host per browser.\n#\n# :copyright: (c) 2013 by Zaur Nasibov.\n# :license: MIT, see LICENSE for more details",
"end": 251,
"score": 0.9998767971992493,
"start": 239,
"tag": "NAME",
"value": "Zaur Nasibov"
}
] | kaylee/client/klinstance.coffee | BasicWolf/archived-kaylee | 2 | ###
# klinstance.coffee
# ~~~~~~~~~~~~~~~~~~
#
# This file is a part of Kaylee client-side module.
# It contains routines which help running only one
# instance of Kaylee per host per browser.
#
# :copyright: (c) 2013 by Zaur Nasibov.
# :license: MIT, see LICENSE for more details.
###
kl.instance = instance = {}
PING = "kaylee.instance.ping"
PONG = "kaylee.instance.pong"
NO_INSTANCE_ID = '0'
# a unique (per single hosts's each browser tab or window) ID
instance.id = NO_INSTANCE_ID
instance.is_unique = (yes_callback, no_callback) ->
PING_TIMEOUT = 1500 # ms
pong_received = false
# is_unique() is called for the first time
if instance.id == NO_INSTANCE_ID
localStorage.clear()
instance.id = (Math.random()).toString()
# reply to ping requests which are coming from other tabs/windows
# (have different instance.id)
_storage_events_handler = (e) ->
if e.key == PING
localStorage[PONG] = e.newValue
else if e.key == PONG and e.newValue == instance.id
pong_received = true
addEventListener('storage', _storage_events_handler, false)
# if no "PONG" will is received in defined timeout, then
# the current instance is considered as the only instance
# running
kl.log("Checking whether there are other instances of Kaylee running...")
kl.util.after(PING_TIMEOUT, () ->
if pong_received then no_callback() else yes_callback()
)
# send PING
localStorage[PING] = instance.id
return | 192110 | ###
# klinstance.coffee
# ~~~~~~~~~~~~~~~~~~
#
# This file is a part of Kaylee client-side module.
# It contains routines which help running only one
# instance of Kaylee per host per browser.
#
# :copyright: (c) 2013 by <NAME>.
# :license: MIT, see LICENSE for more details.
###
kl.instance = instance = {}
PING = "kaylee.instance.ping"
PONG = "kaylee.instance.pong"
NO_INSTANCE_ID = '0'
# a unique (per single hosts's each browser tab or window) ID
instance.id = NO_INSTANCE_ID
instance.is_unique = (yes_callback, no_callback) ->
PING_TIMEOUT = 1500 # ms
pong_received = false
# is_unique() is called for the first time
if instance.id == NO_INSTANCE_ID
localStorage.clear()
instance.id = (Math.random()).toString()
# reply to ping requests which are coming from other tabs/windows
# (have different instance.id)
_storage_events_handler = (e) ->
if e.key == PING
localStorage[PONG] = e.newValue
else if e.key == PONG and e.newValue == instance.id
pong_received = true
addEventListener('storage', _storage_events_handler, false)
# if no "PONG" will is received in defined timeout, then
# the current instance is considered as the only instance
# running
kl.log("Checking whether there are other instances of Kaylee running...")
kl.util.after(PING_TIMEOUT, () ->
if pong_received then no_callback() else yes_callback()
)
# send PING
localStorage[PING] = instance.id
return | true | ###
# klinstance.coffee
# ~~~~~~~~~~~~~~~~~~
#
# This file is a part of Kaylee client-side module.
# It contains routines which help running only one
# instance of Kaylee per host per browser.
#
# :copyright: (c) 2013 by PI:NAME:<NAME>END_PI.
# :license: MIT, see LICENSE for more details.
###
kl.instance = instance = {}
PING = "kaylee.instance.ping"
PONG = "kaylee.instance.pong"
NO_INSTANCE_ID = '0'
# a unique (per single hosts's each browser tab or window) ID
instance.id = NO_INSTANCE_ID
instance.is_unique = (yes_callback, no_callback) ->
PING_TIMEOUT = 1500 # ms
pong_received = false
# is_unique() is called for the first time
if instance.id == NO_INSTANCE_ID
localStorage.clear()
instance.id = (Math.random()).toString()
# reply to ping requests which are coming from other tabs/windows
# (have different instance.id)
_storage_events_handler = (e) ->
if e.key == PING
localStorage[PONG] = e.newValue
else if e.key == PONG and e.newValue == instance.id
pong_received = true
addEventListener('storage', _storage_events_handler, false)
# if no "PONG" will is received in defined timeout, then
# the current instance is considered as the only instance
# running
kl.log("Checking whether there are other instances of Kaylee running...")
kl.util.after(PING_TIMEOUT, () ->
if pong_received then no_callback() else yes_callback()
)
# send PING
localStorage[PING] = instance.id
return |
[
{
"context": "'\n main: '#application'\n data:\n message: 'Hola mundo'\n events: []\n methods:\n after: ->\n ",
"end": 274,
"score": 0.5412228107452393,
"start": 271,
"tag": "NAME",
"value": "ola"
}
] | src/script/events/events.coffee | carrasquel/tulipan-example | 0 | `import html from "../../views/events/events.html";`
`var backend_url = process.env.BACKEND_URL || "http://localhost:5000/"`
events = new Tulipan(
template:
html: html
async: false
route:
route: '/events'
main: '#application'
data:
message: 'Hola mundo'
events: []
methods:
after: ->
@fetchEvents()
return
fetchEvents: ->
apiKey = @$store.get('apiKey')
@$dialog.show 'Fetching events...'
@$http.get(backend_url + 'api/events/', headers: 'X-API-KEY': apiKey).then ((res) ->
data = res.data
@$set 'events', data
@$dialog.hide()
return
), (err) ->
@$dialog.hide()
console.log err
return
return
deleteEvent: (index) ->
id = @events[index].id
apiKey = @$store.get('apiKey')
@$dialog.show 'Deleting event...'
@$http.delete(backend_url + 'api/events/' + id, headers: 'X-API-KEY': apiKey).then ((res) ->
@$dialog.hide()
@fetchEvents()
return
), (err) ->
@$dialog.hide()
console.log err
return
return
createEvent: ->
@$router.navigate '/newevent'
return
) | 121507 | `import html from "../../views/events/events.html";`
`var backend_url = process.env.BACKEND_URL || "http://localhost:5000/"`
events = new Tulipan(
template:
html: html
async: false
route:
route: '/events'
main: '#application'
data:
message: 'H<NAME> mundo'
events: []
methods:
after: ->
@fetchEvents()
return
fetchEvents: ->
apiKey = @$store.get('apiKey')
@$dialog.show 'Fetching events...'
@$http.get(backend_url + 'api/events/', headers: 'X-API-KEY': apiKey).then ((res) ->
data = res.data
@$set 'events', data
@$dialog.hide()
return
), (err) ->
@$dialog.hide()
console.log err
return
return
deleteEvent: (index) ->
id = @events[index].id
apiKey = @$store.get('apiKey')
@$dialog.show 'Deleting event...'
@$http.delete(backend_url + 'api/events/' + id, headers: 'X-API-KEY': apiKey).then ((res) ->
@$dialog.hide()
@fetchEvents()
return
), (err) ->
@$dialog.hide()
console.log err
return
return
createEvent: ->
@$router.navigate '/newevent'
return
) | true | `import html from "../../views/events/events.html";`
`var backend_url = process.env.BACKEND_URL || "http://localhost:5000/"`
events = new Tulipan(
template:
html: html
async: false
route:
route: '/events'
main: '#application'
data:
message: 'HPI:NAME:<NAME>END_PI mundo'
events: []
methods:
after: ->
@fetchEvents()
return
fetchEvents: ->
apiKey = @$store.get('apiKey')
@$dialog.show 'Fetching events...'
@$http.get(backend_url + 'api/events/', headers: 'X-API-KEY': apiKey).then ((res) ->
data = res.data
@$set 'events', data
@$dialog.hide()
return
), (err) ->
@$dialog.hide()
console.log err
return
return
deleteEvent: (index) ->
id = @events[index].id
apiKey = @$store.get('apiKey')
@$dialog.show 'Deleting event...'
@$http.delete(backend_url + 'api/events/' + id, headers: 'X-API-KEY': apiKey).then ((res) ->
@$dialog.hide()
@fetchEvents()
return
), (err) ->
@$dialog.hide()
console.log err
return
return
createEvent: ->
@$router.navigate '/newevent'
return
) |
[
{
"context": "Logic taken from:\n#\n#\t jQuery pub/sub plugin by Peter Higgins (dante@dojotoolkit.org)\n#\t Loosely based on Do",
"end": 73,
"score": 0.9998492002487183,
"start": 60,
"tag": "NAME",
"value": "Peter Higgins"
},
{
"context": ":\n#\n#\t jQuery pub/sub plugin by ... | server/public/javascript/observatory.coffee | TheSoftwareGreenhouse/ourSquareFeet | 1 | # Logic taken from:
#
# jQuery pub/sub plugin by Peter Higgins (dante@dojotoolkit.org)
# Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
# Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
# http://dojofoundation.org/license for more information.
# Which would have been perfect, if it didn't use JQuery. I don't want to use it strictly in the browser.
root = exports ? this
Observatory = (host) ->
# the topic/subscription hash
cache = {}
subscribe = (topic, callback) ->
# summary:
# Register a callback on a named topic.
# topic: String
# The channel to subscribe to
# callback: Function
# The handler event. Anytime something is $.publish'ed on a
# subscribed channel, the callback will be called with the
# published array as ordered arguments.
#
# returns: Array
# A handle which can be used to unsubscribe this particular subscription.
#
# example:
# | $.subscribe("/some/topic", function(a, b, c){ /* handle data */ });
#
if not cache[topic]
cache[topic] = []
cache[topic].push callback
[topic, callback] # Array
unsubscribe = (handle) ->
# summary:
# Disconnect a subscribed function for a topic.
# handle: Array
# The return value from a $.subscribe call.
# example:
# | var handle = $.subscribe("/something", function(){});
# | $.unsubscribe(handle);
t = handle[0]
if cache[t]? then (
cache[t] = (subscriber for subscriber in cache[t] when (subscriber isnt handle[1]))
)
if host?
host.subscribe = subscribe
host.unsubscribe = unsubscribe
{
publish: (topic, args...) ->
# summary:
# Publish some data on a named topic.
#
# topic: String
# The channel to publish on
# args: Array?
# The data to publish. Each array item is converted into an ordered
# arguments on the subscribed functions.
#
# example:
# Publish stuff on '/some/topic'. Anything subscribed will be called
# with a function signature like: function(a,b,c){ ... }
#
# | $.publish("/some/topic", ["a","b","c"]);
if cache[topic]?
for subscription in cache[topic]
subscription.apply root, (args or [])
subscribe: subscribe
unsubscribe: unsubscribe
}
root.Observatory = Observatory
#;(function(d){
# // the topic/subscription hash
# var cache = {};
#
# d.publish = function(/* String */topic, /* Array? */args){
# cache[topic] && d.each(cache[topic], function(){
# this.apply(d, args || []);
# });
# };
# d.subscribe = function(/* String */topic, /* Function */callback){
# if(!cache[topic]){
# cache[topic] = [];
# }
# cache[topic].push(callback);
# return [topic, callback]; // Array
# };
# d.unsubscribe = function(/* Array */handle){
# summary:
# Disconnect a subscribed function for a topic.
# handle: Array
# The return value from a $.subscribe call.
# example:
# | var handle = $.subscribe("/something", function(){});
# | $.unsubscribe(handle);
# var t = handle[0];
# cache[t] && d.each(cache[t], function(idx){
# if(this == handle[1]){
# cache[t].splice(idx, 1);
# }
# });
# };
#})(jQuery);
| 49994 | # Logic taken from:
#
# jQuery pub/sub plugin by <NAME> (<EMAIL>)
# Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
# Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
# http://dojofoundation.org/license for more information.
# Which would have been perfect, if it didn't use JQuery. I don't want to use it strictly in the browser.
root = exports ? this
Observatory = (host) ->
# the topic/subscription hash
cache = {}
subscribe = (topic, callback) ->
# summary:
# Register a callback on a named topic.
# topic: String
# The channel to subscribe to
# callback: Function
# The handler event. Anytime something is $.publish'ed on a
# subscribed channel, the callback will be called with the
# published array as ordered arguments.
#
# returns: Array
# A handle which can be used to unsubscribe this particular subscription.
#
# example:
# | $.subscribe("/some/topic", function(a, b, c){ /* handle data */ });
#
if not cache[topic]
cache[topic] = []
cache[topic].push callback
[topic, callback] # Array
unsubscribe = (handle) ->
# summary:
# Disconnect a subscribed function for a topic.
# handle: Array
# The return value from a $.subscribe call.
# example:
# | var handle = $.subscribe("/something", function(){});
# | $.unsubscribe(handle);
t = handle[0]
if cache[t]? then (
cache[t] = (subscriber for subscriber in cache[t] when (subscriber isnt handle[1]))
)
if host?
host.subscribe = subscribe
host.unsubscribe = unsubscribe
{
publish: (topic, args...) ->
# summary:
# Publish some data on a named topic.
#
# topic: String
# The channel to publish on
# args: Array?
# The data to publish. Each array item is converted into an ordered
# arguments on the subscribed functions.
#
# example:
# Publish stuff on '/some/topic'. Anything subscribed will be called
# with a function signature like: function(a,b,c){ ... }
#
# | $.publish("/some/topic", ["a","b","c"]);
if cache[topic]?
for subscription in cache[topic]
subscription.apply root, (args or [])
subscribe: subscribe
unsubscribe: unsubscribe
}
root.Observatory = Observatory
#;(function(d){
# // the topic/subscription hash
# var cache = {};
#
# d.publish = function(/* String */topic, /* Array? */args){
# cache[topic] && d.each(cache[topic], function(){
# this.apply(d, args || []);
# });
# };
# d.subscribe = function(/* String */topic, /* Function */callback){
# if(!cache[topic]){
# cache[topic] = [];
# }
# cache[topic].push(callback);
# return [topic, callback]; // Array
# };
# d.unsubscribe = function(/* Array */handle){
# summary:
# Disconnect a subscribed function for a topic.
# handle: Array
# The return value from a $.subscribe call.
# example:
# | var handle = $.subscribe("/something", function(){});
# | $.unsubscribe(handle);
# var t = handle[0];
# cache[t] && d.each(cache[t], function(idx){
# if(this == handle[1]){
# cache[t].splice(idx, 1);
# }
# });
# };
#})(jQuery);
| true | # Logic taken from:
#
# jQuery pub/sub plugin by PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
# Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
# http://dojofoundation.org/license for more information.
# Which would have been perfect, if it didn't use JQuery. I don't want to use it strictly in the browser.
root = exports ? this
Observatory = (host) ->
# the topic/subscription hash
cache = {}
subscribe = (topic, callback) ->
# summary:
# Register a callback on a named topic.
# topic: String
# The channel to subscribe to
# callback: Function
# The handler event. Anytime something is $.publish'ed on a
# subscribed channel, the callback will be called with the
# published array as ordered arguments.
#
# returns: Array
# A handle which can be used to unsubscribe this particular subscription.
#
# example:
# | $.subscribe("/some/topic", function(a, b, c){ /* handle data */ });
#
if not cache[topic]
cache[topic] = []
cache[topic].push callback
[topic, callback] # Array
unsubscribe = (handle) ->
# summary:
# Disconnect a subscribed function for a topic.
# handle: Array
# The return value from a $.subscribe call.
# example:
# | var handle = $.subscribe("/something", function(){});
# | $.unsubscribe(handle);
t = handle[0]
if cache[t]? then (
cache[t] = (subscriber for subscriber in cache[t] when (subscriber isnt handle[1]))
)
if host?
host.subscribe = subscribe
host.unsubscribe = unsubscribe
{
publish: (topic, args...) ->
# summary:
# Publish some data on a named topic.
#
# topic: String
# The channel to publish on
# args: Array?
# The data to publish. Each array item is converted into an ordered
# arguments on the subscribed functions.
#
# example:
# Publish stuff on '/some/topic'. Anything subscribed will be called
# with a function signature like: function(a,b,c){ ... }
#
# | $.publish("/some/topic", ["a","b","c"]);
if cache[topic]?
for subscription in cache[topic]
subscription.apply root, (args or [])
subscribe: subscribe
unsubscribe: unsubscribe
}
root.Observatory = Observatory
#;(function(d){
# // the topic/subscription hash
# var cache = {};
#
# d.publish = function(/* String */topic, /* Array? */args){
# cache[topic] && d.each(cache[topic], function(){
# this.apply(d, args || []);
# });
# };
# d.subscribe = function(/* String */topic, /* Function */callback){
# if(!cache[topic]){
# cache[topic] = [];
# }
# cache[topic].push(callback);
# return [topic, callback]; // Array
# };
# d.unsubscribe = function(/* Array */handle){
# summary:
# Disconnect a subscribed function for a topic.
# handle: Array
# The return value from a $.subscribe call.
# example:
# | var handle = $.subscribe("/something", function(){});
# | $.unsubscribe(handle);
# var t = handle[0];
# cache[t] && d.each(cache[t], function(idx){
# if(this == handle[1]){
# cache[t].splice(idx, 1);
# }
# });
# };
#})(jQuery);
|
[
{
"context": "###\nThe MIT License (MIT)\n\nCopyright (c) 2016 Callum Hart\n\nPermission is hereby granted, free of charge, to",
"end": 57,
"score": 0.9997910261154175,
"start": 46,
"tag": "NAME",
"value": "Callum Hart"
}
] | src/coffee/sift.coffee | callum-hart/Sift.js | 2 | ###
The MIT License (MIT)
Copyright (c) 2016 Callum Hart
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
###
noop = ->
###
************************************************************
Sift is the public interface used by the outside world.
************************************************************
###
class Sift
defaultOptions:
onFilterApplied: noop # External hook
onFilterCleared: noop # External hook
version: "0.1.1"
constructor: (selector, options) ->
options = Utils.extend {}, @defaultOptions, options
switch options.type
when "checkbox" then new ListFilter selector, options
when "radio" then new ListFilter selector, options
when "calendar" then new CalendarFilter selector, options
when "multi_calendar" then new CalendarFilter selector, options
###
************************************************************
End of Sift
************************************************************
###
###
************************************************************
CommonFilter implements shared things for all filters
************************************************************
###
class CommonFilter
filtersShowing: no
constructor: ->
@elm = @handleElm()
unless @elm
console.warn "Slab couldn't initialize #{@selector} as it's not in the DOM"
# You can initialize Sift with a class/id selector or with an actual DOM element.
handleElm: ->
if typeof @selector is "string"
elm = document.querySelector @selector
else if typeof @selector is "object"
# Check that object is an actual dom element.
if @selector.nodeName
elm = @selector
elm
# ************************************************************
# Events
# ************************************************************
# Persistent events are ones that need to be listened to all the time.
bindCommonPersistentEvents: ->
@filterButton.addEventListener "click", @openFilters
# Events are ones that need to be listened to when the filter is open.
bindEvents: ->
document.addEventListener "click", @closeFilters
# Stop listening to events (i.e when the filter is closed)
unbindEvents: ->
document.removeEventListener "click", @closeFilters
# ************************************************************
# Actions
# ************************************************************
openFilters: (e) =>
e.preventDefault()
@bindEvents()
@showFilters()
closeFilters: (e) =>
if $(e.target).parents(".sift-container").length < 1
@hideFilters()
@unbindEvents()
clearFilter: ->
@hideFilters()
@options.onFilterCleared()
# ************************************************************
# Templating
# ************************************************************
render: (elm, template) ->
elm.innerHTML = template
handleTemplate: ->
# Handle common template needs of all filters.
@template = """
<a href="" class="sift-link">
<span class="sift-filter-name">#{@options.displayName}</span>
<span class="sift-active-filter-text"></span>
</a>
<div class="sift-dropdown">
<a href="" class="sift-clear">Clear filter</a>
<div class="sift-dropdown-inner"></div>
</div>
"""
handleInitialRender: ->
@render @elm, @template
# Now that sift is rendered we can do DOM related things.
@filterButton = @elm.querySelector ".sift-link"
@filterName = @elm.querySelector ".sift-filter-name"
@activeFilterText = @elm.querySelector ".sift-active-filter-text"
@dropdown = @elm.querySelector ".sift-dropdown"
@clear = @elm.querySelector ".sift-clear"
@dropdownInner = @elm.querySelector ".sift-dropdown-inner"
Utils.addClass "sift-container", @elm
@bindCommonPersistentEvents()
showFilters: ->
@filtersShowing = yes
Utils.addClass "filters-showing", @elm
hideFilters: ->
@filtersShowing = no
Utils.removeClass "filters-showing", @elm
###
************************************************************
End of CommonFilter
************************************************************
###
###
************************************************************
ListFilter used by radio & checkbox filters
************************************************************
###
class ListFilter extends CommonFilter
constructor: (@selector, @options) ->
super
if @elm
@filters = @options.filters
@activeFilters = []
@handleTemplate()
@handleFilters()
@handleActiveFilterText()
# ************************************************************
# Events
# ************************************************************
bindEvents: ->
super
@dropdownInner.addEventListener "click", @dropdownClicked
@clear.addEventListener "click", @clearFilter
unbindEvents: ->
super
@dropdownInner.removeEventListener "click", @dropdownClicked
@clear.addEventListener "click", @clearFilter
# ************************************************************
# Actions
# ************************************************************
dropdownClicked: (e) =>
if e.target.tagName is "INPUT"
@activeFilters = []
for input, index in @inputElms
if input.checked
filter = input.value
if Utils.isNumber filter then filter = parseInt filter
@activeFilters.push filter
@handleActiveFilterText()
if @activeFilters.length isnt 0
if @options.type is "radio"
@hideFilters()
@activeFilters = @activeFilters[0]
@options.onFilterApplied @activeFilters
else
@options.onFilterCleared()
clearFilter: (e) =>
e.preventDefault()
@activeFilters = []
@handleActiveFilterText()
for input, index in @inputElms
input.checked = no
super
# ************************************************************
# Templating
# ************************************************************
handleTemplate: ->
super
# Handle specific template needs of ListFilters.
@filterSnippet = """
<label class="sift-label">
<input type="#{@options.type}" name="{{name}}" value="{{value}}" {{checked}}>
<span>{{displayName}}</span>
</label>
"""
@handleInitialRender()
handleFilters: ->
filtersSnippet = ""
for filter, index in @filters
checked = ""
if @options.activeFilter
multipleActiveFilters = typeof @options.activeFilter is "object"
if multipleActiveFilters
unless @options.type is "radio"
filterActive = Utils.where null, filter.value, @options.activeFilter
if filterActive
checked = "checked"
@activeFilters.push filter.value
else
console.warn "Can't have multiple active filters for radio buttons"
else
if Utils.isNumber @options.activeFilter then @options.activeFilter = parseInt @options.activeFilter
if @options.activeFilter is filter.value
checked = "checked"
@activeFilters.push filter.value
filtersSnippet += @filterSnippet.replace("{{displayName}}", filter.displayName)
.replace("{{name}}", @options.displayName)
.replace("{{value}}", filter.value)
.replace("{{checked}}", checked)
@render @dropdownInner, filtersSnippet
@inputElms = @dropdownInner.getElementsByTagName "input"
handleActiveFilterText: ->
if @activeFilters.length isnt 0
activeFilterText = ""
@render @filterName, "#{@options.displayName}:"
for filter, index in @activeFilters
if index isnt 0 then activeFilterText += ", "
if Utils.isNumber filter then filter = parseInt filter
activeFilterText += Utils.where("value", filter, @filters)[0].displayName
@render @activeFilterText, activeFilterText
Utils.addClass "with-active-filter", @elm
else
@render @filterName, "#{@options.displayName}"
@render @activeFilterText, ""
Utils.removeClass "with-active-filter", @elm
###
************************************************************
End of ListFilter
************************************************************
###
###
************************************************************
CalendarFilter used by date & date range filters
************************************************************
###
class CalendarFilter extends CommonFilter
constructor: (@selector, @options) ->
super
if @elm
@activeDate = @options.calendarOptions?.existingDate
@activeDateRange = @options.calendarOptions?.existingDateRange
@handleTemplate()
@handleFilters()
@handleActiveFilterText()
# ************************************************************
# Events
# ************************************************************
bindEvents: ->
super
@clear.addEventListener "click", @clearFilter
unbindEvents: ->
super
@clear.addEventListener "click", @clearFilter
# ************************************************************
# Hooks
# Subscribe to DateJust or DateRange hooks
# ************************************************************
handleDateJustHooks: ->
@dateJust.options.onDateSelected = (date) =>
@activeDate = date
@activeDateRange = null
@handleActiveFilterText()
@options.onFilterApplied date
@dateJust.options.onDateRangeSelected = (startDate, endDate) =>
@activeDate = null
@activeDateRange = [startDate, endDate]
@handleActiveFilterText()
@options.onFilterApplied startDate, endDate
handleDateRangeHooks: ->
@dateRange.options.onDateRangeSelected = (startDate, endDate) =>
@activeDateRange = [startDate, endDate]
@handleActiveFilterText()
@options.onFilterApplied startDate, endDate
# ************************************************************
# Actions
# ************************************************************
clearFilter: (e) =>
e.preventDefault()
if @options.type is "calendar"
@dateJust.reset()
else if @options.type is "multi_calendar"
@dateRange.reset()
@activeDate = null
@activeDateRange = null
@handleActiveFilterText()
super
# ************************************************************
# Templating
# ************************************************************
handleTemplate: ->
super
@handleInitialRender()
handleFilters: ->
@render @dropdownInner, """<div class="sift-calendar-wrap"></div>"""
@calendarWrap = @dropdownInner.querySelector ".sift-calendar-wrap"
Utils.addClass "without-scroll", @elm
if @options.type is "calendar"
@dateJust = new DateJust @calendarWrap, @options.calendarOptions
@handleDateJustHooks()
else if @options.type is "multi_calendar"
@dateRange = new DateRange @calendarWrap, @options.calendarOptions
Utils.addClass "with-multi-calendar", @elm
@handleDateRangeHooks()
handleActiveFilterText: ->
if @activeDate or @activeDateRange
@render @filterName, "#{@options.displayName}:"
Utils.addClass "with-active-filter", @elm
if @activeDate
@render @activeFilterText, @activeDate.toDateString() # TODO: date format might need to be an option?
else if @activeDateRange
@render @activeFilterText, "#{@activeDateRange[0].toDateString()} - #{@activeDateRange[1].toDateString()}"
else
@render @filterName, "#{@options.displayName}"
Utils.removeClass "with-active-filter", @elm
@render @activeFilterText, ""
###
************************************************************
End of CalendarFilter
************************************************************
###
window.Sift = Sift
Utils =
extend: (target, objects...) ->
for object in objects
target[key] = val for key, val of object
target
where: (key, value, array) ->
results = []
array.filter (object) ->
if typeof object is "object"
results.push object if object[key] == value
else
results.push object if object == value
if results.length > 0
results
addClass: (className, elm) ->
elm.classList.add className
removeClass: (className, elm) ->
elm.classList.remove className
isNumber: (thing) ->
!isNaN(parseInt(thing)) | 30601 | ###
The MIT License (MIT)
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
###
noop = ->
###
************************************************************
Sift is the public interface used by the outside world.
************************************************************
###
class Sift
defaultOptions:
onFilterApplied: noop # External hook
onFilterCleared: noop # External hook
version: "0.1.1"
constructor: (selector, options) ->
options = Utils.extend {}, @defaultOptions, options
switch options.type
when "checkbox" then new ListFilter selector, options
when "radio" then new ListFilter selector, options
when "calendar" then new CalendarFilter selector, options
when "multi_calendar" then new CalendarFilter selector, options
###
************************************************************
End of Sift
************************************************************
###
###
************************************************************
CommonFilter implements shared things for all filters
************************************************************
###
class CommonFilter
filtersShowing: no
constructor: ->
@elm = @handleElm()
unless @elm
console.warn "Slab couldn't initialize #{@selector} as it's not in the DOM"
# You can initialize Sift with a class/id selector or with an actual DOM element.
handleElm: ->
if typeof @selector is "string"
elm = document.querySelector @selector
else if typeof @selector is "object"
# Check that object is an actual dom element.
if @selector.nodeName
elm = @selector
elm
# ************************************************************
# Events
# ************************************************************
# Persistent events are ones that need to be listened to all the time.
bindCommonPersistentEvents: ->
@filterButton.addEventListener "click", @openFilters
# Events are ones that need to be listened to when the filter is open.
bindEvents: ->
document.addEventListener "click", @closeFilters
# Stop listening to events (i.e when the filter is closed)
unbindEvents: ->
document.removeEventListener "click", @closeFilters
# ************************************************************
# Actions
# ************************************************************
openFilters: (e) =>
e.preventDefault()
@bindEvents()
@showFilters()
closeFilters: (e) =>
if $(e.target).parents(".sift-container").length < 1
@hideFilters()
@unbindEvents()
clearFilter: ->
@hideFilters()
@options.onFilterCleared()
# ************************************************************
# Templating
# ************************************************************
render: (elm, template) ->
elm.innerHTML = template
handleTemplate: ->
# Handle common template needs of all filters.
@template = """
<a href="" class="sift-link">
<span class="sift-filter-name">#{@options.displayName}</span>
<span class="sift-active-filter-text"></span>
</a>
<div class="sift-dropdown">
<a href="" class="sift-clear">Clear filter</a>
<div class="sift-dropdown-inner"></div>
</div>
"""
handleInitialRender: ->
@render @elm, @template
# Now that sift is rendered we can do DOM related things.
@filterButton = @elm.querySelector ".sift-link"
@filterName = @elm.querySelector ".sift-filter-name"
@activeFilterText = @elm.querySelector ".sift-active-filter-text"
@dropdown = @elm.querySelector ".sift-dropdown"
@clear = @elm.querySelector ".sift-clear"
@dropdownInner = @elm.querySelector ".sift-dropdown-inner"
Utils.addClass "sift-container", @elm
@bindCommonPersistentEvents()
showFilters: ->
@filtersShowing = yes
Utils.addClass "filters-showing", @elm
hideFilters: ->
@filtersShowing = no
Utils.removeClass "filters-showing", @elm
###
************************************************************
End of CommonFilter
************************************************************
###
###
************************************************************
ListFilter used by radio & checkbox filters
************************************************************
###
class ListFilter extends CommonFilter
constructor: (@selector, @options) ->
super
if @elm
@filters = @options.filters
@activeFilters = []
@handleTemplate()
@handleFilters()
@handleActiveFilterText()
# ************************************************************
# Events
# ************************************************************
bindEvents: ->
super
@dropdownInner.addEventListener "click", @dropdownClicked
@clear.addEventListener "click", @clearFilter
unbindEvents: ->
super
@dropdownInner.removeEventListener "click", @dropdownClicked
@clear.addEventListener "click", @clearFilter
# ************************************************************
# Actions
# ************************************************************
dropdownClicked: (e) =>
if e.target.tagName is "INPUT"
@activeFilters = []
for input, index in @inputElms
if input.checked
filter = input.value
if Utils.isNumber filter then filter = parseInt filter
@activeFilters.push filter
@handleActiveFilterText()
if @activeFilters.length isnt 0
if @options.type is "radio"
@hideFilters()
@activeFilters = @activeFilters[0]
@options.onFilterApplied @activeFilters
else
@options.onFilterCleared()
clearFilter: (e) =>
e.preventDefault()
@activeFilters = []
@handleActiveFilterText()
for input, index in @inputElms
input.checked = no
super
# ************************************************************
# Templating
# ************************************************************
handleTemplate: ->
super
# Handle specific template needs of ListFilters.
@filterSnippet = """
<label class="sift-label">
<input type="#{@options.type}" name="{{name}}" value="{{value}}" {{checked}}>
<span>{{displayName}}</span>
</label>
"""
@handleInitialRender()
handleFilters: ->
filtersSnippet = ""
for filter, index in @filters
checked = ""
if @options.activeFilter
multipleActiveFilters = typeof @options.activeFilter is "object"
if multipleActiveFilters
unless @options.type is "radio"
filterActive = Utils.where null, filter.value, @options.activeFilter
if filterActive
checked = "checked"
@activeFilters.push filter.value
else
console.warn "Can't have multiple active filters for radio buttons"
else
if Utils.isNumber @options.activeFilter then @options.activeFilter = parseInt @options.activeFilter
if @options.activeFilter is filter.value
checked = "checked"
@activeFilters.push filter.value
filtersSnippet += @filterSnippet.replace("{{displayName}}", filter.displayName)
.replace("{{name}}", @options.displayName)
.replace("{{value}}", filter.value)
.replace("{{checked}}", checked)
@render @dropdownInner, filtersSnippet
@inputElms = @dropdownInner.getElementsByTagName "input"
handleActiveFilterText: ->
if @activeFilters.length isnt 0
activeFilterText = ""
@render @filterName, "#{@options.displayName}:"
for filter, index in @activeFilters
if index isnt 0 then activeFilterText += ", "
if Utils.isNumber filter then filter = parseInt filter
activeFilterText += Utils.where("value", filter, @filters)[0].displayName
@render @activeFilterText, activeFilterText
Utils.addClass "with-active-filter", @elm
else
@render @filterName, "#{@options.displayName}"
@render @activeFilterText, ""
Utils.removeClass "with-active-filter", @elm
###
************************************************************
End of ListFilter
************************************************************
###
###
************************************************************
CalendarFilter used by date & date range filters
************************************************************
###
class CalendarFilter extends CommonFilter
constructor: (@selector, @options) ->
super
if @elm
@activeDate = @options.calendarOptions?.existingDate
@activeDateRange = @options.calendarOptions?.existingDateRange
@handleTemplate()
@handleFilters()
@handleActiveFilterText()
# ************************************************************
# Events
# ************************************************************
bindEvents: ->
super
@clear.addEventListener "click", @clearFilter
unbindEvents: ->
super
@clear.addEventListener "click", @clearFilter
# ************************************************************
# Hooks
# Subscribe to DateJust or DateRange hooks
# ************************************************************
handleDateJustHooks: ->
@dateJust.options.onDateSelected = (date) =>
@activeDate = date
@activeDateRange = null
@handleActiveFilterText()
@options.onFilterApplied date
@dateJust.options.onDateRangeSelected = (startDate, endDate) =>
@activeDate = null
@activeDateRange = [startDate, endDate]
@handleActiveFilterText()
@options.onFilterApplied startDate, endDate
handleDateRangeHooks: ->
@dateRange.options.onDateRangeSelected = (startDate, endDate) =>
@activeDateRange = [startDate, endDate]
@handleActiveFilterText()
@options.onFilterApplied startDate, endDate
# ************************************************************
# Actions
# ************************************************************
clearFilter: (e) =>
e.preventDefault()
if @options.type is "calendar"
@dateJust.reset()
else if @options.type is "multi_calendar"
@dateRange.reset()
@activeDate = null
@activeDateRange = null
@handleActiveFilterText()
super
# ************************************************************
# Templating
# ************************************************************
handleTemplate: ->
super
@handleInitialRender()
handleFilters: ->
@render @dropdownInner, """<div class="sift-calendar-wrap"></div>"""
@calendarWrap = @dropdownInner.querySelector ".sift-calendar-wrap"
Utils.addClass "without-scroll", @elm
if @options.type is "calendar"
@dateJust = new DateJust @calendarWrap, @options.calendarOptions
@handleDateJustHooks()
else if @options.type is "multi_calendar"
@dateRange = new DateRange @calendarWrap, @options.calendarOptions
Utils.addClass "with-multi-calendar", @elm
@handleDateRangeHooks()
handleActiveFilterText: ->
if @activeDate or @activeDateRange
@render @filterName, "#{@options.displayName}:"
Utils.addClass "with-active-filter", @elm
if @activeDate
@render @activeFilterText, @activeDate.toDateString() # TODO: date format might need to be an option?
else if @activeDateRange
@render @activeFilterText, "#{@activeDateRange[0].toDateString()} - #{@activeDateRange[1].toDateString()}"
else
@render @filterName, "#{@options.displayName}"
Utils.removeClass "with-active-filter", @elm
@render @activeFilterText, ""
###
************************************************************
End of CalendarFilter
************************************************************
###
window.Sift = Sift
Utils =
extend: (target, objects...) ->
for object in objects
target[key] = val for key, val of object
target
where: (key, value, array) ->
results = []
array.filter (object) ->
if typeof object is "object"
results.push object if object[key] == value
else
results.push object if object == value
if results.length > 0
results
addClass: (className, elm) ->
elm.classList.add className
removeClass: (className, elm) ->
elm.classList.remove className
isNumber: (thing) ->
!isNaN(parseInt(thing)) | true | ###
The MIT License (MIT)
Copyright (c) 2016 PI:NAME:<NAME>END_PI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
###
noop = ->
###
************************************************************
Sift is the public interface used by the outside world.
************************************************************
###
class Sift
defaultOptions:
onFilterApplied: noop # External hook
onFilterCleared: noop # External hook
version: "0.1.1"
constructor: (selector, options) ->
options = Utils.extend {}, @defaultOptions, options
switch options.type
when "checkbox" then new ListFilter selector, options
when "radio" then new ListFilter selector, options
when "calendar" then new CalendarFilter selector, options
when "multi_calendar" then new CalendarFilter selector, options
###
************************************************************
End of Sift
************************************************************
###
###
************************************************************
CommonFilter implements shared things for all filters
************************************************************
###
class CommonFilter
filtersShowing: no
constructor: ->
@elm = @handleElm()
unless @elm
console.warn "Slab couldn't initialize #{@selector} as it's not in the DOM"
# You can initialize Sift with a class/id selector or with an actual DOM element.
handleElm: ->
if typeof @selector is "string"
elm = document.querySelector @selector
else if typeof @selector is "object"
# Check that object is an actual dom element.
if @selector.nodeName
elm = @selector
elm
# ************************************************************
# Events
# ************************************************************
# Persistent events are ones that need to be listened to all the time.
bindCommonPersistentEvents: ->
@filterButton.addEventListener "click", @openFilters
# Events are ones that need to be listened to when the filter is open.
bindEvents: ->
document.addEventListener "click", @closeFilters
# Stop listening to events (i.e when the filter is closed)
unbindEvents: ->
document.removeEventListener "click", @closeFilters
# ************************************************************
# Actions
# ************************************************************
openFilters: (e) =>
e.preventDefault()
@bindEvents()
@showFilters()
closeFilters: (e) =>
if $(e.target).parents(".sift-container").length < 1
@hideFilters()
@unbindEvents()
clearFilter: ->
@hideFilters()
@options.onFilterCleared()
# ************************************************************
# Templating
# ************************************************************
render: (elm, template) ->
elm.innerHTML = template
handleTemplate: ->
# Handle common template needs of all filters.
@template = """
<a href="" class="sift-link">
<span class="sift-filter-name">#{@options.displayName}</span>
<span class="sift-active-filter-text"></span>
</a>
<div class="sift-dropdown">
<a href="" class="sift-clear">Clear filter</a>
<div class="sift-dropdown-inner"></div>
</div>
"""
handleInitialRender: ->
@render @elm, @template
# Now that sift is rendered we can do DOM related things.
@filterButton = @elm.querySelector ".sift-link"
@filterName = @elm.querySelector ".sift-filter-name"
@activeFilterText = @elm.querySelector ".sift-active-filter-text"
@dropdown = @elm.querySelector ".sift-dropdown"
@clear = @elm.querySelector ".sift-clear"
@dropdownInner = @elm.querySelector ".sift-dropdown-inner"
Utils.addClass "sift-container", @elm
@bindCommonPersistentEvents()
showFilters: ->
@filtersShowing = yes
Utils.addClass "filters-showing", @elm
hideFilters: ->
@filtersShowing = no
Utils.removeClass "filters-showing", @elm
###
************************************************************
End of CommonFilter
************************************************************
###
###
************************************************************
ListFilter used by radio & checkbox filters
************************************************************
###
class ListFilter extends CommonFilter
constructor: (@selector, @options) ->
super
if @elm
@filters = @options.filters
@activeFilters = []
@handleTemplate()
@handleFilters()
@handleActiveFilterText()
# ************************************************************
# Events
# ************************************************************
bindEvents: ->
super
@dropdownInner.addEventListener "click", @dropdownClicked
@clear.addEventListener "click", @clearFilter
unbindEvents: ->
super
@dropdownInner.removeEventListener "click", @dropdownClicked
@clear.addEventListener "click", @clearFilter
# ************************************************************
# Actions
# ************************************************************
dropdownClicked: (e) =>
if e.target.tagName is "INPUT"
@activeFilters = []
for input, index in @inputElms
if input.checked
filter = input.value
if Utils.isNumber filter then filter = parseInt filter
@activeFilters.push filter
@handleActiveFilterText()
if @activeFilters.length isnt 0
if @options.type is "radio"
@hideFilters()
@activeFilters = @activeFilters[0]
@options.onFilterApplied @activeFilters
else
@options.onFilterCleared()
clearFilter: (e) =>
e.preventDefault()
@activeFilters = []
@handleActiveFilterText()
for input, index in @inputElms
input.checked = no
super
# ************************************************************
# Templating
# ************************************************************
handleTemplate: ->
super
# Handle specific template needs of ListFilters.
@filterSnippet = """
<label class="sift-label">
<input type="#{@options.type}" name="{{name}}" value="{{value}}" {{checked}}>
<span>{{displayName}}</span>
</label>
"""
@handleInitialRender()
handleFilters: ->
filtersSnippet = ""
for filter, index in @filters
checked = ""
if @options.activeFilter
multipleActiveFilters = typeof @options.activeFilter is "object"
if multipleActiveFilters
unless @options.type is "radio"
filterActive = Utils.where null, filter.value, @options.activeFilter
if filterActive
checked = "checked"
@activeFilters.push filter.value
else
console.warn "Can't have multiple active filters for radio buttons"
else
if Utils.isNumber @options.activeFilter then @options.activeFilter = parseInt @options.activeFilter
if @options.activeFilter is filter.value
checked = "checked"
@activeFilters.push filter.value
filtersSnippet += @filterSnippet.replace("{{displayName}}", filter.displayName)
.replace("{{name}}", @options.displayName)
.replace("{{value}}", filter.value)
.replace("{{checked}}", checked)
@render @dropdownInner, filtersSnippet
@inputElms = @dropdownInner.getElementsByTagName "input"
handleActiveFilterText: ->
if @activeFilters.length isnt 0
activeFilterText = ""
@render @filterName, "#{@options.displayName}:"
for filter, index in @activeFilters
if index isnt 0 then activeFilterText += ", "
if Utils.isNumber filter then filter = parseInt filter
activeFilterText += Utils.where("value", filter, @filters)[0].displayName
@render @activeFilterText, activeFilterText
Utils.addClass "with-active-filter", @elm
else
@render @filterName, "#{@options.displayName}"
@render @activeFilterText, ""
Utils.removeClass "with-active-filter", @elm
###
************************************************************
End of ListFilter
************************************************************
###
###
************************************************************
CalendarFilter used by date & date range filters
************************************************************
###
class CalendarFilter extends CommonFilter
constructor: (@selector, @options) ->
super
if @elm
@activeDate = @options.calendarOptions?.existingDate
@activeDateRange = @options.calendarOptions?.existingDateRange
@handleTemplate()
@handleFilters()
@handleActiveFilterText()
# ************************************************************
# Events
# ************************************************************
bindEvents: ->
super
@clear.addEventListener "click", @clearFilter
unbindEvents: ->
super
@clear.addEventListener "click", @clearFilter
# ************************************************************
# Hooks
# Subscribe to DateJust or DateRange hooks
# ************************************************************
handleDateJustHooks: ->
@dateJust.options.onDateSelected = (date) =>
@activeDate = date
@activeDateRange = null
@handleActiveFilterText()
@options.onFilterApplied date
@dateJust.options.onDateRangeSelected = (startDate, endDate) =>
@activeDate = null
@activeDateRange = [startDate, endDate]
@handleActiveFilterText()
@options.onFilterApplied startDate, endDate
handleDateRangeHooks: ->
@dateRange.options.onDateRangeSelected = (startDate, endDate) =>
@activeDateRange = [startDate, endDate]
@handleActiveFilterText()
@options.onFilterApplied startDate, endDate
# ************************************************************
# Actions
# ************************************************************
clearFilter: (e) =>
e.preventDefault()
if @options.type is "calendar"
@dateJust.reset()
else if @options.type is "multi_calendar"
@dateRange.reset()
@activeDate = null
@activeDateRange = null
@handleActiveFilterText()
super
# ************************************************************
# Templating
# ************************************************************
handleTemplate: ->
super
@handleInitialRender()
handleFilters: ->
@render @dropdownInner, """<div class="sift-calendar-wrap"></div>"""
@calendarWrap = @dropdownInner.querySelector ".sift-calendar-wrap"
Utils.addClass "without-scroll", @elm
if @options.type is "calendar"
@dateJust = new DateJust @calendarWrap, @options.calendarOptions
@handleDateJustHooks()
else if @options.type is "multi_calendar"
@dateRange = new DateRange @calendarWrap, @options.calendarOptions
Utils.addClass "with-multi-calendar", @elm
@handleDateRangeHooks()
handleActiveFilterText: ->
if @activeDate or @activeDateRange
@render @filterName, "#{@options.displayName}:"
Utils.addClass "with-active-filter", @elm
if @activeDate
@render @activeFilterText, @activeDate.toDateString() # TODO: date format might need to be an option?
else if @activeDateRange
@render @activeFilterText, "#{@activeDateRange[0].toDateString()} - #{@activeDateRange[1].toDateString()}"
else
@render @filterName, "#{@options.displayName}"
Utils.removeClass "with-active-filter", @elm
@render @activeFilterText, ""
###
************************************************************
End of CalendarFilter
************************************************************
###
window.Sift = Sift
Utils =
extend: (target, objects...) ->
for object in objects
target[key] = val for key, val of object
target
where: (key, value, array) ->
results = []
array.filter (object) ->
if typeof object is "object"
results.push object if object[key] == value
else
results.push object if object == value
if results.length > 0
results
addClass: (className, elm) ->
elm.classList.add className
removeClass: (className, elm) ->
elm.classList.remove className
isNumber: (thing) ->
!isNaN(parseInt(thing)) |
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.999851405620575,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/client/hallo/hallo/plugins/headings.coffee | HansPinckaers/ShareJS-editor | 4 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget "IKS.halloheadings",
options:
editable: null
toolbar: null
uuid: ""
headers: [1,2,3]
_create: ->
widget = this
buttonset = jQuery "<span class=\"#{widget.widgetName}\"></span>"
id = "#{@options.uuid}-paragraph"
label = "P"
buttonset.append jQuery("<input id=\"#{id}\" type=\"radio\" name=\"#{widget.options.uuid}-headings\"/><label for=\"#{id}\" class=\"p_button\">#{label}</label>").button()
button = jQuery "##{id}", buttonset
button.attr "hallo-command", "formatBlock"
button.bind "change", (event) ->
cmd = jQuery(this).attr "hallo-command"
widget.options.editable.execute cmd, "P"
buttonize = (headerSize) =>
label = "H" + headerSize
id = "#{@options.uuid}-#{headerSize}"
buttonset.append jQuery("<input id=\"#{id}\" type=\"radio\" name=\"#{widget.options.uuid}-headings\"/><label for=\"#{id}\" class=\"h#{headerSize}_button\">#{label}</label>").button()
button = jQuery "##{id}", buttonset
button.attr "hallo-size", "H"+headerSize
button.bind "change", (event) ->
size = jQuery(this).attr "hallo-size"
widget.options.editable.execute "formatBlock", size
buttonize header for header in @options.headers
buttonset.buttonset()
@element.bind "keyup paste change mouseup", (event) ->
try format = document.queryCommandValue("formatBlock").toUpperCase() catch e then format = ''
if format is "P"
selectedButton = jQuery("##{widget.options.uuid}-paragraph")
else if matches = format.match(/\d/)
formatNumber = matches[0]
selectedButton = jQuery("##{widget.options.uuid}-#{formatNumber}")
labelParent = jQuery(buttonset)
labelParent.children("input").attr "checked", false
labelParent.children("label").removeClass "ui-state-clicked"
labelParent.children("input").button("widget").button "refresh"
if selectedButton
selectedButton.attr "checked", true
selectedButton.next("label").addClass "ui-state-clicked"
selectedButton.button "refresh"
@options.toolbar.append buttonset
_init: ->
)(jQuery)
| 24422 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget "IKS.halloheadings",
options:
editable: null
toolbar: null
uuid: ""
headers: [1,2,3]
_create: ->
widget = this
buttonset = jQuery "<span class=\"#{widget.widgetName}\"></span>"
id = "#{@options.uuid}-paragraph"
label = "P"
buttonset.append jQuery("<input id=\"#{id}\" type=\"radio\" name=\"#{widget.options.uuid}-headings\"/><label for=\"#{id}\" class=\"p_button\">#{label}</label>").button()
button = jQuery "##{id}", buttonset
button.attr "hallo-command", "formatBlock"
button.bind "change", (event) ->
cmd = jQuery(this).attr "hallo-command"
widget.options.editable.execute cmd, "P"
buttonize = (headerSize) =>
label = "H" + headerSize
id = "#{@options.uuid}-#{headerSize}"
buttonset.append jQuery("<input id=\"#{id}\" type=\"radio\" name=\"#{widget.options.uuid}-headings\"/><label for=\"#{id}\" class=\"h#{headerSize}_button\">#{label}</label>").button()
button = jQuery "##{id}", buttonset
button.attr "hallo-size", "H"+headerSize
button.bind "change", (event) ->
size = jQuery(this).attr "hallo-size"
widget.options.editable.execute "formatBlock", size
buttonize header for header in @options.headers
buttonset.buttonset()
@element.bind "keyup paste change mouseup", (event) ->
try format = document.queryCommandValue("formatBlock").toUpperCase() catch e then format = ''
if format is "P"
selectedButton = jQuery("##{widget.options.uuid}-paragraph")
else if matches = format.match(/\d/)
formatNumber = matches[0]
selectedButton = jQuery("##{widget.options.uuid}-#{formatNumber}")
labelParent = jQuery(buttonset)
labelParent.children("input").attr "checked", false
labelParent.children("label").removeClass "ui-state-clicked"
labelParent.children("input").button("widget").button "refresh"
if selectedButton
selectedButton.attr "checked", true
selectedButton.next("label").addClass "ui-state-clicked"
selectedButton.button "refresh"
@options.toolbar.append buttonset
_init: ->
)(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
((jQuery) ->
jQuery.widget "IKS.halloheadings",
options:
editable: null
toolbar: null
uuid: ""
headers: [1,2,3]
_create: ->
widget = this
buttonset = jQuery "<span class=\"#{widget.widgetName}\"></span>"
id = "#{@options.uuid}-paragraph"
label = "P"
buttonset.append jQuery("<input id=\"#{id}\" type=\"radio\" name=\"#{widget.options.uuid}-headings\"/><label for=\"#{id}\" class=\"p_button\">#{label}</label>").button()
button = jQuery "##{id}", buttonset
button.attr "hallo-command", "formatBlock"
button.bind "change", (event) ->
cmd = jQuery(this).attr "hallo-command"
widget.options.editable.execute cmd, "P"
buttonize = (headerSize) =>
label = "H" + headerSize
id = "#{@options.uuid}-#{headerSize}"
buttonset.append jQuery("<input id=\"#{id}\" type=\"radio\" name=\"#{widget.options.uuid}-headings\"/><label for=\"#{id}\" class=\"h#{headerSize}_button\">#{label}</label>").button()
button = jQuery "##{id}", buttonset
button.attr "hallo-size", "H"+headerSize
button.bind "change", (event) ->
size = jQuery(this).attr "hallo-size"
widget.options.editable.execute "formatBlock", size
buttonize header for header in @options.headers
buttonset.buttonset()
@element.bind "keyup paste change mouseup", (event) ->
try format = document.queryCommandValue("formatBlock").toUpperCase() catch e then format = ''
if format is "P"
selectedButton = jQuery("##{widget.options.uuid}-paragraph")
else if matches = format.match(/\d/)
formatNumber = matches[0]
selectedButton = jQuery("##{widget.options.uuid}-#{formatNumber}")
labelParent = jQuery(buttonset)
labelParent.children("input").attr "checked", false
labelParent.children("label").removeClass "ui-state-clicked"
labelParent.children("input").button("widget").button "refresh"
if selectedButton
selectedButton.attr "checked", true
selectedButton.next("label").addClass "ui-state-clicked"
selectedButton.button "refresh"
@options.toolbar.append buttonset
_init: ->
)(jQuery)
|
[
{
"context": "ingIO\n importFile: \"\"\n constructor: ({\n name: @name\n importFunc: @importFunc\n exportFunc: @",
"end": 60,
"score": 0.6965059041976929,
"start": 60,
"tag": "NAME",
"value": ""
},
{
"context": "gIO\n importFile: \"\"\n constructor: ({\n name: @name\n... | src/view/config.coffee | readcrx-2/read.crx-2 | 38 | class SettingIO
importFile: ""
constructor: ({
name: @name
importFunc: @importFunc
exportFunc: @exportFunc
}) ->
@$status = $$.I("#{@name}_status")
if @importFunc?
@$fileSelectButton = $$.C("#{@name}_file_show")[0]
@$fileSelectButtonHidden = $$.C("#{@name}_file_hide")[0]
@$importButton = $$.C("#{@name}_import_button")[0]
@setupFileSelectButton()
@setupImportButton()
if @exportFunc?
@$exportButton = $$.C("#{@name}_export_button")[0]
@setupExportButton()
return
setupFileSelectButton: ->
@$fileSelectButton.on("click", =>
return unless _checkExcute(@name, "file_select")
@$status.setClass("")
@$fileSelectButtonHidden.click()
_clearExcute()
return
)
@$fileSelectButtonHidden.on("change", (e) =>
file = e.target.files
reader = new FileReader()
reader.readAsText(file[0])
reader.onload = =>
@importFile = reader.result
@$status.addClass("select")
@$status.textContent = "ファイル選択完了"
return
return
)
return
setupImportButton: ->
@$importButton.on("click", =>
return unless _checkExcute(@name, "import")
if @importFile isnt ""
@$status.setClass("loading")
@$status.textContent = "更新中"
try
await @importFunc(@importFile)
@$status.addClass("done")
@$status.textContent = "インポート完了"
catch
@$status.addClass("fail")
@$status.textContent = "インポート失敗"
else
@$status.addClass("fail")
@$status.textContent = "ファイルを選択してください"
_clearExcute()
return
)
return
setupExportButton: ->
@$exportButton.on("click", =>
return unless _checkExcute(@name, "export")
blob = new Blob([@exportFunc()], type: "text/plain")
$a = $__("a").addClass("hidden")
url = URL.createObjectURL(blob)
$a.href = url
$a.download = "read.crx-2_#{@name}.json"
@$exportButton.addAfter($a)
$a.click()
$a.remove()
URL.revokeObjectURL(url)
_clearExcute()
return
)
return
class HistoryIO extends SettingIO
constructor: ({
name
countFunc: @countFunc
importFunc
exportFunc
clearFunc: @clearFunc
clearRangeFunc: @clearRangeFunc
afterChangedFunc: @afterChangedFunc
}) ->
super({
name
importFunc
exportFunc
})
@name = name
@importFunc = importFunc
@exportFunc = exportFunc
@$count = $$.I("#{@name}_count")
@$progress = $$.I("#{@name}_progress")
@$clearButton = $$.C("#{@name}_clear")[0]
@$clearRangeButton = $$.C("#{@name}_range_clear")[0]
@showCount()
@setupClearButton()
@setupClearRangeButton()
return
showCount: ->
count = await @countFunc()
@$count.textContent = "#{count}件"
return
setupClearButton: ->
@$clearButton.on("click", =>
return unless _checkExcute(@name, "clear")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":削除中"
try
await @clearFunc()
@$status.textContent = ":削除完了"
parent.$$.$("iframe[src=\"/view/#{@name}.html\"]")?.contentDocument.C("view")[0].emit(new Event("request_reload"))
catch
@$status.textContent = ":削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupClearRangeButton: ->
@$clearRangeButton.on("click", =>
return unless _checkExcute(@name, "clear_range")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":範囲指定削除中"
try
await @clearRangeFunc(parseInt($$.C("#{@name}_date_range")[0].value))
@$status.textContent = ":範囲指定削除完了"
parent.$$.$("iframe[src=\"/view/#{@name}.html\"]")?.contentDocument.C("view")[0].emit(new Event("request_reload"))
catch
@$status.textContent = ":範囲指定削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupImportButton: ->
@$importButton.on("click", =>
return unless _checkExcute(@name, "import")
if @importFile isnt ""
@$status.setClass("loading")
@$status.textContent = ":更新中"
try
await @importFunc(JSON.parse(@importFile), @$progress)
count = await @countFunc()
@$status.setClass("done")
@$status.textContent = ":インポート完了"
catch
@$status.setClass("fail")
@$status.textContent = ":インポート失敗"
@showCount()
@afterChangedFunc()
else
@$status.addClass("fail")
@$status.textContent = ":ファイルを選択してください"
@$progress.textContent = ""
_clearExcute()
return
)
return
setupExportButton: ->
@$exportButton.on("click", =>
return unless _checkExcute(@name, "export")
data = await @exportFunc()
exportText = JSON.stringify(data)
blob = new Blob([exportText], type: "text/plain")
$a = $__("a").addClass("hidden")
url = URL.createObjectURL(blob)
$a.href = url
$a.download = "read.crx-2_#{@name}.json"
@$exportButton.addAfter($a)
$a.click()
$a.remove()
URL.revokeObjectURL(url)
_clearExcute()
return
)
return
class BookmarkIO extends SettingIO
constructor: ({
name
countFunc: @countFunc
importFunc
exportFunc
clearFunc: @clearFunc
clearExpiredFunc: @clearExpiredFunc
afterChangedFunc: @afterChangedFunc
}) ->
super({
name
importFunc
exportFunc
})
@name = name
@importFunc = importFunc
@exportFunc = exportFunc
@$count = $$.I("#{@name}_count")
@$progress = $$.I("#{@name}_progress")
@$clearButton = $$.C("#{@name}_clear")[0]
@$clearExpiredButton = $$.C("#{@name}_expired_clear")[0]
@showCount()
@setupClearButton()
@setupClearExpiredButton()
return
showCount: ->
count = await @countFunc()
@$count.textContent = "#{count}件"
return
setupClearButton: ->
@$clearButton.on("click", =>
return unless _checkExcute(@name, "clear")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":削除中"
try
await @clearFunc()
@$status.textContent = ":削除完了"
catch
@$status.textContent = ":削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupClearExpiredButton: ->
@$clearExpiredButton.on("click", =>
return unless _checkExcute(@name, "clear_expired")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":dat落ち削除中"
try
await @clearExpiredFunc()
@$status.textContent = ":dat落ち削除完了"
catch
@$status.textContent = ":dat落ち削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupImportButton: ->
@$importButton.on("click", =>
return unless _checkExcute(@name, "import")
if @importFile isnt ""
@$status.setClass("loading")
@$status.textContent = ":更新中"
try
await @importFunc(JSON.parse(@importFile), @$progress)
count = await @countFunc()
@$status.setClass("done")
@$status.textContent = ":インポート完了"
catch
@$status.setClass("fail")
@$status.textContent = ":インポート失敗"
@showCount()
@afterChangedFunc()
else
@$status.addClass("fail")
@$status.textContent = ":ファイルを選択してください"
@$progress.textContent = ""
_clearExcute()
return
)
return
setupExportButton: ->
@$exportButton.on("click", =>
return unless _checkExcute(@name, "export")
data = await @exportFunc()
exportText = JSON.stringify(data)
blob = new Blob([exportText], type: "text/plain")
$a = $__("a").addClass("hidden")
url = URL.createObjectURL(blob)
$a.href = url
$a.download = "read.crx-2_#{@name}.json"
@$exportButton.addAfter($a)
$a.click()
$a.remove()
URL.revokeObjectURL(url)
_clearExcute()
return
)
return
# 処理の排他制御用
_excuteProcess = null
_excuteFunction = null
_procName = {
"history": "閲覧履歴"
"writehistory": "書込履歴"
"bookmark": "ブックマーク"
"cache": "キャッシュ"
"config": "設定"
}
_funcName = {
"import": "インポート"
"export": "エクスポート"
"clear": "削除"
"clear_range": "範囲指定削除"
"clear_expired":"dat落ち削除"
"file_select": "ファイル読み込み"
}
_checkExcute = (procId, funcId) ->
unless _excuteProcess
_excuteProcess = procId
_excuteFunction = funcId
return true
message = null
if _excuteProcess is procId
if _excuteFunction is funcId
message = "既に実行中です。"
else
message = "#{_funcName[_excuteFunction]}の実行中です。"
else
message = "#{_procName[_excuteProcess]}の処理中です。"
if message
new app.Notification("現在この機能は使用できません", message, "", "invalid")
return false
_clearExcute = ->
_excuteProcess = null
_excuteFunction = null
return
app.boot("/view/config.html", ["Cache", "BBSMenu"], (Cache, BBSMenu) ->
$view = document.documentElement
new app.view.IframeView($view)
# タブ
$tabbar = $view.C("tabbar")[0]
$tabs = $view.C("container")[0]
$tabbar.on("click", ({target}) ->
if target.tagName isnt "LI"
target = target.closest("li")
return unless target?
return if target.hasClass("selected")
$tabbar.C("selected")[0].removeClass("selected")
target.addClass("selected")
$tabs.C("selected")[0].removeClass("selected")
$tabs.$("[name=\"#{target.dataset.name}\"]").addClass("selected")
return
)
whenClose = ->
#NG設定
dom = $view.$("textarea[name=\"ngwords\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.NG.set(dom.value)
#ImageReplaceDat設定
dom = $view.$("textarea[name=\"image_replace_dat\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.ImageReplaceDat.set(dom.value)
#ReplaceStrTxt設定
dom = $view.$("textarea[name=\"replace_str_txt\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.ReplaceStrTxt.set(dom.value)
#bbsmenu設定
changeFlag = false
dom = $view.$("textarea[name=\"bbsmenu\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.config.set("bbsmenu", dom.value)
changeFlag = true
dom = $view.$("textarea[name=\"bbsmenu_option\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.config.set("bbsmenu_option", dom.value)
changeFlag = true
if changeFlag
$view.C("bbsmenu_reload")[0].click()
return
#閉じるボタン
$view.C("button_close")[0].on("click", ->
if frameElement
parent.postMessage(type: "request_killme", location.origin)
whenClose()
return
)
window.on("beforeunload", ->
whenClose()
return
)
#掲示板を開いたときに閉じる
for dom in $view.C("open_in_rcrx")
dom.on("click", ->
$view.C("button_close")[0].click()
return
)
#汎用設定項目
for dom in $view.$$("input.direct[type=\"text\"], textarea.direct")
dom.value = app.config.get(dom.name) or ""
dom.on("input", ->
app.config.set(@name, @value)
@setAttr("changed", "true")
return
)
for dom in $view.$$("input.direct[type=\"number\"]")
dom.value = app.config.get(dom.name) or "0"
dom.on("input", ->
app.config.set(@name, if Number.isNaN(@valueAsNumber) then "0" else @value)
return
)
for dom in $view.$$("input.direct[type=\"checkbox\"]")
dom.checked = app.config.get(dom.name) is "on"
dom.on("change", ->
app.config.set(@name, if @checked then "on" else "off")
return
)
for dom in $view.$$("input.direct[type=\"radio\"]")
if dom.value is app.config.get(dom.name)
dom.checked = true
dom.on("change", ->
val = $view.$("""input[name="#{@name}"]:checked""").value
app.config.set(@name, val)
return
)
for dom in $view.$$("input.direct[type=\"range\"]")
dom.value = app.config.get(dom.name) or "0"
$$.I("#{dom.name}_text").textContent = dom.value
dom.on("input", ->
$$.I("#{@name}_text").textContent = @value
app.config.set(@name, @value)
return
)
for dom in $view.$$("select.direct")
dom.value = app.config.get(dom.name) or ""
dom.on("change", ->
app.config.set(@name, @value)
return
)
#バージョン情報表示
do ->
{name, version} = await app.manifest
$view.C("version_text")[0].textContent = "#{name} v#{version} + #{navigator.userAgent}"
return
$view.C("version_copy")[0].on("click", ->
app.clipboardWrite($$.C("version_text")[0].textContent)
return
)
$view.C("keyboard_help")[0].on("click", (e) ->
e.preventDefault()
app.message.send("showKeyboardHelp")
return
)
#板覧更新ボタン
$view.C("bbsmenu_reload")[0].on("click", ({currentTarget: $button}) ->
$status = $$.I("bbsmenu_reload_status")
$button.disabled = true
$status.setClass("loading")
$status.textContent = "更新中"
dom = $view.$("textarea[name=\"bbsmenu\"]")
dom.removeAttr("changed")
app.config.set("bbsmenu", dom.value)
dom = $view.$("textarea[name=\"bbsmenu_option\"]")
dom.removeAttr("changed")
app.config.set("bbsmenu_option", dom.value)
try
await BBSMenu.get(true)
$status.setClass("done")
$status.textContent = "更新完了"
catch
$status.setClass("fail")
$status.textContent = "更新失敗"
$button.disabled = false
return
)
#履歴
new HistoryIO(
name: "history"
countFunc: ->
return app.History.count()
importFunc: ({history, read_state: readState, historyVersion = 1, readstateVersion = 1}, $progress) ->
total = history.length + readState.length
count = 0
for hs in history
hs.boardTitle = "" if historyVersion is 1
await app.History.add(hs.url, hs.title, hs.date, hs.boardTitle)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
for rs in readState
rs.date = null if readstateVersion is 1
_rs = await app.ReadState.get(rs.url)
if app.util.isNewerReadState(_rs, rs)
await app.ReadState.set(rs)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
return
exportFunc: ->
[readState, history] = await Promise.all([
app.ReadState.getAll()
app.History.getAll()
])
return {"read_state": readState, "history": history, "historyVersion": app.History.DB_VERSION, "readstateVersion": app.ReadState.DB_VERSION}
clearFunc: ->
return Promise.all([app.History.clear(), app.ReadState.clear()])
clearRangeFunc: (day) ->
return app.History.clearRange(day)
afterChangedFunc: ->
updateIndexedDBUsage()
return
)
new HistoryIO(
name: "writehistory"
countFunc: ->
return app.WriteHistory.count()
importFunc: ({writehistory = null, dbVersion = 1}, $progress) ->
return Promise.resolve() unless writehistory
total = writehistory.length
count = 0
unixTime201710 = 1506783600 # 2017/10/01 0:00:00
for whis in writehistory
whis.inputName = whis.input_name
whis.inputMail = whis.input_mail
if dbVersion < 2
if +whis.date <= unixTime201710 and whis.res > 1
date = new Date(+whis.date)
date.setMonth(date.getMonth()-1)
whis.date = date.valueOf()
await app.WriteHistory.add(whis)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
return
exportFunc: ->
return {"writehistory": await app.WriteHistory.getAll(), "dbVersion": app.WriteHistory.DB_VERSION}
clearFunc: ->
return app.WriteHistory.clear()
clearRangeFunc: (day) ->
return app.WriteHistory.clearRange(day)
afterChangedFunc: ->
updateIndexedDBUsage()
return
)
# ブックマーク
new BookmarkIO(
name: "bookmark"
countFunc: ->
return app.bookmark.getAll().length
importFunc: ({bookmark, readState, readstateVersion = 1}, $progress) ->
total = bookmark.length + readState.length
count = 0
for bm in bookmark
await app.bookmark.import(bm)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
for rs in readState
rs.date = null if readstateVersion is 1
_rs = await app.ReadState.get(rs.url)
if app.util.isNewerReadState(_rs, rs)
await app.ReadState.set(rs)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
return
exportFunc: ->
[bookmark, readState] = await Promise.all([
app.bookmark.getAll()
app.ReadState.getAll()
])
return {"bookmark": bookmark, "readState": readState, "readstateVersion": app.ReadState.DB_VERSION}
clearFunc: ->
return app.bookmark.removeAll()
clearExpiredFunc: ->
return app.bookmark.removeAllExpired()
afterChangedFunc: ->
updateIndexedDBUsage()
return
)
do ->
#キャッシュ削除ボタン
$clearButton = $view.C("cache_clear")[0]
$status = $$.I("cache_status")
$count = $$.I("cache_count")
do setCount = ->
count = await Cache.count()
$count.textContent = "#{count}件"
return
$clearButton.on("click", ->
return unless _checkExcute("cache", "clear")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
$status.textContent = ":削除中"
try
await Cache.delete()
$status.textContent = ":削除完了"
catch
$status.textContent = ":削除失敗"
setCount()
updateIndexedDBUsage()
_clearExcute()
return
)
#キャッシュ範囲削除ボタン
$clearRangeButton = $view.C("cache_range_clear")[0]
$clearRangeButton.on("click", ->
return unless _checkExcute("cache", "clear_range")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
$status.textContent = ":範囲指定削除中"
try
await Cache.clearRange(parseInt($view.C("cache_date_range")[0].value))
$status.textContent = ":削除完了"
catch
$status.textContent = ":削除失敗"
setCount()
updateIndexedDBUsage()
_clearExcute()
return
)
return
do ->
#ブックマークフォルダ変更ボタン
$view.C("bookmark_source_change")[0].on("click", ->
app.message.send("open", url: "bookmark_source_selector")
return
)
#ブックマークフォルダ表示
do updateName = ->
[folder] = await parent.browser.bookmarks.get(app.config.get("bookmark_id"))
$$.I("bookmark_source_name").textContent = folder.title
return
app.message.on("config_updated", ({key}) ->
updateName() if key is "bookmark_id"
return
)
return
#「テーマなし」設定
if app.config.get("theme_id") is "none"
$view.C("theme_none")[0].checked = true
app.message.on("config_updated", ({key, val}) ->
if key is "theme_id"
$view.C("theme_none")[0].checked = (val is "none")
return
)
$view.C("theme_none")[0].on("click", ->
app.config.set("theme_id", if @checked then "none" else "default")
return
)
#bbsmenu設定
resetBBSMenu = ->
await app.config.del("bbsmenu")
$view.$("textarea[name=\"bbsmenu\"]").value = app.config.get("bbsmenu")
$$.C("bbsmenu_reload")[0].click()
return
if $view.$("textarea[name=\"bbsmenu\"]").value is ""
resetBBSMenu()
$view.C("bbsmenu_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
resetBBSMenu()
return
)
for $dom in $view.$$("input[type=\"radio\"]") when $dom.name in ["ng_id_expire", "ng_slip_expire"]
$dom.on("change", ->
$$.I(@name).dataset.value = @value if @checked
return
)
$dom.emit(new Event("change"))
# ImageReplaceDatのリセット
$view.C("dat_file_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
await app.config.del("image_replace_dat")
resetData = app.config.get("image_replace_dat")
$view.$("textarea[name=\"image_replace_dat\"]").value = resetData
app.ImageReplaceDat.set(resetData)
return
)
# ぼかし判定用正規表現のリセット
$view.C("image_blur_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
await app.config.del("image_blur_word")
resetData = app.config.get("image_blur_word")
$view.$("input[name=\"image_blur_word\"]").value = resetData
return
)
# NG設定のリセット
$view.C("ngwords_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
await app.config.del("ngwords")
resetData = app.config.get("ngwords")
$view.$("textarea[name=\"ngwords\"]").value = resetData
app.NG.set(resetData)
return
)
# 設定をインポート/エクスポート
new SettingIO(
name: "config"
importFunc: (file) ->
json = JSON.parse(file)
for key, value of json
key = key.slice(7)
if key isnt "theme_id"
$key = $view.$("input[name=\"#{key}\"]")
if $key?
switch $key.getAttr("type")
when "text", "range", "number"
$key.value = value
$key.emit(new Event("input"))
when "checkbox"
$key.checked = (value is "on")
$key.emit(new Event("change"))
when "radio"
for dom in $view.$$("input.direct[name=\"#{key}\"]")
if dom.value is value
dom.checked = true
$key.emit(new Event("change"))
else
$keyTextArea = $view.$("textarea[name=\"#{key}\"]")
if $keyTextArea?
$keyTextArea.value = value
$keyTextArea.emit(new Event("input"))
$keySelect = $view.$("select[name=\"#{key}\"]")
if $keySelect?
$keySelect.value = value
$keySelect.emit(new Event("change"))
#config_theme_idは「テーマなし」の場合があるので特例化
else
if value is "none"
$themeNone = $view.C("theme_none")[0]
$themeNone.click() unless $themeNone.checked
else
$view.$("input[name=\"theme_id\"]").value = value
$view.$("input[name=\"theme_id\"]").emit(new Event("change"))
return
exportFunc: ->
content = app.config.getAll()
delete content.config_last_board_sort_config
delete content.config_last_version
return JSON.stringify(content)
)
# ImageReplaceDatをインポート
new SettingIO(
name: "dat"
importFunc: (file) ->
datDom = $view.$("textarea[name=\"image_replace_dat\"]")
datDom.value = file
datDom.emit(new Event("input"))
return
)
# ReplaceStrTxtをインポート
new SettingIO(
name: "replacestr"
importFunc: (file) ->
replacestrDom = $view.$("textarea[name=\"replace_str_txt\"]")
replacestrDom.value = file
replacestrDom.emit(new Event("input"))
return
)
formatBytes = (bytes) ->
if bytes < 1048576
return (bytes/1024).toFixed(2) + "KB"
if bytes < 1073741824
return (bytes/1048576).toFixed(2) + "MB"
return (bytes/1073741824).toFixed(2) + "GB"
# indexeddbの使用状況
do updateIndexedDBUsage = ->
{quota, usage} = await navigator.storage.estimate()
$view.C("indexeddb_max")[0].textContent = formatBytes(quota)
$view.C("indexeddb_using")[0].textContent = formatBytes(usage)
$meter = $view.C("indexeddb_meter")[0]
$meter.max = quota
$meter.high = quota*0.9
$meter.low = quota*0.8
$meter.value = usage
return
# localstorageの使用状況
do ->
if parent.browser.storage.local.getBytesInUse?
# 無制限なのでindexeddbの最大と一致する
{quota} = await navigator.storage.estimate()
$view.C("localstorage_max")[0].textContent = formatBytes(quota)
$meter = $view.C("localstorage_meter")[0]
$meter.max = quota
$meter.high = quota*0.9
$meter.low = quota*0.8
usage = await parent.browser.storage.local.getBytesInUse()
$view.C("localstorage_using")[0].textContent = formatBytes(usage)
$meter.value = usage
else
$meter = $view.C("localstorage_meter")[0].remove()
$view.C("localstorage_max")[0].textContent = ""
$view.C("localstorage_using")[0].textContent = "このブラウザでは取得できません"
return
)
| 140703 | class SettingIO
importFile: ""
constructor: ({
name:<NAME> @name
importFunc: @importFunc
exportFunc: @exportFunc
}) ->
@$status = $$.I("#{@name}_status")
if @importFunc?
@$fileSelectButton = $$.C("#{@name}_file_show")[0]
@$fileSelectButtonHidden = $$.C("#{@name}_file_hide")[0]
@$importButton = $$.C("#{@name}_import_button")[0]
@setupFileSelectButton()
@setupImportButton()
if @exportFunc?
@$exportButton = $$.C("#{@name}_export_button")[0]
@setupExportButton()
return
setupFileSelectButton: ->
@$fileSelectButton.on("click", =>
return unless _checkExcute(@name, "file_select")
@$status.setClass("")
@$fileSelectButtonHidden.click()
_clearExcute()
return
)
@$fileSelectButtonHidden.on("change", (e) =>
file = e.target.files
reader = new FileReader()
reader.readAsText(file[0])
reader.onload = =>
@importFile = reader.result
@$status.addClass("select")
@$status.textContent = "ファイル選択完了"
return
return
)
return
setupImportButton: ->
@$importButton.on("click", =>
return unless _checkExcute(@name, "import")
if @importFile isnt ""
@$status.setClass("loading")
@$status.textContent = "更新中"
try
await @importFunc(@importFile)
@$status.addClass("done")
@$status.textContent = "インポート完了"
catch
@$status.addClass("fail")
@$status.textContent = "インポート失敗"
else
@$status.addClass("fail")
@$status.textContent = "ファイルを選択してください"
_clearExcute()
return
)
return
setupExportButton: ->
@$exportButton.on("click", =>
return unless _checkExcute(@name, "export")
blob = new Blob([@exportFunc()], type: "text/plain")
$a = $__("a").addClass("hidden")
url = URL.createObjectURL(blob)
$a.href = url
$a.download = "read.crx-2_#{@name}.json"
@$exportButton.addAfter($a)
$a.click()
$a.remove()
URL.revokeObjectURL(url)
_clearExcute()
return
)
return
class HistoryIO extends SettingIO
constructor: ({
name
countFunc: @countFunc
importFunc
exportFunc
clearFunc: @clearFunc
clearRangeFunc: @clearRangeFunc
afterChangedFunc: @afterChangedFunc
}) ->
super({
name
importFunc
exportFunc
})
@name = name
@importFunc = importFunc
@exportFunc = exportFunc
@$count = $$.I("#{@name}_count")
@$progress = $$.I("#{@name}_progress")
@$clearButton = $$.C("#{@name}_clear")[0]
@$clearRangeButton = $$.C("#{@name}_range_clear")[0]
@showCount()
@setupClearButton()
@setupClearRangeButton()
return
showCount: ->
count = await @countFunc()
@$count.textContent = "#{count}件"
return
setupClearButton: ->
@$clearButton.on("click", =>
return unless _checkExcute(@name, "clear")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":削除中"
try
await @clearFunc()
@$status.textContent = ":削除完了"
parent.$$.$("iframe[src=\"/view/#{@name}.html\"]")?.contentDocument.C("view")[0].emit(new Event("request_reload"))
catch
@$status.textContent = ":削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupClearRangeButton: ->
@$clearRangeButton.on("click", =>
return unless _checkExcute(@name, "clear_range")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":範囲指定削除中"
try
await @clearRangeFunc(parseInt($$.C("#{@name}_date_range")[0].value))
@$status.textContent = ":範囲指定削除完了"
parent.$$.$("iframe[src=\"/view/#{@name}.html\"]")?.contentDocument.C("view")[0].emit(new Event("request_reload"))
catch
@$status.textContent = ":範囲指定削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupImportButton: ->
@$importButton.on("click", =>
return unless _checkExcute(@name, "import")
if @importFile isnt ""
@$status.setClass("loading")
@$status.textContent = ":更新中"
try
await @importFunc(JSON.parse(@importFile), @$progress)
count = await @countFunc()
@$status.setClass("done")
@$status.textContent = ":インポート完了"
catch
@$status.setClass("fail")
@$status.textContent = ":インポート失敗"
@showCount()
@afterChangedFunc()
else
@$status.addClass("fail")
@$status.textContent = ":ファイルを選択してください"
@$progress.textContent = ""
_clearExcute()
return
)
return
setupExportButton: ->
@$exportButton.on("click", =>
return unless _checkExcute(@name, "export")
data = await @exportFunc()
exportText = JSON.stringify(data)
blob = new Blob([exportText], type: "text/plain")
$a = $__("a").addClass("hidden")
url = URL.createObjectURL(blob)
$a.href = url
$a.download = "read.crx-2_#{@name}.json"
@$exportButton.addAfter($a)
$a.click()
$a.remove()
URL.revokeObjectURL(url)
_clearExcute()
return
)
return
class BookmarkIO extends SettingIO
constructor: ({
name
countFunc: @countFunc
importFunc
exportFunc
clearFunc: @clearFunc
clearExpiredFunc: @clearExpiredFunc
afterChangedFunc: @afterChangedFunc
}) ->
super({
name
importFunc
exportFunc
})
@name = name
@importFunc = importFunc
@exportFunc = exportFunc
@$count = $$.I("#{@name}_count")
@$progress = $$.I("#{@name}_progress")
@$clearButton = $$.C("#{@name}_clear")[0]
@$clearExpiredButton = $$.C("#{@name}_expired_clear")[0]
@showCount()
@setupClearButton()
@setupClearExpiredButton()
return
showCount: ->
count = await @countFunc()
@$count.textContent = "#{count}件"
return
setupClearButton: ->
@$clearButton.on("click", =>
return unless _checkExcute(@name, "clear")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":削除中"
try
await @clearFunc()
@$status.textContent = ":削除完了"
catch
@$status.textContent = ":削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupClearExpiredButton: ->
@$clearExpiredButton.on("click", =>
return unless _checkExcute(@name, "clear_expired")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":dat落ち削除中"
try
await @clearExpiredFunc()
@$status.textContent = ":dat落ち削除完了"
catch
@$status.textContent = ":dat落ち削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupImportButton: ->
@$importButton.on("click", =>
return unless _checkExcute(@name, "import")
if @importFile isnt ""
@$status.setClass("loading")
@$status.textContent = ":更新中"
try
await @importFunc(JSON.parse(@importFile), @$progress)
count = await @countFunc()
@$status.setClass("done")
@$status.textContent = ":インポート完了"
catch
@$status.setClass("fail")
@$status.textContent = ":インポート失敗"
@showCount()
@afterChangedFunc()
else
@$status.addClass("fail")
@$status.textContent = ":ファイルを選択してください"
@$progress.textContent = ""
_clearExcute()
return
)
return
setupExportButton: ->
@$exportButton.on("click", =>
return unless _checkExcute(@name, "export")
data = await @exportFunc()
exportText = JSON.stringify(data)
blob = new Blob([exportText], type: "text/plain")
$a = $__("a").addClass("hidden")
url = URL.createObjectURL(blob)
$a.href = url
$a.download = "read.crx-2_#{@name}.json"
@$exportButton.addAfter($a)
$a.click()
$a.remove()
URL.revokeObjectURL(url)
_clearExcute()
return
)
return
# 処理の排他制御用
_excuteProcess = null
_excuteFunction = null
_procName = {
"history": "閲覧履歴"
"writehistory": "書込履歴"
"bookmark": "ブックマーク"
"cache": "キャッシュ"
"config": "設定"
}
_funcName = {
"import": "インポート"
"export": "エクスポート"
"clear": "削除"
"clear_range": "範囲指定削除"
"clear_expired":"dat落ち削除"
"file_select": "ファイル読み込み"
}
_checkExcute = (procId, funcId) ->
unless _excuteProcess
_excuteProcess = procId
_excuteFunction = funcId
return true
message = null
if _excuteProcess is procId
if _excuteFunction is funcId
message = "既に実行中です。"
else
message = "#{_funcName[_excuteFunction]}の実行中です。"
else
message = "#{_procName[_excuteProcess]}の処理中です。"
if message
new app.Notification("現在この機能は使用できません", message, "", "invalid")
return false
_clearExcute = ->
_excuteProcess = null
_excuteFunction = null
return
app.boot("/view/config.html", ["Cache", "BBSMenu"], (Cache, BBSMenu) ->
$view = document.documentElement
new app.view.IframeView($view)
# タブ
$tabbar = $view.C("tabbar")[0]
$tabs = $view.C("container")[0]
$tabbar.on("click", ({target}) ->
if target.tagName isnt "LI"
target = target.closest("li")
return unless target?
return if target.hasClass("selected")
$tabbar.C("selected")[0].removeClass("selected")
target.addClass("selected")
$tabs.C("selected")[0].removeClass("selected")
$tabs.$("[name=\"#{target.dataset.name}\"]").addClass("selected")
return
)
whenClose = ->
#NG設定
dom = $view.$("textarea[name=\"ngwords\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.NG.set(dom.value)
#ImageReplaceDat設定
dom = $view.$("textarea[name=\"image_replace_dat\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.ImageReplaceDat.set(dom.value)
#ReplaceStrTxt設定
dom = $view.$("textarea[name=\"replace_str_txt\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.ReplaceStrTxt.set(dom.value)
#bbsmenu設定
changeFlag = false
dom = $view.$("textarea[name=\"bbsmenu\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.config.set("bbsmenu", dom.value)
changeFlag = true
dom = $view.$("textarea[name=\"bbsmenu_option\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.config.set("bbsmenu_option", dom.value)
changeFlag = true
if changeFlag
$view.C("bbsmenu_reload")[0].click()
return
#閉じるボタン
$view.C("button_close")[0].on("click", ->
if frameElement
parent.postMessage(type: "request_killme", location.origin)
whenClose()
return
)
window.on("beforeunload", ->
whenClose()
return
)
#掲示板を開いたときに閉じる
for dom in $view.C("open_in_rcrx")
dom.on("click", ->
$view.C("button_close")[0].click()
return
)
#汎用設定項目
for dom in $view.$$("input.direct[type=\"text\"], textarea.direct")
dom.value = app.config.get(dom.name) or ""
dom.on("input", ->
app.config.set(@name, @value)
@setAttr("changed", "true")
return
)
for dom in $view.$$("input.direct[type=\"number\"]")
dom.value = app.config.get(dom.name) or "0"
dom.on("input", ->
app.config.set(@name, if Number.isNaN(@valueAsNumber) then "0" else @value)
return
)
for dom in $view.$$("input.direct[type=\"checkbox\"]")
dom.checked = app.config.get(dom.name) is "on"
dom.on("change", ->
app.config.set(@name, if @checked then "on" else "off")
return
)
for dom in $view.$$("input.direct[type=\"radio\"]")
if dom.value is app.config.get(dom.name)
dom.checked = true
dom.on("change", ->
val = $view.$("""input[name="#{@name}"]:checked""").value
app.config.set(@name, val)
return
)
for dom in $view.$$("input.direct[type=\"range\"]")
dom.value = app.config.get(dom.name) or "0"
$$.I("#{dom.name}_text").textContent = dom.value
dom.on("input", ->
$$.I("#{@name}_text").textContent = @value
app.config.set(@name, @value)
return
)
for dom in $view.$$("select.direct")
dom.value = app.config.get(dom.name) or ""
dom.on("change", ->
app.config.set(@name, @value)
return
)
#バージョン情報表示
do ->
{name, version} = await app.manifest
$view.C("version_text")[0].textContent = "#{name} v#{version} + #{navigator.userAgent}"
return
$view.C("version_copy")[0].on("click", ->
app.clipboardWrite($$.C("version_text")[0].textContent)
return
)
$view.C("keyboard_help")[0].on("click", (e) ->
e.preventDefault()
app.message.send("showKeyboardHelp")
return
)
#板覧更新ボタン
$view.C("bbsmenu_reload")[0].on("click", ({currentTarget: $button}) ->
$status = $$.I("bbsmenu_reload_status")
$button.disabled = true
$status.setClass("loading")
$status.textContent = "更新中"
dom = $view.$("textarea[name=\"bbsmenu\"]")
dom.removeAttr("changed")
app.config.set("bbsmenu", dom.value)
dom = $view.$("textarea[name=\"bbsmenu_option\"]")
dom.removeAttr("changed")
app.config.set("bbsmenu_option", dom.value)
try
await BBSMenu.get(true)
$status.setClass("done")
$status.textContent = "更新完了"
catch
$status.setClass("fail")
$status.textContent = "更新失敗"
$button.disabled = false
return
)
#履歴
new HistoryIO(
name: "history"
countFunc: ->
return app.History.count()
importFunc: ({history, read_state: readState, historyVersion = 1, readstateVersion = 1}, $progress) ->
total = history.length + readState.length
count = 0
for hs in history
hs.boardTitle = "" if historyVersion is 1
await app.History.add(hs.url, hs.title, hs.date, hs.boardTitle)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
for rs in readState
rs.date = null if readstateVersion is 1
_rs = await app.ReadState.get(rs.url)
if app.util.isNewerReadState(_rs, rs)
await app.ReadState.set(rs)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
return
exportFunc: ->
[readState, history] = await Promise.all([
app.ReadState.getAll()
app.History.getAll()
])
return {"read_state": readState, "history": history, "historyVersion": app.History.DB_VERSION, "readstateVersion": app.ReadState.DB_VERSION}
clearFunc: ->
return Promise.all([app.History.clear(), app.ReadState.clear()])
clearRangeFunc: (day) ->
return app.History.clearRange(day)
afterChangedFunc: ->
updateIndexedDBUsage()
return
)
new HistoryIO(
name: "writehistory"
countFunc: ->
return app.WriteHistory.count()
importFunc: ({writehistory = null, dbVersion = 1}, $progress) ->
return Promise.resolve() unless writehistory
total = writehistory.length
count = 0
unixTime201710 = 1506783600 # 2017/10/01 0:00:00
for whis in writehistory
whis.inputName = whis.input_name
whis.inputMail = whis.input_mail
if dbVersion < 2
if +whis.date <= unixTime201710 and whis.res > 1
date = new Date(+whis.date)
date.setMonth(date.getMonth()-1)
whis.date = date.valueOf()
await app.WriteHistory.add(whis)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
return
exportFunc: ->
return {"writehistory": await app.WriteHistory.getAll(), "dbVersion": app.WriteHistory.DB_VERSION}
clearFunc: ->
return app.WriteHistory.clear()
clearRangeFunc: (day) ->
return app.WriteHistory.clearRange(day)
afterChangedFunc: ->
updateIndexedDBUsage()
return
)
# ブックマーク
new BookmarkIO(
name: "bookmark"
countFunc: ->
return app.bookmark.getAll().length
importFunc: ({bookmark, readState, readstateVersion = 1}, $progress) ->
total = bookmark.length + readState.length
count = 0
for bm in bookmark
await app.bookmark.import(bm)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
for rs in readState
rs.date = null if readstateVersion is 1
_rs = await app.ReadState.get(rs.url)
if app.util.isNewerReadState(_rs, rs)
await app.ReadState.set(rs)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
return
exportFunc: ->
[bookmark, readState] = await Promise.all([
app.bookmark.getAll()
app.ReadState.getAll()
])
return {"bookmark": bookmark, "readState": readState, "readstateVersion": app.ReadState.DB_VERSION}
clearFunc: ->
return app.bookmark.removeAll()
clearExpiredFunc: ->
return app.bookmark.removeAllExpired()
afterChangedFunc: ->
updateIndexedDBUsage()
return
)
do ->
#キャッシュ削除ボタン
$clearButton = $view.C("cache_clear")[0]
$status = $$.I("cache_status")
$count = $$.I("cache_count")
do setCount = ->
count = await Cache.count()
$count.textContent = "#{count}件"
return
$clearButton.on("click", ->
return unless _checkExcute("cache", "clear")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
$status.textContent = ":削除中"
try
await Cache.delete()
$status.textContent = ":削除完了"
catch
$status.textContent = ":削除失敗"
setCount()
updateIndexedDBUsage()
_clearExcute()
return
)
#キャッシュ範囲削除ボタン
$clearRangeButton = $view.C("cache_range_clear")[0]
$clearRangeButton.on("click", ->
return unless _checkExcute("cache", "clear_range")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
$status.textContent = ":範囲指定削除中"
try
await Cache.clearRange(parseInt($view.C("cache_date_range")[0].value))
$status.textContent = ":削除完了"
catch
$status.textContent = ":削除失敗"
setCount()
updateIndexedDBUsage()
_clearExcute()
return
)
return
do ->
#ブックマークフォルダ変更ボタン
$view.C("bookmark_source_change")[0].on("click", ->
app.message.send("open", url: "bookmark_source_selector")
return
)
#ブックマークフォルダ表示
do updateName = ->
[folder] = await parent.browser.bookmarks.get(app.config.get("bookmark_id"))
$$.I("bookmark_source_name").textContent = folder.title
return
app.message.on("config_updated", ({key}) ->
updateName() if key is "bookmark_id"
return
)
return
#「テーマなし」設定
if app.config.get("theme_id") is "none"
$view.C("theme_none")[0].checked = true
app.message.on("config_updated", ({key, val}) ->
if key is "theme_id"
$view.C("theme_none")[0].checked = (val is "none")
return
)
$view.C("theme_none")[0].on("click", ->
app.config.set("theme_id", if @checked then "none" else "default")
return
)
#bbsmenu設定
resetBBSMenu = ->
await app.config.del("bbsmenu")
$view.$("textarea[name=\"bbsmenu\"]").value = app.config.get("bbsmenu")
$$.C("bbsmenu_reload")[0].click()
return
if $view.$("textarea[name=\"bbsmenu\"]").value is ""
resetBBSMenu()
$view.C("bbsmenu_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
resetBBSMenu()
return
)
for $dom in $view.$$("input[type=\"radio\"]") when $dom.name in ["ng_id_expire", "ng_slip_expire"]
$dom.on("change", ->
$$.I(@name).dataset.value = @value if @checked
return
)
$dom.emit(new Event("change"))
# ImageReplaceDatのリセット
$view.C("dat_file_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
await app.config.del("image_replace_dat")
resetData = app.config.get("image_replace_dat")
$view.$("textarea[name=\"image_replace_dat\"]").value = resetData
app.ImageReplaceDat.set(resetData)
return
)
# ぼかし判定用正規表現のリセット
$view.C("image_blur_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
await app.config.del("image_blur_word")
resetData = app.config.get("image_blur_word")
$view.$("input[name=\"image_blur_word\"]").value = resetData
return
)
# NG設定のリセット
$view.C("ngwords_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
await app.config.del("ngwords")
resetData = app.config.get("ngwords")
$view.$("textarea[name=\"ngwords\"]").value = resetData
app.NG.set(resetData)
return
)
# 設定をインポート/エクスポート
new SettingIO(
name: "config"
importFunc: (file) ->
json = JSON.parse(file)
for key, value of json
key = key.slice(7)
if key isnt "theme_id"
$key = $view.$("input[name=\"#{key}\"]")
if $key?
switch $key.getAttr("type")
when "text", "range", "number"
$key.value = value
$key.emit(new Event("input"))
when "checkbox"
$key.checked = (value is "on")
$key.emit(new Event("change"))
when "radio"
for dom in $view.$$("input.direct[name=\"#{key}\"]")
if dom.value is value
dom.checked = true
$key.emit(new Event("change"))
else
$keyTextArea = $view.$("textarea[name=\"#{key}\"]")
if $keyTextArea?
$keyTextArea.value = value
$keyTextArea.emit(new Event("input"))
$keySelect = $view.$("select[name=\"#{key}\"]")
if $keySelect?
$keySelect.value = value
$keySelect.emit(new Event("change"))
#config_theme_idは「テーマなし」の場合があるので特例化
else
if value is "none"
$themeNone = $view.C("theme_none")[0]
$themeNone.click() unless $themeNone.checked
else
$view.$("input[name=\"theme_id\"]").value = value
$view.$("input[name=\"theme_id\"]").emit(new Event("change"))
return
exportFunc: ->
content = app.config.getAll()
delete content.config_last_board_sort_config
delete content.config_last_version
return JSON.stringify(content)
)
# ImageReplaceDatをインポート
new SettingIO(
name: "dat"
importFunc: (file) ->
datDom = $view.$("textarea[name=\"image_replace_dat\"]")
datDom.value = file
datDom.emit(new Event("input"))
return
)
# ReplaceStrTxtをインポート
new SettingIO(
name: "replacestr"
importFunc: (file) ->
replacestrDom = $view.$("textarea[name=\"replace_str_txt\"]")
replacestrDom.value = file
replacestrDom.emit(new Event("input"))
return
)
formatBytes = (bytes) ->
if bytes < 1048576
return (bytes/1024).toFixed(2) + "KB"
if bytes < 1073741824
return (bytes/1048576).toFixed(2) + "MB"
return (bytes/1073741824).toFixed(2) + "GB"
# indexeddbの使用状況
do updateIndexedDBUsage = ->
{quota, usage} = await navigator.storage.estimate()
$view.C("indexeddb_max")[0].textContent = formatBytes(quota)
$view.C("indexeddb_using")[0].textContent = formatBytes(usage)
$meter = $view.C("indexeddb_meter")[0]
$meter.max = quota
$meter.high = quota*0.9
$meter.low = quota*0.8
$meter.value = usage
return
# localstorageの使用状況
do ->
if parent.browser.storage.local.getBytesInUse?
# 無制限なのでindexeddbの最大と一致する
{quota} = await navigator.storage.estimate()
$view.C("localstorage_max")[0].textContent = formatBytes(quota)
$meter = $view.C("localstorage_meter")[0]
$meter.max = quota
$meter.high = quota*0.9
$meter.low = quota*0.8
usage = await parent.browser.storage.local.getBytesInUse()
$view.C("localstorage_using")[0].textContent = formatBytes(usage)
$meter.value = usage
else
$meter = $view.C("localstorage_meter")[0].remove()
$view.C("localstorage_max")[0].textContent = ""
$view.C("localstorage_using")[0].textContent = "このブラウザでは取得できません"
return
)
| true | class SettingIO
importFile: ""
constructor: ({
name:PI:NAME:<NAME>END_PI @name
importFunc: @importFunc
exportFunc: @exportFunc
}) ->
@$status = $$.I("#{@name}_status")
if @importFunc?
@$fileSelectButton = $$.C("#{@name}_file_show")[0]
@$fileSelectButtonHidden = $$.C("#{@name}_file_hide")[0]
@$importButton = $$.C("#{@name}_import_button")[0]
@setupFileSelectButton()
@setupImportButton()
if @exportFunc?
@$exportButton = $$.C("#{@name}_export_button")[0]
@setupExportButton()
return
setupFileSelectButton: ->
@$fileSelectButton.on("click", =>
return unless _checkExcute(@name, "file_select")
@$status.setClass("")
@$fileSelectButtonHidden.click()
_clearExcute()
return
)
@$fileSelectButtonHidden.on("change", (e) =>
file = e.target.files
reader = new FileReader()
reader.readAsText(file[0])
reader.onload = =>
@importFile = reader.result
@$status.addClass("select")
@$status.textContent = "ファイル選択完了"
return
return
)
return
setupImportButton: ->
@$importButton.on("click", =>
return unless _checkExcute(@name, "import")
if @importFile isnt ""
@$status.setClass("loading")
@$status.textContent = "更新中"
try
await @importFunc(@importFile)
@$status.addClass("done")
@$status.textContent = "インポート完了"
catch
@$status.addClass("fail")
@$status.textContent = "インポート失敗"
else
@$status.addClass("fail")
@$status.textContent = "ファイルを選択してください"
_clearExcute()
return
)
return
setupExportButton: ->
@$exportButton.on("click", =>
return unless _checkExcute(@name, "export")
blob = new Blob([@exportFunc()], type: "text/plain")
$a = $__("a").addClass("hidden")
url = URL.createObjectURL(blob)
$a.href = url
$a.download = "read.crx-2_#{@name}.json"
@$exportButton.addAfter($a)
$a.click()
$a.remove()
URL.revokeObjectURL(url)
_clearExcute()
return
)
return
class HistoryIO extends SettingIO
constructor: ({
name
countFunc: @countFunc
importFunc
exportFunc
clearFunc: @clearFunc
clearRangeFunc: @clearRangeFunc
afterChangedFunc: @afterChangedFunc
}) ->
super({
name
importFunc
exportFunc
})
@name = name
@importFunc = importFunc
@exportFunc = exportFunc
@$count = $$.I("#{@name}_count")
@$progress = $$.I("#{@name}_progress")
@$clearButton = $$.C("#{@name}_clear")[0]
@$clearRangeButton = $$.C("#{@name}_range_clear")[0]
@showCount()
@setupClearButton()
@setupClearRangeButton()
return
showCount: ->
count = await @countFunc()
@$count.textContent = "#{count}件"
return
setupClearButton: ->
@$clearButton.on("click", =>
return unless _checkExcute(@name, "clear")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":削除中"
try
await @clearFunc()
@$status.textContent = ":削除完了"
parent.$$.$("iframe[src=\"/view/#{@name}.html\"]")?.contentDocument.C("view")[0].emit(new Event("request_reload"))
catch
@$status.textContent = ":削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupClearRangeButton: ->
@$clearRangeButton.on("click", =>
return unless _checkExcute(@name, "clear_range")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":範囲指定削除中"
try
await @clearRangeFunc(parseInt($$.C("#{@name}_date_range")[0].value))
@$status.textContent = ":範囲指定削除完了"
parent.$$.$("iframe[src=\"/view/#{@name}.html\"]")?.contentDocument.C("view")[0].emit(new Event("request_reload"))
catch
@$status.textContent = ":範囲指定削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupImportButton: ->
@$importButton.on("click", =>
return unless _checkExcute(@name, "import")
if @importFile isnt ""
@$status.setClass("loading")
@$status.textContent = ":更新中"
try
await @importFunc(JSON.parse(@importFile), @$progress)
count = await @countFunc()
@$status.setClass("done")
@$status.textContent = ":インポート完了"
catch
@$status.setClass("fail")
@$status.textContent = ":インポート失敗"
@showCount()
@afterChangedFunc()
else
@$status.addClass("fail")
@$status.textContent = ":ファイルを選択してください"
@$progress.textContent = ""
_clearExcute()
return
)
return
setupExportButton: ->
@$exportButton.on("click", =>
return unless _checkExcute(@name, "export")
data = await @exportFunc()
exportText = JSON.stringify(data)
blob = new Blob([exportText], type: "text/plain")
$a = $__("a").addClass("hidden")
url = URL.createObjectURL(blob)
$a.href = url
$a.download = "read.crx-2_#{@name}.json"
@$exportButton.addAfter($a)
$a.click()
$a.remove()
URL.revokeObjectURL(url)
_clearExcute()
return
)
return
class BookmarkIO extends SettingIO
constructor: ({
name
countFunc: @countFunc
importFunc
exportFunc
clearFunc: @clearFunc
clearExpiredFunc: @clearExpiredFunc
afterChangedFunc: @afterChangedFunc
}) ->
super({
name
importFunc
exportFunc
})
@name = name
@importFunc = importFunc
@exportFunc = exportFunc
@$count = $$.I("#{@name}_count")
@$progress = $$.I("#{@name}_progress")
@$clearButton = $$.C("#{@name}_clear")[0]
@$clearExpiredButton = $$.C("#{@name}_expired_clear")[0]
@showCount()
@setupClearButton()
@setupClearExpiredButton()
return
showCount: ->
count = await @countFunc()
@$count.textContent = "#{count}件"
return
setupClearButton: ->
@$clearButton.on("click", =>
return unless _checkExcute(@name, "clear")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":削除中"
try
await @clearFunc()
@$status.textContent = ":削除完了"
catch
@$status.textContent = ":削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupClearExpiredButton: ->
@$clearExpiredButton.on("click", =>
return unless _checkExcute(@name, "clear_expired")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
@$status.textContent = ":dat落ち削除中"
try
await @clearExpiredFunc()
@$status.textContent = ":dat落ち削除完了"
catch
@$status.textContent = ":dat落ち削除失敗"
@showCount()
@afterChangedFunc()
_clearExcute()
return
)
return
setupImportButton: ->
@$importButton.on("click", =>
return unless _checkExcute(@name, "import")
if @importFile isnt ""
@$status.setClass("loading")
@$status.textContent = ":更新中"
try
await @importFunc(JSON.parse(@importFile), @$progress)
count = await @countFunc()
@$status.setClass("done")
@$status.textContent = ":インポート完了"
catch
@$status.setClass("fail")
@$status.textContent = ":インポート失敗"
@showCount()
@afterChangedFunc()
else
@$status.addClass("fail")
@$status.textContent = ":ファイルを選択してください"
@$progress.textContent = ""
_clearExcute()
return
)
return
setupExportButton: ->
@$exportButton.on("click", =>
return unless _checkExcute(@name, "export")
data = await @exportFunc()
exportText = JSON.stringify(data)
blob = new Blob([exportText], type: "text/plain")
$a = $__("a").addClass("hidden")
url = URL.createObjectURL(blob)
$a.href = url
$a.download = "read.crx-2_#{@name}.json"
@$exportButton.addAfter($a)
$a.click()
$a.remove()
URL.revokeObjectURL(url)
_clearExcute()
return
)
return
# 処理の排他制御用
_excuteProcess = null
_excuteFunction = null
_procName = {
"history": "閲覧履歴"
"writehistory": "書込履歴"
"bookmark": "ブックマーク"
"cache": "キャッシュ"
"config": "設定"
}
_funcName = {
"import": "インポート"
"export": "エクスポート"
"clear": "削除"
"clear_range": "範囲指定削除"
"clear_expired":"dat落ち削除"
"file_select": "ファイル読み込み"
}
_checkExcute = (procId, funcId) ->
unless _excuteProcess
_excuteProcess = procId
_excuteFunction = funcId
return true
message = null
if _excuteProcess is procId
if _excuteFunction is funcId
message = "既に実行中です。"
else
message = "#{_funcName[_excuteFunction]}の実行中です。"
else
message = "#{_procName[_excuteProcess]}の処理中です。"
if message
new app.Notification("現在この機能は使用できません", message, "", "invalid")
return false
_clearExcute = ->
_excuteProcess = null
_excuteFunction = null
return
app.boot("/view/config.html", ["Cache", "BBSMenu"], (Cache, BBSMenu) ->
$view = document.documentElement
new app.view.IframeView($view)
# タブ
$tabbar = $view.C("tabbar")[0]
$tabs = $view.C("container")[0]
$tabbar.on("click", ({target}) ->
if target.tagName isnt "LI"
target = target.closest("li")
return unless target?
return if target.hasClass("selected")
$tabbar.C("selected")[0].removeClass("selected")
target.addClass("selected")
$tabs.C("selected")[0].removeClass("selected")
$tabs.$("[name=\"#{target.dataset.name}\"]").addClass("selected")
return
)
whenClose = ->
#NG設定
dom = $view.$("textarea[name=\"ngwords\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.NG.set(dom.value)
#ImageReplaceDat設定
dom = $view.$("textarea[name=\"image_replace_dat\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.ImageReplaceDat.set(dom.value)
#ReplaceStrTxt設定
dom = $view.$("textarea[name=\"replace_str_txt\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.ReplaceStrTxt.set(dom.value)
#bbsmenu設定
changeFlag = false
dom = $view.$("textarea[name=\"bbsmenu\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.config.set("bbsmenu", dom.value)
changeFlag = true
dom = $view.$("textarea[name=\"bbsmenu_option\"]")
if dom.getAttr("changed")?
dom.removeAttr("changed")
app.config.set("bbsmenu_option", dom.value)
changeFlag = true
if changeFlag
$view.C("bbsmenu_reload")[0].click()
return
#閉じるボタン
$view.C("button_close")[0].on("click", ->
if frameElement
parent.postMessage(type: "request_killme", location.origin)
whenClose()
return
)
window.on("beforeunload", ->
whenClose()
return
)
#掲示板を開いたときに閉じる
for dom in $view.C("open_in_rcrx")
dom.on("click", ->
$view.C("button_close")[0].click()
return
)
#汎用設定項目
for dom in $view.$$("input.direct[type=\"text\"], textarea.direct")
dom.value = app.config.get(dom.name) or ""
dom.on("input", ->
app.config.set(@name, @value)
@setAttr("changed", "true")
return
)
for dom in $view.$$("input.direct[type=\"number\"]")
dom.value = app.config.get(dom.name) or "0"
dom.on("input", ->
app.config.set(@name, if Number.isNaN(@valueAsNumber) then "0" else @value)
return
)
for dom in $view.$$("input.direct[type=\"checkbox\"]")
dom.checked = app.config.get(dom.name) is "on"
dom.on("change", ->
app.config.set(@name, if @checked then "on" else "off")
return
)
for dom in $view.$$("input.direct[type=\"radio\"]")
if dom.value is app.config.get(dom.name)
dom.checked = true
dom.on("change", ->
val = $view.$("""input[name="#{@name}"]:checked""").value
app.config.set(@name, val)
return
)
for dom in $view.$$("input.direct[type=\"range\"]")
dom.value = app.config.get(dom.name) or "0"
$$.I("#{dom.name}_text").textContent = dom.value
dom.on("input", ->
$$.I("#{@name}_text").textContent = @value
app.config.set(@name, @value)
return
)
for dom in $view.$$("select.direct")
dom.value = app.config.get(dom.name) or ""
dom.on("change", ->
app.config.set(@name, @value)
return
)
#バージョン情報表示
do ->
{name, version} = await app.manifest
$view.C("version_text")[0].textContent = "#{name} v#{version} + #{navigator.userAgent}"
return
$view.C("version_copy")[0].on("click", ->
app.clipboardWrite($$.C("version_text")[0].textContent)
return
)
$view.C("keyboard_help")[0].on("click", (e) ->
e.preventDefault()
app.message.send("showKeyboardHelp")
return
)
#板覧更新ボタン
$view.C("bbsmenu_reload")[0].on("click", ({currentTarget: $button}) ->
$status = $$.I("bbsmenu_reload_status")
$button.disabled = true
$status.setClass("loading")
$status.textContent = "更新中"
dom = $view.$("textarea[name=\"bbsmenu\"]")
dom.removeAttr("changed")
app.config.set("bbsmenu", dom.value)
dom = $view.$("textarea[name=\"bbsmenu_option\"]")
dom.removeAttr("changed")
app.config.set("bbsmenu_option", dom.value)
try
await BBSMenu.get(true)
$status.setClass("done")
$status.textContent = "更新完了"
catch
$status.setClass("fail")
$status.textContent = "更新失敗"
$button.disabled = false
return
)
#履歴
new HistoryIO(
name: "history"
countFunc: ->
return app.History.count()
importFunc: ({history, read_state: readState, historyVersion = 1, readstateVersion = 1}, $progress) ->
total = history.length + readState.length
count = 0
for hs in history
hs.boardTitle = "" if historyVersion is 1
await app.History.add(hs.url, hs.title, hs.date, hs.boardTitle)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
for rs in readState
rs.date = null if readstateVersion is 1
_rs = await app.ReadState.get(rs.url)
if app.util.isNewerReadState(_rs, rs)
await app.ReadState.set(rs)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
return
exportFunc: ->
[readState, history] = await Promise.all([
app.ReadState.getAll()
app.History.getAll()
])
return {"read_state": readState, "history": history, "historyVersion": app.History.DB_VERSION, "readstateVersion": app.ReadState.DB_VERSION}
clearFunc: ->
return Promise.all([app.History.clear(), app.ReadState.clear()])
clearRangeFunc: (day) ->
return app.History.clearRange(day)
afterChangedFunc: ->
updateIndexedDBUsage()
return
)
new HistoryIO(
name: "writehistory"
countFunc: ->
return app.WriteHistory.count()
importFunc: ({writehistory = null, dbVersion = 1}, $progress) ->
return Promise.resolve() unless writehistory
total = writehistory.length
count = 0
unixTime201710 = 1506783600 # 2017/10/01 0:00:00
for whis in writehistory
whis.inputName = whis.input_name
whis.inputMail = whis.input_mail
if dbVersion < 2
if +whis.date <= unixTime201710 and whis.res > 1
date = new Date(+whis.date)
date.setMonth(date.getMonth()-1)
whis.date = date.valueOf()
await app.WriteHistory.add(whis)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
return
exportFunc: ->
return {"writehistory": await app.WriteHistory.getAll(), "dbVersion": app.WriteHistory.DB_VERSION}
clearFunc: ->
return app.WriteHistory.clear()
clearRangeFunc: (day) ->
return app.WriteHistory.clearRange(day)
afterChangedFunc: ->
updateIndexedDBUsage()
return
)
# ブックマーク
new BookmarkIO(
name: "bookmark"
countFunc: ->
return app.bookmark.getAll().length
importFunc: ({bookmark, readState, readstateVersion = 1}, $progress) ->
total = bookmark.length + readState.length
count = 0
for bm in bookmark
await app.bookmark.import(bm)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
for rs in readState
rs.date = null if readstateVersion is 1
_rs = await app.ReadState.get(rs.url)
if app.util.isNewerReadState(_rs, rs)
await app.ReadState.set(rs)
$progress.textContent = ":#{Math.floor((count++ / total) * 100)}%"
return
exportFunc: ->
[bookmark, readState] = await Promise.all([
app.bookmark.getAll()
app.ReadState.getAll()
])
return {"bookmark": bookmark, "readState": readState, "readstateVersion": app.ReadState.DB_VERSION}
clearFunc: ->
return app.bookmark.removeAll()
clearExpiredFunc: ->
return app.bookmark.removeAllExpired()
afterChangedFunc: ->
updateIndexedDBUsage()
return
)
do ->
#キャッシュ削除ボタン
$clearButton = $view.C("cache_clear")[0]
$status = $$.I("cache_status")
$count = $$.I("cache_count")
do setCount = ->
count = await Cache.count()
$count.textContent = "#{count}件"
return
$clearButton.on("click", ->
return unless _checkExcute("cache", "clear")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
$status.textContent = ":削除中"
try
await Cache.delete()
$status.textContent = ":削除完了"
catch
$status.textContent = ":削除失敗"
setCount()
updateIndexedDBUsage()
_clearExcute()
return
)
#キャッシュ範囲削除ボタン
$clearRangeButton = $view.C("cache_range_clear")[0]
$clearRangeButton.on("click", ->
return unless _checkExcute("cache", "clear_range")
result = await UI.Dialog("confirm",
message: "本当に削除しますか?"
)
unless result
_clearExcute()
return
$status.textContent = ":範囲指定削除中"
try
await Cache.clearRange(parseInt($view.C("cache_date_range")[0].value))
$status.textContent = ":削除完了"
catch
$status.textContent = ":削除失敗"
setCount()
updateIndexedDBUsage()
_clearExcute()
return
)
return
do ->
#ブックマークフォルダ変更ボタン
$view.C("bookmark_source_change")[0].on("click", ->
app.message.send("open", url: "bookmark_source_selector")
return
)
#ブックマークフォルダ表示
do updateName = ->
[folder] = await parent.browser.bookmarks.get(app.config.get("bookmark_id"))
$$.I("bookmark_source_name").textContent = folder.title
return
app.message.on("config_updated", ({key}) ->
updateName() if key is "bookmark_id"
return
)
return
#「テーマなし」設定
if app.config.get("theme_id") is "none"
$view.C("theme_none")[0].checked = true
app.message.on("config_updated", ({key, val}) ->
if key is "theme_id"
$view.C("theme_none")[0].checked = (val is "none")
return
)
$view.C("theme_none")[0].on("click", ->
app.config.set("theme_id", if @checked then "none" else "default")
return
)
#bbsmenu設定
resetBBSMenu = ->
await app.config.del("bbsmenu")
$view.$("textarea[name=\"bbsmenu\"]").value = app.config.get("bbsmenu")
$$.C("bbsmenu_reload")[0].click()
return
if $view.$("textarea[name=\"bbsmenu\"]").value is ""
resetBBSMenu()
$view.C("bbsmenu_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
resetBBSMenu()
return
)
for $dom in $view.$$("input[type=\"radio\"]") when $dom.name in ["ng_id_expire", "ng_slip_expire"]
$dom.on("change", ->
$$.I(@name).dataset.value = @value if @checked
return
)
$dom.emit(new Event("change"))
# ImageReplaceDatのリセット
$view.C("dat_file_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
await app.config.del("image_replace_dat")
resetData = app.config.get("image_replace_dat")
$view.$("textarea[name=\"image_replace_dat\"]").value = resetData
app.ImageReplaceDat.set(resetData)
return
)
# ぼかし判定用正規表現のリセット
$view.C("image_blur_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
await app.config.del("image_blur_word")
resetData = app.config.get("image_blur_word")
$view.$("input[name=\"image_blur_word\"]").value = resetData
return
)
# NG設定のリセット
$view.C("ngwords_reset")[0].on("click", ->
result = await UI.Dialog("confirm",
message: "設定内容をリセットします。よろしいですか?"
)
return unless result
await app.config.del("ngwords")
resetData = app.config.get("ngwords")
$view.$("textarea[name=\"ngwords\"]").value = resetData
app.NG.set(resetData)
return
)
# 設定をインポート/エクスポート
new SettingIO(
name: "config"
importFunc: (file) ->
json = JSON.parse(file)
for key, value of json
key = key.slice(7)
if key isnt "theme_id"
$key = $view.$("input[name=\"#{key}\"]")
if $key?
switch $key.getAttr("type")
when "text", "range", "number"
$key.value = value
$key.emit(new Event("input"))
when "checkbox"
$key.checked = (value is "on")
$key.emit(new Event("change"))
when "radio"
for dom in $view.$$("input.direct[name=\"#{key}\"]")
if dom.value is value
dom.checked = true
$key.emit(new Event("change"))
else
$keyTextArea = $view.$("textarea[name=\"#{key}\"]")
if $keyTextArea?
$keyTextArea.value = value
$keyTextArea.emit(new Event("input"))
$keySelect = $view.$("select[name=\"#{key}\"]")
if $keySelect?
$keySelect.value = value
$keySelect.emit(new Event("change"))
#config_theme_idは「テーマなし」の場合があるので特例化
else
if value is "none"
$themeNone = $view.C("theme_none")[0]
$themeNone.click() unless $themeNone.checked
else
$view.$("input[name=\"theme_id\"]").value = value
$view.$("input[name=\"theme_id\"]").emit(new Event("change"))
return
exportFunc: ->
content = app.config.getAll()
delete content.config_last_board_sort_config
delete content.config_last_version
return JSON.stringify(content)
)
# ImageReplaceDatをインポート
new SettingIO(
name: "dat"
importFunc: (file) ->
datDom = $view.$("textarea[name=\"image_replace_dat\"]")
datDom.value = file
datDom.emit(new Event("input"))
return
)
# ReplaceStrTxtをインポート
new SettingIO(
name: "replacestr"
importFunc: (file) ->
replacestrDom = $view.$("textarea[name=\"replace_str_txt\"]")
replacestrDom.value = file
replacestrDom.emit(new Event("input"))
return
)
formatBytes = (bytes) ->
if bytes < 1048576
return (bytes/1024).toFixed(2) + "KB"
if bytes < 1073741824
return (bytes/1048576).toFixed(2) + "MB"
return (bytes/1073741824).toFixed(2) + "GB"
# indexeddbの使用状況
do updateIndexedDBUsage = ->
{quota, usage} = await navigator.storage.estimate()
$view.C("indexeddb_max")[0].textContent = formatBytes(quota)
$view.C("indexeddb_using")[0].textContent = formatBytes(usage)
$meter = $view.C("indexeddb_meter")[0]
$meter.max = quota
$meter.high = quota*0.9
$meter.low = quota*0.8
$meter.value = usage
return
# localstorageの使用状況
do ->
if parent.browser.storage.local.getBytesInUse?
# 無制限なのでindexeddbの最大と一致する
{quota} = await navigator.storage.estimate()
$view.C("localstorage_max")[0].textContent = formatBytes(quota)
$meter = $view.C("localstorage_meter")[0]
$meter.max = quota
$meter.high = quota*0.9
$meter.low = quota*0.8
usage = await parent.browser.storage.local.getBytesInUse()
$view.C("localstorage_using")[0].textContent = formatBytes(usage)
$meter.value = usage
else
$meter = $view.C("localstorage_meter")[0].remove()
$view.C("localstorage_max")[0].textContent = ""
$view.C("localstorage_using")[0].textContent = "このブラウザでは取得できません"
return
)
|
[
{
"context": " Limit to one expression per line in JSX\n# @author Mark Ivan Allen <Vydia.com>\n###\n\n'use strict'\n\n# ----------------",
"end": 86,
"score": 0.9998456835746765,
"start": 71,
"tag": "NAME",
"value": "Mark Ivan Allen"
}
] | src/tests/rules/jsx-one-expression-per-line.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Limit to one expression per line in JSX
# @author Mark Ivan Allen <Vydia.com>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/jsx-one-expression-per-line'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-one-expression-per-line', rule,
valid: [
code: '<App />'
,
code: '<App></App>'
,
code: '<App foo="bar" />'
,
code: ['<App>', ' <Foo />', '</App>'].join '\n'
,
code: ['<App>', ' <Foo />', ' <Bar />', '</App>'].join '\n'
,
code: ['<App>', ' <Foo></Foo>', '</App>'].join '\n'
,
code: ['<App>', ' foo bar baz whatever ', '</App>'].join '\n'
,
code: ['<App>', ' <Foo>', ' </Foo>', '</App>'].join '\n'
,
code: ['<App', ' foo="bar"', '>', '<Foo />', '</App>'].join '\n'
,
# ,
# code: ['<', 'App', '>', ' <', ' Foo', ' />', '</', 'App', '>'].join(
# '\n'
# )
code: '<App>foo</App>'
options: [allow: 'literal']
,
code: '<App>123</App>'
options: [allow: 'literal']
,
code: '<App>foo</App>'
options: [allow: 'single-child']
,
code: '<App>{"foo"}</App>'
options: [allow: 'single-child']
,
code: '<App>{foo && <Bar />}</App>'
options: [allow: 'single-child']
,
code: '<App><Foo /></App>'
options: [allow: 'single-child']
,
code: '<></>'
,
# parser: 'babel-eslint'
code: ['<>', ' <Foo />', '</>'].join '\n'
,
# parser: 'babel-eslint'
code: ['<>', ' <Foo />', ' <Bar />', '</>'].join '\n'
# parser: 'babel-eslint'
]
invalid: [
code: '<App>{"foo"}</App>'
# output: ['<App>', '{"foo"}', '</App>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: '<App>foo</App>'
# output: ['<App>', 'foo', '</App>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: ['<div>', ' foo {"bar"}', '</div>'].join '\n'
# output: ['<div>', ' foo ', "{' '}", '{"bar"}', '</div>'].join '\n'
errors: [message: '`{"bar"}` must be placed on a new line']
,
code: ['<div>', ' {"foo"} bar', '</div>'].join '\n'
# output: ['<div>', ' {"foo"}', "{' '}", 'bar', '</div>'].join '\n'
errors: [message: '` bar` must be placed on a new line']
,
code: ['<App>', ' <Foo /><Bar />', '</App>'].join '\n'
# output: ['<App>', ' <Foo />', '<Bar />', '</App>'].join '\n'
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<div>', ' <span />foo', '</div>'].join '\n'
# output: ['<div>', ' <span />', 'foo', '</div>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: ['<div>', ' <span />{"foo"}', '</div>'].join '\n'
# output: ['<div>', ' <span />', '{"foo"}', '</div>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: ['<div>', ' {"foo"} { I18n.t(\'baz\') }', '</div>'].join '\n'
# output: [
# '<div>'
# ' {"foo"} '
# "{' '}"
# "{ I18n.t('baz') }"
# '</div>'
# ].join '\n'
errors: [message: "`{ I18n.t('baz') }` must be placed on a new line"]
,
code: [
"<Text style={styles.foo}>{ bar } <Text/> { I18n.t('baz') }</Text>"
].join '\n'
# output: [
# '<Text style={styles.foo}>'
# '{ bar } '
# "{' '}"
# '<Text/> '
# "{' '}"
# "{ I18n.t('baz') }"
# '</Text>'
# ].join '\n'
errors: [
message: '`{ bar }` must be placed on a new line'
,
message: '`Text` must be placed on a new line'
,
message: "`{ I18n.t('baz') }` must be placed on a new line"
]
,
code: ['<Text style={styles.foo}> <Bar/> <Baz/></Text>'].join '\n'
# output: [
# '<Text style={styles.foo}> '
# "{' '}"
# '<Bar/> '
# "{' '}"
# '<Baz/>'
# '</Text>'
# ].join '\n'
errors: [
message: '`Bar` must be placed on a new line'
,
message: '`Baz` must be placed on a new line'
]
,
code: [
'<Text style={styles.foo}> <Bar/> <Baz/> <Bunk/> <Bruno/> </Text>'
].join '\n'
# output: [
# '<Text style={styles.foo}> '
# "{' '}"
# '<Bar/> '
# "{' '}"
# '<Baz/> '
# "{' '}"
# '<Bunk/> '
# "{' '}"
# '<Bruno/>'
# "{' '}"
# ' </Text>'
# ].join '\n'
errors: [
message: '`Bar` must be placed on a new line'
,
message: '`Baz` must be placed on a new line'
,
message: '`Bunk` must be placed on a new line'
,
message: '`Bruno` must be placed on a new line'
]
,
code: ['<Text style={styles.foo}> <Bar /></Text>'].join '\n'
# output: ['<Text style={styles.foo}> ', "{' '}", '<Bar />', '</Text>'].join(
# '\n'
# )
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<Text style={styles.foo}> <Bar />', '</Text>'].join '\n'
# output: ['<Text style={styles.foo}> ', "{' '}", '<Bar />', '</Text>'].join(
# '\n'
# )
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<Text style={styles.foo}>', ' <Bar /> <Baz />', '</Text>'].join(
'\n'
)
# output: [
# '<Text style={styles.foo}>'
# ' <Bar /> '
# "{' '}"
# '<Baz />'
# '</Text>'
# ].join '\n'
errors: [message: '`Baz` must be placed on a new line']
,
code: [
'<Text style={styles.foo}>'
" { bar } { I18n.t('baz') }"
'</Text>'
].join '\n'
# output: [
# '<Text style={styles.foo}>'
# ' { bar } '
# "{' '}"
# "{ I18n.t('baz') }"
# '</Text>'
# ].join '\n'
errors: [message: "`{ I18n.t('baz') }` must be placed on a new line"]
,
code: ['<div>', ' foo<input />', '</div>'].join '\n'
# output: ['<div>', ' foo', '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' {"foo"}<span />', '</div>'].join '\n'
# output: ['<div>', ' {"foo"}', '<span />', '</div>'].join '\n'
errors: [message: '`span` must be placed on a new line']
,
code: ['<div>', ' foo <input />', '</div>'].join '\n'
# output: ['<div>', ' foo ', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' <input /> foo', '</div>'].join '\n'
# output: ['<div>', ' <input />', "{' '}", 'foo', '</div>'].join '\n'
errors: [message: '` foo` must be placed on a new line']
,
code: ['<div>', ' <span /> <input />', '</div>'].join '\n'
# output: ['<div>', ' <span /> ', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' <span />', "{' '}<input />", '</div>'].join '\n'
# output: ['<div>', ' <span />', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' {"foo"} <input />', '</div>'].join '\n'
# output: ['<div>', ' {"foo"} ', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' {"foo"} bar', '</div>'].join '\n'
# output: ['<div>', ' {"foo"}', "{' '}", 'bar', '</div>'].join '\n'
errors: [message: '` bar` must be placed on a new line']
,
code: ['<div>', ' foo {"bar"}', '</div>'].join '\n'
# output: ['<div>', ' foo ', "{' '}", '{"bar"}', '</div>'].join '\n'
errors: [message: '`{"bar"}` must be placed on a new line']
,
code: ['<div>', ' <input /> {"foo"}', '</div>'].join '\n'
# output: ['<div>', ' <input /> ', "{' '}", '{"foo"}', '</div>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: ['<App>', ' <Foo></Foo><Bar></Bar>', '</App>'].join '\n'
# output: ['<App>', ' <Foo></Foo>', '<Bar></Bar>', '</App>'].join '\n'
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<App>', '<Foo></Foo></App>'].join '\n'
# output: ['<App>', '<Foo></Foo>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App><Foo />', '</App>'].join '\n'
# output: ['<App>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App>', '<Foo/></App>'].join '\n'
# output: ['<App>', '<Foo/>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App><Foo', '/>', '</App>'].join '\n'
# output: ['<App>', '<Foo', '/>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', '>', '<Foo /></App>'].join '\n'
# output: ['<App', '>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', '>', '<Foo', '/></App>'].join '\n'
# output: ['<App', '>', '<Foo', '/>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', '><Foo />', '</App>'].join '\n'
# output: ['<App', '>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App>', ' <Foo>', ' <Bar /></Foo>', '</App>'].join '\n'
# output: ['<App>', ' <Foo>', ' <Bar />', '</Foo>', '</App>'].join '\n'
errors: [message: '`Bar` must be placed on a new line']
,
code: [
'<App>'
' <Foo>'
' <Bar> baz </Bar>'
' </Foo>'
'</App>'
].join '\n'
# output: [
# '<App>'
# ' <Foo>'
# ' <Bar>'
# "{' '}"
# 'baz'
# "{' '}"
# '</Bar>'
# ' </Foo>'
# '</App>'
# ].join '\n'
errors: [message: '` baz ` must be placed on a new line']
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', ' foo {"bar"} baz', '</App>'].join '\n'
# output: ['<App>', ' foo ', "{' '}", '{"bar"} baz', '</App>'].join '\n'
errors: [
message: '`{"bar"}` must be placed on a new line'
,
message: '` baz` must be placed on a new line'
]
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', ' foo {"bar"}', '</App>'].join '\n'
# output: ['<App>', ' foo ', "{' '}", '{"bar"}', '</App>'].join '\n'
errors: [message: '`{"bar"}` must be placed on a new line']
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', ' foo ', "{' '}", '{"bar"} baz', '</App>'].join '\n'
# output: [
# '<App>'
# ' foo '
# "{' '}"
# '{"bar"}'
# "{' '}"
# 'baz'
# '</App>'
# ].join '\n'
errors: [message: '` baz` must be placed on a new line']
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', '', ' foo {"bar"} baz', '', '</App>'].join '\n'
# output: ['<App>', '', ' foo ', "{' '}", '{"bar"} baz', '', '</App>'].join(
# '\n'
# )
errors: [
message: '`{"bar"}` must be placed on a new line'
,
message: '` baz` must be placed on a new line'
]
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', '', ' foo ', "{' '}", '{"bar"} baz', '', '</App>'].join(
'\n'
)
# output: [
# '<App>'
# ''
# ' foo '
# "{' '}"
# '{"bar"}'
# "{' '}"
# 'baz'
# ''
# '</App>'
# ].join '\n'
errors: [message: '` baz` must be placed on a new line']
,
code: ['<App>{', ' foo', '}</App>'].join '\n'
# output: ['<App>', '{', ' foo', '}', '</App>'].join '\n'
errors: [message: '`{ foo}` must be placed on a new line']
,
code: ['<App> {', ' foo', '} </App>'].join '\n'
# output: ['<App> ', "{' '}", '{', ' foo', '}', "{' '}", ' </App>'].join '\n'
errors: [message: '`{ foo}` must be placed on a new line']
,
code: ['<App> ', "{' '}", '{', ' foo', '} </App>'].join '\n'
# output: ['<App> ', "{' '}", '{', ' foo', '}', "{' '}", ' </App>'].join '\n'
errors: [message: '`{ foo}` must be placed on a new line']
,
code: '<App><Foo /></App>'
options: [allow: 'none']
# output: ['<App>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: '<App>foo</App>'
options: [allow: 'none']
# output: ['<App>', 'foo', '</App>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: '<App>{"foo"}</App>'
options: [allow: 'none']
# output: ['<App>', '{"foo"}', '</App>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: ['<App>foo', '</App>'].join '\n'
options: [allow: 'literal']
# output: ['<App>', 'foo', '</App>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: '<App><Foo /></App>'
options: [allow: 'literal']
# output: ['<App>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', ' foo="1"', ' bar="2"', '>baz</App>'].join '\n'
options: [allow: 'literal']
# output: ['<App', ' foo="1"', ' bar="2"', '>', 'baz', '</App>'].join '\n'
errors: [message: '`baz` must be placed on a new line']
,
code: ['<App>foo', 'bar', '</App>'].join '\n'
options: [allow: 'literal']
# output: ['<App>', 'foo', 'bar', '</App>'].join '\n'
errors: [message: '`foobar` must be placed on a new line']
,
# ,
# code: '<>{"foo"}</>'
# output: ['<>', '{"foo"}', '</>'].join '\n'
# errors: [message: '`{"foo"}` must be placed on a new line']
# parser: 'babel-eslint'
code: ['<App>', ' <Foo /><></>', '</App>'].join '\n'
# output: ['<App>', ' <Foo />', '<></>', '</App>'].join '\n'
errors: [message: '`<></>` must be placed on a new line']
]
| 46892 | ###*
# @fileoverview Limit to one expression per line in JSX
# @author <NAME> <Vydia.com>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/jsx-one-expression-per-line'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-one-expression-per-line', rule,
valid: [
code: '<App />'
,
code: '<App></App>'
,
code: '<App foo="bar" />'
,
code: ['<App>', ' <Foo />', '</App>'].join '\n'
,
code: ['<App>', ' <Foo />', ' <Bar />', '</App>'].join '\n'
,
code: ['<App>', ' <Foo></Foo>', '</App>'].join '\n'
,
code: ['<App>', ' foo bar baz whatever ', '</App>'].join '\n'
,
code: ['<App>', ' <Foo>', ' </Foo>', '</App>'].join '\n'
,
code: ['<App', ' foo="bar"', '>', '<Foo />', '</App>'].join '\n'
,
# ,
# code: ['<', 'App', '>', ' <', ' Foo', ' />', '</', 'App', '>'].join(
# '\n'
# )
code: '<App>foo</App>'
options: [allow: 'literal']
,
code: '<App>123</App>'
options: [allow: 'literal']
,
code: '<App>foo</App>'
options: [allow: 'single-child']
,
code: '<App>{"foo"}</App>'
options: [allow: 'single-child']
,
code: '<App>{foo && <Bar />}</App>'
options: [allow: 'single-child']
,
code: '<App><Foo /></App>'
options: [allow: 'single-child']
,
code: '<></>'
,
# parser: 'babel-eslint'
code: ['<>', ' <Foo />', '</>'].join '\n'
,
# parser: 'babel-eslint'
code: ['<>', ' <Foo />', ' <Bar />', '</>'].join '\n'
# parser: 'babel-eslint'
]
invalid: [
code: '<App>{"foo"}</App>'
# output: ['<App>', '{"foo"}', '</App>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: '<App>foo</App>'
# output: ['<App>', 'foo', '</App>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: ['<div>', ' foo {"bar"}', '</div>'].join '\n'
# output: ['<div>', ' foo ', "{' '}", '{"bar"}', '</div>'].join '\n'
errors: [message: '`{"bar"}` must be placed on a new line']
,
code: ['<div>', ' {"foo"} bar', '</div>'].join '\n'
# output: ['<div>', ' {"foo"}', "{' '}", 'bar', '</div>'].join '\n'
errors: [message: '` bar` must be placed on a new line']
,
code: ['<App>', ' <Foo /><Bar />', '</App>'].join '\n'
# output: ['<App>', ' <Foo />', '<Bar />', '</App>'].join '\n'
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<div>', ' <span />foo', '</div>'].join '\n'
# output: ['<div>', ' <span />', 'foo', '</div>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: ['<div>', ' <span />{"foo"}', '</div>'].join '\n'
# output: ['<div>', ' <span />', '{"foo"}', '</div>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: ['<div>', ' {"foo"} { I18n.t(\'baz\') }', '</div>'].join '\n'
# output: [
# '<div>'
# ' {"foo"} '
# "{' '}"
# "{ I18n.t('baz') }"
# '</div>'
# ].join '\n'
errors: [message: "`{ I18n.t('baz') }` must be placed on a new line"]
,
code: [
"<Text style={styles.foo}>{ bar } <Text/> { I18n.t('baz') }</Text>"
].join '\n'
# output: [
# '<Text style={styles.foo}>'
# '{ bar } '
# "{' '}"
# '<Text/> '
# "{' '}"
# "{ I18n.t('baz') }"
# '</Text>'
# ].join '\n'
errors: [
message: '`{ bar }` must be placed on a new line'
,
message: '`Text` must be placed on a new line'
,
message: "`{ I18n.t('baz') }` must be placed on a new line"
]
,
code: ['<Text style={styles.foo}> <Bar/> <Baz/></Text>'].join '\n'
# output: [
# '<Text style={styles.foo}> '
# "{' '}"
# '<Bar/> '
# "{' '}"
# '<Baz/>'
# '</Text>'
# ].join '\n'
errors: [
message: '`Bar` must be placed on a new line'
,
message: '`Baz` must be placed on a new line'
]
,
code: [
'<Text style={styles.foo}> <Bar/> <Baz/> <Bunk/> <Bruno/> </Text>'
].join '\n'
# output: [
# '<Text style={styles.foo}> '
# "{' '}"
# '<Bar/> '
# "{' '}"
# '<Baz/> '
# "{' '}"
# '<Bunk/> '
# "{' '}"
# '<Bruno/>'
# "{' '}"
# ' </Text>'
# ].join '\n'
errors: [
message: '`Bar` must be placed on a new line'
,
message: '`Baz` must be placed on a new line'
,
message: '`Bunk` must be placed on a new line'
,
message: '`Bruno` must be placed on a new line'
]
,
code: ['<Text style={styles.foo}> <Bar /></Text>'].join '\n'
# output: ['<Text style={styles.foo}> ', "{' '}", '<Bar />', '</Text>'].join(
# '\n'
# )
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<Text style={styles.foo}> <Bar />', '</Text>'].join '\n'
# output: ['<Text style={styles.foo}> ', "{' '}", '<Bar />', '</Text>'].join(
# '\n'
# )
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<Text style={styles.foo}>', ' <Bar /> <Baz />', '</Text>'].join(
'\n'
)
# output: [
# '<Text style={styles.foo}>'
# ' <Bar /> '
# "{' '}"
# '<Baz />'
# '</Text>'
# ].join '\n'
errors: [message: '`Baz` must be placed on a new line']
,
code: [
'<Text style={styles.foo}>'
" { bar } { I18n.t('baz') }"
'</Text>'
].join '\n'
# output: [
# '<Text style={styles.foo}>'
# ' { bar } '
# "{' '}"
# "{ I18n.t('baz') }"
# '</Text>'
# ].join '\n'
errors: [message: "`{ I18n.t('baz') }` must be placed on a new line"]
,
code: ['<div>', ' foo<input />', '</div>'].join '\n'
# output: ['<div>', ' foo', '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' {"foo"}<span />', '</div>'].join '\n'
# output: ['<div>', ' {"foo"}', '<span />', '</div>'].join '\n'
errors: [message: '`span` must be placed on a new line']
,
code: ['<div>', ' foo <input />', '</div>'].join '\n'
# output: ['<div>', ' foo ', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' <input /> foo', '</div>'].join '\n'
# output: ['<div>', ' <input />', "{' '}", 'foo', '</div>'].join '\n'
errors: [message: '` foo` must be placed on a new line']
,
code: ['<div>', ' <span /> <input />', '</div>'].join '\n'
# output: ['<div>', ' <span /> ', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' <span />', "{' '}<input />", '</div>'].join '\n'
# output: ['<div>', ' <span />', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' {"foo"} <input />', '</div>'].join '\n'
# output: ['<div>', ' {"foo"} ', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' {"foo"} bar', '</div>'].join '\n'
# output: ['<div>', ' {"foo"}', "{' '}", 'bar', '</div>'].join '\n'
errors: [message: '` bar` must be placed on a new line']
,
code: ['<div>', ' foo {"bar"}', '</div>'].join '\n'
# output: ['<div>', ' foo ', "{' '}", '{"bar"}', '</div>'].join '\n'
errors: [message: '`{"bar"}` must be placed on a new line']
,
code: ['<div>', ' <input /> {"foo"}', '</div>'].join '\n'
# output: ['<div>', ' <input /> ', "{' '}", '{"foo"}', '</div>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: ['<App>', ' <Foo></Foo><Bar></Bar>', '</App>'].join '\n'
# output: ['<App>', ' <Foo></Foo>', '<Bar></Bar>', '</App>'].join '\n'
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<App>', '<Foo></Foo></App>'].join '\n'
# output: ['<App>', '<Foo></Foo>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App><Foo />', '</App>'].join '\n'
# output: ['<App>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App>', '<Foo/></App>'].join '\n'
# output: ['<App>', '<Foo/>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App><Foo', '/>', '</App>'].join '\n'
# output: ['<App>', '<Foo', '/>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', '>', '<Foo /></App>'].join '\n'
# output: ['<App', '>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', '>', '<Foo', '/></App>'].join '\n'
# output: ['<App', '>', '<Foo', '/>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', '><Foo />', '</App>'].join '\n'
# output: ['<App', '>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App>', ' <Foo>', ' <Bar /></Foo>', '</App>'].join '\n'
# output: ['<App>', ' <Foo>', ' <Bar />', '</Foo>', '</App>'].join '\n'
errors: [message: '`Bar` must be placed on a new line']
,
code: [
'<App>'
' <Foo>'
' <Bar> baz </Bar>'
' </Foo>'
'</App>'
].join '\n'
# output: [
# '<App>'
# ' <Foo>'
# ' <Bar>'
# "{' '}"
# 'baz'
# "{' '}"
# '</Bar>'
# ' </Foo>'
# '</App>'
# ].join '\n'
errors: [message: '` baz ` must be placed on a new line']
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', ' foo {"bar"} baz', '</App>'].join '\n'
# output: ['<App>', ' foo ', "{' '}", '{"bar"} baz', '</App>'].join '\n'
errors: [
message: '`{"bar"}` must be placed on a new line'
,
message: '` baz` must be placed on a new line'
]
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', ' foo {"bar"}', '</App>'].join '\n'
# output: ['<App>', ' foo ', "{' '}", '{"bar"}', '</App>'].join '\n'
errors: [message: '`{"bar"}` must be placed on a new line']
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', ' foo ', "{' '}", '{"bar"} baz', '</App>'].join '\n'
# output: [
# '<App>'
# ' foo '
# "{' '}"
# '{"bar"}'
# "{' '}"
# 'baz'
# '</App>'
# ].join '\n'
errors: [message: '` baz` must be placed on a new line']
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', '', ' foo {"bar"} baz', '', '</App>'].join '\n'
# output: ['<App>', '', ' foo ', "{' '}", '{"bar"} baz', '', '</App>'].join(
# '\n'
# )
errors: [
message: '`{"bar"}` must be placed on a new line'
,
message: '` baz` must be placed on a new line'
]
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', '', ' foo ', "{' '}", '{"bar"} baz', '', '</App>'].join(
'\n'
)
# output: [
# '<App>'
# ''
# ' foo '
# "{' '}"
# '{"bar"}'
# "{' '}"
# 'baz'
# ''
# '</App>'
# ].join '\n'
errors: [message: '` baz` must be placed on a new line']
,
code: ['<App>{', ' foo', '}</App>'].join '\n'
# output: ['<App>', '{', ' foo', '}', '</App>'].join '\n'
errors: [message: '`{ foo}` must be placed on a new line']
,
code: ['<App> {', ' foo', '} </App>'].join '\n'
# output: ['<App> ', "{' '}", '{', ' foo', '}', "{' '}", ' </App>'].join '\n'
errors: [message: '`{ foo}` must be placed on a new line']
,
code: ['<App> ', "{' '}", '{', ' foo', '} </App>'].join '\n'
# output: ['<App> ', "{' '}", '{', ' foo', '}', "{' '}", ' </App>'].join '\n'
errors: [message: '`{ foo}` must be placed on a new line']
,
code: '<App><Foo /></App>'
options: [allow: 'none']
# output: ['<App>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: '<App>foo</App>'
options: [allow: 'none']
# output: ['<App>', 'foo', '</App>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: '<App>{"foo"}</App>'
options: [allow: 'none']
# output: ['<App>', '{"foo"}', '</App>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: ['<App>foo', '</App>'].join '\n'
options: [allow: 'literal']
# output: ['<App>', 'foo', '</App>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: '<App><Foo /></App>'
options: [allow: 'literal']
# output: ['<App>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', ' foo="1"', ' bar="2"', '>baz</App>'].join '\n'
options: [allow: 'literal']
# output: ['<App', ' foo="1"', ' bar="2"', '>', 'baz', '</App>'].join '\n'
errors: [message: '`baz` must be placed on a new line']
,
code: ['<App>foo', 'bar', '</App>'].join '\n'
options: [allow: 'literal']
# output: ['<App>', 'foo', 'bar', '</App>'].join '\n'
errors: [message: '`foobar` must be placed on a new line']
,
# ,
# code: '<>{"foo"}</>'
# output: ['<>', '{"foo"}', '</>'].join '\n'
# errors: [message: '`{"foo"}` must be placed on a new line']
# parser: 'babel-eslint'
code: ['<App>', ' <Foo /><></>', '</App>'].join '\n'
# output: ['<App>', ' <Foo />', '<></>', '</App>'].join '\n'
errors: [message: '`<></>` must be placed on a new line']
]
| true | ###*
# @fileoverview Limit to one expression per line in JSX
# @author PI:NAME:<NAME>END_PI <Vydia.com>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/jsx-one-expression-per-line'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-one-expression-per-line', rule,
valid: [
code: '<App />'
,
code: '<App></App>'
,
code: '<App foo="bar" />'
,
code: ['<App>', ' <Foo />', '</App>'].join '\n'
,
code: ['<App>', ' <Foo />', ' <Bar />', '</App>'].join '\n'
,
code: ['<App>', ' <Foo></Foo>', '</App>'].join '\n'
,
code: ['<App>', ' foo bar baz whatever ', '</App>'].join '\n'
,
code: ['<App>', ' <Foo>', ' </Foo>', '</App>'].join '\n'
,
code: ['<App', ' foo="bar"', '>', '<Foo />', '</App>'].join '\n'
,
# ,
# code: ['<', 'App', '>', ' <', ' Foo', ' />', '</', 'App', '>'].join(
# '\n'
# )
code: '<App>foo</App>'
options: [allow: 'literal']
,
code: '<App>123</App>'
options: [allow: 'literal']
,
code: '<App>foo</App>'
options: [allow: 'single-child']
,
code: '<App>{"foo"}</App>'
options: [allow: 'single-child']
,
code: '<App>{foo && <Bar />}</App>'
options: [allow: 'single-child']
,
code: '<App><Foo /></App>'
options: [allow: 'single-child']
,
code: '<></>'
,
# parser: 'babel-eslint'
code: ['<>', ' <Foo />', '</>'].join '\n'
,
# parser: 'babel-eslint'
code: ['<>', ' <Foo />', ' <Bar />', '</>'].join '\n'
# parser: 'babel-eslint'
]
invalid: [
code: '<App>{"foo"}</App>'
# output: ['<App>', '{"foo"}', '</App>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: '<App>foo</App>'
# output: ['<App>', 'foo', '</App>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: ['<div>', ' foo {"bar"}', '</div>'].join '\n'
# output: ['<div>', ' foo ', "{' '}", '{"bar"}', '</div>'].join '\n'
errors: [message: '`{"bar"}` must be placed on a new line']
,
code: ['<div>', ' {"foo"} bar', '</div>'].join '\n'
# output: ['<div>', ' {"foo"}', "{' '}", 'bar', '</div>'].join '\n'
errors: [message: '` bar` must be placed on a new line']
,
code: ['<App>', ' <Foo /><Bar />', '</App>'].join '\n'
# output: ['<App>', ' <Foo />', '<Bar />', '</App>'].join '\n'
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<div>', ' <span />foo', '</div>'].join '\n'
# output: ['<div>', ' <span />', 'foo', '</div>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: ['<div>', ' <span />{"foo"}', '</div>'].join '\n'
# output: ['<div>', ' <span />', '{"foo"}', '</div>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: ['<div>', ' {"foo"} { I18n.t(\'baz\') }', '</div>'].join '\n'
# output: [
# '<div>'
# ' {"foo"} '
# "{' '}"
# "{ I18n.t('baz') }"
# '</div>'
# ].join '\n'
errors: [message: "`{ I18n.t('baz') }` must be placed on a new line"]
,
code: [
"<Text style={styles.foo}>{ bar } <Text/> { I18n.t('baz') }</Text>"
].join '\n'
# output: [
# '<Text style={styles.foo}>'
# '{ bar } '
# "{' '}"
# '<Text/> '
# "{' '}"
# "{ I18n.t('baz') }"
# '</Text>'
# ].join '\n'
errors: [
message: '`{ bar }` must be placed on a new line'
,
message: '`Text` must be placed on a new line'
,
message: "`{ I18n.t('baz') }` must be placed on a new line"
]
,
code: ['<Text style={styles.foo}> <Bar/> <Baz/></Text>'].join '\n'
# output: [
# '<Text style={styles.foo}> '
# "{' '}"
# '<Bar/> '
# "{' '}"
# '<Baz/>'
# '</Text>'
# ].join '\n'
errors: [
message: '`Bar` must be placed on a new line'
,
message: '`Baz` must be placed on a new line'
]
,
code: [
'<Text style={styles.foo}> <Bar/> <Baz/> <Bunk/> <Bruno/> </Text>'
].join '\n'
# output: [
# '<Text style={styles.foo}> '
# "{' '}"
# '<Bar/> '
# "{' '}"
# '<Baz/> '
# "{' '}"
# '<Bunk/> '
# "{' '}"
# '<Bruno/>'
# "{' '}"
# ' </Text>'
# ].join '\n'
errors: [
message: '`Bar` must be placed on a new line'
,
message: '`Baz` must be placed on a new line'
,
message: '`Bunk` must be placed on a new line'
,
message: '`Bruno` must be placed on a new line'
]
,
code: ['<Text style={styles.foo}> <Bar /></Text>'].join '\n'
# output: ['<Text style={styles.foo}> ', "{' '}", '<Bar />', '</Text>'].join(
# '\n'
# )
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<Text style={styles.foo}> <Bar />', '</Text>'].join '\n'
# output: ['<Text style={styles.foo}> ', "{' '}", '<Bar />', '</Text>'].join(
# '\n'
# )
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<Text style={styles.foo}>', ' <Bar /> <Baz />', '</Text>'].join(
'\n'
)
# output: [
# '<Text style={styles.foo}>'
# ' <Bar /> '
# "{' '}"
# '<Baz />'
# '</Text>'
# ].join '\n'
errors: [message: '`Baz` must be placed on a new line']
,
code: [
'<Text style={styles.foo}>'
" { bar } { I18n.t('baz') }"
'</Text>'
].join '\n'
# output: [
# '<Text style={styles.foo}>'
# ' { bar } '
# "{' '}"
# "{ I18n.t('baz') }"
# '</Text>'
# ].join '\n'
errors: [message: "`{ I18n.t('baz') }` must be placed on a new line"]
,
code: ['<div>', ' foo<input />', '</div>'].join '\n'
# output: ['<div>', ' foo', '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' {"foo"}<span />', '</div>'].join '\n'
# output: ['<div>', ' {"foo"}', '<span />', '</div>'].join '\n'
errors: [message: '`span` must be placed on a new line']
,
code: ['<div>', ' foo <input />', '</div>'].join '\n'
# output: ['<div>', ' foo ', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' <input /> foo', '</div>'].join '\n'
# output: ['<div>', ' <input />', "{' '}", 'foo', '</div>'].join '\n'
errors: [message: '` foo` must be placed on a new line']
,
code: ['<div>', ' <span /> <input />', '</div>'].join '\n'
# output: ['<div>', ' <span /> ', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' <span />', "{' '}<input />", '</div>'].join '\n'
# output: ['<div>', ' <span />', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' {"foo"} <input />', '</div>'].join '\n'
# output: ['<div>', ' {"foo"} ', "{' '}", '<input />', '</div>'].join '\n'
errors: [message: '`input` must be placed on a new line']
,
code: ['<div>', ' {"foo"} bar', '</div>'].join '\n'
# output: ['<div>', ' {"foo"}', "{' '}", 'bar', '</div>'].join '\n'
errors: [message: '` bar` must be placed on a new line']
,
code: ['<div>', ' foo {"bar"}', '</div>'].join '\n'
# output: ['<div>', ' foo ', "{' '}", '{"bar"}', '</div>'].join '\n'
errors: [message: '`{"bar"}` must be placed on a new line']
,
code: ['<div>', ' <input /> {"foo"}', '</div>'].join '\n'
# output: ['<div>', ' <input /> ', "{' '}", '{"foo"}', '</div>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: ['<App>', ' <Foo></Foo><Bar></Bar>', '</App>'].join '\n'
# output: ['<App>', ' <Foo></Foo>', '<Bar></Bar>', '</App>'].join '\n'
errors: [message: '`Bar` must be placed on a new line']
,
code: ['<App>', '<Foo></Foo></App>'].join '\n'
# output: ['<App>', '<Foo></Foo>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App><Foo />', '</App>'].join '\n'
# output: ['<App>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App>', '<Foo/></App>'].join '\n'
# output: ['<App>', '<Foo/>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App><Foo', '/>', '</App>'].join '\n'
# output: ['<App>', '<Foo', '/>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', '>', '<Foo /></App>'].join '\n'
# output: ['<App', '>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', '>', '<Foo', '/></App>'].join '\n'
# output: ['<App', '>', '<Foo', '/>', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', '><Foo />', '</App>'].join '\n'
# output: ['<App', '>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App>', ' <Foo>', ' <Bar /></Foo>', '</App>'].join '\n'
# output: ['<App>', ' <Foo>', ' <Bar />', '</Foo>', '</App>'].join '\n'
errors: [message: '`Bar` must be placed on a new line']
,
code: [
'<App>'
' <Foo>'
' <Bar> baz </Bar>'
' </Foo>'
'</App>'
].join '\n'
# output: [
# '<App>'
# ' <Foo>'
# ' <Bar>'
# "{' '}"
# 'baz'
# "{' '}"
# '</Bar>'
# ' </Foo>'
# '</App>'
# ].join '\n'
errors: [message: '` baz ` must be placed on a new line']
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', ' foo {"bar"} baz', '</App>'].join '\n'
# output: ['<App>', ' foo ', "{' '}", '{"bar"} baz', '</App>'].join '\n'
errors: [
message: '`{"bar"}` must be placed on a new line'
,
message: '` baz` must be placed on a new line'
]
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', ' foo {"bar"}', '</App>'].join '\n'
# output: ['<App>', ' foo ', "{' '}", '{"bar"}', '</App>'].join '\n'
errors: [message: '`{"bar"}` must be placed on a new line']
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', ' foo ', "{' '}", '{"bar"} baz', '</App>'].join '\n'
# output: [
# '<App>'
# ' foo '
# "{' '}"
# '{"bar"}'
# "{' '}"
# 'baz'
# '</App>'
# ].join '\n'
errors: [message: '` baz` must be placed on a new line']
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', '', ' foo {"bar"} baz', '', '</App>'].join '\n'
# output: ['<App>', '', ' foo ', "{' '}", '{"bar"} baz', '', '</App>'].join(
# '\n'
# )
errors: [
message: '`{"bar"}` must be placed on a new line'
,
message: '` baz` must be placed on a new line'
]
,
# Would be nice to handle in one pass, but multipass works fine.
code: ['<App>', '', ' foo ', "{' '}", '{"bar"} baz', '', '</App>'].join(
'\n'
)
# output: [
# '<App>'
# ''
# ' foo '
# "{' '}"
# '{"bar"}'
# "{' '}"
# 'baz'
# ''
# '</App>'
# ].join '\n'
errors: [message: '` baz` must be placed on a new line']
,
code: ['<App>{', ' foo', '}</App>'].join '\n'
# output: ['<App>', '{', ' foo', '}', '</App>'].join '\n'
errors: [message: '`{ foo}` must be placed on a new line']
,
code: ['<App> {', ' foo', '} </App>'].join '\n'
# output: ['<App> ', "{' '}", '{', ' foo', '}', "{' '}", ' </App>'].join '\n'
errors: [message: '`{ foo}` must be placed on a new line']
,
code: ['<App> ', "{' '}", '{', ' foo', '} </App>'].join '\n'
# output: ['<App> ', "{' '}", '{', ' foo', '}', "{' '}", ' </App>'].join '\n'
errors: [message: '`{ foo}` must be placed on a new line']
,
code: '<App><Foo /></App>'
options: [allow: 'none']
# output: ['<App>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: '<App>foo</App>'
options: [allow: 'none']
# output: ['<App>', 'foo', '</App>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: '<App>{"foo"}</App>'
options: [allow: 'none']
# output: ['<App>', '{"foo"}', '</App>'].join '\n'
errors: [message: '`{"foo"}` must be placed on a new line']
,
code: ['<App>foo', '</App>'].join '\n'
options: [allow: 'literal']
# output: ['<App>', 'foo', '</App>'].join '\n'
errors: [message: '`foo` must be placed on a new line']
,
code: '<App><Foo /></App>'
options: [allow: 'literal']
# output: ['<App>', '<Foo />', '</App>'].join '\n'
errors: [message: '`Foo` must be placed on a new line']
,
code: ['<App', ' foo="1"', ' bar="2"', '>baz</App>'].join '\n'
options: [allow: 'literal']
# output: ['<App', ' foo="1"', ' bar="2"', '>', 'baz', '</App>'].join '\n'
errors: [message: '`baz` must be placed on a new line']
,
code: ['<App>foo', 'bar', '</App>'].join '\n'
options: [allow: 'literal']
# output: ['<App>', 'foo', 'bar', '</App>'].join '\n'
errors: [message: '`foobar` must be placed on a new line']
,
# ,
# code: '<>{"foo"}</>'
# output: ['<>', '{"foo"}', '</>'].join '\n'
# errors: [message: '`{"foo"}` must be placed on a new line']
# parser: 'babel-eslint'
code: ['<App>', ' <Foo /><></>', '</App>'].join '\n'
# output: ['<App>', ' <Foo />', '<></>', '</App>'].join '\n'
errors: [message: '`<></>` must be placed on a new line']
]
|
[
{
"context": "abels a greyhound as medical hold.\n#\n# Author:\n# Zach Whaley (zachwhaley) <zachbwhaley@gmail.com>\n\ngit = requi",
"end": 171,
"score": 0.9998448491096497,
"start": 160,
"tag": "NAME",
"value": "Zach Whaley"
},
{
"context": "und as medical hold.\n#\n# Author:\n# ... | scripts/medhold.coffee | galtx-centex/roobot | 3 | # Description:
# Label a greyhound as medical hold
#
# Commands:
# hubot medhold <greyhound> (yes/no) - Labels a greyhound as medical hold.
#
# Author:
# Zach Whaley (zachwhaley) <zachbwhaley@gmail.com>
git = require '../lib/git'
site = require '../lib/site'
util = require '../lib/util'
medholdMessage = (medicalhold) ->
if medicalhold
"in Medical Hold 🤕"
else
"not in Medical Hold 😃"
medicalHold = (path, greyhound, name, medicalhold, callback) ->
site.loadGreyhound path, greyhound, (info, bio) ->
if not info?
return callback "Sorry, couldn't find #{greyhound} 😕"
if info.category is 'deceased'
return callback "#{name} has crossed the Rainbow Bridge 😢"
if info.category is 'adopted'
return callback "#{name} has already been adopted 😝"
if info.permafoster is yes
return callback "#{name} is a permanent foster 😕\nRemove #{name} permanent foster status first with `@roobot permafoster #{greyhound} no`"
if info.pending is yes
return callback "#{name} is pending adoption 😕\nRemove #{name} pending adoption status first with `@roobot pending #{greyhound} no`"
if medicalhold and info.medicalhold is yes
return callback "#{name} is already in medical hold 🤕"
if not medicalhold and info.medicalhold is no
return callback "#{name} is already not in medical hold 😃"
info.medicalhold = medicalhold
site.dumpGreyhound path, greyhound, info, bio, callback
module.exports = (robot) ->
robot.respond /medhold (.+?)(\s(yes|no))?$/i, (res) ->
greyhound = util.slugify res.match[1]
name = util.capitalize res.match[1]
medhold = yes
if res.match[3]?.toLowerCase() is 'no'
medhold = no
gitOpts =
message: "#{name} #{medholdMessage(medhold)}"
branch: "medhold-#{greyhound}"
user:
name: res.message.user?.real_name
email: res.message.user?.email_address
res.reply "Labeling #{name} as #{medholdMessage(medhold)}\n" +
"Hang on a sec..."
git.update medicalHold, greyhound, name, medhold, gitOpts, (err) ->
unless err?
res.reply "#{name} labeled as #{medholdMessage(medhold)}"
else
res.reply err
| 49940 | # Description:
# Label a greyhound as medical hold
#
# Commands:
# hubot medhold <greyhound> (yes/no) - Labels a greyhound as medical hold.
#
# Author:
# <NAME> (zachwhaley) <<EMAIL>>
git = require '../lib/git'
site = require '../lib/site'
util = require '../lib/util'
medholdMessage = (medicalhold) ->
if medicalhold
"in Medical Hold 🤕"
else
"not in Medical Hold 😃"
medicalHold = (path, greyhound, name, medicalhold, callback) ->
site.loadGreyhound path, greyhound, (info, bio) ->
if not info?
return callback "Sorry, couldn't find #{greyhound} 😕"
if info.category is 'deceased'
return callback "#{name} has crossed the Rainbow Bridge 😢"
if info.category is 'adopted'
return callback "#{name} has already been adopted 😝"
if info.permafoster is yes
return callback "#{name} is a permanent foster 😕\nRemove #{name} permanent foster status first with `@roobot permafoster #{greyhound} no`"
if info.pending is yes
return callback "#{name} is pending adoption 😕\nRemove #{name} pending adoption status first with `@roobot pending #{greyhound} no`"
if medicalhold and info.medicalhold is yes
return callback "#{name} is already in medical hold 🤕"
if not medicalhold and info.medicalhold is no
return callback "#{name} is already not in medical hold 😃"
info.medicalhold = medicalhold
site.dumpGreyhound path, greyhound, info, bio, callback
module.exports = (robot) ->
robot.respond /medhold (.+?)(\s(yes|no))?$/i, (res) ->
greyhound = util.slugify res.match[1]
name = util.capitalize res.match[1]
medhold = yes
if res.match[3]?.toLowerCase() is 'no'
medhold = no
gitOpts =
message: "#{name} #{medholdMessage(medhold)}"
branch: "medhold-#{greyhound}"
user:
name: res.message.user?.real_name
email: res.message.user?.email_address
res.reply "Labeling #{name} as #{medholdMessage(medhold)}\n" +
"Hang on a sec..."
git.update medicalHold, greyhound, name, medhold, gitOpts, (err) ->
unless err?
res.reply "#{name} labeled as #{medholdMessage(medhold)}"
else
res.reply err
| true | # Description:
# Label a greyhound as medical hold
#
# Commands:
# hubot medhold <greyhound> (yes/no) - Labels a greyhound as medical hold.
#
# Author:
# PI:NAME:<NAME>END_PI (zachwhaley) <PI:EMAIL:<EMAIL>END_PI>
git = require '../lib/git'
site = require '../lib/site'
util = require '../lib/util'
medholdMessage = (medicalhold) ->
if medicalhold
"in Medical Hold 🤕"
else
"not in Medical Hold 😃"
medicalHold = (path, greyhound, name, medicalhold, callback) ->
site.loadGreyhound path, greyhound, (info, bio) ->
if not info?
return callback "Sorry, couldn't find #{greyhound} 😕"
if info.category is 'deceased'
return callback "#{name} has crossed the Rainbow Bridge 😢"
if info.category is 'adopted'
return callback "#{name} has already been adopted 😝"
if info.permafoster is yes
return callback "#{name} is a permanent foster 😕\nRemove #{name} permanent foster status first with `@roobot permafoster #{greyhound} no`"
if info.pending is yes
return callback "#{name} is pending adoption 😕\nRemove #{name} pending adoption status first with `@roobot pending #{greyhound} no`"
if medicalhold and info.medicalhold is yes
return callback "#{name} is already in medical hold 🤕"
if not medicalhold and info.medicalhold is no
return callback "#{name} is already not in medical hold 😃"
info.medicalhold = medicalhold
site.dumpGreyhound path, greyhound, info, bio, callback
module.exports = (robot) ->
robot.respond /medhold (.+?)(\s(yes|no))?$/i, (res) ->
greyhound = util.slugify res.match[1]
name = util.capitalize res.match[1]
medhold = yes
if res.match[3]?.toLowerCase() is 'no'
medhold = no
gitOpts =
message: "#{name} #{medholdMessage(medhold)}"
branch: "medhold-#{greyhound}"
user:
name: res.message.user?.real_name
email: res.message.user?.email_address
res.reply "Labeling #{name} as #{medholdMessage(medhold)}\n" +
"Hang on a sec..."
git.update medicalHold, greyhound, name, medhold, gitOpts, (err) ->
unless err?
res.reply "#{name} labeled as #{medholdMessage(medhold)}"
else
res.reply err
|
[
{
"context": "PipeBackgroundPage\n memory: {}\n\n STORED_KEYS: ['commands']\n\n constructor: ->\n @listen()\n @updateMem",
"end": 77,
"score": 0.986533522605896,
"start": 69,
"tag": "KEY",
"value": "commands"
}
] | source/js/background-page.coffee | cantino/chrome_pipe | 31 | class window.ChromePipeBackgroundPage
memory: {}
STORED_KEYS: ['commands']
constructor: ->
@listen()
@updateMemory()
updateMemory: (callback = null) ->
@chromeStorageGet @STORED_KEYS, (answers) =>
for key in @STORED_KEYS
@memory[key] = answers[key] if key of answers
callback?()
chromeStorageGet: (variables, callback) ->
chrome.storage.local.get variables, (answers) => callback?(answers)
chromeStorageSet: (variables, callback) ->
@memory[key] = value for key, value of variables
chrome.storage.local.set variables, => callback?()
listen: ->
chrome.runtime.onMessage.addListener (request, sender, sendResponse) =>
handler = =>
Utils.log "Remote received from #{sender.tab.url} (#{sender.tab.incognito && 'incognito'}): #{JSON.stringify request}"
switch request.command
when 'copy'
Utils.putInClipboard(request.payload.text)
sendResponse()
when 'paste'
sendResponse(text: Utils.getFromClipboard())
when 'coffeeCompile'
try
sendResponse(javascript: CoffeeScript.compile(request.payload.coffeescript))
catch e
sendResponse(errors: e)
when 'getHistory'
sendResponse(commands: @memory.commands || [])
when 'recordCommand'
@updateMemory =>
@memory.commands ||= []
@memory.commands.unshift(request.payload)
@memory.commands = @memory.commands[0..50]
@chromeStorageSet({ commands: @memory.commands }, -> sendResponse({}))
else sendResponse(errors: "unknown command")
setTimeout handler, 10
true # Return true to indicate async message passing: http://developer.chrome.com/extensions/runtime#event-onMessage
errorResponse: (callback, message) ->
Utils.log message
callback errors: [message]
window.backgroundPage = new ChromePipeBackgroundPage() | 100004 | class window.ChromePipeBackgroundPage
memory: {}
STORED_KEYS: ['<KEY>']
constructor: ->
@listen()
@updateMemory()
updateMemory: (callback = null) ->
@chromeStorageGet @STORED_KEYS, (answers) =>
for key in @STORED_KEYS
@memory[key] = answers[key] if key of answers
callback?()
chromeStorageGet: (variables, callback) ->
chrome.storage.local.get variables, (answers) => callback?(answers)
chromeStorageSet: (variables, callback) ->
@memory[key] = value for key, value of variables
chrome.storage.local.set variables, => callback?()
listen: ->
chrome.runtime.onMessage.addListener (request, sender, sendResponse) =>
handler = =>
Utils.log "Remote received from #{sender.tab.url} (#{sender.tab.incognito && 'incognito'}): #{JSON.stringify request}"
switch request.command
when 'copy'
Utils.putInClipboard(request.payload.text)
sendResponse()
when 'paste'
sendResponse(text: Utils.getFromClipboard())
when 'coffeeCompile'
try
sendResponse(javascript: CoffeeScript.compile(request.payload.coffeescript))
catch e
sendResponse(errors: e)
when 'getHistory'
sendResponse(commands: @memory.commands || [])
when 'recordCommand'
@updateMemory =>
@memory.commands ||= []
@memory.commands.unshift(request.payload)
@memory.commands = @memory.commands[0..50]
@chromeStorageSet({ commands: @memory.commands }, -> sendResponse({}))
else sendResponse(errors: "unknown command")
setTimeout handler, 10
true # Return true to indicate async message passing: http://developer.chrome.com/extensions/runtime#event-onMessage
errorResponse: (callback, message) ->
Utils.log message
callback errors: [message]
window.backgroundPage = new ChromePipeBackgroundPage() | true | class window.ChromePipeBackgroundPage
memory: {}
STORED_KEYS: ['PI:KEY:<KEY>END_PI']
constructor: ->
@listen()
@updateMemory()
updateMemory: (callback = null) ->
@chromeStorageGet @STORED_KEYS, (answers) =>
for key in @STORED_KEYS
@memory[key] = answers[key] if key of answers
callback?()
chromeStorageGet: (variables, callback) ->
chrome.storage.local.get variables, (answers) => callback?(answers)
chromeStorageSet: (variables, callback) ->
@memory[key] = value for key, value of variables
chrome.storage.local.set variables, => callback?()
listen: ->
chrome.runtime.onMessage.addListener (request, sender, sendResponse) =>
handler = =>
Utils.log "Remote received from #{sender.tab.url} (#{sender.tab.incognito && 'incognito'}): #{JSON.stringify request}"
switch request.command
when 'copy'
Utils.putInClipboard(request.payload.text)
sendResponse()
when 'paste'
sendResponse(text: Utils.getFromClipboard())
when 'coffeeCompile'
try
sendResponse(javascript: CoffeeScript.compile(request.payload.coffeescript))
catch e
sendResponse(errors: e)
when 'getHistory'
sendResponse(commands: @memory.commands || [])
when 'recordCommand'
@updateMemory =>
@memory.commands ||= []
@memory.commands.unshift(request.payload)
@memory.commands = @memory.commands[0..50]
@chromeStorageSet({ commands: @memory.commands }, -> sendResponse({}))
else sendResponse(errors: "unknown command")
setTimeout handler, 10
true # Return true to indicate async message passing: http://developer.chrome.com/extensions/runtime#event-onMessage
errorResponse: (callback, message) ->
Utils.log message
callback errors: [message]
window.backgroundPage = new ChromePipeBackgroundPage() |
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999129176139832,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/form-toggle.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.
class @FormToggle
constructor: ->
addEventListener 'turbolinks:load', @sync
$(document).on 'change', '.js-form-toggle--input', @onChange
onChange: (e) =>
@toggle e.currentTarget
sync: =>
inputs = document.getElementsByClassName('js-form-toggle--input')
@toggle(input) for input in inputs
toggle: (input) ->
id = input.dataset.formToggleId
show = input.checked
$form = $(".js-form-toggle--form[data-form-toggle-id='#{id}']")
direction = if show then 'Down' else 'Up'
$form.stop()["slide#{direction}"]()
| 202923 | # 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.
class @FormToggle
constructor: ->
addEventListener 'turbolinks:load', @sync
$(document).on 'change', '.js-form-toggle--input', @onChange
onChange: (e) =>
@toggle e.currentTarget
sync: =>
inputs = document.getElementsByClassName('js-form-toggle--input')
@toggle(input) for input in inputs
toggle: (input) ->
id = input.dataset.formToggleId
show = input.checked
$form = $(".js-form-toggle--form[data-form-toggle-id='#{id}']")
direction = if show then 'Down' else 'Up'
$form.stop()["slide#{direction}"]()
| 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.
class @FormToggle
constructor: ->
addEventListener 'turbolinks:load', @sync
$(document).on 'change', '.js-form-toggle--input', @onChange
onChange: (e) =>
@toggle e.currentTarget
sync: =>
inputs = document.getElementsByClassName('js-form-toggle--input')
@toggle(input) for input in inputs
toggle: (input) ->
id = input.dataset.formToggleId
show = input.checked
$form = $(".js-form-toggle--form[data-form-toggle-id='#{id}']")
direction = if show then 'Down' else 'Up'
$form.stop()["slide#{direction}"]()
|
[
{
"context": "nerdobot's console\"\n version: '0.1'\n authors: ['Álvaro Cuesta']\n",
"end": 727,
"score": 0.9998816847801208,
"start": 714,
"tag": "NAME",
"value": "Álvaro Cuesta"
}
] | plugins/spy.coffee | alvaro-cuesta/nerdobot | 2 | util = require '../lib/util'
clc = require 'cli-color'
module.exports = ->
@events.on 'message', (from, message, recipient) ->
msgIn = if recipient? then clc.yellowBright recipient else clc.redBright 'QUERY'
console.log "[#{msgIn}] #{clc.bold from.nick}: #{util.escape message}"
@events.on 'notice', (from, message, recipient) ->
msgIn = clc.yellowBright recipient ? 'NOTICE'
fromNick = from?.nick ? 'SERVER'
prefix = (clc.bold.magentaBright '{') + msgIn + (clc.bold.magentaBright '}')
console.log clc.magenta "#{prefix} #{clc.bold fromNick}: #{util.escape message}"
name: 'Spy'
description: "See channel and private messages in nerdobot's console"
version: '0.1'
authors: ['Álvaro Cuesta']
| 166423 | util = require '../lib/util'
clc = require 'cli-color'
module.exports = ->
@events.on 'message', (from, message, recipient) ->
msgIn = if recipient? then clc.yellowBright recipient else clc.redBright 'QUERY'
console.log "[#{msgIn}] #{clc.bold from.nick}: #{util.escape message}"
@events.on 'notice', (from, message, recipient) ->
msgIn = clc.yellowBright recipient ? 'NOTICE'
fromNick = from?.nick ? 'SERVER'
prefix = (clc.bold.magentaBright '{') + msgIn + (clc.bold.magentaBright '}')
console.log clc.magenta "#{prefix} #{clc.bold fromNick}: #{util.escape message}"
name: 'Spy'
description: "See channel and private messages in nerdobot's console"
version: '0.1'
authors: ['<NAME>']
| true | util = require '../lib/util'
clc = require 'cli-color'
module.exports = ->
@events.on 'message', (from, message, recipient) ->
msgIn = if recipient? then clc.yellowBright recipient else clc.redBright 'QUERY'
console.log "[#{msgIn}] #{clc.bold from.nick}: #{util.escape message}"
@events.on 'notice', (from, message, recipient) ->
msgIn = clc.yellowBright recipient ? 'NOTICE'
fromNick = from?.nick ? 'SERVER'
prefix = (clc.bold.magentaBright '{') + msgIn + (clc.bold.magentaBright '}')
console.log clc.magenta "#{prefix} #{clc.bold fromNick}: #{util.escape message}"
name: 'Spy'
description: "See channel and private messages in nerdobot's console"
version: '0.1'
authors: ['PI:NAME:<NAME>END_PI']
|
[
{
"context": " 'works of an object', ->\n obj = {id:1, name: 'John', desc: 'blah'}\n keys = processor.keys(obj)\n ",
"end": 143,
"score": 0.9997710585594177,
"start": 139,
"tag": "NAME",
"value": "John"
}
] | spec/keys_spec.coffee | craigerm/jeep-cli | 0 | processor= require '../src/processor'
_ = require 'underscore'
describe 'keys', ->
it 'works of an object', ->
obj = {id:1, name: 'John', desc: 'blah'}
keys = processor.keys(obj)
expect(keys.length).toBe(3)
expect(_.difference(keys,['id','name','desc']).length).toBe(0)
| 149495 | processor= require '../src/processor'
_ = require 'underscore'
describe 'keys', ->
it 'works of an object', ->
obj = {id:1, name: '<NAME>', desc: 'blah'}
keys = processor.keys(obj)
expect(keys.length).toBe(3)
expect(_.difference(keys,['id','name','desc']).length).toBe(0)
| true | processor= require '../src/processor'
_ = require 'underscore'
describe 'keys', ->
it 'works of an object', ->
obj = {id:1, name: 'PI:NAME:<NAME>END_PI', desc: 'blah'}
keys = processor.keys(obj)
expect(keys.length).toBe(3)
expect(_.difference(keys,['id','name','desc']).length).toBe(0)
|
[
{
"context": "rrent_lang: ['en']\n\n\tmode: 'production'\n\n\ttoken: 'mehowthe'\n\n\tdefault: 'usr/demo_ppt'\n\n}\n",
"end": 106,
"score": 0.9874961376190186,
"start": 98,
"tag": "PASSWORD",
"value": "mehowthe"
}
] | var/config.coffee | mehowthe/typescript-presentation | 0 | NB.conf = {
port: 80
load_langs: ['en']
current_lang: ['en']
mode: 'production'
token: 'mehowthe'
default: 'usr/demo_ppt'
}
| 207844 | NB.conf = {
port: 80
load_langs: ['en']
current_lang: ['en']
mode: 'production'
token: '<PASSWORD>'
default: 'usr/demo_ppt'
}
| true | NB.conf = {
port: 80
load_langs: ['en']
current_lang: ['en']
mode: 'production'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
default: 'usr/demo_ppt'
}
|
[
{
"context": " newPassword : null\n confirmPassword : null\n\n validate: (attributes) ->\n errors = {}\n",
"end": 319,
"score": 0.5052781105041504,
"start": 315,
"tag": "PASSWORD",
"value": "null"
}
] | source/TextUml/Scripts/application/models/changepassword.coffee | marufsiddiqui/textuml-dotnet | 1 | define (require) ->
_ = require 'underscore'
Backbone = require 'backbone'
validation = require './validation'
class ChangePassword extends Backbone.Model
url: -> '/api/passwords/change'
defaults: ->
oldPassword : null
newPassword : null
confirmPassword : null
validate: (attributes) ->
errors = {}
unless attributes.oldPassword
validation.addError errors, 'oldPassword', 'Old password is required.'
if attributes.newPassword
unless validation.isValidPasswordLength attributes.newPassword
validation.addError errors, 'newPassword', 'New password length ' +
'must be between 6 to 64 characters.'
else
validation.addError errors, 'newPassword', 'New password is required.'
if attributes.confirmPassword
if attributes.newPassword and
attributes.confirmPassword isnt attributes.newPassword
validation.addError errors, 'confirmPassword', 'New password and ' +
'confirmation password do not match.'
else
validation.addError errors, 'confirmPassword', 'Confirm password is ' +
'required.'
if _(errors).isEmpty() then undefined else errors | 81023 | define (require) ->
_ = require 'underscore'
Backbone = require 'backbone'
validation = require './validation'
class ChangePassword extends Backbone.Model
url: -> '/api/passwords/change'
defaults: ->
oldPassword : null
newPassword : null
confirmPassword : <PASSWORD>
validate: (attributes) ->
errors = {}
unless attributes.oldPassword
validation.addError errors, 'oldPassword', 'Old password is required.'
if attributes.newPassword
unless validation.isValidPasswordLength attributes.newPassword
validation.addError errors, 'newPassword', 'New password length ' +
'must be between 6 to 64 characters.'
else
validation.addError errors, 'newPassword', 'New password is required.'
if attributes.confirmPassword
if attributes.newPassword and
attributes.confirmPassword isnt attributes.newPassword
validation.addError errors, 'confirmPassword', 'New password and ' +
'confirmation password do not match.'
else
validation.addError errors, 'confirmPassword', 'Confirm password is ' +
'required.'
if _(errors).isEmpty() then undefined else errors | true | define (require) ->
_ = require 'underscore'
Backbone = require 'backbone'
validation = require './validation'
class ChangePassword extends Backbone.Model
url: -> '/api/passwords/change'
defaults: ->
oldPassword : null
newPassword : null
confirmPassword : PI:PASSWORD:<PASSWORD>END_PI
validate: (attributes) ->
errors = {}
unless attributes.oldPassword
validation.addError errors, 'oldPassword', 'Old password is required.'
if attributes.newPassword
unless validation.isValidPasswordLength attributes.newPassword
validation.addError errors, 'newPassword', 'New password length ' +
'must be between 6 to 64 characters.'
else
validation.addError errors, 'newPassword', 'New password is required.'
if attributes.confirmPassword
if attributes.newPassword and
attributes.confirmPassword isnt attributes.newPassword
validation.addError errors, 'confirmPassword', 'New password and ' +
'confirmation password do not match.'
else
validation.addError errors, 'confirmPassword', 'Confirm password is ' +
'required.'
if _(errors).isEmpty() then undefined else errors |
[
{
"context": " isStatic, isRight: @side is 'right'}\n key: \"drawer-#{@key}\"\n style:\n display: if windowSize",
"end": 4393,
"score": 0.9768126606941223,
"start": 4384,
"tag": "KEY",
"value": "drawer-#{"
},
{
"context": " isRight: @side is 'right'}\n key: \"dr... | src/components/drawer/index.coffee | FreeRoamApp/free-roam | 14 | z = require 'zorium'
colors = require '../../colors'
config = require '../../config'
if window?
IScroll = require 'iscroll/build/iscroll-lite-snap-zoom.js'
require './index.styl'
MAX_OVERLAY_OPACITY = 0.5
module.exports = class Drawer
constructor: ({@model, @isOpen, @onOpen, @onClose, @side, @key, @isStatic}) ->
@transformProperty = @model.window.getTransformProperty()
@side ?= 'left'
@key ?= 'nav'
@isStatic ?= @model.window.getBreakpoint().map (breakpoint) ->
breakpoint in ['desktop']
.publishReplay(1).refCount()
@state = z.state
isOpen: @isOpen
isStatic: @isStatic
windowSize: @model.window.getSize()
breakpoint: @model.window.getBreakpoint()
appBarHeight: @model.window.getAppBarHeightVal()
drawerWidth: @model.window.getDrawerWidth()
afterMount: (@$$el) =>
{drawerWidth} = @state.getValue()
onStaticChange = (isStatic) =>
# sometimes get cannot get length of undefined for gotopage with this
setTimeout =>
if not @iScrollContainer and not isStatic
checkIsReady = =>
$$container = @$$el
if $$container and $$container.clientWidth
@initIScroll $$container
else
setTimeout checkIsReady, 1000
checkIsReady()
else if @iScrollContainer and isStatic
@open 0
@iScrollContainer?.destroy()
delete @iScrollContainer
@disposable?.unsubscribe()
, 0
@isStaticDisposable = @isStatic.subscribe onStaticChange
beforeUnmount: =>
@iScrollContainer?.destroy()
delete @iScrollContainer
@disposable?.unsubscribe()
@isStaticDisposable?.unsubscribe()
close: (animationLengthMs = 500) =>
try
if @side is 'right'
@iScrollContainer.goToPage 0, 0, animationLengthMs
else
@iScrollContainer.goToPage 1, 0, animationLengthMs
catch err
console.log 'caught err', err
open: (animationLengthMs = 500) =>
try
if @side is 'right'
@iScrollContainer.goToPage 1, 0, animationLengthMs
else
@iScrollContainer.goToPage 0, 0, animationLengthMs
catch err
console.log 'caught err', err
initIScroll: ($$container) =>
{drawerWidth} = @state.getValue()
@iScrollContainer = new IScroll $$container, {
scrollX: true
scrollY: false
eventPassthrough: true
bounce: false
snap: '.tab'
deceleration: 0.002
}
# the scroll listener in IScroll (iscroll-probe.js) is really slow
updateOpacity = =>
if @side is 'right'
opacity = -1 * @iScrollContainer.x / drawerWidth
else
opacity = 1 + @iScrollContainer.x / drawerWidth
@$$overlay.style.opacity = opacity * MAX_OVERLAY_OPACITY
@disposable = @isOpen.subscribe (isOpen) =>
if isOpen then @open() else @close()
@$$overlay = @$$el.querySelector '.overlay-tab'
updateOpacity()
isScrolling = false
@iScrollContainer.on 'scrollStart', =>
isScrolling = true
@$$overlay = @$$el.querySelector '.overlay-tab'
update = ->
updateOpacity()
if isScrolling
window.requestAnimationFrame update
update()
updateOpacity()
@iScrollContainer.on 'scrollEnd', =>
{isOpen} = @state.getValue()
isScrolling = false
openPage = if @side is 'right' then 1 else 0
newIsOpen = @iScrollContainer.currentPage.pageX is openPage
# landing on new tab
if newIsOpen and not isOpen
@onOpen()
else if not newIsOpen and isOpen
@onClose()
render: ({$content, hasAppBar}) =>
{isOpen, windowSize, appBarHeight,
drawerWidth, isStatic, breakpoint} = @state.getValue()
# HACK: isStatic is null on first render for some reason
isStatic ?= breakpoint is 'desktop'
height = windowSize.height
if hasAppBar and isStatic
height -= appBarHeight
x = if @side is 'right' or isStatic then 0 else -drawerWidth
$drawerTab =
z '.drawer-tab.tab',
z '.drawer', {
style:
width: "#{drawerWidth}px"
},
$content
$overlayTab =
z '.overlay-tab.tab', {
onclick: =>
@onClose()
},
z '.grip'
z '.z-drawer', {
className: z.classKebab {isOpen, isStatic, isRight: @side is 'right'}
key: "drawer-#{@key}"
style:
display: if windowSize.width then 'block' else 'none'
height: "#{height}px"
width: if not isStatic \
then '100%'
else "#{drawerWidth}px"
},
z '.drawer-wrapper', {
style:
width: "#{drawerWidth + windowSize.width}px"
# make sure drawer is hidden before js laods
"#{@transformProperty}":
"translate(#{x}px, 0px) translateZ(0px)"
},
if @side is 'right'
[$overlayTab, $drawerTab]
else
[$drawerTab, $overlayTab]
| 111204 | z = require 'zorium'
colors = require '../../colors'
config = require '../../config'
if window?
IScroll = require 'iscroll/build/iscroll-lite-snap-zoom.js'
require './index.styl'
MAX_OVERLAY_OPACITY = 0.5
module.exports = class Drawer
constructor: ({@model, @isOpen, @onOpen, @onClose, @side, @key, @isStatic}) ->
@transformProperty = @model.window.getTransformProperty()
@side ?= 'left'
@key ?= 'nav'
@isStatic ?= @model.window.getBreakpoint().map (breakpoint) ->
breakpoint in ['desktop']
.publishReplay(1).refCount()
@state = z.state
isOpen: @isOpen
isStatic: @isStatic
windowSize: @model.window.getSize()
breakpoint: @model.window.getBreakpoint()
appBarHeight: @model.window.getAppBarHeightVal()
drawerWidth: @model.window.getDrawerWidth()
afterMount: (@$$el) =>
{drawerWidth} = @state.getValue()
onStaticChange = (isStatic) =>
# sometimes get cannot get length of undefined for gotopage with this
setTimeout =>
if not @iScrollContainer and not isStatic
checkIsReady = =>
$$container = @$$el
if $$container and $$container.clientWidth
@initIScroll $$container
else
setTimeout checkIsReady, 1000
checkIsReady()
else if @iScrollContainer and isStatic
@open 0
@iScrollContainer?.destroy()
delete @iScrollContainer
@disposable?.unsubscribe()
, 0
@isStaticDisposable = @isStatic.subscribe onStaticChange
beforeUnmount: =>
@iScrollContainer?.destroy()
delete @iScrollContainer
@disposable?.unsubscribe()
@isStaticDisposable?.unsubscribe()
close: (animationLengthMs = 500) =>
try
if @side is 'right'
@iScrollContainer.goToPage 0, 0, animationLengthMs
else
@iScrollContainer.goToPage 1, 0, animationLengthMs
catch err
console.log 'caught err', err
open: (animationLengthMs = 500) =>
try
if @side is 'right'
@iScrollContainer.goToPage 1, 0, animationLengthMs
else
@iScrollContainer.goToPage 0, 0, animationLengthMs
catch err
console.log 'caught err', err
initIScroll: ($$container) =>
{drawerWidth} = @state.getValue()
@iScrollContainer = new IScroll $$container, {
scrollX: true
scrollY: false
eventPassthrough: true
bounce: false
snap: '.tab'
deceleration: 0.002
}
# the scroll listener in IScroll (iscroll-probe.js) is really slow
updateOpacity = =>
if @side is 'right'
opacity = -1 * @iScrollContainer.x / drawerWidth
else
opacity = 1 + @iScrollContainer.x / drawerWidth
@$$overlay.style.opacity = opacity * MAX_OVERLAY_OPACITY
@disposable = @isOpen.subscribe (isOpen) =>
if isOpen then @open() else @close()
@$$overlay = @$$el.querySelector '.overlay-tab'
updateOpacity()
isScrolling = false
@iScrollContainer.on 'scrollStart', =>
isScrolling = true
@$$overlay = @$$el.querySelector '.overlay-tab'
update = ->
updateOpacity()
if isScrolling
window.requestAnimationFrame update
update()
updateOpacity()
@iScrollContainer.on 'scrollEnd', =>
{isOpen} = @state.getValue()
isScrolling = false
openPage = if @side is 'right' then 1 else 0
newIsOpen = @iScrollContainer.currentPage.pageX is openPage
# landing on new tab
if newIsOpen and not isOpen
@onOpen()
else if not newIsOpen and isOpen
@onClose()
render: ({$content, hasAppBar}) =>
{isOpen, windowSize, appBarHeight,
drawerWidth, isStatic, breakpoint} = @state.getValue()
# HACK: isStatic is null on first render for some reason
isStatic ?= breakpoint is 'desktop'
height = windowSize.height
if hasAppBar and isStatic
height -= appBarHeight
x = if @side is 'right' or isStatic then 0 else -drawerWidth
$drawerTab =
z '.drawer-tab.tab',
z '.drawer', {
style:
width: "#{drawerWidth}px"
},
$content
$overlayTab =
z '.overlay-tab.tab', {
onclick: =>
@onClose()
},
z '.grip'
z '.z-drawer', {
className: z.classKebab {isOpen, isStatic, isRight: @side is 'right'}
key: "<KEY>@<KEY>}"
style:
display: if windowSize.width then 'block' else 'none'
height: "#{height}px"
width: if not isStatic \
then '100%'
else "#{drawerWidth}px"
},
z '.drawer-wrapper', {
style:
width: "#{drawerWidth + windowSize.width}px"
# make sure drawer is hidden before js laods
"#{@transformProperty}":
"translate(#{x}px, 0px) translateZ(0px)"
},
if @side is 'right'
[$overlayTab, $drawerTab]
else
[$drawerTab, $overlayTab]
| true | z = require 'zorium'
colors = require '../../colors'
config = require '../../config'
if window?
IScroll = require 'iscroll/build/iscroll-lite-snap-zoom.js'
require './index.styl'
MAX_OVERLAY_OPACITY = 0.5
module.exports = class Drawer
constructor: ({@model, @isOpen, @onOpen, @onClose, @side, @key, @isStatic}) ->
@transformProperty = @model.window.getTransformProperty()
@side ?= 'left'
@key ?= 'nav'
@isStatic ?= @model.window.getBreakpoint().map (breakpoint) ->
breakpoint in ['desktop']
.publishReplay(1).refCount()
@state = z.state
isOpen: @isOpen
isStatic: @isStatic
windowSize: @model.window.getSize()
breakpoint: @model.window.getBreakpoint()
appBarHeight: @model.window.getAppBarHeightVal()
drawerWidth: @model.window.getDrawerWidth()
afterMount: (@$$el) =>
{drawerWidth} = @state.getValue()
onStaticChange = (isStatic) =>
# sometimes get cannot get length of undefined for gotopage with this
setTimeout =>
if not @iScrollContainer and not isStatic
checkIsReady = =>
$$container = @$$el
if $$container and $$container.clientWidth
@initIScroll $$container
else
setTimeout checkIsReady, 1000
checkIsReady()
else if @iScrollContainer and isStatic
@open 0
@iScrollContainer?.destroy()
delete @iScrollContainer
@disposable?.unsubscribe()
, 0
@isStaticDisposable = @isStatic.subscribe onStaticChange
beforeUnmount: =>
@iScrollContainer?.destroy()
delete @iScrollContainer
@disposable?.unsubscribe()
@isStaticDisposable?.unsubscribe()
close: (animationLengthMs = 500) =>
try
if @side is 'right'
@iScrollContainer.goToPage 0, 0, animationLengthMs
else
@iScrollContainer.goToPage 1, 0, animationLengthMs
catch err
console.log 'caught err', err
open: (animationLengthMs = 500) =>
try
if @side is 'right'
@iScrollContainer.goToPage 1, 0, animationLengthMs
else
@iScrollContainer.goToPage 0, 0, animationLengthMs
catch err
console.log 'caught err', err
initIScroll: ($$container) =>
{drawerWidth} = @state.getValue()
@iScrollContainer = new IScroll $$container, {
scrollX: true
scrollY: false
eventPassthrough: true
bounce: false
snap: '.tab'
deceleration: 0.002
}
# the scroll listener in IScroll (iscroll-probe.js) is really slow
updateOpacity = =>
if @side is 'right'
opacity = -1 * @iScrollContainer.x / drawerWidth
else
opacity = 1 + @iScrollContainer.x / drawerWidth
@$$overlay.style.opacity = opacity * MAX_OVERLAY_OPACITY
@disposable = @isOpen.subscribe (isOpen) =>
if isOpen then @open() else @close()
@$$overlay = @$$el.querySelector '.overlay-tab'
updateOpacity()
isScrolling = false
@iScrollContainer.on 'scrollStart', =>
isScrolling = true
@$$overlay = @$$el.querySelector '.overlay-tab'
update = ->
updateOpacity()
if isScrolling
window.requestAnimationFrame update
update()
updateOpacity()
@iScrollContainer.on 'scrollEnd', =>
{isOpen} = @state.getValue()
isScrolling = false
openPage = if @side is 'right' then 1 else 0
newIsOpen = @iScrollContainer.currentPage.pageX is openPage
# landing on new tab
if newIsOpen and not isOpen
@onOpen()
else if not newIsOpen and isOpen
@onClose()
render: ({$content, hasAppBar}) =>
{isOpen, windowSize, appBarHeight,
drawerWidth, isStatic, breakpoint} = @state.getValue()
# HACK: isStatic is null on first render for some reason
isStatic ?= breakpoint is 'desktop'
height = windowSize.height
if hasAppBar and isStatic
height -= appBarHeight
x = if @side is 'right' or isStatic then 0 else -drawerWidth
$drawerTab =
z '.drawer-tab.tab',
z '.drawer', {
style:
width: "#{drawerWidth}px"
},
$content
$overlayTab =
z '.overlay-tab.tab', {
onclick: =>
@onClose()
},
z '.grip'
z '.z-drawer', {
className: z.classKebab {isOpen, isStatic, isRight: @side is 'right'}
key: "PI:KEY:<KEY>END_PI@PI:KEY:<KEY>END_PI}"
style:
display: if windowSize.width then 'block' else 'none'
height: "#{height}px"
width: if not isStatic \
then '100%'
else "#{drawerWidth}px"
},
z '.drawer-wrapper', {
style:
width: "#{drawerWidth + windowSize.width}px"
# make sure drawer is hidden before js laods
"#{@transformProperty}":
"translate(#{x}px, 0px) translateZ(0px)"
},
if @side is 'right'
[$overlayTab, $drawerTab]
else
[$drawerTab, $overlayTab]
|
[
{
"context": "###\n@Author: Kristinita\n@Date:\t 2017-05-02 11:44:00\n@Last Modified time: ",
"end": 23,
"score": 0.999780535697937,
"start": 13,
"tag": "NAME",
"value": "Kristinita"
},
{
"context": "Usage — post of plugin author:\nhttps://github.com/noeldelgado/gemini-scrollbar/issu... | themes/sashapelican/static/coffee/Gemini/gemini-scrollbar.coffee | Kristinita/--- | 6 | ###
@Author: Kristinita
@Date: 2017-05-02 11:44:00
@Last Modified time: 2020-09-13 08:49:55
###
####################
# gemini-scrollbar #
####################
###
[PURPOSE] Custom scrollbar instead of native body scrollbar:
https://noeldelgado.github.io/gemini-scrollbar/
[INFO] Usage — post of plugin author:
https://github.com/noeldelgado/gemini-scrollbar/issues/46
###
# [REQUIRED] Don’t delete this line! Scrolling will be incorrect.
internals = {}
internals.initialize = ->
internals.scrollbar = new GeminiScrollbar(
###
[INFO] “querySelector” method:
https://www.w3schools.com/jsref/met_document_queryselector.asp
###
element: document.querySelector('body')
autoshow: true
###
[NOTE] Force Gemini for correct scrollbar displaying in mobile devices
https://github.com/noeldelgado/gemini-scrollbar#options
###
forceGemini: true).create()
internals.scrollingElement = internals.scrollbar.getViewElement()
internals.scrollToHash()
# [DECLINED] I migrated to Defer.js
# ###
# [INFO] JQuery Lazy support:
# https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103
# ###
# $('.SashaLazy').Lazy
# appendScroll: $(internals.scrollbar.getViewElement())
# ###
# [INFO] Run Gemini “update” method:
# https://github.com/noeldelgado/gemini-scrollbar#basic-methods
# http://jquery.eisbehr.de/lazy/example_callback-functions
# https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388
# ###
# afterLoad: ->
# internals.scrollbar.update()
# return
# [INFO] Wildfire comments lazy loading:
# https://stackoverflow.com/a/63869810/5951529
# [LEARN][JQUERY_LAZY] Create custom loader:
# https://github.com/dkern/jquery.lazy#custom-content-loaders
# $('.wildfire_thread').Lazy
# KiraComments: (element, response) ->
# $.getScript 'https://cdn.jsdelivr.net/npm/wildfire/dist/wildfire.auto.js', ->
# response true
# return
# return
# # [FIXME] Duplicate code
# appendScroll: $(internals.scrollbar.getViewElement())
# afterLoad: ->
# internals.scrollbar.update()
# return
# return
internals.handleOrientationChange = ->
internals.scrollbar.update()
internals.scrollToHash()
return
internals.scrollToHash = ->
###
[INFO] Get hash — part of URL after “#” symbol:
https://javascript.ru/window-location
###
hash = location.hash
###
[INFO] Decode URL hash, example:
“#%D0%9A%D0%B8%D1%80%D0%B0” → “#Кира”
https://www.w3schools.com/jsref/jsref_decodeuri.asp
[NOTE] Decoding required for some browsers as Chrome and Opera;
without decoding links with anchors will not open;
scrollbar will move to top of page:
https://stackoverflow.com/a/48218282/5951529
###
dechash = decodeURI(hash)
if dechash
###
[INFO] Replacing to id, example:
“#Кира” → “<a id="Кира">”
###
element = document.getElementById(dechash.replace('#', ''))
if element
# [INFO] Scroll to id
internals.scrollingElement.scrollTo 0, element.offsetTop
return
# [INFO] Listeners
window.onload = internals.initialize
window.onorientationchange = internals.handleOrientationChange
| 115060 | ###
@Author: <NAME>
@Date: 2017-05-02 11:44:00
@Last Modified time: 2020-09-13 08:49:55
###
####################
# gemini-scrollbar #
####################
###
[PURPOSE] Custom scrollbar instead of native body scrollbar:
https://noeldelgado.github.io/gemini-scrollbar/
[INFO] Usage — post of plugin author:
https://github.com/noeldelgado/gemini-scrollbar/issues/46
###
# [REQUIRED] Don’t delete this line! Scrolling will be incorrect.
internals = {}
internals.initialize = ->
internals.scrollbar = new GeminiScrollbar(
###
[INFO] “querySelector” method:
https://www.w3schools.com/jsref/met_document_queryselector.asp
###
element: document.querySelector('body')
autoshow: true
###
[NOTE] Force Gemini for correct scrollbar displaying in mobile devices
https://github.com/noeldelgado/gemini-scrollbar#options
###
forceGemini: true).create()
internals.scrollingElement = internals.scrollbar.getViewElement()
internals.scrollToHash()
# [DECLINED] I migrated to Defer.js
# ###
# [INFO] JQuery Lazy support:
# https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103
# ###
# $('.SashaLazy').Lazy
# appendScroll: $(internals.scrollbar.getViewElement())
# ###
# [INFO] Run Gemini “update” method:
# https://github.com/noeldelgado/gemini-scrollbar#basic-methods
# http://jquery.eisbehr.de/lazy/example_callback-functions
# https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388
# ###
# afterLoad: ->
# internals.scrollbar.update()
# return
# [INFO] Wildfire comments lazy loading:
# https://stackoverflow.com/a/63869810/5951529
# [LEARN][JQUERY_LAZY] Create custom loader:
# https://github.com/dkern/jquery.lazy#custom-content-loaders
# $('.wildfire_thread').Lazy
# KiraComments: (element, response) ->
# $.getScript 'https://cdn.jsdelivr.net/npm/wildfire/dist/wildfire.auto.js', ->
# response true
# return
# return
# # [FIXME] Duplicate code
# appendScroll: $(internals.scrollbar.getViewElement())
# afterLoad: ->
# internals.scrollbar.update()
# return
# return
internals.handleOrientationChange = ->
internals.scrollbar.update()
internals.scrollToHash()
return
internals.scrollToHash = ->
###
[INFO] Get hash — part of URL after “#” symbol:
https://javascript.ru/window-location
###
hash = location.hash
###
[INFO] Decode URL hash, example:
“#%D0%9A%D0%B8%D1%80%D0%B0” → “#Кира”
https://www.w3schools.com/jsref/jsref_decodeuri.asp
[NOTE] Decoding required for some browsers as Chrome and Opera;
without decoding links with anchors will not open;
scrollbar will move to top of page:
https://stackoverflow.com/a/48218282/5951529
###
dechash = decodeURI(hash)
if dechash
###
[INFO] Replacing to id, example:
“#Кира” → “<a id="Кира">”
###
element = document.getElementById(dechash.replace('#', ''))
if element
# [INFO] Scroll to id
internals.scrollingElement.scrollTo 0, element.offsetTop
return
# [INFO] Listeners
window.onload = internals.initialize
window.onorientationchange = internals.handleOrientationChange
| true | ###
@Author: PI:NAME:<NAME>END_PI
@Date: 2017-05-02 11:44:00
@Last Modified time: 2020-09-13 08:49:55
###
####################
# gemini-scrollbar #
####################
###
[PURPOSE] Custom scrollbar instead of native body scrollbar:
https://noeldelgado.github.io/gemini-scrollbar/
[INFO] Usage — post of plugin author:
https://github.com/noeldelgado/gemini-scrollbar/issues/46
###
# [REQUIRED] Don’t delete this line! Scrolling will be incorrect.
internals = {}
internals.initialize = ->
internals.scrollbar = new GeminiScrollbar(
###
[INFO] “querySelector” method:
https://www.w3schools.com/jsref/met_document_queryselector.asp
###
element: document.querySelector('body')
autoshow: true
###
[NOTE] Force Gemini for correct scrollbar displaying in mobile devices
https://github.com/noeldelgado/gemini-scrollbar#options
###
forceGemini: true).create()
internals.scrollingElement = internals.scrollbar.getViewElement()
internals.scrollToHash()
# [DECLINED] I migrated to Defer.js
# ###
# [INFO] JQuery Lazy support:
# https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103
# ###
# $('.SashaLazy').Lazy
# appendScroll: $(internals.scrollbar.getViewElement())
# ###
# [INFO] Run Gemini “update” method:
# https://github.com/noeldelgado/gemini-scrollbar#basic-methods
# http://jquery.eisbehr.de/lazy/example_callback-functions
# https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388
# ###
# afterLoad: ->
# internals.scrollbar.update()
# return
# [INFO] Wildfire comments lazy loading:
# https://stackoverflow.com/a/63869810/5951529
# [LEARN][JQUERY_LAZY] Create custom loader:
# https://github.com/dkern/jquery.lazy#custom-content-loaders
# $('.wildfire_thread').Lazy
# KiraComments: (element, response) ->
# $.getScript 'https://cdn.jsdelivr.net/npm/wildfire/dist/wildfire.auto.js', ->
# response true
# return
# return
# # [FIXME] Duplicate code
# appendScroll: $(internals.scrollbar.getViewElement())
# afterLoad: ->
# internals.scrollbar.update()
# return
# return
internals.handleOrientationChange = ->
internals.scrollbar.update()
internals.scrollToHash()
return
internals.scrollToHash = ->
###
[INFO] Get hash — part of URL after “#” symbol:
https://javascript.ru/window-location
###
hash = location.hash
###
[INFO] Decode URL hash, example:
“#%D0%9A%D0%B8%D1%80%D0%B0” → “#Кира”
https://www.w3schools.com/jsref/jsref_decodeuri.asp
[NOTE] Decoding required for some browsers as Chrome and Opera;
without decoding links with anchors will not open;
scrollbar will move to top of page:
https://stackoverflow.com/a/48218282/5951529
###
dechash = decodeURI(hash)
if dechash
###
[INFO] Replacing to id, example:
“#Кира” → “<a id="Кира">”
###
element = document.getElementById(dechash.replace('#', ''))
if element
# [INFO] Scroll to id
internals.scrollingElement.scrollTo 0, element.offsetTop
return
# [INFO] Listeners
window.onload = internals.initialize
window.onorientationchange = internals.handleOrientationChange
|
[
{
"context": "xample !idle-resetpassword \"local-server/Danret\" \"my new awesome password\"\n * @category IRC Commands\n * @pack",
"end": 12417,
"score": 0.9927581548690796,
"start": 12394,
"tag": "PASSWORD",
"value": "my new awesome password"
},
{
"context": "\" x,y\n... | ext/kurea/IdleLandsModule.coffee | Oipo/IdleLandsOld | 0 | BotManager = require("../../../../core/BotManager").BotManager
_ = require "lodash"
_.str = require "underscore.string"
Q = require "q"
finder = require "fs-finder"
watch = require "node-watch"
c = require "irc-colors"
idlePath = __dirname + "/../../src"
try
LogManager = require "../../src/system/managers/LogManager"
catch
console.log "haha" # This is just here to not break stuff
module.exports = (Module) ->
class IdleModule extends Module
shortName: "IdleLands"
helpText:
default: "Nothing special here."
serverBots: {}
serverChannels: {}
currentlyInChannels: []
users: []
userIdentsList: []
userIdents: {}
topic: "Welcome to Idliathlia! New player? Join ##idlebot & read http://new.idle.land | Got feedback? Send it to http://git.idle.land | Check your stats: http://idle.land/"
colorMap:
"player.name": c.bold
"event.partyName": c.underline
"event.partyMembers": c.bold
"event.player": c.bold
"event.damage": c.red
"event.gold": c.olive
"event.realGold": c.olive
"event.shopGold": c.olive
"event.xp": c.green
"event.realXp": c.green
"event.percentXp": c.green
"event.item.newbie": c.brown
"event.item.Normal": c.gray
"event.item.basic": c.gray
"event.item.pro": c.purple
"event.item.idle": c.bold.rainbow
"event.item.godly": c.white.bgblack
"event.item.custom": c.white.bgblue
"event.item.guardian": c.cyan
"event.finditem.scoreboost": c.bold
"event.finditem.perceived": c.bold
"event.finditem.real": c.bold
"event.blessItem.stat": c.bold
"event.blessItem.value": c.bold
"event.flip.stat": c.bold
"event.flip.value": c.bold
"event.enchant.boost": c.bold
"event.enchant.stat": c.bold
"event.tinker.boost": c.bold
"event.tinker.stat": c.bold
"event.transfer.destination": c.bold
"event.transfer.from": c.bold
"player.class": c.italic
"player.level": c.bold
"stats.hp": c.red
"stats.mp": c.blue
"stats.sp": c.olive
"damage.hp": c.red
"damage.mp": c.blue
"spell.turns": c.bold
"spell.spellName": c.underline
"event.casterName": c.bold
"event.spellName": c.underline
"event.targetName": c.bold
"event.achievement": c.underline
"event.guildName": c.underline
loadIdle: (stopIfLoaded) ->
@buildUserList()
if not (stopIfLoaded and @idleLoaded)
@idleLoaded = true
try
@IdleWrapper.load()
@IdleWrapper.api.game.handlers.broadcastHandler @sendMessageToAll, @
@IdleWrapper.api.game.handlers.colorMap @colorMap
@IdleWrapper.api.game.handlers.playerLoadHandler @getAllUsers
catch e
console.error e
addServerChannel: (bot, server, channel) =>
IdleModule::serverBots[server] = bot if not IdleModule::serverBots[server]
if server of @serverChannels
@serverChannels[server].push channel
else
@serverChannels[server] = [channel]
@serverChannels[server] = _.uniq @serverChannels[server]
removeServerChannel: (bot, server, channel) =>
@serverChannels[server] = _.without @serverChannels[server], channel
getAllUsers: =>
@userIdentsList
hashServerChannel: (server, channel) ->
"#{server}/#{channel}"
broadcast: (message) ->
for server, channels of @serverChannels
for channel in channels
IdleModule::serverBots[server]?.say channel, message if (@hashServerChannel server, channel) in @currentlyInChannels
sendMessageToAll: (message) ->
@broadcast message
generateIdent: (server, username) ->
return null if not username
"#{server}##{username}"
addUser: (ident, suppress) ->
return if not ident
@userIdentsList.push ident
@userIdentsList = _.uniq @userIdentsList
@IdleWrapper.api.player.auth.login ident, suppress
removeUser: (ident) ->
return if not ident or not _.contains @userIdentsList, ident
@userIdentsList = _.without @userIdentsList, ident
@IdleWrapper.api.player.auth.logout ident
buildUserList: ->
for server, channels of @serverChannels
for channel in channels
bot = IdleModule::serverBots[server]
if bot.conn.chans[channel]
chanUsers = bot.getUsers channel
chanUsers = _.forEach chanUsers, (user) =>
#whois changes the prototype such that it breaks for subsequent calls even if the server changes
#so we're doing nick-based auth for now
bot.userManager.getUsername user, (e, username) =>
username = user if (not username) and bot.config.auth is "nick"
ident = @generateIdent server, username
@addUser ident, yes
loadOldChannels: ->
Q.when @db.databaseReady, (db) =>
db.find {active: true}, (e, docs) =>
console.error e if e
docs.each (e, doc) =>
return if not doc
bot = BotManager.botHash[doc.server]
return if not bot
@addServerChannel bot, doc.server, doc.channel
beginGameLoop: ->
DELAY_INTERVAL = 10000
doActionPerMember = (arr, action) ->
for i in [0...arr.length]
setTimeout (player, i) ->
action player
, DELAY_INTERVAL/arr.length*i, arr[i]
@interval = setInterval =>
doActionPerMember @userIdentsList, (identifier) => @IdleWrapper.api.player.takeTurn identifier, no
, DELAY_INTERVAL
watchIdleFiles: ->
loadFunction = _.debounce (=>@loadIdle()), 100
watch idlePath, {}, () ->
files = finder.from(idlePath).findFiles("*.coffee")
_.forEach files, (file) ->
delete require.cache[file]
loadFunction()
initialize: ->
@loadIdle()
@loadOldChannels()
@beginGameLoop()
@watchIdleFiles()
isInChannel: (bot, nick) ->
isIn = no
for channel in @serverChannels[bot.config.server]
chanUsers = bot.getUsers channel
isIn = true if _.contains chanUsers, nick
isIn
constructor: (moduleManager) ->
super moduleManager
@IdleWrapper = require("../../src/system/accessibility/ExternalWrapper")()
@db = @newDatabase 'channels'
try
@logManager = new LogManager()
logger = @logManager.getLogger "kureaModule"
logger.warn "This is actually a success"
catch
console.log "useless catch to satisfy stuff." #it's here so that if it doesn't work, it won't break.
@on "join", (bot, channel, sender) =>
if bot.config.nick is sender
setTimeout =>
return if channel isnt '#idlebot'
bot.send 'TOPIC', channel, @topic
bot.send 'MODE', channel, '+m'
@currentlyInChannels.push @hashServerChannel bot.config.server, channel
@buildUserList()
, 1000
return
bot.userManager.getUsername {user: sender, bot: bot}, (e, username) =>
ident = @generateIdent bot.config.server, username
@addUser ident
@userIdents[@generateIdent bot.config.server, sender] = ident
@on "part", (bot, channel, sender) =>
return if channel isnt '#idlebot'
bot.userManager.getUsername {user: sender, bot: bot}, (e, username) =>
ident = @generateIdent bot.config.server, username
@removeUser ident
@userIdents[@generateIdent bot.config.server, sender] = ident
@on "quit", (bot, sender) =>
if bot.config.auth is "nickserv"
@removeUser @generateIdent bot.config.server, @userIdents[@generateIdent bot.config.server, sender]
delete @userIdents[@generateIdent bot.config.server, sender]
else if bot.config.auth is "nick"
@removeUser @generateIdent bot.config.server, sender
@on "nick", (bot, oldNick, newNick) =>
if bot.config.auth is "nickserv"
@userIdents[@generateIdent bot.config.server, newNick] = @userIdents[@generateIdent bot.config.server, oldNick]
delete @userIdents[@generateIdent bot.config.server, oldNick]
else if bot.config.auth is "nick"
@removeUser @generateIdent bot.config.server, oldNick
@addUser @generateIdent bot.config.server, newNick
`/**
* Start the game on the server this is run on. Used when linking new IRC networks.
*
* @name idle-start
* @syntax !idle-start
* @gmOnly
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-start", "idle.game.start", (origin) =>
[channel, server] = [origin.channel, origin.bot.config.server]
@db.update { channel: channel, server: server },
{ channel: channel, server: server, active: true },
{ upsert: true }, ->
@addServerChannel origin.bot, server, channel
@broadcast "#{origin.bot.config.server}/#{origin.channel} has joined the Idle Lands network!"
`/**
* Stop the game server on the server this is run on.
*
* @name idle-stop
* @syntax !idle-stop
* @gmOnly
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-stop", "idle.game.stop", (origin, route) =>
[channel, server] = [origin.channel, origin.bot.config.server]
@db.update { channel: channel, server: server },
{ channel: channel, server: server, active: false },
{ upsert: true }, ->
@broadcast "#{origin.bot.config.server}/#{origin.channel} has left the Idle Lands network!"
@removeServerChannel origin.bot, server, channel
registerCommand = (origin, route) =>
[bot, name] = [origin.bot, route.params.name]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to services play this game!"
return
if not @isInChannel bot, username
@reply origin, "You must be in the channel to actually play, duh!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.auth.register
identifier: identifier
name: name
).then (res) =>
@reply origin, res.message
`/**
* Register a new character on this IRC network.
*
* @name idle-register
* @syntax !idle-register Character Name
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-register :name", registerCommand
@addRoute "register :name", registerCommand
`/**
* Run any event for any logged in player.
*
* @name idle-event
* @syntax !idle-event "Player Name" eventType
* @gmOnly
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-event ":player" :event', "idle.game.gm", (origin, route) =>
[player, event] = [route.params.player, route.params.event]
@IdleWrapper.api.gm.event.single player, event
`/**
* Run a global event (cataclysms, PvP battles, etc).
*
* @name idle-globalevent
* @gmOnly
* @syntax !idle-globalevent eventType
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-globalevent :event?', "idle.game.gm", (origin, route) =>
event = route.params.event
@IdleWrapper.api.gm.event.global event
`/**
* Reset a password for a player.
*
* @name idle-resetpassword
* @gmOnly
* @syntax !idle-resetpassword "identifier" "newPassword"
* @example !idle-resetpassword "local-server/Danret" "my new awesome password"
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-resetpassword ":identifier" ":newPassword"', "idle.game.gm", (origin, route) =>
try
[identifier, password] = [route.params.identifier, route.params.newPassword]
if @gameInstance and @gameInstance.playerManager
@gameInstance.playerManager.storePasswordFor identifier, password
else
@IdleWrapper.api.gm.data.setPassword identifier, password
catch e
logger = @logManager.getLogger "kureaModule"
logger.error "!idle-resetpassword error", {e}
`/**
* Change a players identifier.
*
* @name idle-changeident
* @gmOnly
* @syntax !idle-changeident "identifier" "newIdentifier"
* @example !idle-changeident "local-server/Danret" "local-server/AlsoDanret"
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-changeident ":identifier" ":newIdentifier"', "idle.game.gm", (origin, route) =>
[identifier, newIdentifier] = [route.params.identifier, route.params.newIdentifier]
@gameInstance.api.gm.status.identifierChange identifier, newIdentifier
`/**
* Force the bot to update IdleLands and reboot.
*
* @name idle-update
* @gmOnly
* @syntax !idle-update
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-update', 'idle.game.gm', =>
@IdleWrapper.api.gm.data.update()
`/**
* Ban a player.
*
* @name idle-ban
* @gmOnly
* @syntax !idle-ban Player Name
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-ban :playerName", "idle.game.gm", (origin, route) =>
[name] = [route.params.playerName]
@IdleWrapper.api.gm.status.ban name
`/**
* Unban a player.
*
* @name idle-unban
* @gmOnly
* @syntax !idle-unban Player Name
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-unban :playerName", "idle.game.gm", (origin, route) =>
[name] = [route.params.playerName]
@IdleWrapper.api.gm.status.unban name
`/**
* Teleport a player to a given location.
*
* @name idle-teleportloc
* @gmOnly
* @syntax !idle-teleportloc "Player Name" locationId
* @example !idle-teleport "Swirly" start
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-teleportloc ":playerName" :location', "idle.game.gm", (origin, route) =>
[name, location] = [route.params.playerName, route.params.location]
@IdleWrapper.api.gm.teleport.location.single name, location
`/**
* Teleport a player to a given set of coordinates.
*
* @name idle-teleport
* @gmOnly
* @syntax !idle-teleport "Player Name" "Map Name" x,y
* @example !idle-teleport "Swirly" "Norkos" 10,10
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-teleport ":playerName" ":map" :x,:y', "idle.game.gm", (origin, route) =>
[name, map, x, y] = [route.params.playerName, route.params.map, route.params.x, route.params.y]
x = parseInt x
y = parseInt y
@IdleWrapper.api.gm.teleport.map.single name, map, x, y
`/**
* Teleport all players to a given location.
*
* @name idle-massteleportloc
* @gmOnly
* @syntax !idle-massteleportloc locationId
* @example !idle-massteleportloc norkos
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-massteleportloc :location", "idle.game.gm", (origin, route) =>
[location] = [route.params.location]
@IdleWrapper.api.gm.teleport.map.location location
`/**
* Teleport all players to a given set of coordinates.
*
* @name idle-massteleport
* @gmOnly
* @syntax !idle-massteleport "Map Name" x,y
* @example !idle-massteleport "Norkos" 10,10
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-massteleport ":map" :x,:y', "idle.game.gm", (origin, route) =>
[map, x, y] = [route.params.map, route.params.x, route.params.y]
x = parseInt x
y = parseInt y
@IdleWrapper.api.gm.teleport.map.mass map, x, y
`/**
* Generate a custom item for a player.
*
* @name idle-itemgen
* @gmOnly
* @syntax !idle-itemgen "Player Name" itemSlot "name" stats
* @example !idle-itemgen "Swirly" mainhand "Epic Cheat" luck=10000
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-itemgen ":player" :type *', "idle.game.gm", (origin, route) =>
[playerName, itemType, itemData] = [route.params.player, route.params.type, route.splats[0]]
@IdleWrapper.api.gm.player.createItem playerName, itemType, itemData
`/**
* Give a player some gold.
*
* @name idle-goldgive
* @gmOnly
* @syntax !idle-goldgive "Player Name" gold
* @example !idle-goldgive "Swirly" 10000
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-goldgive ":player" :gold', "idle.game.gm", (origin, route) =>
[playerName, gold] = [route.params.player, route.params.gold]
@IdleWrapper.api.gm.player.giveGold playerName, parseInt gold
`/**
* Modify your personality settings.
*
* @name idle-personality
* @syntax !idle-personality add|remove Personality
* @example !idle-personality add ScaredOfTheDark
* @example !idle-personality remove ScaredOfTheDark
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-personality :action(add|remove) :personality", (origin, route) =>
[bot, action, personality] = [origin.bot, route.params.action, route.params.personality]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your personality settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.personality[action] identifier, personality)
.then (res) =>
@reply origin, res.message
stringFunc = (origin, route) =>
[bot, action, sType, string] = [origin.bot, route.params.action, route.params.type, route.params.string]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your string settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.string[action] identifier, sType, string)
.then (res) =>
@reply origin, res.message
`/**
* Modify your string settings.
*
* @name idle-string
* @syntax !idle-string add|remove type [stringData]
* @example !idle-string set web This is my web string
* @example !idle-string remove web
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-string :action(set) :type :string", stringFunc
@addRoute "idle-string :action(remove) :type", stringFunc
pushbulletFunc = (origin, route) =>
[bot, action, string] = [origin.bot, route.params.action, route.params.string]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your string settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pushbullet[action] identifier, string)
.then (res) =>
@reply origin, res.message
`/**
* Modify your PushBullet settings.
*
* @name idle-pushbullet
* @syntax !idle-pushbullet set|remove [pushbulletApiKey]
* @example !idle-pushbullet set ThisIsAnAPIKey
* @example !idle-pushbullet remove
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pushbullet :action(set) :string", pushbulletFunc
@addRoute "idle-pushbullet :action(remove)", pushbulletFunc
`/**
* Modify your priority point settings.
*
* @name idle-priority
* @syntax !idle-priority add|remove stat points
* @example !idle-priority add str 1
* @example !idle-priority remove str 1
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-priority :action(add|remove) :stat :points", (origin, route) =>
[bot, action, stat, points] = [origin.bot, route.params.action, route.params.stat, route.params.points]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your priority settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.priority[action] identifier, stat, points)
.then (res) =>
@reply origin, res.message
`/**
* Modify your gender settings.
*
* @name idle-gender
* @syntax !idle-gender newGender
* @example !idle-gender male
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-gender :newGender", (origin, route) =>
gender = route.params.newGender
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your gender settings!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.gender.set identifier, gender
.then (ret) =>
@reply origin, ret.message
`/**
* Teleport yourself to somewhere you've been before.
*
* @name idle-teleportself
* @syntax !idle-teleportself townCname
* @example !idle-teleportself norkos
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-teleportself :newLoc", (origin, route) =>
newLoc = route.params.newLoc
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to teleport yourself!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.action.teleport identifier, newLoc
.then (ret) =>
@reply origin, ret.message
`/**
* Modify your title.
*
* @name idle-title
* @syntax !idle-title newTitle
* @example !idle-title Entitled
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-title :newTitle", (origin, route) =>
newTitle = route.params.newTitle
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your title settings!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.title.set identifier, newTitle
.then (ret) =>
@reply origin, ret.message
`/**
* Modify your inventory.
*
* @name idle-inventory
* @syntax !idle-inventory swap|sell|add slot
* @example !idle-inventory add mainhand
* @example !idle-inventory swap 0
* @example !idle-inventory sell 0
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-inventory :action(swap|sell|add) :slot", (origin, route) =>
[action, slot] = [route.params.action, route.params.slot]
slot = parseInt slot if action isnt "add"
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your inventory settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.overflow[action] identifier, slot)
.then (res) =>
@reply origin, res.message
`/**
* Purchase something from a nearby shop (if you're near one, of course).
*
* @name idle-shop
* @syntax !idle-shop buy slot
* @example !idle-shop buy 0
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-shop buy :slot", (origin, route) =>
[slot] = [route.params.slot]
slot = parseInt slot
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to buy from a shop!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.shop.buy identifier, slot)
.then (res) =>
@reply origin, res.message
`/**
* Create a new guild. Costs 100k.
*
* @name Guild Creation
* @syntax !idle-guild create guildName
* @example !idle-guild create Leet Admin Hax
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild create :guildName", (origin, route) =>
[guildName] = [route.params.guildName]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to create a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.create identifier, guildName)
.then (res) =>
@reply origin, res.message
`/**
* Manage guild members.
*
* @name Guild Management
* @syntax !idle-guild invite|promote|demote|kick Player Name
* @example !idle-guild invite Swirly
* @example !idle-guild promote Swirly
* @example !idle-guild demote Swirly
* @example !idle-guild kick Swirly
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild :action(invite|promote|demote|kick) :playerName", (origin, route) =>
[action, playerName] = [route.params.action, route.params.playerName]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild[action] identifier, playerName)
.then (res) =>
@reply origin, res.message
`/**
* Manage your guild's current location.
*
* @name idle-guild move
* @syntax !idle-guild move newLoc
* @example !idle-guild move Vocalnus
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild move :newLoc", (origin, route) =>
[newLoc] = [route.params.newLoc]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.move identifier, newLoc)
.then (res) =>
@reply origin, res.message
`/**
* Construct a new building in your Guild Hall.
*
* @name idle-guild construct
* @syntax !idle-guild construct building slot
* @example !idle-guild construct GuildHall 0
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild construct :building :slot", (origin, route) =>
[building, slot] = [route.params.building, parseInt route.params.slot]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.construct identifier, building, slot)
.then (res) =>
@reply origin, res.message
`/**
* Upgrade a building in your guild hall.
*
* @name idle-guild upgrade
* @syntax !idle-guild upgrade building
* @example !idle-guild upgrade GuildHall
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild upgrade :building", (origin, route) =>
[building] = [route.params.building]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.upgrade identifier, building)
.then (res) =>
@reply origin, res.message
`/**
* Set a specific property for a building in your Guild Hall.
*
* @name idle-guild setprop
* @syntax !idle-guild setprop building prop "value"
* @example !idle-guild setprop Mascot MascotID "Skeleton"
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild setprop :building :prop \":value\"", (origin, route) =>
[building, prop, value] = [route.params.building, route.params.prop, route.params.value]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.setProperty identifier, building, prop, value)
.then (res) =>
@reply origin, res.message
`/**
* Manage your guild status.
*
* @name Guild Status
* @syntax !idle-guild leave|disband
* @example !idle-guild leave
* @example !idle-guild disband
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild :action(leave|disband)", (origin, route) =>
[action] = [route.params.action]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage your guild status!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild[action] identifier)
.then (res) =>
@reply origin, res.message
`/**
* Manage your guild invitations.
*
* @name Guild Invitations
* @syntax !idle-guild manage-invite accept|deny guild name
* @example !idle-guild manage-invite accept Leet Admin Hax
* @example !idle-guild manage-invite deny Leet Admin Hax
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild manage-invite :action(accept|deny) :guildName", (origin, route) =>
[action, guildName] = [route.params.action, route.params.guildName]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to join a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
accepted = action is "accept"
(@IdleWrapper.api.player.guild.manageInvite identifier, accepted, guildName)
.then (res) =>
@reply origin, res.message
`/**
* Donate gold to your guild.
*
* @name Guild Donation
* @syntax !idle-guild donate gold
* @example !idle-guild donate 1337
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild donate :gold", (origin, route) =>
[gold] = [route.params.gold]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to donate gold!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.donate identifier, parseInt gold
.then (res) =>
@reply origin, res.message
`/**
* Purchase a buff for your guild.
*
* @name Guild Buff
* @syntax !idle-guild buff "type" tier
* @example !idle-guild buff "Strength" 1
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild buff \":type\" :tier", (origin, route) =>
[type, tier] = [route.params.type, route.params.tier]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to buy a guild buff!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.buff identifier, type, parseInt tier
.then (res) =>
@reply origin, res.message
`/**
* Adjust your guilds tax rate (anywhere from 0-15%). Only guild leaders can set this.
*
* @name idle-guild tax
* @syntax !idle-guild tax taxPercent
* @example !idle-guild tax 15
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild tax :taxPercent", (origin, route) =>
[taxPercent] = [route.params.taxPercent]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage your guilds taxes!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.tax.whole identifier, parseInt taxPercent
.then (res) =>
@reply origin, res.message
`/**
* Adjust your personal tax rate to pay to your guild (anywhere from 0-85%).
*
* @name idle-guild selftax
* @syntax !idle-guild selftax taxPercent
* @example !idle-guild selftax 15
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild selftax :taxPercent", (origin, route) =>
[taxPercent] = [route.params.taxPercent]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage your taxes!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.tax.self identifier, parseInt taxPercent
.then (res) =>
@reply origin, res.message
`/**
* Manage your password, or authenticate.
*
* @name idle-secure
* @syntax !idle-secure setPassword|authenticate password
* @example !idle-secure setPassword my super secret password
* @example !idle-secure authenticate my super secret password
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-secure :action(setPassword|authenticate) :password", (origin, route) =>
[action, password] = [route.params.action, route.params.password]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set a password!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.auth[action] identifier, password)
.then (res) =>
@reply origin, res.message
`/**
* Buy a new pet.
*
* @name idle-pet buy
* @syntax !idle-pet buy "type" "name" "attr1" "attr2"
* @example !idle-pet buy "Pet Rock" "Rocky" "a top hat" "a monocle"
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pet buy \":petType\" \":petName\" \":attr1\" \":attr2\"", (origin, route) =>
[type, name, attr1, attr2] = [route.params.petType, route.params.petName, route.params.attr1, route.params.attr2]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to buy a pet!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet.buy identifier, type, name, attr1, attr2)
.then (res) =>
@reply origin, res.message
`/**
* Set smart options for your pet.
*
* @name idle-pet set
* @syntax !idle-pet set option on|off
* @example !idle-pet set smartSell on
* @example !idle-pet set smartSelf on
* @example !idle-pet set smartEquip off
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pet set :option :value", (origin, route) =>
[option, value] = [route.params.option, route.params.value is "on"]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change pet settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet.setOption identifier, option, value)
.then (res) =>
@reply origin, res.message
`/**
* Manage your pets items, upgrade their stats, and feed them gold!
*
* @name idle-pet action
* @syntax !idle-pet action actionType actionParameter
* @syntax !idle-pet action upgrade <stat> (maxLevel | inventory | goldStorage | battleJoinPercent | itemFindTimeDuration | itemSellMultiplier | itemFindBonus | itemFindRangeMultiplier | xpPerGold | maxItemScore)
* @syntax !idle-pet action giveEquipment itemSlot
* @syntax !idle-pet action sellEquipment itemSlot
* @syntax !idle-pet action takeEquipment itemSlot
* @syntax !idle-pet action changeClass newClass
* @syntax !idle-pet action equipItem itemSlot
* @syntax !idle-pet action unequipItem itemUid
* @syntax !idle-pet action swapToPet petId
* @syntax !idle-pet action feed
* @syntax !idle-pet action takeGold
* @example !idle-pet action upgrade maxLevel
* @example !idle-pet action giveEquipment 0
* @example !idle-pet action takeEquipment 1
* @example !idle-pet action sellEquipment 2
* @example !idle-pet action changeClass Generalist
* @example !idle-pet action equipItem 3
* @example !idle-pet action unequipItem 1418554184641
* @example !idle-pet action swapToPet 1418503227081
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pet action :action(feed|takeGold)", (origin, route) =>
[action] = [route.params.action]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change pet settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet[action]? identifier)
.then (res) =>
@reply origin, res.message
@addRoute "idle-pet action :action :param", (origin, route) =>
[action, param] = [route.params.action, route.params.param]
param = parseInt param if not (action in ["upgrade", "changeClass"])
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change pet settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet[action]? identifier, param)?.then (res) =>
@reply origin, res.message
`/**
* Manage custom data for the game.
*
* @name idle-customdata
* @gmOnly
* @syntax !idle-customdata <command> (init | update)
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-customdata :action", "idle.game.gm", (origin, route) =>
[action] = [route.params.action]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage custom data!"
return
@IdleWrapper.api.gm.custom[action]?()
`/**
* Manage moderators for managing custom data for the game.
*
* @name idle-custommod
* @gmOnly
* @syntax !idle-custommod "<user-identifier>" status
* @example !idle-custommod "local-server/Danret" 1
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-custommod \":identifier\" :mod", "idle.game.gm", (origin, route) =>
[identifier, modStatus] = [route.params.identifier, parseInt route.params.mod]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage custom mods!"
return
@IdleWrapper.api.gm.custom.modModerator identifier, modStatus
`/**
* Set a logger's level.
*
* @name idle-setloggerlevel
* @gmOnly
* @syntax !idle-setloggerlevel name level
* @example !idle-setloggerlevel battle debug
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-setloggerlevel \":name\" :level", "idle.game.gm", (origin, route) =>
[name, level] = [route.params.name, route.params.level]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set log levels!"
return
@IdleWrapper.api.gm.log.setLoggerLevel name, level
`/**
* Clear a log.
*
* @name idle-clearlog
* @gmOnly
* @syntax !idle-clearlog name
* @example !idle-clearlog battle
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-clearlog \":name\"", "idle.game.gm", (origin, route) =>
[name] = [route.params.name]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set log levels!"
return
@IdleWrapper.api.gm.log.clearLog name
`/**
* Clear all log.
*
* @name idle-clearalllogs
* @gmOnly
* @syntax !idle-clearalllogs
* @example !idle-clearalllogs
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-clearalllogs", "idle.game.gm", (origin, route) =>
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set log levels!"
return
@IdleWrapper.api.gm.log.clearAllLogs()
@initialize()
#@on "notice", (bot, sender, channel, message) =>
# return if not sender or sender in ['InfoServ','*','AUTH']
# console.log "notice from #{sender}|#{channel} on #{bot.config.server}: #{message}"
destroy: ->
clearInterval @interval
delete @db
super()
IdleModule
| 111000 | BotManager = require("../../../../core/BotManager").BotManager
_ = require "lodash"
_.str = require "underscore.string"
Q = require "q"
finder = require "fs-finder"
watch = require "node-watch"
c = require "irc-colors"
idlePath = __dirname + "/../../src"
try
LogManager = require "../../src/system/managers/LogManager"
catch
console.log "haha" # This is just here to not break stuff
module.exports = (Module) ->
class IdleModule extends Module
shortName: "IdleLands"
helpText:
default: "Nothing special here."
serverBots: {}
serverChannels: {}
currentlyInChannels: []
users: []
userIdentsList: []
userIdents: {}
topic: "Welcome to Idliathlia! New player? Join ##idlebot & read http://new.idle.land | Got feedback? Send it to http://git.idle.land | Check your stats: http://idle.land/"
colorMap:
"player.name": c.bold
"event.partyName": c.underline
"event.partyMembers": c.bold
"event.player": c.bold
"event.damage": c.red
"event.gold": c.olive
"event.realGold": c.olive
"event.shopGold": c.olive
"event.xp": c.green
"event.realXp": c.green
"event.percentXp": c.green
"event.item.newbie": c.brown
"event.item.Normal": c.gray
"event.item.basic": c.gray
"event.item.pro": c.purple
"event.item.idle": c.bold.rainbow
"event.item.godly": c.white.bgblack
"event.item.custom": c.white.bgblue
"event.item.guardian": c.cyan
"event.finditem.scoreboost": c.bold
"event.finditem.perceived": c.bold
"event.finditem.real": c.bold
"event.blessItem.stat": c.bold
"event.blessItem.value": c.bold
"event.flip.stat": c.bold
"event.flip.value": c.bold
"event.enchant.boost": c.bold
"event.enchant.stat": c.bold
"event.tinker.boost": c.bold
"event.tinker.stat": c.bold
"event.transfer.destination": c.bold
"event.transfer.from": c.bold
"player.class": c.italic
"player.level": c.bold
"stats.hp": c.red
"stats.mp": c.blue
"stats.sp": c.olive
"damage.hp": c.red
"damage.mp": c.blue
"spell.turns": c.bold
"spell.spellName": c.underline
"event.casterName": c.bold
"event.spellName": c.underline
"event.targetName": c.bold
"event.achievement": c.underline
"event.guildName": c.underline
loadIdle: (stopIfLoaded) ->
@buildUserList()
if not (stopIfLoaded and @idleLoaded)
@idleLoaded = true
try
@IdleWrapper.load()
@IdleWrapper.api.game.handlers.broadcastHandler @sendMessageToAll, @
@IdleWrapper.api.game.handlers.colorMap @colorMap
@IdleWrapper.api.game.handlers.playerLoadHandler @getAllUsers
catch e
console.error e
addServerChannel: (bot, server, channel) =>
IdleModule::serverBots[server] = bot if not IdleModule::serverBots[server]
if server of @serverChannels
@serverChannels[server].push channel
else
@serverChannels[server] = [channel]
@serverChannels[server] = _.uniq @serverChannels[server]
removeServerChannel: (bot, server, channel) =>
@serverChannels[server] = _.without @serverChannels[server], channel
getAllUsers: =>
@userIdentsList
hashServerChannel: (server, channel) ->
"#{server}/#{channel}"
broadcast: (message) ->
for server, channels of @serverChannels
for channel in channels
IdleModule::serverBots[server]?.say channel, message if (@hashServerChannel server, channel) in @currentlyInChannels
sendMessageToAll: (message) ->
@broadcast message
generateIdent: (server, username) ->
return null if not username
"#{server}##{username}"
addUser: (ident, suppress) ->
return if not ident
@userIdentsList.push ident
@userIdentsList = _.uniq @userIdentsList
@IdleWrapper.api.player.auth.login ident, suppress
removeUser: (ident) ->
return if not ident or not _.contains @userIdentsList, ident
@userIdentsList = _.without @userIdentsList, ident
@IdleWrapper.api.player.auth.logout ident
buildUserList: ->
for server, channels of @serverChannels
for channel in channels
bot = IdleModule::serverBots[server]
if bot.conn.chans[channel]
chanUsers = bot.getUsers channel
chanUsers = _.forEach chanUsers, (user) =>
#whois changes the prototype such that it breaks for subsequent calls even if the server changes
#so we're doing nick-based auth for now
bot.userManager.getUsername user, (e, username) =>
username = user if (not username) and bot.config.auth is "nick"
ident = @generateIdent server, username
@addUser ident, yes
loadOldChannels: ->
Q.when @db.databaseReady, (db) =>
db.find {active: true}, (e, docs) =>
console.error e if e
docs.each (e, doc) =>
return if not doc
bot = BotManager.botHash[doc.server]
return if not bot
@addServerChannel bot, doc.server, doc.channel
beginGameLoop: ->
DELAY_INTERVAL = 10000
doActionPerMember = (arr, action) ->
for i in [0...arr.length]
setTimeout (player, i) ->
action player
, DELAY_INTERVAL/arr.length*i, arr[i]
@interval = setInterval =>
doActionPerMember @userIdentsList, (identifier) => @IdleWrapper.api.player.takeTurn identifier, no
, DELAY_INTERVAL
watchIdleFiles: ->
loadFunction = _.debounce (=>@loadIdle()), 100
watch idlePath, {}, () ->
files = finder.from(idlePath).findFiles("*.coffee")
_.forEach files, (file) ->
delete require.cache[file]
loadFunction()
initialize: ->
@loadIdle()
@loadOldChannels()
@beginGameLoop()
@watchIdleFiles()
isInChannel: (bot, nick) ->
isIn = no
for channel in @serverChannels[bot.config.server]
chanUsers = bot.getUsers channel
isIn = true if _.contains chanUsers, nick
isIn
constructor: (moduleManager) ->
super moduleManager
@IdleWrapper = require("../../src/system/accessibility/ExternalWrapper")()
@db = @newDatabase 'channels'
try
@logManager = new LogManager()
logger = @logManager.getLogger "kureaModule"
logger.warn "This is actually a success"
catch
console.log "useless catch to satisfy stuff." #it's here so that if it doesn't work, it won't break.
@on "join", (bot, channel, sender) =>
if bot.config.nick is sender
setTimeout =>
return if channel isnt '#idlebot'
bot.send 'TOPIC', channel, @topic
bot.send 'MODE', channel, '+m'
@currentlyInChannels.push @hashServerChannel bot.config.server, channel
@buildUserList()
, 1000
return
bot.userManager.getUsername {user: sender, bot: bot}, (e, username) =>
ident = @generateIdent bot.config.server, username
@addUser ident
@userIdents[@generateIdent bot.config.server, sender] = ident
@on "part", (bot, channel, sender) =>
return if channel isnt '#idlebot'
bot.userManager.getUsername {user: sender, bot: bot}, (e, username) =>
ident = @generateIdent bot.config.server, username
@removeUser ident
@userIdents[@generateIdent bot.config.server, sender] = ident
@on "quit", (bot, sender) =>
if bot.config.auth is "nickserv"
@removeUser @generateIdent bot.config.server, @userIdents[@generateIdent bot.config.server, sender]
delete @userIdents[@generateIdent bot.config.server, sender]
else if bot.config.auth is "nick"
@removeUser @generateIdent bot.config.server, sender
@on "nick", (bot, oldNick, newNick) =>
if bot.config.auth is "nickserv"
@userIdents[@generateIdent bot.config.server, newNick] = @userIdents[@generateIdent bot.config.server, oldNick]
delete @userIdents[@generateIdent bot.config.server, oldNick]
else if bot.config.auth is "nick"
@removeUser @generateIdent bot.config.server, oldNick
@addUser @generateIdent bot.config.server, newNick
`/**
* Start the game on the server this is run on. Used when linking new IRC networks.
*
* @name idle-start
* @syntax !idle-start
* @gmOnly
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-start", "idle.game.start", (origin) =>
[channel, server] = [origin.channel, origin.bot.config.server]
@db.update { channel: channel, server: server },
{ channel: channel, server: server, active: true },
{ upsert: true }, ->
@addServerChannel origin.bot, server, channel
@broadcast "#{origin.bot.config.server}/#{origin.channel} has joined the Idle Lands network!"
`/**
* Stop the game server on the server this is run on.
*
* @name idle-stop
* @syntax !idle-stop
* @gmOnly
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-stop", "idle.game.stop", (origin, route) =>
[channel, server] = [origin.channel, origin.bot.config.server]
@db.update { channel: channel, server: server },
{ channel: channel, server: server, active: false },
{ upsert: true }, ->
@broadcast "#{origin.bot.config.server}/#{origin.channel} has left the Idle Lands network!"
@removeServerChannel origin.bot, server, channel
registerCommand = (origin, route) =>
[bot, name] = [origin.bot, route.params.name]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to services play this game!"
return
if not @isInChannel bot, username
@reply origin, "You must be in the channel to actually play, duh!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.auth.register
identifier: identifier
name: name
).then (res) =>
@reply origin, res.message
`/**
* Register a new character on this IRC network.
*
* @name idle-register
* @syntax !idle-register Character Name
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-register :name", registerCommand
@addRoute "register :name", registerCommand
`/**
* Run any event for any logged in player.
*
* @name idle-event
* @syntax !idle-event "Player Name" eventType
* @gmOnly
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-event ":player" :event', "idle.game.gm", (origin, route) =>
[player, event] = [route.params.player, route.params.event]
@IdleWrapper.api.gm.event.single player, event
`/**
* Run a global event (cataclysms, PvP battles, etc).
*
* @name idle-globalevent
* @gmOnly
* @syntax !idle-globalevent eventType
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-globalevent :event?', "idle.game.gm", (origin, route) =>
event = route.params.event
@IdleWrapper.api.gm.event.global event
`/**
* Reset a password for a player.
*
* @name idle-resetpassword
* @gmOnly
* @syntax !idle-resetpassword "identifier" "newPassword"
* @example !idle-resetpassword "local-server/Danret" "<PASSWORD>"
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-resetpassword ":identifier" ":newPassword"', "idle.game.gm", (origin, route) =>
try
[identifier, password] = [route.params.identifier, route.params.newPassword]
if @gameInstance and @gameInstance.playerManager
@gameInstance.playerManager.storePasswordFor identifier, password
else
@IdleWrapper.api.gm.data.setPassword identifier, password
catch e
logger = @logManager.getLogger "kureaModule"
logger.error "!idle-resetpassword error", {e}
`/**
* Change a players identifier.
*
* @name idle-changeident
* @gmOnly
* @syntax !idle-changeident "identifier" "newIdentifier"
* @example !idle-changeident "local-server/Danret" "local-server/AlsoDanret"
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-changeident ":identifier" ":newIdentifier"', "idle.game.gm", (origin, route) =>
[identifier, newIdentifier] = [route.params.identifier, route.params.newIdentifier]
@gameInstance.api.gm.status.identifierChange identifier, newIdentifier
`/**
* Force the bot to update IdleLands and reboot.
*
* @name idle-update
* @gmOnly
* @syntax !idle-update
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-update', 'idle.game.gm', =>
@IdleWrapper.api.gm.data.update()
`/**
* Ban a player.
*
* @name idle-ban
* @gmOnly
* @syntax !idle-ban Player Name
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-ban :playerName", "idle.game.gm", (origin, route) =>
[name] = [route.params.playerName]
@IdleWrapper.api.gm.status.ban name
`/**
* Unban a player.
*
* @name idle-unban
* @gmOnly
* @syntax !idle-unban Player Name
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-unban :playerName", "idle.game.gm", (origin, route) =>
[name] = [route.params.playerName]
@IdleWrapper.api.gm.status.unban name
`/**
* Teleport a player to a given location.
*
* @name idle-teleportloc
* @gmOnly
* @syntax !idle-teleportloc "Player Name" locationId
* @example !idle-teleport "Swirly" start
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-teleportloc ":playerName" :location', "idle.game.gm", (origin, route) =>
[name, location] = [route.params.playerName, route.params.location]
@IdleWrapper.api.gm.teleport.location.single name, location
`/**
* Teleport a player to a given set of coordinates.
*
* @name idle-teleport
* @gmOnly
* @syntax !idle-teleport "Player Name" "Map Name" x,y
* @example !idle-teleport "Swirly" "<NAME>orkos" 10,10
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-teleport ":playerName" ":map" :x,:y', "idle.game.gm", (origin, route) =>
[name, map, x, y] = [route.params.playerName, route.params.map, route.params.x, route.params.y]
x = parseInt x
y = parseInt y
@IdleWrapper.api.gm.teleport.map.single name, map, x, y
`/**
* Teleport all players to a given location.
*
* @name idle-massteleportloc
* @gmOnly
* @syntax !idle-massteleportloc locationId
* @example !idle-massteleportloc norkos
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-massteleportloc :location", "idle.game.gm", (origin, route) =>
[location] = [route.params.location]
@IdleWrapper.api.gm.teleport.map.location location
`/**
* Teleport all players to a given set of coordinates.
*
* @name idle-massteleport
* @gmOnly
* @syntax !idle-massteleport "Map Name" x,y
* @example !idle-massteleport "Norkos" 10,10
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-massteleport ":map" :x,:y', "idle.game.gm", (origin, route) =>
[map, x, y] = [route.params.map, route.params.x, route.params.y]
x = parseInt x
y = parseInt y
@IdleWrapper.api.gm.teleport.map.mass map, x, y
`/**
* Generate a custom item for a player.
*
* @name idle-itemgen
* @gmOnly
* @syntax !idle-itemgen "Player Name" itemSlot "name" stats
* @example !idle-itemgen "Swirly" mainhand "Epic Cheat" luck=10000
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-itemgen ":player" :type *', "idle.game.gm", (origin, route) =>
[playerName, itemType, itemData] = [route.params.player, route.params.type, route.splats[0]]
@IdleWrapper.api.gm.player.createItem playerName, itemType, itemData
`/**
* Give a player some gold.
*
* @name idle-goldgive
* @gmOnly
* @syntax !idle-goldgive "Player Name" gold
* @example !idle-goldgive "Swirly" 10000
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-goldgive ":player" :gold', "idle.game.gm", (origin, route) =>
[playerName, gold] = [route.params.player, route.params.gold]
@IdleWrapper.api.gm.player.giveGold playerName, parseInt gold
`/**
* Modify your personality settings.
*
* @name idle-personality
* @syntax !idle-personality add|remove Personality
* @example !idle-personality add ScaredOfTheDark
* @example !idle-personality remove ScaredOfTheDark
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-personality :action(add|remove) :personality", (origin, route) =>
[bot, action, personality] = [origin.bot, route.params.action, route.params.personality]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your personality settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.personality[action] identifier, personality)
.then (res) =>
@reply origin, res.message
stringFunc = (origin, route) =>
[bot, action, sType, string] = [origin.bot, route.params.action, route.params.type, route.params.string]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your string settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.string[action] identifier, sType, string)
.then (res) =>
@reply origin, res.message
`/**
* Modify your string settings.
*
* @name idle-string
* @syntax !idle-string add|remove type [stringData]
* @example !idle-string set web This is my web string
* @example !idle-string remove web
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-string :action(set) :type :string", stringFunc
@addRoute "idle-string :action(remove) :type", stringFunc
pushbulletFunc = (origin, route) =>
[bot, action, string] = [origin.bot, route.params.action, route.params.string]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your string settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pushbullet[action] identifier, string)
.then (res) =>
@reply origin, res.message
`/**
* Modify your PushBullet settings.
*
* @name idle-pushbullet
* @syntax !idle-pushbullet set|remove [pushbulletApiKey]
* @example !idle-pushbullet set ThisIsAnAPIKey
* @example !idle-pushbullet remove
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pushbullet :action(set) :string", pushbulletFunc
@addRoute "idle-pushbullet :action(remove)", pushbulletFunc
`/**
* Modify your priority point settings.
*
* @name idle-priority
* @syntax !idle-priority add|remove stat points
* @example !idle-priority add str 1
* @example !idle-priority remove str 1
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-priority :action(add|remove) :stat :points", (origin, route) =>
[bot, action, stat, points] = [origin.bot, route.params.action, route.params.stat, route.params.points]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your priority settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.priority[action] identifier, stat, points)
.then (res) =>
@reply origin, res.message
`/**
* Modify your gender settings.
*
* @name idle-gender
* @syntax !idle-gender newGender
* @example !idle-gender male
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-gender :newGender", (origin, route) =>
gender = route.params.newGender
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your gender settings!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.gender.set identifier, gender
.then (ret) =>
@reply origin, ret.message
`/**
* Teleport yourself to somewhere you've been before.
*
* @name idle-teleportself
* @syntax !idle-teleportself townCname
* @example !idle-teleportself norkos
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-teleportself :newLoc", (origin, route) =>
newLoc = route.params.newLoc
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to teleport yourself!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.action.teleport identifier, newLoc
.then (ret) =>
@reply origin, ret.message
`/**
* Modify your title.
*
* @name idle-title
* @syntax !idle-title newTitle
* @example !idle-title Entitled
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-title :newTitle", (origin, route) =>
newTitle = route.params.newTitle
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your title settings!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.title.set identifier, newTitle
.then (ret) =>
@reply origin, ret.message
`/**
* Modify your inventory.
*
* @name idle-inventory
* @syntax !idle-inventory swap|sell|add slot
* @example !idle-inventory add mainhand
* @example !idle-inventory swap 0
* @example !idle-inventory sell 0
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-inventory :action(swap|sell|add) :slot", (origin, route) =>
[action, slot] = [route.params.action, route.params.slot]
slot = parseInt slot if action isnt "add"
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your inventory settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.overflow[action] identifier, slot)
.then (res) =>
@reply origin, res.message
`/**
* Purchase something from a nearby shop (if you're near one, of course).
*
* @name idle-shop
* @syntax !idle-shop buy slot
* @example !idle-shop buy 0
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-shop buy :slot", (origin, route) =>
[slot] = [route.params.slot]
slot = parseInt slot
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to buy from a shop!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.shop.buy identifier, slot)
.then (res) =>
@reply origin, res.message
`/**
* Create a new guild. Costs 100k.
*
* @name Guild Creation
* @syntax !idle-guild create guildName
* @example !idle-guild create Leet Admin Hax
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild create :guildName", (origin, route) =>
[guildName] = [route.params.guildName]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to create a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.create identifier, guildName)
.then (res) =>
@reply origin, res.message
`/**
* Manage guild members.
*
* @name Guild Management
* @syntax !idle-guild invite|promote|demote|kick Player Name
* @example !idle-guild invite Swirly
* @example !idle-guild promote Swirly
* @example !idle-guild demote Swirly
* @example !idle-guild kick Swirly
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild :action(invite|promote|demote|kick) :playerName", (origin, route) =>
[action, playerName] = [route.params.action, route.params.playerName]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild[action] identifier, playerName)
.then (res) =>
@reply origin, res.message
`/**
* Manage your guild's current location.
*
* @name idle-guild move
* @syntax !idle-guild move newLoc
* @example !idle-guild move Vocalnus
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild move :newLoc", (origin, route) =>
[newLoc] = [route.params.newLoc]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.move identifier, newLoc)
.then (res) =>
@reply origin, res.message
`/**
* Construct a new building in your Guild Hall.
*
* @name idle-guild construct
* @syntax !idle-guild construct building slot
* @example !idle-guild construct GuildHall 0
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild construct :building :slot", (origin, route) =>
[building, slot] = [route.params.building, parseInt route.params.slot]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.construct identifier, building, slot)
.then (res) =>
@reply origin, res.message
`/**
* Upgrade a building in your guild hall.
*
* @name idle-guild upgrade
* @syntax !idle-guild upgrade building
* @example !idle-guild upgrade GuildHall
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild upgrade :building", (origin, route) =>
[building] = [route.params.building]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.upgrade identifier, building)
.then (res) =>
@reply origin, res.message
`/**
* Set a specific property for a building in your Guild Hall.
*
* @name idle-guild setprop
* @syntax !idle-guild setprop building prop "value"
* @example !idle-guild setprop Mascot MascotID "Skeleton"
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild setprop :building :prop \":value\"", (origin, route) =>
[building, prop, value] = [route.params.building, route.params.prop, route.params.value]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.setProperty identifier, building, prop, value)
.then (res) =>
@reply origin, res.message
`/**
* Manage your guild status.
*
* @name Guild Status
* @syntax !idle-guild leave|disband
* @example !idle-guild leave
* @example !idle-guild disband
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild :action(leave|disband)", (origin, route) =>
[action] = [route.params.action]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage your guild status!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild[action] identifier)
.then (res) =>
@reply origin, res.message
`/**
* Manage your guild invitations.
*
* @name Guild Invitations
* @syntax !idle-guild manage-invite accept|deny guild name
* @example !idle-guild manage-invite accept Leet Admin Hax
* @example !idle-guild manage-invite deny Leet Admin Hax
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild manage-invite :action(accept|deny) :guildName", (origin, route) =>
[action, guildName] = [route.params.action, route.params.guildName]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to join a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
accepted = action is "accept"
(@IdleWrapper.api.player.guild.manageInvite identifier, accepted, guildName)
.then (res) =>
@reply origin, res.message
`/**
* Donate gold to your guild.
*
* @name Guild Donation
* @syntax !idle-guild donate gold
* @example !idle-guild donate 1337
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild donate :gold", (origin, route) =>
[gold] = [route.params.gold]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to donate gold!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.donate identifier, parseInt gold
.then (res) =>
@reply origin, res.message
`/**
* Purchase a buff for your guild.
*
* @name Guild Buff
* @syntax !idle-guild buff "type" tier
* @example !idle-guild buff "Strength" 1
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild buff \":type\" :tier", (origin, route) =>
[type, tier] = [route.params.type, route.params.tier]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to buy a guild buff!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.buff identifier, type, parseInt tier
.then (res) =>
@reply origin, res.message
`/**
* Adjust your guilds tax rate (anywhere from 0-15%). Only guild leaders can set this.
*
* @name idle-guild tax
* @syntax !idle-guild tax taxPercent
* @example !idle-guild tax 15
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild tax :taxPercent", (origin, route) =>
[taxPercent] = [route.params.taxPercent]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage your guilds taxes!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.tax.whole identifier, parseInt taxPercent
.then (res) =>
@reply origin, res.message
`/**
* Adjust your personal tax rate to pay to your guild (anywhere from 0-85%).
*
* @name idle-guild selftax
* @syntax !idle-guild selftax taxPercent
* @example !idle-guild selftax 15
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild selftax :taxPercent", (origin, route) =>
[taxPercent] = [route.params.taxPercent]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage your taxes!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.tax.self identifier, parseInt taxPercent
.then (res) =>
@reply origin, res.message
`/**
* Manage your password, or authenticate.
*
* @name idle-secure
* @syntax !idle-secure setPassword|authenticate password
* @example !idle-secure setPassword my <PASSWORD>
* @example !idle-secure authenticate my super secret password
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-secure :action(setPassword|authenticate) :password", (origin, route) =>
[action, password] = [route.params.action, route.params.password]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set a password!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.auth[action] identifier, password)
.then (res) =>
@reply origin, res.message
`/**
* Buy a new pet.
*
* @name idle-pet buy
* @syntax !idle-pet buy "type" "name" "attr1" "attr2"
* @example !idle-pet buy "Pet Rock" "Rocky" "a top hat" "a monocle"
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pet buy \":petType\" \":petName\" \":attr1\" \":attr2\"", (origin, route) =>
[type, name, attr1, attr2] = [route.params.petType, route.params.petName, route.params.attr1, route.params.attr2]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to buy a pet!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet.buy identifier, type, name, attr1, attr2)
.then (res) =>
@reply origin, res.message
`/**
* Set smart options for your pet.
*
* @name idle-pet set
* @syntax !idle-pet set option on|off
* @example !idle-pet set smartSell on
* @example !idle-pet set smartSelf on
* @example !idle-pet set smartEquip off
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pet set :option :value", (origin, route) =>
[option, value] = [route.params.option, route.params.value is "on"]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change pet settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet.setOption identifier, option, value)
.then (res) =>
@reply origin, res.message
`/**
* Manage your pets items, upgrade their stats, and feed them gold!
*
* @name idle-pet action
* @syntax !idle-pet action actionType actionParameter
* @syntax !idle-pet action upgrade <stat> (maxLevel | inventory | goldStorage | battleJoinPercent | itemFindTimeDuration | itemSellMultiplier | itemFindBonus | itemFindRangeMultiplier | xpPerGold | maxItemScore)
* @syntax !idle-pet action giveEquipment itemSlot
* @syntax !idle-pet action sellEquipment itemSlot
* @syntax !idle-pet action takeEquipment itemSlot
* @syntax !idle-pet action changeClass newClass
* @syntax !idle-pet action equipItem itemSlot
* @syntax !idle-pet action unequipItem itemUid
* @syntax !idle-pet action swapToPet petId
* @syntax !idle-pet action feed
* @syntax !idle-pet action takeGold
* @example !idle-pet action upgrade maxLevel
* @example !idle-pet action giveEquipment 0
* @example !idle-pet action takeEquipment 1
* @example !idle-pet action sellEquipment 2
* @example !idle-pet action changeClass Generalist
* @example !idle-pet action equipItem 3
* @example !idle-pet action unequipItem 1418554184641
* @example !idle-pet action swapToPet 1418503227081
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pet action :action(feed|takeGold)", (origin, route) =>
[action] = [route.params.action]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change pet settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet[action]? identifier)
.then (res) =>
@reply origin, res.message
@addRoute "idle-pet action :action :param", (origin, route) =>
[action, param] = [route.params.action, route.params.param]
param = parseInt param if not (action in ["upgrade", "changeClass"])
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change pet settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet[action]? identifier, param)?.then (res) =>
@reply origin, res.message
`/**
* Manage custom data for the game.
*
* @name idle-customdata
* @gmOnly
* @syntax !idle-customdata <command> (init | update)
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-customdata :action", "idle.game.gm", (origin, route) =>
[action] = [route.params.action]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage custom data!"
return
@IdleWrapper.api.gm.custom[action]?()
`/**
* Manage moderators for managing custom data for the game.
*
* @name idle-custommod
* @gmOnly
* @syntax !idle-custommod "<user-identifier>" status
* @example !idle-custommod "local-server/Danret" 1
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-custommod \":identifier\" :mod", "idle.game.gm", (origin, route) =>
[identifier, modStatus] = [route.params.identifier, parseInt route.params.mod]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage custom mods!"
return
@IdleWrapper.api.gm.custom.modModerator identifier, modStatus
`/**
* Set a logger's level.
*
* @name idle-setloggerlevel
* @gmOnly
* @syntax !idle-setloggerlevel name level
* @example !idle-setloggerlevel battle debug
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-setloggerlevel \":name\" :level", "idle.game.gm", (origin, route) =>
[name, level] = [route.params.name, route.params.level]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set log levels!"
return
@IdleWrapper.api.gm.log.setLoggerLevel name, level
`/**
* Clear a log.
*
* @name idle-clearlog
* @gmOnly
* @syntax !idle-clearlog name
* @example !idle-clearlog battle
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-clearlog \":name\"", "idle.game.gm", (origin, route) =>
[name] = [route.params.name]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set log levels!"
return
@IdleWrapper.api.gm.log.clearLog name
`/**
* Clear all log.
*
* @name idle-clearalllogs
* @gmOnly
* @syntax !idle-clearalllogs
* @example !idle-clearalllogs
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-clearalllogs", "idle.game.gm", (origin, route) =>
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set log levels!"
return
@IdleWrapper.api.gm.log.clearAllLogs()
@initialize()
#@on "notice", (bot, sender, channel, message) =>
# return if not sender or sender in ['InfoServ','*','AUTH']
# console.log "notice from #{sender}|#{channel} on #{bot.config.server}: #{message}"
destroy: ->
clearInterval @interval
delete @db
super()
IdleModule
| true | BotManager = require("../../../../core/BotManager").BotManager
_ = require "lodash"
_.str = require "underscore.string"
Q = require "q"
finder = require "fs-finder"
watch = require "node-watch"
c = require "irc-colors"
idlePath = __dirname + "/../../src"
try
LogManager = require "../../src/system/managers/LogManager"
catch
console.log "haha" # This is just here to not break stuff
module.exports = (Module) ->
class IdleModule extends Module
shortName: "IdleLands"
helpText:
default: "Nothing special here."
serverBots: {}
serverChannels: {}
currentlyInChannels: []
users: []
userIdentsList: []
userIdents: {}
topic: "Welcome to Idliathlia! New player? Join ##idlebot & read http://new.idle.land | Got feedback? Send it to http://git.idle.land | Check your stats: http://idle.land/"
colorMap:
"player.name": c.bold
"event.partyName": c.underline
"event.partyMembers": c.bold
"event.player": c.bold
"event.damage": c.red
"event.gold": c.olive
"event.realGold": c.olive
"event.shopGold": c.olive
"event.xp": c.green
"event.realXp": c.green
"event.percentXp": c.green
"event.item.newbie": c.brown
"event.item.Normal": c.gray
"event.item.basic": c.gray
"event.item.pro": c.purple
"event.item.idle": c.bold.rainbow
"event.item.godly": c.white.bgblack
"event.item.custom": c.white.bgblue
"event.item.guardian": c.cyan
"event.finditem.scoreboost": c.bold
"event.finditem.perceived": c.bold
"event.finditem.real": c.bold
"event.blessItem.stat": c.bold
"event.blessItem.value": c.bold
"event.flip.stat": c.bold
"event.flip.value": c.bold
"event.enchant.boost": c.bold
"event.enchant.stat": c.bold
"event.tinker.boost": c.bold
"event.tinker.stat": c.bold
"event.transfer.destination": c.bold
"event.transfer.from": c.bold
"player.class": c.italic
"player.level": c.bold
"stats.hp": c.red
"stats.mp": c.blue
"stats.sp": c.olive
"damage.hp": c.red
"damage.mp": c.blue
"spell.turns": c.bold
"spell.spellName": c.underline
"event.casterName": c.bold
"event.spellName": c.underline
"event.targetName": c.bold
"event.achievement": c.underline
"event.guildName": c.underline
loadIdle: (stopIfLoaded) ->
@buildUserList()
if not (stopIfLoaded and @idleLoaded)
@idleLoaded = true
try
@IdleWrapper.load()
@IdleWrapper.api.game.handlers.broadcastHandler @sendMessageToAll, @
@IdleWrapper.api.game.handlers.colorMap @colorMap
@IdleWrapper.api.game.handlers.playerLoadHandler @getAllUsers
catch e
console.error e
addServerChannel: (bot, server, channel) =>
IdleModule::serverBots[server] = bot if not IdleModule::serverBots[server]
if server of @serverChannels
@serverChannels[server].push channel
else
@serverChannels[server] = [channel]
@serverChannels[server] = _.uniq @serverChannels[server]
removeServerChannel: (bot, server, channel) =>
@serverChannels[server] = _.without @serverChannels[server], channel
getAllUsers: =>
@userIdentsList
hashServerChannel: (server, channel) ->
"#{server}/#{channel}"
broadcast: (message) ->
for server, channels of @serverChannels
for channel in channels
IdleModule::serverBots[server]?.say channel, message if (@hashServerChannel server, channel) in @currentlyInChannels
sendMessageToAll: (message) ->
@broadcast message
generateIdent: (server, username) ->
return null if not username
"#{server}##{username}"
addUser: (ident, suppress) ->
return if not ident
@userIdentsList.push ident
@userIdentsList = _.uniq @userIdentsList
@IdleWrapper.api.player.auth.login ident, suppress
removeUser: (ident) ->
return if not ident or not _.contains @userIdentsList, ident
@userIdentsList = _.without @userIdentsList, ident
@IdleWrapper.api.player.auth.logout ident
buildUserList: ->
for server, channels of @serverChannels
for channel in channels
bot = IdleModule::serverBots[server]
if bot.conn.chans[channel]
chanUsers = bot.getUsers channel
chanUsers = _.forEach chanUsers, (user) =>
#whois changes the prototype such that it breaks for subsequent calls even if the server changes
#so we're doing nick-based auth for now
bot.userManager.getUsername user, (e, username) =>
username = user if (not username) and bot.config.auth is "nick"
ident = @generateIdent server, username
@addUser ident, yes
loadOldChannels: ->
Q.when @db.databaseReady, (db) =>
db.find {active: true}, (e, docs) =>
console.error e if e
docs.each (e, doc) =>
return if not doc
bot = BotManager.botHash[doc.server]
return if not bot
@addServerChannel bot, doc.server, doc.channel
beginGameLoop: ->
DELAY_INTERVAL = 10000
doActionPerMember = (arr, action) ->
for i in [0...arr.length]
setTimeout (player, i) ->
action player
, DELAY_INTERVAL/arr.length*i, arr[i]
@interval = setInterval =>
doActionPerMember @userIdentsList, (identifier) => @IdleWrapper.api.player.takeTurn identifier, no
, DELAY_INTERVAL
watchIdleFiles: ->
loadFunction = _.debounce (=>@loadIdle()), 100
watch idlePath, {}, () ->
files = finder.from(idlePath).findFiles("*.coffee")
_.forEach files, (file) ->
delete require.cache[file]
loadFunction()
initialize: ->
@loadIdle()
@loadOldChannels()
@beginGameLoop()
@watchIdleFiles()
isInChannel: (bot, nick) ->
isIn = no
for channel in @serverChannels[bot.config.server]
chanUsers = bot.getUsers channel
isIn = true if _.contains chanUsers, nick
isIn
constructor: (moduleManager) ->
super moduleManager
@IdleWrapper = require("../../src/system/accessibility/ExternalWrapper")()
@db = @newDatabase 'channels'
try
@logManager = new LogManager()
logger = @logManager.getLogger "kureaModule"
logger.warn "This is actually a success"
catch
console.log "useless catch to satisfy stuff." #it's here so that if it doesn't work, it won't break.
@on "join", (bot, channel, sender) =>
if bot.config.nick is sender
setTimeout =>
return if channel isnt '#idlebot'
bot.send 'TOPIC', channel, @topic
bot.send 'MODE', channel, '+m'
@currentlyInChannels.push @hashServerChannel bot.config.server, channel
@buildUserList()
, 1000
return
bot.userManager.getUsername {user: sender, bot: bot}, (e, username) =>
ident = @generateIdent bot.config.server, username
@addUser ident
@userIdents[@generateIdent bot.config.server, sender] = ident
@on "part", (bot, channel, sender) =>
return if channel isnt '#idlebot'
bot.userManager.getUsername {user: sender, bot: bot}, (e, username) =>
ident = @generateIdent bot.config.server, username
@removeUser ident
@userIdents[@generateIdent bot.config.server, sender] = ident
@on "quit", (bot, sender) =>
if bot.config.auth is "nickserv"
@removeUser @generateIdent bot.config.server, @userIdents[@generateIdent bot.config.server, sender]
delete @userIdents[@generateIdent bot.config.server, sender]
else if bot.config.auth is "nick"
@removeUser @generateIdent bot.config.server, sender
@on "nick", (bot, oldNick, newNick) =>
if bot.config.auth is "nickserv"
@userIdents[@generateIdent bot.config.server, newNick] = @userIdents[@generateIdent bot.config.server, oldNick]
delete @userIdents[@generateIdent bot.config.server, oldNick]
else if bot.config.auth is "nick"
@removeUser @generateIdent bot.config.server, oldNick
@addUser @generateIdent bot.config.server, newNick
`/**
* Start the game on the server this is run on. Used when linking new IRC networks.
*
* @name idle-start
* @syntax !idle-start
* @gmOnly
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-start", "idle.game.start", (origin) =>
[channel, server] = [origin.channel, origin.bot.config.server]
@db.update { channel: channel, server: server },
{ channel: channel, server: server, active: true },
{ upsert: true }, ->
@addServerChannel origin.bot, server, channel
@broadcast "#{origin.bot.config.server}/#{origin.channel} has joined the Idle Lands network!"
`/**
* Stop the game server on the server this is run on.
*
* @name idle-stop
* @syntax !idle-stop
* @gmOnly
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-stop", "idle.game.stop", (origin, route) =>
[channel, server] = [origin.channel, origin.bot.config.server]
@db.update { channel: channel, server: server },
{ channel: channel, server: server, active: false },
{ upsert: true }, ->
@broadcast "#{origin.bot.config.server}/#{origin.channel} has left the Idle Lands network!"
@removeServerChannel origin.bot, server, channel
registerCommand = (origin, route) =>
[bot, name] = [origin.bot, route.params.name]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to services play this game!"
return
if not @isInChannel bot, username
@reply origin, "You must be in the channel to actually play, duh!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.auth.register
identifier: identifier
name: name
).then (res) =>
@reply origin, res.message
`/**
* Register a new character on this IRC network.
*
* @name idle-register
* @syntax !idle-register Character Name
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-register :name", registerCommand
@addRoute "register :name", registerCommand
`/**
* Run any event for any logged in player.
*
* @name idle-event
* @syntax !idle-event "Player Name" eventType
* @gmOnly
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-event ":player" :event', "idle.game.gm", (origin, route) =>
[player, event] = [route.params.player, route.params.event]
@IdleWrapper.api.gm.event.single player, event
`/**
* Run a global event (cataclysms, PvP battles, etc).
*
* @name idle-globalevent
* @gmOnly
* @syntax !idle-globalevent eventType
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-globalevent :event?', "idle.game.gm", (origin, route) =>
event = route.params.event
@IdleWrapper.api.gm.event.global event
`/**
* Reset a password for a player.
*
* @name idle-resetpassword
* @gmOnly
* @syntax !idle-resetpassword "identifier" "newPassword"
* @example !idle-resetpassword "local-server/Danret" "PI:PASSWORD:<PASSWORD>END_PI"
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-resetpassword ":identifier" ":newPassword"', "idle.game.gm", (origin, route) =>
try
[identifier, password] = [route.params.identifier, route.params.newPassword]
if @gameInstance and @gameInstance.playerManager
@gameInstance.playerManager.storePasswordFor identifier, password
else
@IdleWrapper.api.gm.data.setPassword identifier, password
catch e
logger = @logManager.getLogger "kureaModule"
logger.error "!idle-resetpassword error", {e}
`/**
* Change a players identifier.
*
* @name idle-changeident
* @gmOnly
* @syntax !idle-changeident "identifier" "newIdentifier"
* @example !idle-changeident "local-server/Danret" "local-server/AlsoDanret"
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-changeident ":identifier" ":newIdentifier"', "idle.game.gm", (origin, route) =>
[identifier, newIdentifier] = [route.params.identifier, route.params.newIdentifier]
@gameInstance.api.gm.status.identifierChange identifier, newIdentifier
`/**
* Force the bot to update IdleLands and reboot.
*
* @name idle-update
* @gmOnly
* @syntax !idle-update
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-update', 'idle.game.gm', =>
@IdleWrapper.api.gm.data.update()
`/**
* Ban a player.
*
* @name idle-ban
* @gmOnly
* @syntax !idle-ban Player Name
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-ban :playerName", "idle.game.gm", (origin, route) =>
[name] = [route.params.playerName]
@IdleWrapper.api.gm.status.ban name
`/**
* Unban a player.
*
* @name idle-unban
* @gmOnly
* @syntax !idle-unban Player Name
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-unban :playerName", "idle.game.gm", (origin, route) =>
[name] = [route.params.playerName]
@IdleWrapper.api.gm.status.unban name
`/**
* Teleport a player to a given location.
*
* @name idle-teleportloc
* @gmOnly
* @syntax !idle-teleportloc "Player Name" locationId
* @example !idle-teleport "Swirly" start
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-teleportloc ":playerName" :location', "idle.game.gm", (origin, route) =>
[name, location] = [route.params.playerName, route.params.location]
@IdleWrapper.api.gm.teleport.location.single name, location
`/**
* Teleport a player to a given set of coordinates.
*
* @name idle-teleport
* @gmOnly
* @syntax !idle-teleport "Player Name" "Map Name" x,y
* @example !idle-teleport "Swirly" "PI:NAME:<NAME>END_PIorkos" 10,10
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-teleport ":playerName" ":map" :x,:y', "idle.game.gm", (origin, route) =>
[name, map, x, y] = [route.params.playerName, route.params.map, route.params.x, route.params.y]
x = parseInt x
y = parseInt y
@IdleWrapper.api.gm.teleport.map.single name, map, x, y
`/**
* Teleport all players to a given location.
*
* @name idle-massteleportloc
* @gmOnly
* @syntax !idle-massteleportloc locationId
* @example !idle-massteleportloc norkos
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-massteleportloc :location", "idle.game.gm", (origin, route) =>
[location] = [route.params.location]
@IdleWrapper.api.gm.teleport.map.location location
`/**
* Teleport all players to a given set of coordinates.
*
* @name idle-massteleport
* @gmOnly
* @syntax !idle-massteleport "Map Name" x,y
* @example !idle-massteleport "Norkos" 10,10
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-massteleport ":map" :x,:y', "idle.game.gm", (origin, route) =>
[map, x, y] = [route.params.map, route.params.x, route.params.y]
x = parseInt x
y = parseInt y
@IdleWrapper.api.gm.teleport.map.mass map, x, y
`/**
* Generate a custom item for a player.
*
* @name idle-itemgen
* @gmOnly
* @syntax !idle-itemgen "Player Name" itemSlot "name" stats
* @example !idle-itemgen "Swirly" mainhand "Epic Cheat" luck=10000
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-itemgen ":player" :type *', "idle.game.gm", (origin, route) =>
[playerName, itemType, itemData] = [route.params.player, route.params.type, route.splats[0]]
@IdleWrapper.api.gm.player.createItem playerName, itemType, itemData
`/**
* Give a player some gold.
*
* @name idle-goldgive
* @gmOnly
* @syntax !idle-goldgive "Player Name" gold
* @example !idle-goldgive "Swirly" 10000
* @category IRC Commands
* @package Client
*/`
@addRoute 'idle-goldgive ":player" :gold', "idle.game.gm", (origin, route) =>
[playerName, gold] = [route.params.player, route.params.gold]
@IdleWrapper.api.gm.player.giveGold playerName, parseInt gold
`/**
* Modify your personality settings.
*
* @name idle-personality
* @syntax !idle-personality add|remove Personality
* @example !idle-personality add ScaredOfTheDark
* @example !idle-personality remove ScaredOfTheDark
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-personality :action(add|remove) :personality", (origin, route) =>
[bot, action, personality] = [origin.bot, route.params.action, route.params.personality]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your personality settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.personality[action] identifier, personality)
.then (res) =>
@reply origin, res.message
stringFunc = (origin, route) =>
[bot, action, sType, string] = [origin.bot, route.params.action, route.params.type, route.params.string]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your string settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.string[action] identifier, sType, string)
.then (res) =>
@reply origin, res.message
`/**
* Modify your string settings.
*
* @name idle-string
* @syntax !idle-string add|remove type [stringData]
* @example !idle-string set web This is my web string
* @example !idle-string remove web
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-string :action(set) :type :string", stringFunc
@addRoute "idle-string :action(remove) :type", stringFunc
pushbulletFunc = (origin, route) =>
[bot, action, string] = [origin.bot, route.params.action, route.params.string]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your string settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pushbullet[action] identifier, string)
.then (res) =>
@reply origin, res.message
`/**
* Modify your PushBullet settings.
*
* @name idle-pushbullet
* @syntax !idle-pushbullet set|remove [pushbulletApiKey]
* @example !idle-pushbullet set ThisIsAnAPIKey
* @example !idle-pushbullet remove
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pushbullet :action(set) :string", pushbulletFunc
@addRoute "idle-pushbullet :action(remove)", pushbulletFunc
`/**
* Modify your priority point settings.
*
* @name idle-priority
* @syntax !idle-priority add|remove stat points
* @example !idle-priority add str 1
* @example !idle-priority remove str 1
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-priority :action(add|remove) :stat :points", (origin, route) =>
[bot, action, stat, points] = [origin.bot, route.params.action, route.params.stat, route.params.points]
bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your priority settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.priority[action] identifier, stat, points)
.then (res) =>
@reply origin, res.message
`/**
* Modify your gender settings.
*
* @name idle-gender
* @syntax !idle-gender newGender
* @example !idle-gender male
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-gender :newGender", (origin, route) =>
gender = route.params.newGender
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your gender settings!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.gender.set identifier, gender
.then (ret) =>
@reply origin, ret.message
`/**
* Teleport yourself to somewhere you've been before.
*
* @name idle-teleportself
* @syntax !idle-teleportself townCname
* @example !idle-teleportself norkos
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-teleportself :newLoc", (origin, route) =>
newLoc = route.params.newLoc
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to teleport yourself!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.action.teleport identifier, newLoc
.then (ret) =>
@reply origin, ret.message
`/**
* Modify your title.
*
* @name idle-title
* @syntax !idle-title newTitle
* @example !idle-title Entitled
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-title :newTitle", (origin, route) =>
newTitle = route.params.newTitle
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your title settings!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.title.set identifier, newTitle
.then (ret) =>
@reply origin, ret.message
`/**
* Modify your inventory.
*
* @name idle-inventory
* @syntax !idle-inventory swap|sell|add slot
* @example !idle-inventory add mainhand
* @example !idle-inventory swap 0
* @example !idle-inventory sell 0
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-inventory :action(swap|sell|add) :slot", (origin, route) =>
[action, slot] = [route.params.action, route.params.slot]
slot = parseInt slot if action isnt "add"
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change your inventory settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.overflow[action] identifier, slot)
.then (res) =>
@reply origin, res.message
`/**
* Purchase something from a nearby shop (if you're near one, of course).
*
* @name idle-shop
* @syntax !idle-shop buy slot
* @example !idle-shop buy 0
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-shop buy :slot", (origin, route) =>
[slot] = [route.params.slot]
slot = parseInt slot
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to buy from a shop!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.shop.buy identifier, slot)
.then (res) =>
@reply origin, res.message
`/**
* Create a new guild. Costs 100k.
*
* @name Guild Creation
* @syntax !idle-guild create guildName
* @example !idle-guild create Leet Admin Hax
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild create :guildName", (origin, route) =>
[guildName] = [route.params.guildName]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to create a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.create identifier, guildName)
.then (res) =>
@reply origin, res.message
`/**
* Manage guild members.
*
* @name Guild Management
* @syntax !idle-guild invite|promote|demote|kick Player Name
* @example !idle-guild invite Swirly
* @example !idle-guild promote Swirly
* @example !idle-guild demote Swirly
* @example !idle-guild kick Swirly
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild :action(invite|promote|demote|kick) :playerName", (origin, route) =>
[action, playerName] = [route.params.action, route.params.playerName]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild[action] identifier, playerName)
.then (res) =>
@reply origin, res.message
`/**
* Manage your guild's current location.
*
* @name idle-guild move
* @syntax !idle-guild move newLoc
* @example !idle-guild move Vocalnus
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild move :newLoc", (origin, route) =>
[newLoc] = [route.params.newLoc]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.move identifier, newLoc)
.then (res) =>
@reply origin, res.message
`/**
* Construct a new building in your Guild Hall.
*
* @name idle-guild construct
* @syntax !idle-guild construct building slot
* @example !idle-guild construct GuildHall 0
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild construct :building :slot", (origin, route) =>
[building, slot] = [route.params.building, parseInt route.params.slot]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.construct identifier, building, slot)
.then (res) =>
@reply origin, res.message
`/**
* Upgrade a building in your guild hall.
*
* @name idle-guild upgrade
* @syntax !idle-guild upgrade building
* @example !idle-guild upgrade GuildHall
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild upgrade :building", (origin, route) =>
[building] = [route.params.building]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.upgrade identifier, building)
.then (res) =>
@reply origin, res.message
`/**
* Set a specific property for a building in your Guild Hall.
*
* @name idle-guild setprop
* @syntax !idle-guild setprop building prop "value"
* @example !idle-guild setprop Mascot MascotID "Skeleton"
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild setprop :building :prop \":value\"", (origin, route) =>
[building, prop, value] = [route.params.building, route.params.prop, route.params.value]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to administer a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild.setProperty identifier, building, prop, value)
.then (res) =>
@reply origin, res.message
`/**
* Manage your guild status.
*
* @name Guild Status
* @syntax !idle-guild leave|disband
* @example !idle-guild leave
* @example !idle-guild disband
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild :action(leave|disband)", (origin, route) =>
[action] = [route.params.action]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage your guild status!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.guild[action] identifier)
.then (res) =>
@reply origin, res.message
`/**
* Manage your guild invitations.
*
* @name Guild Invitations
* @syntax !idle-guild manage-invite accept|deny guild name
* @example !idle-guild manage-invite accept Leet Admin Hax
* @example !idle-guild manage-invite deny Leet Admin Hax
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild manage-invite :action(accept|deny) :guildName", (origin, route) =>
[action, guildName] = [route.params.action, route.params.guildName]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to join a guild!"
return
identifier = @generateIdent origin.bot.config.server, username
accepted = action is "accept"
(@IdleWrapper.api.player.guild.manageInvite identifier, accepted, guildName)
.then (res) =>
@reply origin, res.message
`/**
* Donate gold to your guild.
*
* @name Guild Donation
* @syntax !idle-guild donate gold
* @example !idle-guild donate 1337
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild donate :gold", (origin, route) =>
[gold] = [route.params.gold]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to donate gold!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.donate identifier, parseInt gold
.then (res) =>
@reply origin, res.message
`/**
* Purchase a buff for your guild.
*
* @name Guild Buff
* @syntax !idle-guild buff "type" tier
* @example !idle-guild buff "Strength" 1
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild buff \":type\" :tier", (origin, route) =>
[type, tier] = [route.params.type, route.params.tier]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to buy a guild buff!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.buff identifier, type, parseInt tier
.then (res) =>
@reply origin, res.message
`/**
* Adjust your guilds tax rate (anywhere from 0-15%). Only guild leaders can set this.
*
* @name idle-guild tax
* @syntax !idle-guild tax taxPercent
* @example !idle-guild tax 15
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild tax :taxPercent", (origin, route) =>
[taxPercent] = [route.params.taxPercent]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage your guilds taxes!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.tax.whole identifier, parseInt taxPercent
.then (res) =>
@reply origin, res.message
`/**
* Adjust your personal tax rate to pay to your guild (anywhere from 0-85%).
*
* @name idle-guild selftax
* @syntax !idle-guild selftax taxPercent
* @example !idle-guild selftax 15
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-guild selftax :taxPercent", (origin, route) =>
[taxPercent] = [route.params.taxPercent]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage your taxes!"
return
identifier = @generateIdent origin.bot.config.server, username
@IdleWrapper.api.player.guild.tax.self identifier, parseInt taxPercent
.then (res) =>
@reply origin, res.message
`/**
* Manage your password, or authenticate.
*
* @name idle-secure
* @syntax !idle-secure setPassword|authenticate password
* @example !idle-secure setPassword my PI:PASSWORD:<PASSWORD>END_PI
* @example !idle-secure authenticate my super secret password
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-secure :action(setPassword|authenticate) :password", (origin, route) =>
[action, password] = [route.params.action, route.params.password]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set a password!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.auth[action] identifier, password)
.then (res) =>
@reply origin, res.message
`/**
* Buy a new pet.
*
* @name idle-pet buy
* @syntax !idle-pet buy "type" "name" "attr1" "attr2"
* @example !idle-pet buy "Pet Rock" "Rocky" "a top hat" "a monocle"
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pet buy \":petType\" \":petName\" \":attr1\" \":attr2\"", (origin, route) =>
[type, name, attr1, attr2] = [route.params.petType, route.params.petName, route.params.attr1, route.params.attr2]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to buy a pet!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet.buy identifier, type, name, attr1, attr2)
.then (res) =>
@reply origin, res.message
`/**
* Set smart options for your pet.
*
* @name idle-pet set
* @syntax !idle-pet set option on|off
* @example !idle-pet set smartSell on
* @example !idle-pet set smartSelf on
* @example !idle-pet set smartEquip off
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pet set :option :value", (origin, route) =>
[option, value] = [route.params.option, route.params.value is "on"]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change pet settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet.setOption identifier, option, value)
.then (res) =>
@reply origin, res.message
`/**
* Manage your pets items, upgrade their stats, and feed them gold!
*
* @name idle-pet action
* @syntax !idle-pet action actionType actionParameter
* @syntax !idle-pet action upgrade <stat> (maxLevel | inventory | goldStorage | battleJoinPercent | itemFindTimeDuration | itemSellMultiplier | itemFindBonus | itemFindRangeMultiplier | xpPerGold | maxItemScore)
* @syntax !idle-pet action giveEquipment itemSlot
* @syntax !idle-pet action sellEquipment itemSlot
* @syntax !idle-pet action takeEquipment itemSlot
* @syntax !idle-pet action changeClass newClass
* @syntax !idle-pet action equipItem itemSlot
* @syntax !idle-pet action unequipItem itemUid
* @syntax !idle-pet action swapToPet petId
* @syntax !idle-pet action feed
* @syntax !idle-pet action takeGold
* @example !idle-pet action upgrade maxLevel
* @example !idle-pet action giveEquipment 0
* @example !idle-pet action takeEquipment 1
* @example !idle-pet action sellEquipment 2
* @example !idle-pet action changeClass Generalist
* @example !idle-pet action equipItem 3
* @example !idle-pet action unequipItem 1418554184641
* @example !idle-pet action swapToPet 1418503227081
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-pet action :action(feed|takeGold)", (origin, route) =>
[action] = [route.params.action]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change pet settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet[action]? identifier)
.then (res) =>
@reply origin, res.message
@addRoute "idle-pet action :action :param", (origin, route) =>
[action, param] = [route.params.action, route.params.param]
param = parseInt param if not (action in ["upgrade", "changeClass"])
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to change pet settings!"
return
identifier = @generateIdent origin.bot.config.server, username
(@IdleWrapper.api.player.pet[action]? identifier, param)?.then (res) =>
@reply origin, res.message
`/**
* Manage custom data for the game.
*
* @name idle-customdata
* @gmOnly
* @syntax !idle-customdata <command> (init | update)
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-customdata :action", "idle.game.gm", (origin, route) =>
[action] = [route.params.action]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage custom data!"
return
@IdleWrapper.api.gm.custom[action]?()
`/**
* Manage moderators for managing custom data for the game.
*
* @name idle-custommod
* @gmOnly
* @syntax !idle-custommod "<user-identifier>" status
* @example !idle-custommod "local-server/Danret" 1
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-custommod \":identifier\" :mod", "idle.game.gm", (origin, route) =>
[identifier, modStatus] = [route.params.identifier, parseInt route.params.mod]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to manage custom mods!"
return
@IdleWrapper.api.gm.custom.modModerator identifier, modStatus
`/**
* Set a logger's level.
*
* @name idle-setloggerlevel
* @gmOnly
* @syntax !idle-setloggerlevel name level
* @example !idle-setloggerlevel battle debug
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-setloggerlevel \":name\" :level", "idle.game.gm", (origin, route) =>
[name, level] = [route.params.name, route.params.level]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set log levels!"
return
@IdleWrapper.api.gm.log.setLoggerLevel name, level
`/**
* Clear a log.
*
* @name idle-clearlog
* @gmOnly
* @syntax !idle-clearlog name
* @example !idle-clearlog battle
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-clearlog \":name\"", "idle.game.gm", (origin, route) =>
[name] = [route.params.name]
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set log levels!"
return
@IdleWrapper.api.gm.log.clearLog name
`/**
* Clear all log.
*
* @name idle-clearalllogs
* @gmOnly
* @syntax !idle-clearalllogs
* @example !idle-clearalllogs
* @category IRC Commands
* @package Client
*/`
@addRoute "idle-clearalllogs", "idle.game.gm", (origin, route) =>
origin.bot.userManager.getUsername origin, (e, username) =>
if not username
@reply origin, "You must be logged in to set log levels!"
return
@IdleWrapper.api.gm.log.clearAllLogs()
@initialize()
#@on "notice", (bot, sender, channel, message) =>
# return if not sender or sender in ['InfoServ','*','AUTH']
# console.log "notice from #{sender}|#{channel} on #{bot.config.server}: #{message}"
destroy: ->
clearInterval @interval
delete @db
super()
IdleModule
|
[
{
"context": "ly larger than females.\n '''\n\n scientificName: 'Potamochoerus larvatus'\n mainImage: 'assets/fieldguide-content/mammals/",
"end": 431,
"score": 0.8186655640602112,
"start": 409,
"tag": "NAME",
"value": "Potamochoerus larvatus"
}
] | app/lib/field-guide-content/bushpig.coffee | zooniverse/wildcam-gorongosa-facebook | 7 | module.exports =
description: '''
Bushpigs resemble the domestic pig, with a blunt, muscular snout, small eyes, and pointed, tufted ears. Their fur is reddish-brown to dark brown and becomes darker with age. They have a silver-colored mane, which bristles when they become agitated. Their sharp tusks are fairly short and inconspicuous. Males are normally larger than females.
'''
scientificName: 'Potamochoerus larvatus'
mainImage: 'assets/fieldguide-content/mammals/bushpig/bushpig-feature.jpg'
conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '100-150 cm'
}, {
label: 'Height'
value: '66-100 cm'
}, {
label: 'Weight'
value: '55-150 kg'
}, {
label: 'Lifespan'
value: '20 years'
}, {
label: 'Gestation'
value: '120-127 days'
}, {
label: 'Avg. number of offspring'
value: '1 - 4'
}]
sections: [{
title: 'Habitat'
content: '<p>Savanna, woodland, forests, and riverine vegetation</p>'
}, {
title: 'Diet'
content: 'Roots, rhizomes, bulbs, tubers, fruits, insect larvae, crops, and carrion'
}, {
title: 'Predators'
content: 'Lions, leopards, hyenas, pythons, and humans'
}, {
title: 'Behavior'
content: '''
<p>Bushpigs are social animals that are found in groups of up to 12 members, consisting of a dominant male and female, with other females and juveniles. Bushpigs are highly territorial and can be aggressive, especially when young are present. They are predominantly nocturnal. They seek shelter in dense vegetation and build nests during rainy and cold periods. In the heat, they wallow in the mud.</p>
'''
}, {
title: 'Breeding'
content: '''
A bushpig reaches sexual maturity at 18 to 21 months. Bushpig males exclude other males for access to a group of females. The males compete by butting heads. Most births occur between September and November. The female bushpig goes to their sheltered nest before giving birth. After birth, they nurse their young for two to four months. Parents usually drive out young bushpigs at six months of age.
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>Unlike warthogs, bushpigs run with their tails down.</li>
<li>Bushpigs are often found following monkeys, feeding on uneaten fruit that falls to the ground./li>
</ol>
'''
}]
| 50039 | module.exports =
description: '''
Bushpigs resemble the domestic pig, with a blunt, muscular snout, small eyes, and pointed, tufted ears. Their fur is reddish-brown to dark brown and becomes darker with age. They have a silver-colored mane, which bristles when they become agitated. Their sharp tusks are fairly short and inconspicuous. Males are normally larger than females.
'''
scientificName: '<NAME>'
mainImage: 'assets/fieldguide-content/mammals/bushpig/bushpig-feature.jpg'
conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '100-150 cm'
}, {
label: 'Height'
value: '66-100 cm'
}, {
label: 'Weight'
value: '55-150 kg'
}, {
label: 'Lifespan'
value: '20 years'
}, {
label: 'Gestation'
value: '120-127 days'
}, {
label: 'Avg. number of offspring'
value: '1 - 4'
}]
sections: [{
title: 'Habitat'
content: '<p>Savanna, woodland, forests, and riverine vegetation</p>'
}, {
title: 'Diet'
content: 'Roots, rhizomes, bulbs, tubers, fruits, insect larvae, crops, and carrion'
}, {
title: 'Predators'
content: 'Lions, leopards, hyenas, pythons, and humans'
}, {
title: 'Behavior'
content: '''
<p>Bushpigs are social animals that are found in groups of up to 12 members, consisting of a dominant male and female, with other females and juveniles. Bushpigs are highly territorial and can be aggressive, especially when young are present. They are predominantly nocturnal. They seek shelter in dense vegetation and build nests during rainy and cold periods. In the heat, they wallow in the mud.</p>
'''
}, {
title: 'Breeding'
content: '''
A bushpig reaches sexual maturity at 18 to 21 months. Bushpig males exclude other males for access to a group of females. The males compete by butting heads. Most births occur between September and November. The female bushpig goes to their sheltered nest before giving birth. After birth, they nurse their young for two to four months. Parents usually drive out young bushpigs at six months of age.
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>Unlike warthogs, bushpigs run with their tails down.</li>
<li>Bushpigs are often found following monkeys, feeding on uneaten fruit that falls to the ground./li>
</ol>
'''
}]
| true | module.exports =
description: '''
Bushpigs resemble the domestic pig, with a blunt, muscular snout, small eyes, and pointed, tufted ears. Their fur is reddish-brown to dark brown and becomes darker with age. They have a silver-colored mane, which bristles when they become agitated. Their sharp tusks are fairly short and inconspicuous. Males are normally larger than females.
'''
scientificName: 'PI:NAME:<NAME>END_PI'
mainImage: 'assets/fieldguide-content/mammals/bushpig/bushpig-feature.jpg'
conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '100-150 cm'
}, {
label: 'Height'
value: '66-100 cm'
}, {
label: 'Weight'
value: '55-150 kg'
}, {
label: 'Lifespan'
value: '20 years'
}, {
label: 'Gestation'
value: '120-127 days'
}, {
label: 'Avg. number of offspring'
value: '1 - 4'
}]
sections: [{
title: 'Habitat'
content: '<p>Savanna, woodland, forests, and riverine vegetation</p>'
}, {
title: 'Diet'
content: 'Roots, rhizomes, bulbs, tubers, fruits, insect larvae, crops, and carrion'
}, {
title: 'Predators'
content: 'Lions, leopards, hyenas, pythons, and humans'
}, {
title: 'Behavior'
content: '''
<p>Bushpigs are social animals that are found in groups of up to 12 members, consisting of a dominant male and female, with other females and juveniles. Bushpigs are highly territorial and can be aggressive, especially when young are present. They are predominantly nocturnal. They seek shelter in dense vegetation and build nests during rainy and cold periods. In the heat, they wallow in the mud.</p>
'''
}, {
title: 'Breeding'
content: '''
A bushpig reaches sexual maturity at 18 to 21 months. Bushpig males exclude other males for access to a group of females. The males compete by butting heads. Most births occur between September and November. The female bushpig goes to their sheltered nest before giving birth. After birth, they nurse their young for two to four months. Parents usually drive out young bushpigs at six months of age.
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>Unlike warthogs, bushpigs run with their tails down.</li>
<li>Bushpigs are often found following monkeys, feeding on uneaten fruit that falls to the ground./li>
</ol>
'''
}]
|
[
{
"context": "p, index) =>\n DOM.div\n key: \"group-#{index}\"\n className: 'panel'\n s",
"end": 1366,
"score": 0.8430557250976562,
"start": 1366,
"tag": "KEY",
"value": ""
},
{
"context": " identity: identity\n key: \"card-#{i... | src/components/merge.coffee | brianshaler/kerplunk-identity | 0 | _ = require 'lodash'
React = require 'react'
# ugh @ amdifying when
# Promise = require 'when'
{DOM} = React
module.exports = React.createFactory React.createClass
getInitialState: ->
groups: @props.groups ? []
merge: (group) ->
(e) =>
e.preventDefault()
[first, others...] = group
console.log 'merge', first._id, 'with', _.map others, '_id'
Promise.all _.map others, (other) =>
deferred = Promise.defer()
url = "/admin/identity/link/#{first._id}/#{other._id}.json"
console.log 'link', url
@props.request.get url, {}, (err, data) ->
return deferred.reject err if err
deferred.resolve data
deferred.promise
.then (results) =>
return unless @isMounted()
console.log 'results', results
@setState
groups: _.filter @state.groups, (g) ->
g[0]._id != group[0]._id
.catch (err) =>
console.log 'crap', err, group
render: ->
identityConfig = @props.globals.public.identity
cardComponentPath = identityConfig.contactCardComponent ? identityConfig.defaultContactCard
ContactCard = @props.getComponent cardComponentPath
DOM.section
className: 'content'
,
DOM.h3 null, 'Merge duplicate contacts'
_.map @state.groups, (group, index) =>
DOM.div
key: "group-#{index}"
className: 'panel'
style:
marginBottom: '2em'
,
DOM.div
className: 'clearfix'
,
_.map group, (identity) =>
ContactCard _.extend {}, @props,
identity: identity
key: "card-#{identity._id}"
DOM.div null,
DOM.a
onClick: @merge group
href: '#'
className: 'btn btn-success'
, 'merge'
| 188346 | _ = require 'lodash'
React = require 'react'
# ugh @ amdifying when
# Promise = require 'when'
{DOM} = React
module.exports = React.createFactory React.createClass
getInitialState: ->
groups: @props.groups ? []
merge: (group) ->
(e) =>
e.preventDefault()
[first, others...] = group
console.log 'merge', first._id, 'with', _.map others, '_id'
Promise.all _.map others, (other) =>
deferred = Promise.defer()
url = "/admin/identity/link/#{first._id}/#{other._id}.json"
console.log 'link', url
@props.request.get url, {}, (err, data) ->
return deferred.reject err if err
deferred.resolve data
deferred.promise
.then (results) =>
return unless @isMounted()
console.log 'results', results
@setState
groups: _.filter @state.groups, (g) ->
g[0]._id != group[0]._id
.catch (err) =>
console.log 'crap', err, group
render: ->
identityConfig = @props.globals.public.identity
cardComponentPath = identityConfig.contactCardComponent ? identityConfig.defaultContactCard
ContactCard = @props.getComponent cardComponentPath
DOM.section
className: 'content'
,
DOM.h3 null, 'Merge duplicate contacts'
_.map @state.groups, (group, index) =>
DOM.div
key: "group<KEY>-#{index}"
className: 'panel'
style:
marginBottom: '2em'
,
DOM.div
className: 'clearfix'
,
_.map group, (identity) =>
ContactCard _.extend {}, @props,
identity: identity
key: "<KEY>}"
DOM.div null,
DOM.a
onClick: @merge group
href: '#'
className: 'btn btn-success'
, 'merge'
| true | _ = require 'lodash'
React = require 'react'
# ugh @ amdifying when
# Promise = require 'when'
{DOM} = React
module.exports = React.createFactory React.createClass
getInitialState: ->
groups: @props.groups ? []
merge: (group) ->
(e) =>
e.preventDefault()
[first, others...] = group
console.log 'merge', first._id, 'with', _.map others, '_id'
Promise.all _.map others, (other) =>
deferred = Promise.defer()
url = "/admin/identity/link/#{first._id}/#{other._id}.json"
console.log 'link', url
@props.request.get url, {}, (err, data) ->
return deferred.reject err if err
deferred.resolve data
deferred.promise
.then (results) =>
return unless @isMounted()
console.log 'results', results
@setState
groups: _.filter @state.groups, (g) ->
g[0]._id != group[0]._id
.catch (err) =>
console.log 'crap', err, group
render: ->
identityConfig = @props.globals.public.identity
cardComponentPath = identityConfig.contactCardComponent ? identityConfig.defaultContactCard
ContactCard = @props.getComponent cardComponentPath
DOM.section
className: 'content'
,
DOM.h3 null, 'Merge duplicate contacts'
_.map @state.groups, (group, index) =>
DOM.div
key: "groupPI:KEY:<KEY>END_PI-#{index}"
className: 'panel'
style:
marginBottom: '2em'
,
DOM.div
className: 'clearfix'
,
_.map group, (identity) =>
ContactCard _.extend {}, @props,
identity: identity
key: "PI:KEY:<KEY>END_PI}"
DOM.div null,
DOM.a
onClick: @merge group
href: '#'
className: 'btn btn-success'
, 'merge'
|
[
{
"context": "Vue.component \"login\",\n data: () ->\n username: ''\n password: ''\n computed:\n canSubmit: ->\n ",
"end": 50,
"score": 0.8456325531005859,
"start": 50,
"tag": "USERNAME",
"value": ""
},
{
"context": "gin\",\n data: () ->\n username: ''\n password: ... | app/assets/javascripts/views/sessions/new.js.coffee | stronglifters/surface | 2 | Vue.component "login",
data: () ->
username: ''
password: ''
computed:
canSubmit: ->
@username.length > 0 && @password.length > 0
| 133133 | Vue.component "login",
data: () ->
username: ''
password:<PASSWORD> ''
computed:
canSubmit: ->
@username.length > 0 && @password.length > 0
| true | Vue.component "login",
data: () ->
username: ''
password:PI:PASSWORD:<PASSWORD>END_PI ''
computed:
canSubmit: ->
@username.length > 0 && @password.length > 0
|
[
{
"context": "AdminDashboard.path(\"/Equipe\")\n collection: \"Equipe\"\n }\n {\n title: \"Serviços\"\n url: A",
"end": 1826,
"score": 0.8084138035774231,
"start": 1820,
"tag": "NAME",
"value": "Equipe"
}
] | both/config/adminDashboard.coffee | thiago-zaidem/appVilaDosBichos | 0 | AdminDashboard.addSidebarItem "Configurações",
icon: 'gear'
urls: [
{
title: "Perfis de acesso"
url: AdminDashboard.path("/PerfisAcesso")
collection: "PerfisAcesso"
}
{
title: "Planos de saúde"
url: AdminDashboard.path("/PlanosSaude")
collection: "PlanosSaude"
}
{
title: "Tipo de provedor"
url: AdminDashboard.path("/ProvidersType")
collection: "ProvidersType"
}
{
title: "Tipo de serviços"
url: AdminDashboard.path("/ProvidersService")
collection: "ProvidersService"
}
]
AdminDashboard.addSidebarItem "Meus dados",
icon:'file-text-o'
urls: [
{
title: "Cadastrais"
url: AdminDashboard.path("/Providers")
collection: "Providers"
}
{
title: "Pets"
url: AdminDashboard.path("/Pets")
collection: "Pets"
}
{
title: "Locais de atendimento"
url: AdminDashboard.path("/ServiceLocation")
collection: "ServiceLocation"
}
]
AdminDashboard.addSidebarItem "Relatórios",
icon:'pie-chart'
urls: [
{
title: "Histórico de buscas"
url: AdminDashboard.path("/ProvidersHistorySearch")
collection: "ProvidersHistorySearch"
}
]
AdminDashboard.addSidebarItem "Site",
icon: "desktop"
urls: [
{
title: "Quem somos"
url: AdminDashboard.path("/QuemSomos")
collection: "QuemSomos"
}
{
title: "Equipe"
url: AdminDashboard.path("/Equipe")
collection: "Equipe"
}
{
title: "Serviços"
url: AdminDashboard.path("/Slideshow")
collection: "Slideshow"
}
{
title: "Quem somos"
url: AdminDashboard.path("/QuemSomos")
collection: "QuemSomos"
}
{
title: "Equipe"
url: AdminDashboard.path("/Equipe")
collection: "Equipe"
}
{
title: "Serviços"
url: AdminDashboard.path("/Slideshow")
collection: "Slideshow"
}
] | 217330 | AdminDashboard.addSidebarItem "Configurações",
icon: 'gear'
urls: [
{
title: "Perfis de acesso"
url: AdminDashboard.path("/PerfisAcesso")
collection: "PerfisAcesso"
}
{
title: "Planos de saúde"
url: AdminDashboard.path("/PlanosSaude")
collection: "PlanosSaude"
}
{
title: "Tipo de provedor"
url: AdminDashboard.path("/ProvidersType")
collection: "ProvidersType"
}
{
title: "Tipo de serviços"
url: AdminDashboard.path("/ProvidersService")
collection: "ProvidersService"
}
]
AdminDashboard.addSidebarItem "Meus dados",
icon:'file-text-o'
urls: [
{
title: "Cadastrais"
url: AdminDashboard.path("/Providers")
collection: "Providers"
}
{
title: "Pets"
url: AdminDashboard.path("/Pets")
collection: "Pets"
}
{
title: "Locais de atendimento"
url: AdminDashboard.path("/ServiceLocation")
collection: "ServiceLocation"
}
]
AdminDashboard.addSidebarItem "Relatórios",
icon:'pie-chart'
urls: [
{
title: "Histórico de buscas"
url: AdminDashboard.path("/ProvidersHistorySearch")
collection: "ProvidersHistorySearch"
}
]
AdminDashboard.addSidebarItem "Site",
icon: "desktop"
urls: [
{
title: "Quem somos"
url: AdminDashboard.path("/QuemSomos")
collection: "QuemSomos"
}
{
title: "Equipe"
url: AdminDashboard.path("/Equipe")
collection: "Equipe"
}
{
title: "Serviços"
url: AdminDashboard.path("/Slideshow")
collection: "Slideshow"
}
{
title: "Quem somos"
url: AdminDashboard.path("/QuemSomos")
collection: "QuemSomos"
}
{
title: "Equipe"
url: AdminDashboard.path("/Equipe")
collection: "<NAME>"
}
{
title: "Serviços"
url: AdminDashboard.path("/Slideshow")
collection: "Slideshow"
}
] | true | AdminDashboard.addSidebarItem "Configurações",
icon: 'gear'
urls: [
{
title: "Perfis de acesso"
url: AdminDashboard.path("/PerfisAcesso")
collection: "PerfisAcesso"
}
{
title: "Planos de saúde"
url: AdminDashboard.path("/PlanosSaude")
collection: "PlanosSaude"
}
{
title: "Tipo de provedor"
url: AdminDashboard.path("/ProvidersType")
collection: "ProvidersType"
}
{
title: "Tipo de serviços"
url: AdminDashboard.path("/ProvidersService")
collection: "ProvidersService"
}
]
AdminDashboard.addSidebarItem "Meus dados",
icon:'file-text-o'
urls: [
{
title: "Cadastrais"
url: AdminDashboard.path("/Providers")
collection: "Providers"
}
{
title: "Pets"
url: AdminDashboard.path("/Pets")
collection: "Pets"
}
{
title: "Locais de atendimento"
url: AdminDashboard.path("/ServiceLocation")
collection: "ServiceLocation"
}
]
AdminDashboard.addSidebarItem "Relatórios",
icon:'pie-chart'
urls: [
{
title: "Histórico de buscas"
url: AdminDashboard.path("/ProvidersHistorySearch")
collection: "ProvidersHistorySearch"
}
]
AdminDashboard.addSidebarItem "Site",
icon: "desktop"
urls: [
{
title: "Quem somos"
url: AdminDashboard.path("/QuemSomos")
collection: "QuemSomos"
}
{
title: "Equipe"
url: AdminDashboard.path("/Equipe")
collection: "Equipe"
}
{
title: "Serviços"
url: AdminDashboard.path("/Slideshow")
collection: "Slideshow"
}
{
title: "Quem somos"
url: AdminDashboard.path("/QuemSomos")
collection: "QuemSomos"
}
{
title: "Equipe"
url: AdminDashboard.path("/Equipe")
collection: "PI:NAME:<NAME>END_PI"
}
{
title: "Serviços"
url: AdminDashboard.path("/Slideshow")
collection: "Slideshow"
}
] |
[
{
"context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @",
"end": 33,
"score": 0.9998893141746521,
"start": 17,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
},
{
"context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki... | src/app/models/index.coffee | AbdelhakimRafik/Project | 1 | ###
* @author Abdelhakim RAFIK
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 Abdelhakim RAFIK
* @date June 2021
###
path = require 'path'
fs = require 'fs'
{ DataTypes } = require 'sequelize'
{ sequelize } = require '../../database'
associate = require './_associations'
# models container
models = {}
# read all models directory files
files = fs.readdirSync(__dirname).filter (file) ->
# exclude index file
return file.indexOf('.') isnt 0 and file isnt path.basename(__filename) and !file.startsWith('_') and file.slice(-3) is '.js'
# when error occured
unless files
return console.error 'An error occured while reading models', err
# add models to model object
for file in files
# add models to models container
model = require(path.join __dirname, file)(sequelize, DataTypes)
models[model.name] = model
# define associations
associate models
# export models
module.exports = models | 224681 | ###
* @author <NAME>
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 <NAME>
* @date June 2021
###
path = require 'path'
fs = require 'fs'
{ DataTypes } = require 'sequelize'
{ sequelize } = require '../../database'
associate = require './_associations'
# models container
models = {}
# read all models directory files
files = fs.readdirSync(__dirname).filter (file) ->
# exclude index file
return file.indexOf('.') isnt 0 and file isnt path.basename(__filename) and !file.startsWith('_') and file.slice(-3) is '.js'
# when error occured
unless files
return console.error 'An error occured while reading models', err
# add models to model object
for file in files
# add models to models container
model = require(path.join __dirname, file)(sequelize, DataTypes)
models[model.name] = model
# define associations
associate models
# export models
module.exports = models | true | ###
* @author PI:NAME:<NAME>END_PI
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI
* @date June 2021
###
path = require 'path'
fs = require 'fs'
{ DataTypes } = require 'sequelize'
{ sequelize } = require '../../database'
associate = require './_associations'
# models container
models = {}
# read all models directory files
files = fs.readdirSync(__dirname).filter (file) ->
# exclude index file
return file.indexOf('.') isnt 0 and file isnt path.basename(__filename) and !file.startsWith('_') and file.slice(-3) is '.js'
# when error occured
unless files
return console.error 'An error occured while reading models', err
# add models to model object
for file in files
# add models to models container
model = require(path.join __dirname, file)(sequelize, DataTypes)
models[model.name] = model
# define associations
associate models
# export models
module.exports = models |
[
{
"context": "ired http server hello world example\n# \n# (C) 2011 Tristan Slominski\n#\nanode = require '../lib/anode'\n\n# create a new ",
"end": 112,
"score": 0.9997749328613281,
"start": 95,
"tag": "NAME",
"value": "Tristan Slominski"
},
{
"context": "\n\n '#start' : ->\n @se... | examples/helloworld.example.coffee | tristanls/anodejs | 3 | #
# helloworld.example.coffee : node.js inspired http server hello world example
#
# (C) 2011 Tristan Slominski
#
anode = require '../lib/anode'
# create a new actor configuration
cnf = new anode.Configuration()
# create the http actor
httpServer = cnf.actor anode.http.server_beh()
# create the hello world application actor
helloworld = cnf.actor anode.beh( 'httpServer'
'#start' : ->
@send( @, '#listen', 8080, '127.0.0.1' ).to @httpServer
'$httpServer, #listen' : ->
@send( 'Server running at http://127.0.0.1:8080/' ).to cnf.console.log
'$httpServer, #request, request, response' : ->
@send( null, '#end', 'Hello Actor World\n' ).to @response
)( httpServer ) # helloworld
cnf.send( '#start' ).to helloworld | 133068 | #
# helloworld.example.coffee : node.js inspired http server hello world example
#
# (C) 2011 <NAME>
#
anode = require '../lib/anode'
# create a new actor configuration
cnf = new anode.Configuration()
# create the http actor
httpServer = cnf.actor anode.http.server_beh()
# create the hello world application actor
helloworld = cnf.actor anode.beh( 'httpServer'
'#start' : ->
@send( @, '#listen', 8080, '127.0.0.1' ).to @httpServer
'$httpServer, #listen' : ->
@send( 'Server running at http://127.0.0.1:8080/' ).to cnf.console.log
'$httpServer, #request, request, response' : ->
@send( null, '#end', 'Hello Actor World\n' ).to @response
)( httpServer ) # helloworld
cnf.send( '#start' ).to helloworld | true | #
# helloworld.example.coffee : node.js inspired http server hello world example
#
# (C) 2011 PI:NAME:<NAME>END_PI
#
anode = require '../lib/anode'
# create a new actor configuration
cnf = new anode.Configuration()
# create the http actor
httpServer = cnf.actor anode.http.server_beh()
# create the hello world application actor
helloworld = cnf.actor anode.beh( 'httpServer'
'#start' : ->
@send( @, '#listen', 8080, '127.0.0.1' ).to @httpServer
'$httpServer, #listen' : ->
@send( 'Server running at http://127.0.0.1:8080/' ).to cnf.console.log
'$httpServer, #request, request, response' : ->
@send( null, '#end', 'Hello Actor World\n' ).to @response
)( httpServer ) # helloworld
cnf.send( '#start' ).to helloworld |
[
{
"context": "(resolve, reject) ->\n if obj?.user == 'derhuerst'\n return resolve users[2]\n ",
"end": 305,
"score": 0.9997515082359314,
"start": 296,
"tag": "USERNAME",
"value": "derhuerst"
},
{
"context": "Name} = newIdentity\n Should(nickName)... | test/util/preSaveIdentity.coffee | brianshaler/kerplunk-github | 0 | Promise = require 'when'
PreSaveIdentity = require '../../src/util/preSaveIdentity'
System =
getSettings: -> Promise.resolve {}
getGitHub = (users) ->
(settings) ->
api =
user:
getFrom: (obj) ->
Promise.promise (resolve, reject) ->
if obj?.user == 'derhuerst'
return resolve users[2]
if obj?.user == 'fail'
return reject new Error 'because you told me to'
resolve()
describe 'preSaveIdentity', ->
before ->
@users = @fixture 'users.json'
beforeEach ->
@preSaveIdentity = PreSaveIdentity System, getGitHub(@users)
it 'should turn ignore an identity not from github', ->
identity = 'notFromGithub'
@preSaveIdentity(identity).should.equal identity
it 'should turn fetch profile from API if identity.data.github is from user list', (done) ->
identity =
data:
github: @users[0]
promise = @preSaveIdentity identity
Should.exist promise?.then
promise.then (newIdentity) =>
Should.exist newIdentity?.data?.github?.name
newIdentity.data.github.name.should.equal @users[2].name
done()
.catch (err) -> done err
it 'should turn fetch profile from API if identity.data.github is an actor', (done) ->
identity =
data:
github: @users[1]
promise = @preSaveIdentity identity
Should.exist promise?.then
promise.then (newIdentity) =>
Should.exist newIdentity?.data?.github?.name
newIdentity.data.github.name.should.equal @users[2].name
done()
.catch (err) -> done err
it 'should populate name fields after fetching complete profile', (done) ->
identity =
data:
github: @users[1]
promise = @preSaveIdentity identity
Should.exist promise?.then
promise.then (newIdentity) =>
{nickName, fullName, firstName, lastName} = newIdentity
Should(nickName).equal 'derhuerst'
Should(fullName).equal 'Jannis Redmann'
Should(firstName).equal 'Jannis'
Should(lastName).equal 'Redmann'
done()
.catch (err) -> done err
| 177338 | Promise = require 'when'
PreSaveIdentity = require '../../src/util/preSaveIdentity'
System =
getSettings: -> Promise.resolve {}
getGitHub = (users) ->
(settings) ->
api =
user:
getFrom: (obj) ->
Promise.promise (resolve, reject) ->
if obj?.user == 'derhuerst'
return resolve users[2]
if obj?.user == 'fail'
return reject new Error 'because you told me to'
resolve()
describe 'preSaveIdentity', ->
before ->
@users = @fixture 'users.json'
beforeEach ->
@preSaveIdentity = PreSaveIdentity System, getGitHub(@users)
it 'should turn ignore an identity not from github', ->
identity = 'notFromGithub'
@preSaveIdentity(identity).should.equal identity
it 'should turn fetch profile from API if identity.data.github is from user list', (done) ->
identity =
data:
github: @users[0]
promise = @preSaveIdentity identity
Should.exist promise?.then
promise.then (newIdentity) =>
Should.exist newIdentity?.data?.github?.name
newIdentity.data.github.name.should.equal @users[2].name
done()
.catch (err) -> done err
it 'should turn fetch profile from API if identity.data.github is an actor', (done) ->
identity =
data:
github: @users[1]
promise = @preSaveIdentity identity
Should.exist promise?.then
promise.then (newIdentity) =>
Should.exist newIdentity?.data?.github?.name
newIdentity.data.github.name.should.equal @users[2].name
done()
.catch (err) -> done err
it 'should populate name fields after fetching complete profile', (done) ->
identity =
data:
github: @users[1]
promise = @preSaveIdentity identity
Should.exist promise?.then
promise.then (newIdentity) =>
{nickName, fullName, firstName, lastName} = newIdentity
Should(nickName).equal 'derhuerst'
Should(fullName).equal '<NAME>'
Should(firstName).equal '<NAME>'
Should(lastName).equal '<NAME>'
done()
.catch (err) -> done err
| true | Promise = require 'when'
PreSaveIdentity = require '../../src/util/preSaveIdentity'
System =
getSettings: -> Promise.resolve {}
getGitHub = (users) ->
(settings) ->
api =
user:
getFrom: (obj) ->
Promise.promise (resolve, reject) ->
if obj?.user == 'derhuerst'
return resolve users[2]
if obj?.user == 'fail'
return reject new Error 'because you told me to'
resolve()
describe 'preSaveIdentity', ->
before ->
@users = @fixture 'users.json'
beforeEach ->
@preSaveIdentity = PreSaveIdentity System, getGitHub(@users)
it 'should turn ignore an identity not from github', ->
identity = 'notFromGithub'
@preSaveIdentity(identity).should.equal identity
it 'should turn fetch profile from API if identity.data.github is from user list', (done) ->
identity =
data:
github: @users[0]
promise = @preSaveIdentity identity
Should.exist promise?.then
promise.then (newIdentity) =>
Should.exist newIdentity?.data?.github?.name
newIdentity.data.github.name.should.equal @users[2].name
done()
.catch (err) -> done err
it 'should turn fetch profile from API if identity.data.github is an actor', (done) ->
identity =
data:
github: @users[1]
promise = @preSaveIdentity identity
Should.exist promise?.then
promise.then (newIdentity) =>
Should.exist newIdentity?.data?.github?.name
newIdentity.data.github.name.should.equal @users[2].name
done()
.catch (err) -> done err
it 'should populate name fields after fetching complete profile', (done) ->
identity =
data:
github: @users[1]
promise = @preSaveIdentity identity
Should.exist promise?.then
promise.then (newIdentity) =>
{nickName, fullName, firstName, lastName} = newIdentity
Should(nickName).equal 'derhuerst'
Should(fullName).equal 'PI:NAME:<NAME>END_PI'
Should(firstName).equal 'PI:NAME:<NAME>END_PI'
Should(lastName).equal 'PI:NAME:<NAME>END_PI'
done()
.catch (err) -> done err
|
[
{
"context": "/span>'\n 'USGS monitoring ecological impacts'\n \"P. M. S. \\\\ensuremath<span class='Hi'\\\\ensuremath>Hacker\\\\",
"end": 279,
"score": 0.9840350151062012,
"start": 272,
"tag": "NAME",
"value": "P. M. S"
}
] | minitests/markup.coffee | edwinksl/zotero-better-bibtex | 0 | input = [
'Between the Urban City and <the <span class="nocase">Rural</span>: <span class="nocase">Negotiating Place</span> and <span class="nocase">Identity</span> in a <span class="nocase">Danish Suburban Housing Area</span>'
'USGS monitoring ecological impacts'
"P. M. S. \\ensuremath<span class='Hi'\\ensuremath>Hacker\\ensuremath</span\\ensuremath> 1. The ?confusion of psychology? On the concluding page of what is now called ?Part II? of the Investigations, Wittgenstein wrote.."
"The physical: violent <span id='none'>volcanology</span> of <span>the</span> 1600 eruption of Huaynaputina, southern Peru"
"Test of markupconversion: Italics, bold, superscript, subscript, and small caps: Mitochondrial DNA<sub>2</sub> sequences suggest unexpected phylogenetic position of Corso-Sardinian grass snakes (<i>Natrix cetti</i>) and <b>do not</b> support their <span style=\"small-caps\">species status</span>, with notes on phylogeography and subspecies delineation of grass snakes."
]
titleCase = (html, titleCased, positions) ->
pt = ''
for c, i in html
if positions[i] != undefined
pt += titleCased[positions[i]]
else
pt += c
console.log('.: ' + pt)
return pt
for text in input
{html, plain} = BetterBibTeXMarkupParser.parse(text, {titleCase: true, preserveCaps: true})
titlecased = new Array(plain.text.length + 1).join('.')
console.log('')
console.log('T: ' + text)
console.log('H: ' + html)
console.log('P: ' + plain.text)
console.log('C: ' + titleCase(html, titlecased, plain.unprotected))
| 185207 | input = [
'Between the Urban City and <the <span class="nocase">Rural</span>: <span class="nocase">Negotiating Place</span> and <span class="nocase">Identity</span> in a <span class="nocase">Danish Suburban Housing Area</span>'
'USGS monitoring ecological impacts'
"<NAME>. \\ensuremath<span class='Hi'\\ensuremath>Hacker\\ensuremath</span\\ensuremath> 1. The ?confusion of psychology? On the concluding page of what is now called ?Part II? of the Investigations, Wittgenstein wrote.."
"The physical: violent <span id='none'>volcanology</span> of <span>the</span> 1600 eruption of Huaynaputina, southern Peru"
"Test of markupconversion: Italics, bold, superscript, subscript, and small caps: Mitochondrial DNA<sub>2</sub> sequences suggest unexpected phylogenetic position of Corso-Sardinian grass snakes (<i>Natrix cetti</i>) and <b>do not</b> support their <span style=\"small-caps\">species status</span>, with notes on phylogeography and subspecies delineation of grass snakes."
]
titleCase = (html, titleCased, positions) ->
pt = ''
for c, i in html
if positions[i] != undefined
pt += titleCased[positions[i]]
else
pt += c
console.log('.: ' + pt)
return pt
for text in input
{html, plain} = BetterBibTeXMarkupParser.parse(text, {titleCase: true, preserveCaps: true})
titlecased = new Array(plain.text.length + 1).join('.')
console.log('')
console.log('T: ' + text)
console.log('H: ' + html)
console.log('P: ' + plain.text)
console.log('C: ' + titleCase(html, titlecased, plain.unprotected))
| true | input = [
'Between the Urban City and <the <span class="nocase">Rural</span>: <span class="nocase">Negotiating Place</span> and <span class="nocase">Identity</span> in a <span class="nocase">Danish Suburban Housing Area</span>'
'USGS monitoring ecological impacts'
"PI:NAME:<NAME>END_PI. \\ensuremath<span class='Hi'\\ensuremath>Hacker\\ensuremath</span\\ensuremath> 1. The ?confusion of psychology? On the concluding page of what is now called ?Part II? of the Investigations, Wittgenstein wrote.."
"The physical: violent <span id='none'>volcanology</span> of <span>the</span> 1600 eruption of Huaynaputina, southern Peru"
"Test of markupconversion: Italics, bold, superscript, subscript, and small caps: Mitochondrial DNA<sub>2</sub> sequences suggest unexpected phylogenetic position of Corso-Sardinian grass snakes (<i>Natrix cetti</i>) and <b>do not</b> support their <span style=\"small-caps\">species status</span>, with notes on phylogeography and subspecies delineation of grass snakes."
]
titleCase = (html, titleCased, positions) ->
pt = ''
for c, i in html
if positions[i] != undefined
pt += titleCased[positions[i]]
else
pt += c
console.log('.: ' + pt)
return pt
for text in input
{html, plain} = BetterBibTeXMarkupParser.parse(text, {titleCase: true, preserveCaps: true})
titlecased = new Array(plain.text.length + 1).join('.')
console.log('')
console.log('T: ' + text)
console.log('H: ' + html)
console.log('P: ' + plain.text)
console.log('C: ' + titleCase(html, titlecased, plain.unprotected))
|
[
{
"context": "atedAt\").val())\n\t\t\t\tresultsKey = userCreatedMoment.format(\"MMM DD\")\n\t\t\t\tresults[resultsKey] = (results[resu",
"end": 2262,
"score": 0.5450469255447388,
"start": 2256,
"tag": "KEY",
"value": "format"
},
{
"context": "val())\n\t\t\t\tresultsKey = userCreatedM... | scripts/analytics/num_registrations_per_day.coffee | willroberts/duelyst | 5 |
###
num_registrations_per_day - Takes a number of days to look back (assumes 5) and reports how many user registrations occurred per utc day
Examples:
num_registrations_per_day 7
###
# region Requires
# Configuration object
config = require("../../config/config.js")
Promise = require 'bluebird'
Firebase = require("firebase")
_ = require("underscore")
fbRef = new Firebase(config.get("firebase"))
moment = require('moment')
Logger = require '../../app/common/logger.coffee'
# Firebase secure token for duelyst-dev.firebaseio.com
firebaseToken = config.get("firebaseToken")
UsersModule = require("../../server/lib/users_module")
DuelystFirebase = require("../../server/lib/duelyst_firebase_module")
fbUtil = require '../../app/common/utils/utils_firebase.js'
# endregion Requires
# Resolves to an object filled with key-value pairs of (utc date)->(number of users registered on that date)
# Accepts a number of completed days to look back in time for users (reports current partial day but doesn't count it as one of the lookback days)
num_registrations_per_day = (numDaysToLookBack=5) ->
startTodayMoment = moment().startOf('day')
oldestDayToRetrieve = startTodayMoment.subtract(numDaysToLookBack,'days')
results = {}
Logger.module("Script").log(("num_registrations_per_day() -> looking back " + numDaysToLookBack + " days").green)
DuelystFirebase.connect().getRootRef()
.bind({})
.then (fbRootRef) ->
# Retrieves the most recently registered user so we know when we've retrieved all registered users in our range
@fbRootRef = fbRootRef
return new Promise( (resolve,reject) ->
usersRef = fbRootRef.child("users")
usersRef.orderByChild("createdAt").limitToLast(1).on("child_added", (snapshot) ->
Logger.module("Script").log(("num_registrations_per_day() -> Most recently registered user id is: " + snapshot.key()).green)
return resolve(snapshot.key())
)
)
.then (mostRecentRegistrationKey) ->
usersRef = @fbRootRef.child("users")
return new Promise( (resolve, reject) ->
usersRef.orderByChild("createdAt").startAt(oldestDayToRetrieve.valueOf()).endAt(moment().valueOf()).on("child_added", (snapshot) ->
userCreatedMoment = moment(snapshot.child("createdAt").val())
resultsKey = userCreatedMoment.format("MMM DD")
results[resultsKey] = (results[resultsKey] or 0) + 1
if snapshot.key() == mostRecentRegistrationKey
Logger.module("Script").log("num_registrations_per_day() -> processed most recently registered user.".green)
return resolve(results)
)
)
# Handle execution as a script
if process.argv[1].toString().indexOf('num_registrations_per_day.coffee') != -1
if process.argv[2]
numDaysToLookBack = parseInt(process.argv[2])
if (isNaN(numDaysToLookBack))
numDaysToLookBack = undefined
# Begin script execution
console.log process.argv
num_registrations_per_day(numDaysToLookBack)
.then (results) ->
Logger.module("Script").log(("num_registrations_per_day() -> results\n" + JSON.stringify(results,null,2)).blue)
process.exit(1);
module.exports = num_registrations_per_day
| 70446 |
###
num_registrations_per_day - Takes a number of days to look back (assumes 5) and reports how many user registrations occurred per utc day
Examples:
num_registrations_per_day 7
###
# region Requires
# Configuration object
config = require("../../config/config.js")
Promise = require 'bluebird'
Firebase = require("firebase")
_ = require("underscore")
fbRef = new Firebase(config.get("firebase"))
moment = require('moment')
Logger = require '../../app/common/logger.coffee'
# Firebase secure token for duelyst-dev.firebaseio.com
firebaseToken = config.get("firebaseToken")
UsersModule = require("../../server/lib/users_module")
DuelystFirebase = require("../../server/lib/duelyst_firebase_module")
fbUtil = require '../../app/common/utils/utils_firebase.js'
# endregion Requires
# Resolves to an object filled with key-value pairs of (utc date)->(number of users registered on that date)
# Accepts a number of completed days to look back in time for users (reports current partial day but doesn't count it as one of the lookback days)
num_registrations_per_day = (numDaysToLookBack=5) ->
startTodayMoment = moment().startOf('day')
oldestDayToRetrieve = startTodayMoment.subtract(numDaysToLookBack,'days')
results = {}
Logger.module("Script").log(("num_registrations_per_day() -> looking back " + numDaysToLookBack + " days").green)
DuelystFirebase.connect().getRootRef()
.bind({})
.then (fbRootRef) ->
# Retrieves the most recently registered user so we know when we've retrieved all registered users in our range
@fbRootRef = fbRootRef
return new Promise( (resolve,reject) ->
usersRef = fbRootRef.child("users")
usersRef.orderByChild("createdAt").limitToLast(1).on("child_added", (snapshot) ->
Logger.module("Script").log(("num_registrations_per_day() -> Most recently registered user id is: " + snapshot.key()).green)
return resolve(snapshot.key())
)
)
.then (mostRecentRegistrationKey) ->
usersRef = @fbRootRef.child("users")
return new Promise( (resolve, reject) ->
usersRef.orderByChild("createdAt").startAt(oldestDayToRetrieve.valueOf()).endAt(moment().valueOf()).on("child_added", (snapshot) ->
userCreatedMoment = moment(snapshot.child("createdAt").val())
resultsKey = userCreatedMoment.<KEY>("<KEY>")
results[resultsKey] = (results[resultsKey] or 0) + 1
if snapshot.key() == mostRecentRegistrationKey
Logger.module("Script").log("num_registrations_per_day() -> processed most recently registered user.".green)
return resolve(results)
)
)
# Handle execution as a script
if process.argv[1].toString().indexOf('num_registrations_per_day.coffee') != -1
if process.argv[2]
numDaysToLookBack = parseInt(process.argv[2])
if (isNaN(numDaysToLookBack))
numDaysToLookBack = undefined
# Begin script execution
console.log process.argv
num_registrations_per_day(numDaysToLookBack)
.then (results) ->
Logger.module("Script").log(("num_registrations_per_day() -> results\n" + JSON.stringify(results,null,2)).blue)
process.exit(1);
module.exports = num_registrations_per_day
| true |
###
num_registrations_per_day - Takes a number of days to look back (assumes 5) and reports how many user registrations occurred per utc day
Examples:
num_registrations_per_day 7
###
# region Requires
# Configuration object
config = require("../../config/config.js")
Promise = require 'bluebird'
Firebase = require("firebase")
_ = require("underscore")
fbRef = new Firebase(config.get("firebase"))
moment = require('moment')
Logger = require '../../app/common/logger.coffee'
# Firebase secure token for duelyst-dev.firebaseio.com
firebaseToken = config.get("firebaseToken")
UsersModule = require("../../server/lib/users_module")
DuelystFirebase = require("../../server/lib/duelyst_firebase_module")
fbUtil = require '../../app/common/utils/utils_firebase.js'
# endregion Requires
# Resolves to an object filled with key-value pairs of (utc date)->(number of users registered on that date)
# Accepts a number of completed days to look back in time for users (reports current partial day but doesn't count it as one of the lookback days)
num_registrations_per_day = (numDaysToLookBack=5) ->
startTodayMoment = moment().startOf('day')
oldestDayToRetrieve = startTodayMoment.subtract(numDaysToLookBack,'days')
results = {}
Logger.module("Script").log(("num_registrations_per_day() -> looking back " + numDaysToLookBack + " days").green)
DuelystFirebase.connect().getRootRef()
.bind({})
.then (fbRootRef) ->
# Retrieves the most recently registered user so we know when we've retrieved all registered users in our range
@fbRootRef = fbRootRef
return new Promise( (resolve,reject) ->
usersRef = fbRootRef.child("users")
usersRef.orderByChild("createdAt").limitToLast(1).on("child_added", (snapshot) ->
Logger.module("Script").log(("num_registrations_per_day() -> Most recently registered user id is: " + snapshot.key()).green)
return resolve(snapshot.key())
)
)
.then (mostRecentRegistrationKey) ->
usersRef = @fbRootRef.child("users")
return new Promise( (resolve, reject) ->
usersRef.orderByChild("createdAt").startAt(oldestDayToRetrieve.valueOf()).endAt(moment().valueOf()).on("child_added", (snapshot) ->
userCreatedMoment = moment(snapshot.child("createdAt").val())
resultsKey = userCreatedMoment.PI:KEY:<KEY>END_PI("PI:KEY:<KEY>END_PI")
results[resultsKey] = (results[resultsKey] or 0) + 1
if snapshot.key() == mostRecentRegistrationKey
Logger.module("Script").log("num_registrations_per_day() -> processed most recently registered user.".green)
return resolve(results)
)
)
# Handle execution as a script
if process.argv[1].toString().indexOf('num_registrations_per_day.coffee') != -1
if process.argv[2]
numDaysToLookBack = parseInt(process.argv[2])
if (isNaN(numDaysToLookBack))
numDaysToLookBack = undefined
# Begin script execution
console.log process.argv
num_registrations_per_day(numDaysToLookBack)
.then (results) ->
Logger.module("Script").log(("num_registrations_per_day() -> results\n" + JSON.stringify(results,null,2)).blue)
process.exit(1);
module.exports = num_registrations_per_day
|
[
{
"context": "id + '/invite-members'\n data = { emails: ['test@test.com'] }\n request.post { uri: url, json: data }",
"end": 6866,
"score": 0.9998854398727417,
"start": 6853,
"tag": "EMAIL",
"value": "test@test.com"
}
] | spec/server/functional/classrooms.spec.coffee | JurianLock/codecombat | 1 | config = require '../../../server_config'
require '../common'
utils = require '../../../app/core/utils' # Must come after require /common
mongoose = require 'mongoose'
classroomsURL = getURL('/db/classroom')
describe 'GET /db/classroom?ownerID=:id', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'returns an array of classrooms with the given owner', (done) ->
loginNewUser (user1) ->
new Classroom({name: 'Classroom 1', ownerID: user1.get('_id') }).save (err, classroom) ->
expect(err).toBeNull()
loginNewUser (user2) ->
new Classroom({name: 'Classroom 2', ownerID: user2.get('_id') }).save (err, classroom) ->
expect(err).toBeNull()
url = getURL('/db/classroom?ownerID='+user2.id)
request.get { uri: url, json: true }, (err, res, body) ->
expect(res.statusCode).toBe(200)
expect(body.length).toBe(1)
expect(body[0].name).toBe('Classroom 2')
done()
it 'returns 403 when a non-admin tries to get classrooms for another user', (done) ->
loginNewUser (user1) ->
loginNewUser (user2) ->
url = getURL('/db/classroom?ownerID='+user1.id)
request.get { uri: url }, (err, res, body) ->
expect(res.statusCode).toBe(403)
done()
describe 'GET /db/classroom/:id', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'returns the classroom for the given id', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 1' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
classroomID = body._id
request.get {uri: classroomsURL + '/' + body._id }, (err, res, body) ->
expect(res.statusCode).toBe(200)
expect(body._id).toBe(classroomID = body._id)
done()
describe 'POST /db/classroom', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'creates a new classroom for the given user', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 1' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
expect(body.name).toBe('Classroom 1')
expect(body.members.length).toBe(0)
expect(body.ownerID).toBe(user1.id)
done()
it 'does not work for anonymous users', (done) ->
logoutUser ->
data = { name: 'Classroom 2' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(401)
done()
describe 'PUT /db/classroom', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'edits name and description', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 2' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
data = { name: 'Classroom 3', description: 'New Description' }
url = classroomsURL + '/' + body._id
request.put { uri: url, json: data }, (err, res, body) ->
expect(body.name).toBe('Classroom 3')
expect(body.description).toBe('New Description')
done()
it 'is not allowed if you are just a member', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 4' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
classroomCode = body.code
loginNewUser (user2) ->
url = getURL("/db/classroom/~/members")
data = { code: classroomCode }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
url = classroomsURL + '/' + body._id
request.put { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(403)
done()
describe 'POST /db/classroom/~/members', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'adds the signed in user to the list of members in the classroom', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 5' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
classroomCode = body.code
classroomID = body._id
expect(res.statusCode).toBe(200)
loginNewUser (user2) ->
url = getURL("/db/classroom/~/members")
data = { code: classroomCode }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
Classroom.findById classroomID, (err, classroom) ->
expect(classroom.get('members').length).toBe(1)
done()
describe 'DELETE /db/classroom/:id/members', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'removes the given user from the list of members in the classroom', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 6' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
classroomCode = body.code
classroomID = body._id
expect(res.statusCode).toBe(200)
loginNewUser (user2) ->
url = getURL("/db/classroom/~/members")
data = { code: classroomCode }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
Classroom.findById classroomID, (err, classroom) ->
expect(classroom.get('members').length).toBe(1)
url = getURL("/db/classroom/#{classroom.id}/members")
data = { userID: user2.id }
request.del { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
Classroom.findById classroomID, (err, classroom) ->
expect(classroom.get('members').length).toBe(0)
done()
describe 'POST /db/classroom/:id/invite-members', ->
it 'takes a list of emails and sends invites', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 6' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
url = classroomsURL + '/' + body._id + '/invite-members'
data = { emails: ['test@test.com'] }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
done()
| 166886 | config = require '../../../server_config'
require '../common'
utils = require '../../../app/core/utils' # Must come after require /common
mongoose = require 'mongoose'
classroomsURL = getURL('/db/classroom')
describe 'GET /db/classroom?ownerID=:id', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'returns an array of classrooms with the given owner', (done) ->
loginNewUser (user1) ->
new Classroom({name: 'Classroom 1', ownerID: user1.get('_id') }).save (err, classroom) ->
expect(err).toBeNull()
loginNewUser (user2) ->
new Classroom({name: 'Classroom 2', ownerID: user2.get('_id') }).save (err, classroom) ->
expect(err).toBeNull()
url = getURL('/db/classroom?ownerID='+user2.id)
request.get { uri: url, json: true }, (err, res, body) ->
expect(res.statusCode).toBe(200)
expect(body.length).toBe(1)
expect(body[0].name).toBe('Classroom 2')
done()
it 'returns 403 when a non-admin tries to get classrooms for another user', (done) ->
loginNewUser (user1) ->
loginNewUser (user2) ->
url = getURL('/db/classroom?ownerID='+user1.id)
request.get { uri: url }, (err, res, body) ->
expect(res.statusCode).toBe(403)
done()
describe 'GET /db/classroom/:id', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'returns the classroom for the given id', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 1' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
classroomID = body._id
request.get {uri: classroomsURL + '/' + body._id }, (err, res, body) ->
expect(res.statusCode).toBe(200)
expect(body._id).toBe(classroomID = body._id)
done()
describe 'POST /db/classroom', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'creates a new classroom for the given user', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 1' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
expect(body.name).toBe('Classroom 1')
expect(body.members.length).toBe(0)
expect(body.ownerID).toBe(user1.id)
done()
it 'does not work for anonymous users', (done) ->
logoutUser ->
data = { name: 'Classroom 2' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(401)
done()
describe 'PUT /db/classroom', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'edits name and description', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 2' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
data = { name: 'Classroom 3', description: 'New Description' }
url = classroomsURL + '/' + body._id
request.put { uri: url, json: data }, (err, res, body) ->
expect(body.name).toBe('Classroom 3')
expect(body.description).toBe('New Description')
done()
it 'is not allowed if you are just a member', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 4' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
classroomCode = body.code
loginNewUser (user2) ->
url = getURL("/db/classroom/~/members")
data = { code: classroomCode }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
url = classroomsURL + '/' + body._id
request.put { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(403)
done()
describe 'POST /db/classroom/~/members', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'adds the signed in user to the list of members in the classroom', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 5' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
classroomCode = body.code
classroomID = body._id
expect(res.statusCode).toBe(200)
loginNewUser (user2) ->
url = getURL("/db/classroom/~/members")
data = { code: classroomCode }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
Classroom.findById classroomID, (err, classroom) ->
expect(classroom.get('members').length).toBe(1)
done()
describe 'DELETE /db/classroom/:id/members', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'removes the given user from the list of members in the classroom', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 6' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
classroomCode = body.code
classroomID = body._id
expect(res.statusCode).toBe(200)
loginNewUser (user2) ->
url = getURL("/db/classroom/~/members")
data = { code: classroomCode }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
Classroom.findById classroomID, (err, classroom) ->
expect(classroom.get('members').length).toBe(1)
url = getURL("/db/classroom/#{classroom.id}/members")
data = { userID: user2.id }
request.del { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
Classroom.findById classroomID, (err, classroom) ->
expect(classroom.get('members').length).toBe(0)
done()
describe 'POST /db/classroom/:id/invite-members', ->
it 'takes a list of emails and sends invites', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 6' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
url = classroomsURL + '/' + body._id + '/invite-members'
data = { emails: ['<EMAIL>'] }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
done()
| true | config = require '../../../server_config'
require '../common'
utils = require '../../../app/core/utils' # Must come after require /common
mongoose = require 'mongoose'
classroomsURL = getURL('/db/classroom')
describe 'GET /db/classroom?ownerID=:id', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'returns an array of classrooms with the given owner', (done) ->
loginNewUser (user1) ->
new Classroom({name: 'Classroom 1', ownerID: user1.get('_id') }).save (err, classroom) ->
expect(err).toBeNull()
loginNewUser (user2) ->
new Classroom({name: 'Classroom 2', ownerID: user2.get('_id') }).save (err, classroom) ->
expect(err).toBeNull()
url = getURL('/db/classroom?ownerID='+user2.id)
request.get { uri: url, json: true }, (err, res, body) ->
expect(res.statusCode).toBe(200)
expect(body.length).toBe(1)
expect(body[0].name).toBe('Classroom 2')
done()
it 'returns 403 when a non-admin tries to get classrooms for another user', (done) ->
loginNewUser (user1) ->
loginNewUser (user2) ->
url = getURL('/db/classroom?ownerID='+user1.id)
request.get { uri: url }, (err, res, body) ->
expect(res.statusCode).toBe(403)
done()
describe 'GET /db/classroom/:id', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'returns the classroom for the given id', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 1' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
classroomID = body._id
request.get {uri: classroomsURL + '/' + body._id }, (err, res, body) ->
expect(res.statusCode).toBe(200)
expect(body._id).toBe(classroomID = body._id)
done()
describe 'POST /db/classroom', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'creates a new classroom for the given user', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 1' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
expect(body.name).toBe('Classroom 1')
expect(body.members.length).toBe(0)
expect(body.ownerID).toBe(user1.id)
done()
it 'does not work for anonymous users', (done) ->
logoutUser ->
data = { name: 'Classroom 2' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(401)
done()
describe 'PUT /db/classroom', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'edits name and description', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 2' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
data = { name: 'Classroom 3', description: 'New Description' }
url = classroomsURL + '/' + body._id
request.put { uri: url, json: data }, (err, res, body) ->
expect(body.name).toBe('Classroom 3')
expect(body.description).toBe('New Description')
done()
it 'is not allowed if you are just a member', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 4' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
classroomCode = body.code
loginNewUser (user2) ->
url = getURL("/db/classroom/~/members")
data = { code: classroomCode }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
url = classroomsURL + '/' + body._id
request.put { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(403)
done()
describe 'POST /db/classroom/~/members', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'adds the signed in user to the list of members in the classroom', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 5' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
classroomCode = body.code
classroomID = body._id
expect(res.statusCode).toBe(200)
loginNewUser (user2) ->
url = getURL("/db/classroom/~/members")
data = { code: classroomCode }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
Classroom.findById classroomID, (err, classroom) ->
expect(classroom.get('members').length).toBe(1)
done()
describe 'DELETE /db/classroom/:id/members', ->
it 'clears database users and classrooms', (done) ->
clearModels [User, Classroom], (err) ->
throw err if err
done()
it 'removes the given user from the list of members in the classroom', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 6' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
classroomCode = body.code
classroomID = body._id
expect(res.statusCode).toBe(200)
loginNewUser (user2) ->
url = getURL("/db/classroom/~/members")
data = { code: classroomCode }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
Classroom.findById classroomID, (err, classroom) ->
expect(classroom.get('members').length).toBe(1)
url = getURL("/db/classroom/#{classroom.id}/members")
data = { userID: user2.id }
request.del { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
Classroom.findById classroomID, (err, classroom) ->
expect(classroom.get('members').length).toBe(0)
done()
describe 'POST /db/classroom/:id/invite-members', ->
it 'takes a list of emails and sends invites', (done) ->
loginNewUser (user1) ->
data = { name: 'Classroom 6' }
request.post {uri: classroomsURL, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
url = classroomsURL + '/' + body._id + '/invite-members'
data = { emails: ['PI:EMAIL:<EMAIL>END_PI'] }
request.post { uri: url, json: data }, (err, res, body) ->
expect(res.statusCode).toBe(200)
done()
|
[
{
"context": "#\n# Rails main file\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\n\ninclude 'src/ujs'\n\nexports.version = '%{versio",
"end": 60,
"score": 0.9998799562454224,
"start": 43,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/rails/main.coffee | lovely-io/lovely.io-stl | 2 | #
# Rails main file
#
# Copyright (C) 2011 Nikolay Nemshilov
#
include 'src/ujs'
exports.version = '%{version}' | 84633 | #
# Rails main file
#
# Copyright (C) 2011 <NAME>
#
include 'src/ujs'
exports.version = '%{version}' | true | #
# Rails main file
#
# Copyright (C) 2011 PI:NAME:<NAME>END_PI
#
include 'src/ujs'
exports.version = '%{version}' |
[
{
"context": " classes for web apps.\"\nversion: \"0.5.4\"\nauthor: \"Meryn Stol <merynstol@gmail.com>\"\nmain: \"./lib/_\"\nrepository",
"end": 106,
"score": 0.9999009966850281,
"start": 96,
"tag": "NAME",
"value": "Meryn Stol"
},
{
"context": " web apps.\"\nversion: \"0.5.4\"\nauth... | package.coffee | braveg1rl/passthrough | 0 | name: "passthrough"
description: "Tiny utility classes for web apps."
version: "0.5.4"
author: "Meryn Stol <merynstol@gmail.com>"
main: "./lib/_"
repository:
type: "git"
url: "git://github.com/meryn/passthrough.git"
dependencies:
qs: "0.4.x"
underscore: "1.x"
watch: "0.5.x"
"node.extend": "1.x"
environ: "1.x"
watchr: "2.x"
devDependencies:
vows: "0.6.x"
engines:
node: "0.8.x"
npm: "1.1.x"
optionalDependencies: {}
homepage: "https://github.com/meryn/passthrough" | 68691 | name: "passthrough"
description: "Tiny utility classes for web apps."
version: "0.5.4"
author: "<NAME> <<EMAIL>>"
main: "./lib/_"
repository:
type: "git"
url: "git://github.com/meryn/passthrough.git"
dependencies:
qs: "0.4.x"
underscore: "1.x"
watch: "0.5.x"
"node.extend": "1.x"
environ: "1.x"
watchr: "2.x"
devDependencies:
vows: "0.6.x"
engines:
node: "0.8.x"
npm: "1.1.x"
optionalDependencies: {}
homepage: "https://github.com/meryn/passthrough" | true | name: "passthrough"
description: "Tiny utility classes for web apps."
version: "0.5.4"
author: "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
main: "./lib/_"
repository:
type: "git"
url: "git://github.com/meryn/passthrough.git"
dependencies:
qs: "0.4.x"
underscore: "1.x"
watch: "0.5.x"
"node.extend": "1.x"
environ: "1.x"
watchr: "2.x"
devDependencies:
vows: "0.6.x"
engines:
node: "0.8.x"
npm: "1.1.x"
optionalDependencies: {}
homepage: "https://github.com/meryn/passthrough" |
[
{
"context": " assert.equal(perms.admin[0], 'acct:flash@gordon')\n\n it 'returns null if session.state.userid",
"end": 1946,
"score": 0.9923137426376343,
"start": 1941,
"tag": "NAME",
"value": "ordon"
},
{
"context": "n = {\n read: ['group:__world__', 'acct:ang... | h/static/scripts/test/permissions-test.coffee | noscripter/h | 0 | {module, inject} = angular.mock
describe 'h:permissions', ->
sandbox = null
fakeSession = null
fakeLocalStorage = null
before ->
angular.module('h', [])
.service('permissions', require('../permissions'))
beforeEach module('h')
beforeEach module ($provide) ->
sandbox = sinon.sandbox.create()
fakeSession = {
state: {
userid: 'acct:flash@gordon'
}
}
fakeLocalStorage = {
getItem: -> undefined
}
$provide.value 'session', fakeSession
$provide.value 'localStorage', fakeLocalStorage
return
afterEach ->
sandbox.restore()
describe 'permissions service', ->
permissions = null
beforeEach inject (_permissions_) ->
permissions = _permissions_
describe 'private()', ->
it 'fills all permissions with auth.user', ->
perms = permissions.private()
assert.equal(perms.read[0], 'acct:flash@gordon')
assert.equal(perms.update[0], 'acct:flash@gordon')
assert.equal(perms.delete[0], 'acct:flash@gordon')
assert.equal(perms.admin[0], 'acct:flash@gordon')
it 'returns null if session.state.userid is falsey', ->
delete fakeSession.state.userid
assert.equal(permissions.private(), null)
describe 'shared()', ->
it 'fills the read property with group:__world__', ->
perms = permissions.shared()
assert.equal(perms.read[0], 'group:__world__')
assert.equal(perms.update[0], 'acct:flash@gordon')
assert.equal(perms.delete[0], 'acct:flash@gordon')
assert.equal(perms.admin[0], 'acct:flash@gordon')
it 'fills the read property with group:foo if passed "foo"', ->
perms = permissions.shared("foo")
assert.equal(perms.read[0], 'group:foo')
assert.equal(perms.update[0], 'acct:flash@gordon')
assert.equal(perms.delete[0], 'acct:flash@gordon')
assert.equal(perms.admin[0], 'acct:flash@gordon')
it 'returns null if session.state.userid is falsey', ->
delete fakeSession.state.userid
assert.equal(permissions.shared("foo"), null)
describe 'default()', ->
it 'returns shared permissions if localStorage contains "shared"', ->
fakeLocalStorage.getItem = -> 'shared'
assert(permissions.isShared(permissions.default()))
it 'returns private permissions if localStorage contains "private"', ->
fakeLocalStorage.getItem = -> 'private'
assert(permissions.isPrivate(
permissions.default(), fakeSession.state.userid))
it 'returns shared permissions if localStorage is empty', ->
fakeLocalStorage.getItem = -> undefined
assert(permissions.isShared(permissions.default()))
describe 'setDefault()', ->
it 'sets the default permissions that default() will return', ->
stored = {}
fakeLocalStorage.setItem = (key, value) ->
stored[key] = value
fakeLocalStorage.getItem = (key) ->
return stored[key]
permissions.setDefault('private')
assert(permissions.isPrivate(
permissions.default(), fakeSession.state.userid))
permissions.setDefault('shared')
assert(permissions.isShared(
permissions.default('foo'), 'foo'))
describe 'isPublic', ->
it 'isPublic() true if the read permission has group:__world__ in it', ->
permission = {
read: ['group:__world__', 'acct:angry@birds.com']
}
assert.isTrue(permissions.isShared(permission))
it 'isPublic() false otherwise', ->
permission = {
read: ['acct:angry@birds.com']
}
assert.isFalse(permissions.isShared(permission))
permission.read = []
assert.isFalse(permissions.isShared(permission))
permission.read = ['one', 'two', 'three']
assert.isFalse(permissions.isShared(permission))
describe 'isPrivate', ->
it 'returns true if the given user is in the permissions', ->
user = 'acct:angry@birds.com'
permission = {read: [user]}
assert.isTrue(permissions.isPrivate(permission, user))
it 'returns false if another user is in the permissions', ->
users = ['acct:angry@birds.com', 'acct:angry@joe.com']
permission = {read: users}
assert.isFalse(permissions.isPrivate(permission, 'acct:angry@birds.com'))
it 'returns false if different user in the permissions', ->
user = 'acct:angry@joe.com'
permission = {read: ['acct:angry@birds.com']}
assert.isFalse(permissions.isPrivate(permission, user))
describe 'permits', ->
it 'returns true when annotation has no permissions', ->
annotation = {}
assert.isTrue(permissions.permits(null, annotation, null))
it 'returns false for unknown action', ->
annotation = {permissions: permissions.private()}
action = 'Hadouken-ing'
assert.isFalse(permissions.permits(action, annotation, null))
it 'returns true if user different, but permissions has group:__world__', ->
annotation = {permissions: permissions.shared()}
annotation.permissions.read.push 'acct:darthsidious@deathstar.emp'
user = 'acct:darthvader@deathstar.emp'
assert.isTrue(permissions.permits('read', annotation, user))
it 'returns true if user is in permissions[action] list', ->
annotation = {permissions: permissions.private()}
user = 'acct:rogerrabbit@toonland'
annotation.permissions.read.push user
assert.isTrue(permissions.permits('read', annotation, user))
it 'returns false if the user name is missing from the list', ->
annotation = {permissions: permissions.private()}
user = 'acct:rogerrabbit@toonland'
assert.isFalse(permissions.permits('read', annotation, user))
| 189169 | {module, inject} = angular.mock
describe 'h:permissions', ->
sandbox = null
fakeSession = null
fakeLocalStorage = null
before ->
angular.module('h', [])
.service('permissions', require('../permissions'))
beforeEach module('h')
beforeEach module ($provide) ->
sandbox = sinon.sandbox.create()
fakeSession = {
state: {
userid: 'acct:flash@gordon'
}
}
fakeLocalStorage = {
getItem: -> undefined
}
$provide.value 'session', fakeSession
$provide.value 'localStorage', fakeLocalStorage
return
afterEach ->
sandbox.restore()
describe 'permissions service', ->
permissions = null
beforeEach inject (_permissions_) ->
permissions = _permissions_
describe 'private()', ->
it 'fills all permissions with auth.user', ->
perms = permissions.private()
assert.equal(perms.read[0], 'acct:flash@gordon')
assert.equal(perms.update[0], 'acct:flash@gordon')
assert.equal(perms.delete[0], 'acct:flash@gordon')
assert.equal(perms.admin[0], 'acct:flash@gordon')
it 'returns null if session.state.userid is falsey', ->
delete fakeSession.state.userid
assert.equal(permissions.private(), null)
describe 'shared()', ->
it 'fills the read property with group:__world__', ->
perms = permissions.shared()
assert.equal(perms.read[0], 'group:__world__')
assert.equal(perms.update[0], 'acct:flash@gordon')
assert.equal(perms.delete[0], 'acct:flash@gordon')
assert.equal(perms.admin[0], 'acct:flash@gordon')
it 'fills the read property with group:foo if passed "foo"', ->
perms = permissions.shared("foo")
assert.equal(perms.read[0], 'group:foo')
assert.equal(perms.update[0], 'acct:flash@gordon')
assert.equal(perms.delete[0], 'acct:flash@gordon')
assert.equal(perms.admin[0], 'acct:flash@g<NAME>')
it 'returns null if session.state.userid is falsey', ->
delete fakeSession.state.userid
assert.equal(permissions.shared("foo"), null)
describe 'default()', ->
it 'returns shared permissions if localStorage contains "shared"', ->
fakeLocalStorage.getItem = -> 'shared'
assert(permissions.isShared(permissions.default()))
it 'returns private permissions if localStorage contains "private"', ->
fakeLocalStorage.getItem = -> 'private'
assert(permissions.isPrivate(
permissions.default(), fakeSession.state.userid))
it 'returns shared permissions if localStorage is empty', ->
fakeLocalStorage.getItem = -> undefined
assert(permissions.isShared(permissions.default()))
describe 'setDefault()', ->
it 'sets the default permissions that default() will return', ->
stored = {}
fakeLocalStorage.setItem = (key, value) ->
stored[key] = value
fakeLocalStorage.getItem = (key) ->
return stored[key]
permissions.setDefault('private')
assert(permissions.isPrivate(
permissions.default(), fakeSession.state.userid))
permissions.setDefault('shared')
assert(permissions.isShared(
permissions.default('foo'), 'foo'))
describe 'isPublic', ->
it 'isPublic() true if the read permission has group:__world__ in it', ->
permission = {
read: ['group:__world__', 'acct:<EMAIL>']
}
assert.isTrue(permissions.isShared(permission))
it 'isPublic() false otherwise', ->
permission = {
read: ['acct:<EMAIL>']
}
assert.isFalse(permissions.isShared(permission))
permission.read = []
assert.isFalse(permissions.isShared(permission))
permission.read = ['one', 'two', 'three']
assert.isFalse(permissions.isShared(permission))
describe 'isPrivate', ->
it 'returns true if the given user is in the permissions', ->
user = 'acct:<EMAIL>'
permission = {read: [user]}
assert.isTrue(permissions.isPrivate(permission, user))
it 'returns false if another user is in the permissions', ->
users = ['acct:<EMAIL>', 'acct:<EMAIL>']
permission = {read: users}
assert.isFalse(permissions.isPrivate(permission, 'acct:<EMAIL>'))
it 'returns false if different user in the permissions', ->
user = 'acct:<EMAIL>'
permission = {read: ['acct:<EMAIL>']}
assert.isFalse(permissions.isPrivate(permission, user))
describe 'permits', ->
it 'returns true when annotation has no permissions', ->
annotation = {}
assert.isTrue(permissions.permits(null, annotation, null))
it 'returns false for unknown action', ->
annotation = {permissions: permissions.private()}
action = 'Hadouken-ing'
assert.isFalse(permissions.permits(action, annotation, null))
it 'returns true if user different, but permissions has group:__world__', ->
annotation = {permissions: permissions.shared()}
annotation.permissions.read.push 'acct:<EMAIL>'
user = 'acct:<EMAIL>'
assert.isTrue(permissions.permits('read', annotation, user))
it 'returns true if user is in permissions[action] list', ->
annotation = {permissions: permissions.private()}
user = 'acct:rogerrabbit@toonland'
annotation.permissions.read.push user
assert.isTrue(permissions.permits('read', annotation, user))
it 'returns false if the user name is missing from the list', ->
annotation = {permissions: permissions.private()}
user = 'acct:rogerrabbit@toonland'
assert.isFalse(permissions.permits('read', annotation, user))
| true | {module, inject} = angular.mock
describe 'h:permissions', ->
sandbox = null
fakeSession = null
fakeLocalStorage = null
before ->
angular.module('h', [])
.service('permissions', require('../permissions'))
beforeEach module('h')
beforeEach module ($provide) ->
sandbox = sinon.sandbox.create()
fakeSession = {
state: {
userid: 'acct:flash@gordon'
}
}
fakeLocalStorage = {
getItem: -> undefined
}
$provide.value 'session', fakeSession
$provide.value 'localStorage', fakeLocalStorage
return
afterEach ->
sandbox.restore()
describe 'permissions service', ->
permissions = null
beforeEach inject (_permissions_) ->
permissions = _permissions_
describe 'private()', ->
it 'fills all permissions with auth.user', ->
perms = permissions.private()
assert.equal(perms.read[0], 'acct:flash@gordon')
assert.equal(perms.update[0], 'acct:flash@gordon')
assert.equal(perms.delete[0], 'acct:flash@gordon')
assert.equal(perms.admin[0], 'acct:flash@gordon')
it 'returns null if session.state.userid is falsey', ->
delete fakeSession.state.userid
assert.equal(permissions.private(), null)
describe 'shared()', ->
it 'fills the read property with group:__world__', ->
perms = permissions.shared()
assert.equal(perms.read[0], 'group:__world__')
assert.equal(perms.update[0], 'acct:flash@gordon')
assert.equal(perms.delete[0], 'acct:flash@gordon')
assert.equal(perms.admin[0], 'acct:flash@gordon')
it 'fills the read property with group:foo if passed "foo"', ->
perms = permissions.shared("foo")
assert.equal(perms.read[0], 'group:foo')
assert.equal(perms.update[0], 'acct:flash@gordon')
assert.equal(perms.delete[0], 'acct:flash@gordon')
assert.equal(perms.admin[0], 'acct:flash@gPI:NAME:<NAME>END_PI')
it 'returns null if session.state.userid is falsey', ->
delete fakeSession.state.userid
assert.equal(permissions.shared("foo"), null)
describe 'default()', ->
it 'returns shared permissions if localStorage contains "shared"', ->
fakeLocalStorage.getItem = -> 'shared'
assert(permissions.isShared(permissions.default()))
it 'returns private permissions if localStorage contains "private"', ->
fakeLocalStorage.getItem = -> 'private'
assert(permissions.isPrivate(
permissions.default(), fakeSession.state.userid))
it 'returns shared permissions if localStorage is empty', ->
fakeLocalStorage.getItem = -> undefined
assert(permissions.isShared(permissions.default()))
describe 'setDefault()', ->
it 'sets the default permissions that default() will return', ->
stored = {}
fakeLocalStorage.setItem = (key, value) ->
stored[key] = value
fakeLocalStorage.getItem = (key) ->
return stored[key]
permissions.setDefault('private')
assert(permissions.isPrivate(
permissions.default(), fakeSession.state.userid))
permissions.setDefault('shared')
assert(permissions.isShared(
permissions.default('foo'), 'foo'))
describe 'isPublic', ->
it 'isPublic() true if the read permission has group:__world__ in it', ->
permission = {
read: ['group:__world__', 'acct:PI:EMAIL:<EMAIL>END_PI']
}
assert.isTrue(permissions.isShared(permission))
it 'isPublic() false otherwise', ->
permission = {
read: ['acct:PI:EMAIL:<EMAIL>END_PI']
}
assert.isFalse(permissions.isShared(permission))
permission.read = []
assert.isFalse(permissions.isShared(permission))
permission.read = ['one', 'two', 'three']
assert.isFalse(permissions.isShared(permission))
describe 'isPrivate', ->
it 'returns true if the given user is in the permissions', ->
user = 'acct:PI:EMAIL:<EMAIL>END_PI'
permission = {read: [user]}
assert.isTrue(permissions.isPrivate(permission, user))
it 'returns false if another user is in the permissions', ->
users = ['acct:PI:EMAIL:<EMAIL>END_PI', 'acct:PI:EMAIL:<EMAIL>END_PI']
permission = {read: users}
assert.isFalse(permissions.isPrivate(permission, 'acct:PI:EMAIL:<EMAIL>END_PI'))
it 'returns false if different user in the permissions', ->
user = 'acct:PI:EMAIL:<EMAIL>END_PI'
permission = {read: ['acct:PI:EMAIL:<EMAIL>END_PI']}
assert.isFalse(permissions.isPrivate(permission, user))
describe 'permits', ->
it 'returns true when annotation has no permissions', ->
annotation = {}
assert.isTrue(permissions.permits(null, annotation, null))
it 'returns false for unknown action', ->
annotation = {permissions: permissions.private()}
action = 'Hadouken-ing'
assert.isFalse(permissions.permits(action, annotation, null))
it 'returns true if user different, but permissions has group:__world__', ->
annotation = {permissions: permissions.shared()}
annotation.permissions.read.push 'acct:PI:EMAIL:<EMAIL>END_PI'
user = 'acct:PI:EMAIL:<EMAIL>END_PI'
assert.isTrue(permissions.permits('read', annotation, user))
it 'returns true if user is in permissions[action] list', ->
annotation = {permissions: permissions.private()}
user = 'acct:rogerrabbit@toonland'
annotation.permissions.read.push user
assert.isTrue(permissions.permits('read', annotation, user))
it 'returns false if the user name is missing from the list', ->
annotation = {permissions: permissions.private()}
user = 'acct:rogerrabbit@toonland'
assert.isFalse(permissions.permits('read', annotation, user))
|
[
{
"context": "sitories\"\n\t\trepoLink.should.have.property \"key\", \"anton$project1\"\n\t\trepoLink.should.have.property \"tag\", \"reposito",
"end": 771,
"score": 0.999334990978241,
"start": 757,
"tag": "KEY",
"value": "anton$project1"
}
] | test/blob.coffee | circuithub/massive-git | 6 | should = require "should"
Blob = require("../lib/objects/blob").Blob
describe "new Blob", ->
blob = new Blob("test-content", "anton$project1")
it "should have correct properties", ->
blob.id().should.equal "0535cbee7fa4e0fef31389c68336ec6bcb5422b3"
blob.should.have.property "type", "blob"
blob.should.have.property "repo", "anton$project1"
blob.should.have.property "data", "test-content"
blob.content().should.equal blob.data
blob.index().should.have.property "type", "blob"
blob.index().should.have.property "repo", "anton$project1"
it "should have correct links", ->
blob.links().should.have.length(1)
repoLink = blob.links()[0]
repoLink.should.have.property "bucket", "repositories"
repoLink.should.have.property "key", "anton$project1"
repoLink.should.have.property "tag", "repository"
blob.getLink("repository").should.equal "anton$project1"
| 169303 | should = require "should"
Blob = require("../lib/objects/blob").Blob
describe "new Blob", ->
blob = new Blob("test-content", "anton$project1")
it "should have correct properties", ->
blob.id().should.equal "0535cbee7fa4e0fef31389c68336ec6bcb5422b3"
blob.should.have.property "type", "blob"
blob.should.have.property "repo", "anton$project1"
blob.should.have.property "data", "test-content"
blob.content().should.equal blob.data
blob.index().should.have.property "type", "blob"
blob.index().should.have.property "repo", "anton$project1"
it "should have correct links", ->
blob.links().should.have.length(1)
repoLink = blob.links()[0]
repoLink.should.have.property "bucket", "repositories"
repoLink.should.have.property "key", "<KEY>"
repoLink.should.have.property "tag", "repository"
blob.getLink("repository").should.equal "anton$project1"
| true | should = require "should"
Blob = require("../lib/objects/blob").Blob
describe "new Blob", ->
blob = new Blob("test-content", "anton$project1")
it "should have correct properties", ->
blob.id().should.equal "0535cbee7fa4e0fef31389c68336ec6bcb5422b3"
blob.should.have.property "type", "blob"
blob.should.have.property "repo", "anton$project1"
blob.should.have.property "data", "test-content"
blob.content().should.equal blob.data
blob.index().should.have.property "type", "blob"
blob.index().should.have.property "repo", "anton$project1"
it "should have correct links", ->
blob.links().should.have.length(1)
repoLink = blob.links()[0]
repoLink.should.have.property "bucket", "repositories"
repoLink.should.have.property "key", "PI:KEY:<KEY>END_PI"
repoLink.should.have.property "tag", "repository"
blob.getLink("repository").should.equal "anton$project1"
|
[
{
"context": "ith collisions in the lower bits\", ->\n keys = [0x1fffffff, 0x3fffffff, 0x5ff0ffff, 0x7ff0ffff]\n items = ",
"end": 3717,
"score": 0.9257115721702576,
"start": 3707,
"tag": "KEY",
"value": "0x1fffffff"
},
{
"context": "ns in the lower bits\", ->\n keys = [0x1f... | spec/int_map_spec.coffee | odf/pazy.js | 0 | if typeof(require) != 'undefined'
{ seq } = require 'sequence'
{ IntMap } = require 'indexed'
else
{ seq, IntMap } = pazy
describe "An IntMap", ->
describe "with two items the first of which is removed", ->
hash = new IntMap().plus([37, true]).plus([42, true]).minus(37)
it "should not be empty", ->
expect(hash.size()).toBeGreaterThan 0
it "should not be the same object as another one constructed like it", ->
h = new IntMap().plus([37, true]).plus([42, true]).minus(37)
expect(hash).not.toBe h
describe "when empty", ->
hash = new IntMap()
it "should have size 0", ->
expect(hash.size()).toEqual 0
it "should not return anything on get", ->
expect(hash.get("first")).not.toBeDefined()
it "should still be empty when minus is called", ->
expect(hash.minus("first").size()).toEqual 0
it "should have length 0 as an array", ->
expect(hash.toArray().length).toEqual 0
it "should print as HashMap(EmptyNode)", ->
expect(hash.toString()).toEqual('IntMap(EmptyNode)')
describe "containing one item", ->
hash = new IntMap().plus([1337, 1])
it "should have size 1", ->
expect(hash.size()).toEqual 1
it "should retrieve the associated value for the key", ->
expect(hash.get(1337)).toBe 1
it "should not return anything when fed another key", ->
expect(hash.get(4023)).not.toBeDefined()
it "should be empty when the item is removed", ->
expect(hash.minus(1337).size()).toBe 0
it "should be empty when the item is removed twice", ->
expect(hash.minus(1337, 1337).size()).toBe 0
it "should contain the key-value pair", ->
a = hash.toArray()
expect(a.length).toEqual 1
expect(a).toContain([1337, 1])
it "should print as IntMap(1337 ~> 1)", ->
expect(hash.toString()).toEqual('IntMap(1337 ~> 1)')
describe "the value of which is then changed", ->
h = hash.plus([1337, "leet!"])
it "should have size 1", ->
expect(h.size()).toBe 1
it "should retrieve the associated value for the key", ->
expect(h.get(1337)).toBe "leet!"
it "should not return anything when fed another key", ->
expect(h.get(4023)).not.toBeDefined()
it "should contain the new key-value pair", ->
a = h.toArray()
expect(a.length).toEqual 1
expect(a).toContain([1337, "leet!"])
describe "containing two items", ->
hash = new IntMap().plus([1337, 'leet!']).plus([4023, 'lame?'])
it "should have size 2", ->
expect(hash.size()).toEqual 2
it "should not be empty when the first item is removed", ->
expect(hash.minus(1337).size()).toBeGreaterThan 0
it "should be empty when both items are removed", ->
expect(hash.minus(4023).minus(1337).size()).toBe 0
it "should return the associate values for both keys", ->
expect(hash.get(1337)).toBe 'leet!'
expect(hash.get(4023)).toBe 'lame?'
it "should not return anything when fed another key", ->
expect(hash.get(65535)).not.toBeDefined()
it "should contain the key-value pairs", ->
a = hash.toArray()
expect(a.length).toEqual 2
expect(a).toContain([1337, 'leet!'])
expect(a).toContain([4023, 'lame?'])
it "should not change when illegal items are added", ->
expect(hash.plus ["a", 1], [-1, 2], [0x100000000, 4]).toBe hash
expect(hash.plus [2.34, 3], [[1], 5], [{1:2}, 6]).toBe hash
it "should not change when illegal items are removed", ->
expect(hash.minus("a", -1, 2.34, 0x100000000, [1], {1:2})).toBe hash
describe "containing four items with collisions in the lower bits", ->
keys = [0x1fffffff, 0x3fffffff, 0x5ff0ffff, 0x7ff0ffff]
items = ([key, "0x#{key.toString(16)}"] for key in keys)
hash = (new IntMap()).plus items...
it "should return the associated value for all keys", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should have size 1 when all items but one are removed", ->
expect(hash.minus(keys[0..2]...).size()).toEqual 1
it "should be empty when all items are removed", ->
expect(hash.minus(keys...).size()).toBe 0
describe "containing four items with collisions in the higher bits", ->
keys = [0x7ffffff1, 0x7ffffff3, 0x7fff0ff5, 0x7fff0ff7]
items = ([key, "0x#{key.toString(16)}"] for key in keys)
hash = (new IntMap()).plus items...
it "should return the associated value for all keys", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should have size 1 when all items but one are removed", ->
expect(hash.minus(keys[0..2]...).size()).toEqual 1
it "should be empty when all items are removed", ->
expect(hash.minus(keys...).size()).toBe 0
describe "containing three items", ->
key_a = 257
key_b = 513
key_c = 769
key_d = 33
hash = new IntMap().plus([key_a, "a"], [key_b, "b"], [key_c, "c"])
it "should contain the remaining two items when one is removed", ->
a = hash.minus(key_a).toArray()
expect(a.length).toBe 2
expect(a).toContain [key_b, "b"]
expect(a).toContain [key_c, "c"]
it "should contain four items when one with a new hash value is added", ->
a = hash.plus([key_d, "d"]).toArray()
expect(a.length).toBe 4
expect(a).toContain [key_a, "a"]
expect(a).toContain [key_b, "b"]
expect(a).toContain [key_c, "c"]
expect(a).toContain [key_d, "d"]
describe "containing a wild mix of items", ->
keys = ((x * 5 + 7) for x in [0..16])
items = ([key, key.toString()] for key in keys)
scrambled = (items[(i * 7) % 17] for i in [0..16])
hash = (new IntMap()).plus scrambled...
it "should have the right number of items", ->
expect(hash.size()).toEqual keys.length
it "should retrieve the associated value for each key", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should contain all the items when converted to an array", ->
expect(hash.toArray()).toEqual(items)
describe "containing lots of items", ->
keys = [0..306]
items = ([key, key.toString()] for key in keys)
scrambled = (items[(i * 127) % 307] for i in [0..306])
hash = (new IntMap()).plus items...
it "should have the correct number of items", ->
expect(hash.size()).toEqual keys.length
it "should retrieve the associated value for each key", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should not return anythin when fed another key", ->
expect(hash.get(500)).not.toBeDefined()
it "should contain all the items when converted to an array", ->
expect(hash.toArray()).toEqual(items)
it "should have the first (key,value)-pair as its first element", ->
expect(seq.get hash, 0).toEqual(items[0])
it "should have the second (key,value)-pair as its second element", ->
expect(seq.get hash, 1).toEqual(items[1])
it "should have the last (key,value)-pair as its last element", ->
expect(seq.last hash).toEqual(items[306])
describe "some of which are then removed", ->
ex_keys = (keys[(i * 37) % 101] for i in [0..100])
h = hash.minus ex_keys...
it "should have the correct size", ->
expect(h.size()).toEqual keys.length - ex_keys.length
it "should not be the same as the original hash", ->
expect(h).not.toEqual hash
it "should retrieve the associated values for the remaining keys", ->
expect(h.get(key)).toBe value for [key, value] in items[101..]
it "should not return anything for the removed keys", ->
expect(h.get(key)).not.toBeDefined() for key in ex_keys
it "should have exactly the remaining elements when made an array", ->
expect(h.toArray()).toEqual(items[101..])
describe "from which some keys not included are removed", ->
ex_keys = (keys[(i * 37) % 101 + 1000] for i in [0..100])
h = hash.minus ex_keys...
it "should be the same object as before", ->
expect(h).toBe hash
it "should have the correct size", ->
expect(h.size()).toEqual hash.size()
it "should retrieve the associated values for the original keys", ->
expect(h.get(key)).toBe value for [key, value] in items
it "should not return anything for the 'removed' keys", ->
expect(h.get(key)).not.toBeDefined() for key in ex_keys
it "should have exactly the original items as an array", ->
expect(h.toArray()).toEqual items
describe "all of which are then removed", ->
h = hash.minus keys...
it "should have size 0", ->
expect(h.size()).toEqual 0
it "should return nothing for the removed keys", ->
expect(h.get(key)).not.toBeDefined() for key in keys
it "should convert to an empty array", ->
expect(h.toArray().length).toBe 0
describe "some of which are then replaced", ->
ex_keys = [0..100]
newItems = ([k, "0x#{k.toString(16)}"] for k in ex_keys)
scrambled = (newItems[(i * 41) % 101] for i in [0..100])
h = hash.plus scrambled...
it "should have the same size as before", ->
expect(h.size()).toBe hash.size()
it "should retrieve the original values for the untouched keys", ->
expect(h.get(key)).toBe value for [key, value] in items[101..]
it "should return the new values for the modified keys", ->
expect(h.get(key)).toBe value for [key, value] in ex_keys
it "should contain the appropriate key-value pairs", ->
a = h.toArray()
expect(a[101..]).toEqual items[101..]
expect(a[0..100]).toEqual newItems
describe "some of which are then overwritten with the original value", ->
scrambled = (items[(i * 41) % 101] for i in [0..100])
h = hash.plus scrambled...
it "should be the same object as before", ->
expect(h).toBe hash
it "should have the same size as before", ->
expect(h.size()).toEqual hash.size()
it "should retrieve the original values for all keys", ->
expect(h.get(key)).toBe value for [key, value] in items
it "should contain the appropriate key-value pair", ->
expect(h.toArray()).toEqual items
| 5261 | if typeof(require) != 'undefined'
{ seq } = require 'sequence'
{ IntMap } = require 'indexed'
else
{ seq, IntMap } = pazy
describe "An IntMap", ->
describe "with two items the first of which is removed", ->
hash = new IntMap().plus([37, true]).plus([42, true]).minus(37)
it "should not be empty", ->
expect(hash.size()).toBeGreaterThan 0
it "should not be the same object as another one constructed like it", ->
h = new IntMap().plus([37, true]).plus([42, true]).minus(37)
expect(hash).not.toBe h
describe "when empty", ->
hash = new IntMap()
it "should have size 0", ->
expect(hash.size()).toEqual 0
it "should not return anything on get", ->
expect(hash.get("first")).not.toBeDefined()
it "should still be empty when minus is called", ->
expect(hash.minus("first").size()).toEqual 0
it "should have length 0 as an array", ->
expect(hash.toArray().length).toEqual 0
it "should print as HashMap(EmptyNode)", ->
expect(hash.toString()).toEqual('IntMap(EmptyNode)')
describe "containing one item", ->
hash = new IntMap().plus([1337, 1])
it "should have size 1", ->
expect(hash.size()).toEqual 1
it "should retrieve the associated value for the key", ->
expect(hash.get(1337)).toBe 1
it "should not return anything when fed another key", ->
expect(hash.get(4023)).not.toBeDefined()
it "should be empty when the item is removed", ->
expect(hash.minus(1337).size()).toBe 0
it "should be empty when the item is removed twice", ->
expect(hash.minus(1337, 1337).size()).toBe 0
it "should contain the key-value pair", ->
a = hash.toArray()
expect(a.length).toEqual 1
expect(a).toContain([1337, 1])
it "should print as IntMap(1337 ~> 1)", ->
expect(hash.toString()).toEqual('IntMap(1337 ~> 1)')
describe "the value of which is then changed", ->
h = hash.plus([1337, "leet!"])
it "should have size 1", ->
expect(h.size()).toBe 1
it "should retrieve the associated value for the key", ->
expect(h.get(1337)).toBe "leet!"
it "should not return anything when fed another key", ->
expect(h.get(4023)).not.toBeDefined()
it "should contain the new key-value pair", ->
a = h.toArray()
expect(a.length).toEqual 1
expect(a).toContain([1337, "leet!"])
describe "containing two items", ->
hash = new IntMap().plus([1337, 'leet!']).plus([4023, 'lame?'])
it "should have size 2", ->
expect(hash.size()).toEqual 2
it "should not be empty when the first item is removed", ->
expect(hash.minus(1337).size()).toBeGreaterThan 0
it "should be empty when both items are removed", ->
expect(hash.minus(4023).minus(1337).size()).toBe 0
it "should return the associate values for both keys", ->
expect(hash.get(1337)).toBe 'leet!'
expect(hash.get(4023)).toBe 'lame?'
it "should not return anything when fed another key", ->
expect(hash.get(65535)).not.toBeDefined()
it "should contain the key-value pairs", ->
a = hash.toArray()
expect(a.length).toEqual 2
expect(a).toContain([1337, 'leet!'])
expect(a).toContain([4023, 'lame?'])
it "should not change when illegal items are added", ->
expect(hash.plus ["a", 1], [-1, 2], [0x100000000, 4]).toBe hash
expect(hash.plus [2.34, 3], [[1], 5], [{1:2}, 6]).toBe hash
it "should not change when illegal items are removed", ->
expect(hash.minus("a", -1, 2.34, 0x100000000, [1], {1:2})).toBe hash
describe "containing four items with collisions in the lower bits", ->
keys = [<KEY>, <KEY>, <KEY>, 0<KEY>]
items = ([key, "0<KEY>#{key.<KEY>)}"] for key in keys)
hash = (new IntMap()).plus items...
it "should return the associated value for all keys", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should have size 1 when all items but one are removed", ->
expect(hash.minus(keys[0..2]...).size()).toEqual 1
it "should be empty when all items are removed", ->
expect(hash.minus(keys...).size()).toBe 0
describe "containing four items with collisions in the higher bits", ->
keys = [<KEY>, <KEY>, <KEY>, <KEY>]
items = ([key, "0<KEY>#{key.<KEY>)}"] for key in keys)
hash = (new IntMap()).plus items...
it "should return the associated value for all keys", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should have size 1 when all items but one are removed", ->
expect(hash.minus(keys[0..2]...).size()).toEqual 1
it "should be empty when all items are removed", ->
expect(hash.minus(keys...).size()).toBe 0
describe "containing three items", ->
key_a = 2<KEY>
key_b = <KEY>
key_c = <KEY>
key_d = <KEY>
hash = new IntMap().plus([key_a, "a"], [key_b, "b"], [key_c, "c"])
it "should contain the remaining two items when one is removed", ->
a = hash.minus(key_a).toArray()
expect(a.length).toBe 2
expect(a).toContain [key_b, "b"]
expect(a).toContain [key_c, "c"]
it "should contain four items when one with a new hash value is added", ->
a = hash.plus([key_d, "d"]).toArray()
expect(a.length).toBe 4
expect(a).toContain [key_a, "a"]
expect(a).toContain [key_b, "b"]
expect(a).toContain [key_c, "c"]
expect(a).toContain [key_d, "d"]
describe "containing a wild mix of items", ->
keys = ((x * 5 + 7) for x in [0..16])
items = ([key, key.toString()] for key in keys)
scrambled = (items[(i * 7) % 17] for i in [0..16])
hash = (new IntMap()).plus scrambled...
it "should have the right number of items", ->
expect(hash.size()).toEqual keys.length
it "should retrieve the associated value for each key", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should contain all the items when converted to an array", ->
expect(hash.toArray()).toEqual(items)
describe "containing lots of items", ->
keys = [0..306]
items = ([key, key.toString()] for key in keys)
scrambled = (items[(i * 127) % 307] for i in [0..306])
hash = (new IntMap()).plus items...
it "should have the correct number of items", ->
expect(hash.size()).toEqual keys.length
it "should retrieve the associated value for each key", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should not return anythin when fed another key", ->
expect(hash.get(500)).not.toBeDefined()
it "should contain all the items when converted to an array", ->
expect(hash.toArray()).toEqual(items)
it "should have the first (key,value)-pair as its first element", ->
expect(seq.get hash, 0).toEqual(items[0])
it "should have the second (key,value)-pair as its second element", ->
expect(seq.get hash, 1).toEqual(items[1])
it "should have the last (key,value)-pair as its last element", ->
expect(seq.last hash).toEqual(items[306])
describe "some of which are then removed", ->
ex_keys = (keys[(i * 37) % 101] for i in [0..100])
h = hash.minus ex_keys...
it "should have the correct size", ->
expect(h.size()).toEqual keys.length - ex_keys.length
it "should not be the same as the original hash", ->
expect(h).not.toEqual hash
it "should retrieve the associated values for the remaining keys", ->
expect(h.get(key)).toBe value for [key, value] in items[101..]
it "should not return anything for the removed keys", ->
expect(h.get(key)).not.toBeDefined() for key in ex_keys
it "should have exactly the remaining elements when made an array", ->
expect(h.toArray()).toEqual(items[101..])
describe "from which some keys not included are removed", ->
ex_keys = (keys[(i * 37) % 101 + 1000] for i in [0..100])
h = hash.minus ex_keys...
it "should be the same object as before", ->
expect(h).toBe hash
it "should have the correct size", ->
expect(h.size()).toEqual hash.size()
it "should retrieve the associated values for the original keys", ->
expect(h.get(key)).toBe value for [key, value] in items
it "should not return anything for the 'removed' keys", ->
expect(h.get(key)).not.toBeDefined() for key in ex_keys
it "should have exactly the original items as an array", ->
expect(h.toArray()).toEqual items
describe "all of which are then removed", ->
h = hash.minus keys...
it "should have size 0", ->
expect(h.size()).toEqual 0
it "should return nothing for the removed keys", ->
expect(h.get(key)).not.toBeDefined() for key in keys
it "should convert to an empty array", ->
expect(h.toArray().length).toBe 0
describe "some of which are then replaced", ->
ex_keys = [<KEY>]
newItems = ([k, "0x#{k.toString(16)}"] for k in ex_keys)
scrambled = (newItems[(i * 41) % 101] for i in [0..100])
h = hash.plus scrambled...
it "should have the same size as before", ->
expect(h.size()).toBe hash.size()
it "should retrieve the original values for the untouched keys", ->
expect(h.get(key)).toBe value for [key, value] in items[101..]
it "should return the new values for the modified keys", ->
expect(h.get(key)).toBe value for [key, value] in ex_keys
it "should contain the appropriate key-value pairs", ->
a = h.toArray()
expect(a[101..]).toEqual items[101..]
expect(a[0..100]).toEqual newItems
describe "some of which are then overwritten with the original value", ->
scrambled = (items[(i * 41) % 101] for i in [0..100])
h = hash.plus scrambled...
it "should be the same object as before", ->
expect(h).toBe hash
it "should have the same size as before", ->
expect(h.size()).toEqual hash.size()
it "should retrieve the original values for all keys", ->
expect(h.get(key)).toBe value for [key, value] in items
it "should contain the appropriate key-value pair", ->
expect(h.toArray()).toEqual items
| true | if typeof(require) != 'undefined'
{ seq } = require 'sequence'
{ IntMap } = require 'indexed'
else
{ seq, IntMap } = pazy
describe "An IntMap", ->
describe "with two items the first of which is removed", ->
hash = new IntMap().plus([37, true]).plus([42, true]).minus(37)
it "should not be empty", ->
expect(hash.size()).toBeGreaterThan 0
it "should not be the same object as another one constructed like it", ->
h = new IntMap().plus([37, true]).plus([42, true]).minus(37)
expect(hash).not.toBe h
describe "when empty", ->
hash = new IntMap()
it "should have size 0", ->
expect(hash.size()).toEqual 0
it "should not return anything on get", ->
expect(hash.get("first")).not.toBeDefined()
it "should still be empty when minus is called", ->
expect(hash.minus("first").size()).toEqual 0
it "should have length 0 as an array", ->
expect(hash.toArray().length).toEqual 0
it "should print as HashMap(EmptyNode)", ->
expect(hash.toString()).toEqual('IntMap(EmptyNode)')
describe "containing one item", ->
hash = new IntMap().plus([1337, 1])
it "should have size 1", ->
expect(hash.size()).toEqual 1
it "should retrieve the associated value for the key", ->
expect(hash.get(1337)).toBe 1
it "should not return anything when fed another key", ->
expect(hash.get(4023)).not.toBeDefined()
it "should be empty when the item is removed", ->
expect(hash.minus(1337).size()).toBe 0
it "should be empty when the item is removed twice", ->
expect(hash.minus(1337, 1337).size()).toBe 0
it "should contain the key-value pair", ->
a = hash.toArray()
expect(a.length).toEqual 1
expect(a).toContain([1337, 1])
it "should print as IntMap(1337 ~> 1)", ->
expect(hash.toString()).toEqual('IntMap(1337 ~> 1)')
describe "the value of which is then changed", ->
h = hash.plus([1337, "leet!"])
it "should have size 1", ->
expect(h.size()).toBe 1
it "should retrieve the associated value for the key", ->
expect(h.get(1337)).toBe "leet!"
it "should not return anything when fed another key", ->
expect(h.get(4023)).not.toBeDefined()
it "should contain the new key-value pair", ->
a = h.toArray()
expect(a.length).toEqual 1
expect(a).toContain([1337, "leet!"])
describe "containing two items", ->
hash = new IntMap().plus([1337, 'leet!']).plus([4023, 'lame?'])
it "should have size 2", ->
expect(hash.size()).toEqual 2
it "should not be empty when the first item is removed", ->
expect(hash.minus(1337).size()).toBeGreaterThan 0
it "should be empty when both items are removed", ->
expect(hash.minus(4023).minus(1337).size()).toBe 0
it "should return the associate values for both keys", ->
expect(hash.get(1337)).toBe 'leet!'
expect(hash.get(4023)).toBe 'lame?'
it "should not return anything when fed another key", ->
expect(hash.get(65535)).not.toBeDefined()
it "should contain the key-value pairs", ->
a = hash.toArray()
expect(a.length).toEqual 2
expect(a).toContain([1337, 'leet!'])
expect(a).toContain([4023, 'lame?'])
it "should not change when illegal items are added", ->
expect(hash.plus ["a", 1], [-1, 2], [0x100000000, 4]).toBe hash
expect(hash.plus [2.34, 3], [[1], 5], [{1:2}, 6]).toBe hash
it "should not change when illegal items are removed", ->
expect(hash.minus("a", -1, 2.34, 0x100000000, [1], {1:2})).toBe hash
describe "containing four items with collisions in the lower bits", ->
keys = [PI:KEY:<KEY>END_PI, PI:KEY:<KEY>END_PI, PI:KEY:<KEY>END_PI, 0PI:KEY:<KEY>END_PI]
items = ([key, "0PI:KEY:<KEY>END_PI#{key.PI:KEY:<KEY>END_PI)}"] for key in keys)
hash = (new IntMap()).plus items...
it "should return the associated value for all keys", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should have size 1 when all items but one are removed", ->
expect(hash.minus(keys[0..2]...).size()).toEqual 1
it "should be empty when all items are removed", ->
expect(hash.minus(keys...).size()).toBe 0
describe "containing four items with collisions in the higher bits", ->
keys = [PI:KEY:<KEY>END_PI, PI:KEY:<KEY>END_PI, PI:KEY:<KEY>END_PI, PI:KEY:<KEY>END_PI]
items = ([key, "0PI:KEY:<KEY>END_PI#{key.PI:KEY:<KEY>END_PI)}"] for key in keys)
hash = (new IntMap()).plus items...
it "should return the associated value for all keys", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should have size 1 when all items but one are removed", ->
expect(hash.minus(keys[0..2]...).size()).toEqual 1
it "should be empty when all items are removed", ->
expect(hash.minus(keys...).size()).toBe 0
describe "containing three items", ->
key_a = 2PI:KEY:<KEY>END_PI
key_b = PI:KEY:<KEY>END_PI
key_c = PI:KEY:<KEY>END_PI
key_d = PI:KEY:<KEY>END_PI
hash = new IntMap().plus([key_a, "a"], [key_b, "b"], [key_c, "c"])
it "should contain the remaining two items when one is removed", ->
a = hash.minus(key_a).toArray()
expect(a.length).toBe 2
expect(a).toContain [key_b, "b"]
expect(a).toContain [key_c, "c"]
it "should contain four items when one with a new hash value is added", ->
a = hash.plus([key_d, "d"]).toArray()
expect(a.length).toBe 4
expect(a).toContain [key_a, "a"]
expect(a).toContain [key_b, "b"]
expect(a).toContain [key_c, "c"]
expect(a).toContain [key_d, "d"]
describe "containing a wild mix of items", ->
keys = ((x * 5 + 7) for x in [0..16])
items = ([key, key.toString()] for key in keys)
scrambled = (items[(i * 7) % 17] for i in [0..16])
hash = (new IntMap()).plus scrambled...
it "should have the right number of items", ->
expect(hash.size()).toEqual keys.length
it "should retrieve the associated value for each key", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should contain all the items when converted to an array", ->
expect(hash.toArray()).toEqual(items)
describe "containing lots of items", ->
keys = [0..306]
items = ([key, key.toString()] for key in keys)
scrambled = (items[(i * 127) % 307] for i in [0..306])
hash = (new IntMap()).plus items...
it "should have the correct number of items", ->
expect(hash.size()).toEqual keys.length
it "should retrieve the associated value for each key", ->
expect(hash.get(key)).toBe value for [key, value] in items
it "should not return anythin when fed another key", ->
expect(hash.get(500)).not.toBeDefined()
it "should contain all the items when converted to an array", ->
expect(hash.toArray()).toEqual(items)
it "should have the first (key,value)-pair as its first element", ->
expect(seq.get hash, 0).toEqual(items[0])
it "should have the second (key,value)-pair as its second element", ->
expect(seq.get hash, 1).toEqual(items[1])
it "should have the last (key,value)-pair as its last element", ->
expect(seq.last hash).toEqual(items[306])
describe "some of which are then removed", ->
ex_keys = (keys[(i * 37) % 101] for i in [0..100])
h = hash.minus ex_keys...
it "should have the correct size", ->
expect(h.size()).toEqual keys.length - ex_keys.length
it "should not be the same as the original hash", ->
expect(h).not.toEqual hash
it "should retrieve the associated values for the remaining keys", ->
expect(h.get(key)).toBe value for [key, value] in items[101..]
it "should not return anything for the removed keys", ->
expect(h.get(key)).not.toBeDefined() for key in ex_keys
it "should have exactly the remaining elements when made an array", ->
expect(h.toArray()).toEqual(items[101..])
describe "from which some keys not included are removed", ->
ex_keys = (keys[(i * 37) % 101 + 1000] for i in [0..100])
h = hash.minus ex_keys...
it "should be the same object as before", ->
expect(h).toBe hash
it "should have the correct size", ->
expect(h.size()).toEqual hash.size()
it "should retrieve the associated values for the original keys", ->
expect(h.get(key)).toBe value for [key, value] in items
it "should not return anything for the 'removed' keys", ->
expect(h.get(key)).not.toBeDefined() for key in ex_keys
it "should have exactly the original items as an array", ->
expect(h.toArray()).toEqual items
describe "all of which are then removed", ->
h = hash.minus keys...
it "should have size 0", ->
expect(h.size()).toEqual 0
it "should return nothing for the removed keys", ->
expect(h.get(key)).not.toBeDefined() for key in keys
it "should convert to an empty array", ->
expect(h.toArray().length).toBe 0
describe "some of which are then replaced", ->
ex_keys = [PI:KEY:<KEY>END_PI]
newItems = ([k, "0x#{k.toString(16)}"] for k in ex_keys)
scrambled = (newItems[(i * 41) % 101] for i in [0..100])
h = hash.plus scrambled...
it "should have the same size as before", ->
expect(h.size()).toBe hash.size()
it "should retrieve the original values for the untouched keys", ->
expect(h.get(key)).toBe value for [key, value] in items[101..]
it "should return the new values for the modified keys", ->
expect(h.get(key)).toBe value for [key, value] in ex_keys
it "should contain the appropriate key-value pairs", ->
a = h.toArray()
expect(a[101..]).toEqual items[101..]
expect(a[0..100]).toEqual newItems
describe "some of which are then overwritten with the original value", ->
scrambled = (items[(i * 41) % 101] for i in [0..100])
h = hash.plus scrambled...
it "should be the same object as before", ->
expect(h).toBe hash
it "should have the same size as before", ->
expect(h.size()).toEqual hash.size()
it "should retrieve the original values for all keys", ->
expect(h.get(key)).toBe value for [key, value] in items
it "should contain the appropriate key-value pair", ->
expect(h.toArray()).toEqual items
|
[
{
"context": "\tpush(theArgument)\n\tlist(2)\n\n# original routine by John Kennedy, see\n# https://web.archive.org/web/20111027100847",
"end": 1436,
"score": 0.999863862991333,
"start": 1424,
"tag": "NAME",
"value": "John Kennedy"
},
{
"context": "eb/20111027100847/http://homepage.sm... | sources/approxratio.coffee | ribrdb/Algebrite | 4 | ###
Guesses a rational for each float in the passed expression
###
Eval_approxratio = ->
theArgument = cadr(p1)
push(theArgument)
approxratioRecursive()
approxratioRecursive = ->
i = 0
save()
p1 = pop(); # expr
if (istensor(p1))
p4 = alloc_tensor(p1.tensor.nelem)
p4.tensor.ndim = p1.tensor.ndim
for i in [0...p1.tensor.ndim]
p4.tensor.dim[i] = p1.tensor.dim[i]
for i in [0...p1.tensor.nelem]
push(p1.tensor.elem[i])
approxratioRecursive()
p4.tensor.elem[i] = pop()
check_tensor_dimensions p4
push(p4)
else if p1.k == DOUBLE
push(p1)
approxOneRatioOnly()
else if (iscons(p1))
push(car(p1))
approxratioRecursive()
push(cdr(p1))
approxratioRecursive()
cons()
else
push(p1)
restore()
approxOneRatioOnly = ->
zzfloat()
supposedlyTheFloat = pop()
if supposedlyTheFloat.k == DOUBLE
theFloat = supposedlyTheFloat.d
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
theRatio = floatToRatioRoutine(theFloat,precision)
push_rational(theRatio[0], theRatio[1])
else
push_integer(theFloat)
return
# we didn't manage, just leave unexpressed
push_symbol(APPROXRATIO)
push(theArgument)
list(2)
# original routine by John Kennedy, see
# https://web.archive.org/web/20111027100847/http://homepage.smc.edu/kennedy_john/DEC2FRAC.PDF
# courtesy of Michael Borcherds
# who ported this to JavaScript under MIT licence
# also see
# https://github.com/geogebra/geogebra/blob/master/common/src/main/java/org/geogebra/common/kernel/algos/AlgoFractionText.java
# potential other ways to do this:
# https://rosettacode.org/wiki/Convert_decimal_number_to_rational
# http://www.homeschoolmath.net/teaching/rational_numbers.php
# http://stackoverflow.com/questions/95727/how-to-convert-floats-to-human-readable-fractions
floatToRatioRoutine = (decimal, AccuracyFactor) ->
FractionNumerator = undefined
FractionDenominator = undefined
DecimalSign = undefined
Z = undefined
PreviousDenominator = undefined
ScratchValue = undefined
ret = [
0
0
]
if isNaN(decimal)
return ret
# return 0/0
if decimal == Infinity
ret[0] = 1
ret[1] = 0
# 1/0
return ret
if decimal == -Infinity
ret[0] = -1
ret[1] = 0
# -1/0
return ret
if decimal < 0.0
DecimalSign = -1.0
else
DecimalSign = 1.0
decimal = Math.abs(decimal)
if Math.abs(decimal - Math.floor(decimal)) < AccuracyFactor
# handles exact integers including 0
FractionNumerator = decimal * DecimalSign
FractionDenominator = 1.0
ret[0] = FractionNumerator
ret[1] = FractionDenominator
return ret
if decimal < 1.0e-19
# X = 0 already taken care of
FractionNumerator = DecimalSign
FractionDenominator = 9999999999999999999.0
ret[0] = FractionNumerator
ret[1] = FractionDenominator
return ret
if decimal > 1.0e19
FractionNumerator = 9999999999999999999.0 * DecimalSign
FractionDenominator = 1.0
ret[0] = FractionNumerator
ret[1] = FractionDenominator
return ret
Z = decimal
PreviousDenominator = 0.0
FractionDenominator = 1.0
loop
Z = 1.0 / (Z - Math.floor(Z))
ScratchValue = FractionDenominator
FractionDenominator = FractionDenominator * Math.floor(Z) + PreviousDenominator
PreviousDenominator = ScratchValue
FractionNumerator = Math.floor(decimal * FractionDenominator + 0.5)
# Rounding Function
unless Math.abs(decimal - (FractionNumerator / FractionDenominator)) > AccuracyFactor and Z != Math.floor(Z)
break
FractionNumerator = DecimalSign * FractionNumerator
ret[0] = FractionNumerator
ret[1] = FractionDenominator
ret
approx_just_an_integer = 0
approx_sine_of_rational = 1
approx_sine_of_pi_times_rational = 2
approx_rationalOfPi = 3
approx_radicalOfRatio = 4
approx_nothingUseful = 5
approx_ratioOfRadical = 6
approx_rationalOfE = 7
approx_logarithmsOfRationals = 8
approx_rationalsOfLogarithms = 9
approxRationalsOfRadicals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# simple radicals.
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
for i in [2,3,5,6,7,8,10]
for j in [1..10]
#console.log "i,j: " + i + "," + j
hypothesis = Math.sqrt(i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * sqrt( " + i + " ) / " + j
#console.log result + " error: " + error
bestResultSoFar = [result, approx_ratioOfRadical, likelyMultiplier, i, j]
return bestResultSoFar
approxRadicalsOfRationals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# simple radicals.
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# this one catches things like Math.sqrt(3/4), but
# things like Math.sqrt(1/2) are caught by the paragraph
# above (and in a better form)
for i in [1,2,3,5,6,7,8,10]
for j in [1,2,3,5,6,7,8,10]
#console.log "i,j: " + i + "," + j
hypothesis = Math.sqrt(i/j)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * (sqrt( " + i + " / " + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_radicalOfRatio, likelyMultiplier, i, j]
return bestResultSoFar
approxRadicals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# simple radicals.
# we always prefer a rational of a radical of an integer
# to a radical of a rational. Radicals of rationals generate
# radicals at the denominator which we'd rather avoid
approxRationalsOfRadicalsResult = approxRationalsOfRadicals theFloat
if approxRationalsOfRadicalsResult?
return approxRationalsOfRadicalsResult
approxRadicalsOfRationalsResult = approxRadicalsOfRationals theFloat
if approxRadicalsOfRationalsResult?
return approxRadicalsOfRationalsResult
return null
approxLogs = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# we always prefer a rational of a log to a log of
# a rational
approxRationalsOfLogsResult = approxRationalsOfLogs theFloat
if approxRationalsOfLogsResult?
return approxRationalsOfLogsResult
approxLogsOfRationalsResult = approxLogsOfRationals theFloat
if approxLogsOfRationalsResult?
return approxLogsOfRationalsResult
return null
approxRationalsOfLogs = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# simple rationals of logs
for i in [2..5]
for j in [1..5]
#console.log "i,j: " + i + "," + j
hypothesis = Math.log(i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
# it does happen that due to roundings
# a "higher multiple" is picked, which is obviously
# unintended.
# E.g. 1 * log(1 / 3 ) doesn't match log( 3 ) BUT
# it matches -5 * log( 3 ) / 5
# so we avoid any case where the multiplier is a multiple
# of the divisor.
if likelyMultiplier != 1 and Math.abs(Math.floor(likelyMultiplier/j)) == Math.abs(likelyMultiplier/j)
continue
if error < 2.2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * log( " + i + " ) / " + j
#console.log result + " error: " + error
bestResultSoFar = [result, approx_rationalsOfLogarithms, likelyMultiplier, i, j]
return bestResultSoFar
approxLogsOfRationals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# simple logs of rationals
for i in [1..5]
for j in [1..5]
#console.log "i,j: " + i + "," + j
hypothesis = Math.log(i/j)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 1.96 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * log( " + i + " / " + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_logarithmsOfRationals, likelyMultiplier, i, j]
return bestResultSoFar
approxRationalsOfPowersOfE = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# simple rationals of a few powers of e
for i in [1..2]
for j in [1..12]
#console.log "i,j: " + i + "," + j
hypothesis = Math.pow(Math.E,i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * (e ^ " + i + " ) / " + j
#console.log result + " error: " + error
bestResultSoFar = [result, approx_rationalOfE, likelyMultiplier, i, j]
return bestResultSoFar
approxRationalsOfPowersOfPI = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
# here we do somethng a little special: since
# the powers of pi can get quite big, there might
# be multiple hypothesis where more of the
# magnitude is shifted to the multiplier, and some
# where more of the magnitude is shifted towards the
# exponent of pi. So we prefer the hypotheses with the
# lower multiplier since it's likely to insert more
# information.
minimumComplexity = Number.MAX_VALUE
# simple rationals of a few powers of PI
for i in [1..5]
for j in [1..12]
#console.log "i,j: " + i + "," + j
hypothesis = Math.pow(Math.PI,i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * (pi ^ " + i + " ) / " + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_rationalOfPi, likelyMultiplier, i, j]
#console.log "approxRationalsOfPowersOfPI returning: " + bestResultSoFar
return bestResultSoFar
approxTrigonometric = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# we always prefer a sin of a rational without the PI
approxSineOfRationalsResult = approxSineOfRationals theFloat
if approxSineOfRationalsResult?
return approxSineOfRationalsResult
approxSineOfRationalMultiplesOfPIResult = approxSineOfRationalMultiplesOfPI theFloat
if approxSineOfRationalMultiplesOfPIResult?
return approxSineOfRationalMultiplesOfPIResult
return null
approxSineOfRationals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# we only check very simple rationals because they begin to get tricky
# quickly, also they collide often with the "rational of pi" hypothesis.
# For example sin(11) is veeery close to 1 (-0.99999020655)
# (see: http://mathworld.wolfram.com/AlmostInteger.html )
# we stop at rationals that mention up to 10
for i in [1..4]
for j in [1..4]
#console.log "i,j: " + i + "," + j
fraction = i/j
hypothesis = Math.sin(fraction)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * sin( " + i + "/" + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_sine_of_rational, likelyMultiplier, i, j]
return bestResultSoFar
approxSineOfRationalMultiplesOfPI = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# check rational multiples of pi
for i in [1..13]
for j in [1..13]
#console.log "i,j: " + i + "," + j
fraction = i/j
hypothesis = Math.sin(Math.PI * fraction)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
# magic number 23 comes from the case sin(pi/10)
if error < 23 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * sin( " + i + "/" + j + " * pi )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_sine_of_pi_times_rational, likelyMultiplier, i, j]
return bestResultSoFar
approxAll = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
constantsSumMin = Number.MAX_VALUE
constantsSum = 0
bestApproxSoFar = null
LOG_EXPLANATIONS = true
approxRadicalsResult = approxRadicals theFloat
if approxRadicalsResult?
constantsSum = simpleComplexityMeasure approxRadicalsResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxRadicals: " + approxRadicalsResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxRadicalsResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxRadicals: " + approxRadicalsResult + " complexity: " + constantsSum
approxLogsResult = approxLogs(theFloat)
if approxLogsResult?
constantsSum = simpleComplexityMeasure approxLogsResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxLogs: " + approxLogsResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxLogsResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxLogs: " + approxLogsResult + " complexity: " + constantsSum
approxRationalsOfPowersOfEResult = approxRationalsOfPowersOfE(theFloat)
if approxRationalsOfPowersOfEResult?
constantsSum = simpleComplexityMeasure approxRationalsOfPowersOfEResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxRationalsOfPowersOfE: " + approxRationalsOfPowersOfEResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxRationalsOfPowersOfEResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxRationalsOfPowersOfE: " + approxRationalsOfPowersOfEResult + " complexity: " + constantsSum
approxRationalsOfPowersOfPIResult = approxRationalsOfPowersOfPI(theFloat)
if approxRationalsOfPowersOfPIResult?
constantsSum = simpleComplexityMeasure approxRationalsOfPowersOfPIResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxRationalsOfPowersOfPI: " + approxRationalsOfPowersOfPIResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxRationalsOfPowersOfPIResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxRationalsOfPowersOfPI: " + approxRationalsOfPowersOfPIResult + " complexity: " + constantsSum
approxTrigonometricResult = approxTrigonometric(theFloat)
if approxTrigonometricResult?
constantsSum = simpleComplexityMeasure approxTrigonometricResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxTrigonometric: " + approxTrigonometricResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxTrigonometricResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxTrigonometric: " + approxTrigonometricResult + " complexity: " + constantsSum
return bestApproxSoFar
simpleComplexityMeasure = (aResult, b, c) ->
theSum = null
if aResult instanceof Array
# we want PI and E to somewhat increase the
# complexity of the expression, so basically they count
# more than any integer lower than 3, i.e. we consider
# 1,2,3 to be more fundamental than PI or E.
switch aResult[1]
when approx_sine_of_pi_times_rational
theSum = 4
# exponents of PI and E need to be penalised as well
# otherwise they come to explain any big number
# so we count them just as much as the multiplier
when approx_rationalOfPi
theSum = Math.pow(4,Math.abs(aResult[3])) * Math.abs(aResult[2])
when approx_rationalOfE
theSum = Math.pow(3,Math.abs(aResult[3])) * Math.abs(aResult[2])
else theSum = 0
theSum += Math.abs(aResult[2]) * (Math.abs(aResult[3]) + Math.abs(aResult[4]))
else
theSum += Math.abs(aResult) * (Math.abs(b) + Math.abs(c))
# heavily discount unit constants
if aResult[2] == 1
theSum -= 1
else
theSum += 1
if aResult[3] == 1
theSum -= 1
else
theSum += 1
if aResult[4] == 1
theSum -= 1
else
theSum += 1
if theSum < 0
theSum = 0
return theSum
testApprox = () ->
for i in [2,3,5,6,7,8,10]
for j in [2,3,5,6,7,8,10]
if i == j then continue # this is just 1
console.log "testapproxRadicals testing: " + "1 * sqrt( " + i + " ) / " + j
fraction = i/j
value = Math.sqrt(i)/j
returned = approxRadicals(value)
returnedValue = returned[2] * Math.sqrt(returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testapproxRadicals: " + "1 * sqrt( " + i + " ) / " + j + " . obtained: " + returned
for i in [2,3,5,6,7,8,10]
for j in [2,3,5,6,7,8,10]
if i == j then continue # this is just 1
console.log "testapproxRadicals testing with 4 digits: " + "1 * sqrt( " + i + " ) / " + j
fraction = i/j
originalValue = Math.sqrt(i)/j
value = originalValue.toFixed(4)
returned = approxRadicals(value)
returnedValue = returned[2] * Math.sqrt(returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testapproxRadicals with 4 digits: " + "1 * sqrt( " + i + " ) / " + j + " . obtained: " + returned
for i in [2,3,5,6,7,8,10]
for j in [2,3,5,6,7,8,10]
if i == j then continue # this is just 1
console.log "testapproxRadicals testing: " + "1 * sqrt( " + i + " / " + j + " )"
fraction = i/j
value = Math.sqrt(i/j)
returned = approxRadicals(value)
if returned?
returnedValue = returned[2] * Math.sqrt(returned[3]/returned[4])
if returned[1] == approx_radicalOfRatio and Math.abs(value - returnedValue) > 1e-15
console.log "fail testapproxRadicals: " + "1 * sqrt( " + i + " / " + j + " ) . obtained: " + returned
for i in [1,2,3,5,6,7,8,10]
for j in [1,2,3,5,6,7,8,10]
if i == 1 and j == 1 then continue
console.log "testapproxRadicals testing with 4 digits:: " + "1 * sqrt( " + i + " / " + j + " )"
fraction = i/j
originalValue = Math.sqrt(i/j)
value = originalValue.toFixed(4)
returned = approxRadicals(value)
returnedValue = returned[2] * Math.sqrt(returned[3]/returned[4])
if returned[1] == approx_radicalOfRatio and Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testapproxRadicals with 4 digits:: " + "1 * sqrt( " + i + " / " + j + " ) . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing: " + "1 * log(" + i + " ) / " + j
fraction = i/j
value = Math.log(i)/j
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * log(" + i + " ) / " + j + " . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing with 4 digits: " + "1 * log(" + i + " ) / " + j
fraction = i/j
originalValue = Math.log(i)/j
value = originalValue.toFixed(4)
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testApproxAll with 4 digits: " + "1 * log(" + i + " ) / " + j + " . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing: " + "1 * log(" + i + " / " + j + " )"
fraction = i/j
value = Math.log(i/j)
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3]/returned[4])
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * log(" + i + " / " + j + " )" + " . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing with 4 digits: " + "1 * log(" + i + " / " + j + " )"
fraction = i/j
originalValue = Math.log(i/j)
value = originalValue.toFixed(4)
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3]/returned[4])
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testApproxAll with 4 digits: " + "1 * log(" + i + " / " + j + " )" + " . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "testApproxAll testing: " + "1 * (e ^ " + i + " ) / " + j
fraction = i/j
value = Math.pow(Math.E,i)/j
returned = approxAll(value)
returnedValue = returned[2] * Math.pow(Math.E,returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * (e ^ " + i + " ) / " + j + " . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "approxRationalsOfPowersOfE testing with 4 digits: " + "1 * (e ^ " + i + " ) / " + j
fraction = i/j
originalValue = Math.pow(Math.E,i)/j
value = originalValue.toFixed(4)
returned = approxRationalsOfPowersOfE(value)
returnedValue = returned[2] * Math.pow(Math.E,returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail approxRationalsOfPowersOfE with 4 digits: " + "1 * (e ^ " + i + " ) / " + j + " . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "testApproxAll testing: " + "1 * pi ^ " + i + " / " + j
fraction = i/j
value = Math.pow(Math.PI,i)/j
returned = approxAll(value)
returnedValue = returned[2] * Math.pow(Math.PI,returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * pi ^ " + i + " / " + j + " ) . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "approxRationalsOfPowersOfPI testing with 4 digits: " + "1 * pi ^ " + i + " / " + j
fraction = i/j
originalValue = Math.pow(Math.PI,i)/j
value = originalValue.toFixed(4)
returned = approxRationalsOfPowersOfPI(value)
returnedValue = returned[2] * Math.pow(Math.PI,returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail approxRationalsOfPowersOfPI with 4 digits: " + "1 * pi ^ " + i + " / " + j + " ) . obtained: " + returned
for i in [1..4]
for j in [1..4]
console.log "testApproxAll testing: " + "1 * sin( " + i + "/" + j + " )"
fraction = i/j
value = Math.sin(fraction)
returned = approxAll(value)
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(returnedFraction)
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * sin( " + i + "/" + j + " ) . obtained: " + returned
# 5 digits create no problem
for i in [1..4]
for j in [1..4]
console.log "testApproxAll testing with 5 digits: " + "1 * sin( " + i + "/" + j + " )"
fraction = i/j
originalValue = Math.sin(fraction)
value = originalValue.toFixed(5)
returned = approxAll(value)
if !returned?
console.log "fail testApproxAll with 5 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: undefined "
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(returnedFraction)
error = Math.abs(originalValue - returnedValue)
if error > 1e-14
console.log "fail testApproxAll with 5 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: " + returned + " error: " + error
# 4 digits create two collisions
for i in [1..4]
for j in [1..4]
console.log "testApproxAll testing with 4 digits: " + "1 * sin( " + i + "/" + j + " )"
fraction = i/j
originalValue = Math.sin(fraction)
value = originalValue.toFixed(4)
returned = approxAll(value)
if !returned?
console.log "fail testApproxAll with 4 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: undefined "
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(returnedFraction)
error = Math.abs(originalValue - returnedValue)
if error > 1e-14
console.log "fail testApproxAll with 4 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: " + returned + " error: " + error
value = 0
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0"
value = 0.0
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.0"
value = 0.00
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.00"
value = 0.000
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.000"
value = 0.0000
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.0000"
value = 1
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1"
value = 1.0
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.0"
value = 1.00
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.00"
value = 1.000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.000"
value = 1.0000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.0000"
value = 1.00000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.00000"
value = Math.sqrt(2)
if approxAll(value)[0] != "1 * sqrt( 2 ) / 1" then console.log "fail testApproxAll: Math.sqrt(2)"
value = 1.41
if approxAll(value)[0] != "1 * sqrt( 2 ) / 1" then console.log "fail testApproxAll: 1.41"
# if we narrow down to a particular family then we can get
# an OK guess even with few digits, expecially for really "famous" numbers
value = 1.4
if approxRadicals(value)[0] != "1 * sqrt( 2 ) / 1" then console.log "fail approxRadicals: 1.4"
value = 0.6
if approxLogs(value)[0] != "1 * log( 2 ) / 1" then console.log "fail approxLogs: 0.6"
value = 0.69
if approxLogs(value)[0] != "1 * log( 2 ) / 1" then console.log "fail approxLogs: 0.69"
value = 0.7
if approxLogs(value)[0] != "1 * log( 2 ) / 1" then console.log "fail approxLogs: 0.7"
value = 1.09
if approxLogs(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxLogs: 1.09"
value = 1.09
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.09"
value = 1.098
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.098"
value = 1.1
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.1"
value = 1.11
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.11"
value = Math.sqrt(3)
if approxAll(value)[0] != "1 * sqrt( 3 ) / 1" then console.log "fail testApproxAll: Math.sqrt(3)"
value = 1.0000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.0000"
value = 3.141592
if approxAll(value)[0] != "1 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 3.141592"
value = 31.41592
if approxAll(value)[0] != "10 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 31.41592"
value = 314.1592
if approxAll(value)[0] != "100 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 314.1592"
value = 31415926.53589793
if approxAll(value)[0] != "10000000 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 31415926.53589793"
value = Math.sqrt(2)
if approxTrigonometric(value)[0] != "2 * sin( 1/4 * pi )" then console.log "fail approxTrigonometric: Math.sqrt(2)"
value = Math.sqrt(3)
if approxTrigonometric(value)[0] != "2 * sin( 1/3 * pi )" then console.log "fail approxTrigonometric: Math.sqrt(3)"
value = (Math.sqrt(6) - Math.sqrt(2))/4
if approxAll(value)[0] != "1 * sin( 1/12 * pi )" then console.log "fail testApproxAll: (Math.sqrt(6) - Math.sqrt(2))/4"
value = Math.sqrt(2 - Math.sqrt(2))/2
if approxAll(value)[0] != "1 * sin( 1/8 * pi )" then console.log "fail testApproxAll: Math.sqrt(2 - Math.sqrt(2))/2"
value = (Math.sqrt(6) + Math.sqrt(2))/4
if approxAll(value)[0] != "1 * sin( 5/12 * pi )" then console.log "fail testApproxAll: (Math.sqrt(6) + Math.sqrt(2))/4"
value = Math.sqrt(2 + Math.sqrt(3))/2
if approxAll(value)[0] != "1 * sin( 5/12 * pi )" then console.log "fail testApproxAll: Math.sqrt(2 + Math.sqrt(3))/2"
value = (Math.sqrt(5) - 1)/4
if approxAll(value)[0] != "1 * sin( 1/10 * pi )" then console.log "fail testApproxAll: (Math.sqrt(5) - 1)/4"
value = Math.sqrt(10 - 2*Math.sqrt(5))/4
if approxAll(value)[0] != "1 * sin( 1/5 * pi )" then console.log "fail testApproxAll: Math.sqrt(10 - 2*Math.sqrt(5))/4"
# this has a radical form but it's too long to write
value = Math.sin(Math.PI/7)
if approxAll(value)[0] != "1 * sin( 1/7 * pi )" then console.log "fail testApproxAll: Math.sin(Math.PI/7)"
# this has a radical form but it's too long to write
value = Math.sin(Math.PI/9)
if approxAll(value)[0] != "1 * sin( 1/9 * pi )" then console.log "fail testApproxAll: Math.sin(Math.PI/9)"
value = 1836.15267
if approxRationalsOfPowersOfPI(value)[0] != "6 * (pi ^ 5 ) / 1 )" then console.log "fail approxRationalsOfPowersOfPI: 1836.15267"
for i in [1..13]
for j in [1..13]
console.log "approxTrigonometric testing: " + "1 * sin( " + i + "/" + j + " * pi )"
fraction = i/j
value = Math.sin(Math.PI * fraction)
# we specifically search for sines of rational multiples of PI
# because too many of them would be picked up as simple
# rationals.
returned = approxTrigonometric(value)
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(Math.PI * returnedFraction)
if Math.abs(value - returnedValue) > 1e-15
console.log "fail approxTrigonometric: " + "1 * sin( " + i + "/" + j + " * pi ) . obtained: " + returned
for i in [1..13]
for j in [1..13]
# with four digits, there are two collisions with the
# "simple fraction" argument hypotesis, which we prefer since
# it's a simpler expression, so let's skip those
# two tests
if i == 5 and j == 11 or
i == 6 and j == 11
continue
console.log "approxTrigonometric testing with 4 digits: " + "1 * sin( " + i + "/" + j + " * pi )"
fraction = i/j
originalValue = Math.sin(Math.PI * fraction)
value = originalValue.toFixed(4)
# we specifically search for sines of rational multiples of PI
# because too many of them would be picked up as simple
# rationals.
returned = approxTrigonometric(value)
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(Math.PI * returnedFraction)
error = Math.abs(originalValue - returnedValue)
if error > 1e-14
console.log "fail approxTrigonometric with 4 digits: " + "1 * sin( " + i + "/" + j + " * pi ) . obtained: " + returned + " error: " + error
console.log "testApprox done"
$.approxRadicals = approxRadicals
$.approxRationalsOfLogs = approxRationalsOfLogs
$.approxAll = approxAll
$.testApprox = testApprox
| 97089 | ###
Guesses a rational for each float in the passed expression
###
Eval_approxratio = ->
theArgument = cadr(p1)
push(theArgument)
approxratioRecursive()
approxratioRecursive = ->
i = 0
save()
p1 = pop(); # expr
if (istensor(p1))
p4 = alloc_tensor(p1.tensor.nelem)
p4.tensor.ndim = p1.tensor.ndim
for i in [0...p1.tensor.ndim]
p4.tensor.dim[i] = p1.tensor.dim[i]
for i in [0...p1.tensor.nelem]
push(p1.tensor.elem[i])
approxratioRecursive()
p4.tensor.elem[i] = pop()
check_tensor_dimensions p4
push(p4)
else if p1.k == DOUBLE
push(p1)
approxOneRatioOnly()
else if (iscons(p1))
push(car(p1))
approxratioRecursive()
push(cdr(p1))
approxratioRecursive()
cons()
else
push(p1)
restore()
approxOneRatioOnly = ->
zzfloat()
supposedlyTheFloat = pop()
if supposedlyTheFloat.k == DOUBLE
theFloat = supposedlyTheFloat.d
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
theRatio = floatToRatioRoutine(theFloat,precision)
push_rational(theRatio[0], theRatio[1])
else
push_integer(theFloat)
return
# we didn't manage, just leave unexpressed
push_symbol(APPROXRATIO)
push(theArgument)
list(2)
# original routine by <NAME>, see
# https://web.archive.org/web/20111027100847/http://homepage.smc.edu/kennedy_john/DEC2FRAC.PDF
# courtesy of <NAME>
# who ported this to JavaScript under MIT licence
# also see
# https://github.com/geogebra/geogebra/blob/master/common/src/main/java/org/geogebra/common/kernel/algos/AlgoFractionText.java
# potential other ways to do this:
# https://rosettacode.org/wiki/Convert_decimal_number_to_rational
# http://www.homeschoolmath.net/teaching/rational_numbers.php
# http://stackoverflow.com/questions/95727/how-to-convert-floats-to-human-readable-fractions
floatToRatioRoutine = (decimal, AccuracyFactor) ->
FractionNumerator = undefined
FractionDenominator = undefined
DecimalSign = undefined
Z = undefined
PreviousDenominator = undefined
ScratchValue = undefined
ret = [
0
0
]
if isNaN(decimal)
return ret
# return 0/0
if decimal == Infinity
ret[0] = 1
ret[1] = 0
# 1/0
return ret
if decimal == -Infinity
ret[0] = -1
ret[1] = 0
# -1/0
return ret
if decimal < 0.0
DecimalSign = -1.0
else
DecimalSign = 1.0
decimal = Math.abs(decimal)
if Math.abs(decimal - Math.floor(decimal)) < AccuracyFactor
# handles exact integers including 0
FractionNumerator = decimal * DecimalSign
FractionDenominator = 1.0
ret[0] = FractionNumerator
ret[1] = FractionDenominator
return ret
if decimal < 1.0e-19
# X = 0 already taken care of
FractionNumerator = DecimalSign
FractionDenominator = 9999999999999999999.0
ret[0] = FractionNumerator
ret[1] = FractionDenominator
return ret
if decimal > 1.0e19
FractionNumerator = 9999999999999999999.0 * DecimalSign
FractionDenominator = 1.0
ret[0] = FractionNumerator
ret[1] = FractionDenominator
return ret
Z = decimal
PreviousDenominator = 0.0
FractionDenominator = 1.0
loop
Z = 1.0 / (Z - Math.floor(Z))
ScratchValue = FractionDenominator
FractionDenominator = FractionDenominator * Math.floor(Z) + PreviousDenominator
PreviousDenominator = ScratchValue
FractionNumerator = Math.floor(decimal * FractionDenominator + 0.5)
# Rounding Function
unless Math.abs(decimal - (FractionNumerator / FractionDenominator)) > AccuracyFactor and Z != Math.floor(Z)
break
FractionNumerator = DecimalSign * FractionNumerator
ret[0] = FractionNumerator
ret[1] = FractionDenominator
ret
approx_just_an_integer = 0
approx_sine_of_rational = 1
approx_sine_of_pi_times_rational = 2
approx_rationalOfPi = 3
approx_radicalOfRatio = 4
approx_nothingUseful = 5
approx_ratioOfRadical = 6
approx_rationalOfE = 7
approx_logarithmsOfRationals = 8
approx_rationalsOfLogarithms = 9
approxRationalsOfRadicals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# simple radicals.
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
for i in [2,3,5,6,7,8,10]
for j in [1..10]
#console.log "i,j: " + i + "," + j
hypothesis = Math.sqrt(i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * sqrt( " + i + " ) / " + j
#console.log result + " error: " + error
bestResultSoFar = [result, approx_ratioOfRadical, likelyMultiplier, i, j]
return bestResultSoFar
approxRadicalsOfRationals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# simple radicals.
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# this one catches things like Math.sqrt(3/4), but
# things like Math.sqrt(1/2) are caught by the paragraph
# above (and in a better form)
for i in [1,2,3,5,6,7,8,10]
for j in [1,2,3,5,6,7,8,10]
#console.log "i,j: " + i + "," + j
hypothesis = Math.sqrt(i/j)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * (sqrt( " + i + " / " + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_radicalOfRatio, likelyMultiplier, i, j]
return bestResultSoFar
approxRadicals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# simple radicals.
# we always prefer a rational of a radical of an integer
# to a radical of a rational. Radicals of rationals generate
# radicals at the denominator which we'd rather avoid
approxRationalsOfRadicalsResult = approxRationalsOfRadicals theFloat
if approxRationalsOfRadicalsResult?
return approxRationalsOfRadicalsResult
approxRadicalsOfRationalsResult = approxRadicalsOfRationals theFloat
if approxRadicalsOfRationalsResult?
return approxRadicalsOfRationalsResult
return null
approxLogs = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# we always prefer a rational of a log to a log of
# a rational
approxRationalsOfLogsResult = approxRationalsOfLogs theFloat
if approxRationalsOfLogsResult?
return approxRationalsOfLogsResult
approxLogsOfRationalsResult = approxLogsOfRationals theFloat
if approxLogsOfRationalsResult?
return approxLogsOfRationalsResult
return null
approxRationalsOfLogs = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# simple rationals of logs
for i in [2..5]
for j in [1..5]
#console.log "i,j: " + i + "," + j
hypothesis = Math.log(i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
# it does happen that due to roundings
# a "higher multiple" is picked, which is obviously
# unintended.
# E.g. 1 * log(1 / 3 ) doesn't match log( 3 ) BUT
# it matches -5 * log( 3 ) / 5
# so we avoid any case where the multiplier is a multiple
# of the divisor.
if likelyMultiplier != 1 and Math.abs(Math.floor(likelyMultiplier/j)) == Math.abs(likelyMultiplier/j)
continue
if error < 2.2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * log( " + i + " ) / " + j
#console.log result + " error: " + error
bestResultSoFar = [result, approx_rationalsOfLogarithms, likelyMultiplier, i, j]
return bestResultSoFar
approxLogsOfRationals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# simple logs of rationals
for i in [1..5]
for j in [1..5]
#console.log "i,j: " + i + "," + j
hypothesis = Math.log(i/j)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 1.96 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * log( " + i + " / " + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_logarithmsOfRationals, likelyMultiplier, i, j]
return bestResultSoFar
approxRationalsOfPowersOfE = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# simple rationals of a few powers of e
for i in [1..2]
for j in [1..12]
#console.log "i,j: " + i + "," + j
hypothesis = Math.pow(Math.E,i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * (e ^ " + i + " ) / " + j
#console.log result + " error: " + error
bestResultSoFar = [result, approx_rationalOfE, likelyMultiplier, i, j]
return bestResultSoFar
approxRationalsOfPowersOfPI = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
# here we do somethng a little special: since
# the powers of pi can get quite big, there might
# be multiple hypothesis where more of the
# magnitude is shifted to the multiplier, and some
# where more of the magnitude is shifted towards the
# exponent of pi. So we prefer the hypotheses with the
# lower multiplier since it's likely to insert more
# information.
minimumComplexity = Number.MAX_VALUE
# simple rationals of a few powers of PI
for i in [1..5]
for j in [1..12]
#console.log "i,j: " + i + "," + j
hypothesis = Math.pow(Math.PI,i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * (pi ^ " + i + " ) / " + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_rationalOfPi, likelyMultiplier, i, j]
#console.log "approxRationalsOfPowersOfPI returning: " + bestResultSoFar
return bestResultSoFar
approxTrigonometric = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# we always prefer a sin of a rational without the PI
approxSineOfRationalsResult = approxSineOfRationals theFloat
if approxSineOfRationalsResult?
return approxSineOfRationalsResult
approxSineOfRationalMultiplesOfPIResult = approxSineOfRationalMultiplesOfPI theFloat
if approxSineOfRationalMultiplesOfPIResult?
return approxSineOfRationalMultiplesOfPIResult
return null
approxSineOfRationals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# we only check very simple rationals because they begin to get tricky
# quickly, also they collide often with the "rational of pi" hypothesis.
# For example sin(11) is veeery close to 1 (-0.99999020655)
# (see: http://mathworld.wolfram.com/AlmostInteger.html )
# we stop at rationals that mention up to 10
for i in [1..4]
for j in [1..4]
#console.log "i,j: " + i + "," + j
fraction = i/j
hypothesis = Math.sin(fraction)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * sin( " + i + "/" + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_sine_of_rational, likelyMultiplier, i, j]
return bestResultSoFar
approxSineOfRationalMultiplesOfPI = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# check rational multiples of pi
for i in [1..13]
for j in [1..13]
#console.log "i,j: " + i + "," + j
fraction = i/j
hypothesis = Math.sin(Math.PI * fraction)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
# magic number 23 comes from the case sin(pi/10)
if error < 23 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * sin( " + i + "/" + j + " * pi )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_sine_of_pi_times_rational, likelyMultiplier, i, j]
return bestResultSoFar
approxAll = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
constantsSumMin = Number.MAX_VALUE
constantsSum = 0
bestApproxSoFar = null
LOG_EXPLANATIONS = true
approxRadicalsResult = approxRadicals theFloat
if approxRadicalsResult?
constantsSum = simpleComplexityMeasure approxRadicalsResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxRadicals: " + approxRadicalsResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxRadicalsResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxRadicals: " + approxRadicalsResult + " complexity: " + constantsSum
approxLogsResult = approxLogs(theFloat)
if approxLogsResult?
constantsSum = simpleComplexityMeasure approxLogsResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxLogs: " + approxLogsResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxLogsResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxLogs: " + approxLogsResult + " complexity: " + constantsSum
approxRationalsOfPowersOfEResult = approxRationalsOfPowersOfE(theFloat)
if approxRationalsOfPowersOfEResult?
constantsSum = simpleComplexityMeasure approxRationalsOfPowersOfEResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxRationalsOfPowersOfE: " + approxRationalsOfPowersOfEResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxRationalsOfPowersOfEResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxRationalsOfPowersOfE: " + approxRationalsOfPowersOfEResult + " complexity: " + constantsSum
approxRationalsOfPowersOfPIResult = approxRationalsOfPowersOfPI(theFloat)
if approxRationalsOfPowersOfPIResult?
constantsSum = simpleComplexityMeasure approxRationalsOfPowersOfPIResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxRationalsOfPowersOfPI: " + approxRationalsOfPowersOfPIResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxRationalsOfPowersOfPIResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxRationalsOfPowersOfPI: " + approxRationalsOfPowersOfPIResult + " complexity: " + constantsSum
approxTrigonometricResult = approxTrigonometric(theFloat)
if approxTrigonometricResult?
constantsSum = simpleComplexityMeasure approxTrigonometricResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxTrigonometric: " + approxTrigonometricResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxTrigonometricResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxTrigonometric: " + approxTrigonometricResult + " complexity: " + constantsSum
return bestApproxSoFar
simpleComplexityMeasure = (aResult, b, c) ->
theSum = null
if aResult instanceof Array
# we want PI and E to somewhat increase the
# complexity of the expression, so basically they count
# more than any integer lower than 3, i.e. we consider
# 1,2,3 to be more fundamental than PI or E.
switch aResult[1]
when approx_sine_of_pi_times_rational
theSum = 4
# exponents of PI and E need to be penalised as well
# otherwise they come to explain any big number
# so we count them just as much as the multiplier
when approx_rationalOfPi
theSum = Math.pow(4,Math.abs(aResult[3])) * Math.abs(aResult[2])
when approx_rationalOfE
theSum = Math.pow(3,Math.abs(aResult[3])) * Math.abs(aResult[2])
else theSum = 0
theSum += Math.abs(aResult[2]) * (Math.abs(aResult[3]) + Math.abs(aResult[4]))
else
theSum += Math.abs(aResult) * (Math.abs(b) + Math.abs(c))
# heavily discount unit constants
if aResult[2] == 1
theSum -= 1
else
theSum += 1
if aResult[3] == 1
theSum -= 1
else
theSum += 1
if aResult[4] == 1
theSum -= 1
else
theSum += 1
if theSum < 0
theSum = 0
return theSum
testApprox = () ->
for i in [2,3,5,6,7,8,10]
for j in [2,3,5,6,7,8,10]
if i == j then continue # this is just 1
console.log "testapproxRadicals testing: " + "1 * sqrt( " + i + " ) / " + j
fraction = i/j
value = Math.sqrt(i)/j
returned = approxRadicals(value)
returnedValue = returned[2] * Math.sqrt(returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testapproxRadicals: " + "1 * sqrt( " + i + " ) / " + j + " . obtained: " + returned
for i in [2,3,5,6,7,8,10]
for j in [2,3,5,6,7,8,10]
if i == j then continue # this is just 1
console.log "testapproxRadicals testing with 4 digits: " + "1 * sqrt( " + i + " ) / " + j
fraction = i/j
originalValue = Math.sqrt(i)/j
value = originalValue.toFixed(4)
returned = approxRadicals(value)
returnedValue = returned[2] * Math.sqrt(returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testapproxRadicals with 4 digits: " + "1 * sqrt( " + i + " ) / " + j + " . obtained: " + returned
for i in [2,3,5,6,7,8,10]
for j in [2,3,5,6,7,8,10]
if i == j then continue # this is just 1
console.log "testapproxRadicals testing: " + "1 * sqrt( " + i + " / " + j + " )"
fraction = i/j
value = Math.sqrt(i/j)
returned = approxRadicals(value)
if returned?
returnedValue = returned[2] * Math.sqrt(returned[3]/returned[4])
if returned[1] == approx_radicalOfRatio and Math.abs(value - returnedValue) > 1e-15
console.log "fail testapproxRadicals: " + "1 * sqrt( " + i + " / " + j + " ) . obtained: " + returned
for i in [1,2,3,5,6,7,8,10]
for j in [1,2,3,5,6,7,8,10]
if i == 1 and j == 1 then continue
console.log "testapproxRadicals testing with 4 digits:: " + "1 * sqrt( " + i + " / " + j + " )"
fraction = i/j
originalValue = Math.sqrt(i/j)
value = originalValue.toFixed(4)
returned = approxRadicals(value)
returnedValue = returned[2] * Math.sqrt(returned[3]/returned[4])
if returned[1] == approx_radicalOfRatio and Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testapproxRadicals with 4 digits:: " + "1 * sqrt( " + i + " / " + j + " ) . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing: " + "1 * log(" + i + " ) / " + j
fraction = i/j
value = Math.log(i)/j
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * log(" + i + " ) / " + j + " . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing with 4 digits: " + "1 * log(" + i + " ) / " + j
fraction = i/j
originalValue = Math.log(i)/j
value = originalValue.toFixed(4)
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testApproxAll with 4 digits: " + "1 * log(" + i + " ) / " + j + " . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing: " + "1 * log(" + i + " / " + j + " )"
fraction = i/j
value = Math.log(i/j)
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3]/returned[4])
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * log(" + i + " / " + j + " )" + " . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing with 4 digits: " + "1 * log(" + i + " / " + j + " )"
fraction = i/j
originalValue = Math.log(i/j)
value = originalValue.toFixed(4)
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3]/returned[4])
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testApproxAll with 4 digits: " + "1 * log(" + i + " / " + j + " )" + " . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "testApproxAll testing: " + "1 * (e ^ " + i + " ) / " + j
fraction = i/j
value = Math.pow(Math.E,i)/j
returned = approxAll(value)
returnedValue = returned[2] * Math.pow(Math.E,returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * (e ^ " + i + " ) / " + j + " . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "approxRationalsOfPowersOfE testing with 4 digits: " + "1 * (e ^ " + i + " ) / " + j
fraction = i/j
originalValue = Math.pow(Math.E,i)/j
value = originalValue.toFixed(4)
returned = approxRationalsOfPowersOfE(value)
returnedValue = returned[2] * Math.pow(Math.E,returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail approxRationalsOfPowersOfE with 4 digits: " + "1 * (e ^ " + i + " ) / " + j + " . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "testApproxAll testing: " + "1 * pi ^ " + i + " / " + j
fraction = i/j
value = Math.pow(Math.PI,i)/j
returned = approxAll(value)
returnedValue = returned[2] * Math.pow(Math.PI,returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * pi ^ " + i + " / " + j + " ) . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "approxRationalsOfPowersOfPI testing with 4 digits: " + "1 * pi ^ " + i + " / " + j
fraction = i/j
originalValue = Math.pow(Math.PI,i)/j
value = originalValue.toFixed(4)
returned = approxRationalsOfPowersOfPI(value)
returnedValue = returned[2] * Math.pow(Math.PI,returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail approxRationalsOfPowersOfPI with 4 digits: " + "1 * pi ^ " + i + " / " + j + " ) . obtained: " + returned
for i in [1..4]
for j in [1..4]
console.log "testApproxAll testing: " + "1 * sin( " + i + "/" + j + " )"
fraction = i/j
value = Math.sin(fraction)
returned = approxAll(value)
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(returnedFraction)
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * sin( " + i + "/" + j + " ) . obtained: " + returned
# 5 digits create no problem
for i in [1..4]
for j in [1..4]
console.log "testApproxAll testing with 5 digits: " + "1 * sin( " + i + "/" + j + " )"
fraction = i/j
originalValue = Math.sin(fraction)
value = originalValue.toFixed(5)
returned = approxAll(value)
if !returned?
console.log "fail testApproxAll with 5 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: undefined "
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(returnedFraction)
error = Math.abs(originalValue - returnedValue)
if error > 1e-14
console.log "fail testApproxAll with 5 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: " + returned + " error: " + error
# 4 digits create two collisions
for i in [1..4]
for j in [1..4]
console.log "testApproxAll testing with 4 digits: " + "1 * sin( " + i + "/" + j + " )"
fraction = i/j
originalValue = Math.sin(fraction)
value = originalValue.toFixed(4)
returned = approxAll(value)
if !returned?
console.log "fail testApproxAll with 4 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: undefined "
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(returnedFraction)
error = Math.abs(originalValue - returnedValue)
if error > 1e-14
console.log "fail testApproxAll with 4 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: " + returned + " error: " + error
value = 0
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0"
value = 0.0
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.0"
value = 0.00
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.00"
value = 0.000
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.000"
value = 0.0000
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.0000"
value = 1
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1"
value = 1.0
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.0"
value = 1.00
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.00"
value = 1.000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.000"
value = 1.0000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.0000"
value = 1.00000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.00000"
value = Math.sqrt(2)
if approxAll(value)[0] != "1 * sqrt( 2 ) / 1" then console.log "fail testApproxAll: Math.sqrt(2)"
value = 1.41
if approxAll(value)[0] != "1 * sqrt( 2 ) / 1" then console.log "fail testApproxAll: 1.41"
# if we narrow down to a particular family then we can get
# an OK guess even with few digits, expecially for really "famous" numbers
value = 1.4
if approxRadicals(value)[0] != "1 * sqrt( 2 ) / 1" then console.log "fail approxRadicals: 1.4"
value = 0.6
if approxLogs(value)[0] != "1 * log( 2 ) / 1" then console.log "fail approxLogs: 0.6"
value = 0.69
if approxLogs(value)[0] != "1 * log( 2 ) / 1" then console.log "fail approxLogs: 0.69"
value = 0.7
if approxLogs(value)[0] != "1 * log( 2 ) / 1" then console.log "fail approxLogs: 0.7"
value = 1.09
if approxLogs(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxLogs: 1.09"
value = 1.09
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.09"
value = 1.098
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.098"
value = 1.1
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.1"
value = 1.11
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.11"
value = Math.sqrt(3)
if approxAll(value)[0] != "1 * sqrt( 3 ) / 1" then console.log "fail testApproxAll: Math.sqrt(3)"
value = 1.0000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.0000"
value = 3.141592
if approxAll(value)[0] != "1 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 3.141592"
value = 31.41592
if approxAll(value)[0] != "10 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 31.41592"
value = 314.1592
if approxAll(value)[0] != "100 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 314.1592"
value = 31415926.53589793
if approxAll(value)[0] != "10000000 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 31415926.53589793"
value = Math.sqrt(2)
if approxTrigonometric(value)[0] != "2 * sin( 1/4 * pi )" then console.log "fail approxTrigonometric: Math.sqrt(2)"
value = Math.sqrt(3)
if approxTrigonometric(value)[0] != "2 * sin( 1/3 * pi )" then console.log "fail approxTrigonometric: Math.sqrt(3)"
value = (Math.sqrt(6) - Math.sqrt(2))/4
if approxAll(value)[0] != "1 * sin( 1/12 * pi )" then console.log "fail testApproxAll: (Math.sqrt(6) - Math.sqrt(2))/4"
value = Math.sqrt(2 - Math.sqrt(2))/2
if approxAll(value)[0] != "1 * sin( 1/8 * pi )" then console.log "fail testApproxAll: Math.sqrt(2 - Math.sqrt(2))/2"
value = (Math.sqrt(6) + Math.sqrt(2))/4
if approxAll(value)[0] != "1 * sin( 5/12 * pi )" then console.log "fail testApproxAll: (Math.sqrt(6) + Math.sqrt(2))/4"
value = Math.sqrt(2 + Math.sqrt(3))/2
if approxAll(value)[0] != "1 * sin( 5/12 * pi )" then console.log "fail testApproxAll: Math.sqrt(2 + Math.sqrt(3))/2"
value = (Math.sqrt(5) - 1)/4
if approxAll(value)[0] != "1 * sin( 1/10 * pi )" then console.log "fail testApproxAll: (Math.sqrt(5) - 1)/4"
value = Math.sqrt(10 - 2*Math.sqrt(5))/4
if approxAll(value)[0] != "1 * sin( 1/5 * pi )" then console.log "fail testApproxAll: Math.sqrt(10 - 2*Math.sqrt(5))/4"
# this has a radical form but it's too long to write
value = Math.sin(Math.PI/7)
if approxAll(value)[0] != "1 * sin( 1/7 * pi )" then console.log "fail testApproxAll: Math.sin(Math.PI/7)"
# this has a radical form but it's too long to write
value = Math.sin(Math.PI/9)
if approxAll(value)[0] != "1 * sin( 1/9 * pi )" then console.log "fail testApproxAll: Math.sin(Math.PI/9)"
value = 1836.15267
if approxRationalsOfPowersOfPI(value)[0] != "6 * (pi ^ 5 ) / 1 )" then console.log "fail approxRationalsOfPowersOfPI: 1836.15267"
for i in [1..13]
for j in [1..13]
console.log "approxTrigonometric testing: " + "1 * sin( " + i + "/" + j + " * pi )"
fraction = i/j
value = Math.sin(Math.PI * fraction)
# we specifically search for sines of rational multiples of PI
# because too many of them would be picked up as simple
# rationals.
returned = approxTrigonometric(value)
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(Math.PI * returnedFraction)
if Math.abs(value - returnedValue) > 1e-15
console.log "fail approxTrigonometric: " + "1 * sin( " + i + "/" + j + " * pi ) . obtained: " + returned
for i in [1..13]
for j in [1..13]
# with four digits, there are two collisions with the
# "simple fraction" argument hypotesis, which we prefer since
# it's a simpler expression, so let's skip those
# two tests
if i == 5 and j == 11 or
i == 6 and j == 11
continue
console.log "approxTrigonometric testing with 4 digits: " + "1 * sin( " + i + "/" + j + " * pi )"
fraction = i/j
originalValue = Math.sin(Math.PI * fraction)
value = originalValue.toFixed(4)
# we specifically search for sines of rational multiples of PI
# because too many of them would be picked up as simple
# rationals.
returned = approxTrigonometric(value)
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(Math.PI * returnedFraction)
error = Math.abs(originalValue - returnedValue)
if error > 1e-14
console.log "fail approxTrigonometric with 4 digits: " + "1 * sin( " + i + "/" + j + " * pi ) . obtained: " + returned + " error: " + error
console.log "testApprox done"
$.approxRadicals = approxRadicals
$.approxRationalsOfLogs = approxRationalsOfLogs
$.approxAll = approxAll
$.testApprox = testApprox
| true | ###
Guesses a rational for each float in the passed expression
###
Eval_approxratio = ->
theArgument = cadr(p1)
push(theArgument)
approxratioRecursive()
approxratioRecursive = ->
i = 0
save()
p1 = pop(); # expr
if (istensor(p1))
p4 = alloc_tensor(p1.tensor.nelem)
p4.tensor.ndim = p1.tensor.ndim
for i in [0...p1.tensor.ndim]
p4.tensor.dim[i] = p1.tensor.dim[i]
for i in [0...p1.tensor.nelem]
push(p1.tensor.elem[i])
approxratioRecursive()
p4.tensor.elem[i] = pop()
check_tensor_dimensions p4
push(p4)
else if p1.k == DOUBLE
push(p1)
approxOneRatioOnly()
else if (iscons(p1))
push(car(p1))
approxratioRecursive()
push(cdr(p1))
approxratioRecursive()
cons()
else
push(p1)
restore()
approxOneRatioOnly = ->
zzfloat()
supposedlyTheFloat = pop()
if supposedlyTheFloat.k == DOUBLE
theFloat = supposedlyTheFloat.d
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
theRatio = floatToRatioRoutine(theFloat,precision)
push_rational(theRatio[0], theRatio[1])
else
push_integer(theFloat)
return
# we didn't manage, just leave unexpressed
push_symbol(APPROXRATIO)
push(theArgument)
list(2)
# original routine by PI:NAME:<NAME>END_PI, see
# https://web.archive.org/web/20111027100847/http://homepage.smc.edu/kennedy_john/DEC2FRAC.PDF
# courtesy of PI:NAME:<NAME>END_PI
# who ported this to JavaScript under MIT licence
# also see
# https://github.com/geogebra/geogebra/blob/master/common/src/main/java/org/geogebra/common/kernel/algos/AlgoFractionText.java
# potential other ways to do this:
# https://rosettacode.org/wiki/Convert_decimal_number_to_rational
# http://www.homeschoolmath.net/teaching/rational_numbers.php
# http://stackoverflow.com/questions/95727/how-to-convert-floats-to-human-readable-fractions
floatToRatioRoutine = (decimal, AccuracyFactor) ->
FractionNumerator = undefined
FractionDenominator = undefined
DecimalSign = undefined
Z = undefined
PreviousDenominator = undefined
ScratchValue = undefined
ret = [
0
0
]
if isNaN(decimal)
return ret
# return 0/0
if decimal == Infinity
ret[0] = 1
ret[1] = 0
# 1/0
return ret
if decimal == -Infinity
ret[0] = -1
ret[1] = 0
# -1/0
return ret
if decimal < 0.0
DecimalSign = -1.0
else
DecimalSign = 1.0
decimal = Math.abs(decimal)
if Math.abs(decimal - Math.floor(decimal)) < AccuracyFactor
# handles exact integers including 0
FractionNumerator = decimal * DecimalSign
FractionDenominator = 1.0
ret[0] = FractionNumerator
ret[1] = FractionDenominator
return ret
if decimal < 1.0e-19
# X = 0 already taken care of
FractionNumerator = DecimalSign
FractionDenominator = 9999999999999999999.0
ret[0] = FractionNumerator
ret[1] = FractionDenominator
return ret
if decimal > 1.0e19
FractionNumerator = 9999999999999999999.0 * DecimalSign
FractionDenominator = 1.0
ret[0] = FractionNumerator
ret[1] = FractionDenominator
return ret
Z = decimal
PreviousDenominator = 0.0
FractionDenominator = 1.0
loop
Z = 1.0 / (Z - Math.floor(Z))
ScratchValue = FractionDenominator
FractionDenominator = FractionDenominator * Math.floor(Z) + PreviousDenominator
PreviousDenominator = ScratchValue
FractionNumerator = Math.floor(decimal * FractionDenominator + 0.5)
# Rounding Function
unless Math.abs(decimal - (FractionNumerator / FractionDenominator)) > AccuracyFactor and Z != Math.floor(Z)
break
FractionNumerator = DecimalSign * FractionNumerator
ret[0] = FractionNumerator
ret[1] = FractionDenominator
ret
approx_just_an_integer = 0
approx_sine_of_rational = 1
approx_sine_of_pi_times_rational = 2
approx_rationalOfPi = 3
approx_radicalOfRatio = 4
approx_nothingUseful = 5
approx_ratioOfRadical = 6
approx_rationalOfE = 7
approx_logarithmsOfRationals = 8
approx_rationalsOfLogarithms = 9
approxRationalsOfRadicals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# simple radicals.
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
for i in [2,3,5,6,7,8,10]
for j in [1..10]
#console.log "i,j: " + i + "," + j
hypothesis = Math.sqrt(i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * sqrt( " + i + " ) / " + j
#console.log result + " error: " + error
bestResultSoFar = [result, approx_ratioOfRadical, likelyMultiplier, i, j]
return bestResultSoFar
approxRadicalsOfRationals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# simple radicals.
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# this one catches things like Math.sqrt(3/4), but
# things like Math.sqrt(1/2) are caught by the paragraph
# above (and in a better form)
for i in [1,2,3,5,6,7,8,10]
for j in [1,2,3,5,6,7,8,10]
#console.log "i,j: " + i + "," + j
hypothesis = Math.sqrt(i/j)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * (sqrt( " + i + " / " + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_radicalOfRatio, likelyMultiplier, i, j]
return bestResultSoFar
approxRadicals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# simple radicals.
# we always prefer a rational of a radical of an integer
# to a radical of a rational. Radicals of rationals generate
# radicals at the denominator which we'd rather avoid
approxRationalsOfRadicalsResult = approxRationalsOfRadicals theFloat
if approxRationalsOfRadicalsResult?
return approxRationalsOfRadicalsResult
approxRadicalsOfRationalsResult = approxRadicalsOfRationals theFloat
if approxRadicalsOfRationalsResult?
return approxRadicalsOfRationalsResult
return null
approxLogs = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# we always prefer a rational of a log to a log of
# a rational
approxRationalsOfLogsResult = approxRationalsOfLogs theFloat
if approxRationalsOfLogsResult?
return approxRationalsOfLogsResult
approxLogsOfRationalsResult = approxLogsOfRationals theFloat
if approxLogsOfRationalsResult?
return approxLogsOfRationalsResult
return null
approxRationalsOfLogs = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# simple rationals of logs
for i in [2..5]
for j in [1..5]
#console.log "i,j: " + i + "," + j
hypothesis = Math.log(i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
# it does happen that due to roundings
# a "higher multiple" is picked, which is obviously
# unintended.
# E.g. 1 * log(1 / 3 ) doesn't match log( 3 ) BUT
# it matches -5 * log( 3 ) / 5
# so we avoid any case where the multiplier is a multiple
# of the divisor.
if likelyMultiplier != 1 and Math.abs(Math.floor(likelyMultiplier/j)) == Math.abs(likelyMultiplier/j)
continue
if error < 2.2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * log( " + i + " ) / " + j
#console.log result + " error: " + error
bestResultSoFar = [result, approx_rationalsOfLogarithms, likelyMultiplier, i, j]
return bestResultSoFar
approxLogsOfRationals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# simple logs of rationals
for i in [1..5]
for j in [1..5]
#console.log "i,j: " + i + "," + j
hypothesis = Math.log(i/j)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 1.96 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * log( " + i + " / " + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_logarithmsOfRationals, likelyMultiplier, i, j]
return bestResultSoFar
approxRationalsOfPowersOfE = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# simple rationals of a few powers of e
for i in [1..2]
for j in [1..12]
#console.log "i,j: " + i + "," + j
hypothesis = Math.pow(Math.E,i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * (e ^ " + i + " ) / " + j
#console.log result + " error: " + error
bestResultSoFar = [result, approx_rationalOfE, likelyMultiplier, i, j]
return bestResultSoFar
approxRationalsOfPowersOfPI = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
# here we do somethng a little special: since
# the powers of pi can get quite big, there might
# be multiple hypothesis where more of the
# magnitude is shifted to the multiplier, and some
# where more of the magnitude is shifted towards the
# exponent of pi. So we prefer the hypotheses with the
# lower multiplier since it's likely to insert more
# information.
minimumComplexity = Number.MAX_VALUE
# simple rationals of a few powers of PI
for i in [1..5]
for j in [1..12]
#console.log "i,j: " + i + "," + j
hypothesis = Math.pow(Math.PI,i)/j
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * (pi ^ " + i + " ) / " + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_rationalOfPi, likelyMultiplier, i, j]
#console.log "approxRationalsOfPowersOfPI returning: " + bestResultSoFar
return bestResultSoFar
approxTrigonometric = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
# we always prefer a sin of a rational without the PI
approxSineOfRationalsResult = approxSineOfRationals theFloat
if approxSineOfRationalsResult?
return approxSineOfRationalsResult
approxSineOfRationalMultiplesOfPIResult = approxSineOfRationalMultiplesOfPI theFloat
if approxSineOfRationalMultiplesOfPIResult?
return approxSineOfRationalMultiplesOfPIResult
return null
approxSineOfRationals = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# we only check very simple rationals because they begin to get tricky
# quickly, also they collide often with the "rational of pi" hypothesis.
# For example sin(11) is veeery close to 1 (-0.99999020655)
# (see: http://mathworld.wolfram.com/AlmostInteger.html )
# we stop at rationals that mention up to 10
for i in [1..4]
for j in [1..4]
#console.log "i,j: " + i + "," + j
fraction = i/j
hypothesis = Math.sin(fraction)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
if error < 2 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * sin( " + i + "/" + j + " )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_sine_of_rational, likelyMultiplier, i, j]
return bestResultSoFar
approxSineOfRationalMultiplesOfPI = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
bestResultSoFar = null
minimumComplexity = Number.MAX_VALUE
# check rational multiples of pi
for i in [1..13]
for j in [1..13]
#console.log "i,j: " + i + "," + j
fraction = i/j
hypothesis = Math.sin(Math.PI * fraction)
#console.log "hypothesis: " + hypothesis
if Math.abs(hypothesis) > 1e-10
ratio = theFloat/hypothesis
likelyMultiplier = Math.round(ratio)
#console.log "ratio: " + ratio
error = Math.abs(1 - ratio/likelyMultiplier)
else
ratio = 1
likelyMultiplier = 1
error = Math.abs(theFloat - hypothesis)
#console.log "error: " + error
# magic number 23 comes from the case sin(pi/10)
if error < 23 * precision
complexity = simpleComplexityMeasure likelyMultiplier, i, j
if complexity < minimumComplexity
#console.log "MINIMUM MULTIPLIER SO FAR"
minimumComplexity = complexity
result = likelyMultiplier + " * sin( " + i + "/" + j + " * pi )"
#console.log result + " error: " + error
bestResultSoFar = [result, approx_sine_of_pi_times_rational, likelyMultiplier, i, j]
return bestResultSoFar
approxAll = (theFloat) ->
splitBeforeAndAfterDot = theFloat.toString().split(".")
if splitBeforeAndAfterDot.length == 2
numberOfDigitsAfterTheDot = splitBeforeAndAfterDot[1].length
precision = 1/Math.pow(10,numberOfDigitsAfterTheDot)
else
return ["" + Math.floor(theFloat), approx_just_an_integer, Math.floor(theFloat), 1, 2]
console.log "precision: " + precision
constantsSumMin = Number.MAX_VALUE
constantsSum = 0
bestApproxSoFar = null
LOG_EXPLANATIONS = true
approxRadicalsResult = approxRadicals theFloat
if approxRadicalsResult?
constantsSum = simpleComplexityMeasure approxRadicalsResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxRadicals: " + approxRadicalsResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxRadicalsResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxRadicals: " + approxRadicalsResult + " complexity: " + constantsSum
approxLogsResult = approxLogs(theFloat)
if approxLogsResult?
constantsSum = simpleComplexityMeasure approxLogsResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxLogs: " + approxLogsResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxLogsResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxLogs: " + approxLogsResult + " complexity: " + constantsSum
approxRationalsOfPowersOfEResult = approxRationalsOfPowersOfE(theFloat)
if approxRationalsOfPowersOfEResult?
constantsSum = simpleComplexityMeasure approxRationalsOfPowersOfEResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxRationalsOfPowersOfE: " + approxRationalsOfPowersOfEResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxRationalsOfPowersOfEResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxRationalsOfPowersOfE: " + approxRationalsOfPowersOfEResult + " complexity: " + constantsSum
approxRationalsOfPowersOfPIResult = approxRationalsOfPowersOfPI(theFloat)
if approxRationalsOfPowersOfPIResult?
constantsSum = simpleComplexityMeasure approxRationalsOfPowersOfPIResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxRationalsOfPowersOfPI: " + approxRationalsOfPowersOfPIResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxRationalsOfPowersOfPIResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxRationalsOfPowersOfPI: " + approxRationalsOfPowersOfPIResult + " complexity: " + constantsSum
approxTrigonometricResult = approxTrigonometric(theFloat)
if approxTrigonometricResult?
constantsSum = simpleComplexityMeasure approxTrigonometricResult
if constantsSum < constantsSumMin
if LOG_EXPLANATIONS then console.log "better explanation by approxTrigonometric: " + approxTrigonometricResult + " complexity: " + constantsSum
constantsSumMin = constantsSum
bestApproxSoFar = approxTrigonometricResult
else
if LOG_EXPLANATIONS then console.log "subpar explanation by approxTrigonometric: " + approxTrigonometricResult + " complexity: " + constantsSum
return bestApproxSoFar
simpleComplexityMeasure = (aResult, b, c) ->
theSum = null
if aResult instanceof Array
# we want PI and E to somewhat increase the
# complexity of the expression, so basically they count
# more than any integer lower than 3, i.e. we consider
# 1,2,3 to be more fundamental than PI or E.
switch aResult[1]
when approx_sine_of_pi_times_rational
theSum = 4
# exponents of PI and E need to be penalised as well
# otherwise they come to explain any big number
# so we count them just as much as the multiplier
when approx_rationalOfPi
theSum = Math.pow(4,Math.abs(aResult[3])) * Math.abs(aResult[2])
when approx_rationalOfE
theSum = Math.pow(3,Math.abs(aResult[3])) * Math.abs(aResult[2])
else theSum = 0
theSum += Math.abs(aResult[2]) * (Math.abs(aResult[3]) + Math.abs(aResult[4]))
else
theSum += Math.abs(aResult) * (Math.abs(b) + Math.abs(c))
# heavily discount unit constants
if aResult[2] == 1
theSum -= 1
else
theSum += 1
if aResult[3] == 1
theSum -= 1
else
theSum += 1
if aResult[4] == 1
theSum -= 1
else
theSum += 1
if theSum < 0
theSum = 0
return theSum
testApprox = () ->
for i in [2,3,5,6,7,8,10]
for j in [2,3,5,6,7,8,10]
if i == j then continue # this is just 1
console.log "testapproxRadicals testing: " + "1 * sqrt( " + i + " ) / " + j
fraction = i/j
value = Math.sqrt(i)/j
returned = approxRadicals(value)
returnedValue = returned[2] * Math.sqrt(returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testapproxRadicals: " + "1 * sqrt( " + i + " ) / " + j + " . obtained: " + returned
for i in [2,3,5,6,7,8,10]
for j in [2,3,5,6,7,8,10]
if i == j then continue # this is just 1
console.log "testapproxRadicals testing with 4 digits: " + "1 * sqrt( " + i + " ) / " + j
fraction = i/j
originalValue = Math.sqrt(i)/j
value = originalValue.toFixed(4)
returned = approxRadicals(value)
returnedValue = returned[2] * Math.sqrt(returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testapproxRadicals with 4 digits: " + "1 * sqrt( " + i + " ) / " + j + " . obtained: " + returned
for i in [2,3,5,6,7,8,10]
for j in [2,3,5,6,7,8,10]
if i == j then continue # this is just 1
console.log "testapproxRadicals testing: " + "1 * sqrt( " + i + " / " + j + " )"
fraction = i/j
value = Math.sqrt(i/j)
returned = approxRadicals(value)
if returned?
returnedValue = returned[2] * Math.sqrt(returned[3]/returned[4])
if returned[1] == approx_radicalOfRatio and Math.abs(value - returnedValue) > 1e-15
console.log "fail testapproxRadicals: " + "1 * sqrt( " + i + " / " + j + " ) . obtained: " + returned
for i in [1,2,3,5,6,7,8,10]
for j in [1,2,3,5,6,7,8,10]
if i == 1 and j == 1 then continue
console.log "testapproxRadicals testing with 4 digits:: " + "1 * sqrt( " + i + " / " + j + " )"
fraction = i/j
originalValue = Math.sqrt(i/j)
value = originalValue.toFixed(4)
returned = approxRadicals(value)
returnedValue = returned[2] * Math.sqrt(returned[3]/returned[4])
if returned[1] == approx_radicalOfRatio and Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testapproxRadicals with 4 digits:: " + "1 * sqrt( " + i + " / " + j + " ) . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing: " + "1 * log(" + i + " ) / " + j
fraction = i/j
value = Math.log(i)/j
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * log(" + i + " ) / " + j + " . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing with 4 digits: " + "1 * log(" + i + " ) / " + j
fraction = i/j
originalValue = Math.log(i)/j
value = originalValue.toFixed(4)
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testApproxAll with 4 digits: " + "1 * log(" + i + " ) / " + j + " . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing: " + "1 * log(" + i + " / " + j + " )"
fraction = i/j
value = Math.log(i/j)
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3]/returned[4])
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * log(" + i + " / " + j + " )" + " . obtained: " + returned
for i in [1..5]
for j in [1..5]
console.log "testApproxAll testing with 4 digits: " + "1 * log(" + i + " / " + j + " )"
fraction = i/j
originalValue = Math.log(i/j)
value = originalValue.toFixed(4)
returned = approxAll(value)
returnedValue = returned[2] * Math.log(returned[3]/returned[4])
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail testApproxAll with 4 digits: " + "1 * log(" + i + " / " + j + " )" + " . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "testApproxAll testing: " + "1 * (e ^ " + i + " ) / " + j
fraction = i/j
value = Math.pow(Math.E,i)/j
returned = approxAll(value)
returnedValue = returned[2] * Math.pow(Math.E,returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * (e ^ " + i + " ) / " + j + " . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "approxRationalsOfPowersOfE testing with 4 digits: " + "1 * (e ^ " + i + " ) / " + j
fraction = i/j
originalValue = Math.pow(Math.E,i)/j
value = originalValue.toFixed(4)
returned = approxRationalsOfPowersOfE(value)
returnedValue = returned[2] * Math.pow(Math.E,returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail approxRationalsOfPowersOfE with 4 digits: " + "1 * (e ^ " + i + " ) / " + j + " . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "testApproxAll testing: " + "1 * pi ^ " + i + " / " + j
fraction = i/j
value = Math.pow(Math.PI,i)/j
returned = approxAll(value)
returnedValue = returned[2] * Math.pow(Math.PI,returned[3])/returned[4]
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * pi ^ " + i + " / " + j + " ) . obtained: " + returned
for i in [1..2]
for j in [1..12]
console.log "approxRationalsOfPowersOfPI testing with 4 digits: " + "1 * pi ^ " + i + " / " + j
fraction = i/j
originalValue = Math.pow(Math.PI,i)/j
value = originalValue.toFixed(4)
returned = approxRationalsOfPowersOfPI(value)
returnedValue = returned[2] * Math.pow(Math.PI,returned[3])/returned[4]
if Math.abs(originalValue - returnedValue) > 1e-15
console.log "fail approxRationalsOfPowersOfPI with 4 digits: " + "1 * pi ^ " + i + " / " + j + " ) . obtained: " + returned
for i in [1..4]
for j in [1..4]
console.log "testApproxAll testing: " + "1 * sin( " + i + "/" + j + " )"
fraction = i/j
value = Math.sin(fraction)
returned = approxAll(value)
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(returnedFraction)
if Math.abs(value - returnedValue) > 1e-15
console.log "fail testApproxAll: " + "1 * sin( " + i + "/" + j + " ) . obtained: " + returned
# 5 digits create no problem
for i in [1..4]
for j in [1..4]
console.log "testApproxAll testing with 5 digits: " + "1 * sin( " + i + "/" + j + " )"
fraction = i/j
originalValue = Math.sin(fraction)
value = originalValue.toFixed(5)
returned = approxAll(value)
if !returned?
console.log "fail testApproxAll with 5 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: undefined "
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(returnedFraction)
error = Math.abs(originalValue - returnedValue)
if error > 1e-14
console.log "fail testApproxAll with 5 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: " + returned + " error: " + error
# 4 digits create two collisions
for i in [1..4]
for j in [1..4]
console.log "testApproxAll testing with 4 digits: " + "1 * sin( " + i + "/" + j + " )"
fraction = i/j
originalValue = Math.sin(fraction)
value = originalValue.toFixed(4)
returned = approxAll(value)
if !returned?
console.log "fail testApproxAll with 4 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: undefined "
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(returnedFraction)
error = Math.abs(originalValue - returnedValue)
if error > 1e-14
console.log "fail testApproxAll with 4 digits: " + "1 * sin( " + i + "/" + j + " ) . obtained: " + returned + " error: " + error
value = 0
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0"
value = 0.0
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.0"
value = 0.00
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.00"
value = 0.000
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.000"
value = 0.0000
if approxAll(value)[0] != "0" then console.log "fail testApproxAll: 0.0000"
value = 1
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1"
value = 1.0
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.0"
value = 1.00
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.00"
value = 1.000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.000"
value = 1.0000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.0000"
value = 1.00000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.00000"
value = Math.sqrt(2)
if approxAll(value)[0] != "1 * sqrt( 2 ) / 1" then console.log "fail testApproxAll: Math.sqrt(2)"
value = 1.41
if approxAll(value)[0] != "1 * sqrt( 2 ) / 1" then console.log "fail testApproxAll: 1.41"
# if we narrow down to a particular family then we can get
# an OK guess even with few digits, expecially for really "famous" numbers
value = 1.4
if approxRadicals(value)[0] != "1 * sqrt( 2 ) / 1" then console.log "fail approxRadicals: 1.4"
value = 0.6
if approxLogs(value)[0] != "1 * log( 2 ) / 1" then console.log "fail approxLogs: 0.6"
value = 0.69
if approxLogs(value)[0] != "1 * log( 2 ) / 1" then console.log "fail approxLogs: 0.69"
value = 0.7
if approxLogs(value)[0] != "1 * log( 2 ) / 1" then console.log "fail approxLogs: 0.7"
value = 1.09
if approxLogs(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxLogs: 1.09"
value = 1.09
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.09"
value = 1.098
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.098"
value = 1.1
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.1"
value = 1.11
if approxAll(value)[0] != "1 * log( 3 ) / 1" then console.log "fail approxAll: 1.11"
value = Math.sqrt(3)
if approxAll(value)[0] != "1 * sqrt( 3 ) / 1" then console.log "fail testApproxAll: Math.sqrt(3)"
value = 1.0000
if approxAll(value)[0] != "1" then console.log "fail testApproxAll: 1.0000"
value = 3.141592
if approxAll(value)[0] != "1 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 3.141592"
value = 31.41592
if approxAll(value)[0] != "10 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 31.41592"
value = 314.1592
if approxAll(value)[0] != "100 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 314.1592"
value = 31415926.53589793
if approxAll(value)[0] != "10000000 * (pi ^ 1 ) / 1 )" then console.log "fail testApproxAll: 31415926.53589793"
value = Math.sqrt(2)
if approxTrigonometric(value)[0] != "2 * sin( 1/4 * pi )" then console.log "fail approxTrigonometric: Math.sqrt(2)"
value = Math.sqrt(3)
if approxTrigonometric(value)[0] != "2 * sin( 1/3 * pi )" then console.log "fail approxTrigonometric: Math.sqrt(3)"
value = (Math.sqrt(6) - Math.sqrt(2))/4
if approxAll(value)[0] != "1 * sin( 1/12 * pi )" then console.log "fail testApproxAll: (Math.sqrt(6) - Math.sqrt(2))/4"
value = Math.sqrt(2 - Math.sqrt(2))/2
if approxAll(value)[0] != "1 * sin( 1/8 * pi )" then console.log "fail testApproxAll: Math.sqrt(2 - Math.sqrt(2))/2"
value = (Math.sqrt(6) + Math.sqrt(2))/4
if approxAll(value)[0] != "1 * sin( 5/12 * pi )" then console.log "fail testApproxAll: (Math.sqrt(6) + Math.sqrt(2))/4"
value = Math.sqrt(2 + Math.sqrt(3))/2
if approxAll(value)[0] != "1 * sin( 5/12 * pi )" then console.log "fail testApproxAll: Math.sqrt(2 + Math.sqrt(3))/2"
value = (Math.sqrt(5) - 1)/4
if approxAll(value)[0] != "1 * sin( 1/10 * pi )" then console.log "fail testApproxAll: (Math.sqrt(5) - 1)/4"
value = Math.sqrt(10 - 2*Math.sqrt(5))/4
if approxAll(value)[0] != "1 * sin( 1/5 * pi )" then console.log "fail testApproxAll: Math.sqrt(10 - 2*Math.sqrt(5))/4"
# this has a radical form but it's too long to write
value = Math.sin(Math.PI/7)
if approxAll(value)[0] != "1 * sin( 1/7 * pi )" then console.log "fail testApproxAll: Math.sin(Math.PI/7)"
# this has a radical form but it's too long to write
value = Math.sin(Math.PI/9)
if approxAll(value)[0] != "1 * sin( 1/9 * pi )" then console.log "fail testApproxAll: Math.sin(Math.PI/9)"
value = 1836.15267
if approxRationalsOfPowersOfPI(value)[0] != "6 * (pi ^ 5 ) / 1 )" then console.log "fail approxRationalsOfPowersOfPI: 1836.15267"
for i in [1..13]
for j in [1..13]
console.log "approxTrigonometric testing: " + "1 * sin( " + i + "/" + j + " * pi )"
fraction = i/j
value = Math.sin(Math.PI * fraction)
# we specifically search for sines of rational multiples of PI
# because too many of them would be picked up as simple
# rationals.
returned = approxTrigonometric(value)
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(Math.PI * returnedFraction)
if Math.abs(value - returnedValue) > 1e-15
console.log "fail approxTrigonometric: " + "1 * sin( " + i + "/" + j + " * pi ) . obtained: " + returned
for i in [1..13]
for j in [1..13]
# with four digits, there are two collisions with the
# "simple fraction" argument hypotesis, which we prefer since
# it's a simpler expression, so let's skip those
# two tests
if i == 5 and j == 11 or
i == 6 and j == 11
continue
console.log "approxTrigonometric testing with 4 digits: " + "1 * sin( " + i + "/" + j + " * pi )"
fraction = i/j
originalValue = Math.sin(Math.PI * fraction)
value = originalValue.toFixed(4)
# we specifically search for sines of rational multiples of PI
# because too many of them would be picked up as simple
# rationals.
returned = approxTrigonometric(value)
returnedFraction = returned[3]/returned[4]
returnedValue = returned[2] * Math.sin(Math.PI * returnedFraction)
error = Math.abs(originalValue - returnedValue)
if error > 1e-14
console.log "fail approxTrigonometric with 4 digits: " + "1 * sin( " + i + "/" + j + " * pi ) . obtained: " + returned + " error: " + error
console.log "testApprox done"
$.approxRadicals = approxRadicals
$.approxRationalsOfLogs = approxRationalsOfLogs
$.approxAll = approxAll
$.testApprox = testApprox
|
[
{
"context": "\n {tokens} = grammar.tokenizeLine '\"15 April\",\"Muniz, Alvin \"\"Hank\"\"\",\"A\"'\n expect(tokens).toHaveLength 15",
"end": 2408,
"score": 0.9997195601463318,
"start": 2396,
"tag": "NAME",
"value": "Muniz, Alvin"
},
{
"context": " grammar.tokenizeLine '\"15 Ap... | spec/language-csv-spec.coffee | ldez/atom-language-csv | 0 | describe 'CSV file grammars should tokenize when', ->
grammar = null
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage 'language-csv'
runs ->
grammar = atom.grammars.grammarForScopeName 'text.csv'
it 'contains unquoted cells', ->
{tokens} = grammar.tokenizeLine 'Date,Pupil,Grade'
expect(tokens).toHaveLength 5
i = 0
expect(tokens[i++]).toEqualJson value: 'Date', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: 'Pupil', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: 'Grade', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 5
it 'contains double-quoted cells', ->
{tokens} = grammar.tokenizeLine '"Date","Pupil","Grade"'
expect(tokens).toHaveLength 12
i = 0
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Date', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Pupil', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Grade', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: '', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 12
it 'contains double-quoted cells and escaped double-quote', ->
{tokens} = grammar.tokenizeLine '"15 April","Muniz, Alvin ""Hank""","A"'
expect(tokens).toHaveLength 15
i = 0
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: '15 April', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Muniz, Alvin ', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '""', scopes: ['text.csv', 'string.cell.csv', 'constant.character.escape.csv']
expect(tokens[i++]).toEqualJson value: 'Hank', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '""', scopes: ['text.csv', 'string.cell.csv', 'constant.character.escape.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'A', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: '', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 15
it 'contains numeric cells', ->
{tokens} = grammar.tokenizeLine '42,foobar,6'
expect(tokens).toHaveLength 6
i = 0
expect(tokens[i++]).toEqualJson value: '42', scopes: ['text.csv', 'constant.numeric.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: 'foobar', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '6', scopes: ['text.csv', 'constant.numeric.cell.csv']
expect(tokens[i++]).toEqualJson value: '', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 6
| 28155 | describe 'CSV file grammars should tokenize when', ->
grammar = null
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage 'language-csv'
runs ->
grammar = atom.grammars.grammarForScopeName 'text.csv'
it 'contains unquoted cells', ->
{tokens} = grammar.tokenizeLine 'Date,Pupil,Grade'
expect(tokens).toHaveLength 5
i = 0
expect(tokens[i++]).toEqualJson value: 'Date', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: 'Pupil', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: 'Grade', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 5
it 'contains double-quoted cells', ->
{tokens} = grammar.tokenizeLine '"Date","Pupil","Grade"'
expect(tokens).toHaveLength 12
i = 0
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Date', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Pupil', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Grade', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: '', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 12
it 'contains double-quoted cells and escaped double-quote', ->
{tokens} = grammar.tokenizeLine '"15 April","<NAME> ""<NAME>""","A"'
expect(tokens).toHaveLength 15
i = 0
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: '15 April', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: '<NAME> ', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '""', scopes: ['text.csv', 'string.cell.csv', 'constant.character.escape.csv']
expect(tokens[i++]).toEqualJson value: 'H<NAME>', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '""', scopes: ['text.csv', 'string.cell.csv', 'constant.character.escape.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'A', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: '', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 15
it 'contains numeric cells', ->
{tokens} = grammar.tokenizeLine '42,foobar,6'
expect(tokens).toHaveLength 6
i = 0
expect(tokens[i++]).toEqualJson value: '42', scopes: ['text.csv', 'constant.numeric.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: 'foobar', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '6', scopes: ['text.csv', 'constant.numeric.cell.csv']
expect(tokens[i++]).toEqualJson value: '', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 6
| true | describe 'CSV file grammars should tokenize when', ->
grammar = null
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage 'language-csv'
runs ->
grammar = atom.grammars.grammarForScopeName 'text.csv'
it 'contains unquoted cells', ->
{tokens} = grammar.tokenizeLine 'Date,Pupil,Grade'
expect(tokens).toHaveLength 5
i = 0
expect(tokens[i++]).toEqualJson value: 'Date', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: 'Pupil', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: 'Grade', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 5
it 'contains double-quoted cells', ->
{tokens} = grammar.tokenizeLine '"Date","Pupil","Grade"'
expect(tokens).toHaveLength 12
i = 0
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Date', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Pupil', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'Grade', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: '', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 12
it 'contains double-quoted cells and escaped double-quote', ->
{tokens} = grammar.tokenizeLine '"15 April","PI:NAME:<NAME>END_PI ""PI:NAME:<NAME>END_PI""","A"'
expect(tokens).toHaveLength 15
i = 0
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: '15 April', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'PI:NAME:<NAME>END_PI ', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '""', scopes: ['text.csv', 'string.cell.csv', 'constant.character.escape.csv']
expect(tokens[i++]).toEqualJson value: 'HPI:NAME:<NAME>END_PI', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '""', scopes: ['text.csv', 'string.cell.csv', 'constant.character.escape.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.begin.csv']
expect(tokens[i++]).toEqualJson value: 'A', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: '"', scopes: ['text.csv', 'string.cell.csv', 'variable.ending.csv']
expect(tokens[i++]).toEqualJson value: '', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 15
it 'contains numeric cells', ->
{tokens} = grammar.tokenizeLine '42,foobar,6'
expect(tokens).toHaveLength 6
i = 0
expect(tokens[i++]).toEqualJson value: '42', scopes: ['text.csv', 'constant.numeric.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: 'foobar', scopes: ['text.csv', 'string.cell.csv']
expect(tokens[i++]).toEqualJson value: ',', scopes: ['text.csv', 'constant.character.separator.csv']
expect(tokens[i++]).toEqualJson value: '6', scopes: ['text.csv', 'constant.numeric.cell.csv']
expect(tokens[i++]).toEqualJson value: '', scopes: ['text.csv', 'string.cell.csv']
expect(i).toBe 6
|
[
{
"context": "angular.one(\"settings\")\n\tself.settings =\n\t\tname: \"Anon\"\n\tself.getSettings = ->\n\t\tokGet = (res) ->\n\t\t\tsel",
"end": 124,
"score": 0.9975218772888184,
"start": 120,
"tag": "NAME",
"value": "Anon"
}
] | src/app/common/services/SettingsService.coffee | leftiness/ton-social | 0 | SettingsService = ($mdToast, Restangular) ->
self = this
rest = Restangular.one("settings")
self.settings =
name: "Anon"
self.getSettings = ->
okGet = (res) ->
self.settings = res.data
koGet = (res) ->
toast = $mdToast.simple()
.content "Failed to get settings. Reason: #{res.data.reason}"
.position "top right"
$mdToast.show toast
rest.get().then okGet, koGet
self.postSettings = (json) ->
okPost = (res) ->
for own key, value of json
self.settings[key] = value
toast = $mdToast.simple()
.content "Settings saved."
.position "top right"
$mdToast.show toast
koPost = (res) ->
toast = $mdToast.simple()
.content "Failed to post settings. Reason: #{res.data.reason}"
.position "top right"
$mdToast.show toast
rest.customPOST(json).then okPost, koPost
self
SettingsService.$inject = ["$mdToast", "Restangular"];
module.exports = SettingsService;
| 19588 | SettingsService = ($mdToast, Restangular) ->
self = this
rest = Restangular.one("settings")
self.settings =
name: "<NAME>"
self.getSettings = ->
okGet = (res) ->
self.settings = res.data
koGet = (res) ->
toast = $mdToast.simple()
.content "Failed to get settings. Reason: #{res.data.reason}"
.position "top right"
$mdToast.show toast
rest.get().then okGet, koGet
self.postSettings = (json) ->
okPost = (res) ->
for own key, value of json
self.settings[key] = value
toast = $mdToast.simple()
.content "Settings saved."
.position "top right"
$mdToast.show toast
koPost = (res) ->
toast = $mdToast.simple()
.content "Failed to post settings. Reason: #{res.data.reason}"
.position "top right"
$mdToast.show toast
rest.customPOST(json).then okPost, koPost
self
SettingsService.$inject = ["$mdToast", "Restangular"];
module.exports = SettingsService;
| true | SettingsService = ($mdToast, Restangular) ->
self = this
rest = Restangular.one("settings")
self.settings =
name: "PI:NAME:<NAME>END_PI"
self.getSettings = ->
okGet = (res) ->
self.settings = res.data
koGet = (res) ->
toast = $mdToast.simple()
.content "Failed to get settings. Reason: #{res.data.reason}"
.position "top right"
$mdToast.show toast
rest.get().then okGet, koGet
self.postSettings = (json) ->
okPost = (res) ->
for own key, value of json
self.settings[key] = value
toast = $mdToast.simple()
.content "Settings saved."
.position "top right"
$mdToast.show toast
koPost = (res) ->
toast = $mdToast.simple()
.content "Failed to post settings. Reason: #{res.data.reason}"
.position "top right"
$mdToast.show toast
rest.customPOST(json).then okPost, koPost
self
SettingsService.$inject = ["$mdToast", "Restangular"];
module.exports = SettingsService;
|
[
{
"context": "# @author alteredq / http://alteredqualia.com/\n# @author aladjev.and",
"end": 18,
"score": 0.8390713930130005,
"start": 10,
"tag": "USERNAME",
"value": "alteredq"
},
{
"context": "hor alteredq / http://alteredqualia.com/\n# @author aladjev.andrew@gmail.com\n\n#= requir... | source/javascripts/new_src/cameras/orthographic.coffee | andrew-aladev/three.js | 0 | # @author alteredq / http://alteredqualia.com/
# @author aladjev.andrew@gmail.com
#= require new_src/cameras/camera
class OrthographicCamera extends THREE.Camera
constructor: (left, right, top, bottom, near, far) ->
super()
@left = left
@right = right
@top = top
@bottom = bottom
@near = (if (near isnt undefined) then near else 0.1)
@far = (if (far isnt undefined) then far else 2000)
@updateProjectionMatrix()
updateProjectionMatrix: ->
@projectionMatrix.makeOrthographic @left, @right, @top, @bottom, @near, @far
namespace "THREE", (exports) ->
exports.OrthographicCamera = OrthographicCamera | 150421 | # @author alteredq / http://alteredqualia.com/
# @author <EMAIL>
#= require new_src/cameras/camera
class OrthographicCamera extends THREE.Camera
constructor: (left, right, top, bottom, near, far) ->
super()
@left = left
@right = right
@top = top
@bottom = bottom
@near = (if (near isnt undefined) then near else 0.1)
@far = (if (far isnt undefined) then far else 2000)
@updateProjectionMatrix()
updateProjectionMatrix: ->
@projectionMatrix.makeOrthographic @left, @right, @top, @bottom, @near, @far
namespace "THREE", (exports) ->
exports.OrthographicCamera = OrthographicCamera | true | # @author alteredq / http://alteredqualia.com/
# @author PI:EMAIL:<EMAIL>END_PI
#= require new_src/cameras/camera
class OrthographicCamera extends THREE.Camera
constructor: (left, right, top, bottom, near, far) ->
super()
@left = left
@right = right
@top = top
@bottom = bottom
@near = (if (near isnt undefined) then near else 0.1)
@far = (if (far isnt undefined) then far else 2000)
@updateProjectionMatrix()
updateProjectionMatrix: ->
@projectionMatrix.makeOrthographic @left, @right, @top, @bottom, @near, @far
namespace "THREE", (exports) ->
exports.OrthographicCamera = OrthographicCamera |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.