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": " @sut = new MeshbluXMPP uuid: 'uuid', token: 'token', hostname: 'localhost', port: 5222\n @sut.co", "end": 627, "score": 0.8627166748046875, "start": 622, "tag": "KEY", "value": "token" } ]
test/message-spec.coffee
octoblu/node-meshblu-xmpp
1
_ = require 'lodash' ltx = require 'ltx' xmpp = require 'node-xmpp-server' xml2js = require('xml2js').parseString MeshbluXMPP = require '../' describe 'Message', -> beforeEach (done) -> @server = new xmpp.C2S.TCPServer port: 5222 domain: 'localhost' @server.on 'connection', (@client) => @client.on 'authenticate', (opts, callback) => callback(null, opts) @server.on 'listening', done afterEach (done) -> @server.end done describe 'with an active connection', -> beforeEach (done) -> @sut = new MeshbluXMPP uuid: 'uuid', token: 'token', hostname: 'localhost', port: 5222 @sut.connect done afterEach 'close client', -> @sut.close() describe 'when message responds with a 204', -> beforeEach (done) -> @client.on 'stanza', (@request) => @client.send new xmpp.Stanza('iq', type: 'result' to: @request.attrs.from from: @request.attrs.to id: @request.attrs.id ).cnode(ltx.parse """ <response xmlns="meshblu-xmpp:job-manager:response"> <metadata> <code>204</code> </metadata> </response> """) @sut.message devices: ['uuid-2'], payload: 'hi', done it 'should send a stanza to the server', (done) -> expect(@request).to.exist options = {explicitArray: false, mergeAttrs: true} xml2js @request.toString(), options, (error, request) => return done error if error? expect(request).to.containSubset iq: type: 'set' request: metadata: jobType: 'SendMessage' rawData: '{"devices":["uuid-2"],"payload":"hi"}' done()
115761
_ = require 'lodash' ltx = require 'ltx' xmpp = require 'node-xmpp-server' xml2js = require('xml2js').parseString MeshbluXMPP = require '../' describe 'Message', -> beforeEach (done) -> @server = new xmpp.C2S.TCPServer port: 5222 domain: 'localhost' @server.on 'connection', (@client) => @client.on 'authenticate', (opts, callback) => callback(null, opts) @server.on 'listening', done afterEach (done) -> @server.end done describe 'with an active connection', -> beforeEach (done) -> @sut = new MeshbluXMPP uuid: 'uuid', token: '<KEY>', hostname: 'localhost', port: 5222 @sut.connect done afterEach 'close client', -> @sut.close() describe 'when message responds with a 204', -> beforeEach (done) -> @client.on 'stanza', (@request) => @client.send new xmpp.Stanza('iq', type: 'result' to: @request.attrs.from from: @request.attrs.to id: @request.attrs.id ).cnode(ltx.parse """ <response xmlns="meshblu-xmpp:job-manager:response"> <metadata> <code>204</code> </metadata> </response> """) @sut.message devices: ['uuid-2'], payload: 'hi', done it 'should send a stanza to the server', (done) -> expect(@request).to.exist options = {explicitArray: false, mergeAttrs: true} xml2js @request.toString(), options, (error, request) => return done error if error? expect(request).to.containSubset iq: type: 'set' request: metadata: jobType: 'SendMessage' rawData: '{"devices":["uuid-2"],"payload":"hi"}' done()
true
_ = require 'lodash' ltx = require 'ltx' xmpp = require 'node-xmpp-server' xml2js = require('xml2js').parseString MeshbluXMPP = require '../' describe 'Message', -> beforeEach (done) -> @server = new xmpp.C2S.TCPServer port: 5222 domain: 'localhost' @server.on 'connection', (@client) => @client.on 'authenticate', (opts, callback) => callback(null, opts) @server.on 'listening', done afterEach (done) -> @server.end done describe 'with an active connection', -> beforeEach (done) -> @sut = new MeshbluXMPP uuid: 'uuid', token: 'PI:KEY:<KEY>END_PI', hostname: 'localhost', port: 5222 @sut.connect done afterEach 'close client', -> @sut.close() describe 'when message responds with a 204', -> beforeEach (done) -> @client.on 'stanza', (@request) => @client.send new xmpp.Stanza('iq', type: 'result' to: @request.attrs.from from: @request.attrs.to id: @request.attrs.id ).cnode(ltx.parse """ <response xmlns="meshblu-xmpp:job-manager:response"> <metadata> <code>204</code> </metadata> </response> """) @sut.message devices: ['uuid-2'], payload: 'hi', done it 'should send a stanza to the server', (done) -> expect(@request).to.exist options = {explicitArray: false, mergeAttrs: true} xml2js @request.toString(), options, (error, request) => return done error if error? expect(request).to.containSubset iq: type: 'set' request: metadata: jobType: 'SendMessage' rawData: '{"devices":["uuid-2"],"payload":"hi"}' done()
[ { "context": "y-cache', backend: 'memcached'\n\nvalues =\n key1: 'Value 1'\n key2: 'Value 2'\n key3: 'Value 3'\n\ncache.set '", "end": 98, "score": 0.9608394503593445, "start": 91, "tag": "KEY", "value": "Value 1" }, { "context": " 'memcached'\n\nvalues =\n key1: 'Value 1'\n key...
examples/memcached.coffee
Kofia5/node-cached
0
cached = require '..' cache = cached 'my-cache', backend: 'memcached' values = key1: 'Value 1' key2: 'Value 2' key3: 'Value 3' cache.set 'key1', values.key1, -> console.log 'key1: Set callback style' cache.set('key2', values.key2, { expire: 1 }) .then -> console.log 'key2: Set promise style, expires after 1 second' cache.set('key3', values.key3, freshFor: 2) .then -> console.log 'key3: Fresh for 2 seconds' [ 100, 3000 ].map (timeout) -> tryGetFromCache = -> console.log "Trying to get values after #{timeout} msecs" [ 'key1', 'key2', 'key3' ].map (key) -> cache.get key, (err, data) -> console.log "get (callback):\t#{key}: #{data}" cache.get(key).then (data) -> console.log "get (promise):\t#{key}: #{data}" cache.getOrElse(key, "New value for #{key}").then (data) -> console.log "getOrElse:\t#{key}: #{data}" setTimeout(tryGetFromCache, timeout)
147972
cached = require '..' cache = cached 'my-cache', backend: 'memcached' values = key1: '<KEY>' key2: '<KEY>' key3: '<KEY>' cache.set 'key1', values.key1, -> console.log 'key1: Set callback style' cache.set('key2', values.key2, { expire: 1 }) .then -> console.log 'key2: Set promise style, expires after 1 second' cache.set('key3', values.key3, freshFor: 2) .then -> console.log 'key3: Fresh for 2 seconds' [ 100, 3000 ].map (timeout) -> tryGetFromCache = -> console.log "Trying to get values after #{timeout} msecs" [ 'key1', 'key2', 'key3' ].map (key) -> cache.get key, (err, data) -> console.log "get (callback):\t#{key}: #{data}" cache.get(key).then (data) -> console.log "get (promise):\t#{key}: #{data}" cache.getOrElse(key, "New value for #{key}").then (data) -> console.log "getOrElse:\t#{key}: #{data}" setTimeout(tryGetFromCache, timeout)
true
cached = require '..' cache = cached 'my-cache', backend: 'memcached' values = key1: 'PI:KEY:<KEY>END_PI' key2: 'PI:KEY:<KEY>END_PI' key3: 'PI:KEY:<KEY>END_PI' cache.set 'key1', values.key1, -> console.log 'key1: Set callback style' cache.set('key2', values.key2, { expire: 1 }) .then -> console.log 'key2: Set promise style, expires after 1 second' cache.set('key3', values.key3, freshFor: 2) .then -> console.log 'key3: Fresh for 2 seconds' [ 100, 3000 ].map (timeout) -> tryGetFromCache = -> console.log "Trying to get values after #{timeout} msecs" [ 'key1', 'key2', 'key3' ].map (key) -> cache.get key, (err, data) -> console.log "get (callback):\t#{key}: #{data}" cache.get(key).then (data) -> console.log "get (promise):\t#{key}: #{data}" cache.getOrElse(key, "New value for #{key}").then (data) -> console.log "getOrElse:\t#{key}: #{data}" setTimeout(tryGetFromCache, timeout)
[ { "context": "'''\r\nCreated: 2014-9-17\r\nAuthor: niR@github (https://github.com/hentaiPanda)\r\nVersion:", "end": 36, "score": 0.6758166551589966, "start": 33, "tag": "USERNAME", "value": "niR" }, { "context": "'''\r\nCreated: 2014-9-17\r\nAuthor: niR@github (https://github.com/hen...
levenshtein.coffee
hentaiPanda/Levenshtein
5
''' Created: 2014-9-17 Author: niR@github (https://github.com/hentaiPanda) Version: 0.0.1 License: MIT This is a straightforward implementation of Levenshitein Distance and Damerau-Levenshtein Distance. The code is based on the examples on the Wikipedia You can get more infomation from http://en.wikipedia.org/wiki/Levenshtein_distance http://en.wikipedia.org/wiki/Damerau-Levenshtein_distance ''' # Levenshtein Distance lev = (str1, str2) -> n1 = str1.length n2 = str2.length matrix = ( ( 0 for i in [0..n1] ) for j in [0..n2] ) for i in [1..n1] matrix[0][i] = i for j in [1..n2] matrix[j][0] = j for j in [1..n2] for i in [1..n1] cost = if str1[i-1] is str2[j-1] then 0 else 1 elem = Math.min( matrix[j-1][i] + 1, matrix[j][i-1] + 1, matrix[j-1][i-1] + cost) matrix[j][i] = elem return matrix[-1..][0][-1..][0] #array.slice(-1)[0] return last elem # Optimal string alignment distance osa = (str1, str2) -> n1 = str1.length n2 = str2.length matrix = ( ( 0 for i in [0..n1] ) for j in [0..n2] ) for i in [1..n1] matrix[0][i] = i for j in [1..n2] matrix[j][0] = j for j in [1..n2] for i in [1..n1] cost = if str1[i-1] is str2[j-1] then 0 else 1 elem = Math.min( matrix[j-1][i] + 1, matrix[j][i-1] + 1, matrix[j-1][i-1] + cost) if (i > 1 and j > 1 and str1[i-2] is str2[j-1] and str1[i-1] is str2[j-2]) elem = Math.min( elem, matrix[j-3][i-3] + cost ) matrix[j][i] = elem return matrix[-1..][0][-1..][0] #array.slice(-1)[0] return last elem # Damerau-Levenshtein Distance dalev = (str1, str2) -> n1 = str1.length n2 = str2.length max = n1 + n2 letters = {} matrix = ( ( max for i in [0..n1+1] ) for j in [0..n2+1] ) for i in [1..n1+1] matrix[1][i] = i - 1 for j in [1..n2+1] matrix[j][1] = j - 1 for j in [2..n2+1] temp = 1 for i in [2..n1+1] p2 = if letters[str1[i-2]] then letters[str1[i-2]] else 1 p1 = temp cost = if str1[i-2] is str2[j-2] then 0 else 1 if not cost temp = i elem = Math.min( matrix[j-1][i] + 1, matrix[j][i-1] + 1, matrix[j-1][i-1] + cost, matrix[p2-1][p1-1] + 1 + (i-p1-1) + (j-p2-1)) matrix[j][i] = elem letters[str2[j-2]] = j return matrix[-1..][0][-1..][0] module.exports.lev = lev module.exports.osa = osa module.exports.dalev = dalev if require.main is module str1='ca' str2='abc' console.log "str1 = 'ca', str2 = 'abc', D-L Distance is", dalev(str1, str2)
200476
''' Created: 2014-9-17 Author: niR<EMAIL> (https://github.com/hentaiPanda) Version: 0.0.1 License: MIT This is a straightforward implementation of Levenshitein Distance and Damerau-Levenshtein Distance. The code is based on the examples on the Wikipedia You can get more infomation from http://en.wikipedia.org/wiki/Levenshtein_distance http://en.wikipedia.org/wiki/Damerau-Levenshtein_distance ''' # Levenshtein Distance lev = (str1, str2) -> n1 = str1.length n2 = str2.length matrix = ( ( 0 for i in [0..n1] ) for j in [0..n2] ) for i in [1..n1] matrix[0][i] = i for j in [1..n2] matrix[j][0] = j for j in [1..n2] for i in [1..n1] cost = if str1[i-1] is str2[j-1] then 0 else 1 elem = Math.min( matrix[j-1][i] + 1, matrix[j][i-1] + 1, matrix[j-1][i-1] + cost) matrix[j][i] = elem return matrix[-1..][0][-1..][0] #array.slice(-1)[0] return last elem # Optimal string alignment distance osa = (str1, str2) -> n1 = str1.length n2 = str2.length matrix = ( ( 0 for i in [0..n1] ) for j in [0..n2] ) for i in [1..n1] matrix[0][i] = i for j in [1..n2] matrix[j][0] = j for j in [1..n2] for i in [1..n1] cost = if str1[i-1] is str2[j-1] then 0 else 1 elem = Math.min( matrix[j-1][i] + 1, matrix[j][i-1] + 1, matrix[j-1][i-1] + cost) if (i > 1 and j > 1 and str1[i-2] is str2[j-1] and str1[i-1] is str2[j-2]) elem = Math.min( elem, matrix[j-3][i-3] + cost ) matrix[j][i] = elem return matrix[-1..][0][-1..][0] #array.slice(-1)[0] return last elem # Damerau-Levenshtein Distance dalev = (str1, str2) -> n1 = str1.length n2 = str2.length max = n1 + n2 letters = {} matrix = ( ( max for i in [0..n1+1] ) for j in [0..n2+1] ) for i in [1..n1+1] matrix[1][i] = i - 1 for j in [1..n2+1] matrix[j][1] = j - 1 for j in [2..n2+1] temp = 1 for i in [2..n1+1] p2 = if letters[str1[i-2]] then letters[str1[i-2]] else 1 p1 = temp cost = if str1[i-2] is str2[j-2] then 0 else 1 if not cost temp = i elem = Math.min( matrix[j-1][i] + 1, matrix[j][i-1] + 1, matrix[j-1][i-1] + cost, matrix[p2-1][p1-1] + 1 + (i-p1-1) + (j-p2-1)) matrix[j][i] = elem letters[str2[j-2]] = j return matrix[-1..][0][-1..][0] module.exports.lev = lev module.exports.osa = osa module.exports.dalev = dalev if require.main is module str1='ca' str2='abc' console.log "str1 = 'ca', str2 = 'abc', D-L Distance is", dalev(str1, str2)
true
''' Created: 2014-9-17 Author: niRPI:EMAIL:<EMAIL>END_PI (https://github.com/hentaiPanda) Version: 0.0.1 License: MIT This is a straightforward implementation of Levenshitein Distance and Damerau-Levenshtein Distance. The code is based on the examples on the Wikipedia You can get more infomation from http://en.wikipedia.org/wiki/Levenshtein_distance http://en.wikipedia.org/wiki/Damerau-Levenshtein_distance ''' # Levenshtein Distance lev = (str1, str2) -> n1 = str1.length n2 = str2.length matrix = ( ( 0 for i in [0..n1] ) for j in [0..n2] ) for i in [1..n1] matrix[0][i] = i for j in [1..n2] matrix[j][0] = j for j in [1..n2] for i in [1..n1] cost = if str1[i-1] is str2[j-1] then 0 else 1 elem = Math.min( matrix[j-1][i] + 1, matrix[j][i-1] + 1, matrix[j-1][i-1] + cost) matrix[j][i] = elem return matrix[-1..][0][-1..][0] #array.slice(-1)[0] return last elem # Optimal string alignment distance osa = (str1, str2) -> n1 = str1.length n2 = str2.length matrix = ( ( 0 for i in [0..n1] ) for j in [0..n2] ) for i in [1..n1] matrix[0][i] = i for j in [1..n2] matrix[j][0] = j for j in [1..n2] for i in [1..n1] cost = if str1[i-1] is str2[j-1] then 0 else 1 elem = Math.min( matrix[j-1][i] + 1, matrix[j][i-1] + 1, matrix[j-1][i-1] + cost) if (i > 1 and j > 1 and str1[i-2] is str2[j-1] and str1[i-1] is str2[j-2]) elem = Math.min( elem, matrix[j-3][i-3] + cost ) matrix[j][i] = elem return matrix[-1..][0][-1..][0] #array.slice(-1)[0] return last elem # Damerau-Levenshtein Distance dalev = (str1, str2) -> n1 = str1.length n2 = str2.length max = n1 + n2 letters = {} matrix = ( ( max for i in [0..n1+1] ) for j in [0..n2+1] ) for i in [1..n1+1] matrix[1][i] = i - 1 for j in [1..n2+1] matrix[j][1] = j - 1 for j in [2..n2+1] temp = 1 for i in [2..n1+1] p2 = if letters[str1[i-2]] then letters[str1[i-2]] else 1 p1 = temp cost = if str1[i-2] is str2[j-2] then 0 else 1 if not cost temp = i elem = Math.min( matrix[j-1][i] + 1, matrix[j][i-1] + 1, matrix[j-1][i-1] + cost, matrix[p2-1][p1-1] + 1 + (i-p1-1) + (j-p2-1)) matrix[j][i] = elem letters[str2[j-2]] = j return matrix[-1..][0][-1..][0] module.exports.lev = lev module.exports.osa = osa module.exports.dalev = dalev if require.main is module str1='ca' str2='abc' console.log "str1 = 'ca', str2 = 'abc', D-L Distance is", dalev(str1, str2)
[ { "context": "ratch}/authorized_keys\"\n keys: [\n 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkExo0", "end": 450, "score": 0.8004706501960754, "start": 447, "tag": "KEY", "value": "rsa" }, { "context": "h}/authorized_keys\"\n keys: [\n 'ssh-rsa AAAAB...
packages/filetypes/test/ssh_authorized_keys.coffee
chibanemourad/node-nikita
1
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require './test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'file.types.ssh_authorized_keys', -> they 'overwrite file', ({ssh}) -> nikita ssh: ssh .file target: "#{scratch}/authorized_keys" content: "# Some Comment" .file.types.ssh_authorized_keys target: "#{scratch}/authorized_keys" keys: [ 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkExo09Vv6PJmJEjIwrD+MQTLUQrhM6dSCQ40KNJkLATsrm3p14QGzT2G5IiIUVfl/dwXUS5kqOKRYJUBl5o1ETzxWCUzWUcaY7JmrAlQwQgBMwtwv/ClpYqjiHwGcoMOuobumXfsyz7f3CuqvrldQEfcv/f0u7t/78nVceDE4mjlMGH/bwyzH09CYHPnLW9S/Jvhw5hbyCTDDqheCZHb+Y3xecRV+fGDfH7onn/FWu9JRj0UWkzGZoCp8Lj5hZ/mAF2fqH5tbW36DkC66zi3jJNI2cwARHxH1TQ8DeDKnUjaY7J03CbB+RIaKh5KjbEquqWlTQSP Some Description' ] , (err, {status}) -> status.should.be.true() unless err .file.assert target: "#{scratch}/authorized_keys" content: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkExo09Vv6PJmJEjIwrD+MQTLUQrhM6dSCQ40KNJkLATsrm3p14QGzT2G5IiIUVfl/dwXUS5kqOKRYJUBl5o1ETzxWCUzWUcaY7JmrAlQwQgBMwtwv/ClpYqjiHwGcoMOuobumXfsyz7f3CuqvrldQEfcv/f0u7t/78nVceDE4mjlMGH/bwyzH09CYHPnLW9S/Jvhw5hbyCTDDqheCZHb+Y3xecRV+fGDfH7onn/FWu9JRj0UWkzGZoCp8Lj5hZ/mAF2fqH5tbW36DkC66zi3jJNI2cwARHxH1TQ8DeDKnUjaY7J03CbB+RIaKh5KjbEquqWlTQSP Some Description\n" .promise() they 'merge file', ({ssh}) -> nikita ssh: ssh .file target: "#{scratch}/authorized_keys" content: "# Some Comment" .file.types.ssh_authorized_keys target: "#{scratch}/authorized_keys" keys: [ 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkExo09Vv6PJmJEjIwrD+MQTLUQrhM6dSCQ40KNJkLATsrm3p14QGzT2G5IiIUVfl/dwXUS5kqOKRYJUBl5o1ETzxWCUzWUcaY7JmrAlQwQgBMwtwv/ClpYqjiHwGcoMOuobumXfsyz7f3CuqvrldQEfcv/f0u7t/78nVceDE4mjlMGH/bwyzH09CYHPnLW9S/Jvhw5hbyCTDDqheCZHb+Y3xecRV+fGDfH7onn/FWu9JRj0UWkzGZoCp8Lj5hZ/mAF2fqH5tbW36DkC66zi3jJNI2cwARHxH1TQ8DeDKnUjaY7J03CbB+RIaKh5KjbEquqWlTQSP Some Description' ] merge: true , (err, {status}) -> status.should.be.true() unless err .file.assert target: "#{scratch}/authorized_keys" content: """ # Some Comment ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkExo09Vv6PJmJEjIwrD+MQTLUQrhM6dSCQ40KNJkLATsrm3p14QGzT2G5IiIUVfl/dwXUS5kqOKRYJUBl5o1ETzxWCUzWUcaY7JmrAlQwQgBMwtwv/ClpYqjiHwGcoMOuobumXfsyz7f3CuqvrldQEfcv/f0u7t/78nVceDE4mjlMGH/bwyzH09CYHPnLW9S/Jvhw5hbyCTDDqheCZHb+Y3xecRV+fGDfH7onn/FWu9JRj0UWkzGZoCp8Lj5hZ/mAF2fqH5tbW36DkC66zi3jJNI2cwARHxH1TQ8DeDKnUjaY7J03CbB+RIaKh5KjbEquqWlTQSP Some Description\n """ .promise()
21489
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require './test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'file.types.ssh_authorized_keys', -> they 'overwrite file', ({ssh}) -> nikita ssh: ssh .file target: "#{scratch}/authorized_keys" content: "# Some Comment" .file.types.ssh_authorized_keys target: "#{scratch}/authorized_keys" keys: [ 'ssh-<KEY> <KEY> Description' ] , (err, {status}) -> status.should.be.true() unless err .file.assert target: "#{scratch}/authorized_keys" content: "ssh-rsa <KEY> Some Description\n" .promise() they 'merge file', ({ssh}) -> nikita ssh: ssh .file target: "#{scratch}/authorized_keys" content: "# Some Comment" .file.types.ssh_authorized_keys target: "#{scratch}/authorized_keys" keys: [ 'ssh-rsa A<KEY>Kh<KEY>SP Some Description' ] merge: true , (err, {status}) -> status.should.be.true() unless err .file.assert target: "#{scratch}/authorized_keys" content: """ # Some Comment ssh-rsa <KEY>SP Some Description\n """ .promise()
true
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require './test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'file.types.ssh_authorized_keys', -> they 'overwrite file', ({ssh}) -> nikita ssh: ssh .file target: "#{scratch}/authorized_keys" content: "# Some Comment" .file.types.ssh_authorized_keys target: "#{scratch}/authorized_keys" keys: [ 'ssh-PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI Description' ] , (err, {status}) -> status.should.be.true() unless err .file.assert target: "#{scratch}/authorized_keys" content: "ssh-rsa PI:KEY:<KEY>END_PI Some Description\n" .promise() they 'merge file', ({ssh}) -> nikita ssh: ssh .file target: "#{scratch}/authorized_keys" content: "# Some Comment" .file.types.ssh_authorized_keys target: "#{scratch}/authorized_keys" keys: [ 'ssh-rsa API:KEY:<KEY>END_PIKhPI:KEY:<KEY>END_PISP Some Description' ] merge: true , (err, {status}) -> status.should.be.true() unless err .file.assert target: "#{scratch}/authorized_keys" content: """ # Some Comment ssh-rsa PI:KEY:<KEY>END_PISP Some Description\n """ .promise()
[ { "context": "lling: true\n \"exception-reporting\":\n userId: \"46ee98a6-e0de-4874-bc1e-dd381de91e7d\"\n fonts:\n fontFamily: \"FiraCode\"\n \"linter-ui", "end": 369, "score": 0.8738492131233215, "start": 333, "tag": "PASSWORD", "value": "46ee98a6-e0de-4874-bc1e-dd381de91e7d" } ]
.atom/config.cson
tetuya01465/dotfiles
0
"*": autosave: enabled: true core: closeDeletedFileTabs: true disabledPackages: [ "spell-check" ] telemetryConsent: "no" editor: fontSize: 19 preferredLineLength: 1000 showIndentGuide: true showInvisibles: true zoomFontWhenCtrlScrolling: true "exception-reporting": userId: "46ee98a6-e0de-4874-bc1e-dd381de91e7d" fonts: fontFamily: "FiraCode" "linter-ui-default": {} "terminal-plus": core: {} welcome: showOnStartup: false
105401
"*": autosave: enabled: true core: closeDeletedFileTabs: true disabledPackages: [ "spell-check" ] telemetryConsent: "no" editor: fontSize: 19 preferredLineLength: 1000 showIndentGuide: true showInvisibles: true zoomFontWhenCtrlScrolling: true "exception-reporting": userId: "<PASSWORD>" fonts: fontFamily: "FiraCode" "linter-ui-default": {} "terminal-plus": core: {} welcome: showOnStartup: false
true
"*": autosave: enabled: true core: closeDeletedFileTabs: true disabledPackages: [ "spell-check" ] telemetryConsent: "no" editor: fontSize: 19 preferredLineLength: 1000 showIndentGuide: true showInvisibles: true zoomFontWhenCtrlScrolling: true "exception-reporting": userId: "PI:PASSWORD:<PASSWORD>END_PI" fonts: fontFamily: "FiraCode" "linter-ui-default": {} "terminal-plus": core: {} welcome: showOnStartup: false
[ { "context": "ticate'\n .set 'Authorization', \"Basic #{@userAuth}\"\n .reply 200, uuid: 'user-uuid', to", "end": 1191, "score": 0.6107525825500488, "start": 1187, "tag": "USERNAME", "value": "user" }, { "context": "-id\"\n user:\n userId...
test/integration/list-spec.coffee
octoblu/alexa-service
3
{describe,beforeEach,afterEach,expect,it} = global request = require 'request' enableDestroy = require 'server-destroy' shmock = require 'shmock' uuid = require 'uuid' Server = require '../../src/server' describe 'List Triggers', -> beforeEach (done) -> @meshblu = shmock 0xd00d enableDestroy(@meshblu) meshbluConfig = server: 'localhost' port: 0xd00d protocol: 'http' keepAlive: false serverOptions = port: undefined, disableLogging: true meshbluConfig: meshbluConfig alexaServiceUri: 'https://alexa.octoblu.dev' namespace: 'alexa-service:test' disableAlexaVerification: true @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() afterEach -> @meshblu.destroy() @server.destroy() describe 'POST /trigger', -> describe 'when successful', -> beforeEach -> sessionId = uuid.v1() requestId = uuid.v1() @userAuth = new Buffer('user-uuid:user-token').toString('base64') @whoami = @meshblu .post '/authenticate' .set 'Authorization', "Basic #{@userAuth}" .reply 200, uuid: 'user-uuid', token: 'user-token' @options = uri: '/trigger' baseUrl: "http://localhost:#{@serverPort}" json: session: sessionId: sessionId, application: applicationId: "application-id" user: userId: "user-id", accessToken: @userAuth new: true request: type: "IntentRequest", requestId: requestId, timestamp: "2016-02-12T19:28:15Z", intent: name: "ListTriggers" describe 'when one echo-in exist', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [ {online: true, flow: nodes: [{name: 'yay', type: 'operation:echo-in'}]} ] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: ' <speak>You have an available trigger, yay. Say, "trigger yay" to perform the action</speak> ' shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up search your flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when two echo-in exist', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [ {online: true, flow: nodes: [{name: 'sweet', type: 'operation:echo-in'}]} {online: true, flow: nodes: [{name: 'yay', type: 'operation:echo-in'}]} ] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: ' <speak>You have two available triggers, sweet and yay. Say, "trigger sweet" or "trigger yay" to perform the action</speak> ' shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up search your flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when three echo-in exist', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [ {online: true, flow: nodes: [{name: 'sweet', type: 'operation:echo-in'}]} {online: true, flow: nodes: [{name: 'yay', type: 'operation:echo-in'}]} {online: true, flow: nodes: [{name: 'cool', type: 'operation:echo-in'}]} ] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: ' <speak>You have the following available triggers, sweet, yay, and cool. Say "trigger" then the name of the trigger to perform the action</speak> ' shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up search your flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when no echo-in exists', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: " <speak>You don't have any echo-in triggers. Get started by importing one or more alexa bluprints.</speak> " shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up get a list of flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when missing auth', -> beforeEach (done) -> sessionId = uuid.v1() requestId = uuid.v1() @whoami = @meshblu .post '/authenticate' .reply 403, error: message: 'Unauthorized' options = uri: '/trigger' baseUrl: "http://localhost:#{@serverPort}" json: session: sessionId: sessionId application: applicationId: "application-id" user: userId: "user-id", new: true request: type: "IntentRequest", requestId: requestId, timestamp: "2016-02-12T19:28:15Z", intent: name: "ListTriggers" request.post options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: '<speak>Please go to your Alexa app and link your account.</speak>' card: type: 'LinkAccount' shouldEndSession: true it 'should respond with 200', -> expect(@response.statusCode).to.equal 200
196645
{describe,beforeEach,afterEach,expect,it} = global request = require 'request' enableDestroy = require 'server-destroy' shmock = require 'shmock' uuid = require 'uuid' Server = require '../../src/server' describe 'List Triggers', -> beforeEach (done) -> @meshblu = shmock 0xd00d enableDestroy(@meshblu) meshbluConfig = server: 'localhost' port: 0xd00d protocol: 'http' keepAlive: false serverOptions = port: undefined, disableLogging: true meshbluConfig: meshbluConfig alexaServiceUri: 'https://alexa.octoblu.dev' namespace: 'alexa-service:test' disableAlexaVerification: true @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() afterEach -> @meshblu.destroy() @server.destroy() describe 'POST /trigger', -> describe 'when successful', -> beforeEach -> sessionId = uuid.v1() requestId = uuid.v1() @userAuth = new Buffer('user-uuid:user-token').toString('base64') @whoami = @meshblu .post '/authenticate' .set 'Authorization', "Basic #{@userAuth}" .reply 200, uuid: 'user-uuid', token: 'user-token' @options = uri: '/trigger' baseUrl: "http://localhost:#{@serverPort}" json: session: sessionId: sessionId, application: applicationId: "application-id" user: userId: "user-id", accessToken: @userAuth new: true request: type: "IntentRequest", requestId: requestId, timestamp: "2016-02-12T19:28:15Z", intent: name: "ListTriggers" describe 'when one echo-in exist', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [ {online: true, flow: nodes: [{name: '<NAME>', type: 'operation:echo-in'}]} ] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: ' <speak>You have an available trigger, yay. Say, "trigger yay" to perform the action</speak> ' shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up search your flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when two echo-in exist', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [ {online: true, flow: nodes: [{name: 'sweet', type: 'operation:echo-in'}]} {online: true, flow: nodes: [{name: '<NAME>', type: 'operation:echo-in'}]} ] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: ' <speak>You have two available triggers, sweet and yay. Say, "trigger sweet" or "trigger yay" to perform the action</speak> ' shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up search your flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when three echo-in exist', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [ {online: true, flow: nodes: [{name: 'sweet', type: 'operation:echo-in'}]} {online: true, flow: nodes: [{name: 'yay', type: 'operation:echo-in'}]} {online: true, flow: nodes: [{name: 'cool', type: 'operation:echo-in'}]} ] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: ' <speak>You have the following available triggers, sweet, yay, and cool. Say "trigger" then the name of the trigger to perform the action</speak> ' shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up search your flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when no echo-in exists', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: " <speak>You don't have any echo-in triggers. Get started by importing one or more alexa bluprints.</speak> " shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up get a list of flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when missing auth', -> beforeEach (done) -> sessionId = uuid.v1() requestId = uuid.v1() @whoami = @meshblu .post '/authenticate' .reply 403, error: message: 'Unauthorized' options = uri: '/trigger' baseUrl: "http://localhost:#{@serverPort}" json: session: sessionId: sessionId application: applicationId: "application-id" user: userId: "user-id", new: true request: type: "IntentRequest", requestId: requestId, timestamp: "2016-02-12T19:28:15Z", intent: name: "ListTriggers" request.post options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: '<speak>Please go to your Alexa app and link your account.</speak>' card: type: 'LinkAccount' shouldEndSession: true it 'should respond with 200', -> expect(@response.statusCode).to.equal 200
true
{describe,beforeEach,afterEach,expect,it} = global request = require 'request' enableDestroy = require 'server-destroy' shmock = require 'shmock' uuid = require 'uuid' Server = require '../../src/server' describe 'List Triggers', -> beforeEach (done) -> @meshblu = shmock 0xd00d enableDestroy(@meshblu) meshbluConfig = server: 'localhost' port: 0xd00d protocol: 'http' keepAlive: false serverOptions = port: undefined, disableLogging: true meshbluConfig: meshbluConfig alexaServiceUri: 'https://alexa.octoblu.dev' namespace: 'alexa-service:test' disableAlexaVerification: true @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() afterEach -> @meshblu.destroy() @server.destroy() describe 'POST /trigger', -> describe 'when successful', -> beforeEach -> sessionId = uuid.v1() requestId = uuid.v1() @userAuth = new Buffer('user-uuid:user-token').toString('base64') @whoami = @meshblu .post '/authenticate' .set 'Authorization', "Basic #{@userAuth}" .reply 200, uuid: 'user-uuid', token: 'user-token' @options = uri: '/trigger' baseUrl: "http://localhost:#{@serverPort}" json: session: sessionId: sessionId, application: applicationId: "application-id" user: userId: "user-id", accessToken: @userAuth new: true request: type: "IntentRequest", requestId: requestId, timestamp: "2016-02-12T19:28:15Z", intent: name: "ListTriggers" describe 'when one echo-in exist', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [ {online: true, flow: nodes: [{name: 'PI:NAME:<NAME>END_PI', type: 'operation:echo-in'}]} ] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: ' <speak>You have an available trigger, yay. Say, "trigger yay" to perform the action</speak> ' shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up search your flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when two echo-in exist', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [ {online: true, flow: nodes: [{name: 'sweet', type: 'operation:echo-in'}]} {online: true, flow: nodes: [{name: 'PI:NAME:<NAME>END_PI', type: 'operation:echo-in'}]} ] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: ' <speak>You have two available triggers, sweet and yay. Say, "trigger sweet" or "trigger yay" to perform the action</speak> ' shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up search your flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when three echo-in exist', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [ {online: true, flow: nodes: [{name: 'sweet', type: 'operation:echo-in'}]} {online: true, flow: nodes: [{name: 'yay', type: 'operation:echo-in'}]} {online: true, flow: nodes: [{name: 'cool', type: 'operation:echo-in'}]} ] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: ' <speak>You have the following available triggers, sweet, yay, and cool. Say "trigger" then the name of the trigger to perform the action</speak> ' shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up search your flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when no echo-in exists', -> beforeEach (done) -> @searchDevices = @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .set 'X-MESHBLU-PROJECTION', JSON.stringify { uuid: true, 'flow.nodes': true } .send { owner: 'user-uuid', type: 'octoblu:flow', online: true } .reply 200, [] request.post @options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: " <speak>You don't have any echo-in triggers. Get started by importing one or more alexa bluprints.</speak> " shouldEndSession: false it 'should respond with 200', -> expect(@response.statusCode).to.equal 200 it 'should hit up get a list of flows', -> @searchDevices.done() it 'should hit up whoami', -> @whoami.done() describe 'when missing auth', -> beforeEach (done) -> sessionId = uuid.v1() requestId = uuid.v1() @whoami = @meshblu .post '/authenticate' .reply 403, error: message: 'Unauthorized' options = uri: '/trigger' baseUrl: "http://localhost:#{@serverPort}" json: session: sessionId: sessionId application: applicationId: "application-id" user: userId: "user-id", new: true request: type: "IntentRequest", requestId: requestId, timestamp: "2016-02-12T19:28:15Z", intent: name: "ListTriggers" request.post options, (error, @response, @body) => done error it 'should have a body', -> expect(@body).to.deep.equal version: '1.0' response: directives: [] outputSpeech: type: 'SSML' ssml: '<speak>Please go to your Alexa app and link your account.</speak>' card: type: 'LinkAccount' shouldEndSession: true it 'should respond with 200', -> expect(@response.statusCode).to.equal 200
[ { "context": "###\n# grunt/less.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Define our les", "end": 46, "score": 0.9996565580368042, "start": 35, "tag": "NAME", "value": "Dan Nichols" } ]
grunt/less.coffee
dlnichols/h_media
0
### # grunt/less.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # Define our less configuration block for grunt ### 'use strict' module.exports = # Compile LESS to CSS build: files: [ expand: true cwd: 'app/styles/' src: [ '*.less' ] dest: '.tmp/styles/' ext: '.css' extDot: 'last' ] options: sourceMap: false serve: files: [ expand: true cwd: 'app/styles/' src: [ '*.less' ] dest: '.tmp/styles/' ext: '.css' extDot: 'last' ] options: sourceMap: true sourceMapFilename: '' sourceMapBasepath: '' sourceMapRootpath: '/'
217828
### # grunt/less.coffee # # © 2014 <NAME> # See LICENSE for more details # # Define our less configuration block for grunt ### 'use strict' module.exports = # Compile LESS to CSS build: files: [ expand: true cwd: 'app/styles/' src: [ '*.less' ] dest: '.tmp/styles/' ext: '.css' extDot: 'last' ] options: sourceMap: false serve: files: [ expand: true cwd: 'app/styles/' src: [ '*.less' ] dest: '.tmp/styles/' ext: '.css' extDot: 'last' ] options: sourceMap: true sourceMapFilename: '' sourceMapBasepath: '' sourceMapRootpath: '/'
true
### # grunt/less.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # Define our less configuration block for grunt ### 'use strict' module.exports = # Compile LESS to CSS build: files: [ expand: true cwd: 'app/styles/' src: [ '*.less' ] dest: '.tmp/styles/' ext: '.css' extDot: 'last' ] options: sourceMap: false serve: files: [ expand: true cwd: 'app/styles/' src: [ '*.less' ] dest: '.tmp/styles/' ext: '.css' extDot: 'last' ] options: sourceMap: true sourceMapFilename: '' sourceMapBasepath: '' sourceMapRootpath: '/'
[ { "context": "# Tâmia © 2013 Artem Sapegin http://sapegin.me\n# Password field with toggle to", "end": 28, "score": 0.9998998641967773, "start": 15, "tag": "NAME", "value": "Artem Sapegin" } ]
gh-pages/tamia/modules/password/script.coffee
b0n3v/XRB-facebook
0
# Tâmia © 2013 Artem Sapegin http://sapegin.me # Password field with toggle to show characters 'use strict' $ = jQuery supported = undefined class Password extends Component init: -> @types = locked: 'password' unlocked: 'text' @fieldElem = @find('field') @toggleElem = @find('toggle') # Mousedown instead of click to catch focused field @on('mousedown', 'toggle', @toggle) isSupported: -> return supported unless supported is undefined # IE8+ supported = $('<!--[if lte IE 8]><i></i><![endif]-->').find('i').length isnt 1 return supported toggle: -> focused = document.activeElement is @fieldElem[0] locked = @hasState('unlocked') fieldType = @fieldElem.attr('type') @toggleState('unlocked') if fieldType is @types.locked and not locked @fieldElem.attr('type', @types.unlocked) else if fieldType is @types.unlocked and locked @fieldElem.attr('type', @types.locked) if focused setTimeout((=> @fieldElem.focus()), 0) tamia.initComponents(password: Password)
203075
# Tâmia © 2013 <NAME> http://sapegin.me # Password field with toggle to show characters 'use strict' $ = jQuery supported = undefined class Password extends Component init: -> @types = locked: 'password' unlocked: 'text' @fieldElem = @find('field') @toggleElem = @find('toggle') # Mousedown instead of click to catch focused field @on('mousedown', 'toggle', @toggle) isSupported: -> return supported unless supported is undefined # IE8+ supported = $('<!--[if lte IE 8]><i></i><![endif]-->').find('i').length isnt 1 return supported toggle: -> focused = document.activeElement is @fieldElem[0] locked = @hasState('unlocked') fieldType = @fieldElem.attr('type') @toggleState('unlocked') if fieldType is @types.locked and not locked @fieldElem.attr('type', @types.unlocked) else if fieldType is @types.unlocked and locked @fieldElem.attr('type', @types.locked) if focused setTimeout((=> @fieldElem.focus()), 0) tamia.initComponents(password: Password)
true
# Tâmia © 2013 PI:NAME:<NAME>END_PI http://sapegin.me # Password field with toggle to show characters 'use strict' $ = jQuery supported = undefined class Password extends Component init: -> @types = locked: 'password' unlocked: 'text' @fieldElem = @find('field') @toggleElem = @find('toggle') # Mousedown instead of click to catch focused field @on('mousedown', 'toggle', @toggle) isSupported: -> return supported unless supported is undefined # IE8+ supported = $('<!--[if lte IE 8]><i></i><![endif]-->').find('i').length isnt 1 return supported toggle: -> focused = document.activeElement is @fieldElem[0] locked = @hasState('unlocked') fieldType = @fieldElem.attr('type') @toggleState('unlocked') if fieldType is @types.locked and not locked @fieldElem.attr('type', @types.unlocked) else if fieldType is @types.unlocked and locked @fieldElem.attr('type', @types.locked) if focused setTimeout((=> @fieldElem.focus()), 0) tamia.initComponents(password: Password)
[ { "context": " = 'http://api.penncoursereview.com/v1/'\nTOKEN = 'public'\n\nget_json = (path, callback, options) ->\n $.get", "end": 62, "score": 0.85304194688797, "start": 56, "tag": "PASSWORD", "value": "public" } ]
coffee/pcr.coffee
gterrono/coursegrapher
1
DOMAIN = 'http://api.penncoursereview.com/v1/' TOKEN = 'public' get_json = (path, callback, options) -> $.get "#{DOMAIN}#{path}?token=#{TOKEN}", (data) => data = JSON.parse(data).result callback(data, options) departments = (callback, options) -> path = 'depts/' get_json path, callback, options dept_reviews = (did, callback, options) -> path = "depts/#{did}/reviews" get_json path, callback, options departments_received = 0 revs_callback = (data, options) -> if options.dept == "PSSA" # this is some bullshit major return departments_received++ dept_name = options.dept dept = {} dept_totals = {} dept_averages = {} dept_averages = {} for obj in data.values courses = (c.split('-')[1] for c in obj.section.aliases when c.indexOf(dept_name) == 0) for course in courses unless dept[course] dept[course] = {reviews: [], totals: {}, averages: {}} c = dept[course] c.reviews.push(obj.ratings) c.name = obj.section.name for category, val of obj.ratings unless category of c.totals c.totals[category] = {sum: 0, num: 0} c.totals[category].sum += parseFloat(val) c.totals[category].num++ dept_num = 0 for name, c of dept for category, val of c.totals c.averages[category] = val.sum / val.num unless category of dept_totals dept_totals[category] = {sum: 0, num: 0} dept_totals[category].sum += c.averages[category] dept_totals[category].num++ delete c.totals delete c.reviews dept_num++ dept_num -= 4 for category, val of dept_totals dept_averages[category] = val.sum / val.num temp = {} temp[dept_name] = averages: dept_averages, num: dept_num, name: options.dept_full_name depts_db.update(temp) temp = {} temp[dept_name] = dept root_db.update(temp) if departments_fetched == departments_received console.log "Done: #{departments_received} departments processed" departments_fetched = 0 depts_callback = (data, options={}) -> for d in data.values departments_fetched++ options.dept = d.id options.dept_full_name = d.name dept_reviews(d.id, revs_callback, _.clone(options)) window.update_data = (token) -> window.root_db = new Firebase('https://coursegrapher.firebaseio.com/') window.depts_db = new Firebase('https://coursegrapher.firebaseio.com/depts/') TOKEN = token departments(depts_callback)
181287
DOMAIN = 'http://api.penncoursereview.com/v1/' TOKEN = '<PASSWORD>' get_json = (path, callback, options) -> $.get "#{DOMAIN}#{path}?token=#{TOKEN}", (data) => data = JSON.parse(data).result callback(data, options) departments = (callback, options) -> path = 'depts/' get_json path, callback, options dept_reviews = (did, callback, options) -> path = "depts/#{did}/reviews" get_json path, callback, options departments_received = 0 revs_callback = (data, options) -> if options.dept == "PSSA" # this is some bullshit major return departments_received++ dept_name = options.dept dept = {} dept_totals = {} dept_averages = {} dept_averages = {} for obj in data.values courses = (c.split('-')[1] for c in obj.section.aliases when c.indexOf(dept_name) == 0) for course in courses unless dept[course] dept[course] = {reviews: [], totals: {}, averages: {}} c = dept[course] c.reviews.push(obj.ratings) c.name = obj.section.name for category, val of obj.ratings unless category of c.totals c.totals[category] = {sum: 0, num: 0} c.totals[category].sum += parseFloat(val) c.totals[category].num++ dept_num = 0 for name, c of dept for category, val of c.totals c.averages[category] = val.sum / val.num unless category of dept_totals dept_totals[category] = {sum: 0, num: 0} dept_totals[category].sum += c.averages[category] dept_totals[category].num++ delete c.totals delete c.reviews dept_num++ dept_num -= 4 for category, val of dept_totals dept_averages[category] = val.sum / val.num temp = {} temp[dept_name] = averages: dept_averages, num: dept_num, name: options.dept_full_name depts_db.update(temp) temp = {} temp[dept_name] = dept root_db.update(temp) if departments_fetched == departments_received console.log "Done: #{departments_received} departments processed" departments_fetched = 0 depts_callback = (data, options={}) -> for d in data.values departments_fetched++ options.dept = d.id options.dept_full_name = d.name dept_reviews(d.id, revs_callback, _.clone(options)) window.update_data = (token) -> window.root_db = new Firebase('https://coursegrapher.firebaseio.com/') window.depts_db = new Firebase('https://coursegrapher.firebaseio.com/depts/') TOKEN = token departments(depts_callback)
true
DOMAIN = 'http://api.penncoursereview.com/v1/' TOKEN = 'PI:PASSWORD:<PASSWORD>END_PI' get_json = (path, callback, options) -> $.get "#{DOMAIN}#{path}?token=#{TOKEN}", (data) => data = JSON.parse(data).result callback(data, options) departments = (callback, options) -> path = 'depts/' get_json path, callback, options dept_reviews = (did, callback, options) -> path = "depts/#{did}/reviews" get_json path, callback, options departments_received = 0 revs_callback = (data, options) -> if options.dept == "PSSA" # this is some bullshit major return departments_received++ dept_name = options.dept dept = {} dept_totals = {} dept_averages = {} dept_averages = {} for obj in data.values courses = (c.split('-')[1] for c in obj.section.aliases when c.indexOf(dept_name) == 0) for course in courses unless dept[course] dept[course] = {reviews: [], totals: {}, averages: {}} c = dept[course] c.reviews.push(obj.ratings) c.name = obj.section.name for category, val of obj.ratings unless category of c.totals c.totals[category] = {sum: 0, num: 0} c.totals[category].sum += parseFloat(val) c.totals[category].num++ dept_num = 0 for name, c of dept for category, val of c.totals c.averages[category] = val.sum / val.num unless category of dept_totals dept_totals[category] = {sum: 0, num: 0} dept_totals[category].sum += c.averages[category] dept_totals[category].num++ delete c.totals delete c.reviews dept_num++ dept_num -= 4 for category, val of dept_totals dept_averages[category] = val.sum / val.num temp = {} temp[dept_name] = averages: dept_averages, num: dept_num, name: options.dept_full_name depts_db.update(temp) temp = {} temp[dept_name] = dept root_db.update(temp) if departments_fetched == departments_received console.log "Done: #{departments_received} departments processed" departments_fetched = 0 depts_callback = (data, options={}) -> for d in data.values departments_fetched++ options.dept = d.id options.dept_full_name = d.name dept_reviews(d.id, revs_callback, _.clone(options)) window.update_data = (token) -> window.root_db = new Firebase('https://coursegrapher.firebaseio.com/') window.depts_db = new Firebase('https://coursegrapher.firebaseio.com/depts/') TOKEN = token departments(depts_callback)
[ { "context": " 1, 0)))\n days = Days(startDate, endDate)\n key = \"#{date.getFullYear()}-#{date.getMonth()}\"\n\n month.k", "end": 949, "score": 0.549281656742096, "start": 946, "tag": "KEY", "value": "\"#{" }, { "context": "ys(startDate, endDate)\n key = \"#{date.getFullYear()}-...
src/components/calendar/month.coffee
brianshaler/kerplunk-location-calendar
0
{ fragmentShader, vertexShader } = require './shaders' Days = require './days' Square = require '../webgl/square' dayCols = 7 # squareSize = 24 # squareMargin = 5 maxDays = 31 monthNames = [ 'January' 'February' 'March' 'April' 'May' 'June' 'July' 'August' 'September' 'October' 'November' 'December' ] positionDays = (month) -> { squareMargin, squareSize, } = month.config month.days.forEach (day) -> calDaysBefore = month.date.getDay() calIndex = day.d.getDate() + calDaysBefore - 1 calRow = Math.floor(calIndex / dayCols) calCol = calIndex - calRow * dayCols calX = (squareSize + squareMargin) * calCol calY = (squareSize + squareMargin) * calRow day.calX = calX day.calY = calY setMonth = (month, date) -> startDate = date endDate = new Date(Math.min(new Date(), new Date(date.getFullYear(), date.getMonth() + 1, 0))) days = Days(startDate, endDate) key = "#{date.getFullYear()}-#{date.getMonth()}" month.key = key month.date = date month.days = days month.startDate = startDate month.endDate = endDate month updateCalendarPosition = (month, x=month.x, y=month.y) -> calendarPosition = new Array(maxDays).fill([-10000, -10000]) month.x = x month.y = y positionDays(month) month.days.forEach (day, index) -> calendarPosition[index] = [month.x + day.calX, month.y + day.calY] month.updateBuffer('calendarPosition', calendarPosition) updateLegendPosition = (month, days) -> legendPosition = new Array(maxDays).fill([-10000, -10000]) month.days.forEach (day, index) => newDay = days.find (d) => d.key == day.key return [0, 0] unless newDay legendPosition[index] = newDay.legendPosition month.updateBuffer('legendPosition', legendPosition) updateMapPosition = (month, days) -> mapPosition = new Array(maxDays).fill([-10000, -10000]) month.days.forEach (day, index) -> newDay = days.find (d) => d.key == day.key return [0, 0] unless newDay mapPosition[index] = newDay.mapPosition # console.log('month.updateBuffer mapPosition', mapPosition) month.updateBuffer('mapPosition', mapPosition) updateColors = (month, days) -> color1 = [] color2 = [] textureId = [] month.days.forEach (day, index) -> newDay = days.find (d) -> d.key == day.key unless newDay color1[index] = [1, 1, 1] color2[index] = [1, 1, 1] textureId[index] = 0 return color1[index] = newDay.color1 color2[index] = newDay.color2 textureId[index] = newDay.textureId month.updateBuffer('color1', color1) month.updateBuffer('color2', color2) month.updateBuffer('textureId', textureId) filterDaysByMonth = (month, days) -> days.filter ({d}) -> d >= month.startDate && d <= month.endDate destroy = (month) -> null square = Square 1 # console.log('square', square) module.exports = Month = (regl, date, config) -> month = config: config regl: regl x: 0 y: 0 buffers: {} month.updateBuffer = (name, data) -> month.buffers[name].subdata(data) setMonth month, date addBuffer = (name, type, bytes) -> month.buffers[name] = regl.buffer length: maxDays * bytes type: type usage: 'dynamic' addBuffer 'color1', 'float', 12 addBuffer 'color2', 'float', 12 addBuffer 'calendarPosition', 'float', 8 addBuffer 'legendPosition', 'float', 8 addBuffer 'mapPosition', 'float', 8 addBuffer 'textureId', 'uint8', 1 addBuffer 'tOffset', 'float', 4 tOffset = new Array(maxDays).fill().map -> Math.random() - 0.5 month.updateBuffer 'tOffset', tOffset draw = regl frag: fragmentShader vert: vertexShader elements: square.elements count: square.count attributes: position: square.position color1: buffer: month.buffers.color1 divisor: 1 color2: buffer: month.buffers.color2 divisor: 1 calendarPosition: buffer: month.buffers.calendarPosition divisor: 1 legendPosition: buffer: month.buffers.legendPosition divisor: 1 mapPosition: buffer: month.buffers.mapPosition divisor: 1 textureId: buffer: month.buffers.textureId divisor: 1 tOffset: buffer: month.buffers.tOffset divisor: 1 uniforms: selected: regl.prop('selected') scale: regl.prop('scale') instances: maxDays destroy: () -> destroy(month) draw: draw getFormattedDate: () -> "#{monthNames[month.date.getMonth()]} #{month.date.getFullYear()}" getDate: () -> month.date getDays: () -> month.days getKey: () -> month.key getPosition: () -> ({x: month.x, y: month.y}) # positionDays: () -> positionDays(month) setConfig: (config) -> month.config = config setMonth: (date) -> setMonth(month, date) updateCalendarPosition: (x=month.x, y=month.y) -> updateCalendarPosition(month, x, y) updateColors: (allDays) -> updateColors(month, filterDaysByMonth(month, allDays)) updateLegendPosition: (allDays) -> updateLegendPosition(month, filterDaysByMonth(month, allDays)) updateMapPosition: (allDays) -> updateMapPosition(month, filterDaysByMonth(month, allDays))
139978
{ fragmentShader, vertexShader } = require './shaders' Days = require './days' Square = require '../webgl/square' dayCols = 7 # squareSize = 24 # squareMargin = 5 maxDays = 31 monthNames = [ 'January' 'February' 'March' 'April' 'May' 'June' 'July' 'August' 'September' 'October' 'November' 'December' ] positionDays = (month) -> { squareMargin, squareSize, } = month.config month.days.forEach (day) -> calDaysBefore = month.date.getDay() calIndex = day.d.getDate() + calDaysBefore - 1 calRow = Math.floor(calIndex / dayCols) calCol = calIndex - calRow * dayCols calX = (squareSize + squareMargin) * calCol calY = (squareSize + squareMargin) * calRow day.calX = calX day.calY = calY setMonth = (month, date) -> startDate = date endDate = new Date(Math.min(new Date(), new Date(date.getFullYear(), date.getMonth() + 1, 0))) days = Days(startDate, endDate) key = <KEY>date.getFullYear()}-<KEY>date.getMonth()}" month.key = key month.date = date month.days = days month.startDate = startDate month.endDate = endDate month updateCalendarPosition = (month, x=month.x, y=month.y) -> calendarPosition = new Array(maxDays).fill([-10000, -10000]) month.x = x month.y = y positionDays(month) month.days.forEach (day, index) -> calendarPosition[index] = [month.x + day.calX, month.y + day.calY] month.updateBuffer('calendarPosition', calendarPosition) updateLegendPosition = (month, days) -> legendPosition = new Array(maxDays).fill([-10000, -10000]) month.days.forEach (day, index) => newDay = days.find (d) => d.key == day.key return [0, 0] unless newDay legendPosition[index] = newDay.legendPosition month.updateBuffer('legendPosition', legendPosition) updateMapPosition = (month, days) -> mapPosition = new Array(maxDays).fill([-10000, -10000]) month.days.forEach (day, index) -> newDay = days.find (d) => d.key == day.key return [0, 0] unless newDay mapPosition[index] = newDay.mapPosition # console.log('month.updateBuffer mapPosition', mapPosition) month.updateBuffer('mapPosition', mapPosition) updateColors = (month, days) -> color1 = [] color2 = [] textureId = [] month.days.forEach (day, index) -> newDay = days.find (d) -> d.key == day.key unless newDay color1[index] = [1, 1, 1] color2[index] = [1, 1, 1] textureId[index] = 0 return color1[index] = newDay.color1 color2[index] = newDay.color2 textureId[index] = newDay.textureId month.updateBuffer('color1', color1) month.updateBuffer('color2', color2) month.updateBuffer('textureId', textureId) filterDaysByMonth = (month, days) -> days.filter ({d}) -> d >= month.startDate && d <= month.endDate destroy = (month) -> null square = Square 1 # console.log('square', square) module.exports = Month = (regl, date, config) -> month = config: config regl: regl x: 0 y: 0 buffers: {} month.updateBuffer = (name, data) -> month.buffers[name].subdata(data) setMonth month, date addBuffer = (name, type, bytes) -> month.buffers[name] = regl.buffer length: maxDays * bytes type: type usage: 'dynamic' addBuffer 'color1', 'float', 12 addBuffer 'color2', 'float', 12 addBuffer 'calendarPosition', 'float', 8 addBuffer 'legendPosition', 'float', 8 addBuffer 'mapPosition', 'float', 8 addBuffer 'textureId', 'uint8', 1 addBuffer 'tOffset', 'float', 4 tOffset = new Array(maxDays).fill().map -> Math.random() - 0.5 month.updateBuffer 'tOffset', tOffset draw = regl frag: fragmentShader vert: vertexShader elements: square.elements count: square.count attributes: position: square.position color1: buffer: month.buffers.color1 divisor: 1 color2: buffer: month.buffers.color2 divisor: 1 calendarPosition: buffer: month.buffers.calendarPosition divisor: 1 legendPosition: buffer: month.buffers.legendPosition divisor: 1 mapPosition: buffer: month.buffers.mapPosition divisor: 1 textureId: buffer: month.buffers.textureId divisor: 1 tOffset: buffer: month.buffers.tOffset divisor: 1 uniforms: selected: regl.prop('selected') scale: regl.prop('scale') instances: maxDays destroy: () -> destroy(month) draw: draw getFormattedDate: () -> "#{monthNames[month.date.getMonth()]} #{month.date.getFullYear()}" getDate: () -> month.date getDays: () -> month.days getKey: () -> month.key getPosition: () -> ({x: month.x, y: month.y}) # positionDays: () -> positionDays(month) setConfig: (config) -> month.config = config setMonth: (date) -> setMonth(month, date) updateCalendarPosition: (x=month.x, y=month.y) -> updateCalendarPosition(month, x, y) updateColors: (allDays) -> updateColors(month, filterDaysByMonth(month, allDays)) updateLegendPosition: (allDays) -> updateLegendPosition(month, filterDaysByMonth(month, allDays)) updateMapPosition: (allDays) -> updateMapPosition(month, filterDaysByMonth(month, allDays))
true
{ fragmentShader, vertexShader } = require './shaders' Days = require './days' Square = require '../webgl/square' dayCols = 7 # squareSize = 24 # squareMargin = 5 maxDays = 31 monthNames = [ 'January' 'February' 'March' 'April' 'May' 'June' 'July' 'August' 'September' 'October' 'November' 'December' ] positionDays = (month) -> { squareMargin, squareSize, } = month.config month.days.forEach (day) -> calDaysBefore = month.date.getDay() calIndex = day.d.getDate() + calDaysBefore - 1 calRow = Math.floor(calIndex / dayCols) calCol = calIndex - calRow * dayCols calX = (squareSize + squareMargin) * calCol calY = (squareSize + squareMargin) * calRow day.calX = calX day.calY = calY setMonth = (month, date) -> startDate = date endDate = new Date(Math.min(new Date(), new Date(date.getFullYear(), date.getMonth() + 1, 0))) days = Days(startDate, endDate) key = PI:KEY:<KEY>END_PIdate.getFullYear()}-PI:KEY:<KEY>END_PIdate.getMonth()}" month.key = key month.date = date month.days = days month.startDate = startDate month.endDate = endDate month updateCalendarPosition = (month, x=month.x, y=month.y) -> calendarPosition = new Array(maxDays).fill([-10000, -10000]) month.x = x month.y = y positionDays(month) month.days.forEach (day, index) -> calendarPosition[index] = [month.x + day.calX, month.y + day.calY] month.updateBuffer('calendarPosition', calendarPosition) updateLegendPosition = (month, days) -> legendPosition = new Array(maxDays).fill([-10000, -10000]) month.days.forEach (day, index) => newDay = days.find (d) => d.key == day.key return [0, 0] unless newDay legendPosition[index] = newDay.legendPosition month.updateBuffer('legendPosition', legendPosition) updateMapPosition = (month, days) -> mapPosition = new Array(maxDays).fill([-10000, -10000]) month.days.forEach (day, index) -> newDay = days.find (d) => d.key == day.key return [0, 0] unless newDay mapPosition[index] = newDay.mapPosition # console.log('month.updateBuffer mapPosition', mapPosition) month.updateBuffer('mapPosition', mapPosition) updateColors = (month, days) -> color1 = [] color2 = [] textureId = [] month.days.forEach (day, index) -> newDay = days.find (d) -> d.key == day.key unless newDay color1[index] = [1, 1, 1] color2[index] = [1, 1, 1] textureId[index] = 0 return color1[index] = newDay.color1 color2[index] = newDay.color2 textureId[index] = newDay.textureId month.updateBuffer('color1', color1) month.updateBuffer('color2', color2) month.updateBuffer('textureId', textureId) filterDaysByMonth = (month, days) -> days.filter ({d}) -> d >= month.startDate && d <= month.endDate destroy = (month) -> null square = Square 1 # console.log('square', square) module.exports = Month = (regl, date, config) -> month = config: config regl: regl x: 0 y: 0 buffers: {} month.updateBuffer = (name, data) -> month.buffers[name].subdata(data) setMonth month, date addBuffer = (name, type, bytes) -> month.buffers[name] = regl.buffer length: maxDays * bytes type: type usage: 'dynamic' addBuffer 'color1', 'float', 12 addBuffer 'color2', 'float', 12 addBuffer 'calendarPosition', 'float', 8 addBuffer 'legendPosition', 'float', 8 addBuffer 'mapPosition', 'float', 8 addBuffer 'textureId', 'uint8', 1 addBuffer 'tOffset', 'float', 4 tOffset = new Array(maxDays).fill().map -> Math.random() - 0.5 month.updateBuffer 'tOffset', tOffset draw = regl frag: fragmentShader vert: vertexShader elements: square.elements count: square.count attributes: position: square.position color1: buffer: month.buffers.color1 divisor: 1 color2: buffer: month.buffers.color2 divisor: 1 calendarPosition: buffer: month.buffers.calendarPosition divisor: 1 legendPosition: buffer: month.buffers.legendPosition divisor: 1 mapPosition: buffer: month.buffers.mapPosition divisor: 1 textureId: buffer: month.buffers.textureId divisor: 1 tOffset: buffer: month.buffers.tOffset divisor: 1 uniforms: selected: regl.prop('selected') scale: regl.prop('scale') instances: maxDays destroy: () -> destroy(month) draw: draw getFormattedDate: () -> "#{monthNames[month.date.getMonth()]} #{month.date.getFullYear()}" getDate: () -> month.date getDays: () -> month.days getKey: () -> month.key getPosition: () -> ({x: month.x, y: month.y}) # positionDays: () -> positionDays(month) setConfig: (config) -> month.config = config setMonth: (date) -> setMonth(month, date) updateCalendarPosition: (x=month.x, y=month.y) -> updateCalendarPosition(month, x, y) updateColors: (allDays) -> updateColors(month, filterDaysByMonth(month, allDays)) updateLegendPosition: (allDays) -> updateLegendPosition(month, filterDaysByMonth(month, allDays)) updateMapPosition: (allDays) -> updateMapPosition(month, filterDaysByMonth(month, allDays))
[ { "context": "###\nCopyright 2016 Clemens Nylandsted Klokmose, Aarhus University\n\nLicensed under the Apache Lic", "end": 46, "score": 0.9998953342437744, "start": 19, "tag": "NAME", "value": "Clemens Nylandsted Klokmose" } ]
client_src/ot2dom.coffee
kar288/ddd
0
### Copyright 2016 Clemens Nylandsted Klokmose, Aarhus University Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### root = exports ? window root.ot2dom = {} # This function takes a (ShareJS) operation and applies it to a DOM element applyOp = (op, element) -> path = op.p domPath = [] attributePath = false # First convert from json path to domPath if path.length > 0 if op.si? or op.sd? # Its a string manipulation charIndex = op.p.pop() if typeof path[path.length-1] == 'string' # its an attribute path attributePath = true if path.length > 2 # Push all indeces converted to DOM indeces (by substracting 2) up to the target node for index in op.p[0..path.length-3] domPath.push index-2 # Push the attribute key domPath.push path[path.length-1] else # Just push the attribute key domPath.push(path[1]) else # Push all indeces converted to DOM indeces (by substracting 2) for index in op.p domPath.push index-2 if op.oi? # Operation is an object insertion if attributePath setAttribute $(element), domPath, op.oi if op.li? # Operation is a list insertion if not attributePath insert $(element), domPath, domPath, op.li if op.ld? # Operation is a list deletion if not attributePath deleteNode $(element), domPath if op.si? # Operation is a string insertion if not attributePath insertInText $(element), domPath, charIndex, op.si if op.sd? # Operation is a string deletion if not attributePath deleteInText $(element), domPath, charIndex, op.sd insertInText = (element, path, charIndex, value) -> if path.length > 1 insertInText element.contents().eq(path[0]), path[1..path.length], charIndex, value else textNode = if element[0].nodeType == 8 then element[0] else element.contents().eq(path[0])[0] oldString = textNode.data newString = oldString.substring(0, charIndex) + value + oldString.substring(charIndex, oldString.length) textNode.data = newString event = new CustomEvent "insertText", {detail: {position: charIndex, value: value}} textNode.dispatchEvent event deleteInText = (element, path, charIndex, value) -> if path.length > 1 deleteInText element.contents().eq(path[0]), path[1..path.length], charIndex, value else textNode = element.contents().eq(path[0])[0] oldString = textNode.data newString = oldString.substring(0, charIndex) + oldString.substring(charIndex + value.length, oldString.length) if newString.length == 0 #Hack to avoid that the browser removes the empty text node newString = '' textNode.data = newString event = new CustomEvent "deleteText", {detail: {position: charIndex, value: value}} textNode.dispatchEvent event setAttribute = (element, path, value) -> if path.length > 1 # Recursively skip to the end of the path setAttribute element.contents().eq(path[0]), path[1..path.length], value else # Update the attribute element.attr(path[0], value) insert = (element, relativePath, actualPath, value) -> if relativePath.length > 1 # Recursively skip to the end of the path insert element.contents().eq(relativePath[0]), relativePath[1..relativePath.length], actualPath, value if relativePath.length == 1 # Get the XML namespace of the target node ns = root.util.getNs element[0] # Convert the inserted JsonML if typeof value == 'string' html = $(document.createTextNode(value)) else html = $.jqml(value, ns) # Get the next sibling that the node should be inserted before sibling = element.contents().eq(relativePath[0]) if sibling.length > 0 # There is a sibling, we will insert the node before it html.insertBefore(element.contents().eq(relativePath[0])) # There's no sibling, so lets insert it (with a small hack to avoid JQuery not actually inserting a script node else if html[0].tagName? and html[0].tagName.toLowerCase() == "script" element[0].appendChild(html[0]) else element.append(html) # Update the path tree with the new node parentPathNode = util.getPathNode(element[0]) newPathNode = util.createPathTree html[0], parentPathNode, true siblings = parentPathNode.children parentPathNode.children = (siblings[0...relativePath[0]].concat [newPathNode]).concat siblings[relativePath[0]...siblings.length] deleteNode = (element, path) -> # Recursively skip to the end of the path if path.length > 1 deleteNode element.contents().eq(path[0]), path[1..path.length] if path.length == 1 # First remove the node from the path tree toRemove = element.contents().eq(path[0]) parentPathNode = util.getPathNode element[0] toRemovePathNode = util.getPathNode toRemove[0], parentPathNode childIndex = parentPathNode.children.indexOf toRemovePathNode parentPathNode.children.splice childIndex, 1 # Now remove the node from the DOM toRemove.remove() root.ot2dom.applyOp = applyOp
173221
### Copyright 2016 <NAME>, Aarhus University Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### root = exports ? window root.ot2dom = {} # This function takes a (ShareJS) operation and applies it to a DOM element applyOp = (op, element) -> path = op.p domPath = [] attributePath = false # First convert from json path to domPath if path.length > 0 if op.si? or op.sd? # Its a string manipulation charIndex = op.p.pop() if typeof path[path.length-1] == 'string' # its an attribute path attributePath = true if path.length > 2 # Push all indeces converted to DOM indeces (by substracting 2) up to the target node for index in op.p[0..path.length-3] domPath.push index-2 # Push the attribute key domPath.push path[path.length-1] else # Just push the attribute key domPath.push(path[1]) else # Push all indeces converted to DOM indeces (by substracting 2) for index in op.p domPath.push index-2 if op.oi? # Operation is an object insertion if attributePath setAttribute $(element), domPath, op.oi if op.li? # Operation is a list insertion if not attributePath insert $(element), domPath, domPath, op.li if op.ld? # Operation is a list deletion if not attributePath deleteNode $(element), domPath if op.si? # Operation is a string insertion if not attributePath insertInText $(element), domPath, charIndex, op.si if op.sd? # Operation is a string deletion if not attributePath deleteInText $(element), domPath, charIndex, op.sd insertInText = (element, path, charIndex, value) -> if path.length > 1 insertInText element.contents().eq(path[0]), path[1..path.length], charIndex, value else textNode = if element[0].nodeType == 8 then element[0] else element.contents().eq(path[0])[0] oldString = textNode.data newString = oldString.substring(0, charIndex) + value + oldString.substring(charIndex, oldString.length) textNode.data = newString event = new CustomEvent "insertText", {detail: {position: charIndex, value: value}} textNode.dispatchEvent event deleteInText = (element, path, charIndex, value) -> if path.length > 1 deleteInText element.contents().eq(path[0]), path[1..path.length], charIndex, value else textNode = element.contents().eq(path[0])[0] oldString = textNode.data newString = oldString.substring(0, charIndex) + oldString.substring(charIndex + value.length, oldString.length) if newString.length == 0 #Hack to avoid that the browser removes the empty text node newString = '' textNode.data = newString event = new CustomEvent "deleteText", {detail: {position: charIndex, value: value}} textNode.dispatchEvent event setAttribute = (element, path, value) -> if path.length > 1 # Recursively skip to the end of the path setAttribute element.contents().eq(path[0]), path[1..path.length], value else # Update the attribute element.attr(path[0], value) insert = (element, relativePath, actualPath, value) -> if relativePath.length > 1 # Recursively skip to the end of the path insert element.contents().eq(relativePath[0]), relativePath[1..relativePath.length], actualPath, value if relativePath.length == 1 # Get the XML namespace of the target node ns = root.util.getNs element[0] # Convert the inserted JsonML if typeof value == 'string' html = $(document.createTextNode(value)) else html = $.jqml(value, ns) # Get the next sibling that the node should be inserted before sibling = element.contents().eq(relativePath[0]) if sibling.length > 0 # There is a sibling, we will insert the node before it html.insertBefore(element.contents().eq(relativePath[0])) # There's no sibling, so lets insert it (with a small hack to avoid JQuery not actually inserting a script node else if html[0].tagName? and html[0].tagName.toLowerCase() == "script" element[0].appendChild(html[0]) else element.append(html) # Update the path tree with the new node parentPathNode = util.getPathNode(element[0]) newPathNode = util.createPathTree html[0], parentPathNode, true siblings = parentPathNode.children parentPathNode.children = (siblings[0...relativePath[0]].concat [newPathNode]).concat siblings[relativePath[0]...siblings.length] deleteNode = (element, path) -> # Recursively skip to the end of the path if path.length > 1 deleteNode element.contents().eq(path[0]), path[1..path.length] if path.length == 1 # First remove the node from the path tree toRemove = element.contents().eq(path[0]) parentPathNode = util.getPathNode element[0] toRemovePathNode = util.getPathNode toRemove[0], parentPathNode childIndex = parentPathNode.children.indexOf toRemovePathNode parentPathNode.children.splice childIndex, 1 # Now remove the node from the DOM toRemove.remove() root.ot2dom.applyOp = applyOp
true
### Copyright 2016 PI:NAME:<NAME>END_PI, Aarhus University Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### root = exports ? window root.ot2dom = {} # This function takes a (ShareJS) operation and applies it to a DOM element applyOp = (op, element) -> path = op.p domPath = [] attributePath = false # First convert from json path to domPath if path.length > 0 if op.si? or op.sd? # Its a string manipulation charIndex = op.p.pop() if typeof path[path.length-1] == 'string' # its an attribute path attributePath = true if path.length > 2 # Push all indeces converted to DOM indeces (by substracting 2) up to the target node for index in op.p[0..path.length-3] domPath.push index-2 # Push the attribute key domPath.push path[path.length-1] else # Just push the attribute key domPath.push(path[1]) else # Push all indeces converted to DOM indeces (by substracting 2) for index in op.p domPath.push index-2 if op.oi? # Operation is an object insertion if attributePath setAttribute $(element), domPath, op.oi if op.li? # Operation is a list insertion if not attributePath insert $(element), domPath, domPath, op.li if op.ld? # Operation is a list deletion if not attributePath deleteNode $(element), domPath if op.si? # Operation is a string insertion if not attributePath insertInText $(element), domPath, charIndex, op.si if op.sd? # Operation is a string deletion if not attributePath deleteInText $(element), domPath, charIndex, op.sd insertInText = (element, path, charIndex, value) -> if path.length > 1 insertInText element.contents().eq(path[0]), path[1..path.length], charIndex, value else textNode = if element[0].nodeType == 8 then element[0] else element.contents().eq(path[0])[0] oldString = textNode.data newString = oldString.substring(0, charIndex) + value + oldString.substring(charIndex, oldString.length) textNode.data = newString event = new CustomEvent "insertText", {detail: {position: charIndex, value: value}} textNode.dispatchEvent event deleteInText = (element, path, charIndex, value) -> if path.length > 1 deleteInText element.contents().eq(path[0]), path[1..path.length], charIndex, value else textNode = element.contents().eq(path[0])[0] oldString = textNode.data newString = oldString.substring(0, charIndex) + oldString.substring(charIndex + value.length, oldString.length) if newString.length == 0 #Hack to avoid that the browser removes the empty text node newString = '' textNode.data = newString event = new CustomEvent "deleteText", {detail: {position: charIndex, value: value}} textNode.dispatchEvent event setAttribute = (element, path, value) -> if path.length > 1 # Recursively skip to the end of the path setAttribute element.contents().eq(path[0]), path[1..path.length], value else # Update the attribute element.attr(path[0], value) insert = (element, relativePath, actualPath, value) -> if relativePath.length > 1 # Recursively skip to the end of the path insert element.contents().eq(relativePath[0]), relativePath[1..relativePath.length], actualPath, value if relativePath.length == 1 # Get the XML namespace of the target node ns = root.util.getNs element[0] # Convert the inserted JsonML if typeof value == 'string' html = $(document.createTextNode(value)) else html = $.jqml(value, ns) # Get the next sibling that the node should be inserted before sibling = element.contents().eq(relativePath[0]) if sibling.length > 0 # There is a sibling, we will insert the node before it html.insertBefore(element.contents().eq(relativePath[0])) # There's no sibling, so lets insert it (with a small hack to avoid JQuery not actually inserting a script node else if html[0].tagName? and html[0].tagName.toLowerCase() == "script" element[0].appendChild(html[0]) else element.append(html) # Update the path tree with the new node parentPathNode = util.getPathNode(element[0]) newPathNode = util.createPathTree html[0], parentPathNode, true siblings = parentPathNode.children parentPathNode.children = (siblings[0...relativePath[0]].concat [newPathNode]).concat siblings[relativePath[0]...siblings.length] deleteNode = (element, path) -> # Recursively skip to the end of the path if path.length > 1 deleteNode element.contents().eq(path[0]), path[1..path.length] if path.length == 1 # First remove the node from the path tree toRemove = element.contents().eq(path[0]) parentPathNode = util.getPathNode element[0] toRemovePathNode = util.getPathNode toRemove[0], parentPathNode childIndex = parentPathNode.children.indexOf toRemovePathNode parentPathNode.children.splice childIndex, 1 # Now remove the node from the DOM toRemove.remove() root.ot2dom.applyOp = applyOp
[ { "context": "ly,\n subdomain: 'academy'\n auth:\n username: 'JSSolutions'\n password: 'projectx'\n inputToken: 'd88ea45c", "end": 85, "score": 0.9994722604751587, "start": 74, "tag": "USERNAME", "value": "JSSolutions" }, { "context": " auth:\n username: 'JSSolutions'\n ...
app/server/bootstrap/winston.coffee
JSSolutions-Academy/Team-A
0
Winston.add Winston_Loggly, subdomain: 'academy' auth: username: 'JSSolutions' password: 'projectx' inputToken: 'd88ea45c-3798-4816-800c-f1cb81644df9' json: true handleExceptions: true Winston.info 'Added winston loggly transport'
129702
Winston.add Winston_Loggly, subdomain: 'academy' auth: username: 'JSSolutions' password: '<PASSWORD>' inputToken: '<PASSWORD>' json: true handleExceptions: true Winston.info 'Added winston loggly transport'
true
Winston.add Winston_Loggly, subdomain: 'academy' auth: username: 'JSSolutions' password: 'PI:PASSWORD:<PASSWORD>END_PI' inputToken: 'PI:PASSWORD:<PASSWORD>END_PI' json: true handleExceptions: true Winston.info 'Added winston loggly transport'
[ { "context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#", "end": 166, "score": 0.9917707443237305, "start": 152, "tag": "USERNAME", "value": "programmfabrik" }, { "context": "tControl\n\t\t\tuser_control: tru...
demo/src/demos/Playground.coffee
programmfabrik/coffeescript-ui
10
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### class Demo.Playground extends Demo getGroup: -> "" getName: -> "Playground" getButtons: (opts ={}) -> @getElements(CUI.Button, opts, [ text: "Button" , disabled: true text: "Disabled" , switch: true active: true text: "Switch" , switch: true disabled: true active: true text: "Disabled & Active" , primary: true text: "Primary" ]) getOptions: (opts = {}) -> @getElements(CUI.Options, opts, [ min_checked: 0 options: [ text: "One" , disabled: true text: "Two" , text: "Three" ] ])[0] getLabel: (opts = {}) -> label = @getElements(CUI.Label, opts, [{}])[0] label getMultiLabel: -> @getLabel( multiline: true text: Playground.longText ) getElements: (cls, opts={}, ele_opts) -> elements = [] for ele_opt in ele_opts copy_opts = CUI.util.copyObject(opts, true) for k, v of ele_opt if not copy_opts.hasOwnProperty(k) copy_opts[k] = v elements.push(new cls(copy_opts)) elements getLayoutTab: -> hl = new CUI.HorizontalLayout left: flexHandle: hidden: false content: CUI.dom.text("Left Side") center: {} right: flexHandle: hidden: false content: new CUI.SimplePane header_center: new CUI.Label(text: "CUI.SimplePane") header_right: icon: "close" content: new CUI.Label(text: "Content") footer_right: text: "Ok" treeDemo = new Demo.ListViewTreeDemo() tree = new CUI.ListViewTree cols: ["auto", "maximize", "auto", "auto"] fixedRows: 1 fixedCols: 1 root: new Demo.ListViewTreeDemoNode(demo: treeDemo) selectable: true hl.replace(tree.render(), "left") tree.appendRow(new Demo.ListViewTreeDemoHeaderNode()) tree.root.open() shc = new CUI.StickyHeaderControl(element: hl.center()) sticky_flow = [] for i in [0...10] sticky_flow.push(new CUI.StickyHeader(text: "Header "+i, level: 0, control: shc)) for j in [0..Math.ceil(Math.random()*10)] sticky_flow.push(@getMultiLabel()) if Math.random() > 0.7 sticky_flow.push(new CUI.StickyHeader(level: 1, text: "Sub-Header", control: shc)) hl.append(sticky_flow, "center") hl getLayerTab: -> dt = new Demo.DemoTable() dt.addExample("Buttons", new CUI.Buttonbar(buttons: @getButtons()) ) dt.addExample("Layer", new CUI.Buttonbar(buttons: [ text: "Popover" onClick: (ev, btn) => pop = new CUI.Popover element: btn cancel: true pane: header_left: new CUI.Label(text: "Popover") content: new CUI.MultilineLabel markdown: true text: """# Markdown\n\nYo Test Test""" footer_right: text: "Ok" onClick: => pop.destroy() pop.show() , text: "Popover (Blur)" onClick: (ev, btn) => pop = new CUI.Popover element: btn placement: "n" placements: ["n"] # force north, so we see the blur effect cancel: true backdrop: policy: "click-thru" blur: true pane: header_left: new CUI.Label(text: "Popover") content: new CUI.MultilineLabel markdown: true text: """# Markdown\n\nYo Test Test""" footer_right: text: "Ok" onClick: => pop.destroy() pop.show() , text: "Modal" onClick: (ev, btn) => mod = new CUI.Modal # element: btn cancel: true pane: header_left: new CUI.Label(text: "Modal") content: new CUI.MultilineLabel markdown: true text: """# Markdown\n\nYo Test Test""" footer_right: text: "Ok" primary: true onClick: => mod.destroy() mod.show() ]) ) dt.addExample("Tooltip", new CUI.Buttonbar(buttons: [ text: "Tooltip (Short)" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text" on_click: false on_hover: false .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Tooltip (Long)" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: Playground.longText on_click: false on_hover: false .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Placement West" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text" on_click: false on_hover: false placement: "w" .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Placement East" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text" on_click: false on_hover: false placement: "e" .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Placement SW" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text Tooltip with short Text" on_click: false on_hover: false placement: "sw" .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) ]) ) dt.addExample("Confirmations", new CUI.Buttonbar(buttons: [ text: "CUI.alert" onClick: => CUI.alert( title: "Alert" text: "Alert!" ) , text: "CUI.toaster" onClick: => ms = 3000 steps = 100 toaster = CUI.toaster show_ms: ms text: "Toaster 100!" c = 0 counter = => c = c + 1 CUI.setTimeout ms: ms / steps call: => toaster.setText("Toaster! "+(steps-c)) if c < steps counter() counter() , text: "CUI.problem" onClick: => CUI.problem( title: "Problem" text: "This is going to be a problem!" ) , text: "CUI.confirm" onClick: => CUI.confirm( title: "Confirmation" text: "Yes or No?" ) , text: "CUI.prompt" onClick: => CUI.prompt( title: "Question" text: "What's your name?" ) ]) ) dt.table getFormsTab: -> form = new CUI.Form fields: [ form: label: "Output" type: CUI.Output text: "Output" , form: label: "Input" type: CUI.Input placeholder: "Placeholder" , form: label: "Textarea (Wide)" use_field_as_label: true type: CUI.Input textarea: true placeholder: "Long CUI.Output" , form: label: "Options (Horizontal)" type: CUI.Options horizontal: true options: @getNumberOptions((v) -> text: ""+v, value: v) , form: label: "Options (Horizontal 4)" type: CUI.Options horizontal: 4 options: @getNumberOptions((v) -> text: ""+v, value: v) , form: label: "Form (Horizontal)" type: CUI.Form horizontal: true fields: => fields = [] for i in [0..10] fields.push type: CUI.Checkbox text: "H "+i fields , form: label: "Form (Horizontal 4)" type: CUI.Form horizontal: 4 fields: => fields = [] for i in [0..10] fields.push type: CUI.Checkbox text: "H4 - "+i fields , form: label: "Inline Form" type: CUI.Form fields: => fields = [] for i in [0..10] if i % 4 == 0 fields.push type: CUI.Form fields: ({ type: CUI.Input form: label: "Inner Input "+i } for i in [0..5]) else if i % 7 == 0 fields.push type: CUI.Form fields: ({ type: CUI.Input } for i in [0..5]) else fields.push type: CUI.Input form: label: "Input "+i fields ] form.start() getNumberOptions: (func) -> opts = [] for i in [100..120] opts.push(func(i)) opts getInputsTab: -> fields = [] multi_input_control = new CUI.MultiInputControl user_control: true preferred_key: "de-DE" keys: [ name: "de-DE" tag: "DE" enabled: true tooltip: text: "de-DE" , name: "en-US" tag: "EN" tooltip: text: "en-US" , name: "fr-FR" tag: "FR" tooltip: text: "fr-FR" ] data = input: "" textarea: "" password: "" options_sorted: [2,4] table: [] select: 21 select_mini: 5 data_table: [ a: "Henk" b: true , a: "Henk 1" b: true , a: "Henk 2" b: false ] data_table_sortable: [ a: "Thomas" b: true , a: "Henk" b: false , a: "Torsten" b: true ] fields.push @getOptions( form: label: "Options [Radio]" radio: true ) fields.push @getOptions( form: label: "Options [Checkbox]" radio: false ) fields.push @getOptions( form: label: "Options [Sortable]" radio: false options: [ text: "One" value: 1 , text: "Two" value: 2 , text: "Three" value: 3 , text: "Four" value: 4 , text: "Five" value: 5 , text: "Six" value: 6 ] name: "options_sorted" sortable: true sortable_hint: "Sort checked options, unchecked are sorted alphabetically" ) fields.push @getOptions( form: label: "Options [Horizontal]" radio: true horizontal: true ) fields.push new CUI.Input form: label: "Input" name: "input" placeholder: "CUI.Input" fields.push new CUI.Input form: label: "Input [Content-Size]" name: "input" content_size: true fields.push new CUI.Input form: label: "Input [Textarea]" name: "textarea" textarea: true placeholder: "CUI.Input [Textarea]" fields.push new CUI.Input form: label: "Input [Textarea | Content-Size]" name: "textarea" textarea: true content_size: true placeholder: "CUI.Input [Textarea | Content-Size]" last_tooltip = null fields.push new CUI.Slider form: label: "Slider" name: "slider" min: 1 max: 1000 value: 300 onDragging: (slider, value) => last_tooltip = new CUI.Tooltip on_hover: false text: value+'' element: slider.getHandle() .show() onDrop: => last_tooltip?.hideTimeout() onUpdate: (slider, value) => console.info("CUI.Slider: New value:", value) fields.push new CUI.Output form: label: "Output" text: "Simple CUI.Output" fields.push new CUI.Password form: label: "Input [Password]" name: "password" fields.push new CUI.MultiInput name: "MultiInput" form: label: "MultiInput" spellcheck: true control: multi_input_control fields.push new CUI.MultiInput name: "MultiInputTextarea" form: label: "MultiInput [Textarea]" spellcheck: true textarea: true control: multi_input_control fields.push new CUI.DateTime form: label: "DateTime" select_opts = [] icons = ["", "play", "audio", "left", "right"] for i in [0...100] if i % 20 == 0 select_opts.push divider: true else if i % 10 == 0 select_opts.push label: text: "Label "+i else select_opts.push text: "Opt "+(i+1) value: i icon: icons[Math.floor(Math.random()*4)] fields.push new CUI.Select form: label: "Select" name: "select" options: select_opts select_mini_opts = [] for i in [0...10] select_mini_opts.push text: "Mini "+(i+1) value: i fields.push new CUI.Select form: label: "Select" name: "select_mini" options: select_mini_opts fields.push new CUI.DataTable name: "table" form: label: "DataTable" name: "data_table" fields: [ form: label: "Column A" type: CUI.Input name: "a" , form: label: "Column B" type: CUI.Checkbox text: "Checkbox" name: "b" ] fields.push new CUI.DataTable name: "table" rowMove: true name: "data_table_sortable" form: label: "DataTable [sortable]" fields: [ form: label: "Column A" type: CUI.Input name: "a" , form: rotate_90: true label: "Column B" type: CUI.Checkbox text: "Checkbox" name: "b" ] form = [ new CUI.Form(data: data, maximize: false, fields: fields).start() ] getTableTab: -> ttab = new Demo.DemoTable() table = @getTableDefault() ttab.addExample("Default Table with Border", table) table = @getTableDefaultNoBorder() ttab.addExample("Default Table with no border", table) table = @getTableZebra() ttab.addExample("Zebra Table maximized", table) table = @getTableKeyvalue() ttab.addExample("Flex Table with Border and key/value", table) getTableZebra: -> table = new CUI.Table class: 'cui-maximize-horizontal cui-demo-table-zebra' columns: [ name: "a" text: "alpha" class: "a-class" , name: "b" text: "beta" class: "b-class" , name: "c" text: "gamma" class: "c-class" , name: "d" text: "delta" class: "d-class" ] rows: [ a: "a0" b: "b0" c: "Hello" d: "world" , a: "a1" b: "b1" c: "how" d: "are you" ] for i in [2..5] table.addRow a: "a"+i b: "b"+i table getTableDefault: -> table = new CUI.Table columns: [ name: "a" text: "alpha" class: "a-class" , name: "b" text: "beta" class: "b-class" , name: "c" text: "gamma" class: "c-class" , name: "d" text: "delta" class: "d-class" ] rows: [ a: "a0" b: "b0" c: "Hello" d: "world" , a: "a1" b: "b1" c: "how" d: "are you" ] for i in [2..5] table.addRow a: "a"+i b: "b"+i table getTableDefaultNoBorder: -> table = new CUI.Table class: 'cui-maximize-horizontal cui-demo-table-no-border' columns: [ name: "a" text: "alpha" class: "a-class" , name: "b" text: "beta" class: "b-class" , name: "c" text: "gamma" class: "c-class" , name: "d" text: "delta" class: "d-class" ] rows: [ a: "a0" b: "b0" c: "Hello" d: "world" , a: "a1" b: "b1" c: "how" d: "are you" ] for i in [2..5] table.addRow a: "a"+i b: "b"+i table getTableKeyvalue: -> table = new CUI.Table flex: true key_value: true someInfoData = [ key: "compiled" value: "pdf document, 3 pages, 727.5 kB" , key: "compiled_create_date" value: "1489755602.23" , key: "compiled_create_date_iso8601" value: "2017-03-17 T13:00:02+00:00" , key: "compiled_create_date_source" value: "m" , key: "extension" value: "pdf" , key: "fileclass" value: "office" ] for info in someInfoData table.addRow key: info.key value: info.value table getControlsTab: -> fu = new CUI.FileUpload url: "FileUpload.php" controls = [ new CUI.Block text: "Buttons" content: [ new CUI.Buttonbar(buttons: @getButtons()) , new CUI.Buttonbar(buttons: @getButtons(group: "A")) , new CUI.Buttonbar(buttons: @getButtons(appearance: "flat")) , new CUI.Buttonbar(buttons: @getButtons(icon: "refresh")) , new CUI.Buttonbar(buttons: @getButtons(icon: "play", appearance: "flat")) , new CUI.Buttonbar(buttons: [ new CUI.FileUploadButton icon: "upload" fileUpload: fu text: "File Upload" , new CUI.ButtonHref icon: "share" href: "https://www.programmfabrik.de" target: "_blank" text: "www.programmfabrik.de" ]) , new CUI.Buttonbar(buttons: [ new CUI.FileUploadButton appearance: "flat" fileUpload: fu text: "File Upload" , new CUI.ButtonHref appearance: "flat" href: "https://www.programmfabrik.de" target: "_blank" text: "www.programmfabrik.de" ]) ] , new CUI.Block text: "Labels" content: [ @getLabel(text: "Simple") , @getLabel(markdown: true, text: "Simple **Markdown**") , new CUI.EmptyLabel(text: "Empty Label") , @getMultiLabel() ] , new CUI.Panel text: "Panel Test" content: @getMultiLabel() ] getIconsTab: -> dt = new Demo.DemoTable() # Font Awesome Icons icons = ["play", "fa-angle-left", "fa-angle-right", "fa-angle-up", "fa-angle-down", "fa-angle-double-up", "fa-angle-double-down"] dt.addExample("Single Icon", new CUI.Block class: "cui-demo-icons" text: "Font Awesome icons that are customized" content: @getIconCollection(icons) ) # All Font Awesome Icons icons = [ "fa-crop", "fa-arrows-alt", "fa-warning", "fa-slack", "fa-file", "fa-filter", "fa-sliders", "fa-refresh", "fa fa-file-archive-o", "fa-rotate-right", "fa-rotate-left", "fa-arrows-v", "fa-arrows-h", "fa-calendar-plus-o", "fa-question", "fa-question", "fa-question", "fa-cog", "fa-download", "fa-download", "fa-question", "fa-upload", "fa-envelope-o", "fa-envelope", "fa-floppy-o", "fa-heart", "fa-user", "fa-clock-o", "fa-plus", "fa-pencil", "fa-files-o", "fa-search", "fa-share", "fa-play", "fa-music", "fa-play", "fa-stop", "fa-print", "fa-minus", "fa-caret-right", "fa-caret-down", "fa-ellipsis-h", "fa-ellipsis-v", "fa-bars", "fa-info-circle", "fa-bolt", "fa-check", "fa-warning", "fa-legal", "fa-cloud", "fa-angle-left", "fa-angle-right", "fa-angle-right", "fa-search-plus", "fa-search-minus", "fa-compress", "fa-expand", "fa-envelope-o", "fa-file-text", "fa-file-text-o", "fa-bullhorn", "fa-angle-left", "fa-angle-right", "fa-angle-down", "fa-angle-up", "fa-caret-up", "fa-caret-down", "fa-camera", "fa-list-ul", "fa-picture-o", "fa-sitemap", "fa-hourglass-half", ] dt.addExample("Single Icon", new CUI.Block class: "cui-demo-icons" text: "All Font Awesome icons" content: @getIconCollection(icons) ) # SVG Icons icons = [ "svg-arrow-right", "svg-close", "svg-drupal", "svg-easydb", "svg-external-link", "svg-falcon-io", "svg-folder-shared-upload", "svg-folder-shared", "svg-folder-upload", "svg-folder", "svg-grid", "svg-hierarchy", "svg-info-circle", "svg-multiple", "svg-popup", "svg-reset", "svg-rows", "svg-select-all", "svg-select-pages", "svg-spinner", "svg-table", "svg-tag-o", "svg-trash", "svg-typo3", "svg-easydb", "svg-fylr-logo", ] dt.addExample("Single Icon", new CUI.Block class: "cui-demo-icons" text: "SVG icons" content: @getIconCollection(icons) ) asset_icons = [ "svg-asset-failed", ] dt.addExample("Asset Icons", new CUI.Block class: "cui-demo-icons cui-demo-asset-icons" text: "Asset icons" content: @getIconCollection(asset_icons) ) dt.addExample("Icon in Buttons", new CUI.Buttonbar(buttons: @getButtons(icon: "download")) ) dt.addExample("SVG Spinner", new CUI.Label text: "Label" icon: "spinner" ) dt.addExample("FA Spinner", new CUI.Label text: "Label" icon: "fa-spinner" ) dt.addExample("Hourglass spinner", new CUI.Block class: "cui-demo-hourglass" content: @getHourglassIcon() ) dt.addExample("Times Thin, regular font icon (not FA)", new CUI.Label text: "Close" icon: "fa-times-thin" ) getHourglassIcon: -> hourglass_icons = [ "fa-hourglass-start" "fa-hourglass-half" "fa-hourglass-end" "fa-hourglass-end" "fa-hourglass-o" ] hourglass_container = CUI.dom.div("cui-hourglass-animation fa-stack") for i in hourglass_icons icon = new CUI.Icon icon: i class: "fa-stack-1x" CUI.dom.append(hourglass_container, icon.DOM) hourglass_container getIconCollection: (icons = []) -> icon_container = CUI.dom.div("cui-demo-icon-container") for i in icons icon_wrap = CUI.dom.div("cui-demo-icon") icon = new CUI.Icon icon: i new CUI.Tooltip element: icon_wrap show_ms: 1000 hide_ms: 200 text: i CUI.dom.append(icon_wrap, icon.DOM) CUI.dom.append(icon_container, icon_wrap) icon_container display: -> tabs = new CUI.Tabs maximize: true tabs: [ text: "Controls" content: @getControlsTab() class: "cui-demo-playground-tab-control" , text: "Inputs" content: @getInputsTab() , text: "Forms" content: @getFormsTab() , text: "Layer" content: @getLayerTab() , text: "Layout" content: @getLayoutTab() , text: "Table" content: @getTableTab() , text: "Icons" content: @getIconsTab() ] md = new Demo.MenuDemo() md.listenOnNode(tabs) tabs @longText: """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.""" Demo.register(new Demo.Playground())
44803
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### class Demo.Playground extends Demo getGroup: -> "" getName: -> "Playground" getButtons: (opts ={}) -> @getElements(CUI.Button, opts, [ text: "Button" , disabled: true text: "Disabled" , switch: true active: true text: "Switch" , switch: true disabled: true active: true text: "Disabled & Active" , primary: true text: "Primary" ]) getOptions: (opts = {}) -> @getElements(CUI.Options, opts, [ min_checked: 0 options: [ text: "One" , disabled: true text: "Two" , text: "Three" ] ])[0] getLabel: (opts = {}) -> label = @getElements(CUI.Label, opts, [{}])[0] label getMultiLabel: -> @getLabel( multiline: true text: Playground.longText ) getElements: (cls, opts={}, ele_opts) -> elements = [] for ele_opt in ele_opts copy_opts = CUI.util.copyObject(opts, true) for k, v of ele_opt if not copy_opts.hasOwnProperty(k) copy_opts[k] = v elements.push(new cls(copy_opts)) elements getLayoutTab: -> hl = new CUI.HorizontalLayout left: flexHandle: hidden: false content: CUI.dom.text("Left Side") center: {} right: flexHandle: hidden: false content: new CUI.SimplePane header_center: new CUI.Label(text: "CUI.SimplePane") header_right: icon: "close" content: new CUI.Label(text: "Content") footer_right: text: "Ok" treeDemo = new Demo.ListViewTreeDemo() tree = new CUI.ListViewTree cols: ["auto", "maximize", "auto", "auto"] fixedRows: 1 fixedCols: 1 root: new Demo.ListViewTreeDemoNode(demo: treeDemo) selectable: true hl.replace(tree.render(), "left") tree.appendRow(new Demo.ListViewTreeDemoHeaderNode()) tree.root.open() shc = new CUI.StickyHeaderControl(element: hl.center()) sticky_flow = [] for i in [0...10] sticky_flow.push(new CUI.StickyHeader(text: "Header "+i, level: 0, control: shc)) for j in [0..Math.ceil(Math.random()*10)] sticky_flow.push(@getMultiLabel()) if Math.random() > 0.7 sticky_flow.push(new CUI.StickyHeader(level: 1, text: "Sub-Header", control: shc)) hl.append(sticky_flow, "center") hl getLayerTab: -> dt = new Demo.DemoTable() dt.addExample("Buttons", new CUI.Buttonbar(buttons: @getButtons()) ) dt.addExample("Layer", new CUI.Buttonbar(buttons: [ text: "Popover" onClick: (ev, btn) => pop = new CUI.Popover element: btn cancel: true pane: header_left: new CUI.Label(text: "Popover") content: new CUI.MultilineLabel markdown: true text: """# Markdown\n\nYo Test Test""" footer_right: text: "Ok" onClick: => pop.destroy() pop.show() , text: "Popover (Blur)" onClick: (ev, btn) => pop = new CUI.Popover element: btn placement: "n" placements: ["n"] # force north, so we see the blur effect cancel: true backdrop: policy: "click-thru" blur: true pane: header_left: new CUI.Label(text: "Popover") content: new CUI.MultilineLabel markdown: true text: """# Markdown\n\nYo Test Test""" footer_right: text: "Ok" onClick: => pop.destroy() pop.show() , text: "Modal" onClick: (ev, btn) => mod = new CUI.Modal # element: btn cancel: true pane: header_left: new CUI.Label(text: "Modal") content: new CUI.MultilineLabel markdown: true text: """# Markdown\n\nYo Test Test""" footer_right: text: "Ok" primary: true onClick: => mod.destroy() mod.show() ]) ) dt.addExample("Tooltip", new CUI.Buttonbar(buttons: [ text: "Tooltip (Short)" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text" on_click: false on_hover: false .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Tooltip (Long)" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: Playground.longText on_click: false on_hover: false .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Placement West" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text" on_click: false on_hover: false placement: "w" .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Placement East" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text" on_click: false on_hover: false placement: "e" .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Placement SW" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text Tooltip with short Text" on_click: false on_hover: false placement: "sw" .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) ]) ) dt.addExample("Confirmations", new CUI.Buttonbar(buttons: [ text: "CUI.alert" onClick: => CUI.alert( title: "Alert" text: "Alert!" ) , text: "CUI.toaster" onClick: => ms = 3000 steps = 100 toaster = CUI.toaster show_ms: ms text: "Toaster 100!" c = 0 counter = => c = c + 1 CUI.setTimeout ms: ms / steps call: => toaster.setText("Toaster! "+(steps-c)) if c < steps counter() counter() , text: "CUI.problem" onClick: => CUI.problem( title: "Problem" text: "This is going to be a problem!" ) , text: "CUI.confirm" onClick: => CUI.confirm( title: "Confirmation" text: "Yes or No?" ) , text: "CUI.prompt" onClick: => CUI.prompt( title: "Question" text: "What's your name?" ) ]) ) dt.table getFormsTab: -> form = new CUI.Form fields: [ form: label: "Output" type: CUI.Output text: "Output" , form: label: "Input" type: CUI.Input placeholder: "Placeholder" , form: label: "Textarea (Wide)" use_field_as_label: true type: CUI.Input textarea: true placeholder: "Long CUI.Output" , form: label: "Options (Horizontal)" type: CUI.Options horizontal: true options: @getNumberOptions((v) -> text: ""+v, value: v) , form: label: "Options (Horizontal 4)" type: CUI.Options horizontal: 4 options: @getNumberOptions((v) -> text: ""+v, value: v) , form: label: "Form (Horizontal)" type: CUI.Form horizontal: true fields: => fields = [] for i in [0..10] fields.push type: CUI.Checkbox text: "H "+i fields , form: label: "Form (Horizontal 4)" type: CUI.Form horizontal: 4 fields: => fields = [] for i in [0..10] fields.push type: CUI.Checkbox text: "H4 - "+i fields , form: label: "Inline Form" type: CUI.Form fields: => fields = [] for i in [0..10] if i % 4 == 0 fields.push type: CUI.Form fields: ({ type: CUI.Input form: label: "Inner Input "+i } for i in [0..5]) else if i % 7 == 0 fields.push type: CUI.Form fields: ({ type: CUI.Input } for i in [0..5]) else fields.push type: CUI.Input form: label: "Input "+i fields ] form.start() getNumberOptions: (func) -> opts = [] for i in [100..120] opts.push(func(i)) opts getInputsTab: -> fields = [] multi_input_control = new CUI.MultiInputControl user_control: true preferred_key: "<KEY>" keys: [ name: "de-DE" tag: "DE" enabled: true tooltip: text: "de-DE" , name: "en-US" tag: "EN" tooltip: text: "en-US" , name: "fr-FR" tag: "FR" tooltip: text: "fr-FR" ] data = input: "" textarea: "" password: "" options_sorted: [2,4] table: [] select: 21 select_mini: 5 data_table: [ a: "<NAME>" b: true , a: "<NAME>" b: true , a: "<NAME>" b: false ] data_table_sortable: [ a: "<NAME>" b: true , a: "<NAME>" b: false , a: "<NAME>" b: true ] fields.push @getOptions( form: label: "Options [Radio]" radio: true ) fields.push @getOptions( form: label: "Options [Checkbox]" radio: false ) fields.push @getOptions( form: label: "Options [Sortable]" radio: false options: [ text: "One" value: 1 , text: "Two" value: 2 , text: "Three" value: 3 , text: "Four" value: 4 , text: "Five" value: 5 , text: "Six" value: 6 ] name: "options_sorted" sortable: true sortable_hint: "Sort checked options, unchecked are sorted alphabetically" ) fields.push @getOptions( form: label: "Options [Horizontal]" radio: true horizontal: true ) fields.push new CUI.Input form: label: "Input" name: "input" placeholder: "CUI.Input" fields.push new CUI.Input form: label: "Input [Content-Size]" name: "input" content_size: true fields.push new CUI.Input form: label: "Input [Textarea]" name: "textarea" textarea: true placeholder: "CUI.Input [Textarea]" fields.push new CUI.Input form: label: "Input [Textarea | Content-Size]" name: "textarea" textarea: true content_size: true placeholder: "CUI.Input [Textarea | Content-Size]" last_tooltip = null fields.push new CUI.Slider form: label: "Slider" name: "slider" min: 1 max: 1000 value: 300 onDragging: (slider, value) => last_tooltip = new CUI.Tooltip on_hover: false text: value+'' element: slider.getHandle() .show() onDrop: => last_tooltip?.hideTimeout() onUpdate: (slider, value) => console.info("CUI.Slider: New value:", value) fields.push new CUI.Output form: label: "Output" text: "Simple CUI.Output" fields.push new CUI.Password form: label: "Input [Password]" name: "password" fields.push new CUI.MultiInput name: "MultiInput" form: label: "MultiInput" spellcheck: true control: multi_input_control fields.push new CUI.MultiInput name: "MultiInputTextarea" form: label: "MultiInput [Textarea]" spellcheck: true textarea: true control: multi_input_control fields.push new CUI.DateTime form: label: "DateTime" select_opts = [] icons = ["", "play", "audio", "left", "right"] for i in [0...100] if i % 20 == 0 select_opts.push divider: true else if i % 10 == 0 select_opts.push label: text: "Label "+i else select_opts.push text: "Opt "+(i+1) value: i icon: icons[Math.floor(Math.random()*4)] fields.push new CUI.Select form: label: "Select" name: "select" options: select_opts select_mini_opts = [] for i in [0...10] select_mini_opts.push text: "Mini "+(i+1) value: i fields.push new CUI.Select form: label: "Select" name: "select_mini" options: select_mini_opts fields.push new CUI.DataTable name: "table" form: label: "DataTable" name: "data_table" fields: [ form: label: "Column A" type: CUI.Input name: "a" , form: label: "Column B" type: CUI.Checkbox text: "Checkbox" name: "b" ] fields.push new CUI.DataTable name: "table" rowMove: true name: "data_table_sortable" form: label: "DataTable [sortable]" fields: [ form: label: "Column A" type: CUI.Input name: "a" , form: rotate_90: true label: "Column B" type: CUI.Checkbox text: "Checkbox" name: "b" ] form = [ new CUI.Form(data: data, maximize: false, fields: fields).start() ] getTableTab: -> ttab = new Demo.DemoTable() table = @getTableDefault() ttab.addExample("Default Table with Border", table) table = @getTableDefaultNoBorder() ttab.addExample("Default Table with no border", table) table = @getTableZebra() ttab.addExample("Zebra Table maximized", table) table = @getTableKeyvalue() ttab.addExample("Flex Table with Border and key/value", table) getTableZebra: -> table = new CUI.Table class: 'cui-maximize-horizontal cui-demo-table-zebra' columns: [ name: "a" text: "alpha" class: "a-class" , name: "b" text: "beta" class: "b-class" , name: "c" text: "gamma" class: "c-class" , name: "d" text: "delta" class: "d-class" ] rows: [ a: "a0" b: "b0" c: "Hello" d: "world" , a: "a1" b: "b1" c: "how" d: "are you" ] for i in [2..5] table.addRow a: "a"+i b: "b"+i table getTableDefault: -> table = new CUI.Table columns: [ name: "a" text: "alpha" class: "a-class" , name: "b" text: "beta" class: "b-class" , name: "c" text: "gamma" class: "c-class" , name: "d" text: "delta" class: "d-class" ] rows: [ a: "a0" b: "b0" c: "Hello" d: "world" , a: "a1" b: "b1" c: "how" d: "are you" ] for i in [2..5] table.addRow a: "a"+i b: "b"+i table getTableDefaultNoBorder: -> table = new CUI.Table class: 'cui-maximize-horizontal cui-demo-table-no-border' columns: [ name: "a" text: "alpha" class: "a-class" , name: "b" text: "beta" class: "b-class" , name: "c" text: "gamma" class: "c-class" , name: "d" text: "delta" class: "d-class" ] rows: [ a: "a0" b: "b0" c: "Hello" d: "world" , a: "a1" b: "b1" c: "how" d: "are you" ] for i in [2..5] table.addRow a: "a"+i b: "b"+i table getTableKeyvalue: -> table = new CUI.Table flex: true key_value: true someInfoData = [ key: "compiled" value: "pdf document, 3 pages, 727.5 kB" , key: "compiled_create_date" value: "1489755602.23" , key: "compiled_create_date_iso8601" value: "2017-03-17 T13:00:02+00:00" , key: "compiled_create_date_source" value: "m" , key: "extension" value: "pdf" , key: "fileclass" value: "office" ] for info in someInfoData table.addRow key: info.key value: info.value table getControlsTab: -> fu = new CUI.FileUpload url: "FileUpload.php" controls = [ new CUI.Block text: "Buttons" content: [ new CUI.Buttonbar(buttons: @getButtons()) , new CUI.Buttonbar(buttons: @getButtons(group: "A")) , new CUI.Buttonbar(buttons: @getButtons(appearance: "flat")) , new CUI.Buttonbar(buttons: @getButtons(icon: "refresh")) , new CUI.Buttonbar(buttons: @getButtons(icon: "play", appearance: "flat")) , new CUI.Buttonbar(buttons: [ new CUI.FileUploadButton icon: "upload" fileUpload: fu text: "File Upload" , new CUI.ButtonHref icon: "share" href: "https://www.programmfabrik.de" target: "_blank" text: "www.programmfabrik.de" ]) , new CUI.Buttonbar(buttons: [ new CUI.FileUploadButton appearance: "flat" fileUpload: fu text: "File Upload" , new CUI.ButtonHref appearance: "flat" href: "https://www.programmfabrik.de" target: "_blank" text: "www.programmfabrik.de" ]) ] , new CUI.Block text: "Labels" content: [ @getLabel(text: "Simple") , @getLabel(markdown: true, text: "Simple **Markdown**") , new CUI.EmptyLabel(text: "Empty Label") , @getMultiLabel() ] , new CUI.Panel text: "Panel Test" content: @getMultiLabel() ] getIconsTab: -> dt = new Demo.DemoTable() # Font Awesome Icons icons = ["play", "fa-angle-left", "fa-angle-right", "fa-angle-up", "fa-angle-down", "fa-angle-double-up", "fa-angle-double-down"] dt.addExample("Single Icon", new CUI.Block class: "cui-demo-icons" text: "Font Awesome icons that are customized" content: @getIconCollection(icons) ) # All Font Awesome Icons icons = [ "fa-crop", "fa-arrows-alt", "fa-warning", "fa-slack", "fa-file", "fa-filter", "fa-sliders", "fa-refresh", "fa fa-file-archive-o", "fa-rotate-right", "fa-rotate-left", "fa-arrows-v", "fa-arrows-h", "fa-calendar-plus-o", "fa-question", "fa-question", "fa-question", "fa-cog", "fa-download", "fa-download", "fa-question", "fa-upload", "fa-envelope-o", "fa-envelope", "fa-floppy-o", "fa-heart", "fa-user", "fa-clock-o", "fa-plus", "fa-pencil", "fa-files-o", "fa-search", "fa-share", "fa-play", "fa-music", "fa-play", "fa-stop", "fa-print", "fa-minus", "fa-caret-right", "fa-caret-down", "fa-ellipsis-h", "fa-ellipsis-v", "fa-bars", "fa-info-circle", "fa-bolt", "fa-check", "fa-warning", "fa-legal", "fa-cloud", "fa-angle-left", "fa-angle-right", "fa-angle-right", "fa-search-plus", "fa-search-minus", "fa-compress", "fa-expand", "fa-envelope-o", "fa-file-text", "fa-file-text-o", "fa-bullhorn", "fa-angle-left", "fa-angle-right", "fa-angle-down", "fa-angle-up", "fa-caret-up", "fa-caret-down", "fa-camera", "fa-list-ul", "fa-picture-o", "fa-sitemap", "fa-hourglass-half", ] dt.addExample("Single Icon", new CUI.Block class: "cui-demo-icons" text: "All Font Awesome icons" content: @getIconCollection(icons) ) # SVG Icons icons = [ "svg-arrow-right", "svg-close", "svg-drupal", "svg-easydb", "svg-external-link", "svg-falcon-io", "svg-folder-shared-upload", "svg-folder-shared", "svg-folder-upload", "svg-folder", "svg-grid", "svg-hierarchy", "svg-info-circle", "svg-multiple", "svg-popup", "svg-reset", "svg-rows", "svg-select-all", "svg-select-pages", "svg-spinner", "svg-table", "svg-tag-o", "svg-trash", "svg-typo3", "svg-easydb", "svg-fylr-logo", ] dt.addExample("Single Icon", new CUI.Block class: "cui-demo-icons" text: "SVG icons" content: @getIconCollection(icons) ) asset_icons = [ "svg-asset-failed", ] dt.addExample("Asset Icons", new CUI.Block class: "cui-demo-icons cui-demo-asset-icons" text: "Asset icons" content: @getIconCollection(asset_icons) ) dt.addExample("Icon in Buttons", new CUI.Buttonbar(buttons: @getButtons(icon: "download")) ) dt.addExample("SVG Spinner", new CUI.Label text: "Label" icon: "spinner" ) dt.addExample("FA Spinner", new CUI.Label text: "Label" icon: "fa-spinner" ) dt.addExample("Hourglass spinner", new CUI.Block class: "cui-demo-hourglass" content: @getHourglassIcon() ) dt.addExample("Times Thin, regular font icon (not FA)", new CUI.Label text: "Close" icon: "fa-times-thin" ) getHourglassIcon: -> hourglass_icons = [ "fa-hourglass-start" "fa-hourglass-half" "fa-hourglass-end" "fa-hourglass-end" "fa-hourglass-o" ] hourglass_container = CUI.dom.div("cui-hourglass-animation fa-stack") for i in hourglass_icons icon = new CUI.Icon icon: i class: "fa-stack-1x" CUI.dom.append(hourglass_container, icon.DOM) hourglass_container getIconCollection: (icons = []) -> icon_container = CUI.dom.div("cui-demo-icon-container") for i in icons icon_wrap = CUI.dom.div("cui-demo-icon") icon = new CUI.Icon icon: i new CUI.Tooltip element: icon_wrap show_ms: 1000 hide_ms: 200 text: i CUI.dom.append(icon_wrap, icon.DOM) CUI.dom.append(icon_container, icon_wrap) icon_container display: -> tabs = new CUI.Tabs maximize: true tabs: [ text: "Controls" content: @getControlsTab() class: "cui-demo-playground-tab-control" , text: "Inputs" content: @getInputsTab() , text: "Forms" content: @getFormsTab() , text: "Layer" content: @getLayerTab() , text: "Layout" content: @getLayoutTab() , text: "Table" content: @getTableTab() , text: "Icons" content: @getIconsTab() ] md = new Demo.MenuDemo() md.listenOnNode(tabs) tabs @longText: """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.""" Demo.register(new Demo.Playground())
true
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### class Demo.Playground extends Demo getGroup: -> "" getName: -> "Playground" getButtons: (opts ={}) -> @getElements(CUI.Button, opts, [ text: "Button" , disabled: true text: "Disabled" , switch: true active: true text: "Switch" , switch: true disabled: true active: true text: "Disabled & Active" , primary: true text: "Primary" ]) getOptions: (opts = {}) -> @getElements(CUI.Options, opts, [ min_checked: 0 options: [ text: "One" , disabled: true text: "Two" , text: "Three" ] ])[0] getLabel: (opts = {}) -> label = @getElements(CUI.Label, opts, [{}])[0] label getMultiLabel: -> @getLabel( multiline: true text: Playground.longText ) getElements: (cls, opts={}, ele_opts) -> elements = [] for ele_opt in ele_opts copy_opts = CUI.util.copyObject(opts, true) for k, v of ele_opt if not copy_opts.hasOwnProperty(k) copy_opts[k] = v elements.push(new cls(copy_opts)) elements getLayoutTab: -> hl = new CUI.HorizontalLayout left: flexHandle: hidden: false content: CUI.dom.text("Left Side") center: {} right: flexHandle: hidden: false content: new CUI.SimplePane header_center: new CUI.Label(text: "CUI.SimplePane") header_right: icon: "close" content: new CUI.Label(text: "Content") footer_right: text: "Ok" treeDemo = new Demo.ListViewTreeDemo() tree = new CUI.ListViewTree cols: ["auto", "maximize", "auto", "auto"] fixedRows: 1 fixedCols: 1 root: new Demo.ListViewTreeDemoNode(demo: treeDemo) selectable: true hl.replace(tree.render(), "left") tree.appendRow(new Demo.ListViewTreeDemoHeaderNode()) tree.root.open() shc = new CUI.StickyHeaderControl(element: hl.center()) sticky_flow = [] for i in [0...10] sticky_flow.push(new CUI.StickyHeader(text: "Header "+i, level: 0, control: shc)) for j in [0..Math.ceil(Math.random()*10)] sticky_flow.push(@getMultiLabel()) if Math.random() > 0.7 sticky_flow.push(new CUI.StickyHeader(level: 1, text: "Sub-Header", control: shc)) hl.append(sticky_flow, "center") hl getLayerTab: -> dt = new Demo.DemoTable() dt.addExample("Buttons", new CUI.Buttonbar(buttons: @getButtons()) ) dt.addExample("Layer", new CUI.Buttonbar(buttons: [ text: "Popover" onClick: (ev, btn) => pop = new CUI.Popover element: btn cancel: true pane: header_left: new CUI.Label(text: "Popover") content: new CUI.MultilineLabel markdown: true text: """# Markdown\n\nYo Test Test""" footer_right: text: "Ok" onClick: => pop.destroy() pop.show() , text: "Popover (Blur)" onClick: (ev, btn) => pop = new CUI.Popover element: btn placement: "n" placements: ["n"] # force north, so we see the blur effect cancel: true backdrop: policy: "click-thru" blur: true pane: header_left: new CUI.Label(text: "Popover") content: new CUI.MultilineLabel markdown: true text: """# Markdown\n\nYo Test Test""" footer_right: text: "Ok" onClick: => pop.destroy() pop.show() , text: "Modal" onClick: (ev, btn) => mod = new CUI.Modal # element: btn cancel: true pane: header_left: new CUI.Label(text: "Modal") content: new CUI.MultilineLabel markdown: true text: """# Markdown\n\nYo Test Test""" footer_right: text: "Ok" primary: true onClick: => mod.destroy() mod.show() ]) ) dt.addExample("Tooltip", new CUI.Buttonbar(buttons: [ text: "Tooltip (Short)" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text" on_click: false on_hover: false .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Tooltip (Long)" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: Playground.longText on_click: false on_hover: false .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Placement West" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text" on_click: false on_hover: false placement: "w" .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Placement East" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text" on_click: false on_hover: false placement: "e" .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) , text: "Placement SW" switch: true activate_initial: false onActivate: (btn) => btn.___tt = new CUI.Tooltip element: btn text: "Tooltip with short Text Tooltip with short Text" on_click: false on_hover: false placement: "sw" .show() onDeactivate: (btn) => btn.___tt.destroy() delete(btn.___tt) ]) ) dt.addExample("Confirmations", new CUI.Buttonbar(buttons: [ text: "CUI.alert" onClick: => CUI.alert( title: "Alert" text: "Alert!" ) , text: "CUI.toaster" onClick: => ms = 3000 steps = 100 toaster = CUI.toaster show_ms: ms text: "Toaster 100!" c = 0 counter = => c = c + 1 CUI.setTimeout ms: ms / steps call: => toaster.setText("Toaster! "+(steps-c)) if c < steps counter() counter() , text: "CUI.problem" onClick: => CUI.problem( title: "Problem" text: "This is going to be a problem!" ) , text: "CUI.confirm" onClick: => CUI.confirm( title: "Confirmation" text: "Yes or No?" ) , text: "CUI.prompt" onClick: => CUI.prompt( title: "Question" text: "What's your name?" ) ]) ) dt.table getFormsTab: -> form = new CUI.Form fields: [ form: label: "Output" type: CUI.Output text: "Output" , form: label: "Input" type: CUI.Input placeholder: "Placeholder" , form: label: "Textarea (Wide)" use_field_as_label: true type: CUI.Input textarea: true placeholder: "Long CUI.Output" , form: label: "Options (Horizontal)" type: CUI.Options horizontal: true options: @getNumberOptions((v) -> text: ""+v, value: v) , form: label: "Options (Horizontal 4)" type: CUI.Options horizontal: 4 options: @getNumberOptions((v) -> text: ""+v, value: v) , form: label: "Form (Horizontal)" type: CUI.Form horizontal: true fields: => fields = [] for i in [0..10] fields.push type: CUI.Checkbox text: "H "+i fields , form: label: "Form (Horizontal 4)" type: CUI.Form horizontal: 4 fields: => fields = [] for i in [0..10] fields.push type: CUI.Checkbox text: "H4 - "+i fields , form: label: "Inline Form" type: CUI.Form fields: => fields = [] for i in [0..10] if i % 4 == 0 fields.push type: CUI.Form fields: ({ type: CUI.Input form: label: "Inner Input "+i } for i in [0..5]) else if i % 7 == 0 fields.push type: CUI.Form fields: ({ type: CUI.Input } for i in [0..5]) else fields.push type: CUI.Input form: label: "Input "+i fields ] form.start() getNumberOptions: (func) -> opts = [] for i in [100..120] opts.push(func(i)) opts getInputsTab: -> fields = [] multi_input_control = new CUI.MultiInputControl user_control: true preferred_key: "PI:KEY:<KEY>END_PI" keys: [ name: "de-DE" tag: "DE" enabled: true tooltip: text: "de-DE" , name: "en-US" tag: "EN" tooltip: text: "en-US" , name: "fr-FR" tag: "FR" tooltip: text: "fr-FR" ] data = input: "" textarea: "" password: "" options_sorted: [2,4] table: [] select: 21 select_mini: 5 data_table: [ a: "PI:NAME:<NAME>END_PI" b: true , a: "PI:NAME:<NAME>END_PI" b: true , a: "PI:NAME:<NAME>END_PI" b: false ] data_table_sortable: [ a: "PI:NAME:<NAME>END_PI" b: true , a: "PI:NAME:<NAME>END_PI" b: false , a: "PI:NAME:<NAME>END_PI" b: true ] fields.push @getOptions( form: label: "Options [Radio]" radio: true ) fields.push @getOptions( form: label: "Options [Checkbox]" radio: false ) fields.push @getOptions( form: label: "Options [Sortable]" radio: false options: [ text: "One" value: 1 , text: "Two" value: 2 , text: "Three" value: 3 , text: "Four" value: 4 , text: "Five" value: 5 , text: "Six" value: 6 ] name: "options_sorted" sortable: true sortable_hint: "Sort checked options, unchecked are sorted alphabetically" ) fields.push @getOptions( form: label: "Options [Horizontal]" radio: true horizontal: true ) fields.push new CUI.Input form: label: "Input" name: "input" placeholder: "CUI.Input" fields.push new CUI.Input form: label: "Input [Content-Size]" name: "input" content_size: true fields.push new CUI.Input form: label: "Input [Textarea]" name: "textarea" textarea: true placeholder: "CUI.Input [Textarea]" fields.push new CUI.Input form: label: "Input [Textarea | Content-Size]" name: "textarea" textarea: true content_size: true placeholder: "CUI.Input [Textarea | Content-Size]" last_tooltip = null fields.push new CUI.Slider form: label: "Slider" name: "slider" min: 1 max: 1000 value: 300 onDragging: (slider, value) => last_tooltip = new CUI.Tooltip on_hover: false text: value+'' element: slider.getHandle() .show() onDrop: => last_tooltip?.hideTimeout() onUpdate: (slider, value) => console.info("CUI.Slider: New value:", value) fields.push new CUI.Output form: label: "Output" text: "Simple CUI.Output" fields.push new CUI.Password form: label: "Input [Password]" name: "password" fields.push new CUI.MultiInput name: "MultiInput" form: label: "MultiInput" spellcheck: true control: multi_input_control fields.push new CUI.MultiInput name: "MultiInputTextarea" form: label: "MultiInput [Textarea]" spellcheck: true textarea: true control: multi_input_control fields.push new CUI.DateTime form: label: "DateTime" select_opts = [] icons = ["", "play", "audio", "left", "right"] for i in [0...100] if i % 20 == 0 select_opts.push divider: true else if i % 10 == 0 select_opts.push label: text: "Label "+i else select_opts.push text: "Opt "+(i+1) value: i icon: icons[Math.floor(Math.random()*4)] fields.push new CUI.Select form: label: "Select" name: "select" options: select_opts select_mini_opts = [] for i in [0...10] select_mini_opts.push text: "Mini "+(i+1) value: i fields.push new CUI.Select form: label: "Select" name: "select_mini" options: select_mini_opts fields.push new CUI.DataTable name: "table" form: label: "DataTable" name: "data_table" fields: [ form: label: "Column A" type: CUI.Input name: "a" , form: label: "Column B" type: CUI.Checkbox text: "Checkbox" name: "b" ] fields.push new CUI.DataTable name: "table" rowMove: true name: "data_table_sortable" form: label: "DataTable [sortable]" fields: [ form: label: "Column A" type: CUI.Input name: "a" , form: rotate_90: true label: "Column B" type: CUI.Checkbox text: "Checkbox" name: "b" ] form = [ new CUI.Form(data: data, maximize: false, fields: fields).start() ] getTableTab: -> ttab = new Demo.DemoTable() table = @getTableDefault() ttab.addExample("Default Table with Border", table) table = @getTableDefaultNoBorder() ttab.addExample("Default Table with no border", table) table = @getTableZebra() ttab.addExample("Zebra Table maximized", table) table = @getTableKeyvalue() ttab.addExample("Flex Table with Border and key/value", table) getTableZebra: -> table = new CUI.Table class: 'cui-maximize-horizontal cui-demo-table-zebra' columns: [ name: "a" text: "alpha" class: "a-class" , name: "b" text: "beta" class: "b-class" , name: "c" text: "gamma" class: "c-class" , name: "d" text: "delta" class: "d-class" ] rows: [ a: "a0" b: "b0" c: "Hello" d: "world" , a: "a1" b: "b1" c: "how" d: "are you" ] for i in [2..5] table.addRow a: "a"+i b: "b"+i table getTableDefault: -> table = new CUI.Table columns: [ name: "a" text: "alpha" class: "a-class" , name: "b" text: "beta" class: "b-class" , name: "c" text: "gamma" class: "c-class" , name: "d" text: "delta" class: "d-class" ] rows: [ a: "a0" b: "b0" c: "Hello" d: "world" , a: "a1" b: "b1" c: "how" d: "are you" ] for i in [2..5] table.addRow a: "a"+i b: "b"+i table getTableDefaultNoBorder: -> table = new CUI.Table class: 'cui-maximize-horizontal cui-demo-table-no-border' columns: [ name: "a" text: "alpha" class: "a-class" , name: "b" text: "beta" class: "b-class" , name: "c" text: "gamma" class: "c-class" , name: "d" text: "delta" class: "d-class" ] rows: [ a: "a0" b: "b0" c: "Hello" d: "world" , a: "a1" b: "b1" c: "how" d: "are you" ] for i in [2..5] table.addRow a: "a"+i b: "b"+i table getTableKeyvalue: -> table = new CUI.Table flex: true key_value: true someInfoData = [ key: "compiled" value: "pdf document, 3 pages, 727.5 kB" , key: "compiled_create_date" value: "1489755602.23" , key: "compiled_create_date_iso8601" value: "2017-03-17 T13:00:02+00:00" , key: "compiled_create_date_source" value: "m" , key: "extension" value: "pdf" , key: "fileclass" value: "office" ] for info in someInfoData table.addRow key: info.key value: info.value table getControlsTab: -> fu = new CUI.FileUpload url: "FileUpload.php" controls = [ new CUI.Block text: "Buttons" content: [ new CUI.Buttonbar(buttons: @getButtons()) , new CUI.Buttonbar(buttons: @getButtons(group: "A")) , new CUI.Buttonbar(buttons: @getButtons(appearance: "flat")) , new CUI.Buttonbar(buttons: @getButtons(icon: "refresh")) , new CUI.Buttonbar(buttons: @getButtons(icon: "play", appearance: "flat")) , new CUI.Buttonbar(buttons: [ new CUI.FileUploadButton icon: "upload" fileUpload: fu text: "File Upload" , new CUI.ButtonHref icon: "share" href: "https://www.programmfabrik.de" target: "_blank" text: "www.programmfabrik.de" ]) , new CUI.Buttonbar(buttons: [ new CUI.FileUploadButton appearance: "flat" fileUpload: fu text: "File Upload" , new CUI.ButtonHref appearance: "flat" href: "https://www.programmfabrik.de" target: "_blank" text: "www.programmfabrik.de" ]) ] , new CUI.Block text: "Labels" content: [ @getLabel(text: "Simple") , @getLabel(markdown: true, text: "Simple **Markdown**") , new CUI.EmptyLabel(text: "Empty Label") , @getMultiLabel() ] , new CUI.Panel text: "Panel Test" content: @getMultiLabel() ] getIconsTab: -> dt = new Demo.DemoTable() # Font Awesome Icons icons = ["play", "fa-angle-left", "fa-angle-right", "fa-angle-up", "fa-angle-down", "fa-angle-double-up", "fa-angle-double-down"] dt.addExample("Single Icon", new CUI.Block class: "cui-demo-icons" text: "Font Awesome icons that are customized" content: @getIconCollection(icons) ) # All Font Awesome Icons icons = [ "fa-crop", "fa-arrows-alt", "fa-warning", "fa-slack", "fa-file", "fa-filter", "fa-sliders", "fa-refresh", "fa fa-file-archive-o", "fa-rotate-right", "fa-rotate-left", "fa-arrows-v", "fa-arrows-h", "fa-calendar-plus-o", "fa-question", "fa-question", "fa-question", "fa-cog", "fa-download", "fa-download", "fa-question", "fa-upload", "fa-envelope-o", "fa-envelope", "fa-floppy-o", "fa-heart", "fa-user", "fa-clock-o", "fa-plus", "fa-pencil", "fa-files-o", "fa-search", "fa-share", "fa-play", "fa-music", "fa-play", "fa-stop", "fa-print", "fa-minus", "fa-caret-right", "fa-caret-down", "fa-ellipsis-h", "fa-ellipsis-v", "fa-bars", "fa-info-circle", "fa-bolt", "fa-check", "fa-warning", "fa-legal", "fa-cloud", "fa-angle-left", "fa-angle-right", "fa-angle-right", "fa-search-plus", "fa-search-minus", "fa-compress", "fa-expand", "fa-envelope-o", "fa-file-text", "fa-file-text-o", "fa-bullhorn", "fa-angle-left", "fa-angle-right", "fa-angle-down", "fa-angle-up", "fa-caret-up", "fa-caret-down", "fa-camera", "fa-list-ul", "fa-picture-o", "fa-sitemap", "fa-hourglass-half", ] dt.addExample("Single Icon", new CUI.Block class: "cui-demo-icons" text: "All Font Awesome icons" content: @getIconCollection(icons) ) # SVG Icons icons = [ "svg-arrow-right", "svg-close", "svg-drupal", "svg-easydb", "svg-external-link", "svg-falcon-io", "svg-folder-shared-upload", "svg-folder-shared", "svg-folder-upload", "svg-folder", "svg-grid", "svg-hierarchy", "svg-info-circle", "svg-multiple", "svg-popup", "svg-reset", "svg-rows", "svg-select-all", "svg-select-pages", "svg-spinner", "svg-table", "svg-tag-o", "svg-trash", "svg-typo3", "svg-easydb", "svg-fylr-logo", ] dt.addExample("Single Icon", new CUI.Block class: "cui-demo-icons" text: "SVG icons" content: @getIconCollection(icons) ) asset_icons = [ "svg-asset-failed", ] dt.addExample("Asset Icons", new CUI.Block class: "cui-demo-icons cui-demo-asset-icons" text: "Asset icons" content: @getIconCollection(asset_icons) ) dt.addExample("Icon in Buttons", new CUI.Buttonbar(buttons: @getButtons(icon: "download")) ) dt.addExample("SVG Spinner", new CUI.Label text: "Label" icon: "spinner" ) dt.addExample("FA Spinner", new CUI.Label text: "Label" icon: "fa-spinner" ) dt.addExample("Hourglass spinner", new CUI.Block class: "cui-demo-hourglass" content: @getHourglassIcon() ) dt.addExample("Times Thin, regular font icon (not FA)", new CUI.Label text: "Close" icon: "fa-times-thin" ) getHourglassIcon: -> hourglass_icons = [ "fa-hourglass-start" "fa-hourglass-half" "fa-hourglass-end" "fa-hourglass-end" "fa-hourglass-o" ] hourglass_container = CUI.dom.div("cui-hourglass-animation fa-stack") for i in hourglass_icons icon = new CUI.Icon icon: i class: "fa-stack-1x" CUI.dom.append(hourglass_container, icon.DOM) hourglass_container getIconCollection: (icons = []) -> icon_container = CUI.dom.div("cui-demo-icon-container") for i in icons icon_wrap = CUI.dom.div("cui-demo-icon") icon = new CUI.Icon icon: i new CUI.Tooltip element: icon_wrap show_ms: 1000 hide_ms: 200 text: i CUI.dom.append(icon_wrap, icon.DOM) CUI.dom.append(icon_container, icon_wrap) icon_container display: -> tabs = new CUI.Tabs maximize: true tabs: [ text: "Controls" content: @getControlsTab() class: "cui-demo-playground-tab-control" , text: "Inputs" content: @getInputsTab() , text: "Forms" content: @getFormsTab() , text: "Layer" content: @getLayerTab() , text: "Layout" content: @getLayoutTab() , text: "Table" content: @getTableTab() , text: "Icons" content: @getIconsTab() ] md = new Demo.MenuDemo() md.listenOnNode(tabs) tabs @longText: """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.""" Demo.register(new Demo.Playground())
[ { "context": "commands to server'\n version: '0.1'\n authors: ['Álvaro Cuesta']\n", "end": 347, "score": 0.999866247177124, "start": 334, "tag": "NAME", "value": "Álvaro Cuesta" } ]
plugins/raw.coffee
alvaro-cuesta/nerdobot
2
module.exports = -> @addCommand 'raw', args: '<command>', description: 'Send a raw command to the IRC server' (from, command) => if command? @raw command else @notice from.nick, "What should I do?" name: 'Raw' description: 'Send raw IRC commands to server' version: '0.1' authors: ['Álvaro Cuesta']
4528
module.exports = -> @addCommand 'raw', args: '<command>', description: 'Send a raw command to the IRC server' (from, command) => if command? @raw command else @notice from.nick, "What should I do?" name: 'Raw' description: 'Send raw IRC commands to server' version: '0.1' authors: ['<NAME>']
true
module.exports = -> @addCommand 'raw', args: '<command>', description: 'Send a raw command to the IRC server' (from, command) => if command? @raw command else @notice from.nick, "What should I do?" name: 'Raw' description: 'Send raw IRC commands to server' version: '0.1' authors: ['PI:NAME:<NAME>END_PI']
[ { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Cof", "end": 23, "score": 0.9998836517333984, "start": 13, "tag": "NAME", "value": "Mat Groves" }, { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/d...
src/Coffixi/display/DisplayObject.coffee
namuol/Coffixi
1
###* @author Mat Groves http://matgroves.com/ @Doormat23 ### define 'Coffixi/display/DisplayObject', [ 'Coffixi/core/Point' 'Coffixi/core/Matrix' 'Coffixi/filters/FilterBlock' 'Coffixi/utils/Module' ], ( Point Matrix FilterBlock Module ) -> ###* The base class for all objects that are rendered on the screen. @class DisplayObject @constructor ### class DisplayObject extends Module constructor: -> @last = this @first = this ###* The x coordinate of the object relative to the local coordinates of the parent. @property x ### @x = 0 ###* The y coordinate of the object relative to the local coordinates of the parent. @property y ### @y = 0 ###* The X scale factor of the object. @property scaleX ### @scaleX = 1 ###* The Y scale factor of the object. @property scaleY ### @scaleY = 1 ###* The x-coordinate of the pivot point that this rotates around. @property pivotX ### @pivotX = 0 ###* The y-coordinate of the pivot point that this rotates around. @property pivotY ### @pivotY = 0 ###* The rotation of the object in radians. @property rotation @type Number ### @rotation = 0 ###* The opacity of the object. @property alpha @type Number ### @alpha = 1 ###* Whether this object is renderable or not. @property renderable @type Boolean ### @renderable = false ###* Whether this object should be rendered or not (ignored if [`renderable`](#property_renderable) is `false`). @property visible @type Boolean ### @visible = true ###* The visibility of the object based on world (parent) factors. @property worldVisible @type Boolean @final ### @worldVisible = false ###* The display object container that contains this display object. @property parent @type DisplayObjectContainer @final ### @parent = null ###* The stage the display object is connected to, or undefined if it is not connected to the stage. @property stage @type Stage @final ### @stage ?= null ###* The multiplied alpha of the displayobject @property worldAlpha @type Number @final ### @worldAlpha = 1 ###* Current transform of the object based on world (parent) factors @property worldTransform @type Mat3 @final @private ### @worldTransform = Matrix.mat3.create() #mat3.identity(); ###* Current transform of the object locally @property localTransform @type Mat3 @final @private ### @localTransform = Matrix.mat3.create() #mat3.identity(); # chach that puppy! @_sr = 0 @_cr = 1 ###* Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it. A regular mask must be a Graphics object. This allows for much faster masking in canvas as it utilises shape clipping. To remove a mask, set this property to null. @property mask @type Graphics ### Object.defineProperty @::, 'mask', get: -> @_mask set: (value) -> @_mask = value if value @addFilter value else @removeFilter() ###* Adds a filter to this displayObject @method addFilter @param mask {Graphics} the graphics object to use as a filter @private ### addFilter: (mask) -> return if @filter @filter = true # insert a filter block.. start = new FilterBlock() end = new FilterBlock() start.mask = mask end.mask = mask start.first = start.last = this end.first = end.last = this start.open = true # insert start childFirst = start childLast = start nextObject = undefined previousObject = undefined previousObject = @first._iPrev if previousObject nextObject = previousObject._iNext childFirst._iPrev = previousObject previousObject._iNext = childFirst else nextObject = this if nextObject nextObject._iPrev = childLast childLast._iNext = nextObject # now insert the end filter block.. # insert end filter childFirst = end childLast = end nextObject = null previousObject = null previousObject = @last nextObject = previousObject._iNext if nextObject nextObject._iPrev = childLast childLast._iNext = nextObject childFirst._iPrev = previousObject previousObject._iNext = childFirst updateLast = this prevLast = @last while updateLast updateLast.last = end if updateLast.last is prevLast updateLast = updateLast.parent @first = start # if webGL... @__renderGroup.addFilterBlocks start, end if @__renderGroup mask.renderable = false ###* Removes the filter to this displayObject @method removeFilter @private ### removeFilter: -> return unless @filter @filter = false # modify the list.. startBlock = @first nextObject = startBlock._iNext previousObject = startBlock._iPrev nextObject._iPrev = previousObject if nextObject previousObject._iNext = nextObject if previousObject @first = startBlock._iNext # remove the end filter lastBlock = @last nextObject = lastBlock._iNext previousObject = lastBlock._iPrev nextObject._iPrev = previousObject if nextObject previousObject._iNext = nextObject # this is always true too! # if(this.last == lastBlock) #{ tempLast = lastBlock._iPrev # need to make sure the parents last is updated too updateLast = this while updateLast.last is lastBlock updateLast.last = tempLast updateLast = updateLast.parent break unless updateLast mask = startBlock.mask mask.renderable = true # if webGL... @__renderGroup.removeFilterBlocks startBlock, lastBlock if @__renderGroup ###* Updates the object transform for rendering @method updateTransform @private ### updateTransform: -> # TODO OPTIMIZE THIS!! with dirty unless @rotation is @rotationCache @rotationCache = @rotation @_sr = Math.sin(@rotation) @_cr = Math.cos(@rotation) localTransform = @localTransform parentTransform = @parent.worldTransform worldTransform = @worldTransform #console.log(localTransform) localTransform[0] = @_cr * @scaleX localTransform[1] = -@_sr * @scaleY localTransform[3] = @_sr * @scaleX localTransform[4] = @_cr * @scaleY # TODO --> do we even need a local matrix??? px = @pivotX py = @pivotY # Cache the matrix values (makes for huge speed increases!) a00 = localTransform[0] a01 = localTransform[1] a02 = @x - localTransform[0] * px - py * localTransform[1] a10 = localTransform[3] a11 = localTransform[4] a12 = @y - localTransform[4] * py - px * localTransform[3] b00 = parentTransform[0] b01 = parentTransform[1] b02 = parentTransform[2] b10 = parentTransform[3] b11 = parentTransform[4] b12 = parentTransform[5] localTransform[2] = a02 localTransform[5] = a12 worldTransform[0] = b00 * a00 + b01 * a10 worldTransform[1] = b00 * a01 + b01 * a11 worldTransform[2] = b00 * a02 + b01 * a12 + b02 worldTransform[3] = b10 * a00 + b11 * a10 worldTransform[4] = b10 * a01 + b11 * a11 worldTransform[5] = b10 * a02 + b11 * a12 + b12 # because we are using affine transformation, we can optimise the matrix concatenation process.. wooo! # mat3.multiply(this.localTransform, this.parent.worldTransform, this.worldTransform); @worldAlpha = @alpha * @parent.worldAlpha getGlobalX: -> @updateTransform() @worldTransform[2] getGlobalY: -> @updateTransform() @worldTransform[5] getChildIndex: -> @parent?.children.indexOf @ ? NaN getTreeDepth: -> return 0 if not @parent? return 1 + @parent.getTreeDepth() isAbove: (other) -> a = @ b = other otherDepth = other.getTreeDepth() depth = @getTreeDepth() loop return true if a.parent is b return false if b.parent is a break if (a.parent is b.parent) or (not a.parent?) or (not b.parent?) if depth > otherDepth a = a.parent depth -= 1 else if otherDepth > depth b = b.parent otherDepth -= 1 else a = a.parent b = b.parent return a.getChildIndex() > b.getChildIndex()
225875
###* @author <NAME> http://matgroves.com/ @Doormat23 ### define 'Coffixi/display/DisplayObject', [ 'Coffixi/core/Point' 'Coffixi/core/Matrix' 'Coffixi/filters/FilterBlock' 'Coffixi/utils/Module' ], ( Point Matrix FilterBlock Module ) -> ###* The base class for all objects that are rendered on the screen. @class DisplayObject @constructor ### class DisplayObject extends Module constructor: -> @last = this @first = this ###* The x coordinate of the object relative to the local coordinates of the parent. @property x ### @x = 0 ###* The y coordinate of the object relative to the local coordinates of the parent. @property y ### @y = 0 ###* The X scale factor of the object. @property scaleX ### @scaleX = 1 ###* The Y scale factor of the object. @property scaleY ### @scaleY = 1 ###* The x-coordinate of the pivot point that this rotates around. @property pivotX ### @pivotX = 0 ###* The y-coordinate of the pivot point that this rotates around. @property pivotY ### @pivotY = 0 ###* The rotation of the object in radians. @property rotation @type Number ### @rotation = 0 ###* The opacity of the object. @property alpha @type Number ### @alpha = 1 ###* Whether this object is renderable or not. @property renderable @type Boolean ### @renderable = false ###* Whether this object should be rendered or not (ignored if [`renderable`](#property_renderable) is `false`). @property visible @type Boolean ### @visible = true ###* The visibility of the object based on world (parent) factors. @property worldVisible @type Boolean @final ### @worldVisible = false ###* The display object container that contains this display object. @property parent @type DisplayObjectContainer @final ### @parent = null ###* The stage the display object is connected to, or undefined if it is not connected to the stage. @property stage @type Stage @final ### @stage ?= null ###* The multiplied alpha of the displayobject @property worldAlpha @type Number @final ### @worldAlpha = 1 ###* Current transform of the object based on world (parent) factors @property worldTransform @type Mat3 @final @private ### @worldTransform = Matrix.mat3.create() #mat3.identity(); ###* Current transform of the object locally @property localTransform @type Mat3 @final @private ### @localTransform = Matrix.mat3.create() #mat3.identity(); # chach that puppy! @_sr = 0 @_cr = 1 ###* Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it. A regular mask must be a Graphics object. This allows for much faster masking in canvas as it utilises shape clipping. To remove a mask, set this property to null. @property mask @type Graphics ### Object.defineProperty @::, 'mask', get: -> @_mask set: (value) -> @_mask = value if value @addFilter value else @removeFilter() ###* Adds a filter to this displayObject @method addFilter @param mask {Graphics} the graphics object to use as a filter @private ### addFilter: (mask) -> return if @filter @filter = true # insert a filter block.. start = new FilterBlock() end = new FilterBlock() start.mask = mask end.mask = mask start.first = start.last = this end.first = end.last = this start.open = true # insert start childFirst = start childLast = start nextObject = undefined previousObject = undefined previousObject = @first._iPrev if previousObject nextObject = previousObject._iNext childFirst._iPrev = previousObject previousObject._iNext = childFirst else nextObject = this if nextObject nextObject._iPrev = childLast childLast._iNext = nextObject # now insert the end filter block.. # insert end filter childFirst = end childLast = end nextObject = null previousObject = null previousObject = @last nextObject = previousObject._iNext if nextObject nextObject._iPrev = childLast childLast._iNext = nextObject childFirst._iPrev = previousObject previousObject._iNext = childFirst updateLast = this prevLast = @last while updateLast updateLast.last = end if updateLast.last is prevLast updateLast = updateLast.parent @first = start # if webGL... @__renderGroup.addFilterBlocks start, end if @__renderGroup mask.renderable = false ###* Removes the filter to this displayObject @method removeFilter @private ### removeFilter: -> return unless @filter @filter = false # modify the list.. startBlock = @first nextObject = startBlock._iNext previousObject = startBlock._iPrev nextObject._iPrev = previousObject if nextObject previousObject._iNext = nextObject if previousObject @first = startBlock._iNext # remove the end filter lastBlock = @last nextObject = lastBlock._iNext previousObject = lastBlock._iPrev nextObject._iPrev = previousObject if nextObject previousObject._iNext = nextObject # this is always true too! # if(this.last == lastBlock) #{ tempLast = lastBlock._iPrev # need to make sure the parents last is updated too updateLast = this while updateLast.last is lastBlock updateLast.last = tempLast updateLast = updateLast.parent break unless updateLast mask = startBlock.mask mask.renderable = true # if webGL... @__renderGroup.removeFilterBlocks startBlock, lastBlock if @__renderGroup ###* Updates the object transform for rendering @method updateTransform @private ### updateTransform: -> # TODO OPTIMIZE THIS!! with dirty unless @rotation is @rotationCache @rotationCache = @rotation @_sr = Math.sin(@rotation) @_cr = Math.cos(@rotation) localTransform = @localTransform parentTransform = @parent.worldTransform worldTransform = @worldTransform #console.log(localTransform) localTransform[0] = @_cr * @scaleX localTransform[1] = -@_sr * @scaleY localTransform[3] = @_sr * @scaleX localTransform[4] = @_cr * @scaleY # TODO --> do we even need a local matrix??? px = @pivotX py = @pivotY # Cache the matrix values (makes for huge speed increases!) a00 = localTransform[0] a01 = localTransform[1] a02 = @x - localTransform[0] * px - py * localTransform[1] a10 = localTransform[3] a11 = localTransform[4] a12 = @y - localTransform[4] * py - px * localTransform[3] b00 = parentTransform[0] b01 = parentTransform[1] b02 = parentTransform[2] b10 = parentTransform[3] b11 = parentTransform[4] b12 = parentTransform[5] localTransform[2] = a02 localTransform[5] = a12 worldTransform[0] = b00 * a00 + b01 * a10 worldTransform[1] = b00 * a01 + b01 * a11 worldTransform[2] = b00 * a02 + b01 * a12 + b02 worldTransform[3] = b10 * a00 + b11 * a10 worldTransform[4] = b10 * a01 + b11 * a11 worldTransform[5] = b10 * a02 + b11 * a12 + b12 # because we are using affine transformation, we can optimise the matrix concatenation process.. wooo! # mat3.multiply(this.localTransform, this.parent.worldTransform, this.worldTransform); @worldAlpha = @alpha * @parent.worldAlpha getGlobalX: -> @updateTransform() @worldTransform[2] getGlobalY: -> @updateTransform() @worldTransform[5] getChildIndex: -> @parent?.children.indexOf @ ? NaN getTreeDepth: -> return 0 if not @parent? return 1 + @parent.getTreeDepth() isAbove: (other) -> a = @ b = other otherDepth = other.getTreeDepth() depth = @getTreeDepth() loop return true if a.parent is b return false if b.parent is a break if (a.parent is b.parent) or (not a.parent?) or (not b.parent?) if depth > otherDepth a = a.parent depth -= 1 else if otherDepth > depth b = b.parent otherDepth -= 1 else a = a.parent b = b.parent return a.getChildIndex() > b.getChildIndex()
true
###* @author PI:NAME:<NAME>END_PI http://matgroves.com/ @Doormat23 ### define 'Coffixi/display/DisplayObject', [ 'Coffixi/core/Point' 'Coffixi/core/Matrix' 'Coffixi/filters/FilterBlock' 'Coffixi/utils/Module' ], ( Point Matrix FilterBlock Module ) -> ###* The base class for all objects that are rendered on the screen. @class DisplayObject @constructor ### class DisplayObject extends Module constructor: -> @last = this @first = this ###* The x coordinate of the object relative to the local coordinates of the parent. @property x ### @x = 0 ###* The y coordinate of the object relative to the local coordinates of the parent. @property y ### @y = 0 ###* The X scale factor of the object. @property scaleX ### @scaleX = 1 ###* The Y scale factor of the object. @property scaleY ### @scaleY = 1 ###* The x-coordinate of the pivot point that this rotates around. @property pivotX ### @pivotX = 0 ###* The y-coordinate of the pivot point that this rotates around. @property pivotY ### @pivotY = 0 ###* The rotation of the object in radians. @property rotation @type Number ### @rotation = 0 ###* The opacity of the object. @property alpha @type Number ### @alpha = 1 ###* Whether this object is renderable or not. @property renderable @type Boolean ### @renderable = false ###* Whether this object should be rendered or not (ignored if [`renderable`](#property_renderable) is `false`). @property visible @type Boolean ### @visible = true ###* The visibility of the object based on world (parent) factors. @property worldVisible @type Boolean @final ### @worldVisible = false ###* The display object container that contains this display object. @property parent @type DisplayObjectContainer @final ### @parent = null ###* The stage the display object is connected to, or undefined if it is not connected to the stage. @property stage @type Stage @final ### @stage ?= null ###* The multiplied alpha of the displayobject @property worldAlpha @type Number @final ### @worldAlpha = 1 ###* Current transform of the object based on world (parent) factors @property worldTransform @type Mat3 @final @private ### @worldTransform = Matrix.mat3.create() #mat3.identity(); ###* Current transform of the object locally @property localTransform @type Mat3 @final @private ### @localTransform = Matrix.mat3.create() #mat3.identity(); # chach that puppy! @_sr = 0 @_cr = 1 ###* Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it. A regular mask must be a Graphics object. This allows for much faster masking in canvas as it utilises shape clipping. To remove a mask, set this property to null. @property mask @type Graphics ### Object.defineProperty @::, 'mask', get: -> @_mask set: (value) -> @_mask = value if value @addFilter value else @removeFilter() ###* Adds a filter to this displayObject @method addFilter @param mask {Graphics} the graphics object to use as a filter @private ### addFilter: (mask) -> return if @filter @filter = true # insert a filter block.. start = new FilterBlock() end = new FilterBlock() start.mask = mask end.mask = mask start.first = start.last = this end.first = end.last = this start.open = true # insert start childFirst = start childLast = start nextObject = undefined previousObject = undefined previousObject = @first._iPrev if previousObject nextObject = previousObject._iNext childFirst._iPrev = previousObject previousObject._iNext = childFirst else nextObject = this if nextObject nextObject._iPrev = childLast childLast._iNext = nextObject # now insert the end filter block.. # insert end filter childFirst = end childLast = end nextObject = null previousObject = null previousObject = @last nextObject = previousObject._iNext if nextObject nextObject._iPrev = childLast childLast._iNext = nextObject childFirst._iPrev = previousObject previousObject._iNext = childFirst updateLast = this prevLast = @last while updateLast updateLast.last = end if updateLast.last is prevLast updateLast = updateLast.parent @first = start # if webGL... @__renderGroup.addFilterBlocks start, end if @__renderGroup mask.renderable = false ###* Removes the filter to this displayObject @method removeFilter @private ### removeFilter: -> return unless @filter @filter = false # modify the list.. startBlock = @first nextObject = startBlock._iNext previousObject = startBlock._iPrev nextObject._iPrev = previousObject if nextObject previousObject._iNext = nextObject if previousObject @first = startBlock._iNext # remove the end filter lastBlock = @last nextObject = lastBlock._iNext previousObject = lastBlock._iPrev nextObject._iPrev = previousObject if nextObject previousObject._iNext = nextObject # this is always true too! # if(this.last == lastBlock) #{ tempLast = lastBlock._iPrev # need to make sure the parents last is updated too updateLast = this while updateLast.last is lastBlock updateLast.last = tempLast updateLast = updateLast.parent break unless updateLast mask = startBlock.mask mask.renderable = true # if webGL... @__renderGroup.removeFilterBlocks startBlock, lastBlock if @__renderGroup ###* Updates the object transform for rendering @method updateTransform @private ### updateTransform: -> # TODO OPTIMIZE THIS!! with dirty unless @rotation is @rotationCache @rotationCache = @rotation @_sr = Math.sin(@rotation) @_cr = Math.cos(@rotation) localTransform = @localTransform parentTransform = @parent.worldTransform worldTransform = @worldTransform #console.log(localTransform) localTransform[0] = @_cr * @scaleX localTransform[1] = -@_sr * @scaleY localTransform[3] = @_sr * @scaleX localTransform[4] = @_cr * @scaleY # TODO --> do we even need a local matrix??? px = @pivotX py = @pivotY # Cache the matrix values (makes for huge speed increases!) a00 = localTransform[0] a01 = localTransform[1] a02 = @x - localTransform[0] * px - py * localTransform[1] a10 = localTransform[3] a11 = localTransform[4] a12 = @y - localTransform[4] * py - px * localTransform[3] b00 = parentTransform[0] b01 = parentTransform[1] b02 = parentTransform[2] b10 = parentTransform[3] b11 = parentTransform[4] b12 = parentTransform[5] localTransform[2] = a02 localTransform[5] = a12 worldTransform[0] = b00 * a00 + b01 * a10 worldTransform[1] = b00 * a01 + b01 * a11 worldTransform[2] = b00 * a02 + b01 * a12 + b02 worldTransform[3] = b10 * a00 + b11 * a10 worldTransform[4] = b10 * a01 + b11 * a11 worldTransform[5] = b10 * a02 + b11 * a12 + b12 # because we are using affine transformation, we can optimise the matrix concatenation process.. wooo! # mat3.multiply(this.localTransform, this.parent.worldTransform, this.worldTransform); @worldAlpha = @alpha * @parent.worldAlpha getGlobalX: -> @updateTransform() @worldTransform[2] getGlobalY: -> @updateTransform() @worldTransform[5] getChildIndex: -> @parent?.children.indexOf @ ? NaN getTreeDepth: -> return 0 if not @parent? return 1 + @parent.getTreeDepth() isAbove: (other) -> a = @ b = other otherDepth = other.getTreeDepth() depth = @getTreeDepth() loop return true if a.parent is b return false if b.parent is a break if (a.parent is b.parent) or (not a.parent?) or (not b.parent?) if depth > otherDepth a = a.parent depth -= 1 else if otherDepth > depth b = b.parent otherDepth -= 1 else a = a.parent b = b.parent return a.getChildIndex() > b.getChildIndex()
[ { "context": "\"title\": \"Artusi's cooking\"\n\n\"api\":\n \"baseUrl\": \"http://diegopi", "end": 16, "score": 0.9990209341049194, "start": 10, "tag": "NAME", "value": "Artusi" } ]
dist/config.cson
robertDpi/mangiabene
0
"title": "Artusi's cooking" "api": "baseUrl": "http://diegopinna.com/cooking/wp-json" "timeout": 10000 "maxAttempt": 3 # # "translation": # "displayed" : ["en", "fr"] # "prefered": "en" # POST PAGES "post": "comments": "enabled": true "depth": 2 "per_page": 50 "cache": "maxAge": 10800000 "capacity": 10 "cordova": "admob": "enabled":false "android": "bannerID": null "interstitialID": null "ios": "bannerID": null "interstitialID": null "pushNotifications": "enabled": false "baseUrl": "http://yourDomain.com/pnfw" "android": "senderID": ""
1470
"title": "<NAME>'s cooking" "api": "baseUrl": "http://diegopinna.com/cooking/wp-json" "timeout": 10000 "maxAttempt": 3 # # "translation": # "displayed" : ["en", "fr"] # "prefered": "en" # POST PAGES "post": "comments": "enabled": true "depth": 2 "per_page": 50 "cache": "maxAge": 10800000 "capacity": 10 "cordova": "admob": "enabled":false "android": "bannerID": null "interstitialID": null "ios": "bannerID": null "interstitialID": null "pushNotifications": "enabled": false "baseUrl": "http://yourDomain.com/pnfw" "android": "senderID": ""
true
"title": "PI:NAME:<NAME>END_PI's cooking" "api": "baseUrl": "http://diegopinna.com/cooking/wp-json" "timeout": 10000 "maxAttempt": 3 # # "translation": # "displayed" : ["en", "fr"] # "prefered": "en" # POST PAGES "post": "comments": "enabled": true "depth": 2 "per_page": 50 "cache": "maxAge": 10800000 "capacity": 10 "cordova": "admob": "enabled":false "android": "bannerID": null "interstitialID": null "ios": "bannerID": null "interstitialID": null "pushNotifications": "enabled": false "baseUrl": "http://yourDomain.com/pnfw" "android": "senderID": ""
[ { "context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o", "end": 67, "score": 0.5976675748825073, "start": 62, "tag": "NAME", "value": "Hatio" } ]
src/serialize.coffee
heartyoh/dou
1
# ========================================== # Copyright 2014 Hatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './compose' './property' ], (compose, withProperty) -> "use strict" serialize = -> [ "type: #{this.name}" "id: #{this.id}" "props: #{JSON.stringify(this.attrs)}" ].join(',') deserialize = -> # serialize 되는 객체는 # 타입과 id를 가지면 좋겠다. # 타입 정보는 .. # 클래스이름과 구현이 있는 로케이션 정보 등이 좋겠다. # 플러그인 정보는 필요없나 ? 나중에 고민 합시다.. -> compose.mixin this, withProperty this.serialize = serialize if !this.serialize this.deserialize = deserialize if !this.deserialize
12911
# ========================================== # Copyright 2014 <NAME>, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './compose' './property' ], (compose, withProperty) -> "use strict" serialize = -> [ "type: #{this.name}" "id: #{this.id}" "props: #{JSON.stringify(this.attrs)}" ].join(',') deserialize = -> # serialize 되는 객체는 # 타입과 id를 가지면 좋겠다. # 타입 정보는 .. # 클래스이름과 구현이 있는 로케이션 정보 등이 좋겠다. # 플러그인 정보는 필요없나 ? 나중에 고민 합시다.. -> compose.mixin this, withProperty this.serialize = serialize if !this.serialize this.deserialize = deserialize if !this.deserialize
true
# ========================================== # Copyright 2014 PI:NAME:<NAME>END_PI, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './compose' './property' ], (compose, withProperty) -> "use strict" serialize = -> [ "type: #{this.name}" "id: #{this.id}" "props: #{JSON.stringify(this.attrs)}" ].join(',') deserialize = -> # serialize 되는 객체는 # 타입과 id를 가지면 좋겠다. # 타입 정보는 .. # 클래스이름과 구현이 있는 로케이션 정보 등이 좋겠다. # 플러그인 정보는 필요없나 ? 나중에 고민 합시다.. -> compose.mixin this, withProperty this.serialize = serialize if !this.serialize this.deserialize = deserialize if !this.deserialize
[ { "context": "hema)\n \n instance = new SimpleModel({name: 'testName', title: 'testTitle'})\n should.exist ins", "end": 972, "score": 0.997313380241394, "start": 968, "tag": "NAME", "value": "test" }, { "context": ")\n \n instance = new SimpleModel({name: 'testName',...
API/public/node_modules/mongoose-createdmodified/test/test.coffee
kidSk/cmpnSite
0
chai = require 'chai' assert = chai.assert expect = chai.expect should = chai.should() mongoose = require 'mongoose' index = require '../src/index' db = mongoose.createConnection('localhost', 'mongoose_createdmodified_tests') db.on('error', console.error.bind(console, 'connection error:')) Schema = mongoose.Schema ObjectId = Schema.ObjectId SimpleSchema = new Schema name: String title: String describe 'WHEN working with the plugin', -> before (done) -> done() after (done) -> SimpleModel = db.model("SimpleModel", SimpleSchema) SimpleModel.remove {}, (err) -> return done(err) if err done() describe 'library', -> it 'should exist', (done) -> should.exist index done() describe 'adding the plugin', -> it 'should work', (done) -> SimpleSchema.plugin index.createdModifiedPlugin, {index: true} SimpleModel = db.model("SimpleModel", SimpleSchema) instance = new SimpleModel({name: 'testName', title: 'testTitle'}) should.exist instance instance.should.have.property 'name', 'testName' instance.should.have.property 'title', 'testTitle' instance.should.have.property 'created' instance.should.have.property 'modified' should.not.exist(instance.created) should.not.exist(instance.modified) instance.save (err) -> return done(err) if err should.exist(instance.created) should.exist(instance.modified) instance.created.should.be.instanceof(Date) instance.modified.should.be.instanceof(Date) instance.modified.should.not.be.below(instance.created) done()
112763
chai = require 'chai' assert = chai.assert expect = chai.expect should = chai.should() mongoose = require 'mongoose' index = require '../src/index' db = mongoose.createConnection('localhost', 'mongoose_createdmodified_tests') db.on('error', console.error.bind(console, 'connection error:')) Schema = mongoose.Schema ObjectId = Schema.ObjectId SimpleSchema = new Schema name: String title: String describe 'WHEN working with the plugin', -> before (done) -> done() after (done) -> SimpleModel = db.model("SimpleModel", SimpleSchema) SimpleModel.remove {}, (err) -> return done(err) if err done() describe 'library', -> it 'should exist', (done) -> should.exist index done() describe 'adding the plugin', -> it 'should work', (done) -> SimpleSchema.plugin index.createdModifiedPlugin, {index: true} SimpleModel = db.model("SimpleModel", SimpleSchema) instance = new SimpleModel({name: '<NAME> <NAME>', title: 'testTitle'}) should.exist instance instance.should.have.property 'name', '<NAME> <NAME>' instance.should.have.property 'title', 'testTitle' instance.should.have.property 'created' instance.should.have.property 'modified' should.not.exist(instance.created) should.not.exist(instance.modified) instance.save (err) -> return done(err) if err should.exist(instance.created) should.exist(instance.modified) instance.created.should.be.instanceof(Date) instance.modified.should.be.instanceof(Date) instance.modified.should.not.be.below(instance.created) done()
true
chai = require 'chai' assert = chai.assert expect = chai.expect should = chai.should() mongoose = require 'mongoose' index = require '../src/index' db = mongoose.createConnection('localhost', 'mongoose_createdmodified_tests') db.on('error', console.error.bind(console, 'connection error:')) Schema = mongoose.Schema ObjectId = Schema.ObjectId SimpleSchema = new Schema name: String title: String describe 'WHEN working with the plugin', -> before (done) -> done() after (done) -> SimpleModel = db.model("SimpleModel", SimpleSchema) SimpleModel.remove {}, (err) -> return done(err) if err done() describe 'library', -> it 'should exist', (done) -> should.exist index done() describe 'adding the plugin', -> it 'should work', (done) -> SimpleSchema.plugin index.createdModifiedPlugin, {index: true} SimpleModel = db.model("SimpleModel", SimpleSchema) instance = new SimpleModel({name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI', title: 'testTitle'}) should.exist instance instance.should.have.property 'name', 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' instance.should.have.property 'title', 'testTitle' instance.should.have.property 'created' instance.should.have.property 'modified' should.not.exist(instance.created) should.not.exist(instance.modified) instance.save (err) -> return done(err) if err should.exist(instance.created) should.exist(instance.modified) instance.created.should.be.instanceof(Date) instance.modified.should.be.instanceof(Date) instance.modified.should.not.be.below(instance.created) done()
[ { "context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.", "end": 17, "score": 0.925456702709198, "start": 16, "tag": "EMAIL", "value": "j" }, { "context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.\n#\n# Per", "end": 25, "...
src/lib/parsedir.coffee
yadutaf/Weathermap-archive
1
### # Copyright jtlebi.fr <admin@jtlebi.fr> and other 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. ### # This file adds a method on 'fs' module to improve directory read fs = require 'fs' fs.parsedir = (path, cb) -> dir = {} this.readdir path, (err, list) => return cb(err) if err pending = list.length return cb(null, dir) if not pending list.forEach (file) => fs.stat path+'/'+file, (err, stat) => if stat if stat.isDirectory() dir.directories = [] if not dir.directories dir.directories.push file else if stat.isFile() dir.files = [] if not dir.files dir.files.push file cb(null, dir) if not --pending
24830
### # Copyright <EMAIL>tlebi.fr <<EMAIL>> and other 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. ### # This file adds a method on 'fs' module to improve directory read fs = require 'fs' fs.parsedir = (path, cb) -> dir = {} this.readdir path, (err, list) => return cb(err) if err pending = list.length return cb(null, dir) if not pending list.forEach (file) => fs.stat path+'/'+file, (err, stat) => if stat if stat.isDirectory() dir.directories = [] if not dir.directories dir.directories.push file else if stat.isFile() dir.files = [] if not dir.files dir.files.push file cb(null, dir) if not --pending
true
### # Copyright PI:EMAIL:<EMAIL>END_PItlebi.fr <PI:EMAIL:<EMAIL>END_PI> and other 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. ### # This file adds a method on 'fs' module to improve directory read fs = require 'fs' fs.parsedir = (path, cb) -> dir = {} this.readdir path, (err, list) => return cb(err) if err pending = list.length return cb(null, dir) if not pending list.forEach (file) => fs.stat path+'/'+file, (err, stat) => if stat if stat.isDirectory() dir.directories = [] if not dir.directories dir.directories.push file else if stat.isFile() dir.files = [] if not dir.files dir.files.push file cb(null, dir) if not --pending
[ { "context": "k\"\n },\n \"email\": {\n \"$t\": \"okfn.rufus.pollock@gmail.com\"\n }\n }\n ],\n \"openSearch$startIn", "end": 618, "score": 0.999884843826294, "start": 590, "tag": "EMAIL", "value": "okfn.rufus.pollock@gmail.com" }, { "context"...
tests/spec/lib/utils/gdocs.coffee
openspending/openspendingjs-old
7
sample_gdocs_spreadsheet_data = { "feed": { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "xmlns": "http://www.w3.org/2005/Atom", "xmlns$gsx": "http://schemas.google.com/spreadsheets/2006/extended", "title": { "$t": "Sheet1", "type": "text" }, "author": [ { "name": { "$t": "okfn.rufus.pollock" }, "email": { "$t": "okfn.rufus.pollock@gmail.com" } } ], "openSearch$startIndex": { "$t": "1" }, "link": [ { "href": "http://spreadsheets.google.com/pub?key=0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc", "type": "text/html", "rel": "alternate" }, { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values", "type": "application/atom+xml", "rel": "http://schemas.google.com/g/2005#feed" }, { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values?alt=json-in-script", "type": "application/atom+xml", "rel": "self" } ], "xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/", "entry": [ { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "gsx$column-2": { "$t": "1" }, "gsx$column-1": { "$t": "A" }, "title": { "$t": "A", "type": "text" }, "content": { "$t": "column-2: 1", "type": "text" }, "link": [ { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cokwr", "type": "application/atom+xml", "rel": "self" } ], "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cokwr" } }, { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "gsx$column-2": { "$t": "2" }, "gsx$column-1": { "$t": "b" }, "title": { "$t": "b", "type": "text" }, "content": { "$t": "column-2: 2", "type": "text" }, "link": [ { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cpzh4", "type": "application/atom+xml", "rel": "self" } ], "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cpzh4" } }, { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "gsx$column-2": { "$t": "3" }, "gsx$column-1": { "$t": "c" }, "title": { "$t": "c", "type": "text" }, "content": { "$t": "column-2: 3", "type": "text" }, "link": [ { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cre1l", "type": "application/atom+xml", "rel": "self" } ], "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cre1l" } } ], "openSearch$totalResults": { "$t": "3" }, "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values" } }, "version": "1.0", "encoding": "UTF-8" } describe 'lib/utils/gdocs', -> describe 'gdocsToJavascript', -> it 'should parse GDocs json', -> res = gdocsToJavascript(sample_gdocs_spreadsheet_data) expect(res.header[0]).to.equal('column-2') expect(res.header[1]).to.equal('column-1') expect(res.data.length).to.equal(3) expect(res.data[0][0]).to.equal('1') expect(res.data[0][1]).to.equal('A') it 'should use options.columnsToUse as column names', -> res = gdocsToJavascript(sample_gdocs_spreadsheet_data, columnsToUse: ['column-1', 'column-2']) expect(res.header[0]).to.equal('column-1') expect(res.header[1]).to.equal('column-2') expect(res.data.length).to.equal(3) expect(res.data[0][0]).to.equal('A') expect(res.data[0][1]).to.equal('1')
37489
sample_gdocs_spreadsheet_data = { "feed": { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "xmlns": "http://www.w3.org/2005/Atom", "xmlns$gsx": "http://schemas.google.com/spreadsheets/2006/extended", "title": { "$t": "Sheet1", "type": "text" }, "author": [ { "name": { "$t": "okfn.rufus.pollock" }, "email": { "$t": "<EMAIL>" } } ], "openSearch$startIndex": { "$t": "1" }, "link": [ { "href": "http://spreadsheets.google.com/pub?key=<KEY>", "type": "text/html", "rel": "alternate" }, { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQw<KEY>1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values", "type": "application/atom+xml", "rel": "http://schemas.google.com/g/2005#feed" }, { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values?alt=json-in-script", "type": "application/atom+xml", "rel": "self" } ], "xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/", "entry": [ { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "gsx$column-2": { "$t": "1" }, "gsx$column-1": { "$t": "A" }, "title": { "$t": "A", "type": "text" }, "content": { "$t": "column-2: 1", "type": "text" }, "link": [ { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cokwr", "type": "application/atom+xml", "rel": "self" } ], "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cokwr" } }, { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "gsx$column-2": { "$t": "2" }, "gsx$column-1": { "$t": "b" }, "title": { "$t": "b", "type": "text" }, "content": { "$t": "column-2: 2", "type": "text" }, "link": [ { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cpzh4", "type": "application/atom+xml", "rel": "self" } ], "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cpzh4" } }, { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "gsx$column-2": { "$t": "3" }, "gsx$column-1": { "$t": "c" }, "title": { "$t": "c", "type": "text" }, "content": { "$t": "column-2: 3", "type": "text" }, "link": [ { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cre1l", "type": "application/atom+xml", "rel": "self" } ], "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cre1l" } } ], "openSearch$totalResults": { "$t": "3" }, "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values" } }, "version": "1.0", "encoding": "UTF-8" } describe 'lib/utils/gdocs', -> describe 'gdocsToJavascript', -> it 'should parse GDocs json', -> res = gdocsToJavascript(sample_gdocs_spreadsheet_data) expect(res.header[0]).to.equal('column-2') expect(res.header[1]).to.equal('column-1') expect(res.data.length).to.equal(3) expect(res.data[0][0]).to.equal('1') expect(res.data[0][1]).to.equal('A') it 'should use options.columnsToUse as column names', -> res = gdocsToJavascript(sample_gdocs_spreadsheet_data, columnsToUse: ['column-1', 'column-2']) expect(res.header[0]).to.equal('column-1') expect(res.header[1]).to.equal('column-2') expect(res.data.length).to.equal(3) expect(res.data[0][0]).to.equal('A') expect(res.data[0][1]).to.equal('1')
true
sample_gdocs_spreadsheet_data = { "feed": { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "xmlns": "http://www.w3.org/2005/Atom", "xmlns$gsx": "http://schemas.google.com/spreadsheets/2006/extended", "title": { "$t": "Sheet1", "type": "text" }, "author": [ { "name": { "$t": "okfn.rufus.pollock" }, "email": { "$t": "PI:EMAIL:<EMAIL>END_PI" } } ], "openSearch$startIndex": { "$t": "1" }, "link": [ { "href": "http://spreadsheets.google.com/pub?key=PI:KEY:<KEY>END_PI", "type": "text/html", "rel": "alternate" }, { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwPI:KEY:<KEY>END_PI1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values", "type": "application/atom+xml", "rel": "http://schemas.google.com/g/2005#feed" }, { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values?alt=json-in-script", "type": "application/atom+xml", "rel": "self" } ], "xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/", "entry": [ { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "gsx$column-2": { "$t": "1" }, "gsx$column-1": { "$t": "A" }, "title": { "$t": "A", "type": "text" }, "content": { "$t": "column-2: 1", "type": "text" }, "link": [ { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cokwr", "type": "application/atom+xml", "rel": "self" } ], "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cokwr" } }, { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "gsx$column-2": { "$t": "2" }, "gsx$column-1": { "$t": "b" }, "title": { "$t": "b", "type": "text" }, "content": { "$t": "column-2: 2", "type": "text" }, "link": [ { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cpzh4", "type": "application/atom+xml", "rel": "self" } ], "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cpzh4" } }, { "category": [ { "term": "http://schemas.google.com/spreadsheets/2006#list", "scheme": "http://schemas.google.com/spreadsheets/2006" } ], "updated": { "$t": "2010-07-12T18:32:16.200Z" }, "gsx$column-2": { "$t": "3" }, "gsx$column-1": { "$t": "c" }, "title": { "$t": "c", "type": "text" }, "content": { "$t": "column-2: 3", "type": "text" }, "link": [ { "href": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cre1l", "type": "application/atom+xml", "rel": "self" } ], "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values/cre1l" } } ], "openSearch$totalResults": { "$t": "3" }, "id": { "$t": "http://spreadsheets.google.com/feeds/list/0Aon3JiuouxLUdDQwZE1JdV94cUd6NWtuZ0IyWTBjLWc/od6/public/values" } }, "version": "1.0", "encoding": "UTF-8" } describe 'lib/utils/gdocs', -> describe 'gdocsToJavascript', -> it 'should parse GDocs json', -> res = gdocsToJavascript(sample_gdocs_spreadsheet_data) expect(res.header[0]).to.equal('column-2') expect(res.header[1]).to.equal('column-1') expect(res.data.length).to.equal(3) expect(res.data[0][0]).to.equal('1') expect(res.data[0][1]).to.equal('A') it 'should use options.columnsToUse as column names', -> res = gdocsToJavascript(sample_gdocs_spreadsheet_data, columnsToUse: ['column-1', 'column-2']) expect(res.header[0]).to.equal('column-1') expect(res.header[1]).to.equal('column-2') expect(res.data.length).to.equal(3) expect(res.data[0][0]).to.equal('A') expect(res.data[0][1]).to.equal('1')
[ { "context": "edit: 'Image Credits'\n\n bios:\n townsend: 'Phil Townsend is a professor of Forest &amp; Wildlife Ecology a", "end": 27525, "score": 0.9998682737350464, "start": 27512, "tag": "NAME", "value": "Phil Townsend" }, { "context": "ter understand ecosystems.'\n ...
app/lib/en-us.coffee
aliburchard/gorongosa-clone
0
module.exports = navigation: home: 'Home' classify: 'Classify' science: 'Science' team: 'Team' education: 'Education' profile: 'Profile' talk: 'Talk' blog: 'Blog' home: heading: 'Welcome to Wildlife Watch' rightBannerHeader: "What is Wildlife Watch?" tagline: 'WildlifeWatch is an effort to monitor forest wildlife year-round across a network of trail cameras. Help us to identify the animals captured on camera and better understand the distribution and trends of our wildlife populations.' action: 'Get Started' nasa: 'In partnership with NASA' currentStatus: '<span class="classification-count">0</span> classifications by <span class="user-count">0</span> volunteers' stats: header: "WILDLIFE WATCH Statistics" activeUsers: "Active Users" crittersIdentified: "Critters Identified" totalImages: "Images Total" complete: "Complete" siteIntro: s1: title: "Welcome!" content: "Welcome to Wildlife Watch! In this project, we are asking you to identify animals found in camera trap photos from around Wisconsin. Your help allows us better understand how animal populations across the state change through time." s2: title: "Identifying animals" content: "You are presented with a photo on the left and a list of potential animals on the right. When you spot an animal within a photo, simply click the corresponding animal on the right. You will be asked to supply some followup info, such as the number of animals found in the image." s3: title: "Filtering by characteristics" content: "Occasionally it is difficult to determine which animal is in the photo. Just above the list of animals is a variety of methods to filter the animal list. Selecting different options reduces the number of choices, making your job easier." s4: title: "Made a mistake?" content: "If you need to delete any of your existing marks while viewing an image, simply find your animal in the list below the image and click the 'X' icon. Don’t worry if you’re unsure about your choices, though—even a guess is more helpful than nothing!" s5: title: "That's it!" content: "You may catch up on project updates through speaking with other volunteers via Talk." classify: deleteAnnotation: 'Delete' notSignedIn: 'You\'re not signed in!' favorite: 'Favorite' unfavorite: 'Unfavorite' play: 'View series' pause: 'Stop' satellite: 'Satellite view' nothingLabel: 'Nothing here' nextSubjectButton: 'Finish' share: 'Share' tweet: 'Tweet' pin: 'Pin it' discuss: 'Discuss' next: 'Next capture' search: 'Search' nothingToShow: 'There\'s nothing to show with these filters.' clearFilters: 'Clear filters' oftenConfused: 'Often confused with:' count: 'How many' startTutorial: 'Start tutorial' deer: fawns: "Fawns" antlered: "Adult antlered" antlerless: "Adult antlerless" notVisible: "Adult head not visible" behavior: 'Behavior' behaviors: standing: 'standing' resting: 'resting' moving: 'moving' eating: 'eating' interacting: 'interacting' babies: 'Young present' rain: 'Raining' cancel: 'Cancel' identify: 'Identify' differences: aardvark: pangolin: 'A pangolin is covered in scales while an aardvark has brown fur. It also has a shorter, pointier snout than an aardvark.' baboon: samangoMonkey: 'A samango monkey has bluish-gray fur while a baboon has yellow-brown fur. It also has a dark face with prominent fur on the cheeks.' baboon: vervetMonkey: 'A vervet monkey is much smaller than a baboon with a black face and light gray fur.' buffalo: wildebeest: 'A wildebeest is more slender than a buffalo with a long, narrow face and a beard.' bushbuck: reedbuck: 'A reedbuck has solid tan fur without white spots or stripes. Its horns are ringed and it has a large, black spot below the ears.' bushbuck: nyala: 'A nyala female has prominent vertical white stripes and white markings between the eyes, while a bushbuck female has lighter stripes and more prominent spots.' bushpig: warthog: 'A warthog is a slate gray color with prominent warts on the sides of its face and larger tusks than a bushpig.' caracal: lionFemale: 'A lion is larger than a caracal with rounded ears, no white or black markings on the face or ears, and its fur is a lighter golden-yellow color.' civet: genet: 'A genet is more slender than a civet with a much longer, bushier tail. ' duiker: oribi: 'An oribi is more slender and taller than a duiker with a flat back, white underbelly, and prominent black spots below the ears. ' eland: hartebeest: 'A hartebeest is a taller and more slender than an eland with reddish fur, narrow face, and short, spiral horns.' eland: kudu: 'A kudu is taller and less ox-like than an eland, it has massive spiral horns and lacks a dewlap on the throat.' genet: civet: 'A civet is stockier than a genet with a much shorter tail and a dark mask on the face.' hartebeest: eland: 'An eland is more stocky and ox-like than a hartebeest with long, straight horns that twist. It has a dewlap below the neck.' hartebeest: wildebeest: 'A wildebeest is dark gray-brown with a mane and beard. Its horns are longer than a hartebeest.' hartebeest: kudu: 'A kudu is stockier than a hartebeest with tan-gray fur, vertical stripes, and the males have manes and massive spiral horns.' hippopotamus: warthog: 'A warthog is much smaller than a hippopotamus with horns and prominent warts on the face.' hyena: wildDog: 'A wild dog is more slender than a hyena with patchy black, orange, and white fur and a flat back.' impala: bushbuck: 'A bushbuck has vertical white stripes and spots on the flanks as well as a rounded back.' impala: reedbuck: 'A reedbuck has solid tan fur without horizontal bands. Its horns are curved and ringed and it has large, black spots below the ears.' jackal: wildDog: 'A wild dog is more larger than a jackal with patchy black, orange, and white fur.' kudu: eland: 'An eland is more stocky and ox-like than a kudu with long, straight horns that twist. It has a dewlap below the neck.' kudu: hartebeest: 'A hartebeest is more slender than a kudu with reddish fur, narrow face, and short, spiral horns.' kudu: nyala: 'A nyala is smaller than a kudu and females are more reddish-brown while males are chestnut with orange legs.' leopard: lionFemale: 'A lion has solid golden-tan fur without dark spots. ' leopard: lionCub: 'A lion cub is small with solid golden-tan fur without dark spots. ' leopard: serval: 'A serval is much smaller and lankier than a leopard with pointy ears, a small face, and a bushy tail.' lionCub: lionFemale: 'A female lion is much larger than a cub.' lionCub: leopard: 'A leopard is much larger than a lion cub and it has dark spots.' lionFemale: lionCub: 'A lion cub is much smaller than an adult female lion.' lionFemale: caracal: 'A caracal has pointy ears, reddish-tan fur, and white and black markings on the face.' lionFemale: leopard: 'A leopard has dark black spots.' mongoose: weasel: 'The weasel species in Gorongosa are skunklike with black and white fur.' nyala: kudu: 'A kudu is larger than a nyala with grayish-tan fur. Males have shaggy beards and massive, spiral horns.' oribi: duiker: 'A duiker is stockier than an oribi with a rounded back. The common duiker has a dark stripe on its nose, while the red duiker has reddish fur and the blue duiker has bluish-gray fur.' otter: honeyBadger: 'A honey badger has a distinct white patch on its back and is stockier than an otter' otter: mongoose: 'A mongoose is smaller and more slender than an otter, with a long thin tail.' otter: weasel: 'The weasel species in Gorongosa are skunklike with black and white fur.' pangolin: aardvark: 'An aardvark has brown fur and a long, flat snout.' reedbuck: bushbuck: 'A bushbuck has vertical white stripes and spots on the flanks as well as a rounded back.' reedbuck: impala: 'An impala has horizontal bands and males have large, spiral horns.' samangoMonkey: baboon: 'A baboon has yellow-brown fur and a light colored face.' samangoMonkey: vervetMonkey: 'A vervet monkey is much smaller than a samango monkey with a black face and light gray fur.' serval: leopard: 'A leopard is much larger and stockier than a serval and it has a round face and a smooth tail.' serval: wildCat: 'A wildcat is smaller and stockier than a serval and resembles a house cat.' vervetMonkey: baboon: 'A baboon is larger than a vervet monkey with yellow-brown fur and a light colored face.' vervetMonkey: samangoMonkey: 'A samango monkey is larger than a vervet monkey with bluish-gray fur and prominent fur on the cheeks.' warthog: bushpig: 'A bushpig has thick reddish-silvery fur and smaller tusks than a warthog.' warthog: hippopotamus: 'A hippopotamus is much larger than a warthog with a round body, face, and tiny pink ears. ' weasel: mongoose: 'The mongoose species in Gorongosa are various shades of brown while the weasels are black and white and skunklike.' wildDog: hyena: 'A hyena is stockier than a wild dog with yellowish fur and light brown spots. Its back is sloped downward. ' wildDog: jackal: 'A jackal is smaller than a wild dog with light brown and silver-black fur.' wildcat: serval: 'A serval is larger, taller, and more slender than a wildcat with yellow fur and black spots.' wildebeest: buffalo: 'A buffalo is stockier and more cattlelike than a wildebeest and lacks a beard and mane.' wildebeest: hartebeest: 'A hartebeest has reddish-brown fur, very short horns, and lacks a beard and mane.' animals: aardvark: label:'Aardvark' description:'Short, stocky animal with a long snout and a flat, piglike nose. The aardvark has brown to pink skin with thin, bristly hair, long ears, clawed toes, and a long, smooth tail. ' baboon: label:'Baboon' description:'Medium-sized primate with golden fur that is paler on the underbelly and a dark face that protrudes and widens at the nose and mouth. It has a straight brow, brown eyes, and a tail that juts out and drops.' birdOther: label:'Bird (other)' description:'There are about 400 bird species in Gorongosa, from small songbirds to large geese and ducks. If you find a bird that is not on the list, mark it here!' buffalo: label:'Buffalo' description:'Large, cattlelike animal with short legs and a long, tufted tail, dark brown to black fur, large, droopy ears, and a broad muzzle. Both sexes have U-shaped horns, but males horns form a fused shield on the top of their heads. ' bushbuck: label:'Bushbuck' description:'Medium-sized antelope with tan to chestnut brown fur with thin white stripes and spots on their flanks. Males are shaggy with darker fur and thick, spiral horns. Females are light tan and slender.' bushpig: label:'Bushpig' description:'Squat, flat-nosed, and piglike with long ears and reddish-brown fur with silver running down the spine. Both sexes have short, inconspicuous tusks. ' caracal: label:'Caracal' description:'Medium to large muscular cat with red-brown fur, a lighter underbelly, distinctive large, pointy ears with tufts of black fur at the tips, and white and black striped markings on the face.' civet: label:'Civet' description:'Long, stocky mammal with short legs and a pointy face. Fur is light brown-gray with a dark mask, white at the tip of the muzzle, dark legs, spots, and bands along the neck. ' crane: label:'Crane' description:'Long-legged, long-necked bird with a straight beak. There are two crane species in Gorongosa: the gray-crowned crane and the wattled crane. The gray-crowned crane has gray, white, and yellow feathers with a distinctive yellow fan of feathers on its head. The wattled crane has gray, black, and white feathers with red skin around its yellow beak.' duiker: label:'Duiker' description:'Duikers are small, deerlike antelope with a thin, short tail and colors ranging from blue-gray to red depending on the species. Males have short, straight horns. There are three species of duiker in Gorongosa: red, common, and blue duiker.' eland: label:'Eland' description:'Massive antelope with an oxlike body and short legs. Both sexes have straight, spiraled horns, a short mane, and a smooth light tan to gray coat with thin white stripes on the sides. Males have a large dewlap under the throat.' elephant: label:'Elephant' description:'Huge, leathery, gray-skinned mammal with large, floppy ears and thick, strong legs. It has a short, tufted tail and a long, thick trunk. Some elephants of both sexes have large, white tusks, but some individuals are born without tusks or have only one tusk. ' genet: label:'Genet' description:'Small, slender animal with tan-gray fur, large, ringed spots, a long, thick, black-ringed tail, and a white underbelly. It has a black stripe down the spine and a pointy muzzle. ' groundHornbill: label:'Ground Hornbill' description:'Large, stocky black bird with a red face, long, black beak, and red flaps of skin on its throat.' hare: label:'Hare' description:'Large rabbitlike animal with very long ears. There are two hare species in Gorongosa. The savanna hare has gray fur with a lighter brown underbelly, while the scrub hare is darker gray and has a white underbelly.' hartebeest: label:'Hartebeest' description:'Large, reddish-yellow antelope with an elongated, horselike face, large, pointy ears, humped shoulders, sloped back, and a light underbelly and hind parts with a short, tufted tail. Both sexes have curved, ridged horns.' hippopotamus: label:'Hippopotamus' description:'Massive and low to the ground with short legs, small ears, gray to pink skin, a wide muzzle, and a short tail with a bristly tassel.' honeyBadger: label:'Honey Badger' description:'Small, stocky mammal with short legs and a wide body. The lower half of the body is covered in black fur, and the head, back, and the top of the tail are covered in solid white-gray fur. ' human: label:'Human' description:'Sometimes people are captured in photos too, such as researchers checking the cameras, scouts on patrol, and tourists driving past in their vehicles.' hyena: label:'Hyena' description:'Medium-sized, stocky, doglike animal with a thick neck and a sloped back, golden tan-gray fur with dark spots, and small, round ears. ' impala: label:'Impala' description:'Medium-sized antelope with reddish-brown fur, white stripes around the eyes, and black stripes on the forehead and tail. Coat forms horizontal bands of red fur along the back, tan fur along the sides, and white fur on the underbelly. Males have large, spiral horns. ' jackal: label:'Jackal' description:'Medium-sized, gray-brown, doglike animal with a pointy face and ears. It has tan legs and underbelly with a black and white striped side, a gray back, and a long, bushy black tail with a white tip. ' kudu: label:'Kudu' description:'Large, lanky antelope with long legs, a short mane along the neck and shoulders, a brownish-gray to tan coat with vertical white stripes along the torso, a white chevron between the eyes, and large round ears. Males have a beard along the throat and massive spiral horns. ' leopard: label:'Leopard' description:'Large, muscular cat with short, yellow fur and black, ringed spots, small, round ears, and a long, smooth tail. ' lionCub: label:'Lion (cub)' description:'Cubs are smaller than adults with tan-yellow fur and some darker spots, a lighter underbelly, and white fur under the chin. Cubs do not have manes.' lionFemale: label:'Lion (female)' description:'Large, muscular cat with short tan-yellow fur, a long, smooth tail, a lighter underbelly, and white fur under the chin. Females do not have manes.' lionMale: label:'Lion (male)' description:'Large, muscular cat with short tan-yellow fur, a long, smooth tail with a tuft at the end, a lighter underbelly, and white fur under the chin. Males have a thick reddish mane that gets darker and thicker with age.' mammalOther: label:'Mammal (other)' description:'There are over 70 additional species of mammals in Gorongosa that are not on this list, including bats, rats, mice, squirrels, gerbils, shrews, and hyraxes. If you find one of these mammals that is not on the list, mark it here.' mongoose: label:'Mongoose' description:'Small, sleek mammal with short legs, a long body, and a long tail. There are eight mongoose species in Gorongosa that range in size and color from the brown dwarf mongoose to the larger Egyptian mongoose with bushy gray fur and tiny spots.' nyala: label:'Nyala' description:'Medium-sized antelope with long legs and a shaggy tail. Males are dark brown to reddish with thin white stripes and small spots on the rump, orange legs and a white patch of fur between the eyes. Males also have a mane along the neck, chest, and belly as well as long, spiraling horns. Females are tan with vertical white stripes and spots on the sides, large ears, and no horns.' oribi: label:'Oribi' description:'Small, deerlike antelope with a long, slender neck, brownish fur with a white underbelly, white around the eyes and muzzle, and distinctive black spots below the ears. Males have short, straight horns.' otter: label:'Otter' description:'Small, sleek mammal with a long body, short legs, and brown-gray fur. Otters have webbed feet, small, round ears, and a thick tail. There are two otter species in Gorongosa. The Cape clawless otter is lighter brown has a pale underbelly, while the spotted-necked otter is smaller and has darker fur with white spots on the neck.' pangolin: label:'Pangolin' description:'Small, stocky animal with short legs and a long, thick tail. The pangolin is covered with hard, armored, brown scales. It has a small, pointy face and large claws.' porcupine: label:'Porcupine' description:'Short, stocky animal with brown fur and long, black and white quills covering its back from head to tail. It has a small face with dark eyes and a blunt nose. It is often seen at night.' raptorOther: label:'Raptor (other)' description:'Raptors are predatory birds with large wingspans, sharp, hooked beaks, and huge talons. In addition to vultures, Gorongosa has over 30 species of raptors, including eagles, hawks, kites, falcons, and buzzards. ' reedbuck: label:'Reedbuck' description:'Medium-sized, slender antelope with tan to brown fur, a white underbelly, white around the eyes and muzzle, and distinctive dark spots under their large ears. Males have ringed horns that curve forward.' reptile: label:'Reptile' description:'There are over 60 species of reptiles in Gorongosa including crocodiles, snakes, lizards, chameleons, geckos, skinks, tortoises, terrapins, and turtles. This category includes any reptile that you find!' sableAntelope: label:'Sable Antelope' description:'Full-bodied, horselike antelope with a thick neck, mane, long, tufted tail, chestnut brown to black fur with white underbelly and chin, and white under the eyes with a black stripe down the nose. Both sexes have large, ringed horns that curve backward. ' samangoMonkey: label:'Samango Monkey' description:'Medium-sized monkey with long, gray, speckled fur. Its face is dark gray, while its arms and legs fade to black toward the hands and feet. It has brown eyes, a white throat and underbelly, and a long, black tail.' secretaryBird: label:'Secretary bird' description:'Large, tall bird with gray feathers on the body and black feathers on the tips of the wings and legs. Its legs are extremely long, and its face is red-orange with a white beak. It has black feathers protruding from the back of its head like a fan.' serval: label:'Serval' description:'Medium-sized cat with long legs, a long neck, a lanky body, yellow-tan fur with black spots, very large ears, a long, striped tail, and black stripes around the neck, nose, and eyes.' vervetMonkey: label:'Vervet Monkey' description:'Small, gray-furred monkey whose face is black and ringed in white fur. Its hands, feet, and ears are also black, and it has a very long, black-tipped tail. ' vulture: label:'Vulture' description:'A large raptor with a bald head, large wings, and talons that is often found scavenging on carcasses. Gorongosa has five species of vultures, each with a distinct appearance. The hooded, white-headed, and lappet-faced vultures all have mostly black feathers and pink to blue faces. The white-backed and Egyptian vultures both have lighter gray to white feathers with gray and yellow faces (respectively).' warthog: label:'Warthog' description:'Squat, maned, slate-furred, and piglike with a long, thin, tufted tail. Males have curved tusks at the end of their broad snout, while females have shorter tusks. Both sexes have distinctive warts below their eyes.' waterbuck: label:'Waterbuck' description:'Large antelope with a wide, strong build, brownish-gray fur, a long neck with a shaggy mane, white fur under the neck and on the muzzle, and a white ring around the rump. Males have ringed horns that curve forward.' weasel: label:'Weasel' description:'The two weasel species in Gorongosa are the zorilla and the African striped weasel. Both are skunklike with black fur, large white stripes along the back, and a fluffy tail. Zorillas are fluffier with three white patches on the face, while African striped weasels are smoother with a black face.' wildDog: label:'Wild Dog' description:'Medium-sized, lanky doglike animal with patchy tan, black, and white fur. It has a long, black muzzle and big, round, mostly black ears.' wildcat: label:'Wildcat' description:'Resembles a domestic tabby cat with brown to gray fur and darker stripes with a long striped tail. ' wildebeest: label:'Wildebeest' description:'Large, muscular antelope with a dark muzzle with a mane of hair along the throat and spine, broad shoulders, blue-gray to brown fur with subtle stripes, and a long, tufted tail. Both sexes have large, U-shaped horns.' zebra: label:'Zebra' description:'Horselike animal with short, white fur and distinctive black stripes. The mane is striped and sticks up vertically along the neck. The muzzle, nose, and tufted tail are black.' characteristics: like: 'Looks like...' coat: 'Coat' tail: 'Tail' build: 'Build' pattern: 'Pattern' horns: 'Horns' characteristicValues: likeCatdog: 'cat/dog' likeCowhorse: 'cow/horse' likeAntelopedeer: 'antelope/deer' likePrimate: 'primate' likeWeasel: 'weasel' likeBird: 'bird' likeOther: 'other' patternSolid: 'solid' patternStripes: 'stripes' patternBands: 'bands' patternSpots: 'spots' coatTanyellow: 'tan/yellow' coatRed: 'red' coatBrown: 'brown' coatWhite: 'white' coatGray: 'gray' coatBlack: 'black' hornsStraight: 'straight' hornsCurved: 'curved' hornsSpiral: 'spiral' hornsUshaped: 'u-shaped' tailSmooth: 'smooth' tailBushy: 'bushy' tailTufted: 'tufted' tailLong: 'long' tailShort: 'short' buildStocky: 'stocky' buildLanky: 'lanky' buildLarge: 'large' buildSmall: 'small' buildLowslung: 'low-slung' profile: header: "Your Profile" favorites: 'Favorites' recents: 'Recents' noFavorites: 'You have no favorites!' noRecents: 'You have no recent classifications!' showing: 'Showing' loadMore: 'Load more' science: understandingPopulations: ''' <h2>Understanding wildlife populations</h2> <p>Forests are home to dozens of native mammals, hundreds of other vertebrate species, and thousands of invertebrates and native plant species, living together in diverse natural communities. WildlifeWatch is a collaborative effort to utilize camera traps, also known as trail cameras, to learn about the distribution and trends of our wildlife populations.</p> ''' whyWeNeedYou: ''' <h2>Why we need you</h2> <p>Over the course of a month, a single camera might take thousands of photographs. You help to make all these photographs meaningful by classifying the type and number of animals in the image. Because we know where and when these photographs were taken, we can create maps for both common and rare species across the state and visualize how animal populations change through time. From black bears to badgers, see what critters you can spot roaming the Wisconsin forests! Share your favorites and join the discussion about what you are observing along the way. We will share with you what we are learning back here at Zooniverse.</p> ''' education: inTheClassroom: ''' <h2>Citizen science in the classroom</h2> <p>Wildlife Watch is a great opportunity to integrate science and technology in the classroom and a unique way for students to learn about wildlife and their habitats.</p> <p><a href="http://www.zooteach.org">ZooTeach</a> is a companion website to Zooniverse where educators can find and share educational resources relating to WildlifeWatch and the other Zooniverse citizen science projects. WildlifeWatch is a recent addition to Zooniverse, so if you have any ideas for how to use the project in the classroom, please share your lesson ideas or resources on ZooTeach.</p> <p>There are a number of excellent wildlife education resources available online. A few of our favorites are below:</p> <ul> <li><a href="http://dnr.wi.gov/eek/">http://dnr.wi.gov/eek/</a> - Environmental Education for Kids! (EEK!) is an electronic magazine for kids in grades 4-8 published by the Wisconsin Department of Natural Resources. It includes information on Wisconsin’s wildlife and resources for educators on how to help students use EEK!</li> <li><a href="http://projectwild.org/">http://projectwild.org/</a> - Project WILD is a nationwide program that provides resources for educators in teaching about wildlife and their habitat. The materials are available through Project WILD workshops lead by certified instructors. The Project WILD handbook includes more than 165 hands-on activities for PreK-12.</li> </ul> ''' team: navigation: people: 'People' organizations: 'Organizations' credit: 'Image Credits' bios: townsend: 'Phil Townsend is a professor of Forest &amp; Wildlife Ecology at the University of Wisconsin. He is interested in how different components of ecosystems interact across landscapes, for example how nutrients and water affect vegetation, and then how patterns of vegetation processes affect insects and animals. He is particularly interested in how we can leverage a range of technologies including remote sensing to better understand ecosystems.' zuckerberg: 'Dr. Benjamin Zuckerberg is an assistant professor in the Department of Forest and Wildlife Ecology at the University of Wisconsin-Madison. His research focuses on how climate change and habitat loss impacts wildlife populations. He is a strong advocate for the role of the public in collecting biological data. Using the data from these “citizen science” programs, Ben has studied shifts in bird ranges and migration in response to a changing climate.' deelen: 'Tim Van Deelen has been on the faculty at the UW-Madison since 2004. Tim’s research specializes in the applied management of wildlife with an emphasis on large mammals in Wisconsin and is a frequent collaborator with the Wisconsin DNR and the Apostle Islands National Lakeshore. Prior positions include working as the research specialist for deer in the Wisconsin Department of Natural Resources and as a Research Scientist for the Illinois Natural History Survey where he had a joint appointment with the University of Illinois at Urbana-Champaign.' singh: 'Aditya Singh is a post-doctoral scientist with the Department of Forest and Wildlife Ecology at the University of Wisconsin-Madison. He uses a combination of airborne and remotely sensed data to study the impacts of environmental change and disturbance on landscape-scale indicators of ecosystem health.' martin: 'Karl Martin is the State Director for the Community, Natural Resource and Economic Development Program and an Assistant Dean with the University of Wisconsin Cooperative Extension. He is an adjunct Associate Professor at the University of Wisconsin-Madison’s Forest and Wildlife Ecology Department and recently served as the Wildlife and Forestry Research Section Chief at the Wisconsin Department of Natural Resources. Karl received his Bachelors degree in Wildlife Ecology at UW-Madison and his Masters and Doctorate degrees at Oregon State University. Karl’s research has focused on interaction of forest management and multi-scale wildlife habitat relationships. His current position focuses on the ‘Wisconsin Idea’ of taking the information and resources of the University to communities and citizens of the state.' organizations: uwm: 'Members of the Wildlife Watch team are ecologists at the University of Wisconsin Madison in the Department of Forest and Wildlife Ecology. UW-Madison is a public, land-grant institution founded in 1848 whose mission is to provide “a learning environment in which faculty, staff and students can discover, examine critically, preserve and transmit the knowledge, wisdom and values that will help insure the survival of this and future generations and improve the quality of life for all.”' nasa: 'NASA provided partial funding for the first year of the project thought the Ecological Forecasting for Conservation and Natural Resource Management Program. The NASA Applied Sciences Program supports projects that enable uses of Earth observations in organizations’ policy, business, and management decisions.' wcbmn: 'The Wisconsin Citizen-based Monitoring (WCBM) Network provided funding for materials used in training citizen volunteers during the first year of the project. The WCBM Network is a stakeholder collaboration “to improve the efficiency and effectiveness of monitoring efforts by providing coordination, communications, technical, and financial resources and recognition to members of the Wisconsin citizen-based monitoring community.”' adler: 'The Adler Planetarium was founded in 1930 by Chicago business leader Max Adler. A recognized leader in public learning, the Adler inspires young people -particularly women and minorities - to pursue careers in science, technology, engineering, and math. Scientists, historians and educators at the museum inspire the next generation of explorers.' uwExtension: 'The University of Wisconsin Extension provides ongoing support for the project. The Extension’s purpose is to "connect people with the University of Wisconsin and engage with them in transforming lives and communities."' connect: header: 'Connect' action: 'Get Started'
139651
module.exports = navigation: home: 'Home' classify: 'Classify' science: 'Science' team: 'Team' education: 'Education' profile: 'Profile' talk: 'Talk' blog: 'Blog' home: heading: 'Welcome to Wildlife Watch' rightBannerHeader: "What is Wildlife Watch?" tagline: 'WildlifeWatch is an effort to monitor forest wildlife year-round across a network of trail cameras. Help us to identify the animals captured on camera and better understand the distribution and trends of our wildlife populations.' action: 'Get Started' nasa: 'In partnership with NASA' currentStatus: '<span class="classification-count">0</span> classifications by <span class="user-count">0</span> volunteers' stats: header: "WILDLIFE WATCH Statistics" activeUsers: "Active Users" crittersIdentified: "Critters Identified" totalImages: "Images Total" complete: "Complete" siteIntro: s1: title: "Welcome!" content: "Welcome to Wildlife Watch! In this project, we are asking you to identify animals found in camera trap photos from around Wisconsin. Your help allows us better understand how animal populations across the state change through time." s2: title: "Identifying animals" content: "You are presented with a photo on the left and a list of potential animals on the right. When you spot an animal within a photo, simply click the corresponding animal on the right. You will be asked to supply some followup info, such as the number of animals found in the image." s3: title: "Filtering by characteristics" content: "Occasionally it is difficult to determine which animal is in the photo. Just above the list of animals is a variety of methods to filter the animal list. Selecting different options reduces the number of choices, making your job easier." s4: title: "Made a mistake?" content: "If you need to delete any of your existing marks while viewing an image, simply find your animal in the list below the image and click the 'X' icon. Don’t worry if you’re unsure about your choices, though—even a guess is more helpful than nothing!" s5: title: "That's it!" content: "You may catch up on project updates through speaking with other volunteers via Talk." classify: deleteAnnotation: 'Delete' notSignedIn: 'You\'re not signed in!' favorite: 'Favorite' unfavorite: 'Unfavorite' play: 'View series' pause: 'Stop' satellite: 'Satellite view' nothingLabel: 'Nothing here' nextSubjectButton: 'Finish' share: 'Share' tweet: 'Tweet' pin: 'Pin it' discuss: 'Discuss' next: 'Next capture' search: 'Search' nothingToShow: 'There\'s nothing to show with these filters.' clearFilters: 'Clear filters' oftenConfused: 'Often confused with:' count: 'How many' startTutorial: 'Start tutorial' deer: fawns: "Fawns" antlered: "Adult antlered" antlerless: "Adult antlerless" notVisible: "Adult head not visible" behavior: 'Behavior' behaviors: standing: 'standing' resting: 'resting' moving: 'moving' eating: 'eating' interacting: 'interacting' babies: 'Young present' rain: 'Raining' cancel: 'Cancel' identify: 'Identify' differences: aardvark: pangolin: 'A pangolin is covered in scales while an aardvark has brown fur. It also has a shorter, pointier snout than an aardvark.' baboon: samangoMonkey: 'A samango monkey has bluish-gray fur while a baboon has yellow-brown fur. It also has a dark face with prominent fur on the cheeks.' baboon: vervetMonkey: 'A vervet monkey is much smaller than a baboon with a black face and light gray fur.' buffalo: wildebeest: 'A wildebeest is more slender than a buffalo with a long, narrow face and a beard.' bushbuck: reedbuck: 'A reedbuck has solid tan fur without white spots or stripes. Its horns are ringed and it has a large, black spot below the ears.' bushbuck: nyala: 'A nyala female has prominent vertical white stripes and white markings between the eyes, while a bushbuck female has lighter stripes and more prominent spots.' bushpig: warthog: 'A warthog is a slate gray color with prominent warts on the sides of its face and larger tusks than a bushpig.' caracal: lionFemale: 'A lion is larger than a caracal with rounded ears, no white or black markings on the face or ears, and its fur is a lighter golden-yellow color.' civet: genet: 'A genet is more slender than a civet with a much longer, bushier tail. ' duiker: oribi: 'An oribi is more slender and taller than a duiker with a flat back, white underbelly, and prominent black spots below the ears. ' eland: hartebeest: 'A hartebeest is a taller and more slender than an eland with reddish fur, narrow face, and short, spiral horns.' eland: kudu: 'A kudu is taller and less ox-like than an eland, it has massive spiral horns and lacks a dewlap on the throat.' genet: civet: 'A civet is stockier than a genet with a much shorter tail and a dark mask on the face.' hartebeest: eland: 'An eland is more stocky and ox-like than a hartebeest with long, straight horns that twist. It has a dewlap below the neck.' hartebeest: wildebeest: 'A wildebeest is dark gray-brown with a mane and beard. Its horns are longer than a hartebeest.' hartebeest: kudu: 'A kudu is stockier than a hartebeest with tan-gray fur, vertical stripes, and the males have manes and massive spiral horns.' hippopotamus: warthog: 'A warthog is much smaller than a hippopotamus with horns and prominent warts on the face.' hyena: wildDog: 'A wild dog is more slender than a hyena with patchy black, orange, and white fur and a flat back.' impala: bushbuck: 'A bushbuck has vertical white stripes and spots on the flanks as well as a rounded back.' impala: reedbuck: 'A reedbuck has solid tan fur without horizontal bands. Its horns are curved and ringed and it has large, black spots below the ears.' jackal: wildDog: 'A wild dog is more larger than a jackal with patchy black, orange, and white fur.' kudu: eland: 'An eland is more stocky and ox-like than a kudu with long, straight horns that twist. It has a dewlap below the neck.' kudu: hartebeest: 'A hartebeest is more slender than a kudu with reddish fur, narrow face, and short, spiral horns.' kudu: nyala: 'A nyala is smaller than a kudu and females are more reddish-brown while males are chestnut with orange legs.' leopard: lionFemale: 'A lion has solid golden-tan fur without dark spots. ' leopard: lionCub: 'A lion cub is small with solid golden-tan fur without dark spots. ' leopard: serval: 'A serval is much smaller and lankier than a leopard with pointy ears, a small face, and a bushy tail.' lionCub: lionFemale: 'A female lion is much larger than a cub.' lionCub: leopard: 'A leopard is much larger than a lion cub and it has dark spots.' lionFemale: lionCub: 'A lion cub is much smaller than an adult female lion.' lionFemale: caracal: 'A caracal has pointy ears, reddish-tan fur, and white and black markings on the face.' lionFemale: leopard: 'A leopard has dark black spots.' mongoose: weasel: 'The weasel species in Gorongosa are skunklike with black and white fur.' nyala: kudu: 'A kudu is larger than a nyala with grayish-tan fur. Males have shaggy beards and massive, spiral horns.' oribi: duiker: 'A duiker is stockier than an oribi with a rounded back. The common duiker has a dark stripe on its nose, while the red duiker has reddish fur and the blue duiker has bluish-gray fur.' otter: honeyBadger: 'A honey badger has a distinct white patch on its back and is stockier than an otter' otter: mongoose: 'A mongoose is smaller and more slender than an otter, with a long thin tail.' otter: weasel: 'The weasel species in Gorongosa are skunklike with black and white fur.' pangolin: aardvark: 'An aardvark has brown fur and a long, flat snout.' reedbuck: bushbuck: 'A bushbuck has vertical white stripes and spots on the flanks as well as a rounded back.' reedbuck: impala: 'An impala has horizontal bands and males have large, spiral horns.' samangoMonkey: baboon: 'A baboon has yellow-brown fur and a light colored face.' samangoMonkey: vervetMonkey: 'A vervet monkey is much smaller than a samango monkey with a black face and light gray fur.' serval: leopard: 'A leopard is much larger and stockier than a serval and it has a round face and a smooth tail.' serval: wildCat: 'A wildcat is smaller and stockier than a serval and resembles a house cat.' vervetMonkey: baboon: 'A baboon is larger than a vervet monkey with yellow-brown fur and a light colored face.' vervetMonkey: samangoMonkey: 'A samango monkey is larger than a vervet monkey with bluish-gray fur and prominent fur on the cheeks.' warthog: bushpig: 'A bushpig has thick reddish-silvery fur and smaller tusks than a warthog.' warthog: hippopotamus: 'A hippopotamus is much larger than a warthog with a round body, face, and tiny pink ears. ' weasel: mongoose: 'The mongoose species in Gorongosa are various shades of brown while the weasels are black and white and skunklike.' wildDog: hyena: 'A hyena is stockier than a wild dog with yellowish fur and light brown spots. Its back is sloped downward. ' wildDog: jackal: 'A jackal is smaller than a wild dog with light brown and silver-black fur.' wildcat: serval: 'A serval is larger, taller, and more slender than a wildcat with yellow fur and black spots.' wildebeest: buffalo: 'A buffalo is stockier and more cattlelike than a wildebeest and lacks a beard and mane.' wildebeest: hartebeest: 'A hartebeest has reddish-brown fur, very short horns, and lacks a beard and mane.' animals: aardvark: label:'Aardvark' description:'Short, stocky animal with a long snout and a flat, piglike nose. The aardvark has brown to pink skin with thin, bristly hair, long ears, clawed toes, and a long, smooth tail. ' baboon: label:'Baboon' description:'Medium-sized primate with golden fur that is paler on the underbelly and a dark face that protrudes and widens at the nose and mouth. It has a straight brow, brown eyes, and a tail that juts out and drops.' birdOther: label:'Bird (other)' description:'There are about 400 bird species in Gorongosa, from small songbirds to large geese and ducks. If you find a bird that is not on the list, mark it here!' buffalo: label:'Buffalo' description:'Large, cattlelike animal with short legs and a long, tufted tail, dark brown to black fur, large, droopy ears, and a broad muzzle. Both sexes have U-shaped horns, but males horns form a fused shield on the top of their heads. ' bushbuck: label:'Bushbuck' description:'Medium-sized antelope with tan to chestnut brown fur with thin white stripes and spots on their flanks. Males are shaggy with darker fur and thick, spiral horns. Females are light tan and slender.' bushpig: label:'Bushpig' description:'Squat, flat-nosed, and piglike with long ears and reddish-brown fur with silver running down the spine. Both sexes have short, inconspicuous tusks. ' caracal: label:'Caracal' description:'Medium to large muscular cat with red-brown fur, a lighter underbelly, distinctive large, pointy ears with tufts of black fur at the tips, and white and black striped markings on the face.' civet: label:'Civet' description:'Long, stocky mammal with short legs and a pointy face. Fur is light brown-gray with a dark mask, white at the tip of the muzzle, dark legs, spots, and bands along the neck. ' crane: label:'Crane' description:'Long-legged, long-necked bird with a straight beak. There are two crane species in Gorongosa: the gray-crowned crane and the wattled crane. The gray-crowned crane has gray, white, and yellow feathers with a distinctive yellow fan of feathers on its head. The wattled crane has gray, black, and white feathers with red skin around its yellow beak.' duiker: label:'Duiker' description:'Duikers are small, deerlike antelope with a thin, short tail and colors ranging from blue-gray to red depending on the species. Males have short, straight horns. There are three species of duiker in Gorongosa: red, common, and blue duiker.' eland: label:'Eland' description:'Massive antelope with an oxlike body and short legs. Both sexes have straight, spiraled horns, a short mane, and a smooth light tan to gray coat with thin white stripes on the sides. Males have a large dewlap under the throat.' elephant: label:'Elephant' description:'Huge, leathery, gray-skinned mammal with large, floppy ears and thick, strong legs. It has a short, tufted tail and a long, thick trunk. Some elephants of both sexes have large, white tusks, but some individuals are born without tusks or have only one tusk. ' genet: label:'Genet' description:'Small, slender animal with tan-gray fur, large, ringed spots, a long, thick, black-ringed tail, and a white underbelly. It has a black stripe down the spine and a pointy muzzle. ' groundHornbill: label:'Ground Hornbill' description:'Large, stocky black bird with a red face, long, black beak, and red flaps of skin on its throat.' hare: label:'Hare' description:'Large rabbitlike animal with very long ears. There are two hare species in Gorongosa. The savanna hare has gray fur with a lighter brown underbelly, while the scrub hare is darker gray and has a white underbelly.' hartebeest: label:'Hartebeest' description:'Large, reddish-yellow antelope with an elongated, horselike face, large, pointy ears, humped shoulders, sloped back, and a light underbelly and hind parts with a short, tufted tail. Both sexes have curved, ridged horns.' hippopotamus: label:'Hippopotamus' description:'Massive and low to the ground with short legs, small ears, gray to pink skin, a wide muzzle, and a short tail with a bristly tassel.' honeyBadger: label:'Honey Badger' description:'Small, stocky mammal with short legs and a wide body. The lower half of the body is covered in black fur, and the head, back, and the top of the tail are covered in solid white-gray fur. ' human: label:'Human' description:'Sometimes people are captured in photos too, such as researchers checking the cameras, scouts on patrol, and tourists driving past in their vehicles.' hyena: label:'Hyena' description:'Medium-sized, stocky, doglike animal with a thick neck and a sloped back, golden tan-gray fur with dark spots, and small, round ears. ' impala: label:'Impala' description:'Medium-sized antelope with reddish-brown fur, white stripes around the eyes, and black stripes on the forehead and tail. Coat forms horizontal bands of red fur along the back, tan fur along the sides, and white fur on the underbelly. Males have large, spiral horns. ' jackal: label:'Jackal' description:'Medium-sized, gray-brown, doglike animal with a pointy face and ears. It has tan legs and underbelly with a black and white striped side, a gray back, and a long, bushy black tail with a white tip. ' kudu: label:'Kudu' description:'Large, lanky antelope with long legs, a short mane along the neck and shoulders, a brownish-gray to tan coat with vertical white stripes along the torso, a white chevron between the eyes, and large round ears. Males have a beard along the throat and massive spiral horns. ' leopard: label:'Leopard' description:'Large, muscular cat with short, yellow fur and black, ringed spots, small, round ears, and a long, smooth tail. ' lionCub: label:'Lion (cub)' description:'Cubs are smaller than adults with tan-yellow fur and some darker spots, a lighter underbelly, and white fur under the chin. Cubs do not have manes.' lionFemale: label:'Lion (female)' description:'Large, muscular cat with short tan-yellow fur, a long, smooth tail, a lighter underbelly, and white fur under the chin. Females do not have manes.' lionMale: label:'Lion (male)' description:'Large, muscular cat with short tan-yellow fur, a long, smooth tail with a tuft at the end, a lighter underbelly, and white fur under the chin. Males have a thick reddish mane that gets darker and thicker with age.' mammalOther: label:'Mammal (other)' description:'There are over 70 additional species of mammals in Gorongosa that are not on this list, including bats, rats, mice, squirrels, gerbils, shrews, and hyraxes. If you find one of these mammals that is not on the list, mark it here.' mongoose: label:'Mongoose' description:'Small, sleek mammal with short legs, a long body, and a long tail. There are eight mongoose species in Gorongosa that range in size and color from the brown dwarf mongoose to the larger Egyptian mongoose with bushy gray fur and tiny spots.' nyala: label:'Nyala' description:'Medium-sized antelope with long legs and a shaggy tail. Males are dark brown to reddish with thin white stripes and small spots on the rump, orange legs and a white patch of fur between the eyes. Males also have a mane along the neck, chest, and belly as well as long, spiraling horns. Females are tan with vertical white stripes and spots on the sides, large ears, and no horns.' oribi: label:'Oribi' description:'Small, deerlike antelope with a long, slender neck, brownish fur with a white underbelly, white around the eyes and muzzle, and distinctive black spots below the ears. Males have short, straight horns.' otter: label:'Otter' description:'Small, sleek mammal with a long body, short legs, and brown-gray fur. Otters have webbed feet, small, round ears, and a thick tail. There are two otter species in Gorongosa. The Cape clawless otter is lighter brown has a pale underbelly, while the spotted-necked otter is smaller and has darker fur with white spots on the neck.' pangolin: label:'Pangolin' description:'Small, stocky animal with short legs and a long, thick tail. The pangolin is covered with hard, armored, brown scales. It has a small, pointy face and large claws.' porcupine: label:'Porcupine' description:'Short, stocky animal with brown fur and long, black and white quills covering its back from head to tail. It has a small face with dark eyes and a blunt nose. It is often seen at night.' raptorOther: label:'Raptor (other)' description:'Raptors are predatory birds with large wingspans, sharp, hooked beaks, and huge talons. In addition to vultures, Gorongosa has over 30 species of raptors, including eagles, hawks, kites, falcons, and buzzards. ' reedbuck: label:'Reedbuck' description:'Medium-sized, slender antelope with tan to brown fur, a white underbelly, white around the eyes and muzzle, and distinctive dark spots under their large ears. Males have ringed horns that curve forward.' reptile: label:'Reptile' description:'There are over 60 species of reptiles in Gorongosa including crocodiles, snakes, lizards, chameleons, geckos, skinks, tortoises, terrapins, and turtles. This category includes any reptile that you find!' sableAntelope: label:'Sable Antelope' description:'Full-bodied, horselike antelope with a thick neck, mane, long, tufted tail, chestnut brown to black fur with white underbelly and chin, and white under the eyes with a black stripe down the nose. Both sexes have large, ringed horns that curve backward. ' samangoMonkey: label:'Samango Monkey' description:'Medium-sized monkey with long, gray, speckled fur. Its face is dark gray, while its arms and legs fade to black toward the hands and feet. It has brown eyes, a white throat and underbelly, and a long, black tail.' secretaryBird: label:'Secretary bird' description:'Large, tall bird with gray feathers on the body and black feathers on the tips of the wings and legs. Its legs are extremely long, and its face is red-orange with a white beak. It has black feathers protruding from the back of its head like a fan.' serval: label:'Serval' description:'Medium-sized cat with long legs, a long neck, a lanky body, yellow-tan fur with black spots, very large ears, a long, striped tail, and black stripes around the neck, nose, and eyes.' vervetMonkey: label:'Vervet Monkey' description:'Small, gray-furred monkey whose face is black and ringed in white fur. Its hands, feet, and ears are also black, and it has a very long, black-tipped tail. ' vulture: label:'Vulture' description:'A large raptor with a bald head, large wings, and talons that is often found scavenging on carcasses. Gorongosa has five species of vultures, each with a distinct appearance. The hooded, white-headed, and lappet-faced vultures all have mostly black feathers and pink to blue faces. The white-backed and Egyptian vultures both have lighter gray to white feathers with gray and yellow faces (respectively).' warthog: label:'Warthog' description:'Squat, maned, slate-furred, and piglike with a long, thin, tufted tail. Males have curved tusks at the end of their broad snout, while females have shorter tusks. Both sexes have distinctive warts below their eyes.' waterbuck: label:'Waterbuck' description:'Large antelope with a wide, strong build, brownish-gray fur, a long neck with a shaggy mane, white fur under the neck and on the muzzle, and a white ring around the rump. Males have ringed horns that curve forward.' weasel: label:'Weasel' description:'The two weasel species in Gorongosa are the zorilla and the African striped weasel. Both are skunklike with black fur, large white stripes along the back, and a fluffy tail. Zorillas are fluffier with three white patches on the face, while African striped weasels are smoother with a black face.' wildDog: label:'Wild Dog' description:'Medium-sized, lanky doglike animal with patchy tan, black, and white fur. It has a long, black muzzle and big, round, mostly black ears.' wildcat: label:'Wildcat' description:'Resembles a domestic tabby cat with brown to gray fur and darker stripes with a long striped tail. ' wildebeest: label:'Wildebeest' description:'Large, muscular antelope with a dark muzzle with a mane of hair along the throat and spine, broad shoulders, blue-gray to brown fur with subtle stripes, and a long, tufted tail. Both sexes have large, U-shaped horns.' zebra: label:'Zebra' description:'Horselike animal with short, white fur and distinctive black stripes. The mane is striped and sticks up vertically along the neck. The muzzle, nose, and tufted tail are black.' characteristics: like: 'Looks like...' coat: 'Coat' tail: 'Tail' build: 'Build' pattern: 'Pattern' horns: 'Horns' characteristicValues: likeCatdog: 'cat/dog' likeCowhorse: 'cow/horse' likeAntelopedeer: 'antelope/deer' likePrimate: 'primate' likeWeasel: 'weasel' likeBird: 'bird' likeOther: 'other' patternSolid: 'solid' patternStripes: 'stripes' patternBands: 'bands' patternSpots: 'spots' coatTanyellow: 'tan/yellow' coatRed: 'red' coatBrown: 'brown' coatWhite: 'white' coatGray: 'gray' coatBlack: 'black' hornsStraight: 'straight' hornsCurved: 'curved' hornsSpiral: 'spiral' hornsUshaped: 'u-shaped' tailSmooth: 'smooth' tailBushy: 'bushy' tailTufted: 'tufted' tailLong: 'long' tailShort: 'short' buildStocky: 'stocky' buildLanky: 'lanky' buildLarge: 'large' buildSmall: 'small' buildLowslung: 'low-slung' profile: header: "Your Profile" favorites: 'Favorites' recents: 'Recents' noFavorites: 'You have no favorites!' noRecents: 'You have no recent classifications!' showing: 'Showing' loadMore: 'Load more' science: understandingPopulations: ''' <h2>Understanding wildlife populations</h2> <p>Forests are home to dozens of native mammals, hundreds of other vertebrate species, and thousands of invertebrates and native plant species, living together in diverse natural communities. WildlifeWatch is a collaborative effort to utilize camera traps, also known as trail cameras, to learn about the distribution and trends of our wildlife populations.</p> ''' whyWeNeedYou: ''' <h2>Why we need you</h2> <p>Over the course of a month, a single camera might take thousands of photographs. You help to make all these photographs meaningful by classifying the type and number of animals in the image. Because we know where and when these photographs were taken, we can create maps for both common and rare species across the state and visualize how animal populations change through time. From black bears to badgers, see what critters you can spot roaming the Wisconsin forests! Share your favorites and join the discussion about what you are observing along the way. We will share with you what we are learning back here at Zooniverse.</p> ''' education: inTheClassroom: ''' <h2>Citizen science in the classroom</h2> <p>Wildlife Watch is a great opportunity to integrate science and technology in the classroom and a unique way for students to learn about wildlife and their habitats.</p> <p><a href="http://www.zooteach.org">ZooTeach</a> is a companion website to Zooniverse where educators can find and share educational resources relating to WildlifeWatch and the other Zooniverse citizen science projects. WildlifeWatch is a recent addition to Zooniverse, so if you have any ideas for how to use the project in the classroom, please share your lesson ideas or resources on ZooTeach.</p> <p>There are a number of excellent wildlife education resources available online. A few of our favorites are below:</p> <ul> <li><a href="http://dnr.wi.gov/eek/">http://dnr.wi.gov/eek/</a> - Environmental Education for Kids! (EEK!) is an electronic magazine for kids in grades 4-8 published by the Wisconsin Department of Natural Resources. It includes information on Wisconsin’s wildlife and resources for educators on how to help students use EEK!</li> <li><a href="http://projectwild.org/">http://projectwild.org/</a> - Project WILD is a nationwide program that provides resources for educators in teaching about wildlife and their habitat. The materials are available through Project WILD workshops lead by certified instructors. The Project WILD handbook includes more than 165 hands-on activities for PreK-12.</li> </ul> ''' team: navigation: people: 'People' organizations: 'Organizations' credit: 'Image Credits' bios: townsend: '<NAME> is a professor of Forest &amp; Wildlife Ecology at the University of Wisconsin. He is interested in how different components of ecosystems interact across landscapes, for example how nutrients and water affect vegetation, and then how patterns of vegetation processes affect insects and animals. He is particularly interested in how we can leverage a range of technologies including remote sensing to better understand ecosystems.' zuckerberg: 'Dr. <NAME> is an assistant professor in the Department of Forest and Wildlife Ecology at the University of Wisconsin-Madison. His research focuses on how climate change and habitat loss impacts wildlife populations. He is a strong advocate for the role of the public in collecting biological data. Using the data from these “citizen science” programs, <NAME> has studied shifts in bird ranges and migration in response to a changing climate.' deelen: '<NAME> has been on the faculty at the UW-Madison since 2004. Tim’s research specializes in the applied management of wildlife with an emphasis on large mammals in Wisconsin and is a frequent collaborator with the Wisconsin DNR and the Apostle Islands National Lakeshore. Prior positions include working as the research specialist for deer in the Wisconsin Department of Natural Resources and as a Research Scientist for the Illinois Natural History Survey where he had a joint appointment with the University of Illinois at Urbana-Champaign.' singh: '<NAME> is a post-doctoral scientist with the Department of Forest and Wildlife Ecology at the University of Wisconsin-Madison. He uses a combination of airborne and remotely sensed data to study the impacts of environmental change and disturbance on landscape-scale indicators of ecosystem health.' <NAME>: '<NAME> is the State Director for the Community, Natural Resource and Economic Development Program and an Assistant Dean with the University of Wisconsin Cooperative Extension. He is an adjunct Associate Professor at the University of Wisconsin-Madison’s Forest and Wildlife Ecology Department and recently served as the Wildlife and Forestry Research Section Chief at the Wisconsin Department of Natural Resources. <NAME> received his Bachelors degree in Wildlife Ecology at UW-Madison and his Masters and Doctorate degrees at Oregon State University. Karl’s research has focused on interaction of forest management and multi-scale wildlife habitat relationships. His current position focuses on the ‘Wisconsin Idea’ of taking the information and resources of the University to communities and citizens of the state.' organizations: uwm: 'Members of the Wildlife Watch team are ecologists at the University of Wisconsin Madison in the Department of Forest and Wildlife Ecology. UW-Madison is a public, land-grant institution founded in 1848 whose mission is to provide “a learning environment in which faculty, staff and students can discover, examine critically, preserve and transmit the knowledge, wisdom and values that will help insure the survival of this and future generations and improve the quality of life for all.”' nasa: 'NASA provided partial funding for the first year of the project thought the Ecological Forecasting for Conservation and Natural Resource Management Program. The NASA Applied Sciences Program supports projects that enable uses of Earth observations in organizations’ policy, business, and management decisions.' wcbmn: 'The Wisconsin Citizen-based Monitoring (WCBM) Network provided funding for materials used in training citizen volunteers during the first year of the project. The WCBM Network is a stakeholder collaboration “to improve the efficiency and effectiveness of monitoring efforts by providing coordination, communications, technical, and financial resources and recognition to members of the Wisconsin citizen-based monitoring community.”' adler: 'The Adler Planetarium was founded in 1930 by Chicago business leader <NAME>. A recognized leader in public learning, the Adler inspires young people -particularly women and minorities - to pursue careers in science, technology, engineering, and math. Scientists, historians and educators at the museum inspire the next generation of explorers.' uwExtension: 'The University of Wisconsin Extension provides ongoing support for the project. The Extension’s purpose is to "connect people with the University of Wisconsin and engage with them in transforming lives and communities."' connect: header: 'Connect' action: 'Get Started'
true
module.exports = navigation: home: 'Home' classify: 'Classify' science: 'Science' team: 'Team' education: 'Education' profile: 'Profile' talk: 'Talk' blog: 'Blog' home: heading: 'Welcome to Wildlife Watch' rightBannerHeader: "What is Wildlife Watch?" tagline: 'WildlifeWatch is an effort to monitor forest wildlife year-round across a network of trail cameras. Help us to identify the animals captured on camera and better understand the distribution and trends of our wildlife populations.' action: 'Get Started' nasa: 'In partnership with NASA' currentStatus: '<span class="classification-count">0</span> classifications by <span class="user-count">0</span> volunteers' stats: header: "WILDLIFE WATCH Statistics" activeUsers: "Active Users" crittersIdentified: "Critters Identified" totalImages: "Images Total" complete: "Complete" siteIntro: s1: title: "Welcome!" content: "Welcome to Wildlife Watch! In this project, we are asking you to identify animals found in camera trap photos from around Wisconsin. Your help allows us better understand how animal populations across the state change through time." s2: title: "Identifying animals" content: "You are presented with a photo on the left and a list of potential animals on the right. When you spot an animal within a photo, simply click the corresponding animal on the right. You will be asked to supply some followup info, such as the number of animals found in the image." s3: title: "Filtering by characteristics" content: "Occasionally it is difficult to determine which animal is in the photo. Just above the list of animals is a variety of methods to filter the animal list. Selecting different options reduces the number of choices, making your job easier." s4: title: "Made a mistake?" content: "If you need to delete any of your existing marks while viewing an image, simply find your animal in the list below the image and click the 'X' icon. Don’t worry if you’re unsure about your choices, though—even a guess is more helpful than nothing!" s5: title: "That's it!" content: "You may catch up on project updates through speaking with other volunteers via Talk." classify: deleteAnnotation: 'Delete' notSignedIn: 'You\'re not signed in!' favorite: 'Favorite' unfavorite: 'Unfavorite' play: 'View series' pause: 'Stop' satellite: 'Satellite view' nothingLabel: 'Nothing here' nextSubjectButton: 'Finish' share: 'Share' tweet: 'Tweet' pin: 'Pin it' discuss: 'Discuss' next: 'Next capture' search: 'Search' nothingToShow: 'There\'s nothing to show with these filters.' clearFilters: 'Clear filters' oftenConfused: 'Often confused with:' count: 'How many' startTutorial: 'Start tutorial' deer: fawns: "Fawns" antlered: "Adult antlered" antlerless: "Adult antlerless" notVisible: "Adult head not visible" behavior: 'Behavior' behaviors: standing: 'standing' resting: 'resting' moving: 'moving' eating: 'eating' interacting: 'interacting' babies: 'Young present' rain: 'Raining' cancel: 'Cancel' identify: 'Identify' differences: aardvark: pangolin: 'A pangolin is covered in scales while an aardvark has brown fur. It also has a shorter, pointier snout than an aardvark.' baboon: samangoMonkey: 'A samango monkey has bluish-gray fur while a baboon has yellow-brown fur. It also has a dark face with prominent fur on the cheeks.' baboon: vervetMonkey: 'A vervet monkey is much smaller than a baboon with a black face and light gray fur.' buffalo: wildebeest: 'A wildebeest is more slender than a buffalo with a long, narrow face and a beard.' bushbuck: reedbuck: 'A reedbuck has solid tan fur without white spots or stripes. Its horns are ringed and it has a large, black spot below the ears.' bushbuck: nyala: 'A nyala female has prominent vertical white stripes and white markings between the eyes, while a bushbuck female has lighter stripes and more prominent spots.' bushpig: warthog: 'A warthog is a slate gray color with prominent warts on the sides of its face and larger tusks than a bushpig.' caracal: lionFemale: 'A lion is larger than a caracal with rounded ears, no white or black markings on the face or ears, and its fur is a lighter golden-yellow color.' civet: genet: 'A genet is more slender than a civet with a much longer, bushier tail. ' duiker: oribi: 'An oribi is more slender and taller than a duiker with a flat back, white underbelly, and prominent black spots below the ears. ' eland: hartebeest: 'A hartebeest is a taller and more slender than an eland with reddish fur, narrow face, and short, spiral horns.' eland: kudu: 'A kudu is taller and less ox-like than an eland, it has massive spiral horns and lacks a dewlap on the throat.' genet: civet: 'A civet is stockier than a genet with a much shorter tail and a dark mask on the face.' hartebeest: eland: 'An eland is more stocky and ox-like than a hartebeest with long, straight horns that twist. It has a dewlap below the neck.' hartebeest: wildebeest: 'A wildebeest is dark gray-brown with a mane and beard. Its horns are longer than a hartebeest.' hartebeest: kudu: 'A kudu is stockier than a hartebeest with tan-gray fur, vertical stripes, and the males have manes and massive spiral horns.' hippopotamus: warthog: 'A warthog is much smaller than a hippopotamus with horns and prominent warts on the face.' hyena: wildDog: 'A wild dog is more slender than a hyena with patchy black, orange, and white fur and a flat back.' impala: bushbuck: 'A bushbuck has vertical white stripes and spots on the flanks as well as a rounded back.' impala: reedbuck: 'A reedbuck has solid tan fur without horizontal bands. Its horns are curved and ringed and it has large, black spots below the ears.' jackal: wildDog: 'A wild dog is more larger than a jackal with patchy black, orange, and white fur.' kudu: eland: 'An eland is more stocky and ox-like than a kudu with long, straight horns that twist. It has a dewlap below the neck.' kudu: hartebeest: 'A hartebeest is more slender than a kudu with reddish fur, narrow face, and short, spiral horns.' kudu: nyala: 'A nyala is smaller than a kudu and females are more reddish-brown while males are chestnut with orange legs.' leopard: lionFemale: 'A lion has solid golden-tan fur without dark spots. ' leopard: lionCub: 'A lion cub is small with solid golden-tan fur without dark spots. ' leopard: serval: 'A serval is much smaller and lankier than a leopard with pointy ears, a small face, and a bushy tail.' lionCub: lionFemale: 'A female lion is much larger than a cub.' lionCub: leopard: 'A leopard is much larger than a lion cub and it has dark spots.' lionFemale: lionCub: 'A lion cub is much smaller than an adult female lion.' lionFemale: caracal: 'A caracal has pointy ears, reddish-tan fur, and white and black markings on the face.' lionFemale: leopard: 'A leopard has dark black spots.' mongoose: weasel: 'The weasel species in Gorongosa are skunklike with black and white fur.' nyala: kudu: 'A kudu is larger than a nyala with grayish-tan fur. Males have shaggy beards and massive, spiral horns.' oribi: duiker: 'A duiker is stockier than an oribi with a rounded back. The common duiker has a dark stripe on its nose, while the red duiker has reddish fur and the blue duiker has bluish-gray fur.' otter: honeyBadger: 'A honey badger has a distinct white patch on its back and is stockier than an otter' otter: mongoose: 'A mongoose is smaller and more slender than an otter, with a long thin tail.' otter: weasel: 'The weasel species in Gorongosa are skunklike with black and white fur.' pangolin: aardvark: 'An aardvark has brown fur and a long, flat snout.' reedbuck: bushbuck: 'A bushbuck has vertical white stripes and spots on the flanks as well as a rounded back.' reedbuck: impala: 'An impala has horizontal bands and males have large, spiral horns.' samangoMonkey: baboon: 'A baboon has yellow-brown fur and a light colored face.' samangoMonkey: vervetMonkey: 'A vervet monkey is much smaller than a samango monkey with a black face and light gray fur.' serval: leopard: 'A leopard is much larger and stockier than a serval and it has a round face and a smooth tail.' serval: wildCat: 'A wildcat is smaller and stockier than a serval and resembles a house cat.' vervetMonkey: baboon: 'A baboon is larger than a vervet monkey with yellow-brown fur and a light colored face.' vervetMonkey: samangoMonkey: 'A samango monkey is larger than a vervet monkey with bluish-gray fur and prominent fur on the cheeks.' warthog: bushpig: 'A bushpig has thick reddish-silvery fur and smaller tusks than a warthog.' warthog: hippopotamus: 'A hippopotamus is much larger than a warthog with a round body, face, and tiny pink ears. ' weasel: mongoose: 'The mongoose species in Gorongosa are various shades of brown while the weasels are black and white and skunklike.' wildDog: hyena: 'A hyena is stockier than a wild dog with yellowish fur and light brown spots. Its back is sloped downward. ' wildDog: jackal: 'A jackal is smaller than a wild dog with light brown and silver-black fur.' wildcat: serval: 'A serval is larger, taller, and more slender than a wildcat with yellow fur and black spots.' wildebeest: buffalo: 'A buffalo is stockier and more cattlelike than a wildebeest and lacks a beard and mane.' wildebeest: hartebeest: 'A hartebeest has reddish-brown fur, very short horns, and lacks a beard and mane.' animals: aardvark: label:'Aardvark' description:'Short, stocky animal with a long snout and a flat, piglike nose. The aardvark has brown to pink skin with thin, bristly hair, long ears, clawed toes, and a long, smooth tail. ' baboon: label:'Baboon' description:'Medium-sized primate with golden fur that is paler on the underbelly and a dark face that protrudes and widens at the nose and mouth. It has a straight brow, brown eyes, and a tail that juts out and drops.' birdOther: label:'Bird (other)' description:'There are about 400 bird species in Gorongosa, from small songbirds to large geese and ducks. If you find a bird that is not on the list, mark it here!' buffalo: label:'Buffalo' description:'Large, cattlelike animal with short legs and a long, tufted tail, dark brown to black fur, large, droopy ears, and a broad muzzle. Both sexes have U-shaped horns, but males horns form a fused shield on the top of their heads. ' bushbuck: label:'Bushbuck' description:'Medium-sized antelope with tan to chestnut brown fur with thin white stripes and spots on their flanks. Males are shaggy with darker fur and thick, spiral horns. Females are light tan and slender.' bushpig: label:'Bushpig' description:'Squat, flat-nosed, and piglike with long ears and reddish-brown fur with silver running down the spine. Both sexes have short, inconspicuous tusks. ' caracal: label:'Caracal' description:'Medium to large muscular cat with red-brown fur, a lighter underbelly, distinctive large, pointy ears with tufts of black fur at the tips, and white and black striped markings on the face.' civet: label:'Civet' description:'Long, stocky mammal with short legs and a pointy face. Fur is light brown-gray with a dark mask, white at the tip of the muzzle, dark legs, spots, and bands along the neck. ' crane: label:'Crane' description:'Long-legged, long-necked bird with a straight beak. There are two crane species in Gorongosa: the gray-crowned crane and the wattled crane. The gray-crowned crane has gray, white, and yellow feathers with a distinctive yellow fan of feathers on its head. The wattled crane has gray, black, and white feathers with red skin around its yellow beak.' duiker: label:'Duiker' description:'Duikers are small, deerlike antelope with a thin, short tail and colors ranging from blue-gray to red depending on the species. Males have short, straight horns. There are three species of duiker in Gorongosa: red, common, and blue duiker.' eland: label:'Eland' description:'Massive antelope with an oxlike body and short legs. Both sexes have straight, spiraled horns, a short mane, and a smooth light tan to gray coat with thin white stripes on the sides. Males have a large dewlap under the throat.' elephant: label:'Elephant' description:'Huge, leathery, gray-skinned mammal with large, floppy ears and thick, strong legs. It has a short, tufted tail and a long, thick trunk. Some elephants of both sexes have large, white tusks, but some individuals are born without tusks or have only one tusk. ' genet: label:'Genet' description:'Small, slender animal with tan-gray fur, large, ringed spots, a long, thick, black-ringed tail, and a white underbelly. It has a black stripe down the spine and a pointy muzzle. ' groundHornbill: label:'Ground Hornbill' description:'Large, stocky black bird with a red face, long, black beak, and red flaps of skin on its throat.' hare: label:'Hare' description:'Large rabbitlike animal with very long ears. There are two hare species in Gorongosa. The savanna hare has gray fur with a lighter brown underbelly, while the scrub hare is darker gray and has a white underbelly.' hartebeest: label:'Hartebeest' description:'Large, reddish-yellow antelope with an elongated, horselike face, large, pointy ears, humped shoulders, sloped back, and a light underbelly and hind parts with a short, tufted tail. Both sexes have curved, ridged horns.' hippopotamus: label:'Hippopotamus' description:'Massive and low to the ground with short legs, small ears, gray to pink skin, a wide muzzle, and a short tail with a bristly tassel.' honeyBadger: label:'Honey Badger' description:'Small, stocky mammal with short legs and a wide body. The lower half of the body is covered in black fur, and the head, back, and the top of the tail are covered in solid white-gray fur. ' human: label:'Human' description:'Sometimes people are captured in photos too, such as researchers checking the cameras, scouts on patrol, and tourists driving past in their vehicles.' hyena: label:'Hyena' description:'Medium-sized, stocky, doglike animal with a thick neck and a sloped back, golden tan-gray fur with dark spots, and small, round ears. ' impala: label:'Impala' description:'Medium-sized antelope with reddish-brown fur, white stripes around the eyes, and black stripes on the forehead and tail. Coat forms horizontal bands of red fur along the back, tan fur along the sides, and white fur on the underbelly. Males have large, spiral horns. ' jackal: label:'Jackal' description:'Medium-sized, gray-brown, doglike animal with a pointy face and ears. It has tan legs and underbelly with a black and white striped side, a gray back, and a long, bushy black tail with a white tip. ' kudu: label:'Kudu' description:'Large, lanky antelope with long legs, a short mane along the neck and shoulders, a brownish-gray to tan coat with vertical white stripes along the torso, a white chevron between the eyes, and large round ears. Males have a beard along the throat and massive spiral horns. ' leopard: label:'Leopard' description:'Large, muscular cat with short, yellow fur and black, ringed spots, small, round ears, and a long, smooth tail. ' lionCub: label:'Lion (cub)' description:'Cubs are smaller than adults with tan-yellow fur and some darker spots, a lighter underbelly, and white fur under the chin. Cubs do not have manes.' lionFemale: label:'Lion (female)' description:'Large, muscular cat with short tan-yellow fur, a long, smooth tail, a lighter underbelly, and white fur under the chin. Females do not have manes.' lionMale: label:'Lion (male)' description:'Large, muscular cat with short tan-yellow fur, a long, smooth tail with a tuft at the end, a lighter underbelly, and white fur under the chin. Males have a thick reddish mane that gets darker and thicker with age.' mammalOther: label:'Mammal (other)' description:'There are over 70 additional species of mammals in Gorongosa that are not on this list, including bats, rats, mice, squirrels, gerbils, shrews, and hyraxes. If you find one of these mammals that is not on the list, mark it here.' mongoose: label:'Mongoose' description:'Small, sleek mammal with short legs, a long body, and a long tail. There are eight mongoose species in Gorongosa that range in size and color from the brown dwarf mongoose to the larger Egyptian mongoose with bushy gray fur and tiny spots.' nyala: label:'Nyala' description:'Medium-sized antelope with long legs and a shaggy tail. Males are dark brown to reddish with thin white stripes and small spots on the rump, orange legs and a white patch of fur between the eyes. Males also have a mane along the neck, chest, and belly as well as long, spiraling horns. Females are tan with vertical white stripes and spots on the sides, large ears, and no horns.' oribi: label:'Oribi' description:'Small, deerlike antelope with a long, slender neck, brownish fur with a white underbelly, white around the eyes and muzzle, and distinctive black spots below the ears. Males have short, straight horns.' otter: label:'Otter' description:'Small, sleek mammal with a long body, short legs, and brown-gray fur. Otters have webbed feet, small, round ears, and a thick tail. There are two otter species in Gorongosa. The Cape clawless otter is lighter brown has a pale underbelly, while the spotted-necked otter is smaller and has darker fur with white spots on the neck.' pangolin: label:'Pangolin' description:'Small, stocky animal with short legs and a long, thick tail. The pangolin is covered with hard, armored, brown scales. It has a small, pointy face and large claws.' porcupine: label:'Porcupine' description:'Short, stocky animal with brown fur and long, black and white quills covering its back from head to tail. It has a small face with dark eyes and a blunt nose. It is often seen at night.' raptorOther: label:'Raptor (other)' description:'Raptors are predatory birds with large wingspans, sharp, hooked beaks, and huge talons. In addition to vultures, Gorongosa has over 30 species of raptors, including eagles, hawks, kites, falcons, and buzzards. ' reedbuck: label:'Reedbuck' description:'Medium-sized, slender antelope with tan to brown fur, a white underbelly, white around the eyes and muzzle, and distinctive dark spots under their large ears. Males have ringed horns that curve forward.' reptile: label:'Reptile' description:'There are over 60 species of reptiles in Gorongosa including crocodiles, snakes, lizards, chameleons, geckos, skinks, tortoises, terrapins, and turtles. This category includes any reptile that you find!' sableAntelope: label:'Sable Antelope' description:'Full-bodied, horselike antelope with a thick neck, mane, long, tufted tail, chestnut brown to black fur with white underbelly and chin, and white under the eyes with a black stripe down the nose. Both sexes have large, ringed horns that curve backward. ' samangoMonkey: label:'Samango Monkey' description:'Medium-sized monkey with long, gray, speckled fur. Its face is dark gray, while its arms and legs fade to black toward the hands and feet. It has brown eyes, a white throat and underbelly, and a long, black tail.' secretaryBird: label:'Secretary bird' description:'Large, tall bird with gray feathers on the body and black feathers on the tips of the wings and legs. Its legs are extremely long, and its face is red-orange with a white beak. It has black feathers protruding from the back of its head like a fan.' serval: label:'Serval' description:'Medium-sized cat with long legs, a long neck, a lanky body, yellow-tan fur with black spots, very large ears, a long, striped tail, and black stripes around the neck, nose, and eyes.' vervetMonkey: label:'Vervet Monkey' description:'Small, gray-furred monkey whose face is black and ringed in white fur. Its hands, feet, and ears are also black, and it has a very long, black-tipped tail. ' vulture: label:'Vulture' description:'A large raptor with a bald head, large wings, and talons that is often found scavenging on carcasses. Gorongosa has five species of vultures, each with a distinct appearance. The hooded, white-headed, and lappet-faced vultures all have mostly black feathers and pink to blue faces. The white-backed and Egyptian vultures both have lighter gray to white feathers with gray and yellow faces (respectively).' warthog: label:'Warthog' description:'Squat, maned, slate-furred, and piglike with a long, thin, tufted tail. Males have curved tusks at the end of their broad snout, while females have shorter tusks. Both sexes have distinctive warts below their eyes.' waterbuck: label:'Waterbuck' description:'Large antelope with a wide, strong build, brownish-gray fur, a long neck with a shaggy mane, white fur under the neck and on the muzzle, and a white ring around the rump. Males have ringed horns that curve forward.' weasel: label:'Weasel' description:'The two weasel species in Gorongosa are the zorilla and the African striped weasel. Both are skunklike with black fur, large white stripes along the back, and a fluffy tail. Zorillas are fluffier with three white patches on the face, while African striped weasels are smoother with a black face.' wildDog: label:'Wild Dog' description:'Medium-sized, lanky doglike animal with patchy tan, black, and white fur. It has a long, black muzzle and big, round, mostly black ears.' wildcat: label:'Wildcat' description:'Resembles a domestic tabby cat with brown to gray fur and darker stripes with a long striped tail. ' wildebeest: label:'Wildebeest' description:'Large, muscular antelope with a dark muzzle with a mane of hair along the throat and spine, broad shoulders, blue-gray to brown fur with subtle stripes, and a long, tufted tail. Both sexes have large, U-shaped horns.' zebra: label:'Zebra' description:'Horselike animal with short, white fur and distinctive black stripes. The mane is striped and sticks up vertically along the neck. The muzzle, nose, and tufted tail are black.' characteristics: like: 'Looks like...' coat: 'Coat' tail: 'Tail' build: 'Build' pattern: 'Pattern' horns: 'Horns' characteristicValues: likeCatdog: 'cat/dog' likeCowhorse: 'cow/horse' likeAntelopedeer: 'antelope/deer' likePrimate: 'primate' likeWeasel: 'weasel' likeBird: 'bird' likeOther: 'other' patternSolid: 'solid' patternStripes: 'stripes' patternBands: 'bands' patternSpots: 'spots' coatTanyellow: 'tan/yellow' coatRed: 'red' coatBrown: 'brown' coatWhite: 'white' coatGray: 'gray' coatBlack: 'black' hornsStraight: 'straight' hornsCurved: 'curved' hornsSpiral: 'spiral' hornsUshaped: 'u-shaped' tailSmooth: 'smooth' tailBushy: 'bushy' tailTufted: 'tufted' tailLong: 'long' tailShort: 'short' buildStocky: 'stocky' buildLanky: 'lanky' buildLarge: 'large' buildSmall: 'small' buildLowslung: 'low-slung' profile: header: "Your Profile" favorites: 'Favorites' recents: 'Recents' noFavorites: 'You have no favorites!' noRecents: 'You have no recent classifications!' showing: 'Showing' loadMore: 'Load more' science: understandingPopulations: ''' <h2>Understanding wildlife populations</h2> <p>Forests are home to dozens of native mammals, hundreds of other vertebrate species, and thousands of invertebrates and native plant species, living together in diverse natural communities. WildlifeWatch is a collaborative effort to utilize camera traps, also known as trail cameras, to learn about the distribution and trends of our wildlife populations.</p> ''' whyWeNeedYou: ''' <h2>Why we need you</h2> <p>Over the course of a month, a single camera might take thousands of photographs. You help to make all these photographs meaningful by classifying the type and number of animals in the image. Because we know where and when these photographs were taken, we can create maps for both common and rare species across the state and visualize how animal populations change through time. From black bears to badgers, see what critters you can spot roaming the Wisconsin forests! Share your favorites and join the discussion about what you are observing along the way. We will share with you what we are learning back here at Zooniverse.</p> ''' education: inTheClassroom: ''' <h2>Citizen science in the classroom</h2> <p>Wildlife Watch is a great opportunity to integrate science and technology in the classroom and a unique way for students to learn about wildlife and their habitats.</p> <p><a href="http://www.zooteach.org">ZooTeach</a> is a companion website to Zooniverse where educators can find and share educational resources relating to WildlifeWatch and the other Zooniverse citizen science projects. WildlifeWatch is a recent addition to Zooniverse, so if you have any ideas for how to use the project in the classroom, please share your lesson ideas or resources on ZooTeach.</p> <p>There are a number of excellent wildlife education resources available online. A few of our favorites are below:</p> <ul> <li><a href="http://dnr.wi.gov/eek/">http://dnr.wi.gov/eek/</a> - Environmental Education for Kids! (EEK!) is an electronic magazine for kids in grades 4-8 published by the Wisconsin Department of Natural Resources. It includes information on Wisconsin’s wildlife and resources for educators on how to help students use EEK!</li> <li><a href="http://projectwild.org/">http://projectwild.org/</a> - Project WILD is a nationwide program that provides resources for educators in teaching about wildlife and their habitat. The materials are available through Project WILD workshops lead by certified instructors. The Project WILD handbook includes more than 165 hands-on activities for PreK-12.</li> </ul> ''' team: navigation: people: 'People' organizations: 'Organizations' credit: 'Image Credits' bios: townsend: 'PI:NAME:<NAME>END_PI is a professor of Forest &amp; Wildlife Ecology at the University of Wisconsin. He is interested in how different components of ecosystems interact across landscapes, for example how nutrients and water affect vegetation, and then how patterns of vegetation processes affect insects and animals. He is particularly interested in how we can leverage a range of technologies including remote sensing to better understand ecosystems.' zuckerberg: 'Dr. PI:NAME:<NAME>END_PI is an assistant professor in the Department of Forest and Wildlife Ecology at the University of Wisconsin-Madison. His research focuses on how climate change and habitat loss impacts wildlife populations. He is a strong advocate for the role of the public in collecting biological data. Using the data from these “citizen science” programs, PI:NAME:<NAME>END_PI has studied shifts in bird ranges and migration in response to a changing climate.' deelen: 'PI:NAME:<NAME>END_PI has been on the faculty at the UW-Madison since 2004. Tim’s research specializes in the applied management of wildlife with an emphasis on large mammals in Wisconsin and is a frequent collaborator with the Wisconsin DNR and the Apostle Islands National Lakeshore. Prior positions include working as the research specialist for deer in the Wisconsin Department of Natural Resources and as a Research Scientist for the Illinois Natural History Survey where he had a joint appointment with the University of Illinois at Urbana-Champaign.' singh: 'PI:NAME:<NAME>END_PI is a post-doctoral scientist with the Department of Forest and Wildlife Ecology at the University of Wisconsin-Madison. He uses a combination of airborne and remotely sensed data to study the impacts of environmental change and disturbance on landscape-scale indicators of ecosystem health.' PI:NAME:<NAME>END_PI: 'PI:NAME:<NAME>END_PI is the State Director for the Community, Natural Resource and Economic Development Program and an Assistant Dean with the University of Wisconsin Cooperative Extension. He is an adjunct Associate Professor at the University of Wisconsin-Madison’s Forest and Wildlife Ecology Department and recently served as the Wildlife and Forestry Research Section Chief at the Wisconsin Department of Natural Resources. PI:NAME:<NAME>END_PI received his Bachelors degree in Wildlife Ecology at UW-Madison and his Masters and Doctorate degrees at Oregon State University. Karl’s research has focused on interaction of forest management and multi-scale wildlife habitat relationships. His current position focuses on the ‘Wisconsin Idea’ of taking the information and resources of the University to communities and citizens of the state.' organizations: uwm: 'Members of the Wildlife Watch team are ecologists at the University of Wisconsin Madison in the Department of Forest and Wildlife Ecology. UW-Madison is a public, land-grant institution founded in 1848 whose mission is to provide “a learning environment in which faculty, staff and students can discover, examine critically, preserve and transmit the knowledge, wisdom and values that will help insure the survival of this and future generations and improve the quality of life for all.”' nasa: 'NASA provided partial funding for the first year of the project thought the Ecological Forecasting for Conservation and Natural Resource Management Program. The NASA Applied Sciences Program supports projects that enable uses of Earth observations in organizations’ policy, business, and management decisions.' wcbmn: 'The Wisconsin Citizen-based Monitoring (WCBM) Network provided funding for materials used in training citizen volunteers during the first year of the project. The WCBM Network is a stakeholder collaboration “to improve the efficiency and effectiveness of monitoring efforts by providing coordination, communications, technical, and financial resources and recognition to members of the Wisconsin citizen-based monitoring community.”' adler: 'The Adler Planetarium was founded in 1930 by Chicago business leader PI:NAME:<NAME>END_PI. A recognized leader in public learning, the Adler inspires young people -particularly women and minorities - to pursue careers in science, technology, engineering, and math. Scientists, historians and educators at the museum inspire the next generation of explorers.' uwExtension: 'The University of Wisconsin Extension provides ongoing support for the project. The Extension’s purpose is to "connect people with the University of Wisconsin and engage with them in transforming lives and communities."' connect: header: 'Connect' action: 'Get Started'
[ { "context": "e.exports = [\n {\n id: 'device_1',\n label: 'Alex\\'s AstroKey',\n status_code: 1,\n keys: [\n {\n ", "end": 138, "score": 0.7623370289802551, "start": 122, "tag": "NAME", "value": "Alex\\'s AstroKey" }, { "context": " \"key\": \"A\",...
app/coffee/modules/main/data.coffee
aeksco/astrokey_web
0
# Dummy Device Data for UI development # TODO - pull from WebUSB? module.exports = [ { id: 'device_1', label: 'Alex\'s AstroKey', status_code: 1, keys: [ { id: 'device_1_key_1', config: { type: 'macro', macros: [ { "row": "r2", "key": "A", "keycode": 65, "order": 1, "position": 0 }, { "row": "r2", "key": "S", "keycode": 83, "order": 2, "position": 0 }, { "row": "r3", "key": "T", "keycode": 84, "order": 3, "position": 0 }, { "row": "r3", "key": "R", "keycode": 82, "order": 4, "position": 0 }, { "row": "r3", "key": "O", "keycode": 79, "order": 5, "position": 0 }, { "row": "r2", "key": "K", "keycode": 75, "order": 6, "position": 0 }, { "row": "r3", "key": "E", "keycode": 69, "order": 7, "position": 0 }, { "row": "r3", "key": "Y", "keycode": 89, "order": 8, "position": 0 } ] } } { id: 'device_1_key_2', config: { type: 'text', text_value: 'Hello world!' } } { id: 'device_1_key_3', config: { type: 'macro', macros: [] } } { id: 'device_1_key_4', config: { type: 'text', text_value: 'Hello, again' } } { id: 'device_1_key_5', config: { type: 'macro', macros: [] } } ] } ]
147499
# Dummy Device Data for UI development # TODO - pull from WebUSB? module.exports = [ { id: 'device_1', label: '<NAME>', status_code: 1, keys: [ { id: 'device_1_key_1', config: { type: 'macro', macros: [ { "row": "r2", "key": "A", "keycode": 6<KEY>, "order": 1, "position": 0 }, { "row": "r2", "key": "S", "keycode": 8<KEY>, "order": 2, "position": 0 }, { "row": "r3", "key": "T", "keycode": 8<KEY>, "order": 3, "position": 0 }, { "row": "r3", "key": "R", "keycode": 8<KEY>, "order": 4, "position": 0 }, { "row": "r3", "key": "O", "keycode": 79, "order": 5, "position": 0 }, { "row": "r2", "key": "K", "keycode": 75, "order": 6, "position": 0 }, { "row": "r3", "key": "E", "keycode": 69, "order": 7, "position": 0 }, { "row": "r3", "key": "Y", "keycode": 89, "order": 8, "position": 0 } ] } } { id: 'device_1_key_2', config: { type: 'text', text_value: 'Hello world!' } } { id: 'device_1_key_3', config: { type: 'macro', macros: [] } } { id: 'device_1_key_4', config: { type: 'text', text_value: '<NAME>, <NAME>' } } { id: 'device_1_key_5', config: { type: 'macro', macros: [] } } ] } ]
true
# Dummy Device Data for UI development # TODO - pull from WebUSB? module.exports = [ { id: 'device_1', label: 'PI:NAME:<NAME>END_PI', status_code: 1, keys: [ { id: 'device_1_key_1', config: { type: 'macro', macros: [ { "row": "r2", "key": "A", "keycode": 6PI:KEY:<KEY>END_PI, "order": 1, "position": 0 }, { "row": "r2", "key": "S", "keycode": 8PI:KEY:<KEY>END_PI, "order": 2, "position": 0 }, { "row": "r3", "key": "T", "keycode": 8PI:KEY:<KEY>END_PI, "order": 3, "position": 0 }, { "row": "r3", "key": "R", "keycode": 8PI:KEY:<KEY>END_PI, "order": 4, "position": 0 }, { "row": "r3", "key": "O", "keycode": 79, "order": 5, "position": 0 }, { "row": "r2", "key": "K", "keycode": 75, "order": 6, "position": 0 }, { "row": "r3", "key": "E", "keycode": 69, "order": 7, "position": 0 }, { "row": "r3", "key": "Y", "keycode": 89, "order": 8, "position": 0 } ] } } { id: 'device_1_key_2', config: { type: 'text', text_value: 'Hello world!' } } { id: 'device_1_key_3', config: { type: 'macro', macros: [] } } { id: 'device_1_key_4', config: { type: 'text', text_value: 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI' } } { id: 'device_1_key_5', config: { type: 'macro', macros: [] } } ] } ]
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission ", "end": 18, "score": 0.8858577013015747, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/pummel/test-timers.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. # why is does this need to be so big? # check that these don't blow up. # this timer shouldn't execute # Single param: # Multiple param # setInterval(cb, 0) should be called multiple times. # we should be able to clearTimeout multiple times without breakage. t = -> expectedTimeouts-- return common = require("../common") assert = require("assert") WINDOW = 200 interval_count = 0 setTimeout_called = false clearTimeout null clearInterval null assert.equal true, setTimeout instanceof Function starttime = new Date setTimeout (-> endtime = new Date diff = endtime - starttime assert.ok diff > 0 console.error "diff: " + diff assert.equal true, 1000 - WINDOW < diff and diff < 1000 + WINDOW setTimeout_called = true return ), 1000 id = setTimeout(-> assert.equal true, false return , 500) clearTimeout id setInterval (-> interval_count += 1 endtime = new Date diff = endtime - starttime assert.ok diff > 0 console.error "diff: " + diff t = interval_count * 1000 assert.equal true, t - WINDOW < diff and diff < t + WINDOW assert.equal true, interval_count <= 3 clearInterval this if interval_count is 3 return ), 1000 setTimeout ((param) -> assert.equal "test param", param return ), 1000, "test param" interval_count2 = 0 setInterval ((param) -> ++interval_count2 assert.equal "test param", param clearInterval this if interval_count2 is 3 return ), 1000, "test param" setTimeout ((param1, param2) -> assert.equal "param1", param1 assert.equal "param2", param2 return ), 1000, "param1", "param2" interval_count3 = 0 setInterval ((param1, param2) -> ++interval_count3 assert.equal "param1", param1 assert.equal "param2", param2 clearInterval this if interval_count3 is 3 return ), 1000, "param1", "param2" count4 = 0 interval4 = setInterval(-> clearInterval interval4 if ++count4 > 10 return , 0) expectedTimeouts = 3 w = setTimeout(t, 200) x = setTimeout(t, 200) y = setTimeout(t, 200) clearTimeout y z = setTimeout(t, 200) clearTimeout y process.on "exit", -> assert.equal true, setTimeout_called assert.equal 3, interval_count assert.equal 11, count4 assert.equal 0, expectedTimeouts, "clearTimeout cleared too many timeouts" return
55422
# 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. # why is does this need to be so big? # check that these don't blow up. # this timer shouldn't execute # Single param: # Multiple param # setInterval(cb, 0) should be called multiple times. # we should be able to clearTimeout multiple times without breakage. t = -> expectedTimeouts-- return common = require("../common") assert = require("assert") WINDOW = 200 interval_count = 0 setTimeout_called = false clearTimeout null clearInterval null assert.equal true, setTimeout instanceof Function starttime = new Date setTimeout (-> endtime = new Date diff = endtime - starttime assert.ok diff > 0 console.error "diff: " + diff assert.equal true, 1000 - WINDOW < diff and diff < 1000 + WINDOW setTimeout_called = true return ), 1000 id = setTimeout(-> assert.equal true, false return , 500) clearTimeout id setInterval (-> interval_count += 1 endtime = new Date diff = endtime - starttime assert.ok diff > 0 console.error "diff: " + diff t = interval_count * 1000 assert.equal true, t - WINDOW < diff and diff < t + WINDOW assert.equal true, interval_count <= 3 clearInterval this if interval_count is 3 return ), 1000 setTimeout ((param) -> assert.equal "test param", param return ), 1000, "test param" interval_count2 = 0 setInterval ((param) -> ++interval_count2 assert.equal "test param", param clearInterval this if interval_count2 is 3 return ), 1000, "test param" setTimeout ((param1, param2) -> assert.equal "param1", param1 assert.equal "param2", param2 return ), 1000, "param1", "param2" interval_count3 = 0 setInterval ((param1, param2) -> ++interval_count3 assert.equal "param1", param1 assert.equal "param2", param2 clearInterval this if interval_count3 is 3 return ), 1000, "param1", "param2" count4 = 0 interval4 = setInterval(-> clearInterval interval4 if ++count4 > 10 return , 0) expectedTimeouts = 3 w = setTimeout(t, 200) x = setTimeout(t, 200) y = setTimeout(t, 200) clearTimeout y z = setTimeout(t, 200) clearTimeout y process.on "exit", -> assert.equal true, setTimeout_called assert.equal 3, interval_count assert.equal 11, count4 assert.equal 0, expectedTimeouts, "clearTimeout cleared too many timeouts" 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. # why is does this need to be so big? # check that these don't blow up. # this timer shouldn't execute # Single param: # Multiple param # setInterval(cb, 0) should be called multiple times. # we should be able to clearTimeout multiple times without breakage. t = -> expectedTimeouts-- return common = require("../common") assert = require("assert") WINDOW = 200 interval_count = 0 setTimeout_called = false clearTimeout null clearInterval null assert.equal true, setTimeout instanceof Function starttime = new Date setTimeout (-> endtime = new Date diff = endtime - starttime assert.ok diff > 0 console.error "diff: " + diff assert.equal true, 1000 - WINDOW < diff and diff < 1000 + WINDOW setTimeout_called = true return ), 1000 id = setTimeout(-> assert.equal true, false return , 500) clearTimeout id setInterval (-> interval_count += 1 endtime = new Date diff = endtime - starttime assert.ok diff > 0 console.error "diff: " + diff t = interval_count * 1000 assert.equal true, t - WINDOW < diff and diff < t + WINDOW assert.equal true, interval_count <= 3 clearInterval this if interval_count is 3 return ), 1000 setTimeout ((param) -> assert.equal "test param", param return ), 1000, "test param" interval_count2 = 0 setInterval ((param) -> ++interval_count2 assert.equal "test param", param clearInterval this if interval_count2 is 3 return ), 1000, "test param" setTimeout ((param1, param2) -> assert.equal "param1", param1 assert.equal "param2", param2 return ), 1000, "param1", "param2" interval_count3 = 0 setInterval ((param1, param2) -> ++interval_count3 assert.equal "param1", param1 assert.equal "param2", param2 clearInterval this if interval_count3 is 3 return ), 1000, "param1", "param2" count4 = 0 interval4 = setInterval(-> clearInterval interval4 if ++count4 > 10 return , 0) expectedTimeouts = 3 w = setTimeout(t, 200) x = setTimeout(t, 200) y = setTimeout(t, 200) clearTimeout y z = setTimeout(t, 200) clearTimeout y process.on "exit", -> assert.equal true, setTimeout_called assert.equal 3, interval_count assert.equal 11, count4 assert.equal 0, expectedTimeouts, "clearTimeout cleared too many timeouts" return
[ { "context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ", "end": 33, "score": 0.9998641014099121, "start": 21, "tag": "NAME", "value": "John Judnich" } ]
shaders/NearMapGeneratorShader.coffee
anandprabhakar0507/Kosmos
46
# Copyright (C) 2013 John Judnich # Released under The MIT License - see "LICENSE" file for details. frag = """precision highp float; varying vec3 vPos; varying vec3 vTangent; varying vec3 vBinormal; """ + windowsCompatibilityUglyHacks.randomSeedDefString + """ //uniform vec3 randomSeed; #define ONE_TEXEL (1.0/4096.0) float getHeightOnCube(vec3 cubePos) { vec3 pos = normalize(cubePos); return heightFunc(pos, randomSeed); } void main(void) { float height = getHeightOnCube(vPos); gl_FragColor = vec4(height, height, height, height); } """ vert = """ attribute vec2 aUV; attribute vec3 aPos; attribute vec3 aTangent; attribute vec3 aBinormal; varying vec3 vPos; varying vec3 vTangent; varying vec3 vBinormal; uniform vec2 verticalViewport; void main(void) { vPos = aPos; vTangent = aTangent; vBinormal = aBinormal; vec2 pos = aUV; pos.y = (pos.y - verticalViewport.x) / verticalViewport.y; pos = pos * 2.0 - 1.0; gl_Position = vec4(pos, 0.0, 1.0); } """ for i in [0..kosmosShaderHeightFunctions.length-1] xgl.addProgram("nearMapGenerator" + i, vert, xgl.commonNoiseShaderSource3 + kosmosShaderHeightFunctions[i] + frag)
34088
# Copyright (C) 2013 <NAME> # Released under The MIT License - see "LICENSE" file for details. frag = """precision highp float; varying vec3 vPos; varying vec3 vTangent; varying vec3 vBinormal; """ + windowsCompatibilityUglyHacks.randomSeedDefString + """ //uniform vec3 randomSeed; #define ONE_TEXEL (1.0/4096.0) float getHeightOnCube(vec3 cubePos) { vec3 pos = normalize(cubePos); return heightFunc(pos, randomSeed); } void main(void) { float height = getHeightOnCube(vPos); gl_FragColor = vec4(height, height, height, height); } """ vert = """ attribute vec2 aUV; attribute vec3 aPos; attribute vec3 aTangent; attribute vec3 aBinormal; varying vec3 vPos; varying vec3 vTangent; varying vec3 vBinormal; uniform vec2 verticalViewport; void main(void) { vPos = aPos; vTangent = aTangent; vBinormal = aBinormal; vec2 pos = aUV; pos.y = (pos.y - verticalViewport.x) / verticalViewport.y; pos = pos * 2.0 - 1.0; gl_Position = vec4(pos, 0.0, 1.0); } """ for i in [0..kosmosShaderHeightFunctions.length-1] xgl.addProgram("nearMapGenerator" + i, vert, xgl.commonNoiseShaderSource3 + kosmosShaderHeightFunctions[i] + frag)
true
# Copyright (C) 2013 PI:NAME:<NAME>END_PI # Released under The MIT License - see "LICENSE" file for details. frag = """precision highp float; varying vec3 vPos; varying vec3 vTangent; varying vec3 vBinormal; """ + windowsCompatibilityUglyHacks.randomSeedDefString + """ //uniform vec3 randomSeed; #define ONE_TEXEL (1.0/4096.0) float getHeightOnCube(vec3 cubePos) { vec3 pos = normalize(cubePos); return heightFunc(pos, randomSeed); } void main(void) { float height = getHeightOnCube(vPos); gl_FragColor = vec4(height, height, height, height); } """ vert = """ attribute vec2 aUV; attribute vec3 aPos; attribute vec3 aTangent; attribute vec3 aBinormal; varying vec3 vPos; varying vec3 vTangent; varying vec3 vBinormal; uniform vec2 verticalViewport; void main(void) { vPos = aPos; vTangent = aTangent; vBinormal = aBinormal; vec2 pos = aUV; pos.y = (pos.y - verticalViewport.x) / verticalViewport.y; pos = pos * 2.0 - 1.0; gl_Position = vec4(pos, 0.0, 1.0); } """ for i in [0..kosmosShaderHeightFunctions.length-1] xgl.addProgram("nearMapGenerator" + i, vert, xgl.commonNoiseShaderSource3 + kosmosShaderHeightFunctions[i] + frag)
[ { "context": "n a clockAPI'\n clockAPI =\n hostname: '127.0.0.1'\n method: 'GET'\n port: clockPort\n ", "end": 1359, "score": 0.9988915324211121, "start": 1350, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " port: clockPort\n path: '/...
tests/bundles.test.coffee
iti-ict/localstamp
1
should = require 'should' q = require 'q' http = require 'http' qs = require 'querystring' LocalStamp = require '..' Component = require 'component' clockPort = null frontPort = null volumePort = null a = null EXAMPLES='/workspaces/slap/git/examples' BUNDLE="#{EXAMPLES}/java-example/bundles/deploy_bundle.zip" INTERSERVICE="#{EXAMPLES}/interservice-example" INTERSERVICE_BACK="#{INTERSERVICE}/back/bundles/deploy_bundle.zip" INTERSERVICE_FRONT="#{INTERSERVICE}/front/bundles/deploy_bundle.zip" RESOURCES_BUNDLE="#{EXAMPLES}/java-web-example/bundles/deploy_bundle.zip" TEST_BUNDLE ="#{process.cwd()}/tests/bundle-test.zip" describe 'Local stamp - Bundle Support', -> @timeout 40 * 1000 before -> a = new LocalStamp('test',{runtimeFolder:'/tmp/runtime-agent'}) a.init() .then -> console.log 'Workspace ready' after (done)-> a.shutdown() .then -> done() it 'Normal bundle', -> a.launchBundle BUNDLE .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] clockPort = deployment.portMapping[0].port q.delay 3500 .then -> deferred = q.defer() console.log 'Haciendo petición a clockAPI' clockAPI = hostname: '127.0.0.1' method: 'GET' port: clockPort path: '/mola?username=Peras&password=Peras' http.request clockAPI, (res) -> res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.should.have.property 'clock' deferred.resolve true .end() deferred.promise describe 'Interconnecting services', -> frontDeployment = backDeployment = null it 'Normal connection', -> @timeout 60 * 1000 a.launchBundle INTERSERVICE_BACK .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] backDeployment = deployment.deploymentURN a.launchBundle INTERSERVICE_FRONT .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] frontDeployment = deployment.deploymentURN frontPort = deployment.portMapping[0].port q.delay 3500 .then -> console.log 'Conectando canales...' a.connectDeployments spec: 'http://eslap.cloud/manifest/link/1_0_0' endpoints: [ { deployment: frontDeployment channel: 'back' }, { deployment: backDeployment channel: 'service' } ] console.log 'Servicios conectados' console.log 'Haciendo petición a calculatorAPI' deferred = q.defer() calculatorAPI = hostname: '127.0.0.1' method: 'POST' port: frontPort headers: {'Content-Type': 'application/json'} path: '/restapi/add' req = http.request calculatorAPI, (res) -> res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.result.should.be.eql 80 deferred.resolve true req.write JSON.stringify {value1:45,value2:35} req.end() deferred.promise it 'Connects a tester to a bundle', -> TESTER_COMPONENT_CONFIG = iid: 'IS-tester' incnum: 1 parameters: {} role: 'tester' offerings: [] dependencies: [{id:'test',type:'Request'}] a.launch InterserviceTester, TESTER_COMPONENT_CONFIG, frontDeployment .then -> a.connect 'loadbalancer', [{role:'cfe', endpoint:'test'}], [{role:'tester', endpoint:'test'}], frontDeployment a.instances['IS-tester'].instance.case0(21, 37) .then (result)-> console.log "Vía IS-tester se obtiene #{JSON.stringify result}" result.result.should.be.eql 58 it 'Works with resources', -> @timeout 45 * 1000 * 500 a.launchBundle RESOURCES_BUNDLE .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] volumePort = deployment.portMapping[0].port q.delay 3500 .then -> deferred = q.defer() query = operation: 'read' volume: 'volatile' volumeAPI = hostname: '127.0.0.1' method: 'GET' port: volumePort path: "/java-resources-web-example/rest?#{qs.stringify query}" console.log "Haciendo petición a volumeAPI: #{JSON.stringify volumeAPI}" req = http.request volumeAPI, (res) -> res.statusCode.should.be.eql 400 res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.success.should.be.eql false result.error.should.be.eql 'No data' deferred.resolve true req.end() deferred.promise .then -> deferred = q.defer() query = operation: 'write' volume: 'volatile' data: 'Hello Donald' volumeAPI = hostname: '127.0.0.1' method: 'GET' port: volumePort path: "/java-resources-web-example/rest?#{qs.stringify query}" console.log "Haciendo petición a volumeAPI: #{JSON.stringify volumeAPI}" req = http.request volumeAPI, (res) -> res.statusCode.should.be.eql 200 res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.success.should.be.eql true result.data.should.be.eql 'OK' deferred.resolve true req.end() deferred.promise .then -> deferred = q.defer() query = operation: 'read' volume: 'volatile' volumeAPI = hostname: '127.0.0.1' method: 'GET' port: volumePort path: "/java-resources-web-example/rest?#{qs.stringify query}" console.log "Haciendo petición a volumeAPI: #{JSON.stringify volumeAPI}" req = http.request volumeAPI, (res) -> res.statusCode.should.be.eql 200 res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.success.should.be.eql true result.data.should.be.eql 'Hello Donald' deferred.resolve true req.end() deferred.promise it.skip 'Test bundle', (done)-> @timeout 120 * 60 * 1000 a.launchBundle TEST_BUNDLE .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" do done class InterserviceTester extends Component constructor: (@runtime, @role, @iid, @incnum, @localData, @resources , @parameters, @dependencies, @offerings) -> # NOTHING run: -> @running = true case0: (s1, s2)-> @dependencies.test.sendRequest JSON.stringify {value1:s1, value2:s2} .then (value)-> JSON.parse value.message.toString() process.on 'uncaughtException', (e)-> console.error 'uncaughtException:', e.stack process.on 'unhandledRejection', (reason, p)-> console.log 'Unhandled Rejection at: Promise', p, 'reason:', reason
168491
should = require 'should' q = require 'q' http = require 'http' qs = require 'querystring' LocalStamp = require '..' Component = require 'component' clockPort = null frontPort = null volumePort = null a = null EXAMPLES='/workspaces/slap/git/examples' BUNDLE="#{EXAMPLES}/java-example/bundles/deploy_bundle.zip" INTERSERVICE="#{EXAMPLES}/interservice-example" INTERSERVICE_BACK="#{INTERSERVICE}/back/bundles/deploy_bundle.zip" INTERSERVICE_FRONT="#{INTERSERVICE}/front/bundles/deploy_bundle.zip" RESOURCES_BUNDLE="#{EXAMPLES}/java-web-example/bundles/deploy_bundle.zip" TEST_BUNDLE ="#{process.cwd()}/tests/bundle-test.zip" describe 'Local stamp - Bundle Support', -> @timeout 40 * 1000 before -> a = new LocalStamp('test',{runtimeFolder:'/tmp/runtime-agent'}) a.init() .then -> console.log 'Workspace ready' after (done)-> a.shutdown() .then -> done() it 'Normal bundle', -> a.launchBundle BUNDLE .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] clockPort = deployment.portMapping[0].port q.delay 3500 .then -> deferred = q.defer() console.log 'Haciendo petición a clockAPI' clockAPI = hostname: '127.0.0.1' method: 'GET' port: clockPort path: '/mola?username=Peras&password=<PASSWORD>' http.request clockAPI, (res) -> res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.should.have.property 'clock' deferred.resolve true .end() deferred.promise describe 'Interconnecting services', -> frontDeployment = backDeployment = null it 'Normal connection', -> @timeout 60 * 1000 a.launchBundle INTERSERVICE_BACK .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] backDeployment = deployment.deploymentURN a.launchBundle INTERSERVICE_FRONT .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] frontDeployment = deployment.deploymentURN frontPort = deployment.portMapping[0].port q.delay 3500 .then -> console.log 'Conectando canales...' a.connectDeployments spec: 'http://eslap.cloud/manifest/link/1_0_0' endpoints: [ { deployment: frontDeployment channel: 'back' }, { deployment: backDeployment channel: 'service' } ] console.log 'Servicios conectados' console.log 'Haciendo petición a calculatorAPI' deferred = q.defer() calculatorAPI = hostname: '127.0.0.1' method: 'POST' port: frontPort headers: {'Content-Type': 'application/json'} path: '/restapi/add' req = http.request calculatorAPI, (res) -> res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.result.should.be.eql 80 deferred.resolve true req.write JSON.stringify {value1:45,value2:35} req.end() deferred.promise it 'Connects a tester to a bundle', -> TESTER_COMPONENT_CONFIG = iid: 'IS-tester' incnum: 1 parameters: {} role: 'tester' offerings: [] dependencies: [{id:'test',type:'Request'}] a.launch InterserviceTester, TESTER_COMPONENT_CONFIG, frontDeployment .then -> a.connect 'loadbalancer', [{role:'cfe', endpoint:'test'}], [{role:'tester', endpoint:'test'}], frontDeployment a.instances['IS-tester'].instance.case0(21, 37) .then (result)-> console.log "Vía IS-tester se obtiene #{JSON.stringify result}" result.result.should.be.eql 58 it 'Works with resources', -> @timeout 45 * 1000 * 500 a.launchBundle RESOURCES_BUNDLE .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] volumePort = deployment.portMapping[0].port q.delay 3500 .then -> deferred = q.defer() query = operation: 'read' volume: 'volatile' volumeAPI = hostname: '127.0.0.1' method: 'GET' port: volumePort path: "/java-resources-web-example/rest?#{qs.stringify query}" console.log "Haciendo petición a volumeAPI: #{JSON.stringify volumeAPI}" req = http.request volumeAPI, (res) -> res.statusCode.should.be.eql 400 res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.success.should.be.eql false result.error.should.be.eql 'No data' deferred.resolve true req.end() deferred.promise .then -> deferred = q.defer() query = operation: 'write' volume: 'volatile' data: '<NAME>' volumeAPI = hostname: '127.0.0.1' method: 'GET' port: volumePort path: "/java-resources-web-example/rest?#{qs.stringify query}" console.log "Haciendo petición a volumeAPI: #{JSON.stringify volumeAPI}" req = http.request volumeAPI, (res) -> res.statusCode.should.be.eql 200 res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.success.should.be.eql true result.data.should.be.eql 'OK' deferred.resolve true req.end() deferred.promise .then -> deferred = q.defer() query = operation: 'read' volume: 'volatile' volumeAPI = hostname: '127.0.0.1' method: 'GET' port: volumePort path: "/java-resources-web-example/rest?#{qs.stringify query}" console.log "Haciendo petición a volumeAPI: #{JSON.stringify volumeAPI}" req = http.request volumeAPI, (res) -> res.statusCode.should.be.eql 200 res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.success.should.be.eql true result.data.should.be.eql '<NAME>' deferred.resolve true req.end() deferred.promise it.skip 'Test bundle', (done)-> @timeout 120 * 60 * 1000 a.launchBundle TEST_BUNDLE .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" do done class InterserviceTester extends Component constructor: (@runtime, @role, @iid, @incnum, @localData, @resources , @parameters, @dependencies, @offerings) -> # NOTHING run: -> @running = true case0: (s1, s2)-> @dependencies.test.sendRequest JSON.stringify {value1:s1, value2:s2} .then (value)-> JSON.parse value.message.toString() process.on 'uncaughtException', (e)-> console.error 'uncaughtException:', e.stack process.on 'unhandledRejection', (reason, p)-> console.log 'Unhandled Rejection at: Promise', p, 'reason:', reason
true
should = require 'should' q = require 'q' http = require 'http' qs = require 'querystring' LocalStamp = require '..' Component = require 'component' clockPort = null frontPort = null volumePort = null a = null EXAMPLES='/workspaces/slap/git/examples' BUNDLE="#{EXAMPLES}/java-example/bundles/deploy_bundle.zip" INTERSERVICE="#{EXAMPLES}/interservice-example" INTERSERVICE_BACK="#{INTERSERVICE}/back/bundles/deploy_bundle.zip" INTERSERVICE_FRONT="#{INTERSERVICE}/front/bundles/deploy_bundle.zip" RESOURCES_BUNDLE="#{EXAMPLES}/java-web-example/bundles/deploy_bundle.zip" TEST_BUNDLE ="#{process.cwd()}/tests/bundle-test.zip" describe 'Local stamp - Bundle Support', -> @timeout 40 * 1000 before -> a = new LocalStamp('test',{runtimeFolder:'/tmp/runtime-agent'}) a.init() .then -> console.log 'Workspace ready' after (done)-> a.shutdown() .then -> done() it 'Normal bundle', -> a.launchBundle BUNDLE .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] clockPort = deployment.portMapping[0].port q.delay 3500 .then -> deferred = q.defer() console.log 'Haciendo petición a clockAPI' clockAPI = hostname: '127.0.0.1' method: 'GET' port: clockPort path: '/mola?username=Peras&password=PI:PASSWORD:<PASSWORD>END_PI' http.request clockAPI, (res) -> res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.should.have.property 'clock' deferred.resolve true .end() deferred.promise describe 'Interconnecting services', -> frontDeployment = backDeployment = null it 'Normal connection', -> @timeout 60 * 1000 a.launchBundle INTERSERVICE_BACK .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] backDeployment = deployment.deploymentURN a.launchBundle INTERSERVICE_FRONT .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] frontDeployment = deployment.deploymentURN frontPort = deployment.portMapping[0].port q.delay 3500 .then -> console.log 'Conectando canales...' a.connectDeployments spec: 'http://eslap.cloud/manifest/link/1_0_0' endpoints: [ { deployment: frontDeployment channel: 'back' }, { deployment: backDeployment channel: 'service' } ] console.log 'Servicios conectados' console.log 'Haciendo petición a calculatorAPI' deferred = q.defer() calculatorAPI = hostname: '127.0.0.1' method: 'POST' port: frontPort headers: {'Content-Type': 'application/json'} path: '/restapi/add' req = http.request calculatorAPI, (res) -> res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.result.should.be.eql 80 deferred.resolve true req.write JSON.stringify {value1:45,value2:35} req.end() deferred.promise it 'Connects a tester to a bundle', -> TESTER_COMPONENT_CONFIG = iid: 'IS-tester' incnum: 1 parameters: {} role: 'tester' offerings: [] dependencies: [{id:'test',type:'Request'}] a.launch InterserviceTester, TESTER_COMPONENT_CONFIG, frontDeployment .then -> a.connect 'loadbalancer', [{role:'cfe', endpoint:'test'}], [{role:'tester', endpoint:'test'}], frontDeployment a.instances['IS-tester'].instance.case0(21, 37) .then (result)-> console.log "Vía IS-tester se obtiene #{JSON.stringify result}" result.result.should.be.eql 58 it 'Works with resources', -> @timeout 45 * 1000 * 500 a.launchBundle RESOURCES_BUNDLE .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" deployment = result.deployments.successful[0] volumePort = deployment.portMapping[0].port q.delay 3500 .then -> deferred = q.defer() query = operation: 'read' volume: 'volatile' volumeAPI = hostname: '127.0.0.1' method: 'GET' port: volumePort path: "/java-resources-web-example/rest?#{qs.stringify query}" console.log "Haciendo petición a volumeAPI: #{JSON.stringify volumeAPI}" req = http.request volumeAPI, (res) -> res.statusCode.should.be.eql 400 res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.success.should.be.eql false result.error.should.be.eql 'No data' deferred.resolve true req.end() deferred.promise .then -> deferred = q.defer() query = operation: 'write' volume: 'volatile' data: 'PI:NAME:<NAME>END_PI' volumeAPI = hostname: '127.0.0.1' method: 'GET' port: volumePort path: "/java-resources-web-example/rest?#{qs.stringify query}" console.log "Haciendo petición a volumeAPI: #{JSON.stringify volumeAPI}" req = http.request volumeAPI, (res) -> res.statusCode.should.be.eql 200 res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.success.should.be.eql true result.data.should.be.eql 'OK' deferred.resolve true req.end() deferred.promise .then -> deferred = q.defer() query = operation: 'read' volume: 'volatile' volumeAPI = hostname: '127.0.0.1' method: 'GET' port: volumePort path: "/java-resources-web-example/rest?#{qs.stringify query}" console.log "Haciendo petición a volumeAPI: #{JSON.stringify volumeAPI}" req = http.request volumeAPI, (res) -> res.statusCode.should.be.eql 200 res.on 'data', (chunk) -> result = chunk.toString() console.log result result = JSON.parse result result.success.should.be.eql true result.data.should.be.eql 'PI:NAME:<NAME>END_PI' deferred.resolve true req.end() deferred.promise it.skip 'Test bundle', (done)-> @timeout 120 * 60 * 1000 a.launchBundle TEST_BUNDLE .then (result)-> console.log "DEPLOYMENT: #{JSON.stringify result, null, 2}" do done class InterserviceTester extends Component constructor: (@runtime, @role, @iid, @incnum, @localData, @resources , @parameters, @dependencies, @offerings) -> # NOTHING run: -> @running = true case0: (s1, s2)-> @dependencies.test.sendRequest JSON.stringify {value1:s1, value2:s2} .then (value)-> JSON.parse value.message.toString() process.on 'uncaughtException', (e)-> console.error 'uncaughtException:', e.stack process.on 'unhandledRejection', (reason, p)-> console.log 'Unhandled Rejection at: Promise', p, 'reason:', reason
[ { "context": "s.database = @cfg.database\n params.password = pw\n conn = mysql.createConnection params\n ", "end": 1428, "score": 0.9409129619598389, "start": 1426, "tag": "PASSWORD", "value": "pw" }, { "context": "\"\n obj = mm.config.secrets or {}\n obj.dbpw = ...
src/dbsetup.iced
AngelKey/Angelkey.nodehttpserver
1
mm = require('./mod').mgr env = require './env' fs = require 'fs' mysql = require 'mysql' read = require 'read' {make_esc} = require 'iced-error' {base64u} = require('pgp-utils').util {prng} = require 'crypto' path = require 'path' log = require 'iced-logger' ##----------------------------------------------------------------------- prune_sql_comments = (all) -> (line.split('--')[0] for line in all.split /\n/).join('\n') ##----------------------------------------------------------------------- class InitDB #--------- constructor : () -> @_mysqls = {} @_cmd = null #--------- init : (cb) -> await mm.start [ 'config' ], defer ok if not ok err = new Error 'failed to configure module manager' else @cfg = mm.config.db cb err #--------- get_root_pw : (cb) -> err = null p = env.get().get_root_db_pw() unless p? await read { prompt : 'mysql root db pw> ', silent : true }, defer err, p cb err, p #--------- get_conn : ({root}, cb) -> esc = make_esc cb, "InitDB::get_conn" user = if root then "root" else @cfg.user unless (conn = @_mysqls[user])? params = { host : @cfg.host, user, multipleStatements : true } if root await @get_root_pw esc defer pw else pw = @password or mm.config.secrets?.dbpw params.database = @cfg.database params.password = pw conn = mysql.createConnection params await conn.connect esc defer() @_mysqls[user] = conn cb null, conn #--------- parse_args : (cb) -> err = null if ((v = env.get().get_args()).length is 1) and (cmd = v[0])? switch cmd.toLowerCase() when 'init' then @cmd = @cmd_init.bind(@) when 'nuke' then @cmd = @cmd_delete.bind(@) if not @cmd err = new Error 'need a command: either "init" or "nuke"' cb err #--------- open_file : (cb) -> fn = path.join(env.get().get_top_dir(), "sql", [@cfg.database, "sql"].join(".")) await fs.readFile fn, defer err, dat unless err? @_create_tables = prune_sql_comments dat.toString('utf8') cb err #--------- test_connect : (cb) -> log.info "+ Testing connection to database #{@cfg.database}" esc = make_esc cb, "test_conenct" await @get_conn { root : false }, esc defer conn await conn.query "SELECT 1", esc defer dummy log.info "- DB connection succeeded" cb null #--------- cmd_init : (cb) -> await @test_connect defer err if err? log.warn "Failed to connect to DB; will try to create a new one" await @do_create defer err cb err #--------- write_secrets : (cb) -> fn = path.join env.get().get_config_dir(), 'secrets.json' log.info "| writing password out to #{fn}" obj = mm.config.secrets or {} obj.dbpw = @password json = JSON.stringify obj, null, " " await fs.writeFile fn, json, {mode : 0o640 }, defer err cb err #--------- fq_user : () -> [@cfg.user, @cfg.host].join('@') #--------- do_create : (cb) -> esc = make_esc cb, "do_create" log.info "+ creating database: #{@cfg.database}" await @open_file esc defer() await @get_conn { root : true }, esc defer c @password = base64u.encode prng 15 queries = [ "CREATE DATABASE #{@cfg.database}" "CREATE USER #{@fq_user()}" "SET PASSWORD FOR #{@fq_user()} = PASSWORD('#{@password}')" "GRANT ALL ON #{@cfg.database}.* TO #{@cfg.user}" "FLUSH PRIVILEGES" ] for q in queries await c.query q, esc defer() await @get_conn { root : false }, esc defer c2 await c2.query @_create_tables, esc defer() await @write_secrets esc defer() log.info "- created database" cb null #--------- confirm_please : (msg, cb) -> await read { prompt : msg }, defer err, val if not err? and not (val in ['y', 'Y', 'yes', 'YES' ]) err = new Error "canceled" cb err #--------- cmd_delete : (cb) -> esc = make_esc cb, "do_create" await @confirm_please "Really nuke your database? [y/N]", esc defer() log.info "+ Nuking database #{@cfg.database}" await @get_conn { root : true }, esc defer c queries = [ "DROP USER #{@fq_user()}" "DROP DATABASE #{@cfg.database}" "FLUSH PRIVILEGES" ] for q in queries await c.query q, esc defer() log.info "- Nuked!" cb null #--------- run : (cb) -> esc = make_esc cb, "run" await @init esc defer() await @parse_args esc defer() await @cmd esc defer() cb null ##----------------------------------------------------------------------- exports.main = () -> env.make (m) -> m.usage "Usage: $0 [-m <runmode>] [<init|nuke>]" eng = new InitDB() await eng.run defer err rc = 0 if err? console.error err.message rc = 2 process.exit rc ##-----------------------------------------------------------------------
11602
mm = require('./mod').mgr env = require './env' fs = require 'fs' mysql = require 'mysql' read = require 'read' {make_esc} = require 'iced-error' {base64u} = require('pgp-utils').util {prng} = require 'crypto' path = require 'path' log = require 'iced-logger' ##----------------------------------------------------------------------- prune_sql_comments = (all) -> (line.split('--')[0] for line in all.split /\n/).join('\n') ##----------------------------------------------------------------------- class InitDB #--------- constructor : () -> @_mysqls = {} @_cmd = null #--------- init : (cb) -> await mm.start [ 'config' ], defer ok if not ok err = new Error 'failed to configure module manager' else @cfg = mm.config.db cb err #--------- get_root_pw : (cb) -> err = null p = env.get().get_root_db_pw() unless p? await read { prompt : 'mysql root db pw> ', silent : true }, defer err, p cb err, p #--------- get_conn : ({root}, cb) -> esc = make_esc cb, "InitDB::get_conn" user = if root then "root" else @cfg.user unless (conn = @_mysqls[user])? params = { host : @cfg.host, user, multipleStatements : true } if root await @get_root_pw esc defer pw else pw = @password or mm.config.secrets?.dbpw params.database = @cfg.database params.password = <PASSWORD> conn = mysql.createConnection params await conn.connect esc defer() @_mysqls[user] = conn cb null, conn #--------- parse_args : (cb) -> err = null if ((v = env.get().get_args()).length is 1) and (cmd = v[0])? switch cmd.toLowerCase() when 'init' then @cmd = @cmd_init.bind(@) when 'nuke' then @cmd = @cmd_delete.bind(@) if not @cmd err = new Error 'need a command: either "init" or "nuke"' cb err #--------- open_file : (cb) -> fn = path.join(env.get().get_top_dir(), "sql", [@cfg.database, "sql"].join(".")) await fs.readFile fn, defer err, dat unless err? @_create_tables = prune_sql_comments dat.toString('utf8') cb err #--------- test_connect : (cb) -> log.info "+ Testing connection to database #{@cfg.database}" esc = make_esc cb, "test_conenct" await @get_conn { root : false }, esc defer conn await conn.query "SELECT 1", esc defer dummy log.info "- DB connection succeeded" cb null #--------- cmd_init : (cb) -> await @test_connect defer err if err? log.warn "Failed to connect to DB; will try to create a new one" await @do_create defer err cb err #--------- write_secrets : (cb) -> fn = path.join env.get().get_config_dir(), 'secrets.json' log.info "| writing password out to #{fn}" obj = mm.config.secrets or {} obj.dbpw = <PASSWORD> json = JSON.stringify obj, null, " " await fs.writeFile fn, json, {mode : 0o640 }, defer err cb err #--------- fq_user : () -> [@cfg.user, @cfg.host].join('@') #--------- do_create : (cb) -> esc = make_esc cb, "do_create" log.info "+ creating database: #{@cfg.database}" await @open_file esc defer() await @get_conn { root : true }, esc defer c @password = <PASSWORD>4u.encode prng 15 queries = [ "CREATE DATABASE #{@cfg.database}" "CREATE USER #{@fq_user()}" "SET PASSWORD FOR #{@fq_user()} = PASSWORD('#{<PASSWORD>}')" "GRANT ALL ON #{@cfg.database}.* TO #{@cfg.user}" "FLUSH PRIVILEGES" ] for q in queries await c.query q, esc defer() await @get_conn { root : false }, esc defer c2 await c2.query @_create_tables, esc defer() await @write_secrets esc defer() log.info "- created database" cb null #--------- confirm_please : (msg, cb) -> await read { prompt : msg }, defer err, val if not err? and not (val in ['y', 'Y', 'yes', 'YES' ]) err = new Error "canceled" cb err #--------- cmd_delete : (cb) -> esc = make_esc cb, "do_create" await @confirm_please "Really nuke your database? [y/N]", esc defer() log.info "+ Nuking database #{@cfg.database}" await @get_conn { root : true }, esc defer c queries = [ "DROP USER #{@fq_user()}" "DROP DATABASE #{@cfg.database}" "FLUSH PRIVILEGES" ] for q in queries await c.query q, esc defer() log.info "- Nuked!" cb null #--------- run : (cb) -> esc = make_esc cb, "run" await @init esc defer() await @parse_args esc defer() await @cmd esc defer() cb null ##----------------------------------------------------------------------- exports.main = () -> env.make (m) -> m.usage "Usage: $0 [-m <runmode>] [<init|nuke>]" eng = new InitDB() await eng.run defer err rc = 0 if err? console.error err.message rc = 2 process.exit rc ##-----------------------------------------------------------------------
true
mm = require('./mod').mgr env = require './env' fs = require 'fs' mysql = require 'mysql' read = require 'read' {make_esc} = require 'iced-error' {base64u} = require('pgp-utils').util {prng} = require 'crypto' path = require 'path' log = require 'iced-logger' ##----------------------------------------------------------------------- prune_sql_comments = (all) -> (line.split('--')[0] for line in all.split /\n/).join('\n') ##----------------------------------------------------------------------- class InitDB #--------- constructor : () -> @_mysqls = {} @_cmd = null #--------- init : (cb) -> await mm.start [ 'config' ], defer ok if not ok err = new Error 'failed to configure module manager' else @cfg = mm.config.db cb err #--------- get_root_pw : (cb) -> err = null p = env.get().get_root_db_pw() unless p? await read { prompt : 'mysql root db pw> ', silent : true }, defer err, p cb err, p #--------- get_conn : ({root}, cb) -> esc = make_esc cb, "InitDB::get_conn" user = if root then "root" else @cfg.user unless (conn = @_mysqls[user])? params = { host : @cfg.host, user, multipleStatements : true } if root await @get_root_pw esc defer pw else pw = @password or mm.config.secrets?.dbpw params.database = @cfg.database params.password = PI:PASSWORD:<PASSWORD>END_PI conn = mysql.createConnection params await conn.connect esc defer() @_mysqls[user] = conn cb null, conn #--------- parse_args : (cb) -> err = null if ((v = env.get().get_args()).length is 1) and (cmd = v[0])? switch cmd.toLowerCase() when 'init' then @cmd = @cmd_init.bind(@) when 'nuke' then @cmd = @cmd_delete.bind(@) if not @cmd err = new Error 'need a command: either "init" or "nuke"' cb err #--------- open_file : (cb) -> fn = path.join(env.get().get_top_dir(), "sql", [@cfg.database, "sql"].join(".")) await fs.readFile fn, defer err, dat unless err? @_create_tables = prune_sql_comments dat.toString('utf8') cb err #--------- test_connect : (cb) -> log.info "+ Testing connection to database #{@cfg.database}" esc = make_esc cb, "test_conenct" await @get_conn { root : false }, esc defer conn await conn.query "SELECT 1", esc defer dummy log.info "- DB connection succeeded" cb null #--------- cmd_init : (cb) -> await @test_connect defer err if err? log.warn "Failed to connect to DB; will try to create a new one" await @do_create defer err cb err #--------- write_secrets : (cb) -> fn = path.join env.get().get_config_dir(), 'secrets.json' log.info "| writing password out to #{fn}" obj = mm.config.secrets or {} obj.dbpw = PI:PASSWORD:<PASSWORD>END_PI json = JSON.stringify obj, null, " " await fs.writeFile fn, json, {mode : 0o640 }, defer err cb err #--------- fq_user : () -> [@cfg.user, @cfg.host].join('@') #--------- do_create : (cb) -> esc = make_esc cb, "do_create" log.info "+ creating database: #{@cfg.database}" await @open_file esc defer() await @get_conn { root : true }, esc defer c @password = PI:PASSWORD:<PASSWORD>END_PI4u.encode prng 15 queries = [ "CREATE DATABASE #{@cfg.database}" "CREATE USER #{@fq_user()}" "SET PASSWORD FOR #{@fq_user()} = PASSWORD('#{PI:PASSWORD:<PASSWORD>END_PI}')" "GRANT ALL ON #{@cfg.database}.* TO #{@cfg.user}" "FLUSH PRIVILEGES" ] for q in queries await c.query q, esc defer() await @get_conn { root : false }, esc defer c2 await c2.query @_create_tables, esc defer() await @write_secrets esc defer() log.info "- created database" cb null #--------- confirm_please : (msg, cb) -> await read { prompt : msg }, defer err, val if not err? and not (val in ['y', 'Y', 'yes', 'YES' ]) err = new Error "canceled" cb err #--------- cmd_delete : (cb) -> esc = make_esc cb, "do_create" await @confirm_please "Really nuke your database? [y/N]", esc defer() log.info "+ Nuking database #{@cfg.database}" await @get_conn { root : true }, esc defer c queries = [ "DROP USER #{@fq_user()}" "DROP DATABASE #{@cfg.database}" "FLUSH PRIVILEGES" ] for q in queries await c.query q, esc defer() log.info "- Nuked!" cb null #--------- run : (cb) -> esc = make_esc cb, "run" await @init esc defer() await @parse_args esc defer() await @cmd esc defer() cb null ##----------------------------------------------------------------------- exports.main = () -> env.make (m) -> m.usage "Usage: $0 [-m <runmode>] [<init|nuke>]" eng = new InitDB() await eng.run defer err rc = 0 if err? console.error err.message rc = 2 process.exit rc ##-----------------------------------------------------------------------
[ { "context": " ()->\n Accounts.emailTemplates.from = '来了吗APP <notify@mail.tiegushi.com>'\n Accounts.emailTemplates.siteName = '来了吗APP'", "end": 201, "score": 0.9999286532402039, "start": 177, "tag": "EMAIL", "value": "notify@mail.tiegushi.com" } ]
hotShareWeb/server/reset_password_template.coffee
fay1986/mobile_app_server
4
if Meteor.isServer Accounts.urls.resetPassword = (token)-> return Meteor.absoluteUrl('reset/' + token); Meteor.startup ()-> Accounts.emailTemplates.from = '来了吗APP <notify@mail.tiegushi.com>' Accounts.emailTemplates.siteName = '来了吗APP' #A Function that takes a user object and returns a String for the subject line of the email. Accounts.emailTemplates.verifyEmail.subject = (user)-> return '请验证您的邮件地址' #A Function that takes a user object and a url, and returns the body text for the email. #Note: if you need to return HTML instead, use Accounts.emailTemplates.verifyEmail.html Accounts.emailTemplates.verifyEmail.text = (user, url)-> return '请点击链接验证您的邮件地址: ' + url Accounts.emailTemplates.resetPassword.subject = (user)-> return '您请求重设来了吗APP的登录密码' Accounts.emailTemplates.resetPassword.text = (user,url)-> if user.profile and user.profile.fullname and user.profile.fullname isnt '' displayName = user.profile.fullname else displayName = user.fullname if displayName is undefined displayName = "您好" console.log url token = url.substring(url.lastIndexOf('/')+1, url.length) newUrl = Meteor.absoluteUrl('reset/' + token) displayName = displayName + ':\n' +'忘记来了吗APP密码了吗?别着急,请点击以下链接,我们协助您重设密码:\n' displayName = displayName + newUrl + '\n\n如果这不是您的邮件请忽略,很抱歉打扰您,请原谅。' return displayName
139634
if Meteor.isServer Accounts.urls.resetPassword = (token)-> return Meteor.absoluteUrl('reset/' + token); Meteor.startup ()-> Accounts.emailTemplates.from = '来了吗APP <<EMAIL>>' Accounts.emailTemplates.siteName = '来了吗APP' #A Function that takes a user object and returns a String for the subject line of the email. Accounts.emailTemplates.verifyEmail.subject = (user)-> return '请验证您的邮件地址' #A Function that takes a user object and a url, and returns the body text for the email. #Note: if you need to return HTML instead, use Accounts.emailTemplates.verifyEmail.html Accounts.emailTemplates.verifyEmail.text = (user, url)-> return '请点击链接验证您的邮件地址: ' + url Accounts.emailTemplates.resetPassword.subject = (user)-> return '您请求重设来了吗APP的登录密码' Accounts.emailTemplates.resetPassword.text = (user,url)-> if user.profile and user.profile.fullname and user.profile.fullname isnt '' displayName = user.profile.fullname else displayName = user.fullname if displayName is undefined displayName = "您好" console.log url token = url.substring(url.lastIndexOf('/')+1, url.length) newUrl = Meteor.absoluteUrl('reset/' + token) displayName = displayName + ':\n' +'忘记来了吗APP密码了吗?别着急,请点击以下链接,我们协助您重设密码:\n' displayName = displayName + newUrl + '\n\n如果这不是您的邮件请忽略,很抱歉打扰您,请原谅。' return displayName
true
if Meteor.isServer Accounts.urls.resetPassword = (token)-> return Meteor.absoluteUrl('reset/' + token); Meteor.startup ()-> Accounts.emailTemplates.from = '来了吗APP <PI:EMAIL:<EMAIL>END_PI>' Accounts.emailTemplates.siteName = '来了吗APP' #A Function that takes a user object and returns a String for the subject line of the email. Accounts.emailTemplates.verifyEmail.subject = (user)-> return '请验证您的邮件地址' #A Function that takes a user object and a url, and returns the body text for the email. #Note: if you need to return HTML instead, use Accounts.emailTemplates.verifyEmail.html Accounts.emailTemplates.verifyEmail.text = (user, url)-> return '请点击链接验证您的邮件地址: ' + url Accounts.emailTemplates.resetPassword.subject = (user)-> return '您请求重设来了吗APP的登录密码' Accounts.emailTemplates.resetPassword.text = (user,url)-> if user.profile and user.profile.fullname and user.profile.fullname isnt '' displayName = user.profile.fullname else displayName = user.fullname if displayName is undefined displayName = "您好" console.log url token = url.substring(url.lastIndexOf('/')+1, url.length) newUrl = Meteor.absoluteUrl('reset/' + token) displayName = displayName + ':\n' +'忘记来了吗APP密码了吗?别着急,请点击以下链接,我们协助您重设密码:\n' displayName = displayName + newUrl + '\n\n如果这不是您的邮件请忽略,很抱歉打扰您,请原谅。' return displayName
[ { "context": "sed on the Raconteur story scaffold, copyright (c) Bruno Dias 2015.\n\nDistributed under the MIT license. See LIC", "end": 68, "score": 0.9998660087585449, "start": 58, "tag": "NAME", "value": "Bruno Dias" }, { "context": "arth.\n\t\t<br><br>\n\t\t#{ timedWriter(system,...
game/main.coffee
jdormit/branches-raconteur
0
### Based on the Raconteur story scaffold, copyright (c) Bruno Dias 2015. Distributed under the MIT license. See LICENSE for information. ### # Require the libraries we rely on situation = require('raconteur') undum = require('undum-commonjs') oneOf = require('raconteur/lib/oneOf.js') elements = require('raconteur/lib/elements.js') qualities = require('raconteur/lib/qualities.js') a = elements.a span = elements.span img = elements.img p = (content) -> "<p>" + content + "</p>" # ---------------------------------------------------------------------------- # IFID and game version - Edit this undum.game.id = "659fb84c-62ed-4d1c-ba01-89c9316e3270" #UUID undum.game.version = "0.1" # ---------------------------------------------------------------------------- # Helper functions # Function that makes content appear after a number of seconds have passed # The `action` parameter should be the id of an action in the actions object of the parent situation timedWriter = (system, seconds, action) -> seconds *= 1000 action = "./_writer_" + action setTimeout( (() -> system.doLink(action) ), seconds) "" #return an empty string # ---------------------------------------------------------------------------- # Game content situation 'start', content: (character, system) -> """ *\"Cities, like dreams, are made of [desires and fears](intro), even if the thread of their discourse is secret, their rules are absurd, their perspectives deceitful, and everything conceals something else.\"* -- Italo Calvino, Invisible Cities <br><br> """ situation 'intro', content: (character, system) -> """ A fire crackles and pops in the hearth. <br><br> #{ timedWriter(system, 2, 'old-man') } """ writers: "old-man": (character, system) -> """ In a velvet armchair before the ornate fireplace sits an old man. His thick hair, the color of dirty snow, frames his lined face. His suit, though worn, is impeccable. White smoke from his wooden pipe mingles with sooty fumes from the fire. #{ timedWriter(system, 5, 'he-speaks') } """ "he-speaks": (character, system) -> """ [He speaks](opening_monologue): """ situation 'opening_monologue', content: """ &ldquo;There are some cities so heavy with memory that they resist the flow of time. Each generation walks upon the bones of the generations that came before, and make their small marks only to be buried beneath the feet of their children and their children's children. But the city remains -- or rather, new cities are built on top of the old, and no matter how deep you dig there will be another layer of cracked streets and faded murals and ghosts. &ldquo;Poets have written more verses of glittering Adriata by the sea than there are grains of sand on her beaches. Historians have chronicled her many triumphs and lamented her ancient defeats. But the memory of Adriata's marble walls stretches past the time of the most ancient histories, and beneath her cobbled streets lie secrets entombed for millennia. Sometimes, when the passing footstep of an errant child disturbs earth long undisturbed or the song of a love-struck youth finds its way into rooms that have not known song for a century, something shifts in the delicate architecture of Adriata's jumbled past. Cracks begin to form - and if you are very watchful, and very patient, you might find a way to slip into these cracks and explore her secrets long forgotten.&rdquo; The old man pauses. His pipe has run low. He stands and walks to side table where he keeps a little wooden box of the finest Virginia tobacco. He refills his pipe and stands by the window, contemplating the jumbled stones of [the city](city) outside. \"My story begins in Adriata, and it ends in Adriata, just as all stories ultimately begin and end in Adriata. Listen carefully, for like the city itself this story conceals its roots with its substance, and somewhere beneath its intricate surface lies the ghost of truth...\" """ situation 'city', content: """ The sun has just crested the inland hills, bathing the sky in orange and yellow. The old man does not squint against the glare. He looks instead at the achingly familiar skyline. To the south, towards the ocean, the tall crooked tenements of [The Narrows](narrows) give way to the cranes and masts of the harbor. Steeples and clocktowers punctuate the low roofs of the Flower District, where bakers sweeten the air with the scent of fresh bread and artisans tighten springs in clever clockwork toys. The streets rise to the north, where the pocked walls of the Inner City look inward at mansions almost as old as the families of those who live in them. Behind those ancient walls, crowning the hill around which Adriata grew, the burnt-out ruin of the [Royal Palace](palace) crumbles into obscurity. """ situation 'narrows', content: """ <br><br> &ldquo;I lived here with Elia. """ situation 'palace', content: """ <br><br> &ldquo;My first visit to the palace felt like a dream. """ #----------------------------------------------------------------------------- # Initialise Undum undum.game.init = (character, system) -> # Add initialisation code here # Get the party started when the DOM is ready. window.onload = undum.begin
141847
### Based on the Raconteur story scaffold, copyright (c) <NAME> 2015. Distributed under the MIT license. See LICENSE for information. ### # Require the libraries we rely on situation = require('raconteur') undum = require('undum-commonjs') oneOf = require('raconteur/lib/oneOf.js') elements = require('raconteur/lib/elements.js') qualities = require('raconteur/lib/qualities.js') a = elements.a span = elements.span img = elements.img p = (content) -> "<p>" + content + "</p>" # ---------------------------------------------------------------------------- # IFID and game version - Edit this undum.game.id = "659fb84c-62ed-4d1c-ba01-89c9316e3270" #UUID undum.game.version = "0.1" # ---------------------------------------------------------------------------- # Helper functions # Function that makes content appear after a number of seconds have passed # The `action` parameter should be the id of an action in the actions object of the parent situation timedWriter = (system, seconds, action) -> seconds *= 1000 action = "./_writer_" + action setTimeout( (() -> system.doLink(action) ), seconds) "" #return an empty string # ---------------------------------------------------------------------------- # Game content situation 'start', content: (character, system) -> """ *\"Cities, like dreams, are made of [desires and fears](intro), even if the thread of their discourse is secret, their rules are absurd, their perspectives deceitful, and everything conceals something else.\"* -- Italo Calvino, Invisible Cities <br><br> """ situation 'intro', content: (character, system) -> """ A fire crackles and pops in the hearth. <br><br> #{ timedWriter(system, 2, 'old-<NAME>') } """ writers: "old-man": (character, system) -> """ In a velvet armchair before the ornate fireplace sits an old man. His thick hair, the color of dirty snow, frames his lined face. His suit, though worn, is impeccable. White smoke from his wooden pipe mingles with sooty fumes from the fire. #{ timedWriter(system, 5, 'he-speaks') } """ "he-speaks": (character, system) -> """ [He speaks](opening_monologue): """ situation 'opening_monologue', content: """ &ldquo;There are some cities so heavy with memory that they resist the flow of time. Each generation walks upon the bones of the generations that came before, and make their small marks only to be buried beneath the feet of their children and their children's children. But the city remains -- or rather, new cities are built on top of the old, and no matter how deep you dig there will be another layer of cracked streets and faded murals and ghosts. &ldquo;Poets have written more verses of glittering Adriata by the sea than there are grains of sand on her beaches. Historians have chronicled her many triumphs and lamented her ancient defeats. But the memory of Adriata's marble walls stretches past the time of the most ancient histories, and beneath her cobbled streets lie secrets entombed for millennia. Sometimes, when the passing footstep of an errant child disturbs earth long undisturbed or the song of a love-struck youth finds its way into rooms that have not known song for a century, something shifts in the delicate architecture of Adriata's jumbled past. Cracks begin to form - and if you are very watchful, and very patient, you might find a way to slip into these cracks and explore her secrets long forgotten.&rdquo; The old man pauses. His pipe has run low. He stands and walks to side table where he keeps a little wooden box of the finest Virginia tobacco. He refills his pipe and stands by the window, contemplating the jumbled stones of [the city](city) outside. \"My story begins in Adriata, and it ends in Adriata, just as all stories ultimately begin and end in Adriata. Listen carefully, for like the city itself this story conceals its roots with its substance, and somewhere beneath its intricate surface lies the ghost of truth...\" """ situation 'city', content: """ The sun has just crested the inland hills, bathing the sky in orange and yellow. The old man does not squint against the glare. He looks instead at the achingly familiar skyline. To the south, towards the ocean, the tall crooked tenements of [The Narrows](narrows) give way to the cranes and masts of the harbor. Steeples and clocktowers punctuate the low roofs of the Flower District, where bakers sweeten the air with the scent of fresh bread and artisans tighten springs in clever clockwork toys. The streets rise to the north, where the pocked walls of the Inner City look inward at mansions almost as old as the families of those who live in them. Behind those ancient walls, crowning the hill around which Adriata grew, the burnt-out ruin of the [Royal Palace](palace) crumbles into obscurity. """ situation 'narrows', content: """ <br><br> &ldquo;I lived here with <NAME>. """ situation 'palace', content: """ <br><br> &ldquo;My first visit to the palace felt like a dream. """ #----------------------------------------------------------------------------- # Initialise Undum undum.game.init = (character, system) -> # Add initialisation code here # Get the party started when the DOM is ready. window.onload = undum.begin
true
### Based on the Raconteur story scaffold, copyright (c) PI:NAME:<NAME>END_PI 2015. Distributed under the MIT license. See LICENSE for information. ### # Require the libraries we rely on situation = require('raconteur') undum = require('undum-commonjs') oneOf = require('raconteur/lib/oneOf.js') elements = require('raconteur/lib/elements.js') qualities = require('raconteur/lib/qualities.js') a = elements.a span = elements.span img = elements.img p = (content) -> "<p>" + content + "</p>" # ---------------------------------------------------------------------------- # IFID and game version - Edit this undum.game.id = "659fb84c-62ed-4d1c-ba01-89c9316e3270" #UUID undum.game.version = "0.1" # ---------------------------------------------------------------------------- # Helper functions # Function that makes content appear after a number of seconds have passed # The `action` parameter should be the id of an action in the actions object of the parent situation timedWriter = (system, seconds, action) -> seconds *= 1000 action = "./_writer_" + action setTimeout( (() -> system.doLink(action) ), seconds) "" #return an empty string # ---------------------------------------------------------------------------- # Game content situation 'start', content: (character, system) -> """ *\"Cities, like dreams, are made of [desires and fears](intro), even if the thread of their discourse is secret, their rules are absurd, their perspectives deceitful, and everything conceals something else.\"* -- Italo Calvino, Invisible Cities <br><br> """ situation 'intro', content: (character, system) -> """ A fire crackles and pops in the hearth. <br><br> #{ timedWriter(system, 2, 'old-PI:NAME:<NAME>END_PI') } """ writers: "old-man": (character, system) -> """ In a velvet armchair before the ornate fireplace sits an old man. His thick hair, the color of dirty snow, frames his lined face. His suit, though worn, is impeccable. White smoke from his wooden pipe mingles with sooty fumes from the fire. #{ timedWriter(system, 5, 'he-speaks') } """ "he-speaks": (character, system) -> """ [He speaks](opening_monologue): """ situation 'opening_monologue', content: """ &ldquo;There are some cities so heavy with memory that they resist the flow of time. Each generation walks upon the bones of the generations that came before, and make their small marks only to be buried beneath the feet of their children and their children's children. But the city remains -- or rather, new cities are built on top of the old, and no matter how deep you dig there will be another layer of cracked streets and faded murals and ghosts. &ldquo;Poets have written more verses of glittering Adriata by the sea than there are grains of sand on her beaches. Historians have chronicled her many triumphs and lamented her ancient defeats. But the memory of Adriata's marble walls stretches past the time of the most ancient histories, and beneath her cobbled streets lie secrets entombed for millennia. Sometimes, when the passing footstep of an errant child disturbs earth long undisturbed or the song of a love-struck youth finds its way into rooms that have not known song for a century, something shifts in the delicate architecture of Adriata's jumbled past. Cracks begin to form - and if you are very watchful, and very patient, you might find a way to slip into these cracks and explore her secrets long forgotten.&rdquo; The old man pauses. His pipe has run low. He stands and walks to side table where he keeps a little wooden box of the finest Virginia tobacco. He refills his pipe and stands by the window, contemplating the jumbled stones of [the city](city) outside. \"My story begins in Adriata, and it ends in Adriata, just as all stories ultimately begin and end in Adriata. Listen carefully, for like the city itself this story conceals its roots with its substance, and somewhere beneath its intricate surface lies the ghost of truth...\" """ situation 'city', content: """ The sun has just crested the inland hills, bathing the sky in orange and yellow. The old man does not squint against the glare. He looks instead at the achingly familiar skyline. To the south, towards the ocean, the tall crooked tenements of [The Narrows](narrows) give way to the cranes and masts of the harbor. Steeples and clocktowers punctuate the low roofs of the Flower District, where bakers sweeten the air with the scent of fresh bread and artisans tighten springs in clever clockwork toys. The streets rise to the north, where the pocked walls of the Inner City look inward at mansions almost as old as the families of those who live in them. Behind those ancient walls, crowning the hill around which Adriata grew, the burnt-out ruin of the [Royal Palace](palace) crumbles into obscurity. """ situation 'narrows', content: """ <br><br> &ldquo;I lived here with PI:NAME:<NAME>END_PI. """ situation 'palace', content: """ <br><br> &ldquo;My first visit to the palace felt like a dream. """ #----------------------------------------------------------------------------- # Initialise Undum undum.game.init = (character, system) -> # Add initialisation code here # Get the party started when the DOM is ready. window.onload = undum.begin
[ { "context": "ault\"\n\t\t\"list\":\n\t\t\ttagName: \"div\"\n\t\t\tcontextKey: \"flexContent\"\n\t\t\tcontent:\n\t\t\t\ttagName: \"c-listview\"\n\t\t\t\tcontex", "end": 17082, "score": 0.8751342296600342, "start": 17071, "tag": "KEY", "value": "flexContent" }, { "context": "\t\t\t\t}...
src/widget/edit/dropdown.coffee
homeant/cola-ui
90
dropdownDialogMargin = 0 cola.findDropDown = (target)-> layer = cola.findWidget(target, cola.AbstractLayer, true) while layer and not layer._dropdown layer = cola.findWidget(layer, cola.AbstractLayer, true) return layer?._dropdown class cola.AbstractDropdown extends cola.AbstractInput @className: "input drop" @attributes: items: refreshDom: true expressionType: "repeat" # expressionNegative: true setter: (items)-> if typeof items is "string" items = items.split(/[,;]/) for item, i in items pos = item.indexOf("=") if pos >= 0 items[i] = key: item.substring(0, pos) value: item.substring(pos + 1) if not @_valueProperty and not @_textProperty @_valueProperty = "key" @_textProperty = "value" if not @_acceptUnknownValue and not @_valueProperty and not @_textProperty result = cola.util.decideValueProperty(items) if result @_valueProperty = result.valueProperty @_textProperty = result.textProperty changed = @_items isnt items or @_itemsTimestamp isnt items?.timestamp @_items = items if changed if items?.timestamp @_itemsTimestamp = items.timestamp delete @_itemsIndex if @_value isnt undefined and items @_setValue(@_value) return currentItem: readOnly: true valueProperty: null textProperty: null assignment: null editable: type: "boolean" defaultValue: true showClearButton: type: "boolean" defaultValue: true openOnActive: type: "boolean" defaultValue: true openMode: enum: [ "auto", "drop", "dialog", "layer", "sidebar" ] defaultValue: "auto" opened: readOnly: true dropdownLayer: null dropdownWidth: null dropdownHeight: null dropdownTitle: null @events: initDropdownBox: null beforeOpen: null open: null close: null selectData: null focus: null blur: null keyDown: null keyPress: null input: null _initDom: (dom)-> super(dom) if @getTemplate("value-content") @_useValueContent = true if @_useValueContent @_doms.input.value = "" $fly(@_doms.input).xInsertAfter({ tagName: "div" class: "value-content" contextKey: "valueContent" }, @_doms) $fly(dom).delegate(">.icon.drop", "click", ()=> if @_opened if new Date() - @_openTimestamp > 300 @close() else if not @_finalReadOnly @open() return false ).on("keypress", (evt)=> arg = keyCode: evt.keyCode shiftKey: evt.shiftKey ctrlKey: evt.ctrlKey altKey: evt.altKey event: evt inputValue: @_doms.input.value if @fire("keyPress", @, arg) is false return false ).on("mouseenter", (evt)=> if @_showClearButton clearButton = @_doms.clearButton if not clearButton @_doms.clearButton = clearButton = $.xCreate({ tagName: "i" class: "icon remove" mousedown: ()=> @_selectData(null) return false }) dom.appendChild(clearButton) $fly(clearButton).toggleClass("disabled", !@_doms.input.value) ) $(@_doms.input).on("input", (evt)=> value = @_doms.input.value arg = event: evt inputValue: value @fire("input", @, arg) ).on("keypress", ()=> @_inputEdited = true) unless @_skipSetIcon unless @_icon then @set("icon", "dropdown") if @_setValueOnInitDom and @_value isnt undefined delete @_setValueOnInitDom @_setValue(@_value) return _onFocus: ()-> @_inputEdited = false super() if @_openOnActive and not @_opened and not @_finalReadOnly @open() if @_useValueContent @_showValueTipIfNecessary() return _onBlur: ()-> if @_opened and @_finalOpenMode is "drop" @close() super() @_doms.tipDom and cola.util.cacheDom(@_doms.tipDom) return _onKeyDown: (evt)-> if evt.keyCode is 27 # ESC @close() return _showValueTipIfNecessary: ()-> if @_useValueContent and @_doms.valueContent valueContent = @_doms.valueContent if valueContent.scrollWidth > valueContent.clientWidth tipDom = @_doms.tipDom if not tipDom @_doms.tipDom = tipDom = cola.xCreate({ class: "dropdown-value-tip" }) if tipDom isnt document.body document.body.appendChild(tipDom) tipDom.innerHTML = @_doms.valueContent.innerHTML rect = $fly(@_dom).offset() $fly(tipDom).css( left: rect.left + @_dom.offsetWidth / 2 top: rect.top minWidth: @_dom.offsetWidth ) return _parseDom: (dom)-> return unless dom super(dom) @_parseTemplates() if not @_icon child = @_doms.input.nextSibling while child if child.nodeType is 1 and child.nodeName isnt "TEMPLATE" @_skipSetIcon = true break child = child.nextSibling return _createEditorDom: ()-> return $.xCreate( tagName: "input" type: "text" click: ()=> this.focus() ) _isEditorDom: (node)-> return node.nodeName is "INPUT" _isEditorReadOnly: ()-> return not @_editable or (@_filterable and @_useValueContent) _refreshIcon: ()-> super() if @_doms.iconDom $fly(@_doms.iconDom).addClass("drop") return _refreshInput: ()-> $inputDom = $fly(@_doms.input) $inputDom.attr("name", @_name) if @_name $inputDom.attr("placeholder", @get("placeholder")) $inputDom.attr("readOnly", @_finalReadOnly or @_isEditorReadOnly() or null) @get("actionButton")?.set("disabled", @_finalReadOnly) @_setValueContent() return _setValue: (value)-> if value isnt undefined if not @_dom @_setValueOnInitDom = true else if not @_skipFindCurrentItem and @_valueProperty if not @_items attrBinding = @_elementAttrBindings?["items"] if attrBinding and @_valueProperty @_refreshAttrValue("items") if @_items if not @_itemsIndex if @_items instanceof cola.EntityList @_itemsIndex = cola.util.buildIndex(@_items, @_valueProperty) else @_itemsIndex = index = {} valueProperty = @_valueProperty cola.each @_items, (item)-> if item instanceof cola.Entity key = item.get(valueProperty) else key = item[valueProperty] index[key + ""] = item return if @_itemsIndex if @_itemsIndex instanceof cola.EntityIndex currentItem = @_itemsIndex.find(value) else currentItem = @_itemsIndex[value + ""] @_currentItem = currentItem else item = @_currentItem = { $emptyItem: true } item[@_valueProperty] = value item[@_textProperty] = value else @_currentItem = { $emptyItem: true } return super(value) _setValueContent: ()-> item = @_currentItem if not item? if not @_textProperty item = @_value else item = { $emptyItem: true } item[@_textProperty] = @_value input = @_doms.input if item if @_useValueContent elementAttrBinding = @_elementAttrBindings?["items"] alias = elementAttrBinding?.expression.alias or "item" currentItemScope = @_currentItemScope if currentItemScope and currentItemScope.data.alias isnt alias currentItemScope = null if not currentItemScope @_currentItemScope = currentItemScope = new cola.ItemScope(@_scope, alias) currentItemScope.data.setItemData(item) valueContent = @_doms.valueContent if not valueContent._inited valueContent._inited = true ctx = defaultPath: alias @_initValueContent(valueContent, ctx) cola.xRender(valueContent, currentItemScope, ctx) $fly(valueContent).show() else property = @_textProperty or @_valueProperty if property if item instanceof cola.Entity text = cola.Entity._evalDataPath(item, property or "value") else if typeof item is "object" and not (item instanceof Date) if item.hasOwnProperty(property) text = item[property] else text = cola.Entity._evalDataPath(item, property or "value") else text = item input.value = text or "" else text = @readBindingValue() input.value = text or "" else if not @_useValueContent text = @readBindingValue() input.value = text or "" if @_useValueContent $fly(@_doms.valueContent).hide() if item and not item.$emptyItem input.placeholder = "" @get$Dom().removeClass("placeholder") else input.placeholder = @_placeholder or "" @get$Dom().addClass("placeholder") if @_focused and @_useValueContent @_showValueTipIfNecessary() return _initValueContent: (valueContent, context)-> property = @_textProperty or @_valueProperty or "value" if property context.defaultPath += "." + property template = @getTemplate("value-content") if template valueContent.appendChild(template) return _getFinalOpenMode: ()-> openMode = @_openMode if !openMode or openMode is "auto" if cola.device.desktop openMode = "drop" else if cola.device.phone openMode = "layer" else # pad openMode = "dialog" return openMode _getTitleContent: ()-> return cola.xRender({ tagName: "div" class: "box" content: tagName: "c-titlebar" content: [ { tagName: "a" icon: "chevron left" click: ()=> @close() } ] }, @_scope, {}) _getContainer: (dontCreate)-> if @_container @_dontRefreshItems = true @_refreshDropdownContent?() delete @_dontRefreshItems return @_container else if not dontCreate @_finalOpenMode = openMode = @_getFinalOpenMode() config = class: "drop-container" dom: $.xCreate( content: @_getDropdownContent() ) beforeHide: ()=> $fly(@_dom).removeClass("opened") return hide: ()=> @_opened = false return @_dropdownContent = config.dom.firstChild config.width = @_dropdownWidth if @_dropdownWidth config.height = @_dropdownHeight if @_dropdownHeight if openMode is "drop" config.duration = 200 config.dropdown = @ config.class = @_class container = new cola.DropBox(config) else if openMode is "layer" if openMode is "sidebar" config.animation = "slide up" config.height = "50%" titleContent = @_getTitleContent() $fly(config.dom.firstChild.firstChild).before(titleContent) container = new cola.Layer(config) else if openMode is "sidebar" config.direction = "bottom" config.size = document.documentElement.clientHeight / 2 $fly(config.dom.firstChild.firstChild).before(titleContent) container = new cola.Sidebar(config) else if openMode is "dialog" config.modalOpacity = 0.05 config.closeable = false config.dimmerClose = true if not config.width then config.width = "80%" if not config.height then config.height = "80%" if @_dropdownTitle config.dom = $.xCreate( content: [ { class: "header" content: @_dropdownTitle } { class: "content" content: config.dom } ] ) container = new cola.Dialog(config) @_container = container container.appendTo(document.body) return container return open: (callback)-> if @_finalReadOnly then return if @fire("beforeOpen", @) is false then return doCallback = ()=> @fire("open", @) cola.callback(callback, true) return container = @_getContainer() if container container._dropdown = @ container._focusParent = @ container.on("hide", (self)-> delete self._dropdown return ) if container instanceof cola.Dialog $flexContent = $(@_doms.flexContent) $flexContent.height("") $containerDom = container.get$Dom() $containerDom.removeClass("hidden") containerHeight = $containerDom.height() clientHeight = document.documentElement.clientHeight if containerHeight > (clientHeight - dropdownDialogMargin * 2) height = $flexContent.height() - (containerHeight - (clientHeight - dropdownDialogMargin * 2)) $containerDom.addClass("hidden") $flexContent.height(height) else $containerDom.addClass("hidden") @fire("initDropdownBox", @, { dropdownBox: container }) if container.constructor.events.$has("hide") container.on("hide:dropdown", ()=> @fire("close", @) return , true) container.show?(doCallback) @_opened = true @_openTimestamp = new Date() $fly(@_dom).addClass("opened") if @_filterable and @_useValueContent @_refreshInputValue(null) return true return close: (selectedData, callback)-> if selectedData isnt undefined @_selectData(selectedData) else if @_inputEdited if @_acceptUnknownValue @set("value", @_doms.input.value) @post() else @refresh() container = @_getContainer(true) container?.hide?(callback) return _getItemValue: (item)-> if @_valueProperty and item if item instanceof cola.Entity value = item.get(@_valueProperty) else value = item[@_valueProperty] else value = item return value _selectData: (item)-> @_inputEdited = false @_skipFindCurrentItem = true if @fire("selectData", @, { data: item }) isnt false @_currentItem = item if @_assignment and @_bindInfo?.writeable if @_valueProperty or @_textProperty prop = @_valueProperty or @_textProperty if item if item instanceof cola.Entity value = item.get(prop) else value = item[prop] else value = null arg = { oldValue: @_value, value: value } if @fire("beforeChange", @, arg) is false @refreshValue() return if @fire("beforePost", @, arg) is false @refreshValue() return bindEntity = @_scope.get(@_bindInfo.entityPath) @_assignment.split(/[,;]/).forEach((part)=> pair = part.split("=") targetProp = pair[0] if targetProp sourceProp = pair[1] or targetProp if item if item instanceof cola.Entity value = item.get(sourceProp) else value = item[sourceProp] else value = null bindEntity.set(targetProp, value) return ) @fire("change", @, arg) @fire("post", @) else value = @_getItemValue(item) @set("value", value) @_skipFindCurrentItem = false @refresh() return cola.Element.mixin(cola.AbstractDropdown, cola.TemplateSupport) class cola.DropBox extends cola.Layer @tagName: "c-drop-box" @className: "drop-box transition" @attributes: height: setter: (height)-> @_maxHeight = height return dropdown: null focusable: defaultValue: true resize: (opened)-> dom = @getDom() $dom = @get$Dom() dropdownDom = @_dropdown._doms.input if not cola.util.isVisible(dropdownDom) @hide() return # 防止因改变高度导致滚动条自动还原到初始位置 if opened boxWidth = dom.offsetWidth boxHeight = dom.offsetHeight else if @_maxHeight $dom.css("max-height", @_maxHeight) $dom.css("height", "") $dom.removeClass("hidden") boxWidth = $dom.width() boxHeight = $dom.height() $dom.addClass("hidden") rect = $fly(dropdownDom).offset() clientWidth = document.documentElement.clientWidth - 6 clientHeight = document.documentElement.clientHeight - 6 bottomSpace = Math.abs(document.documentElement.scrollTop + clientHeight - rect.top - dropdownDom.clientHeight) if bottomSpace >= boxHeight direction = "down" else topSpace = rect.top - document.documentElement.scrollTop - 6 if topSpace > bottomSpace direction = "up" if boxHeight > topSpace then height = topSpace else direction = "down" if boxHeight > bottomSpace then height = bottomSpace if opened if height $dom.css("height", height) else if dom.firstElementChild is dom.lastElementChild if dom.firstElementChild.offsetHeight < dom.clientHeight $dom.css("height", "auto") if direction is "down" top = rect.top + dropdownDom.clientHeight else top = rect.top - dom.offsetHeight + 2 left = rect.left if boxWidth > dropdownDom.offsetWidth if boxWidth + rect.left > clientWidth left = clientWidth - boxWidth if left < 0 then left = 0 if opened $dom.removeClass(if direction is "down" then "direction-up" else "direction-down") .addClass("direction-" + direction) .toggleClass("x-over", boxWidth > dropdownDom.offsetWidth) .css("left", left).css("top", top) $dom.css("min-width", dropdownDom.offsetWidth || 80) .css("max-width", document.documentElement.clientWidth) return show: (options, callback)-> @resize() @_animation = "fade" super(options, callback) @resize(true) @_resizeTimer = setInterval(()=> @resize(true) return , 300) return hide: (options, callback)-> if @_resizeTimer clearInterval(@_resizeTimer) delete @_resizeTimer super(options, callback) return class cola.Dropdown extends cola.AbstractDropdown @tagName: "c-dropdown" @attributes: filterable: readOnlyAfterCreate: true defaultValue: true filterValue: readOnly: true filterProperty: null filterInterval: defaultValue: 300 @events: filterItem: null @templates: "default": tagName: "li" "c-bind": "$default" "list": tagName: "div" contextKey: "flexContent" content: tagName: "c-listview" contextKey: "list" allowNoCurrent: true changeCurrentItem: true highlightCurrentItem: true transition: true style: "overflow:auto" keydown: (evt)-> if not @_disableKeyBubble @_disableKeyBubble = true $fly(@).find(">c-listview").trigger(evt) @_disableKeyBubble = false return true "filterable-list": tagName: "div" class: "v-box" content: [ { tagName: "div" class: "box filter-container" content: tagName: "c-input" contextKey: "input" class: "fluid" icon: "search" } { tagName: "div" contextKey: "flexContent" class: "flex-box list-container" style: "min-height:2em" content: tagName: "c-listview" contextKey: "list" allowNoCurrent: true changeCurrentItem: true highlightCurrentItem: true transition: true } ] keydown: (evt)-> if not @_disableKeyBubble @_disableKeyBubble = true $fly(@).find(">.flex-box >c-listview").trigger(evt) @_disableKeyBubble = false return true _initDom: (dom)-> @_regDefaultTemplates() inputDom = @_doms.input $fly(inputDom).on("input", ()=> @_inputDirty = true @_onInput(inputDom.value) return ) super(dom) if @_filterable and @_useValueContent $fly(dom).addClass("filterable").xAppend( contextKey: "filterInput" tagName: "input" text: "input" type: "text", class: "filter-input" focus: ()=> cola._setFocusWidget(@) input: (evt)=> if @_useValueContent $valueContent = $fly(@_doms.valueContent) if evt.target.value $valueContent.hide() else $valueContent.show() @_onInput(@_doms.filterInput.value) return , @_doms) return _refreshInputValue: (value)-> super(if @_useValueContent then null else value) return open: ()-> if super() list = @_list if list and @_currentItem isnt list.get("currentItem") list.set("currentItem", @_currentItem) if @_opened and @_filterable if @_list.get("filterCriteria") isnt null @_list.set("filterCriteria", null).refresh() return true return _onInput: (value)-> cola.util.delay(@, "filterItems", 150, ()-> return unless @_list criteria = value if @_opened and @_filterable filterProperty = @_filterProperty or @_textProperty if not value if filterProperty criteria = {} criteria[filterProperty] = value @_list.set("filterCriteria", criteria).refresh() items = @_list.getItems() currentItemDom = null if @_filterable if value isnt null exactlyMatch firstItem = items?[0] if firstItem if filterProperty exactlyMatch = cola.Entity._evalDataPath(firstItem, filterProperty) is value else exactlyMatch = firstItem is value if exactlyMatch currentItemDom = @_list._getFirstItemDom() @_list._setCurrentItemDom(currentItemDom) else item = items and cola.util.find(items, criteria) if item entityId = cola.Entity._getEntityId(item) if entityId @_list.set("currentItem", item) else @_list._setCurrentItemDom(currentItemDom) else @_list._setCurrentItemDom(null) return ) return _getSelectData: ()-> return @_list?.get("currentItem") or null _onKeyDown: (evt)-> if evt.keyCode is 13 # Enter @close(@_getSelectData()) return false else if evt.keyCode is 27 # ESC @close(@_currentItem or null) else if evt.keyCode is 38 or evt.keyCode is 40 # UP, DOWN @_list?._onKeyDown(evt) return _selectData: (item)-> @_inputDirty = false @_doms.filterInput?.value = "" return super(item) _onBlur: ()-> if @_inputDirty @close(@_getSelectData()) @_doms.filterInput?.value = "" return super() _getDropdownContent: ()-> if not @_dropdownContent if @_filterable and @_finalOpenMode isnt "drop" templateName = "filterable-list" else templateName = "list" template = @getTemplate(templateName) @_dropdownContent = template = cola.xRender(template, @_scope) @_list = list = cola.widget(@_doms.list) if @_templates templ = @_templates["item-content"] or @_templates["value-content"] if templ list.regTemplate("default", templ) hasDefaultTemplate = true if not hasDefaultTemplate list.regTemplate("default", { tagName: "li" "c-bind": "$default" }) list.on("itemClick", (self, arg)=> @close(self.getItemByItemDom(arg.dom)) return ).on("click", ()-> false) @_refreshDropdownContent() return template _refreshDropdownContent: ()-> attrBinding = @_elementAttrBindings?["items"] list = @_list list._textProperty = @_textProperty or @_valueProperty if attrBinding && list.get("model").get(attrBinding.expression.raw) # if not @_dontRefreshItems # @_refreshAttrValue("items") list.set("bind", attrBinding.expression.raw) else list.set("items", @_items) list.refresh() cola.registerWidget(cola.Dropdown) class cola.CustomDropdown extends cola.AbstractDropdown @tagName: "c-custom-dropdown" @attributes: content: null @templates: "default": tagName: "div" content: "<Undefined>" _isEditorReadOnly: ()-> return true _getDropdownContent: ()-> if not @_dropdownContent if @_content dropdownContent = @_content else dropdownContent = @getTemplate() @_dropdownContent = cola.xRender(dropdownContent, @_scope) return @_dropdownContent cola.registerWidget(cola.CustomDropdown) class cola.ComboBox extends cola.Dropdown @tagName: "c-combo-box" @attributes: postOnInput: type: "boolean" @events: keyPress: null input:null constructor: (config)-> @_acceptUnknownValue = true super(config) _initDom: (dom)-> super(dom) input = @_doms.input $(input).on("input", ()=> arg = { inputValue: input.value, value: this.get("value") } @fire("input", @, arg) if @_postOnInput then @set("value", input.value) return ).on("keypress", (event)=> arg = keyCode: event.keyCode shiftKey: event.shiftKey ctrlKey: event.ctrlKey altKey: event.altKey event: event if @fire("keyPress", @, arg) == false then return false if event.keyCode is 13 and isIE11 then @_postInput() ) return fire: (eventName, self, arg)-> if eventName is "keyDown" or eventName is "keyPress" arg.inputValue = @_doms.input.value return super(eventName, self, arg) _setValueContent: ()-> ctx = {} value = @readBindingValue(ctx) input = @_doms.input input.value = value or "" if value input.placeholder = "" @get$Dom().removeClass("placeholder") else input.placeholder = @_placeholder or "" @get$Dom().addClass("placeholder") return _getSelectData: ()-> items = @_list?.get("items") if items if items instanceof Array if items.length is 1 then item = items[0] else if items instanceof cola.EntityList if items.entityCount is 1 then item = items.current value = @_doms.input.value matchProperty = @_filterProperty or @_textProperty or @_valueProperty if matchProperty if item instanceof cola.Entity if item.get(matchProperty) is value return item else if typeof item is "object" if item[matchProperty] is value return item if value if @_valueProperty or @_textProperty item = { $emptyItem: true } item[@_valueProperty] = value item[@_textProperty] = value return item return undefined cola.registerWidget(cola.ComboBox)
30111
dropdownDialogMargin = 0 cola.findDropDown = (target)-> layer = cola.findWidget(target, cola.AbstractLayer, true) while layer and not layer._dropdown layer = cola.findWidget(layer, cola.AbstractLayer, true) return layer?._dropdown class cola.AbstractDropdown extends cola.AbstractInput @className: "input drop" @attributes: items: refreshDom: true expressionType: "repeat" # expressionNegative: true setter: (items)-> if typeof items is "string" items = items.split(/[,;]/) for item, i in items pos = item.indexOf("=") if pos >= 0 items[i] = key: item.substring(0, pos) value: item.substring(pos + 1) if not @_valueProperty and not @_textProperty @_valueProperty = "key" @_textProperty = "value" if not @_acceptUnknownValue and not @_valueProperty and not @_textProperty result = cola.util.decideValueProperty(items) if result @_valueProperty = result.valueProperty @_textProperty = result.textProperty changed = @_items isnt items or @_itemsTimestamp isnt items?.timestamp @_items = items if changed if items?.timestamp @_itemsTimestamp = items.timestamp delete @_itemsIndex if @_value isnt undefined and items @_setValue(@_value) return currentItem: readOnly: true valueProperty: null textProperty: null assignment: null editable: type: "boolean" defaultValue: true showClearButton: type: "boolean" defaultValue: true openOnActive: type: "boolean" defaultValue: true openMode: enum: [ "auto", "drop", "dialog", "layer", "sidebar" ] defaultValue: "auto" opened: readOnly: true dropdownLayer: null dropdownWidth: null dropdownHeight: null dropdownTitle: null @events: initDropdownBox: null beforeOpen: null open: null close: null selectData: null focus: null blur: null keyDown: null keyPress: null input: null _initDom: (dom)-> super(dom) if @getTemplate("value-content") @_useValueContent = true if @_useValueContent @_doms.input.value = "" $fly(@_doms.input).xInsertAfter({ tagName: "div" class: "value-content" contextKey: "valueContent" }, @_doms) $fly(dom).delegate(">.icon.drop", "click", ()=> if @_opened if new Date() - @_openTimestamp > 300 @close() else if not @_finalReadOnly @open() return false ).on("keypress", (evt)=> arg = keyCode: evt.keyCode shiftKey: evt.shiftKey ctrlKey: evt.ctrlKey altKey: evt.altKey event: evt inputValue: @_doms.input.value if @fire("keyPress", @, arg) is false return false ).on("mouseenter", (evt)=> if @_showClearButton clearButton = @_doms.clearButton if not clearButton @_doms.clearButton = clearButton = $.xCreate({ tagName: "i" class: "icon remove" mousedown: ()=> @_selectData(null) return false }) dom.appendChild(clearButton) $fly(clearButton).toggleClass("disabled", !@_doms.input.value) ) $(@_doms.input).on("input", (evt)=> value = @_doms.input.value arg = event: evt inputValue: value @fire("input", @, arg) ).on("keypress", ()=> @_inputEdited = true) unless @_skipSetIcon unless @_icon then @set("icon", "dropdown") if @_setValueOnInitDom and @_value isnt undefined delete @_setValueOnInitDom @_setValue(@_value) return _onFocus: ()-> @_inputEdited = false super() if @_openOnActive and not @_opened and not @_finalReadOnly @open() if @_useValueContent @_showValueTipIfNecessary() return _onBlur: ()-> if @_opened and @_finalOpenMode is "drop" @close() super() @_doms.tipDom and cola.util.cacheDom(@_doms.tipDom) return _onKeyDown: (evt)-> if evt.keyCode is 27 # ESC @close() return _showValueTipIfNecessary: ()-> if @_useValueContent and @_doms.valueContent valueContent = @_doms.valueContent if valueContent.scrollWidth > valueContent.clientWidth tipDom = @_doms.tipDom if not tipDom @_doms.tipDom = tipDom = cola.xCreate({ class: "dropdown-value-tip" }) if tipDom isnt document.body document.body.appendChild(tipDom) tipDom.innerHTML = @_doms.valueContent.innerHTML rect = $fly(@_dom).offset() $fly(tipDom).css( left: rect.left + @_dom.offsetWidth / 2 top: rect.top minWidth: @_dom.offsetWidth ) return _parseDom: (dom)-> return unless dom super(dom) @_parseTemplates() if not @_icon child = @_doms.input.nextSibling while child if child.nodeType is 1 and child.nodeName isnt "TEMPLATE" @_skipSetIcon = true break child = child.nextSibling return _createEditorDom: ()-> return $.xCreate( tagName: "input" type: "text" click: ()=> this.focus() ) _isEditorDom: (node)-> return node.nodeName is "INPUT" _isEditorReadOnly: ()-> return not @_editable or (@_filterable and @_useValueContent) _refreshIcon: ()-> super() if @_doms.iconDom $fly(@_doms.iconDom).addClass("drop") return _refreshInput: ()-> $inputDom = $fly(@_doms.input) $inputDom.attr("name", @_name) if @_name $inputDom.attr("placeholder", @get("placeholder")) $inputDom.attr("readOnly", @_finalReadOnly or @_isEditorReadOnly() or null) @get("actionButton")?.set("disabled", @_finalReadOnly) @_setValueContent() return _setValue: (value)-> if value isnt undefined if not @_dom @_setValueOnInitDom = true else if not @_skipFindCurrentItem and @_valueProperty if not @_items attrBinding = @_elementAttrBindings?["items"] if attrBinding and @_valueProperty @_refreshAttrValue("items") if @_items if not @_itemsIndex if @_items instanceof cola.EntityList @_itemsIndex = cola.util.buildIndex(@_items, @_valueProperty) else @_itemsIndex = index = {} valueProperty = @_valueProperty cola.each @_items, (item)-> if item instanceof cola.Entity key = item.get(valueProperty) else key = item[valueProperty] index[key + ""] = item return if @_itemsIndex if @_itemsIndex instanceof cola.EntityIndex currentItem = @_itemsIndex.find(value) else currentItem = @_itemsIndex[value + ""] @_currentItem = currentItem else item = @_currentItem = { $emptyItem: true } item[@_valueProperty] = value item[@_textProperty] = value else @_currentItem = { $emptyItem: true } return super(value) _setValueContent: ()-> item = @_currentItem if not item? if not @_textProperty item = @_value else item = { $emptyItem: true } item[@_textProperty] = @_value input = @_doms.input if item if @_useValueContent elementAttrBinding = @_elementAttrBindings?["items"] alias = elementAttrBinding?.expression.alias or "item" currentItemScope = @_currentItemScope if currentItemScope and currentItemScope.data.alias isnt alias currentItemScope = null if not currentItemScope @_currentItemScope = currentItemScope = new cola.ItemScope(@_scope, alias) currentItemScope.data.setItemData(item) valueContent = @_doms.valueContent if not valueContent._inited valueContent._inited = true ctx = defaultPath: alias @_initValueContent(valueContent, ctx) cola.xRender(valueContent, currentItemScope, ctx) $fly(valueContent).show() else property = @_textProperty or @_valueProperty if property if item instanceof cola.Entity text = cola.Entity._evalDataPath(item, property or "value") else if typeof item is "object" and not (item instanceof Date) if item.hasOwnProperty(property) text = item[property] else text = cola.Entity._evalDataPath(item, property or "value") else text = item input.value = text or "" else text = @readBindingValue() input.value = text or "" else if not @_useValueContent text = @readBindingValue() input.value = text or "" if @_useValueContent $fly(@_doms.valueContent).hide() if item and not item.$emptyItem input.placeholder = "" @get$Dom().removeClass("placeholder") else input.placeholder = @_placeholder or "" @get$Dom().addClass("placeholder") if @_focused and @_useValueContent @_showValueTipIfNecessary() return _initValueContent: (valueContent, context)-> property = @_textProperty or @_valueProperty or "value" if property context.defaultPath += "." + property template = @getTemplate("value-content") if template valueContent.appendChild(template) return _getFinalOpenMode: ()-> openMode = @_openMode if !openMode or openMode is "auto" if cola.device.desktop openMode = "drop" else if cola.device.phone openMode = "layer" else # pad openMode = "dialog" return openMode _getTitleContent: ()-> return cola.xRender({ tagName: "div" class: "box" content: tagName: "c-titlebar" content: [ { tagName: "a" icon: "chevron left" click: ()=> @close() } ] }, @_scope, {}) _getContainer: (dontCreate)-> if @_container @_dontRefreshItems = true @_refreshDropdownContent?() delete @_dontRefreshItems return @_container else if not dontCreate @_finalOpenMode = openMode = @_getFinalOpenMode() config = class: "drop-container" dom: $.xCreate( content: @_getDropdownContent() ) beforeHide: ()=> $fly(@_dom).removeClass("opened") return hide: ()=> @_opened = false return @_dropdownContent = config.dom.firstChild config.width = @_dropdownWidth if @_dropdownWidth config.height = @_dropdownHeight if @_dropdownHeight if openMode is "drop" config.duration = 200 config.dropdown = @ config.class = @_class container = new cola.DropBox(config) else if openMode is "layer" if openMode is "sidebar" config.animation = "slide up" config.height = "50%" titleContent = @_getTitleContent() $fly(config.dom.firstChild.firstChild).before(titleContent) container = new cola.Layer(config) else if openMode is "sidebar" config.direction = "bottom" config.size = document.documentElement.clientHeight / 2 $fly(config.dom.firstChild.firstChild).before(titleContent) container = new cola.Sidebar(config) else if openMode is "dialog" config.modalOpacity = 0.05 config.closeable = false config.dimmerClose = true if not config.width then config.width = "80%" if not config.height then config.height = "80%" if @_dropdownTitle config.dom = $.xCreate( content: [ { class: "header" content: @_dropdownTitle } { class: "content" content: config.dom } ] ) container = new cola.Dialog(config) @_container = container container.appendTo(document.body) return container return open: (callback)-> if @_finalReadOnly then return if @fire("beforeOpen", @) is false then return doCallback = ()=> @fire("open", @) cola.callback(callback, true) return container = @_getContainer() if container container._dropdown = @ container._focusParent = @ container.on("hide", (self)-> delete self._dropdown return ) if container instanceof cola.Dialog $flexContent = $(@_doms.flexContent) $flexContent.height("") $containerDom = container.get$Dom() $containerDom.removeClass("hidden") containerHeight = $containerDom.height() clientHeight = document.documentElement.clientHeight if containerHeight > (clientHeight - dropdownDialogMargin * 2) height = $flexContent.height() - (containerHeight - (clientHeight - dropdownDialogMargin * 2)) $containerDom.addClass("hidden") $flexContent.height(height) else $containerDom.addClass("hidden") @fire("initDropdownBox", @, { dropdownBox: container }) if container.constructor.events.$has("hide") container.on("hide:dropdown", ()=> @fire("close", @) return , true) container.show?(doCallback) @_opened = true @_openTimestamp = new Date() $fly(@_dom).addClass("opened") if @_filterable and @_useValueContent @_refreshInputValue(null) return true return close: (selectedData, callback)-> if selectedData isnt undefined @_selectData(selectedData) else if @_inputEdited if @_acceptUnknownValue @set("value", @_doms.input.value) @post() else @refresh() container = @_getContainer(true) container?.hide?(callback) return _getItemValue: (item)-> if @_valueProperty and item if item instanceof cola.Entity value = item.get(@_valueProperty) else value = item[@_valueProperty] else value = item return value _selectData: (item)-> @_inputEdited = false @_skipFindCurrentItem = true if @fire("selectData", @, { data: item }) isnt false @_currentItem = item if @_assignment and @_bindInfo?.writeable if @_valueProperty or @_textProperty prop = @_valueProperty or @_textProperty if item if item instanceof cola.Entity value = item.get(prop) else value = item[prop] else value = null arg = { oldValue: @_value, value: value } if @fire("beforeChange", @, arg) is false @refreshValue() return if @fire("beforePost", @, arg) is false @refreshValue() return bindEntity = @_scope.get(@_bindInfo.entityPath) @_assignment.split(/[,;]/).forEach((part)=> pair = part.split("=") targetProp = pair[0] if targetProp sourceProp = pair[1] or targetProp if item if item instanceof cola.Entity value = item.get(sourceProp) else value = item[sourceProp] else value = null bindEntity.set(targetProp, value) return ) @fire("change", @, arg) @fire("post", @) else value = @_getItemValue(item) @set("value", value) @_skipFindCurrentItem = false @refresh() return cola.Element.mixin(cola.AbstractDropdown, cola.TemplateSupport) class cola.DropBox extends cola.Layer @tagName: "c-drop-box" @className: "drop-box transition" @attributes: height: setter: (height)-> @_maxHeight = height return dropdown: null focusable: defaultValue: true resize: (opened)-> dom = @getDom() $dom = @get$Dom() dropdownDom = @_dropdown._doms.input if not cola.util.isVisible(dropdownDom) @hide() return # 防止因改变高度导致滚动条自动还原到初始位置 if opened boxWidth = dom.offsetWidth boxHeight = dom.offsetHeight else if @_maxHeight $dom.css("max-height", @_maxHeight) $dom.css("height", "") $dom.removeClass("hidden") boxWidth = $dom.width() boxHeight = $dom.height() $dom.addClass("hidden") rect = $fly(dropdownDom).offset() clientWidth = document.documentElement.clientWidth - 6 clientHeight = document.documentElement.clientHeight - 6 bottomSpace = Math.abs(document.documentElement.scrollTop + clientHeight - rect.top - dropdownDom.clientHeight) if bottomSpace >= boxHeight direction = "down" else topSpace = rect.top - document.documentElement.scrollTop - 6 if topSpace > bottomSpace direction = "up" if boxHeight > topSpace then height = topSpace else direction = "down" if boxHeight > bottomSpace then height = bottomSpace if opened if height $dom.css("height", height) else if dom.firstElementChild is dom.lastElementChild if dom.firstElementChild.offsetHeight < dom.clientHeight $dom.css("height", "auto") if direction is "down" top = rect.top + dropdownDom.clientHeight else top = rect.top - dom.offsetHeight + 2 left = rect.left if boxWidth > dropdownDom.offsetWidth if boxWidth + rect.left > clientWidth left = clientWidth - boxWidth if left < 0 then left = 0 if opened $dom.removeClass(if direction is "down" then "direction-up" else "direction-down") .addClass("direction-" + direction) .toggleClass("x-over", boxWidth > dropdownDom.offsetWidth) .css("left", left).css("top", top) $dom.css("min-width", dropdownDom.offsetWidth || 80) .css("max-width", document.documentElement.clientWidth) return show: (options, callback)-> @resize() @_animation = "fade" super(options, callback) @resize(true) @_resizeTimer = setInterval(()=> @resize(true) return , 300) return hide: (options, callback)-> if @_resizeTimer clearInterval(@_resizeTimer) delete @_resizeTimer super(options, callback) return class cola.Dropdown extends cola.AbstractDropdown @tagName: "c-dropdown" @attributes: filterable: readOnlyAfterCreate: true defaultValue: true filterValue: readOnly: true filterProperty: null filterInterval: defaultValue: 300 @events: filterItem: null @templates: "default": tagName: "li" "c-bind": "$default" "list": tagName: "div" contextKey: "<KEY>" content: tagName: "c-listview" contextKey: "list" allowNoCurrent: true changeCurrentItem: true highlightCurrentItem: true transition: true style: "overflow:auto" keydown: (evt)-> if not @_disableKeyBubble @_disableKeyBubble = true $fly(@).find(">c-listview").trigger(evt) @_disableKeyBubble = false return true "filterable-list": tagName: "div" class: "v-box" content: [ { tagName: "div" class: "box filter-container" content: tagName: "c-input" contextKey: "input" class: "fluid" icon: "search" } { tagName: "div" contextKey: "<KEY>" class: "flex-box list-container" style: "min-height:2em" content: tagName: "c-listview" contextKey: "list" allowNoCurrent: true changeCurrentItem: true highlightCurrentItem: true transition: true } ] keydown: (evt)-> if not @_disableKeyBubble @_disableKeyBubble = true $fly(@).find(">.flex-box >c-listview").trigger(evt) @_disableKeyBubble = false return true _initDom: (dom)-> @_regDefaultTemplates() inputDom = @_doms.input $fly(inputDom).on("input", ()=> @_inputDirty = true @_onInput(inputDom.value) return ) super(dom) if @_filterable and @_useValueContent $fly(dom).addClass("filterable").xAppend( contextKey: "filterInput" tagName: "input" text: "input" type: "text", class: "filter-input" focus: ()=> cola._setFocusWidget(@) input: (evt)=> if @_useValueContent $valueContent = $fly(@_doms.valueContent) if evt.target.value $valueContent.hide() else $valueContent.show() @_onInput(@_doms.filterInput.value) return , @_doms) return _refreshInputValue: (value)-> super(if @_useValueContent then null else value) return open: ()-> if super() list = @_list if list and @_currentItem isnt list.get("currentItem") list.set("currentItem", @_currentItem) if @_opened and @_filterable if @_list.get("filterCriteria") isnt null @_list.set("filterCriteria", null).refresh() return true return _onInput: (value)-> cola.util.delay(@, "filterItems", 150, ()-> return unless @_list criteria = value if @_opened and @_filterable filterProperty = @_filterProperty or @_textProperty if not value if filterProperty criteria = {} criteria[filterProperty] = value @_list.set("filterCriteria", criteria).refresh() items = @_list.getItems() currentItemDom = null if @_filterable if value isnt null exactlyMatch firstItem = items?[0] if firstItem if filterProperty exactlyMatch = cola.Entity._evalDataPath(firstItem, filterProperty) is value else exactlyMatch = firstItem is value if exactlyMatch currentItemDom = @_list._getFirstItemDom() @_list._setCurrentItemDom(currentItemDom) else item = items and cola.util.find(items, criteria) if item entityId = cola.Entity._getEntityId(item) if entityId @_list.set("currentItem", item) else @_list._setCurrentItemDom(currentItemDom) else @_list._setCurrentItemDom(null) return ) return _getSelectData: ()-> return @_list?.get("currentItem") or null _onKeyDown: (evt)-> if evt.keyCode is 13 # Enter @close(@_getSelectData()) return false else if evt.keyCode is 27 # ESC @close(@_currentItem or null) else if evt.keyCode is 38 or evt.keyCode is 40 # UP, DOWN @_list?._onKeyDown(evt) return _selectData: (item)-> @_inputDirty = false @_doms.filterInput?.value = "" return super(item) _onBlur: ()-> if @_inputDirty @close(@_getSelectData()) @_doms.filterInput?.value = "" return super() _getDropdownContent: ()-> if not @_dropdownContent if @_filterable and @_finalOpenMode isnt "drop" templateName = "filterable-list" else templateName = "list" template = @getTemplate(templateName) @_dropdownContent = template = cola.xRender(template, @_scope) @_list = list = cola.widget(@_doms.list) if @_templates templ = @_templates["item-content"] or @_templates["value-content"] if templ list.regTemplate("default", templ) hasDefaultTemplate = true if not hasDefaultTemplate list.regTemplate("default", { tagName: "li" "c-bind": "$default" }) list.on("itemClick", (self, arg)=> @close(self.getItemByItemDom(arg.dom)) return ).on("click", ()-> false) @_refreshDropdownContent() return template _refreshDropdownContent: ()-> attrBinding = @_elementAttrBindings?["items"] list = @_list list._textProperty = @_textProperty or @_valueProperty if attrBinding && list.get("model").get(attrBinding.expression.raw) # if not @_dontRefreshItems # @_refreshAttrValue("items") list.set("bind", attrBinding.expression.raw) else list.set("items", @_items) list.refresh() cola.registerWidget(cola.Dropdown) class cola.CustomDropdown extends cola.AbstractDropdown @tagName: "c-custom-dropdown" @attributes: content: null @templates: "default": tagName: "div" content: "<Undefined>" _isEditorReadOnly: ()-> return true _getDropdownContent: ()-> if not @_dropdownContent if @_content dropdownContent = @_content else dropdownContent = @getTemplate() @_dropdownContent = cola.xRender(dropdownContent, @_scope) return @_dropdownContent cola.registerWidget(cola.CustomDropdown) class cola.ComboBox extends cola.Dropdown @tagName: "c-combo-box" @attributes: postOnInput: type: "boolean" @events: keyPress: null input:null constructor: (config)-> @_acceptUnknownValue = true super(config) _initDom: (dom)-> super(dom) input = @_doms.input $(input).on("input", ()=> arg = { inputValue: input.value, value: this.get("value") } @fire("input", @, arg) if @_postOnInput then @set("value", input.value) return ).on("keypress", (event)=> arg = keyCode: event.keyCode shiftKey: event.shiftKey ctrlKey: event.ctrlKey altKey: event.altKey event: event if @fire("keyPress", @, arg) == false then return false if event.keyCode is 13 and isIE11 then @_postInput() ) return fire: (eventName, self, arg)-> if eventName is "keyDown" or eventName is "keyPress" arg.inputValue = @_doms.input.value return super(eventName, self, arg) _setValueContent: ()-> ctx = {} value = @readBindingValue(ctx) input = @_doms.input input.value = value or "" if value input.placeholder = "" @get$Dom().removeClass("placeholder") else input.placeholder = @_placeholder or "" @get$Dom().addClass("placeholder") return _getSelectData: ()-> items = @_list?.get("items") if items if items instanceof Array if items.length is 1 then item = items[0] else if items instanceof cola.EntityList if items.entityCount is 1 then item = items.current value = @_doms.input.value matchProperty = @_filterProperty or @_textProperty or @_valueProperty if matchProperty if item instanceof cola.Entity if item.get(matchProperty) is value return item else if typeof item is "object" if item[matchProperty] is value return item if value if @_valueProperty or @_textProperty item = { $emptyItem: true } item[@_valueProperty] = value item[@_textProperty] = value return item return undefined cola.registerWidget(cola.ComboBox)
true
dropdownDialogMargin = 0 cola.findDropDown = (target)-> layer = cola.findWidget(target, cola.AbstractLayer, true) while layer and not layer._dropdown layer = cola.findWidget(layer, cola.AbstractLayer, true) return layer?._dropdown class cola.AbstractDropdown extends cola.AbstractInput @className: "input drop" @attributes: items: refreshDom: true expressionType: "repeat" # expressionNegative: true setter: (items)-> if typeof items is "string" items = items.split(/[,;]/) for item, i in items pos = item.indexOf("=") if pos >= 0 items[i] = key: item.substring(0, pos) value: item.substring(pos + 1) if not @_valueProperty and not @_textProperty @_valueProperty = "key" @_textProperty = "value" if not @_acceptUnknownValue and not @_valueProperty and not @_textProperty result = cola.util.decideValueProperty(items) if result @_valueProperty = result.valueProperty @_textProperty = result.textProperty changed = @_items isnt items or @_itemsTimestamp isnt items?.timestamp @_items = items if changed if items?.timestamp @_itemsTimestamp = items.timestamp delete @_itemsIndex if @_value isnt undefined and items @_setValue(@_value) return currentItem: readOnly: true valueProperty: null textProperty: null assignment: null editable: type: "boolean" defaultValue: true showClearButton: type: "boolean" defaultValue: true openOnActive: type: "boolean" defaultValue: true openMode: enum: [ "auto", "drop", "dialog", "layer", "sidebar" ] defaultValue: "auto" opened: readOnly: true dropdownLayer: null dropdownWidth: null dropdownHeight: null dropdownTitle: null @events: initDropdownBox: null beforeOpen: null open: null close: null selectData: null focus: null blur: null keyDown: null keyPress: null input: null _initDom: (dom)-> super(dom) if @getTemplate("value-content") @_useValueContent = true if @_useValueContent @_doms.input.value = "" $fly(@_doms.input).xInsertAfter({ tagName: "div" class: "value-content" contextKey: "valueContent" }, @_doms) $fly(dom).delegate(">.icon.drop", "click", ()=> if @_opened if new Date() - @_openTimestamp > 300 @close() else if not @_finalReadOnly @open() return false ).on("keypress", (evt)=> arg = keyCode: evt.keyCode shiftKey: evt.shiftKey ctrlKey: evt.ctrlKey altKey: evt.altKey event: evt inputValue: @_doms.input.value if @fire("keyPress", @, arg) is false return false ).on("mouseenter", (evt)=> if @_showClearButton clearButton = @_doms.clearButton if not clearButton @_doms.clearButton = clearButton = $.xCreate({ tagName: "i" class: "icon remove" mousedown: ()=> @_selectData(null) return false }) dom.appendChild(clearButton) $fly(clearButton).toggleClass("disabled", !@_doms.input.value) ) $(@_doms.input).on("input", (evt)=> value = @_doms.input.value arg = event: evt inputValue: value @fire("input", @, arg) ).on("keypress", ()=> @_inputEdited = true) unless @_skipSetIcon unless @_icon then @set("icon", "dropdown") if @_setValueOnInitDom and @_value isnt undefined delete @_setValueOnInitDom @_setValue(@_value) return _onFocus: ()-> @_inputEdited = false super() if @_openOnActive and not @_opened and not @_finalReadOnly @open() if @_useValueContent @_showValueTipIfNecessary() return _onBlur: ()-> if @_opened and @_finalOpenMode is "drop" @close() super() @_doms.tipDom and cola.util.cacheDom(@_doms.tipDom) return _onKeyDown: (evt)-> if evt.keyCode is 27 # ESC @close() return _showValueTipIfNecessary: ()-> if @_useValueContent and @_doms.valueContent valueContent = @_doms.valueContent if valueContent.scrollWidth > valueContent.clientWidth tipDom = @_doms.tipDom if not tipDom @_doms.tipDom = tipDom = cola.xCreate({ class: "dropdown-value-tip" }) if tipDom isnt document.body document.body.appendChild(tipDom) tipDom.innerHTML = @_doms.valueContent.innerHTML rect = $fly(@_dom).offset() $fly(tipDom).css( left: rect.left + @_dom.offsetWidth / 2 top: rect.top minWidth: @_dom.offsetWidth ) return _parseDom: (dom)-> return unless dom super(dom) @_parseTemplates() if not @_icon child = @_doms.input.nextSibling while child if child.nodeType is 1 and child.nodeName isnt "TEMPLATE" @_skipSetIcon = true break child = child.nextSibling return _createEditorDom: ()-> return $.xCreate( tagName: "input" type: "text" click: ()=> this.focus() ) _isEditorDom: (node)-> return node.nodeName is "INPUT" _isEditorReadOnly: ()-> return not @_editable or (@_filterable and @_useValueContent) _refreshIcon: ()-> super() if @_doms.iconDom $fly(@_doms.iconDom).addClass("drop") return _refreshInput: ()-> $inputDom = $fly(@_doms.input) $inputDom.attr("name", @_name) if @_name $inputDom.attr("placeholder", @get("placeholder")) $inputDom.attr("readOnly", @_finalReadOnly or @_isEditorReadOnly() or null) @get("actionButton")?.set("disabled", @_finalReadOnly) @_setValueContent() return _setValue: (value)-> if value isnt undefined if not @_dom @_setValueOnInitDom = true else if not @_skipFindCurrentItem and @_valueProperty if not @_items attrBinding = @_elementAttrBindings?["items"] if attrBinding and @_valueProperty @_refreshAttrValue("items") if @_items if not @_itemsIndex if @_items instanceof cola.EntityList @_itemsIndex = cola.util.buildIndex(@_items, @_valueProperty) else @_itemsIndex = index = {} valueProperty = @_valueProperty cola.each @_items, (item)-> if item instanceof cola.Entity key = item.get(valueProperty) else key = item[valueProperty] index[key + ""] = item return if @_itemsIndex if @_itemsIndex instanceof cola.EntityIndex currentItem = @_itemsIndex.find(value) else currentItem = @_itemsIndex[value + ""] @_currentItem = currentItem else item = @_currentItem = { $emptyItem: true } item[@_valueProperty] = value item[@_textProperty] = value else @_currentItem = { $emptyItem: true } return super(value) _setValueContent: ()-> item = @_currentItem if not item? if not @_textProperty item = @_value else item = { $emptyItem: true } item[@_textProperty] = @_value input = @_doms.input if item if @_useValueContent elementAttrBinding = @_elementAttrBindings?["items"] alias = elementAttrBinding?.expression.alias or "item" currentItemScope = @_currentItemScope if currentItemScope and currentItemScope.data.alias isnt alias currentItemScope = null if not currentItemScope @_currentItemScope = currentItemScope = new cola.ItemScope(@_scope, alias) currentItemScope.data.setItemData(item) valueContent = @_doms.valueContent if not valueContent._inited valueContent._inited = true ctx = defaultPath: alias @_initValueContent(valueContent, ctx) cola.xRender(valueContent, currentItemScope, ctx) $fly(valueContent).show() else property = @_textProperty or @_valueProperty if property if item instanceof cola.Entity text = cola.Entity._evalDataPath(item, property or "value") else if typeof item is "object" and not (item instanceof Date) if item.hasOwnProperty(property) text = item[property] else text = cola.Entity._evalDataPath(item, property or "value") else text = item input.value = text or "" else text = @readBindingValue() input.value = text or "" else if not @_useValueContent text = @readBindingValue() input.value = text or "" if @_useValueContent $fly(@_doms.valueContent).hide() if item and not item.$emptyItem input.placeholder = "" @get$Dom().removeClass("placeholder") else input.placeholder = @_placeholder or "" @get$Dom().addClass("placeholder") if @_focused and @_useValueContent @_showValueTipIfNecessary() return _initValueContent: (valueContent, context)-> property = @_textProperty or @_valueProperty or "value" if property context.defaultPath += "." + property template = @getTemplate("value-content") if template valueContent.appendChild(template) return _getFinalOpenMode: ()-> openMode = @_openMode if !openMode or openMode is "auto" if cola.device.desktop openMode = "drop" else if cola.device.phone openMode = "layer" else # pad openMode = "dialog" return openMode _getTitleContent: ()-> return cola.xRender({ tagName: "div" class: "box" content: tagName: "c-titlebar" content: [ { tagName: "a" icon: "chevron left" click: ()=> @close() } ] }, @_scope, {}) _getContainer: (dontCreate)-> if @_container @_dontRefreshItems = true @_refreshDropdownContent?() delete @_dontRefreshItems return @_container else if not dontCreate @_finalOpenMode = openMode = @_getFinalOpenMode() config = class: "drop-container" dom: $.xCreate( content: @_getDropdownContent() ) beforeHide: ()=> $fly(@_dom).removeClass("opened") return hide: ()=> @_opened = false return @_dropdownContent = config.dom.firstChild config.width = @_dropdownWidth if @_dropdownWidth config.height = @_dropdownHeight if @_dropdownHeight if openMode is "drop" config.duration = 200 config.dropdown = @ config.class = @_class container = new cola.DropBox(config) else if openMode is "layer" if openMode is "sidebar" config.animation = "slide up" config.height = "50%" titleContent = @_getTitleContent() $fly(config.dom.firstChild.firstChild).before(titleContent) container = new cola.Layer(config) else if openMode is "sidebar" config.direction = "bottom" config.size = document.documentElement.clientHeight / 2 $fly(config.dom.firstChild.firstChild).before(titleContent) container = new cola.Sidebar(config) else if openMode is "dialog" config.modalOpacity = 0.05 config.closeable = false config.dimmerClose = true if not config.width then config.width = "80%" if not config.height then config.height = "80%" if @_dropdownTitle config.dom = $.xCreate( content: [ { class: "header" content: @_dropdownTitle } { class: "content" content: config.dom } ] ) container = new cola.Dialog(config) @_container = container container.appendTo(document.body) return container return open: (callback)-> if @_finalReadOnly then return if @fire("beforeOpen", @) is false then return doCallback = ()=> @fire("open", @) cola.callback(callback, true) return container = @_getContainer() if container container._dropdown = @ container._focusParent = @ container.on("hide", (self)-> delete self._dropdown return ) if container instanceof cola.Dialog $flexContent = $(@_doms.flexContent) $flexContent.height("") $containerDom = container.get$Dom() $containerDom.removeClass("hidden") containerHeight = $containerDom.height() clientHeight = document.documentElement.clientHeight if containerHeight > (clientHeight - dropdownDialogMargin * 2) height = $flexContent.height() - (containerHeight - (clientHeight - dropdownDialogMargin * 2)) $containerDom.addClass("hidden") $flexContent.height(height) else $containerDom.addClass("hidden") @fire("initDropdownBox", @, { dropdownBox: container }) if container.constructor.events.$has("hide") container.on("hide:dropdown", ()=> @fire("close", @) return , true) container.show?(doCallback) @_opened = true @_openTimestamp = new Date() $fly(@_dom).addClass("opened") if @_filterable and @_useValueContent @_refreshInputValue(null) return true return close: (selectedData, callback)-> if selectedData isnt undefined @_selectData(selectedData) else if @_inputEdited if @_acceptUnknownValue @set("value", @_doms.input.value) @post() else @refresh() container = @_getContainer(true) container?.hide?(callback) return _getItemValue: (item)-> if @_valueProperty and item if item instanceof cola.Entity value = item.get(@_valueProperty) else value = item[@_valueProperty] else value = item return value _selectData: (item)-> @_inputEdited = false @_skipFindCurrentItem = true if @fire("selectData", @, { data: item }) isnt false @_currentItem = item if @_assignment and @_bindInfo?.writeable if @_valueProperty or @_textProperty prop = @_valueProperty or @_textProperty if item if item instanceof cola.Entity value = item.get(prop) else value = item[prop] else value = null arg = { oldValue: @_value, value: value } if @fire("beforeChange", @, arg) is false @refreshValue() return if @fire("beforePost", @, arg) is false @refreshValue() return bindEntity = @_scope.get(@_bindInfo.entityPath) @_assignment.split(/[,;]/).forEach((part)=> pair = part.split("=") targetProp = pair[0] if targetProp sourceProp = pair[1] or targetProp if item if item instanceof cola.Entity value = item.get(sourceProp) else value = item[sourceProp] else value = null bindEntity.set(targetProp, value) return ) @fire("change", @, arg) @fire("post", @) else value = @_getItemValue(item) @set("value", value) @_skipFindCurrentItem = false @refresh() return cola.Element.mixin(cola.AbstractDropdown, cola.TemplateSupport) class cola.DropBox extends cola.Layer @tagName: "c-drop-box" @className: "drop-box transition" @attributes: height: setter: (height)-> @_maxHeight = height return dropdown: null focusable: defaultValue: true resize: (opened)-> dom = @getDom() $dom = @get$Dom() dropdownDom = @_dropdown._doms.input if not cola.util.isVisible(dropdownDom) @hide() return # 防止因改变高度导致滚动条自动还原到初始位置 if opened boxWidth = dom.offsetWidth boxHeight = dom.offsetHeight else if @_maxHeight $dom.css("max-height", @_maxHeight) $dom.css("height", "") $dom.removeClass("hidden") boxWidth = $dom.width() boxHeight = $dom.height() $dom.addClass("hidden") rect = $fly(dropdownDom).offset() clientWidth = document.documentElement.clientWidth - 6 clientHeight = document.documentElement.clientHeight - 6 bottomSpace = Math.abs(document.documentElement.scrollTop + clientHeight - rect.top - dropdownDom.clientHeight) if bottomSpace >= boxHeight direction = "down" else topSpace = rect.top - document.documentElement.scrollTop - 6 if topSpace > bottomSpace direction = "up" if boxHeight > topSpace then height = topSpace else direction = "down" if boxHeight > bottomSpace then height = bottomSpace if opened if height $dom.css("height", height) else if dom.firstElementChild is dom.lastElementChild if dom.firstElementChild.offsetHeight < dom.clientHeight $dom.css("height", "auto") if direction is "down" top = rect.top + dropdownDom.clientHeight else top = rect.top - dom.offsetHeight + 2 left = rect.left if boxWidth > dropdownDom.offsetWidth if boxWidth + rect.left > clientWidth left = clientWidth - boxWidth if left < 0 then left = 0 if opened $dom.removeClass(if direction is "down" then "direction-up" else "direction-down") .addClass("direction-" + direction) .toggleClass("x-over", boxWidth > dropdownDom.offsetWidth) .css("left", left).css("top", top) $dom.css("min-width", dropdownDom.offsetWidth || 80) .css("max-width", document.documentElement.clientWidth) return show: (options, callback)-> @resize() @_animation = "fade" super(options, callback) @resize(true) @_resizeTimer = setInterval(()=> @resize(true) return , 300) return hide: (options, callback)-> if @_resizeTimer clearInterval(@_resizeTimer) delete @_resizeTimer super(options, callback) return class cola.Dropdown extends cola.AbstractDropdown @tagName: "c-dropdown" @attributes: filterable: readOnlyAfterCreate: true defaultValue: true filterValue: readOnly: true filterProperty: null filterInterval: defaultValue: 300 @events: filterItem: null @templates: "default": tagName: "li" "c-bind": "$default" "list": tagName: "div" contextKey: "PI:KEY:<KEY>END_PI" content: tagName: "c-listview" contextKey: "list" allowNoCurrent: true changeCurrentItem: true highlightCurrentItem: true transition: true style: "overflow:auto" keydown: (evt)-> if not @_disableKeyBubble @_disableKeyBubble = true $fly(@).find(">c-listview").trigger(evt) @_disableKeyBubble = false return true "filterable-list": tagName: "div" class: "v-box" content: [ { tagName: "div" class: "box filter-container" content: tagName: "c-input" contextKey: "input" class: "fluid" icon: "search" } { tagName: "div" contextKey: "PI:KEY:<KEY>END_PI" class: "flex-box list-container" style: "min-height:2em" content: tagName: "c-listview" contextKey: "list" allowNoCurrent: true changeCurrentItem: true highlightCurrentItem: true transition: true } ] keydown: (evt)-> if not @_disableKeyBubble @_disableKeyBubble = true $fly(@).find(">.flex-box >c-listview").trigger(evt) @_disableKeyBubble = false return true _initDom: (dom)-> @_regDefaultTemplates() inputDom = @_doms.input $fly(inputDom).on("input", ()=> @_inputDirty = true @_onInput(inputDom.value) return ) super(dom) if @_filterable and @_useValueContent $fly(dom).addClass("filterable").xAppend( contextKey: "filterInput" tagName: "input" text: "input" type: "text", class: "filter-input" focus: ()=> cola._setFocusWidget(@) input: (evt)=> if @_useValueContent $valueContent = $fly(@_doms.valueContent) if evt.target.value $valueContent.hide() else $valueContent.show() @_onInput(@_doms.filterInput.value) return , @_doms) return _refreshInputValue: (value)-> super(if @_useValueContent then null else value) return open: ()-> if super() list = @_list if list and @_currentItem isnt list.get("currentItem") list.set("currentItem", @_currentItem) if @_opened and @_filterable if @_list.get("filterCriteria") isnt null @_list.set("filterCriteria", null).refresh() return true return _onInput: (value)-> cola.util.delay(@, "filterItems", 150, ()-> return unless @_list criteria = value if @_opened and @_filterable filterProperty = @_filterProperty or @_textProperty if not value if filterProperty criteria = {} criteria[filterProperty] = value @_list.set("filterCriteria", criteria).refresh() items = @_list.getItems() currentItemDom = null if @_filterable if value isnt null exactlyMatch firstItem = items?[0] if firstItem if filterProperty exactlyMatch = cola.Entity._evalDataPath(firstItem, filterProperty) is value else exactlyMatch = firstItem is value if exactlyMatch currentItemDom = @_list._getFirstItemDom() @_list._setCurrentItemDom(currentItemDom) else item = items and cola.util.find(items, criteria) if item entityId = cola.Entity._getEntityId(item) if entityId @_list.set("currentItem", item) else @_list._setCurrentItemDom(currentItemDom) else @_list._setCurrentItemDom(null) return ) return _getSelectData: ()-> return @_list?.get("currentItem") or null _onKeyDown: (evt)-> if evt.keyCode is 13 # Enter @close(@_getSelectData()) return false else if evt.keyCode is 27 # ESC @close(@_currentItem or null) else if evt.keyCode is 38 or evt.keyCode is 40 # UP, DOWN @_list?._onKeyDown(evt) return _selectData: (item)-> @_inputDirty = false @_doms.filterInput?.value = "" return super(item) _onBlur: ()-> if @_inputDirty @close(@_getSelectData()) @_doms.filterInput?.value = "" return super() _getDropdownContent: ()-> if not @_dropdownContent if @_filterable and @_finalOpenMode isnt "drop" templateName = "filterable-list" else templateName = "list" template = @getTemplate(templateName) @_dropdownContent = template = cola.xRender(template, @_scope) @_list = list = cola.widget(@_doms.list) if @_templates templ = @_templates["item-content"] or @_templates["value-content"] if templ list.regTemplate("default", templ) hasDefaultTemplate = true if not hasDefaultTemplate list.regTemplate("default", { tagName: "li" "c-bind": "$default" }) list.on("itemClick", (self, arg)=> @close(self.getItemByItemDom(arg.dom)) return ).on("click", ()-> false) @_refreshDropdownContent() return template _refreshDropdownContent: ()-> attrBinding = @_elementAttrBindings?["items"] list = @_list list._textProperty = @_textProperty or @_valueProperty if attrBinding && list.get("model").get(attrBinding.expression.raw) # if not @_dontRefreshItems # @_refreshAttrValue("items") list.set("bind", attrBinding.expression.raw) else list.set("items", @_items) list.refresh() cola.registerWidget(cola.Dropdown) class cola.CustomDropdown extends cola.AbstractDropdown @tagName: "c-custom-dropdown" @attributes: content: null @templates: "default": tagName: "div" content: "<Undefined>" _isEditorReadOnly: ()-> return true _getDropdownContent: ()-> if not @_dropdownContent if @_content dropdownContent = @_content else dropdownContent = @getTemplate() @_dropdownContent = cola.xRender(dropdownContent, @_scope) return @_dropdownContent cola.registerWidget(cola.CustomDropdown) class cola.ComboBox extends cola.Dropdown @tagName: "c-combo-box" @attributes: postOnInput: type: "boolean" @events: keyPress: null input:null constructor: (config)-> @_acceptUnknownValue = true super(config) _initDom: (dom)-> super(dom) input = @_doms.input $(input).on("input", ()=> arg = { inputValue: input.value, value: this.get("value") } @fire("input", @, arg) if @_postOnInput then @set("value", input.value) return ).on("keypress", (event)=> arg = keyCode: event.keyCode shiftKey: event.shiftKey ctrlKey: event.ctrlKey altKey: event.altKey event: event if @fire("keyPress", @, arg) == false then return false if event.keyCode is 13 and isIE11 then @_postInput() ) return fire: (eventName, self, arg)-> if eventName is "keyDown" or eventName is "keyPress" arg.inputValue = @_doms.input.value return super(eventName, self, arg) _setValueContent: ()-> ctx = {} value = @readBindingValue(ctx) input = @_doms.input input.value = value or "" if value input.placeholder = "" @get$Dom().removeClass("placeholder") else input.placeholder = @_placeholder or "" @get$Dom().addClass("placeholder") return _getSelectData: ()-> items = @_list?.get("items") if items if items instanceof Array if items.length is 1 then item = items[0] else if items instanceof cola.EntityList if items.entityCount is 1 then item = items.current value = @_doms.input.value matchProperty = @_filterProperty or @_textProperty or @_valueProperty if matchProperty if item instanceof cola.Entity if item.get(matchProperty) is value return item else if typeof item is "object" if item[matchProperty] is value return item if value if @_valueProperty or @_textProperty item = { $emptyItem: true } item[@_valueProperty] = value item[@_textProperty] = value return item return undefined cola.registerWidget(cola.ComboBox)
[ { "context": "Turn arrays into smooth functions.\n\nCopyright 2012 Spencer Cohen\nLicensed under MIT license (see \"Smooth.js MIT li", "end": 93, "score": 0.9998472332954407, "start": 80, "tag": "NAME", "value": "Spencer Cohen" } ]
Smooth.coffee
xunleif2e/Smooth.js
243
### Smooth.js version 0.1.7 Turn arrays into smooth functions. Copyright 2012 Spencer Cohen Licensed under MIT license (see "Smooth.js MIT license.txt") ### ###Constants (these are accessible by Smooth.WHATEVER in user space)### Enum = ###Interpolation methods### METHOD_NEAREST: 'nearest' #Rounds to nearest whole index METHOD_LINEAR: 'linear' METHOD_CUBIC: 'cubic' # Default: cubic interpolation METHOD_LANCZOS: 'lanczos' METHOD_SINC: 'sinc' ###Input clipping modes### CLIP_CLAMP: 'clamp' # Default: clamp to [0, arr.length-1] CLIP_ZERO: 'zero' # When out of bounds, clip to zero CLIP_PERIODIC: 'periodic' # Repeat the array infinitely in either direction CLIP_MIRROR: 'mirror' # Repeat infinitely in either direction, flipping each time ### Constants for control over the cubic interpolation tension ### CUBIC_TENSION_DEFAULT: 0 # Default tension value CUBIC_TENSION_CATMULL_ROM: 0 defaultConfig = method: Enum.METHOD_CUBIC #The interpolation method cubicTension: Enum.CUBIC_TENSION_DEFAULT #The cubic tension parameter clip: Enum.CLIP_CLAMP #The clipping mode scaleTo: 0 #The scale-to value (0 means don't scale) (can also be a range) sincFilterSize: 2 #The size of the sinc filter kernel (must be an integer) sincWindow: undefined #The window function for the sinc filter ###Index clipping functions### clipClamp = (i, n) -> Math.max 0, Math.min i, n - 1 clipPeriodic = (i, n) -> i = i % n #wrap i += n if i < 0 #if negative, wrap back around i clipMirror = (i, n) -> period = 2*(n - 1) #period of index mirroring function i = clipPeriodic i, period i = period - i if i > n - 1 #flip when out of bounds i ### Abstract scalar interpolation class which provides common functionality for all interpolators Subclasses must override interpolate(). ### class AbstractInterpolator constructor: (array, config) -> @array = array.slice 0 #copy the array @length = @array.length #cache length #Set the clipping helper method throw "Invalid clip: #{config.clip}" unless @clipHelper = { clamp: @clipHelperClamp zero: @clipHelperZero periodic: @clipHelperPeriodic mirror: @clipHelperMirror }[config.clip] # Get input array value at i, applying the clipping method getClippedInput: (i) -> #Normal behavior for indexes within bounds if 0 <= i < @length @array[i] else @clipHelper i clipHelperClamp: (i) -> @array[clipClamp i, @length] clipHelperZero: (i) -> 0 clipHelperPeriodic: (i) -> @array[clipPeriodic i, @length] clipHelperMirror: (i) -> @array[clipMirror i, @length] interpolate: (t) -> throw 'Subclasses of AbstractInterpolator must override the interpolate() method.' #Nearest neighbor interpolator (round to whole index) class NearestInterpolator extends AbstractInterpolator interpolate: (t) -> @getClippedInput Math.round t #Linear interpolator (first order Bezier) class LinearInterpolator extends AbstractInterpolator interpolate: (t) -> k = Math.floor t #Translate t to interpolate between k and k+1 t -= k return (1-t)*@getClippedInput(k) + (t)*@getClippedInput(k+1) class CubicInterpolator extends AbstractInterpolator constructor: (array, config)-> #clamp cubic tension to [0,1] range @tangentFactor = 1 - Math.max 0, Math.min 1, config.cubicTension super # Cardinal spline with tension 0.5) getTangent: (k) -> @tangentFactor*(@getClippedInput(k + 1) - @getClippedInput(k - 1))/2 interpolate: (t) -> k = Math.floor t m = [(@getTangent k), (@getTangent k+1)] #get tangents p = [(@getClippedInput k), (@getClippedInput k+1)] #get points #Translate t to interpolate between k and k+1 t -= k t2 = t*t #t^2 t3 = t*t2 #t^3 #Apply cubic hermite spline formula return (2*t3 - 3*t2 + 1)*p[0] + (t3 - 2*t2 + t)*m[0] + (-2*t3 + 3*t2)*p[1] + (t3 - t2)*m[1] {sin, PI} = Math #Normalized sinc function sinc = (x) -> if x is 0 then 1 else sin(PI*x)/(PI*x) #Make a lanczos window function for a given filter size 'a' makeLanczosWindow = (a) -> (x) -> sinc(x/a) #Make a sinc kernel function by multiplying the sinc function by a window function makeSincKernel = (window) -> (x) -> sinc(x)*window(x) class SincFilterInterpolator extends AbstractInterpolator constructor: (array, config) -> super #Create the lanczos kernel function @a = config.sincFilterSize #Cannot make sinc filter without a window function throw 'No sincWindow provided' unless config.sincWindow #Window the sinc function to make the kernel @kernel = makeSincKernel config.sincWindow interpolate: (t) -> k = Math.floor t #Convolve with Lanczos kernel sum = 0 sum += @kernel(t - n)*@getClippedInput(n) for n in [(k - @a + 1)..(k + @a)] sum #Extract a column from a two dimensional array getColumn = (arr, i) -> (row[i] for row in arr) #Take a function with one parameter and apply a scale factor to its parameter makeScaledFunction = (f, baseScale, scaleRange) -> if scaleRange.join is '0,1' f #don't wrap the function unecessarily else scaleFactor = baseScale/(scaleRange[1] - scaleRange[0]) translation = scaleRange[0] (t) -> f scaleFactor*(t - translation) getType = (x) -> Object::toString.call(x)[('[object '.length)...-1] #Throw exception if input is not a number validateNumber = (n) -> throw 'NaN in Smooth() input' if isNaN n throw 'Non-number in Smooth() input' unless getType(n) is 'Number' throw 'Infinity in Smooth() input' unless isFinite n #Throw an exception if input is not a vector of numbers which is the correct length validateVector = (v, dimension) -> throw 'Non-vector in Smooth() input' unless getType(v) is 'Array' throw 'Inconsistent dimension in Smooth() input' unless v.length is dimension validateNumber n for n in v return isValidNumber = (n) -> (getType(n) is 'Number') and isFinite(n) and not isNaN(n) normalizeScaleTo = (s) -> invalidErr = "scaleTo param must be number or array of two numbers" switch getType s when 'Number' throw invalidErr unless isValidNumber s s = [0, s] when 'Array' throw invalidErr unless s.length is 2 throw invalidErr unless isValidNumber(s[0]) and isValidNumber(s[1]) else throw invalidErr return s shallowCopy = (obj) -> copy = {} copy[k] = v for own k,v of obj copy Smooth = (arr, config = {}) -> #Properties to copy to the function once it is created properties = {} #Make a copy of the config object to modify config = shallowCopy config #Make another copy of the config object to save to the function properties.config = shallowCopy config #Alias 'period' to 'scaleTo' config.scaleTo ?= config.period #Alias lanczosFilterSize to sincFilterSize config.sincFilterSize ?= config.lanczosFilterSize config[k] ?= v for own k,v of defaultConfig #fill in defaults #Get the interpolator class according to the configuration throw "Invalid method: #{config.method}" unless interpolatorClass = { nearest: NearestInterpolator linear: LinearInterpolator cubic: CubicInterpolator lanczos: SincFilterInterpolator #lanczos is a specific case of sinc filter sinc: SincFilterInterpolator }[config.method] if config.method is 'lanczos' #Setup lanczos window config.sincWindow = makeLanczosWindow config.sincFilterSize #Make sure there's at least one element in the input array throw 'Array must have at least two elements' if arr.length < 2 #save count property properties.count = arr.length #See what type of data we're dealing with smoothFunc = switch getType arr[0] when 'Number' #scalar properties.dimension = 'scalar' #Validate all input if deep validation is on validateNumber n for n in arr if Smooth.deepValidation #Create the interpolator interpolator = new interpolatorClass arr, config #make function that runs the interpolator (t) -> interpolator.interpolate t when 'Array' # vector properties.dimension = dimension = arr[0].length throw 'Vectors must be non-empty' unless dimension #Validate all input if deep validation is on validateVector v, dimension for v in arr if Smooth.deepValidation #Create interpolator for each column interpolators = (new interpolatorClass(getColumn(arr, i), config) for i in [0...dimension]) #make function that runs the interpolators and puts them into an array (t) -> (interpolator.interpolate(t) for interpolator in interpolators) else throw "Invalid element type: #{getType arr[0]}" # Determine the end of the original function's domain if config.clip is 'periodic' then baseDomainEnd = arr.length #after last element for periodic else baseDomainEnd = arr.length - 1 #at last element for non-periodic config.scaleTo ||= baseDomainEnd #default scales to the end of the original domain for no effect properties.domain = normalizeScaleTo config.scaleTo smoothFunc = makeScaledFunction smoothFunc, baseDomainEnd, properties.domain properties.domain.sort() ###copy properties### smoothFunc[k] = v for own k,v of properties return smoothFunc #Copy enums to Smooth Smooth[k] = v for own k,v of Enum Smooth.deepValidation = true (exports ? window).Smooth = Smooth
88852
### Smooth.js version 0.1.7 Turn arrays into smooth functions. Copyright 2012 <NAME> Licensed under MIT license (see "Smooth.js MIT license.txt") ### ###Constants (these are accessible by Smooth.WHATEVER in user space)### Enum = ###Interpolation methods### METHOD_NEAREST: 'nearest' #Rounds to nearest whole index METHOD_LINEAR: 'linear' METHOD_CUBIC: 'cubic' # Default: cubic interpolation METHOD_LANCZOS: 'lanczos' METHOD_SINC: 'sinc' ###Input clipping modes### CLIP_CLAMP: 'clamp' # Default: clamp to [0, arr.length-1] CLIP_ZERO: 'zero' # When out of bounds, clip to zero CLIP_PERIODIC: 'periodic' # Repeat the array infinitely in either direction CLIP_MIRROR: 'mirror' # Repeat infinitely in either direction, flipping each time ### Constants for control over the cubic interpolation tension ### CUBIC_TENSION_DEFAULT: 0 # Default tension value CUBIC_TENSION_CATMULL_ROM: 0 defaultConfig = method: Enum.METHOD_CUBIC #The interpolation method cubicTension: Enum.CUBIC_TENSION_DEFAULT #The cubic tension parameter clip: Enum.CLIP_CLAMP #The clipping mode scaleTo: 0 #The scale-to value (0 means don't scale) (can also be a range) sincFilterSize: 2 #The size of the sinc filter kernel (must be an integer) sincWindow: undefined #The window function for the sinc filter ###Index clipping functions### clipClamp = (i, n) -> Math.max 0, Math.min i, n - 1 clipPeriodic = (i, n) -> i = i % n #wrap i += n if i < 0 #if negative, wrap back around i clipMirror = (i, n) -> period = 2*(n - 1) #period of index mirroring function i = clipPeriodic i, period i = period - i if i > n - 1 #flip when out of bounds i ### Abstract scalar interpolation class which provides common functionality for all interpolators Subclasses must override interpolate(). ### class AbstractInterpolator constructor: (array, config) -> @array = array.slice 0 #copy the array @length = @array.length #cache length #Set the clipping helper method throw "Invalid clip: #{config.clip}" unless @clipHelper = { clamp: @clipHelperClamp zero: @clipHelperZero periodic: @clipHelperPeriodic mirror: @clipHelperMirror }[config.clip] # Get input array value at i, applying the clipping method getClippedInput: (i) -> #Normal behavior for indexes within bounds if 0 <= i < @length @array[i] else @clipHelper i clipHelperClamp: (i) -> @array[clipClamp i, @length] clipHelperZero: (i) -> 0 clipHelperPeriodic: (i) -> @array[clipPeriodic i, @length] clipHelperMirror: (i) -> @array[clipMirror i, @length] interpolate: (t) -> throw 'Subclasses of AbstractInterpolator must override the interpolate() method.' #Nearest neighbor interpolator (round to whole index) class NearestInterpolator extends AbstractInterpolator interpolate: (t) -> @getClippedInput Math.round t #Linear interpolator (first order Bezier) class LinearInterpolator extends AbstractInterpolator interpolate: (t) -> k = Math.floor t #Translate t to interpolate between k and k+1 t -= k return (1-t)*@getClippedInput(k) + (t)*@getClippedInput(k+1) class CubicInterpolator extends AbstractInterpolator constructor: (array, config)-> #clamp cubic tension to [0,1] range @tangentFactor = 1 - Math.max 0, Math.min 1, config.cubicTension super # Cardinal spline with tension 0.5) getTangent: (k) -> @tangentFactor*(@getClippedInput(k + 1) - @getClippedInput(k - 1))/2 interpolate: (t) -> k = Math.floor t m = [(@getTangent k), (@getTangent k+1)] #get tangents p = [(@getClippedInput k), (@getClippedInput k+1)] #get points #Translate t to interpolate between k and k+1 t -= k t2 = t*t #t^2 t3 = t*t2 #t^3 #Apply cubic hermite spline formula return (2*t3 - 3*t2 + 1)*p[0] + (t3 - 2*t2 + t)*m[0] + (-2*t3 + 3*t2)*p[1] + (t3 - t2)*m[1] {sin, PI} = Math #Normalized sinc function sinc = (x) -> if x is 0 then 1 else sin(PI*x)/(PI*x) #Make a lanczos window function for a given filter size 'a' makeLanczosWindow = (a) -> (x) -> sinc(x/a) #Make a sinc kernel function by multiplying the sinc function by a window function makeSincKernel = (window) -> (x) -> sinc(x)*window(x) class SincFilterInterpolator extends AbstractInterpolator constructor: (array, config) -> super #Create the lanczos kernel function @a = config.sincFilterSize #Cannot make sinc filter without a window function throw 'No sincWindow provided' unless config.sincWindow #Window the sinc function to make the kernel @kernel = makeSincKernel config.sincWindow interpolate: (t) -> k = Math.floor t #Convolve with Lanczos kernel sum = 0 sum += @kernel(t - n)*@getClippedInput(n) for n in [(k - @a + 1)..(k + @a)] sum #Extract a column from a two dimensional array getColumn = (arr, i) -> (row[i] for row in arr) #Take a function with one parameter and apply a scale factor to its parameter makeScaledFunction = (f, baseScale, scaleRange) -> if scaleRange.join is '0,1' f #don't wrap the function unecessarily else scaleFactor = baseScale/(scaleRange[1] - scaleRange[0]) translation = scaleRange[0] (t) -> f scaleFactor*(t - translation) getType = (x) -> Object::toString.call(x)[('[object '.length)...-1] #Throw exception if input is not a number validateNumber = (n) -> throw 'NaN in Smooth() input' if isNaN n throw 'Non-number in Smooth() input' unless getType(n) is 'Number' throw 'Infinity in Smooth() input' unless isFinite n #Throw an exception if input is not a vector of numbers which is the correct length validateVector = (v, dimension) -> throw 'Non-vector in Smooth() input' unless getType(v) is 'Array' throw 'Inconsistent dimension in Smooth() input' unless v.length is dimension validateNumber n for n in v return isValidNumber = (n) -> (getType(n) is 'Number') and isFinite(n) and not isNaN(n) normalizeScaleTo = (s) -> invalidErr = "scaleTo param must be number or array of two numbers" switch getType s when 'Number' throw invalidErr unless isValidNumber s s = [0, s] when 'Array' throw invalidErr unless s.length is 2 throw invalidErr unless isValidNumber(s[0]) and isValidNumber(s[1]) else throw invalidErr return s shallowCopy = (obj) -> copy = {} copy[k] = v for own k,v of obj copy Smooth = (arr, config = {}) -> #Properties to copy to the function once it is created properties = {} #Make a copy of the config object to modify config = shallowCopy config #Make another copy of the config object to save to the function properties.config = shallowCopy config #Alias 'period' to 'scaleTo' config.scaleTo ?= config.period #Alias lanczosFilterSize to sincFilterSize config.sincFilterSize ?= config.lanczosFilterSize config[k] ?= v for own k,v of defaultConfig #fill in defaults #Get the interpolator class according to the configuration throw "Invalid method: #{config.method}" unless interpolatorClass = { nearest: NearestInterpolator linear: LinearInterpolator cubic: CubicInterpolator lanczos: SincFilterInterpolator #lanczos is a specific case of sinc filter sinc: SincFilterInterpolator }[config.method] if config.method is 'lanczos' #Setup lanczos window config.sincWindow = makeLanczosWindow config.sincFilterSize #Make sure there's at least one element in the input array throw 'Array must have at least two elements' if arr.length < 2 #save count property properties.count = arr.length #See what type of data we're dealing with smoothFunc = switch getType arr[0] when 'Number' #scalar properties.dimension = 'scalar' #Validate all input if deep validation is on validateNumber n for n in arr if Smooth.deepValidation #Create the interpolator interpolator = new interpolatorClass arr, config #make function that runs the interpolator (t) -> interpolator.interpolate t when 'Array' # vector properties.dimension = dimension = arr[0].length throw 'Vectors must be non-empty' unless dimension #Validate all input if deep validation is on validateVector v, dimension for v in arr if Smooth.deepValidation #Create interpolator for each column interpolators = (new interpolatorClass(getColumn(arr, i), config) for i in [0...dimension]) #make function that runs the interpolators and puts them into an array (t) -> (interpolator.interpolate(t) for interpolator in interpolators) else throw "Invalid element type: #{getType arr[0]}" # Determine the end of the original function's domain if config.clip is 'periodic' then baseDomainEnd = arr.length #after last element for periodic else baseDomainEnd = arr.length - 1 #at last element for non-periodic config.scaleTo ||= baseDomainEnd #default scales to the end of the original domain for no effect properties.domain = normalizeScaleTo config.scaleTo smoothFunc = makeScaledFunction smoothFunc, baseDomainEnd, properties.domain properties.domain.sort() ###copy properties### smoothFunc[k] = v for own k,v of properties return smoothFunc #Copy enums to Smooth Smooth[k] = v for own k,v of Enum Smooth.deepValidation = true (exports ? window).Smooth = Smooth
true
### Smooth.js version 0.1.7 Turn arrays into smooth functions. Copyright 2012 PI:NAME:<NAME>END_PI Licensed under MIT license (see "Smooth.js MIT license.txt") ### ###Constants (these are accessible by Smooth.WHATEVER in user space)### Enum = ###Interpolation methods### METHOD_NEAREST: 'nearest' #Rounds to nearest whole index METHOD_LINEAR: 'linear' METHOD_CUBIC: 'cubic' # Default: cubic interpolation METHOD_LANCZOS: 'lanczos' METHOD_SINC: 'sinc' ###Input clipping modes### CLIP_CLAMP: 'clamp' # Default: clamp to [0, arr.length-1] CLIP_ZERO: 'zero' # When out of bounds, clip to zero CLIP_PERIODIC: 'periodic' # Repeat the array infinitely in either direction CLIP_MIRROR: 'mirror' # Repeat infinitely in either direction, flipping each time ### Constants for control over the cubic interpolation tension ### CUBIC_TENSION_DEFAULT: 0 # Default tension value CUBIC_TENSION_CATMULL_ROM: 0 defaultConfig = method: Enum.METHOD_CUBIC #The interpolation method cubicTension: Enum.CUBIC_TENSION_DEFAULT #The cubic tension parameter clip: Enum.CLIP_CLAMP #The clipping mode scaleTo: 0 #The scale-to value (0 means don't scale) (can also be a range) sincFilterSize: 2 #The size of the sinc filter kernel (must be an integer) sincWindow: undefined #The window function for the sinc filter ###Index clipping functions### clipClamp = (i, n) -> Math.max 0, Math.min i, n - 1 clipPeriodic = (i, n) -> i = i % n #wrap i += n if i < 0 #if negative, wrap back around i clipMirror = (i, n) -> period = 2*(n - 1) #period of index mirroring function i = clipPeriodic i, period i = period - i if i > n - 1 #flip when out of bounds i ### Abstract scalar interpolation class which provides common functionality for all interpolators Subclasses must override interpolate(). ### class AbstractInterpolator constructor: (array, config) -> @array = array.slice 0 #copy the array @length = @array.length #cache length #Set the clipping helper method throw "Invalid clip: #{config.clip}" unless @clipHelper = { clamp: @clipHelperClamp zero: @clipHelperZero periodic: @clipHelperPeriodic mirror: @clipHelperMirror }[config.clip] # Get input array value at i, applying the clipping method getClippedInput: (i) -> #Normal behavior for indexes within bounds if 0 <= i < @length @array[i] else @clipHelper i clipHelperClamp: (i) -> @array[clipClamp i, @length] clipHelperZero: (i) -> 0 clipHelperPeriodic: (i) -> @array[clipPeriodic i, @length] clipHelperMirror: (i) -> @array[clipMirror i, @length] interpolate: (t) -> throw 'Subclasses of AbstractInterpolator must override the interpolate() method.' #Nearest neighbor interpolator (round to whole index) class NearestInterpolator extends AbstractInterpolator interpolate: (t) -> @getClippedInput Math.round t #Linear interpolator (first order Bezier) class LinearInterpolator extends AbstractInterpolator interpolate: (t) -> k = Math.floor t #Translate t to interpolate between k and k+1 t -= k return (1-t)*@getClippedInput(k) + (t)*@getClippedInput(k+1) class CubicInterpolator extends AbstractInterpolator constructor: (array, config)-> #clamp cubic tension to [0,1] range @tangentFactor = 1 - Math.max 0, Math.min 1, config.cubicTension super # Cardinal spline with tension 0.5) getTangent: (k) -> @tangentFactor*(@getClippedInput(k + 1) - @getClippedInput(k - 1))/2 interpolate: (t) -> k = Math.floor t m = [(@getTangent k), (@getTangent k+1)] #get tangents p = [(@getClippedInput k), (@getClippedInput k+1)] #get points #Translate t to interpolate between k and k+1 t -= k t2 = t*t #t^2 t3 = t*t2 #t^3 #Apply cubic hermite spline formula return (2*t3 - 3*t2 + 1)*p[0] + (t3 - 2*t2 + t)*m[0] + (-2*t3 + 3*t2)*p[1] + (t3 - t2)*m[1] {sin, PI} = Math #Normalized sinc function sinc = (x) -> if x is 0 then 1 else sin(PI*x)/(PI*x) #Make a lanczos window function for a given filter size 'a' makeLanczosWindow = (a) -> (x) -> sinc(x/a) #Make a sinc kernel function by multiplying the sinc function by a window function makeSincKernel = (window) -> (x) -> sinc(x)*window(x) class SincFilterInterpolator extends AbstractInterpolator constructor: (array, config) -> super #Create the lanczos kernel function @a = config.sincFilterSize #Cannot make sinc filter without a window function throw 'No sincWindow provided' unless config.sincWindow #Window the sinc function to make the kernel @kernel = makeSincKernel config.sincWindow interpolate: (t) -> k = Math.floor t #Convolve with Lanczos kernel sum = 0 sum += @kernel(t - n)*@getClippedInput(n) for n in [(k - @a + 1)..(k + @a)] sum #Extract a column from a two dimensional array getColumn = (arr, i) -> (row[i] for row in arr) #Take a function with one parameter and apply a scale factor to its parameter makeScaledFunction = (f, baseScale, scaleRange) -> if scaleRange.join is '0,1' f #don't wrap the function unecessarily else scaleFactor = baseScale/(scaleRange[1] - scaleRange[0]) translation = scaleRange[0] (t) -> f scaleFactor*(t - translation) getType = (x) -> Object::toString.call(x)[('[object '.length)...-1] #Throw exception if input is not a number validateNumber = (n) -> throw 'NaN in Smooth() input' if isNaN n throw 'Non-number in Smooth() input' unless getType(n) is 'Number' throw 'Infinity in Smooth() input' unless isFinite n #Throw an exception if input is not a vector of numbers which is the correct length validateVector = (v, dimension) -> throw 'Non-vector in Smooth() input' unless getType(v) is 'Array' throw 'Inconsistent dimension in Smooth() input' unless v.length is dimension validateNumber n for n in v return isValidNumber = (n) -> (getType(n) is 'Number') and isFinite(n) and not isNaN(n) normalizeScaleTo = (s) -> invalidErr = "scaleTo param must be number or array of two numbers" switch getType s when 'Number' throw invalidErr unless isValidNumber s s = [0, s] when 'Array' throw invalidErr unless s.length is 2 throw invalidErr unless isValidNumber(s[0]) and isValidNumber(s[1]) else throw invalidErr return s shallowCopy = (obj) -> copy = {} copy[k] = v for own k,v of obj copy Smooth = (arr, config = {}) -> #Properties to copy to the function once it is created properties = {} #Make a copy of the config object to modify config = shallowCopy config #Make another copy of the config object to save to the function properties.config = shallowCopy config #Alias 'period' to 'scaleTo' config.scaleTo ?= config.period #Alias lanczosFilterSize to sincFilterSize config.sincFilterSize ?= config.lanczosFilterSize config[k] ?= v for own k,v of defaultConfig #fill in defaults #Get the interpolator class according to the configuration throw "Invalid method: #{config.method}" unless interpolatorClass = { nearest: NearestInterpolator linear: LinearInterpolator cubic: CubicInterpolator lanczos: SincFilterInterpolator #lanczos is a specific case of sinc filter sinc: SincFilterInterpolator }[config.method] if config.method is 'lanczos' #Setup lanczos window config.sincWindow = makeLanczosWindow config.sincFilterSize #Make sure there's at least one element in the input array throw 'Array must have at least two elements' if arr.length < 2 #save count property properties.count = arr.length #See what type of data we're dealing with smoothFunc = switch getType arr[0] when 'Number' #scalar properties.dimension = 'scalar' #Validate all input if deep validation is on validateNumber n for n in arr if Smooth.deepValidation #Create the interpolator interpolator = new interpolatorClass arr, config #make function that runs the interpolator (t) -> interpolator.interpolate t when 'Array' # vector properties.dimension = dimension = arr[0].length throw 'Vectors must be non-empty' unless dimension #Validate all input if deep validation is on validateVector v, dimension for v in arr if Smooth.deepValidation #Create interpolator for each column interpolators = (new interpolatorClass(getColumn(arr, i), config) for i in [0...dimension]) #make function that runs the interpolators and puts them into an array (t) -> (interpolator.interpolate(t) for interpolator in interpolators) else throw "Invalid element type: #{getType arr[0]}" # Determine the end of the original function's domain if config.clip is 'periodic' then baseDomainEnd = arr.length #after last element for periodic else baseDomainEnd = arr.length - 1 #at last element for non-periodic config.scaleTo ||= baseDomainEnd #default scales to the end of the original domain for no effect properties.domain = normalizeScaleTo config.scaleTo smoothFunc = makeScaledFunction smoothFunc, baseDomainEnd, properties.domain properties.domain.sort() ###copy properties### smoothFunc[k] = v for own k,v of properties return smoothFunc #Copy enums to Smooth Smooth[k] = v for own k,v of Enum Smooth.deepValidation = true (exports ? window).Smooth = Smooth
[ { "context": " username: process.env.EMMI_USERNAME\n password: process.env.EMMI_PASSWORD\n endpoint: process.env.EMMI_ENDPOINT\n exter", "end": 101, "score": 0.9992930293083191, "start": 76, "tag": "PASSWORD", "value": "process.env.EMMI_PASSWORD" } ]
server/EMMIClientSettings.coffee
drobbins/kassebaum
0
@EMMIClientSettings = username: process.env.EMMI_USERNAME password: process.env.EMMI_PASSWORD endpoint: process.env.EMMI_ENDPOINT externalSystem: process.env.EMMI_EXTERNALSYSTEM if process.env.NODE_ENV is "development" process.env.MOCK_EMMI = true
106414
@EMMIClientSettings = username: process.env.EMMI_USERNAME password: <PASSWORD> endpoint: process.env.EMMI_ENDPOINT externalSystem: process.env.EMMI_EXTERNALSYSTEM if process.env.NODE_ENV is "development" process.env.MOCK_EMMI = true
true
@EMMIClientSettings = username: process.env.EMMI_USERNAME password: PI:PASSWORD:<PASSWORD>END_PI endpoint: process.env.EMMI_ENDPOINT externalSystem: process.env.EMMI_EXTERNALSYSTEM if process.env.NODE_ENV is "development" process.env.MOCK_EMMI = true
[ { "context": " disallow uses of await inside of loops.\n# @author Nat Mote (nmote)\n###\n'use strict'\n\n###*\n# Check whether it", "end": 87, "score": 0.9998556971549988, "start": 79, "tag": "NAME", "value": "Nat Mote" }, { "context": "ses of await inside of loops.\n# @author Nat Mo...
src/rules/no-await-in-loop.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to disallow uses of await inside of loops. # @author Nat Mote (nmote) ### 'use strict' ###* # Check whether it should stop traversing ancestors at the given node. # @param {ASTNode} node A node to check. # @returns {boolean} `true` if it should stop traversing. ### isBoundary = (node) -> t = node.type t in [ 'FunctionDeclaration' 'FunctionExpression' 'ArrowFunctionExpression' ] or ### # Don't report the await expressions on for-await-of loop since it's # asynchronous iteration intentionally. ### (t is 'For' and node.await is yes) ###* # Check whether the given node is in loop. # @param {ASTNode} node A node to check. # @param {ASTNode} parent A parent node to check. # @returns {boolean} `true` if the node is in loop. ### isLooped = (node, parent) -> switch parent.type when 'For' return node is parent.body when 'WhileStatement' return node in [parent.test, parent.body] else return no module.exports = meta: docs: description: 'disallow `await` inside of loops' category: 'Possible Errors' recommended: no url: 'https://eslint.org/docs/rules/no-await-in-loop' schema: [] messages: unexpectedAwait: 'Unexpected `await` inside a loop.' create: (context) -> ###* # Validate an await expression. # @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate. # @returns {void} ### validate = (awaitNode) -> return if awaitNode.type is 'For' and not awaitNode.await node = awaitNode {parent} = node while parent and not isBoundary parent if isLooped node, parent context.report node: awaitNode messageId: 'unexpectedAwait' return node = parent {parent} = parent AwaitExpression: validate For: validate
14301
###* # @fileoverview Rule to disallow uses of await inside of loops. # @author <NAME> (nmote) ### 'use strict' ###* # Check whether it should stop traversing ancestors at the given node. # @param {ASTNode} node A node to check. # @returns {boolean} `true` if it should stop traversing. ### isBoundary = (node) -> t = node.type t in [ 'FunctionDeclaration' 'FunctionExpression' 'ArrowFunctionExpression' ] or ### # Don't report the await expressions on for-await-of loop since it's # asynchronous iteration intentionally. ### (t is 'For' and node.await is yes) ###* # Check whether the given node is in loop. # @param {ASTNode} node A node to check. # @param {ASTNode} parent A parent node to check. # @returns {boolean} `true` if the node is in loop. ### isLooped = (node, parent) -> switch parent.type when 'For' return node is parent.body when 'WhileStatement' return node in [parent.test, parent.body] else return no module.exports = meta: docs: description: 'disallow `await` inside of loops' category: 'Possible Errors' recommended: no url: 'https://eslint.org/docs/rules/no-await-in-loop' schema: [] messages: unexpectedAwait: 'Unexpected `await` inside a loop.' create: (context) -> ###* # Validate an await expression. # @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate. # @returns {void} ### validate = (awaitNode) -> return if awaitNode.type is 'For' and not awaitNode.await node = awaitNode {parent} = node while parent and not isBoundary parent if isLooped node, parent context.report node: awaitNode messageId: 'unexpectedAwait' return node = parent {parent} = parent AwaitExpression: validate For: validate
true
###* # @fileoverview Rule to disallow uses of await inside of loops. # @author PI:NAME:<NAME>END_PI (nmote) ### 'use strict' ###* # Check whether it should stop traversing ancestors at the given node. # @param {ASTNode} node A node to check. # @returns {boolean} `true` if it should stop traversing. ### isBoundary = (node) -> t = node.type t in [ 'FunctionDeclaration' 'FunctionExpression' 'ArrowFunctionExpression' ] or ### # Don't report the await expressions on for-await-of loop since it's # asynchronous iteration intentionally. ### (t is 'For' and node.await is yes) ###* # Check whether the given node is in loop. # @param {ASTNode} node A node to check. # @param {ASTNode} parent A parent node to check. # @returns {boolean} `true` if the node is in loop. ### isLooped = (node, parent) -> switch parent.type when 'For' return node is parent.body when 'WhileStatement' return node in [parent.test, parent.body] else return no module.exports = meta: docs: description: 'disallow `await` inside of loops' category: 'Possible Errors' recommended: no url: 'https://eslint.org/docs/rules/no-await-in-loop' schema: [] messages: unexpectedAwait: 'Unexpected `await` inside a loop.' create: (context) -> ###* # Validate an await expression. # @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate. # @returns {void} ### validate = (awaitNode) -> return if awaitNode.type is 'For' and not awaitNode.await node = awaitNode {parent} = node while parent and not isBoundary parent if isLooped node, parent context.report node: awaitNode messageId: 'unexpectedAwait' return node = parent {parent} = parent AwaitExpression: validate For: validate
[ { "context": "leName + '@' + id\n\n @getById: (id) ->\n key = @generateCacheKey(id)\n if (model = @cache.get(key))?\n Q(mod", "end": 3656, "score": 0.6597051620483398, "start": 3640, "tag": "KEY", "value": "generateCacheKey" } ]
lib/model-base.coffee
xmail-client/node-sqlite-orm
0
Mixin = require 'mixto' _ = require 'underscore' Q = require 'q' {Emitter} = require 'event-kit' ModelAssociation = require './model-association' module.exports = class ModelBaseMixin extends Mixin ModelAssociation.includeInto this @models = {} initModel: (params) -> @_modelEmitter = new Emitter @isInsert = false @changeFields = {} @query = @constructor.query this[key] = val for key, val of params @included: -> this._name ?= this.name ModelBaseMixin.models[this._name] = this @_initAssos() @defineAttr: (name, opts) -> key = '_' + name defaultVal = opts.default ? null interpreter = @mapper.getInterpreter(opts.type) {from, to} = interpreter if interpreter Object.defineProperty @prototype, name, get: -> val = this[key] ? defaultVal if from then from.call(interpreter, val) else val set: (val) -> val ?= null savedVal = if to then to.call(interpreter, val) else val unless this[key] is savedVal @_modelEmitter.emit name, {oldValue: this[name]} @changeFields[name] = savedVal this[key] = savedVal # apply tableInfo's attributes into the Model's prototype, # so that the model has the db column variables @extendAttrs: (tableInfo) -> for name, opts of tableInfo.attributes when not @::hasOwnProperty(name) @defineAttr name, opts @extendModel: (mapper, tableInfo) -> @mapper = mapper @query = mapper.getQuery() @cache = mapper.cache @tableName = tableInfo.tableName @primaryKeyName = tableInfo.primaryKeyName @extendAttrs tableInfo @getMapper: -> @mapper @wrapWhere: (where) -> if where and not _.isObject where where = {"#{@primaryKeyName}": where} where getIdFromWhere = (where) -> return where unless _.isObject(where) keys = _.keys(where) if keys.length is 1 and keys[0] is @primaryKeyName keys[0] @find: (where, opts={}) -> if (primaryVal = getIdFromWhere.call(this, where))? @getById(primaryVal) else opts.limit = 1 @query.selectOne(@tableName, @wrapWhere(where), opts).then (res) => if res then @load(res) else null @findAll: (where, opts) -> @query.select(@tableName, @wrapWhere(where), opts).then (results) => promises = for res in results @load(res) Q.all promises @each: (where, opts, step) -> if _.isFunction(where) step = where where = opts = null else if _.isFunction(opts) step = opts opts = null @query.selectEach(@tableName, @wrapWhere(where), opts, step) on: (name, callback) -> @_modelEmitter.on(name, callback) save: -> Constructor = @constructor keyName = Constructor.primaryKeyName tableName = Constructor.tableName unless @isInsert @query.insert(tableName, @changeFields).then (rowId) => this[keyName] = rowId @changeFields = {} Model = @constructor Model.cache.set Model.generateCacheKey(rowId), this @isInsert = true # Model.loadAssos(this) else if _.keys(@changeFields).length is 0 Q() else where = "#{keyName}": this[keyName] @query.update(tableName, @changeFields, where).then => @changeFields = {} destroy: -> @destroyAssos() Constructor = @constructor keyName = Constructor.primaryKeyName @query.remove(Constructor.tableName, "#{keyName}": this[keyName]) @remove: (where) -> @query.remove(@tableName, where) @clear: -> @query.remove(@tableName) @generateCacheKey: (id) -> @tableName + '@' + id @getById: (id) -> key = @generateCacheKey(id) if (model = @cache.get(key))? Q(model) else @query.selectOne(@tableName, @wrapWhere(id)).then (res) => if res then @loadNoCache(res) else null @loadNoCache: (obj) -> model = new this model['_' + key] = val for key, val of obj model.isInsert = true primaryVal = obj[@primaryKeyName] @cache.set @generateCacheKey(primaryVal), model @loadAssos(model).then -> model @load: (obj) -> primaryVal = obj[@primaryKeyName] cacheKey = @generateCacheKey(primaryVal) if (model = @cache.get(cacheKey))? Q(model) else @loadNoCache(obj) @new: (obj) -> new this(obj) @create: (obj) -> model = new this(obj) model.save().then -> model @drop: -> delete @models[@name] @query.dropTable @tableName
171140
Mixin = require 'mixto' _ = require 'underscore' Q = require 'q' {Emitter} = require 'event-kit' ModelAssociation = require './model-association' module.exports = class ModelBaseMixin extends Mixin ModelAssociation.includeInto this @models = {} initModel: (params) -> @_modelEmitter = new Emitter @isInsert = false @changeFields = {} @query = @constructor.query this[key] = val for key, val of params @included: -> this._name ?= this.name ModelBaseMixin.models[this._name] = this @_initAssos() @defineAttr: (name, opts) -> key = '_' + name defaultVal = opts.default ? null interpreter = @mapper.getInterpreter(opts.type) {from, to} = interpreter if interpreter Object.defineProperty @prototype, name, get: -> val = this[key] ? defaultVal if from then from.call(interpreter, val) else val set: (val) -> val ?= null savedVal = if to then to.call(interpreter, val) else val unless this[key] is savedVal @_modelEmitter.emit name, {oldValue: this[name]} @changeFields[name] = savedVal this[key] = savedVal # apply tableInfo's attributes into the Model's prototype, # so that the model has the db column variables @extendAttrs: (tableInfo) -> for name, opts of tableInfo.attributes when not @::hasOwnProperty(name) @defineAttr name, opts @extendModel: (mapper, tableInfo) -> @mapper = mapper @query = mapper.getQuery() @cache = mapper.cache @tableName = tableInfo.tableName @primaryKeyName = tableInfo.primaryKeyName @extendAttrs tableInfo @getMapper: -> @mapper @wrapWhere: (where) -> if where and not _.isObject where where = {"#{@primaryKeyName}": where} where getIdFromWhere = (where) -> return where unless _.isObject(where) keys = _.keys(where) if keys.length is 1 and keys[0] is @primaryKeyName keys[0] @find: (where, opts={}) -> if (primaryVal = getIdFromWhere.call(this, where))? @getById(primaryVal) else opts.limit = 1 @query.selectOne(@tableName, @wrapWhere(where), opts).then (res) => if res then @load(res) else null @findAll: (where, opts) -> @query.select(@tableName, @wrapWhere(where), opts).then (results) => promises = for res in results @load(res) Q.all promises @each: (where, opts, step) -> if _.isFunction(where) step = where where = opts = null else if _.isFunction(opts) step = opts opts = null @query.selectEach(@tableName, @wrapWhere(where), opts, step) on: (name, callback) -> @_modelEmitter.on(name, callback) save: -> Constructor = @constructor keyName = Constructor.primaryKeyName tableName = Constructor.tableName unless @isInsert @query.insert(tableName, @changeFields).then (rowId) => this[keyName] = rowId @changeFields = {} Model = @constructor Model.cache.set Model.generateCacheKey(rowId), this @isInsert = true # Model.loadAssos(this) else if _.keys(@changeFields).length is 0 Q() else where = "#{keyName}": this[keyName] @query.update(tableName, @changeFields, where).then => @changeFields = {} destroy: -> @destroyAssos() Constructor = @constructor keyName = Constructor.primaryKeyName @query.remove(Constructor.tableName, "#{keyName}": this[keyName]) @remove: (where) -> @query.remove(@tableName, where) @clear: -> @query.remove(@tableName) @generateCacheKey: (id) -> @tableName + '@' + id @getById: (id) -> key = @<KEY>(id) if (model = @cache.get(key))? Q(model) else @query.selectOne(@tableName, @wrapWhere(id)).then (res) => if res then @loadNoCache(res) else null @loadNoCache: (obj) -> model = new this model['_' + key] = val for key, val of obj model.isInsert = true primaryVal = obj[@primaryKeyName] @cache.set @generateCacheKey(primaryVal), model @loadAssos(model).then -> model @load: (obj) -> primaryVal = obj[@primaryKeyName] cacheKey = @generateCacheKey(primaryVal) if (model = @cache.get(cacheKey))? Q(model) else @loadNoCache(obj) @new: (obj) -> new this(obj) @create: (obj) -> model = new this(obj) model.save().then -> model @drop: -> delete @models[@name] @query.dropTable @tableName
true
Mixin = require 'mixto' _ = require 'underscore' Q = require 'q' {Emitter} = require 'event-kit' ModelAssociation = require './model-association' module.exports = class ModelBaseMixin extends Mixin ModelAssociation.includeInto this @models = {} initModel: (params) -> @_modelEmitter = new Emitter @isInsert = false @changeFields = {} @query = @constructor.query this[key] = val for key, val of params @included: -> this._name ?= this.name ModelBaseMixin.models[this._name] = this @_initAssos() @defineAttr: (name, opts) -> key = '_' + name defaultVal = opts.default ? null interpreter = @mapper.getInterpreter(opts.type) {from, to} = interpreter if interpreter Object.defineProperty @prototype, name, get: -> val = this[key] ? defaultVal if from then from.call(interpreter, val) else val set: (val) -> val ?= null savedVal = if to then to.call(interpreter, val) else val unless this[key] is savedVal @_modelEmitter.emit name, {oldValue: this[name]} @changeFields[name] = savedVal this[key] = savedVal # apply tableInfo's attributes into the Model's prototype, # so that the model has the db column variables @extendAttrs: (tableInfo) -> for name, opts of tableInfo.attributes when not @::hasOwnProperty(name) @defineAttr name, opts @extendModel: (mapper, tableInfo) -> @mapper = mapper @query = mapper.getQuery() @cache = mapper.cache @tableName = tableInfo.tableName @primaryKeyName = tableInfo.primaryKeyName @extendAttrs tableInfo @getMapper: -> @mapper @wrapWhere: (where) -> if where and not _.isObject where where = {"#{@primaryKeyName}": where} where getIdFromWhere = (where) -> return where unless _.isObject(where) keys = _.keys(where) if keys.length is 1 and keys[0] is @primaryKeyName keys[0] @find: (where, opts={}) -> if (primaryVal = getIdFromWhere.call(this, where))? @getById(primaryVal) else opts.limit = 1 @query.selectOne(@tableName, @wrapWhere(where), opts).then (res) => if res then @load(res) else null @findAll: (where, opts) -> @query.select(@tableName, @wrapWhere(where), opts).then (results) => promises = for res in results @load(res) Q.all promises @each: (where, opts, step) -> if _.isFunction(where) step = where where = opts = null else if _.isFunction(opts) step = opts opts = null @query.selectEach(@tableName, @wrapWhere(where), opts, step) on: (name, callback) -> @_modelEmitter.on(name, callback) save: -> Constructor = @constructor keyName = Constructor.primaryKeyName tableName = Constructor.tableName unless @isInsert @query.insert(tableName, @changeFields).then (rowId) => this[keyName] = rowId @changeFields = {} Model = @constructor Model.cache.set Model.generateCacheKey(rowId), this @isInsert = true # Model.loadAssos(this) else if _.keys(@changeFields).length is 0 Q() else where = "#{keyName}": this[keyName] @query.update(tableName, @changeFields, where).then => @changeFields = {} destroy: -> @destroyAssos() Constructor = @constructor keyName = Constructor.primaryKeyName @query.remove(Constructor.tableName, "#{keyName}": this[keyName]) @remove: (where) -> @query.remove(@tableName, where) @clear: -> @query.remove(@tableName) @generateCacheKey: (id) -> @tableName + '@' + id @getById: (id) -> key = @PI:KEY:<KEY>END_PI(id) if (model = @cache.get(key))? Q(model) else @query.selectOne(@tableName, @wrapWhere(id)).then (res) => if res then @loadNoCache(res) else null @loadNoCache: (obj) -> model = new this model['_' + key] = val for key, val of obj model.isInsert = true primaryVal = obj[@primaryKeyName] @cache.set @generateCacheKey(primaryVal), model @loadAssos(model).then -> model @load: (obj) -> primaryVal = obj[@primaryKeyName] cacheKey = @generateCacheKey(primaryVal) if (model = @cache.get(cacheKey))? Q(model) else @loadNoCache(obj) @new: (obj) -> new this(obj) @create: (obj) -> model = new this(obj) model.save().then -> model @drop: -> delete @models[@name] @query.dropTable @tableName
[ { "context": " typeLogin \"foo\"\n typeEmail \"foo@example.com\"\n\n it \"register button is enabled\", ->", "end": 2105, "score": 0.9999116659164429, "start": 2090, "tag": "EMAIL", "value": "foo@example.com" } ]
www/test/src/register.coffee
berekuk/questhub
15
define [ "views/register" "models/current-user" ], (Register, currentUser) -> describe "register:", -> # FIXME - currentUser should be registered=0, it's a complete accident these tests are working! server = undefined beforeEach -> sinon.spy mixpanel, "track" server = sinon.fakeServer.create() afterEach -> mixpanel.track.restore() server.restore() view = undefined beforeEach -> view = new Register(model: currentUser) typeLogin = (text) -> view.$("[name=login]").val text e = $.Event("keyup") e.which = 65 # A - we just want to trigger keyup once view.$("[name=login]").trigger e typeEmail = (text) -> view.$("[name=email]").val text e = $.Event("keyup") e.which = 65 # A view.$("[name=email]").trigger e describe "initially", -> beforeEach -> view.render() it "register button is disabled", -> expect(view.$el.find ".submit").toHaveClass 'disabled' it "cancel button is enabled", -> expect(view.$el.find ".cancel").not.toHaveClass 'disabled' it "clicking Register does nothing", -> view.$(".submit").click() server.respond() expect(server.requests.length).not.toBeTruthy describe "after login is not empty", -> beforeEach -> view.render() typeLogin "foo" it "register button is still disabled", -> expect(view.$(".submit")).toHaveClass 'disabled' it "clicking Register does nothing", -> view.$(".submit").click() server.respond() expect(server.requests.length).not.toBeTruthy describe "after login AND email are not empty", -> beforeEach -> view.render() typeLogin "foo" typeEmail "foo@example.com" it "register button is enabled", -> expect(view.$(".submit")).not.toHaveClass 'disabled' it "clicking Register sends a request", -> view.$(".submit").click() server.respond() expect(server.requests.length).toBeTruthy expect(server.requests[0].requestBody).toMatch 'login=foo' expect(server.requests[0].requestBody).toMatch 'email%22%3A%22foo%40example.com'
153760
define [ "views/register" "models/current-user" ], (Register, currentUser) -> describe "register:", -> # FIXME - currentUser should be registered=0, it's a complete accident these tests are working! server = undefined beforeEach -> sinon.spy mixpanel, "track" server = sinon.fakeServer.create() afterEach -> mixpanel.track.restore() server.restore() view = undefined beforeEach -> view = new Register(model: currentUser) typeLogin = (text) -> view.$("[name=login]").val text e = $.Event("keyup") e.which = 65 # A - we just want to trigger keyup once view.$("[name=login]").trigger e typeEmail = (text) -> view.$("[name=email]").val text e = $.Event("keyup") e.which = 65 # A view.$("[name=email]").trigger e describe "initially", -> beforeEach -> view.render() it "register button is disabled", -> expect(view.$el.find ".submit").toHaveClass 'disabled' it "cancel button is enabled", -> expect(view.$el.find ".cancel").not.toHaveClass 'disabled' it "clicking Register does nothing", -> view.$(".submit").click() server.respond() expect(server.requests.length).not.toBeTruthy describe "after login is not empty", -> beforeEach -> view.render() typeLogin "foo" it "register button is still disabled", -> expect(view.$(".submit")).toHaveClass 'disabled' it "clicking Register does nothing", -> view.$(".submit").click() server.respond() expect(server.requests.length).not.toBeTruthy describe "after login AND email are not empty", -> beforeEach -> view.render() typeLogin "foo" typeEmail "<EMAIL>" it "register button is enabled", -> expect(view.$(".submit")).not.toHaveClass 'disabled' it "clicking Register sends a request", -> view.$(".submit").click() server.respond() expect(server.requests.length).toBeTruthy expect(server.requests[0].requestBody).toMatch 'login=foo' expect(server.requests[0].requestBody).toMatch 'email%22%3A%22foo%40example.com'
true
define [ "views/register" "models/current-user" ], (Register, currentUser) -> describe "register:", -> # FIXME - currentUser should be registered=0, it's a complete accident these tests are working! server = undefined beforeEach -> sinon.spy mixpanel, "track" server = sinon.fakeServer.create() afterEach -> mixpanel.track.restore() server.restore() view = undefined beforeEach -> view = new Register(model: currentUser) typeLogin = (text) -> view.$("[name=login]").val text e = $.Event("keyup") e.which = 65 # A - we just want to trigger keyup once view.$("[name=login]").trigger e typeEmail = (text) -> view.$("[name=email]").val text e = $.Event("keyup") e.which = 65 # A view.$("[name=email]").trigger e describe "initially", -> beforeEach -> view.render() it "register button is disabled", -> expect(view.$el.find ".submit").toHaveClass 'disabled' it "cancel button is enabled", -> expect(view.$el.find ".cancel").not.toHaveClass 'disabled' it "clicking Register does nothing", -> view.$(".submit").click() server.respond() expect(server.requests.length).not.toBeTruthy describe "after login is not empty", -> beforeEach -> view.render() typeLogin "foo" it "register button is still disabled", -> expect(view.$(".submit")).toHaveClass 'disabled' it "clicking Register does nothing", -> view.$(".submit").click() server.respond() expect(server.requests.length).not.toBeTruthy describe "after login AND email are not empty", -> beforeEach -> view.render() typeLogin "foo" typeEmail "PI:EMAIL:<EMAIL>END_PI" it "register button is enabled", -> expect(view.$(".submit")).not.toHaveClass 'disabled' it "clicking Register sends a request", -> view.$(".submit").click() server.respond() expect(server.requests.length).toBeTruthy expect(server.requests[0].requestBody).toMatch 'login=foo' expect(server.requests[0].requestBody).toMatch 'email%22%3A%22foo%40example.com'
[ { "context": "ew\", values: [\"No\", \"Yes\"]}\n ]\n\n f =\n name: \"Instructor\"\n gid: 12\n type: \"Guild NPC\"\n properties", "end": 2029, "score": 0.8585789203643799, "start": 2019, "tag": "NAME", "value": "Instructor" } ]
src/map/guild-buildings/Academy.coffee
Oipo/IdleLandsOld
0
GuildBuilding = require "../GuildBuilding" `/** * The Academy affects the capability of your minor permanent buffs as well as the major buffs you can purchase for a limited time. * * @name Academy * @category Buildings * @package Guild * @cost {level-up} 15000 (if level <= 100) * @property AutoRenew (Yes/No; whether or not to auto renew buffs upon expiration) * @size {md} */` class Academy extends GuildBuilding @size = Academy::size = "md" @desc = Academy::desc = "Upgrade this building to make your buffs better and get some permanent ones!" @levelupCost = Academy::levelupCost = (level) -> if level > 100 then level * (50000 + (25000*Math.floor level/100)) else 15000 @getStatEffects: (level) -> { strPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 1) ret = +(ret).toFixed(1) intPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 2) ret = +(ret).toFixed(1) conPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 3) ret = +(ret).toFixed(1) wisPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 4) ret = +(ret).toFixed(1) dexPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 5) ret = +(ret).toFixed(1) agiPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 6) ret = +(ret).toFixed(1) goldPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 7) ret = +(ret).toFixed(1) xpPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 7) ret = +(ret).toFixed(1) itemFindRange: -> ret = Math.floor(level/10) * 100 ret += 100 if ((level % 10) > 8) ret } properties: [ { name: "AutoRenew", values: ["No", "Yes"]} ] f = name: "Instructor" gid: 12 type: "Guild NPC" properties: {} tiles: [ 0, 0, 0, 0, 0, 0, f, 0, 44, 0, 0, 0, 0, 0, 0, 0, 44, 0, 44, 0, 0, 0, 0, 0, 0 ] module.exports = exports = Academy
171457
GuildBuilding = require "../GuildBuilding" `/** * The Academy affects the capability of your minor permanent buffs as well as the major buffs you can purchase for a limited time. * * @name Academy * @category Buildings * @package Guild * @cost {level-up} 15000 (if level <= 100) * @property AutoRenew (Yes/No; whether or not to auto renew buffs upon expiration) * @size {md} */` class Academy extends GuildBuilding @size = Academy::size = "md" @desc = Academy::desc = "Upgrade this building to make your buffs better and get some permanent ones!" @levelupCost = Academy::levelupCost = (level) -> if level > 100 then level * (50000 + (25000*Math.floor level/100)) else 15000 @getStatEffects: (level) -> { strPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 1) ret = +(ret).toFixed(1) intPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 2) ret = +(ret).toFixed(1) conPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 3) ret = +(ret).toFixed(1) wisPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 4) ret = +(ret).toFixed(1) dexPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 5) ret = +(ret).toFixed(1) agiPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 6) ret = +(ret).toFixed(1) goldPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 7) ret = +(ret).toFixed(1) xpPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 7) ret = +(ret).toFixed(1) itemFindRange: -> ret = Math.floor(level/10) * 100 ret += 100 if ((level % 10) > 8) ret } properties: [ { name: "AutoRenew", values: ["No", "Yes"]} ] f = name: "<NAME>" gid: 12 type: "Guild NPC" properties: {} tiles: [ 0, 0, 0, 0, 0, 0, f, 0, 44, 0, 0, 0, 0, 0, 0, 0, 44, 0, 44, 0, 0, 0, 0, 0, 0 ] module.exports = exports = Academy
true
GuildBuilding = require "../GuildBuilding" `/** * The Academy affects the capability of your minor permanent buffs as well as the major buffs you can purchase for a limited time. * * @name Academy * @category Buildings * @package Guild * @cost {level-up} 15000 (if level <= 100) * @property AutoRenew (Yes/No; whether or not to auto renew buffs upon expiration) * @size {md} */` class Academy extends GuildBuilding @size = Academy::size = "md" @desc = Academy::desc = "Upgrade this building to make your buffs better and get some permanent ones!" @levelupCost = Academy::levelupCost = (level) -> if level > 100 then level * (50000 + (25000*Math.floor level/100)) else 15000 @getStatEffects: (level) -> { strPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 1) ret = +(ret).toFixed(1) intPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 2) ret = +(ret).toFixed(1) conPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 3) ret = +(ret).toFixed(1) wisPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 4) ret = +(ret).toFixed(1) dexPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 5) ret = +(ret).toFixed(1) agiPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 6) ret = +(ret).toFixed(1) goldPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 7) ret = +(ret).toFixed(1) xpPercent: -> ret = Math.floor(level/10) * 0.1 ret += 0.1 if ((level % 10) > 7) ret = +(ret).toFixed(1) itemFindRange: -> ret = Math.floor(level/10) * 100 ret += 100 if ((level % 10) > 8) ret } properties: [ { name: "AutoRenew", values: ["No", "Yes"]} ] f = name: "PI:NAME:<NAME>END_PI" gid: 12 type: "Guild NPC" properties: {} tiles: [ 0, 0, 0, 0, 0, 0, f, 0, 44, 0, 0, 0, 0, 0, 0, 0, 44, 0, 44, 0, 0, 0, 0, 0, 0 ] module.exports = exports = Academy
[ { "context": " Joi.string().required().description('The username signed up with')\n password: Joi.string().required().d", "end": 5694, "score": 0.5568745732307434, "start": 5680, "tag": "USERNAME", "value": "signed up with" }, { "context": " password: Joi.string().requir...
lib/routes/user.coffee
ethanmick/fastchat-server
7
'use strict' # # FastChat # 2015 # User = require '../model/user' ObjectId = require('mongoose-q')().Types.ObjectId multiparty = require 'multiparty' Boom = require 'boom' Joi = require 'joi' # POST /login # This is an alternative implementation that uses a custom callback to # acheive the same functionality. login = (req, reply)-> {username, password} = req.payload User.findByLowercaseUsername(username).then (user)-> [user, user.comparePassword(password)] .spread (user, matched)-> token = user.generateRandomToken() user.accessToken.push token [token, user.saveQ()] .spread (token)-> reply(access_token: token) .fail(reply) .done() # POST /user register = (req, reply)-> User.register(req.payload?.username, req.payload?.password) .then (user)-> reply(user).code(201) .fail(reply) .done() # GET /user profile = (req, reply)-> {user} = req.auth.credentials User.findOne(_id: user.id) .populate('groups', 'name') .populate('leftGroups', 'name') .populate('groupSettings') .execQ() .then (user)-> reply(user) .fail(reply) .done() logout = (req, reply)-> {user, token} = req.auth.credentials user.logout(token, req.query.all) .then -> reply({}) .fail(reply) .done() uploadAvatar = (req, reply)-> {user} = req.auth.credentials user.uploadAvatar(req.payload.avatar).then -> reply({}) .fail(reply) .done() getAvatar = (req, reply)-> userId = new ObjectId(req.params.id) User.findOneQ(_id: userId) .then (user)-> throw Boom.notFound() unless user user.getAvatar() .spread (meta, data)-> reply(data).type(meta) .fail(reply) .done() module.exports = [ { method: 'POST' path: '/login' config: handler: login auth: false description: 'Logs a user in.' notes: 'Given a username and unhashed password, logs in the user.' tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } ] validate: payload: username: ( Joi.string() .min(4).max(100).lowercase().trim().regex(/^[a-zA-Z0-9-_.]+$/).required() ) password: ( Joi.string().min(1).max(100).required() ) response: schema: Joi.object({ access_token: Joi.string().required().description("The Access Token used for authentication. The client should store this and keep it safe and secret").example('token') }) } { method: 'POST' path: '/user' config: handler: register auth: false description: 'Registers a user' notes: "The starting place for users. This endpoint registers a new user and sets the default values on the profile. This endpoint does *not* log them in, so you will have to hit /login" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 409 message: 'Conflict. The username is already taken.' } ] validate: payload: username: ( Joi.string() .min(4).max(100).lowercase().trim().regex(/^[a-zA-Z0-9-_.]+$/).required() ) password: ( Joi.string().min(1).max(100).required() ) response: schema: Joi.object({ username: Joi.string().required().description('The username signed up with') password: Joi.string().required().description("The user's hashed password") _id: Joi.required().description("The unique id for the user") avatar: Joi.optional() groupSettings: Joi.array().length(0).required() devices: Joi.array().length(0).required() leftGroups: Joi.array().items(Joi.string()).length(0).required() groups: Joi.array().length(0).required() accessToken: Joi.array().length(0).required() }).meta({ className: 'User' }).unknown() } { method: 'GET' path: '/user' config: handler: profile description: 'Gets the user profile.' notes: "Gets the currently logged in user's profile. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token}. The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } ] validate: query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() response: schema: Joi.object({ username: Joi.string().required().description('The username signed up with') password: Joi.string().required().description("The user's hashed password") _id: Joi.required().description("The unique id for the user") avatar: Joi.optional() groupSettings: Joi.array().required() devices: Joi.array().required() leftGroups: Joi.array().items( Joi.object( _id: Joi.required() name: Joi.optional() ).unknown() ).required() groups: Joi.array().required() accessToken: Joi.array().required() }).meta({ className: 'User' }).unknown() } { method: 'DELETE' path: '/logout' config: handler: logout description: 'Logs the user out' notes: "Logs the user out. Optionally logs the user out of all devices, by clearing out all session tokens. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token}. The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } ] validate: query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) all: Joi.boolean() headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() response: schema: Joi.object({}) } { method: 'POST' path: '/user/{id}/avatar' config: payload: output: 'file' handler: uploadAvatar description: 'Uploads an avatar for the user.' notes: "The avatar must be an image, and it will be shown in a smaller scale, so uploading large images will not help. The images will be cropped into a circle on some platforms. This work is done client side. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token} The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': payloadType: 'form' responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } { code: 501 message: "Not Implemented. This indicates that the server does not have acess to the AWS_KEY and AWS_SECRET, or was configured incorrectly." } ] validate: params: id: Joi.string().regex(/^[0-9a-f]{24}$/) query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() payload: avatar: Joi.required().meta(swaggerType: 'file') response: schema: Joi.object({}) } { method: 'GET' path: '/user/{id}/avatar' config: handler: getAvatar description: 'Gets the Avatar for the user' notes: "For protection, the avatar is stored on AWS, but must be accessed through the server with the key and secret. This means that the information is not public. This route returns the binary data for the image. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token} The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } { code: 404 message: "Not Found. Thrown when you try and access a user's avatar when you are not in any groups with that user." } { code: 501 message: "Not Implemented. This indicates that the server does not have acess to the AWS_KEY and AWS_SECRET, or was configured incorrectly." } ] validate: params: id: Joi.string().regex(/^[0-9a-f]{24}$/) query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() } ]
171520
'use strict' # # FastChat # 2015 # User = require '../model/user' ObjectId = require('mongoose-q')().Types.ObjectId multiparty = require 'multiparty' Boom = require 'boom' Joi = require 'joi' # POST /login # This is an alternative implementation that uses a custom callback to # acheive the same functionality. login = (req, reply)-> {username, password} = req.payload User.findByLowercaseUsername(username).then (user)-> [user, user.comparePassword(password)] .spread (user, matched)-> token = user.generateRandomToken() user.accessToken.push token [token, user.saveQ()] .spread (token)-> reply(access_token: token) .fail(reply) .done() # POST /user register = (req, reply)-> User.register(req.payload?.username, req.payload?.password) .then (user)-> reply(user).code(201) .fail(reply) .done() # GET /user profile = (req, reply)-> {user} = req.auth.credentials User.findOne(_id: user.id) .populate('groups', 'name') .populate('leftGroups', 'name') .populate('groupSettings') .execQ() .then (user)-> reply(user) .fail(reply) .done() logout = (req, reply)-> {user, token} = req.auth.credentials user.logout(token, req.query.all) .then -> reply({}) .fail(reply) .done() uploadAvatar = (req, reply)-> {user} = req.auth.credentials user.uploadAvatar(req.payload.avatar).then -> reply({}) .fail(reply) .done() getAvatar = (req, reply)-> userId = new ObjectId(req.params.id) User.findOneQ(_id: userId) .then (user)-> throw Boom.notFound() unless user user.getAvatar() .spread (meta, data)-> reply(data).type(meta) .fail(reply) .done() module.exports = [ { method: 'POST' path: '/login' config: handler: login auth: false description: 'Logs a user in.' notes: 'Given a username and unhashed password, logs in the user.' tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } ] validate: payload: username: ( Joi.string() .min(4).max(100).lowercase().trim().regex(/^[a-zA-Z0-9-_.]+$/).required() ) password: ( Joi.string().min(1).max(100).required() ) response: schema: Joi.object({ access_token: Joi.string().required().description("The Access Token used for authentication. The client should store this and keep it safe and secret").example('token') }) } { method: 'POST' path: '/user' config: handler: register auth: false description: 'Registers a user' notes: "The starting place for users. This endpoint registers a new user and sets the default values on the profile. This endpoint does *not* log them in, so you will have to hit /login" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 409 message: 'Conflict. The username is already taken.' } ] validate: payload: username: ( Joi.string() .min(4).max(100).lowercase().trim().regex(/^[a-zA-Z0-9-_.]+$/).required() ) password: ( Joi.string().min(1).max(100).required() ) response: schema: Joi.object({ username: Joi.string().required().description('The username signed up with') password: Joi.string().required().description("The user's hashed password") _id: Joi.required().description("The unique id for the user") avatar: Joi.optional() groupSettings: Joi.array().length(0).required() devices: Joi.array().length(0).required() leftGroups: Joi.array().items(Joi.string()).length(0).required() groups: Joi.array().length(0).required() accessToken: Joi.array().length(0).required() }).meta({ className: 'User' }).unknown() } { method: 'GET' path: '/user' config: handler: profile description: 'Gets the user profile.' notes: "Gets the currently logged in user's profile. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token}. The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } ] validate: query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() response: schema: Joi.object({ username: Joi.string().required().description('The username signed up with') password: Joi.string().required().description("<PASSWORD>") _id: Joi.required().description("The unique id for the user") avatar: Joi.optional() groupSettings: Joi.array().required() devices: Joi.array().required() leftGroups: Joi.array().items( Joi.object( _id: Joi.required() name: Joi.optional() ).unknown() ).required() groups: Joi.array().required() accessToken: Joi.array().required() }).meta({ className: 'User' }).unknown() } { method: 'DELETE' path: '/logout' config: handler: logout description: 'Logs the user out' notes: "Logs the user out. Optionally logs the user out of all devices, by clearing out all session tokens. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token}. The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } ] validate: query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) all: Joi.boolean() headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() response: schema: Joi.object({}) } { method: 'POST' path: '/user/{id}/avatar' config: payload: output: 'file' handler: uploadAvatar description: 'Uploads an avatar for the user.' notes: "The avatar must be an image, and it will be shown in a smaller scale, so uploading large images will not help. The images will be cropped into a circle on some platforms. This work is done client side. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token} The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': payloadType: 'form' responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } { code: 501 message: "Not Implemented. This indicates that the server does not have acess to the AWS_KEY and AWS_SECRET, or was configured incorrectly." } ] validate: params: id: Joi.string().regex(/^[0-9a-f]{24}$/) query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() payload: avatar: Joi.required().meta(swaggerType: 'file') response: schema: Joi.object({}) } { method: 'GET' path: '/user/{id}/avatar' config: handler: getAvatar description: 'Gets the Avatar for the user' notes: "For protection, the avatar is stored on AWS, but must be accessed through the server with the key and secret. This means that the information is not public. This route returns the binary data for the image. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token} The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } { code: 404 message: "Not Found. Thrown when you try and access a user's avatar when you are not in any groups with that user." } { code: 501 message: "Not Implemented. This indicates that the server does not have acess to the AWS_KEY and AWS_SECRET, or was configured incorrectly." } ] validate: params: id: Joi.string().regex(/^[0-9a-f]{24}$/) query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() } ]
true
'use strict' # # FastChat # 2015 # User = require '../model/user' ObjectId = require('mongoose-q')().Types.ObjectId multiparty = require 'multiparty' Boom = require 'boom' Joi = require 'joi' # POST /login # This is an alternative implementation that uses a custom callback to # acheive the same functionality. login = (req, reply)-> {username, password} = req.payload User.findByLowercaseUsername(username).then (user)-> [user, user.comparePassword(password)] .spread (user, matched)-> token = user.generateRandomToken() user.accessToken.push token [token, user.saveQ()] .spread (token)-> reply(access_token: token) .fail(reply) .done() # POST /user register = (req, reply)-> User.register(req.payload?.username, req.payload?.password) .then (user)-> reply(user).code(201) .fail(reply) .done() # GET /user profile = (req, reply)-> {user} = req.auth.credentials User.findOne(_id: user.id) .populate('groups', 'name') .populate('leftGroups', 'name') .populate('groupSettings') .execQ() .then (user)-> reply(user) .fail(reply) .done() logout = (req, reply)-> {user, token} = req.auth.credentials user.logout(token, req.query.all) .then -> reply({}) .fail(reply) .done() uploadAvatar = (req, reply)-> {user} = req.auth.credentials user.uploadAvatar(req.payload.avatar).then -> reply({}) .fail(reply) .done() getAvatar = (req, reply)-> userId = new ObjectId(req.params.id) User.findOneQ(_id: userId) .then (user)-> throw Boom.notFound() unless user user.getAvatar() .spread (meta, data)-> reply(data).type(meta) .fail(reply) .done() module.exports = [ { method: 'POST' path: '/login' config: handler: login auth: false description: 'Logs a user in.' notes: 'Given a username and unhashed password, logs in the user.' tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } ] validate: payload: username: ( Joi.string() .min(4).max(100).lowercase().trim().regex(/^[a-zA-Z0-9-_.]+$/).required() ) password: ( Joi.string().min(1).max(100).required() ) response: schema: Joi.object({ access_token: Joi.string().required().description("The Access Token used for authentication. The client should store this and keep it safe and secret").example('token') }) } { method: 'POST' path: '/user' config: handler: register auth: false description: 'Registers a user' notes: "The starting place for users. This endpoint registers a new user and sets the default values on the profile. This endpoint does *not* log them in, so you will have to hit /login" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 409 message: 'Conflict. The username is already taken.' } ] validate: payload: username: ( Joi.string() .min(4).max(100).lowercase().trim().regex(/^[a-zA-Z0-9-_.]+$/).required() ) password: ( Joi.string().min(1).max(100).required() ) response: schema: Joi.object({ username: Joi.string().required().description('The username signed up with') password: Joi.string().required().description("The user's hashed password") _id: Joi.required().description("The unique id for the user") avatar: Joi.optional() groupSettings: Joi.array().length(0).required() devices: Joi.array().length(0).required() leftGroups: Joi.array().items(Joi.string()).length(0).required() groups: Joi.array().length(0).required() accessToken: Joi.array().length(0).required() }).meta({ className: 'User' }).unknown() } { method: 'GET' path: '/user' config: handler: profile description: 'Gets the user profile.' notes: "Gets the currently logged in user's profile. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token}. The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } ] validate: query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() response: schema: Joi.object({ username: Joi.string().required().description('The username signed up with') password: Joi.string().required().description("PI:PASSWORD:<PASSWORD>END_PI") _id: Joi.required().description("The unique id for the user") avatar: Joi.optional() groupSettings: Joi.array().required() devices: Joi.array().required() leftGroups: Joi.array().items( Joi.object( _id: Joi.required() name: Joi.optional() ).unknown() ).required() groups: Joi.array().required() accessToken: Joi.array().required() }).meta({ className: 'User' }).unknown() } { method: 'DELETE' path: '/logout' config: handler: logout description: 'Logs the user out' notes: "Logs the user out. Optionally logs the user out of all devices, by clearing out all session tokens. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token}. The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } ] validate: query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) all: Joi.boolean() headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() response: schema: Joi.object({}) } { method: 'POST' path: '/user/{id}/avatar' config: payload: output: 'file' handler: uploadAvatar description: 'Uploads an avatar for the user.' notes: "The avatar must be an image, and it will be shown in a smaller scale, so uploading large images will not help. The images will be cropped into a circle on some platforms. This work is done client side. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token} The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': payloadType: 'form' responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } { code: 501 message: "Not Implemented. This indicates that the server does not have acess to the AWS_KEY and AWS_SECRET, or was configured incorrectly." } ] validate: params: id: Joi.string().regex(/^[0-9a-f]{24}$/) query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() payload: avatar: Joi.required().meta(swaggerType: 'file') response: schema: Joi.object({}) } { method: 'GET' path: '/user/{id}/avatar' config: handler: getAvatar description: 'Gets the Avatar for the user' notes: "For protection, the avatar is stored on AWS, but must be accessed through the server with the key and secret. This means that the information is not public. This route returns the binary data for the image. This route requires the user's access token, either as a query param, or a header, but not both. The header format must be: authorization: Bearer {token} The query format must be: access_token={token}" tags: ['api'] plugins: 'hapi-swagger': responseMessages: [ { code: 400 message: 'Bad Request. Occurs when you fail to give the required data.' } { code: 401 message: 'Unauthorized' } { code: 404 message: "Not Found. Thrown when you try and access a user's avatar when you are not in any groups with that user." } { code: 501 message: "Not Implemented. This indicates that the server does not have acess to the AWS_KEY and AWS_SECRET, or was configured incorrectly." } ] validate: params: id: Joi.string().regex(/^[0-9a-f]{24}$/) query: access_token: Joi.string().min(1).lowercase().trim().when( '$headers.authorization', { is: Joi.exist(), otherwise: Joi.forbidden() }) headers: Joi.object({ authorization: Joi.string().trim().regex(/^Bearer\s[a-zA-Z0-9]+$/).when( '$query.access_token', { is: Joi.forbidden(), otherwise: Joi.exist() } ) }).unknown() } ]
[ { "context": "h/callback&hub.lease_seconds=864000&hub.secret=hexweaver\"\n headers: {\n \"Client-ID\": ke", "end": 4830, "score": 0.42325544357299805, "start": 4828, "tag": "KEY", "value": "we" }, { "context": " json: true\n body: {\n nick: user...
motorbotEventHandler.coffee
motorlatitude/MotorBot
4
Table = require 'cli-table' keys = require '/var/www/motorbot/keys.json' apiai = require('apiai') apiai = apiai(keys.apiai) #AI for !talk method fs = require 'fs' req = require 'request' moment = require 'moment' cheerio = require 'cheerio' turndown = require 'turndown' class motorbotEventHandler constructor: (@app, @client) -> @setUpEvents() @already_announced = false @challenged = {} @challenger = {} setupSoundboard: (guild_id, filepath, volume = 1) -> self = @ if !self.app.soundboard[guild_id] self.app.client.voiceConnections[guild_id].playFromFile(filepath).then((audioPlayer) -> self.app.soundboard[guild_id] = audioPlayer self.app.org_volume = 0.5 #set default self.app.soundboard[guild_id].on('streamDone', () -> self.app.debug("StreamDone Received") delete self.app.soundboard[guild_id] if self.app.musicPlayers[guild_id] self.app.musicPlayers[guild_id].setVolume(self.app.org_volume) #set back to original volume of music self.app.musicPlayers[guild_id].play() ) self.app.soundboard[guild_id].on('ready', () -> if self.app.musicPlayers[guild_id] self.app.org_volume = self.app.musicPlayers[guild_id].getVolume() self.app.musicPlayers[guild_id].pause() else self.app.soundboard[guild_id].setVolume(volume) self.app.soundboard[guild_id].play() ) self.app.musicPlayers[guild_id].on("paused", () -> if self.app.soundboard[guild_id] self.app.soundboard[guild_id].setVolume(volume) self.app.soundboard[guild_id].play() ) ) else self.app.debug("Soundboard already playing") toTitleCase: (str) -> return str.replace(/\w\S*/g, (txt) -> return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() ); patchListener: (game) -> self = @ if game == "ow" patches = {} p = [] req({ url: "https://playoverwatch.com/en-us/game/patch-notes/pc/" }, (error, httpResponse, body) -> console.log "Overwatch Request Complete" if error then console.log error $ = cheerio.load(body) $(".patch-notes-body").each((i, element) -> p[i] = $(this).attr("id") console.log p[i] desc = $(this).html().replace(/<\/h2>/,'sdfgpoih345e87th').split('sdfgpoih345e87th')[1] patches[$(this).attr("id")] = { patch_id: $(this).attr("id"), title: $(this).find("h1").text(), sub_title: $(this).find("h2").eq(0).text(), desc: desc } ) #find all logged patches patchCollection = self.app.database.collection("patches") patchCollection.find({patch_id: {"$in": p}}).toArray((err, results) -> if err then return console.log err if results[0] console.log "found patches in db" for result in results for patch_id, patch of patches if result.patch_id == patch_id delete patches[patch_id] #remove patch from patches array #process any left patches console.log "processing any left patches" td = new turndown() database_patches = [] for key, new_patch of patches d = new Date() database_patches.push(new_patch) embed_element = { title: self.toTitleCase(new_patch.title), url: "https://playoverwatch.com/en-us/game/patch-notes/pc/#" + new_patch.patch_id, description: new_patch.sub_title + "\n------\n" + td.turndown(new_patch.desc).substring(0, 1000) + "\n\n[Read More](https://playoverwatch.com/en-us/game/patch-notes/pc/#" + new_patch.patch_id+")", color: 16751872, timestamp: d.toISOString(), type: "rich", "footer": { "icon_url": "https://motorbot.io/overwatch_sm.png", "text": "Patch Notification" }, thumbnail: { url: "https://motorbot.io/overwatch_sm.png" } } console.log embed_element self.app.client.channels["438307738250903553"].sendMessage("", { embed: embed_element }) if database_patches.length > 0 patchCollection.insertMany(database_patches) ) ) twitchSubscribeToStream: (user_id) -> # Subscribe to Twitch Webhook Services self = @ req.post({ url: "https://api.twitch.tv/helix/webhooks/hub?hub.mode=subscribe&hub.topic=https://api.twitch.tv/helix/streams?user_id="+user_id+"&hub.callback=https://motorbot.io/twitch/callback&hub.lease_seconds=864000&hub.secret=hexweaver" headers: { "Client-ID": keys.twitch }, json: true }, (error, httpResponse, body) -> self.app.debug("Twitch Webhook Subscription Response Code: "+httpResponse.statusCode, "debug") if error self.app.debug("subscription error to webhook", "error") console.log error ) changeNickname: (guild_id, user_id, user_name, karma) -> # doesn't work for same roles and roles above bots current role ###req({ url: "https://discordapp.com/api/guilds/"+guild_id+"/members/"+user_id, method: "PATCH" headers: { "Authorization": "Bot "+keys.token }, json: true body: { nick: user_name+" ("+karma+")" } }, (err, httpResponse, body) -> if err then console.log err console.log "request complete" console.log body )### rockPaperScissors: (msg, author, choice) -> self = @ compareRPS = (challenged, challengedID, challenger, challengerID, cb) -> outcome = { winner: undefined, challenged: { id: challengedID win: true }, challenger: { id: challengerID win: true } } if challenged.choice == "rock" if challenger.choice == "paper" outcome.challenger.win = true outcome.challenged.win = false outcome.winner = challengerID if challenger.choice == "rock" outcome.challenger.win = true outcome.challenged.win = true outcome.winner = "tie" if challenger.choice == "scissors" outcome.challenger.win = false outcome.challenged.win = true outcome.winner = challengedID else if challenged.choice == "paper" if challenger.choice == "paper" outcome.challenger.win = true outcome.challenged.win = true outcome.winner = "tie" if challenger.choice == "rock" outcome.challenger.win = false outcome.challenged.win = true outcome.winner = challengedID if challenger.choice == "scissors" outcome.challenger.win = true outcome.challenged.win = false outcome.winner = challengerID else if challenged.choice == "scissors" if challenger.choice == "paper" outcome.challenger.win = false outcome.challenged.win = true outcome.winner = challengedID if challenger.choice == "rock" outcome.challenger.win = true outcome.challenged.win = false outcome.winner = challengerID if challenger.choice == "scissors" outcome.challenger.win = true outcome.challenged.win = true outcome.winner = "tie" cb(outcome) if self.challenged[author] self.challenged[author].choice = choice challenger = self.challenger[self.challenged[author].challenger] if self.challenger[self.challenged[author].challenger].choice #both users have made their choice, compare compareRPS(self.challenged[author], author, self.challenger[self.challenged[author].challenger], self.challenged[author].challenger, (outcome) -> if outcome.winner == "tie" challenger.channel.sendMessage("The challenge between <@"+author+"> and <@"+self.challenged[author].challenger+"> resulted in a draw, fight again?") delete self.challenger[self.challenged[author].challenger] delete self.challenged[author] else if self.challenged[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenged[outcome.winner].challenger+">") delete self.challenger[self.challenged[outcome.winner].challenger] delete self.challenged[outcome.winner] else if self.challenger[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenger[outcome.winner].challenged+">") delete self.challenged[self.challenger[outcome.winner].challenged] delete self.challenger[outcome.winner] ) if self.challenger[author] self.challenger[author].choice = choice challenger = self.challenger[author] if self.challenged[self.challenger[author].challenged].choice #both users have made their choice, compare compareRPS(self.challenged[self.challenger[author].challenged], self.challenger[author].challenged, self.challenger[author], author, (outcome) -> if outcome.winner == "tie" challenger.channel.sendMessage("The challenge between <@"+author+"> and <@"+self.challenger[author].challenged+"> resulted in a draw, fight again?") delete self.challenged[self.challenger[author].challenged] delete self.challenger[author] else if self.challenged[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenged[outcome.winner].challenger+">") delete self.challenger[self.challenged[outcome.winner].challenger] delete self.challenged[outcome.winner] else if self.challenger[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenger[outcome.winner].challenged+">") delete self.challenged[self.challenger[outcome.winner].challenged] delete self.challenger[outcome.winner] ) setUpEvents: () -> self = @ self.twitchSubscribeToStream(22032158) #motorlatitude self.twitchSubscribeToStream(26752266) #mutme self.twitchSubscribeToStream(24991333) #imaqtpie self.twitchSubscribeToStream(22510310) #GDQ #League LCS self.twitchSubscribeToStream(36029255) #RiotGames self.twitchSubscribeToStream(36794584) #RiotGames2 @client.on("ready", () -> self.app.debug("Ready!") ) y = 0 @client.on("guildCreate", (server) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if server.id == "130734377066954752" self.client.channels["432351112616738837"].sendMessage(":x: <@&443191635657097217>","embed": { "title": "MOTORBOT RESTARTED" "description": "Motorbot had to restart either through manual input or due to a fatal error occurring, please consult error logs in console if the latter.", "color": 16724787 }) #self.client.channels["432351112616738837"].sendMessage(time + " Joined Guild: "+server.name+" ("+server.presences.length+" online / "+(parseInt(server.member_count)-server.presences.length)+" offline)") if y == 0 #Listen for patches #setInterval( () -> # self.patchListener("ow") #, 3600000) y = 1 ) @client.on("voiceUpdate_Speaking", (data) -> self.app.websocket.broadcast(JSON.stringify({type: "VOICE_UPDATE_SPEAKING", d:data})) ) voiceStates = {} @client.on("voiceChannelUpdate", (data) -> if data.user_id == '169554882674556930' if data.channel self.app.websocket.broadcast(JSON.stringify({type: "VOICE_UPDATE", d:{status:"JOIN", channel: data.channel.name, channel_id: data.channel.id, channel_obj: data}}, (key, value) -> if key == "client" return undefined else return value )) else self.app.websocket.broadcast(JSON.stringify({type: "VOICE_UPDATE", d:{status:"LEAVE", channel: undefined, channel_id: undefined, channel_obj: data}}, (key, value) -> if key == "client" return undefined else return value )) d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if data.channel if voiceStates[data.user_id] if voiceStates[data.user_id].channel #previously in channel hence channel voice state change #voice state trigger if data.deaf && !voiceStates[data.user_id].deaf #deafened from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> was server deafened in the `"+data.channel.name+"` voice channel") if data.mute && !voiceStates[data.user_id].mute #muted from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> was server muted in the `"+data.channel.name+"` voice channel") if data.self_deaf && !voiceStates[data.user_id].self_deaf #user has deafened himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has deafened them self in the `"+data.channel.name+"` voice channel") if data.self_mute && !voiceStates[data.user_id].self_mute #user has muted himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has muted them self in the `"+data.channel.name+"` voice channel") #voice state trigger reverse if !data.deaf && voiceStates[data.user_id].deaf #undeafened from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer server deafened in the `"+data.channel.name+"` voice channel") if !data.mute && voiceStates[data.user_id].mute #unmuted from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer server muted in the `"+data.channel.name+"` voice channel") if !data.self_deaf && voiceStates[data.user_id].self_deaf #user has undeafened himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer deafened in the `"+data.channel.name+"` voice channel") if !data.self_mute && voiceStates[data.user_id].self_mute #user has unmuted himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer muted in the `"+data.channel.name+"` voice channel") else #newly joined self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has joined the `"+data.channel.name+"` voice channel") else self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has joined the `"+data.channel.name+"` voice channel") else self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has left a voice channel") voiceStates[data.user_id] = data ) userStatus = {} @client.on("status", (user_id,status,game,extra_info) -> if extra_info.guild_id == "130734377066954752" #only listening for presence updates in the KTJ guild for now to avoid duplicates across multiple channels if game self.app.debug(user_id+"'s status ("+status+") has changed; "+game.name+"("+game.type+")","notification") else self.app.debug(user_id+"'s status ("+status+") has changed", "notification") d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " gameText = "" statusText = "" additionalString = "" if game extra_info["last_game_update"] = new Date().getTime() if userStatus[user_id] if userStatus[user_id].game if userStatus[user_id].game.name == game.name extra_info["last_game_update"] = userStatus[user_id].last_game_update if game.details additionalString += "\n"+time+" *"+game.details+"*" if game.state additionalString += "\n"+time+" "+game.state if userStatus[user_id] if userStatus[user_id].status == status #no status change, only game update if !game && userStatus[user_id].game if userStatus[user_id].game.type == 0 statusText = " has stopped playing **"+userStatus[user_id].game.name+"** after "+(moment.unix(userStatus[user_id].last_game_update/1000).fromNow()).replace(" ago","") else if userStatus[user_id].game.type == 1 statusText = " has stopped streaming **"+userStatus[user_id].game.name+"** after "+(moment.unix(userStatus[user_id].last_game_update/1000).fromNow()).replace(" ago","") else if userStatus[user_id].game.type == 2 statusText = " has stopped listening to **"+userStatus[user_id].game.name+"** after "+(moment.unix(userStatus[user_id].last_game_update/1000).fromNow()).replace(" ago","") extra_info["last_update"] = userStatus[user_id].last_update else #status change statusText = " was `"+userStatus[user_id].status+"` for "+(moment.unix(userStatus[user_id].last_update/1000).fromNow()).replace(" ago","")+" and is now `"+status+"`" extra_info["last_update"] = new Date().getTime() else #we don't know previous status so assume status change statusText = "'s status has changed to `"+status+"`" extra_info["last_update"] = new Date().getTime() if game && game.type == 0 gameText = " is playing **"+game.name+"**" else if game && game.type == 1 gameText = " is streaming **"+game.name+"**" else if game && game.type == 2 gameText = " is listening to **"+game.name+"**" else gameText = "" #status change if game if userStatus[user_id] if userStatus[user_id].game if userStatus[user_id].game.name == game.name && game.type == 0 gameText = " game presence update :video_game: " else if userStatus[user_id].game.name == game.name && game.type == 2 gameText = " is switching song" someText = if(gameText != "" && statusText != "") then " and"+gameText else gameText if game && game.type == 2 additionalString = "" if game.details additionalString += "\n"+time+" **"+game.details+"**" if game.state additionalString += "\n"+time+" by "+game.state if game.assets.large_text additionalString += "\n"+time+" on "+game.assets.large_text console.log game desc = time+"<@"+user_id+">"+statusText+someText+additionalString thumbnail_url = "" if game.assets if game.assets.large_image thumbnail_id = game.assets.large_image.replace("spotify:","") thumbnail_url = "https://i.scdn.co/image/"+thumbnail_id console.log thumbnail_url self.client.channels["432351112616738837"].sendMessage("","embed": { "description": desc, "color": 2021216, "thumbnail": { "url": thumbnail_url } }) else if statusText == "" && someText == "" && additionalString == "" self.client.channels["432351112616738837"].sendMessage(time+"<@"+user_id+"> is `invisible` and a status refresh event occurred") else self.client.channels["432351112616738837"].sendMessage(time+"<@"+user_id+">"+statusText+someText+additionalString) userStatus[user_id] = extra_info ) @client.on("reaction", (type, data) -> if data.user_id != "169554882674556930" d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if data.emoji.name == "downvote" || data.emoji.name == "upvote" if type == "add" self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has added the `"+data.emoji.name+"` reaction to message `"+data.message_id+"` in channel <#"+data.channel_id+">") #find message for user self.client.channels[data.channel_id].getMessage(data.message_id).then((message) -> author_id = message.author.id karmaCollection = self.app.database.collection("karma_points") karmaCollection.find({"author": author_id}).toArray((err, results) -> if err then return console.log err if results[0] author_karma = results[0].karma else author_karma = 0 if data.emoji.name == "upvote" author_karma += 1 else if data.emoji.name == "downvote" author_karma -= 1 karma_obj = { author: author_id, karma: author_karma } self.client.channels["432351112616738837"].sendMessage(time+"<@"+author_id+"> now has "+author_karma+" karma") karmaCollection.update({author: author_id}, karma_obj, {upsert: true}) self.changeNickname(message.guild_id , author_id, message.author.username, author_karma) ) ).catch((err) -> console.log "Couldn't retrieve message" console.log err ) else if type == "remove" self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has removed the `"+data.emoji.name+"` reaction on message `"+data.message_id+"` in channel <#"+data.channel_id+">") #find message for user self.client.channels[data.channel_id].getMessage(data.message_id).then((message) -> author_id = message.author.id karmaCollection = self.app.database.collection("karma_points") karmaCollection.find({"author": author_id}).toArray((err, results) -> if err then return console.log err if results[0] author_karma = results[0].karma else author_karma = 0 if data.emoji.name == "upvote" author_karma -= 1 else if data.emoji.name == "downvote" author_karma += 1 karma_obj = { author: author_id, karma: author_karma } self.client.channels["432351112616738837"].sendMessage(time+"<@"+author_id+"> now has "+author_karma+" karma") karmaCollection.update({author: author_id}, karma_obj, {upsert: true}) self.changeNickname(message.guild_id , author_id, message.author.username, author_karma) ) ).catch((err) -> console.log "Couldn't retrieve message" console.log err ) ) @client.on("message", (msg) -> #store all messages messageCollection = self.app.database.collection("messages") db_msg_obj = { id: msg.id, channel_id: msg.channel_id, guild_id: msg.guild_id, author: msg.author, content: msg.content, timestamp: msg.timestamp, edited_timestamp: msg.edited_timestamp, tts: msg.tts, mention_everyone: msg.mention_everyone, mentions: msg.mentions, mention_roles: msg.mention_roles, attachments: msg.attachments, embeds: msg.embeds, reactions: msg.reactions, nonce: msg.nonce, pinned: msg.pinned, webhook_id: msg.webhook_id } messageCollection.update({id: msg.id}, db_msg_obj, {upsert: true}) if msg.content.match(/^\!voice\sjoin/) channelName = msg.content.replace(/^\!voice\sjoin\s/,"") joined = false if channelName for channel in self.client.guilds[msg.guild_id].channels if channel.name == channelName && channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[msg.guild_id] = VoiceConnection ) joined = true break if !joined for channel in self.client.guilds[msg.guild_id].channels if channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[msg.guild_id] = VoiceConnection ) break else if msg.content.match(/^\!voice\s(.*?)\sjoin/) channelName = msg.content.replace(/^\!voice\s(.*?)\sjoin\s/,"") selected_guild_id = msg.content.match(/^\!voice\s(.*?)\sjoin/)[1] console.log msg.author joined = false if self.client.guilds[selected_guild_id] if channelName for channel in self.client.guilds[selected_guild_id].channels if channel.name == channelName && channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[selected_guild_id] = VoiceConnection ) joined = true break if !joined for channel in self.client.guilds[selected_guild_id].channels if channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[selected_guild_id] = VoiceConnection ) break else msg.channel.sendMessage("```diff\n- Unknown Server\n```") else if msg.content.match(/^\!voice\s(.*?)\sleave/) selected_guild_id = msg.content.match(/^\!voice\s(.*?)\sleave/)[1] if self.client.guilds[selected_guild_id] self.client.leaveVoiceChannel(selected_guild_id) else msg.channel.sendMessage("```diff\n- Unknown Server\n```") else if msg.content.match(/^!ban doug/gmi) msg.channel.sendMessage("If only I could :rolling_eyes: <@"+msg.author.id+">") else if msg.content.match(/^!kys/gmi) || msg.content.match(/kys/gmi) msg.channel.sendMessage("Calm down before you go and hurt someone <@"+msg.author.id+">") else if msg.content.match(/fight\sme(\sbro|)/gmi) || msg.content.match(/come\sat\sme(\sbro|)/gmi) msg.channel.sendMessage("(ง’̀-‘́)ง") else if msg.content == "!voice leave" self.client.leaveVoiceChannel(msg.guild_id) else if msg.content.match(/heads\sor\stails(\?|)/gmi) if Math.random() >= 0.5 msg.channel.sendMessage(":one: Heads <@"+msg.author.id+">") else msg.channel.sendMessage(":zero: Tails <@"+msg.author.id+">") else if msg.content.match(/\!random/) msg.channel.sendMessage("Random Number: "+(Math.round((Math.random()*100)))) else if msg.content == "!sb diddly" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/DootDiddly.mp3", 5) else if msg.content == "!sb pog" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/play of the game.mp3", 3) else if msg.content == "!sb kled" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Kled.mp3", 3) else if msg.content == "!sb wonder" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/wonder.mp3", 3) else if msg.content == "!sb 1" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/1.mp3", 3) else if msg.content == "!sb 2" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/2.mp3", 3) else if msg.content == "!sb 3" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/3.mp3", 3) else if msg.content == "!sb affirmative" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/affirmative.mp3", 3) else if msg.content == "!sb gp" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/gp.mp3", 3) else if msg.content == "!sb justice" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/justice 3.mp3", 3) else if msg.content == "!sb speed boost" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/speed boost.mp3", 3) else if msg.content == "!sb stop the payload" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/stop the payload.mp3", 3) else if msg.content == "!sb wsr" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/wsr.mp3", 2) else if msg.content == "!sb drop" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/drop_beat.wav", 3) else if msg.content == "!sb tears" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/bings_tears.wav", 3) else if msg.content == "!sb balanced" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/balancing_teams.wav", 3) else if msg.content == "!sb ez mode" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/D.Va_-_Easy_mode.ogg", 3) else if msg.content == "!sb enemy" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Enemy Slain.mp3", 2) else if msg.content == "!sb victory" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Victory.mp3", 2) else if msg.content == "!sb defeat" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Defeat.mp3", 2) else if msg.content == "!sb pentakill" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Pentakill1.mp3", 2) else if msg.content == "!sb happy birthday adz" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/happybirthdayadz.wav", 3) else if msg.content == "!sb airport" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/En-BAW-LHR-boarding.mp3", 2) else if msg.content == "!sb airport de" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Ge-DLH-FRA-boarding.mp3", 2) else if msg.content == "!sb stop" if self.app.soundboard[msg.guild_id] self.app.soundboard[msg.guild_id].stop() delete self.app.soundboard[msg.guild_id] else if msg.content == "!sb help" msg.channel.sendMessage("",{ embed: { title: "Soundboard Commands", description: "**!sb diddly** - Doot Diddly\n **!sb pog** - Play Of The Game\n **!sb kled** - I Find Courage Unpredictable...\n **!sb wonder** - And I sometimes wonder...\n **!sb 1** - Overwatch Announcer: One\n **!sb 2** - Overwatch Announcer: Two\n **!sb 3** - Overwatch Announcer: Three\n **!sb affirmative** - Affirmative\n **!sb gp** - 100% German Power\n **!sb justice** - Justice Rains From Above\n **!sb speed boost** - Speed Boost\n **!sb stop the payload** - Stop The Payload\n **!sb wsr** - Welcome To Summoner's Rift\n **!sb happy birthday adz** - Happy Birthday To Adz\n **!sb drop** - Drop The Beat\n **!sb tears** - Brings Tears\n **!sb balanced** - Balancing Teams\n **!sb ez mode** - Is this easy mode?\n **!sb enemy** - Enemy Slain\n **!sb victory** - Victory\n **!sb defeat** - Defeat\n **!sb pentakill** - PENTAKILL\n **!sb airport** - Airport Announcement\n **!sb airport de** - German Airport Announcement\n\n **!sb stop** - Resets the soundboard, useful if the soundboard commands aren't working" color: 39125 } }) else if msg.content == "!help" msg.channel.sendMessage("",{ embed: { title: "Motorbot Commands", description: "**!voice {guild_id} join {channel_name}** *- join a voice channel, {channel_name} and {guild_id} are optional*\n **!voice {guild_id} leave** *- leave voice channel, {guild_id} are optional*\n **!ban doug** *- bans doug*\n **!kys** *- KYS*\n **heads or tails** *- 50/50 chance*\n **fight me** *- you looking for a fight?*\n **cum on me** *- ...*\n **!random** *- generates a random number between 0 and 100*\n **!sb** *- soundboard (!sb help to get help with the soundboard)*\n **!ping** *- pong (dev test)*\n **!dev** *- bunch of dev status commands*\n **!react** *- react test*\n **!lolstat{.region} {summoner_name}** *- lolstat profile, {.region} is optional*\n **!ow {battlenet id}** *- gets some Overwatch Stats*\n **!triggerTyping** *- triggers typing indicator*\n **!reddit {subreddit}** *- gets the top 5 posts for /r/all, unless subreddit is specified e.g. `!reddit linuxmasterrace`* " color: 46066 } }) else if msg.content == "!ping" msg.channel.sendMessage("pong!") else if msg.content.match(/^\!dev client status/) server = msg.guild_id content = "Motorbot is connected to your gateway server on **"+self.client.internals.gateway+"** with an average ping of **"+Math.round(self.client.internals.avgPing*100)/100+"ms**. The last ping was **"+self.client.internals.pings[self.client.internals.pings.length-1]+"ms**." additionalParams = msg.content.replace(/^\!dev client status\s/gmi,"") if additionalParams == "detailed" table = new Table({ style: {'padding-left':1, 'padding-right':1, head:[], border:[]} }) avgPing = Math.round(self.client.internals.avgPing*100)/100 table.push(["Endpoint",self.client.internals.gateway]) table.push(["Average Ping",avgPing+"ms"]) table.push(["Last Ping",self.client.internals.pings[self.client.internals.pings.length-1]+"ms"]) table.push(["Heartbeats Sent",self.client.internals.pings.length]) table.push(["Sequence",self.client.internals.sequence]) table.push(["Connected Guilds",Object.keys(self.client.guilds).length]) table.push(["Channels",Object.keys(self.client.channels).length]) table.push(["Active Voice Handlers",Object.keys(self.client.voiceHandlers).length]) table.push(["Connection Retry Count",self.client.internals.connection_retry_count]) table.push(["Resuming", self.client.internals.resuming]) content = "```markdown\n"+table.toString()+"\n```" msg.channel.sendMessage(content) else if msg.content.match(/^\!dev voice status/) additionalParams = msg.content.replace(/^\!dev voice status\s/gmi,"") server = msg.guild_id if self.client.voiceHandlers[server] bytes = self.client.voiceHandlers[server].bytesTransmitted units = "Bytes" if bytes > 1024 bytes = (Math.round((bytes/1024)*100)/100) units = "KB" if bytes > 1024 bytes = (Math.round((bytes/1024)*100)/100) units = "MB" if bytes > 1024 bytes = (Math.round((bytes/1024)*100)/100) units = "GB" content = "Motorbot is connected to your voice server on **"+self.client.voiceHandlers[server].endpoint+"** with an average ping of **"+Math.round(self.client.voiceHandlers[server].avgPing*100)/100+"ms**. The last ping was **"+self.client.voiceHandlers[server].pings[self.client.voiceHandlers[server].pings.length-1]+"ms**.\n" if additionalParams == "detailed" table = new Table({ #head: ["Parameter","Value"] style: {'padding-left':1, 'padding-right':1, head:[], border:[]} }) avgPing = (Math.round(self.client.voiceHandlers[server].avgPing*100)/100) connectedTime = (Math.round(((new Date().getTime() - self.client.voiceHandlers[server].connectTime)/1000)*10)/10) table.push(["Endpoint",self.client.voiceHandlers[server].endpoint]) table.push(["Local Port",self.client.voiceHandlers[server].localPort]) table.push(["Average Ping",avgPing+"ms"]) table.push(["Last Ping",self.client.voiceHandlers[server].pings[self.client.voiceHandlers[server].pings.length-1]+"ms"]) table.push(["Heartbeats Sent",self.client.voiceHandlers[server].pings.length]) table.push(["Buffer Size",self.client.voiceHandlers[server].buffer_size]) table.push(["Bytes Transmitted",bytes+" "+units]) table.push(["Sequence",self.client.voiceHandlers[server].sequence]) table.push(["Timestamp",self.client.voiceHandlers[server].timestamp]) table.push(["Source ID (ssrc)",self.client.voiceHandlers[server].ssrc]) table.push(["User ID",self.client.voiceHandlers[server].user_id]) table.push(["Session",self.client.voiceHandlers[server].session_id]) table.push(["Token",self.client.voiceHandlers[server].token]) table.push(["Connected",connectedTime+"s"]) content = "```markdown\n"+table.toString()+"\n```" if !self.client.voiceHandlers[server].pings[0] content += "\n```diff\n- Status: Unknown - Too soon to tell\n```" else if avgPing >= 35 content += "\n```diff\n- Status: Poor - Pings a bit high, switch servers?\n```" else if connectedTime >= 172800 content += "\n```diff\n- Status: Sweating - Been working for at least 48 hours straight\n```" else content += "\n```diff\n+ Status: Awesome\n```" msg.channel.sendMessage(content) else msg.channel.sendMessage("```diff\n- Not Currently in voice channel\n```") else if msg.content == "!react" msg.channel.sendMessage("Reacting!") else if msg.content.match(/^!lolstat(\s|\.euw|\.na|\.br|\.eune|\.kr|\.lan|\.las|\.oce|\.ru|\.tr|\.jp)/gmi) region = "euw" if msg.content.replace(/^!lolstat/gmi,"").indexOf(".") > -1 region = msg.content.replace(/^!lolstat/gmi,"").split(".")[1].split(/\s/gmi)[0] summoner = encodeURI(msg.content.replace(/^!lolstat(\s|\.euw|\.na|\.br|\.eune|\.kr|\.lan|\.las|\.oce|\.ru|\.tr|\.jp)/gmi,"").replace(/\s/gmi,"").toLowerCase()) msg.channel.sendMessageWithFile("",req('https://api.lolstat.net/discord/profile/'+summoner+'/'+region), "profile.png") else if msg.content.match(/^!ow\s/gmi) battle_id = msg.content.replace(/^!ow\s/gmi, "").replace("#","-") req({ url: "https://playoverwatch.com/en-gb/career/pc/eu/"+battle_id }, (error, httpResponse, body) -> console.log "Overwatch Request Complete" if error then console.log error $ = cheerio.load(body) wins = $(".masthead .masthead-detail span").text() if wins quickplayStats = "" $("#quickplay > section.content-box.u-max-width-container.highlights-section > div > ul > li").each((i, elem) -> quickplayStats += $(elem).find(".card > .card-content > .card-copy").text().replace(" - Average","")+": "+$(this).find(".card > .card-content > .card-heading").text()+"\n" ) competitiveStats = "" $("#competitive > section.content-box.u-max-width-container.highlights-section > div > ul > li").each((i, elem) -> competitiveStats += $(elem).find(".card > .card-content > .card-copy").text().replace(" - Average","")+": "+$(this).find(".card > .card-content > .card-heading").text()+"\n" ) msg.channel.reply("",{ embed:{ title: $("#overview-section > div > div.u-max-width-container.row.content-box.gutter-18 > div > div > div.masthead-player > h1").text(), url: "https://playoverwatch.com/en-gb/career/pc/eu/"+battle_id, description: wins, color: 16751872, type: "rich", fields:[{ name: "Quick Play" value: quickplayStats, inline: true },{ name: "Competitive" value: competitiveStats, inline: true }], thumbnail: { url: $("#overview-section > div > div.u-max-width-container.row.content-box.gutter-18 > div > div > div.masthead-player > img").attr("src") } } }) else msg.channel.reply("Couldn't find account :(") ) else if msg.content == "!getMessages" console.log "Getting Messages" msg.channel.getMessages({limit: 5}).then((messages) -> console.log messages[0] ).catch((err) -> console.log err.statusMessage ) else if msg.content == "!getInvites" msg.channel.getInvites().then((invites) -> console.log invites ).catch((err) -> console.log err.statusMessage ) else if msg.content == "!createInvite" msg.channel.createInvite().then((invite) -> console.log invite ).catch((err) -> console.log err.statusMessage ) else if msg.content == "!triggerTyping" msg.channel.triggerTyping() else if msg.content.match(/^\!setStatus\s/gmi) newStatus = msg.content.replace(/^\!setStatus\s/gmi,"") self.client.setStatus(newStatus, 0, "online") else if msg.content.match(/^\!setState\s/gmi) newState = msg.content.replace(/^\!setState\s/gmi,"") if newState == "online" || newState == "offline" || newState == "dnd" || newState == "idle" || newState == "invisible" self.client.setStatus(null, 0, newState) else msg.channel.sendMessage("That state is not recognised, please use a standard state as specified here https://discordapp.com/developers/docs/topics/gateway#update-status") else if msg.content.match(/^setChannelName\s/gmi) name = msg.content.replace(/^setChannelName\s/gmi,"") msg.channel.setChannelName(name) else if msg.content.match(/^\!setUserLimit\s/gmi) user_limit = parseInt(msg.content.replace(/^\!setUserLimit\s/gmi,"")) self.client.channels["194904787924418561"].setUserLimit(user_limit) else if msg.content.match(/^\!test_embed/) msg.channel.sendMessage("",{ embed: { title: "Status: Awesome", #description: "Big ass description" color: 6795119, ### fields:[{ name:"name of field" value:"value of field", inline:true },{ name:"name of field" value:"value of field" inline:false }], footer: { text: "squírrel", icon_url: "https://discordapp.com/api/users/95164972807487488/avatars/de1f84de5db24c6681e8447a8106dfd9.jpg" }### } }) else if msg.content == "Reacting!" && msg.author.id == "169554882674556930" msg.addReaction("%F0%9F%91%BB") else if msg.content.match(/http(s|):\/\//gmi) && msg.channel.id == "130734377066954752" console.log "we got a meme bois" setTimeout( () -> msg.addReaction("\:upvote\:429449534389616641") setTimeout( () -> msg.addReaction("\:downvote\:429449638454493187") , 500) , 500) else if msg.content.match(/^\!challenge\s/gmi) challenged_user = msg.content.split(/\s/gmi)[1] challenged_user_id = challenged_user.replace("<","").replace(">","").replace("@","") challenger_user_id = msg.author.id #if challenged_user_id != challenger_user_id msg.channel.sendMessage("<@"+challenger_user_id+"> has challenged <@"+challenged_user_id+"> to a rock paper scissors duel. Both parties type `!rock`, `!paper` or `!scissors` as a DM to <@169554882674556930>") self.challenged[challenged_user_id] = {} self.challenged[challenged_user_id] = { challenge_in_progress: true, challenger: challenger_user_id, choice: undefined } self.challenger[challenger_user_id] ={} self.challenger[challenger_user_id] = { challenge_in_progress: true, challenged: challenged_user_id, channel: msg.channel, choice: undefined } console.log "CHALLENGED_USER: "+challenged_user #else # msg.channel.sendMessage("Sorry <@"+challenger_user_id+">, you can't challenge yourself :(") else if msg.content.match(/^!rock/) self.rockPaperScissors(msg, msg.author.id, "rock") else if msg.content.match(/^!paper/) self.rockPaperScissors(msg, msg.author.id, "paper") else if msg.content.match(/^!scissors/) self.rockPaperScissors(msg, msg.author.id, "scissors") else if msg.content.match(/^\!reddit/) subreddit = "/r/all" cmds = msg.content.replace(/^\!reddit\s/gmi,"") if cmds && cmds != "" && cmds != "!reddit" then subreddit = "/r/"+cmds req.get({url: "https://www.reddit.com"+subreddit+"/hot.json", json: true}, (err, httpResponse, body) -> if err utils.debug("Error occurred getting hot from /r/all", "error") msg.channel.sendMessage("",{embed: { title: "Error Occurred Retrieving Hot Posts from /r/all", color: 6795119 } }) else count = 5 i = 0 if body.data if body.data.children for post in body.data.children if i >= count then break i++ if post.data.thumbnail && post.data.thumbnail != "self" && post.data.thumbnail != "default" && post.data.thumbnail != "spoiler" && post.data.thumbnail.match(/^https\:(.*?)/) msg.channel.sendMessage("",{embed:{ title: "[/"+post.data.subreddit_name_prefixed+"] "+post.data.title, url: "https://www.reddit.com"+post.data.permalink, color: 16728832, type: "rich", fields:[{ name: "Score" value: post.data.score, inline: true },{ name: "Comments" value: post.data.num_comments, inline: true },{ name: "Published" value: moment.unix(post.data.created_utc).format("DD/MM/YYYY [at] HH:mm"), inline: true },{ name: "Author" value: "/u/"+post.data.author, inline: true }], thumbnail: { url: post.data.thumbnail } } }) else msg.channel.sendMessage("",{embed:{ title: "[/"+post.data.subreddit_name_prefixed+"] "+post.data.title, url: "https://www.reddit.com"+post.data.permalink, color: 1601757, type: "rich", fields:[{ name: "Score" value: post.data.score, inline: true },{ name: "Comments" value: post.data.num_comments, inline: true },{ name: "Published" value: moment.unix(post.data.created_utc).format("DD/MM/YYYY [at] HH:mm"), inline: true },{ name: "Author" value: "/u/"+post.data.author, inline: true }] } }) ) msg.delete() else #console.log msg.content #do nothing, aint a command or anything if self.client.channels["432351112616738837"] && msg.author.id != "169554882674556930" d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if self.client.guilds[msg.channel.guild_id] self.client.channels["432351112616738837"].sendMessage(time + " Message sent by <@"+msg.author.id+"> to the <#"+msg.channel_id+"> channel in the "+self.client.guilds[msg.channel.guild_id].name+" guild") else self.client.channels["432351112616738837"].sendMessage(time + " Message sent by <@"+msg.author.id+"> to the <#"+msg.channel_id+"> channel (DM)") ) @client.on("messageUpdate", (msg) -> if self.client.channels["432351112616738837"] && msg.channel_id != "432351112616738837" d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " Message `"+msg.id+"` was updated in the <#"+msg.channel_id+"> channel") ) @client.on("messageDelete", (msg_id, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " desc = time + " Cached Message (`"+msg_id+"`) :link:" self.client.channels["432351112616738837"].sendMessage(time + " Message `"+msg_id+"` was deleted from the <#"+channel.id+"> channel in the "+self.client.guilds[channel.guild_id].name+" guild", { "embed": { "title": desc, "url": "https://motorbot.io/api/message_history/"+msg_id, "color": 38609 } }) ) @client.on("channelCreate", (type, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " The <#"+channel.id+"> channel was created with channel type `"+type+"`") ) @client.on("channelUpdate", (type, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " The <#"+channel.id+"> channel was modified") ) @client.on("channelDelete", (type, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " The channel `"+channel.id+"` was deleted") ) @client.on("channelPinsUpdate", (update) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " Pins updated in channel <#"+update.channel_id+">") ) @client.on("typingStart", (user_id, channel, timestamp) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " <@"+user_id+"> has started typing in the <#"+channel.id+"> channel") ) @client.on("userUpdate", (user_id, username, data) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " <@"+user_id+"> updated their discord profile") ) module.exports = motorbotEventHandler
204305
Table = require 'cli-table' keys = require '/var/www/motorbot/keys.json' apiai = require('apiai') apiai = apiai(keys.apiai) #AI for !talk method fs = require 'fs' req = require 'request' moment = require 'moment' cheerio = require 'cheerio' turndown = require 'turndown' class motorbotEventHandler constructor: (@app, @client) -> @setUpEvents() @already_announced = false @challenged = {} @challenger = {} setupSoundboard: (guild_id, filepath, volume = 1) -> self = @ if !self.app.soundboard[guild_id] self.app.client.voiceConnections[guild_id].playFromFile(filepath).then((audioPlayer) -> self.app.soundboard[guild_id] = audioPlayer self.app.org_volume = 0.5 #set default self.app.soundboard[guild_id].on('streamDone', () -> self.app.debug("StreamDone Received") delete self.app.soundboard[guild_id] if self.app.musicPlayers[guild_id] self.app.musicPlayers[guild_id].setVolume(self.app.org_volume) #set back to original volume of music self.app.musicPlayers[guild_id].play() ) self.app.soundboard[guild_id].on('ready', () -> if self.app.musicPlayers[guild_id] self.app.org_volume = self.app.musicPlayers[guild_id].getVolume() self.app.musicPlayers[guild_id].pause() else self.app.soundboard[guild_id].setVolume(volume) self.app.soundboard[guild_id].play() ) self.app.musicPlayers[guild_id].on("paused", () -> if self.app.soundboard[guild_id] self.app.soundboard[guild_id].setVolume(volume) self.app.soundboard[guild_id].play() ) ) else self.app.debug("Soundboard already playing") toTitleCase: (str) -> return str.replace(/\w\S*/g, (txt) -> return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() ); patchListener: (game) -> self = @ if game == "ow" patches = {} p = [] req({ url: "https://playoverwatch.com/en-us/game/patch-notes/pc/" }, (error, httpResponse, body) -> console.log "Overwatch Request Complete" if error then console.log error $ = cheerio.load(body) $(".patch-notes-body").each((i, element) -> p[i] = $(this).attr("id") console.log p[i] desc = $(this).html().replace(/<\/h2>/,'sdfgpoih345e87th').split('sdfgpoih345e87th')[1] patches[$(this).attr("id")] = { patch_id: $(this).attr("id"), title: $(this).find("h1").text(), sub_title: $(this).find("h2").eq(0).text(), desc: desc } ) #find all logged patches patchCollection = self.app.database.collection("patches") patchCollection.find({patch_id: {"$in": p}}).toArray((err, results) -> if err then return console.log err if results[0] console.log "found patches in db" for result in results for patch_id, patch of patches if result.patch_id == patch_id delete patches[patch_id] #remove patch from patches array #process any left patches console.log "processing any left patches" td = new turndown() database_patches = [] for key, new_patch of patches d = new Date() database_patches.push(new_patch) embed_element = { title: self.toTitleCase(new_patch.title), url: "https://playoverwatch.com/en-us/game/patch-notes/pc/#" + new_patch.patch_id, description: new_patch.sub_title + "\n------\n" + td.turndown(new_patch.desc).substring(0, 1000) + "\n\n[Read More](https://playoverwatch.com/en-us/game/patch-notes/pc/#" + new_patch.patch_id+")", color: 16751872, timestamp: d.toISOString(), type: "rich", "footer": { "icon_url": "https://motorbot.io/overwatch_sm.png", "text": "Patch Notification" }, thumbnail: { url: "https://motorbot.io/overwatch_sm.png" } } console.log embed_element self.app.client.channels["438307738250903553"].sendMessage("", { embed: embed_element }) if database_patches.length > 0 patchCollection.insertMany(database_patches) ) ) twitchSubscribeToStream: (user_id) -> # Subscribe to Twitch Webhook Services self = @ req.post({ url: "https://api.twitch.tv/helix/webhooks/hub?hub.mode=subscribe&hub.topic=https://api.twitch.tv/helix/streams?user_id="+user_id+"&hub.callback=https://motorbot.io/twitch/callback&hub.lease_seconds=864000&hub.secret=hex<KEY>aver" headers: { "Client-ID": keys.twitch }, json: true }, (error, httpResponse, body) -> self.app.debug("Twitch Webhook Subscription Response Code: "+httpResponse.statusCode, "debug") if error self.app.debug("subscription error to webhook", "error") console.log error ) changeNickname: (guild_id, user_id, user_name, karma) -> # doesn't work for same roles and roles above bots current role ###req({ url: "https://discordapp.com/api/guilds/"+guild_id+"/members/"+user_id, method: "PATCH" headers: { "Authorization": "Bot "+keys.token }, json: true body: { nick: user_name+" ("+karma+")" } }, (err, httpResponse, body) -> if err then console.log err console.log "request complete" console.log body )### rockPaperScissors: (msg, author, choice) -> self = @ compareRPS = (challenged, challengedID, challenger, challengerID, cb) -> outcome = { winner: undefined, challenged: { id: challengedID win: true }, challenger: { id: challengerID win: true } } if challenged.choice == "rock" if challenger.choice == "paper" outcome.challenger.win = true outcome.challenged.win = false outcome.winner = challengerID if challenger.choice == "rock" outcome.challenger.win = true outcome.challenged.win = true outcome.winner = "tie" if challenger.choice == "scissors" outcome.challenger.win = false outcome.challenged.win = true outcome.winner = challengedID else if challenged.choice == "paper" if challenger.choice == "paper" outcome.challenger.win = true outcome.challenged.win = true outcome.winner = "tie" if challenger.choice == "rock" outcome.challenger.win = false outcome.challenged.win = true outcome.winner = challengedID if challenger.choice == "scissors" outcome.challenger.win = true outcome.challenged.win = false outcome.winner = challengerID else if challenged.choice == "scissors" if challenger.choice == "paper" outcome.challenger.win = false outcome.challenged.win = true outcome.winner = challengedID if challenger.choice == "rock" outcome.challenger.win = true outcome.challenged.win = false outcome.winner = challengerID if challenger.choice == "scissors" outcome.challenger.win = true outcome.challenged.win = true outcome.winner = "tie" cb(outcome) if self.challenged[author] self.challenged[author].choice = choice challenger = self.challenger[self.challenged[author].challenger] if self.challenger[self.challenged[author].challenger].choice #both users have made their choice, compare compareRPS(self.challenged[author], author, self.challenger[self.challenged[author].challenger], self.challenged[author].challenger, (outcome) -> if outcome.winner == "tie" challenger.channel.sendMessage("The challenge between <@"+author+"> and <@"+self.challenged[author].challenger+"> resulted in a draw, fight again?") delete self.challenger[self.challenged[author].challenger] delete self.challenged[author] else if self.challenged[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenged[outcome.winner].challenger+">") delete self.challenger[self.challenged[outcome.winner].challenger] delete self.challenged[outcome.winner] else if self.challenger[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenger[outcome.winner].challenged+">") delete self.challenged[self.challenger[outcome.winner].challenged] delete self.challenger[outcome.winner] ) if self.challenger[author] self.challenger[author].choice = choice challenger = self.challenger[author] if self.challenged[self.challenger[author].challenged].choice #both users have made their choice, compare compareRPS(self.challenged[self.challenger[author].challenged], self.challenger[author].challenged, self.challenger[author], author, (outcome) -> if outcome.winner == "tie" challenger.channel.sendMessage("The challenge between <@"+author+"> and <@"+self.challenger[author].challenged+"> resulted in a draw, fight again?") delete self.challenged[self.challenger[author].challenged] delete self.challenger[author] else if self.challenged[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenged[outcome.winner].challenger+">") delete self.challenger[self.challenged[outcome.winner].challenger] delete self.challenged[outcome.winner] else if self.challenger[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenger[outcome.winner].challenged+">") delete self.challenged[self.challenger[outcome.winner].challenged] delete self.challenger[outcome.winner] ) setUpEvents: () -> self = @ self.twitchSubscribeToStream(22032158) #motorlatitude self.twitchSubscribeToStream(26752266) #mutme self.twitchSubscribeToStream(24991333) #imaqtpie self.twitchSubscribeToStream(22510310) #GDQ #League LCS self.twitchSubscribeToStream(36029255) #RiotGames self.twitchSubscribeToStream(36794584) #RiotGames2 @client.on("ready", () -> self.app.debug("Ready!") ) y = 0 @client.on("guildCreate", (server) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if server.id == "130734377066954752" self.client.channels["432351112616738837"].sendMessage(":x: <@&443191635657097217>","embed": { "title": "MOTORBOT RESTARTED" "description": "Motorbot had to restart either through manual input or due to a fatal error occurring, please consult error logs in console if the latter.", "color": 16724787 }) #self.client.channels["432351112616738837"].sendMessage(time + " Joined Guild: "+server.name+" ("+server.presences.length+" online / "+(parseInt(server.member_count)-server.presences.length)+" offline)") if y == 0 #Listen for patches #setInterval( () -> # self.patchListener("ow") #, 3600000) y = 1 ) @client.on("voiceUpdate_Speaking", (data) -> self.app.websocket.broadcast(JSON.stringify({type: "VOICE_UPDATE_SPEAKING", d:data})) ) voiceStates = {} @client.on("voiceChannelUpdate", (data) -> if data.user_id == '169554882674556930' if data.channel self.app.websocket.broadcast(JSON.stringify({type: "VOICE_UPDATE", d:{status:"JOIN", channel: data.channel.name, channel_id: data.channel.id, channel_obj: data}}, (key, value) -> if key == "client" return undefined else return value )) else self.app.websocket.broadcast(JSON.stringify({type: "VOICE_UPDATE", d:{status:"LEAVE", channel: undefined, channel_id: undefined, channel_obj: data}}, (key, value) -> if key == "client" return undefined else return value )) d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if data.channel if voiceStates[data.user_id] if voiceStates[data.user_id].channel #previously in channel hence channel voice state change #voice state trigger if data.deaf && !voiceStates[data.user_id].deaf #deafened from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> was server deafened in the `"+data.channel.name+"` voice channel") if data.mute && !voiceStates[data.user_id].mute #muted from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> was server muted in the `"+data.channel.name+"` voice channel") if data.self_deaf && !voiceStates[data.user_id].self_deaf #user has deafened himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has deafened them self in the `"+data.channel.name+"` voice channel") if data.self_mute && !voiceStates[data.user_id].self_mute #user has muted himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has muted them self in the `"+data.channel.name+"` voice channel") #voice state trigger reverse if !data.deaf && voiceStates[data.user_id].deaf #undeafened from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer server deafened in the `"+data.channel.name+"` voice channel") if !data.mute && voiceStates[data.user_id].mute #unmuted from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer server muted in the `"+data.channel.name+"` voice channel") if !data.self_deaf && voiceStates[data.user_id].self_deaf #user has undeafened himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer deafened in the `"+data.channel.name+"` voice channel") if !data.self_mute && voiceStates[data.user_id].self_mute #user has unmuted himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer muted in the `"+data.channel.name+"` voice channel") else #newly joined self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has joined the `"+data.channel.name+"` voice channel") else self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has joined the `"+data.channel.name+"` voice channel") else self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has left a voice channel") voiceStates[data.user_id] = data ) userStatus = {} @client.on("status", (user_id,status,game,extra_info) -> if extra_info.guild_id == "130734377066954752" #only listening for presence updates in the KTJ guild for now to avoid duplicates across multiple channels if game self.app.debug(user_id+"'s status ("+status+") has changed; "+game.name+"("+game.type+")","notification") else self.app.debug(user_id+"'s status ("+status+") has changed", "notification") d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " gameText = "" statusText = "" additionalString = "" if game extra_info["last_game_update"] = new Date().getTime() if userStatus[user_id] if userStatus[user_id].game if userStatus[user_id].game.name == game.name extra_info["last_game_update"] = userStatus[user_id].last_game_update if game.details additionalString += "\n"+time+" *"+game.details+"*" if game.state additionalString += "\n"+time+" "+game.state if userStatus[user_id] if userStatus[user_id].status == status #no status change, only game update if !game && userStatus[user_id].game if userStatus[user_id].game.type == 0 statusText = " has stopped playing **"+userStatus[user_id].game.name+"** after "+(moment.unix(userStatus[user_id].last_game_update/1000).fromNow()).replace(" ago","") else if userStatus[user_id].game.type == 1 statusText = " has stopped streaming **"+userStatus[user_id].game.name+"** after "+(moment.unix(userStatus[user_id].last_game_update/1000).fromNow()).replace(" ago","") else if userStatus[user_id].game.type == 2 statusText = " has stopped listening to **"+userStatus[user_id].game.name+"** after "+(moment.unix(userStatus[user_id].last_game_update/1000).fromNow()).replace(" ago","") extra_info["last_update"] = userStatus[user_id].last_update else #status change statusText = " was `"+userStatus[user_id].status+"` for "+(moment.unix(userStatus[user_id].last_update/1000).fromNow()).replace(" ago","")+" and is now `"+status+"`" extra_info["last_update"] = new Date().getTime() else #we don't know previous status so assume status change statusText = "'s status has changed to `"+status+"`" extra_info["last_update"] = new Date().getTime() if game && game.type == 0 gameText = " is playing **"+game.name+"**" else if game && game.type == 1 gameText = " is streaming **"+game.name+"**" else if game && game.type == 2 gameText = " is listening to **"+game.name+"**" else gameText = "" #status change if game if userStatus[user_id] if userStatus[user_id].game if userStatus[user_id].game.name == game.name && game.type == 0 gameText = " game presence update :video_game: " else if userStatus[user_id].game.name == game.name && game.type == 2 gameText = " is switching song" someText = if(gameText != "" && statusText != "") then " and"+gameText else gameText if game && game.type == 2 additionalString = "" if game.details additionalString += "\n"+time+" **"+game.details+"**" if game.state additionalString += "\n"+time+" by "+game.state if game.assets.large_text additionalString += "\n"+time+" on "+game.assets.large_text console.log game desc = time+"<@"+user_id+">"+statusText+someText+additionalString thumbnail_url = "" if game.assets if game.assets.large_image thumbnail_id = game.assets.large_image.replace("spotify:","") thumbnail_url = "https://i.scdn.co/image/"+thumbnail_id console.log thumbnail_url self.client.channels["432351112616738837"].sendMessage("","embed": { "description": desc, "color": 2021216, "thumbnail": { "url": thumbnail_url } }) else if statusText == "" && someText == "" && additionalString == "" self.client.channels["432351112616738837"].sendMessage(time+"<@"+user_id+"> is `invisible` and a status refresh event occurred") else self.client.channels["432351112616738837"].sendMessage(time+"<@"+user_id+">"+statusText+someText+additionalString) userStatus[user_id] = extra_info ) @client.on("reaction", (type, data) -> if data.user_id != "169554882674556930" d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if data.emoji.name == "downvote" || data.emoji.name == "upvote" if type == "add" self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has added the `"+data.emoji.name+"` reaction to message `"+data.message_id+"` in channel <#"+data.channel_id+">") #find message for user self.client.channels[data.channel_id].getMessage(data.message_id).then((message) -> author_id = message.author.id karmaCollection = self.app.database.collection("karma_points") karmaCollection.find({"author": author_id}).toArray((err, results) -> if err then return console.log err if results[0] author_karma = results[0].karma else author_karma = 0 if data.emoji.name == "upvote" author_karma += 1 else if data.emoji.name == "downvote" author_karma -= 1 karma_obj = { author: author_id, karma: author_karma } self.client.channels["432351112616738837"].sendMessage(time+"<@"+author_id+"> now has "+author_karma+" karma") karmaCollection.update({author: author_id}, karma_obj, {upsert: true}) self.changeNickname(message.guild_id , author_id, message.author.username, author_karma) ) ).catch((err) -> console.log "Couldn't retrieve message" console.log err ) else if type == "remove" self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has removed the `"+data.emoji.name+"` reaction on message `"+data.message_id+"` in channel <#"+data.channel_id+">") #find message for user self.client.channels[data.channel_id].getMessage(data.message_id).then((message) -> author_id = message.author.id karmaCollection = self.app.database.collection("karma_points") karmaCollection.find({"author": author_id}).toArray((err, results) -> if err then return console.log err if results[0] author_karma = results[0].karma else author_karma = 0 if data.emoji.name == "upvote" author_karma -= 1 else if data.emoji.name == "downvote" author_karma += 1 karma_obj = { author: author_id, karma: author_karma } self.client.channels["432351112616738837"].sendMessage(time+"<@"+author_id+"> now has "+author_karma+" karma") karmaCollection.update({author: author_id}, karma_obj, {upsert: true}) self.changeNickname(message.guild_id , author_id, message.author.username, author_karma) ) ).catch((err) -> console.log "Couldn't retrieve message" console.log err ) ) @client.on("message", (msg) -> #store all messages messageCollection = self.app.database.collection("messages") db_msg_obj = { id: msg.id, channel_id: msg.channel_id, guild_id: msg.guild_id, author: msg.author, content: msg.content, timestamp: msg.timestamp, edited_timestamp: msg.edited_timestamp, tts: msg.tts, mention_everyone: msg.mention_everyone, mentions: msg.mentions, mention_roles: msg.mention_roles, attachments: msg.attachments, embeds: msg.embeds, reactions: msg.reactions, nonce: msg.nonce, pinned: msg.pinned, webhook_id: msg.webhook_id } messageCollection.update({id: msg.id}, db_msg_obj, {upsert: true}) if msg.content.match(/^\!voice\sjoin/) channelName = msg.content.replace(/^\!voice\sjoin\s/,"") joined = false if channelName for channel in self.client.guilds[msg.guild_id].channels if channel.name == channelName && channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[msg.guild_id] = VoiceConnection ) joined = true break if !joined for channel in self.client.guilds[msg.guild_id].channels if channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[msg.guild_id] = VoiceConnection ) break else if msg.content.match(/^\!voice\s(.*?)\sjoin/) channelName = msg.content.replace(/^\!voice\s(.*?)\sjoin\s/,"") selected_guild_id = msg.content.match(/^\!voice\s(.*?)\sjoin/)[1] console.log msg.author joined = false if self.client.guilds[selected_guild_id] if channelName for channel in self.client.guilds[selected_guild_id].channels if channel.name == channelName && channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[selected_guild_id] = VoiceConnection ) joined = true break if !joined for channel in self.client.guilds[selected_guild_id].channels if channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[selected_guild_id] = VoiceConnection ) break else msg.channel.sendMessage("```diff\n- Unknown Server\n```") else if msg.content.match(/^\!voice\s(.*?)\sleave/) selected_guild_id = msg.content.match(/^\!voice\s(.*?)\sleave/)[1] if self.client.guilds[selected_guild_id] self.client.leaveVoiceChannel(selected_guild_id) else msg.channel.sendMessage("```diff\n- Unknown Server\n```") else if msg.content.match(/^!ban doug/gmi) msg.channel.sendMessage("If only I could :rolling_eyes: <@"+msg.author.id+">") else if msg.content.match(/^!kys/gmi) || msg.content.match(/kys/gmi) msg.channel.sendMessage("Calm down before you go and hurt someone <@"+msg.author.id+">") else if msg.content.match(/fight\sme(\sbro|)/gmi) || msg.content.match(/come\sat\sme(\sbro|)/gmi) msg.channel.sendMessage("(ง’̀-‘́)ง") else if msg.content == "!voice leave" self.client.leaveVoiceChannel(msg.guild_id) else if msg.content.match(/heads\sor\stails(\?|)/gmi) if Math.random() >= 0.5 msg.channel.sendMessage(":one: Heads <@"+msg.author.id+">") else msg.channel.sendMessage(":zero: Tails <@"+msg.author.id+">") else if msg.content.match(/\!random/) msg.channel.sendMessage("Random Number: "+(Math.round((Math.random()*100)))) else if msg.content == "!sb diddly" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/DootDiddly.mp3", 5) else if msg.content == "!sb pog" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/play of the game.mp3", 3) else if msg.content == "!sb kled" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Kled.mp3", 3) else if msg.content == "!sb wonder" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/wonder.mp3", 3) else if msg.content == "!sb 1" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/1.mp3", 3) else if msg.content == "!sb 2" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/2.mp3", 3) else if msg.content == "!sb 3" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/3.mp3", 3) else if msg.content == "!sb affirmative" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/affirmative.mp3", 3) else if msg.content == "!sb gp" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/gp.mp3", 3) else if msg.content == "!sb justice" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/justice 3.mp3", 3) else if msg.content == "!sb speed boost" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/speed boost.mp3", 3) else if msg.content == "!sb stop the payload" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/stop the payload.mp3", 3) else if msg.content == "!sb wsr" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/wsr.mp3", 2) else if msg.content == "!sb drop" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/drop_beat.wav", 3) else if msg.content == "!sb tears" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/bings_tears.wav", 3) else if msg.content == "!sb balanced" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/balancing_teams.wav", 3) else if msg.content == "!sb ez mode" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/D.Va_-_Easy_mode.ogg", 3) else if msg.content == "!sb enemy" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Enemy Slain.mp3", 2) else if msg.content == "!sb victory" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Victory.mp3", 2) else if msg.content == "!sb defeat" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Defeat.mp3", 2) else if msg.content == "!sb pentakill" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Pentakill1.mp3", 2) else if msg.content == "!sb happy birthday adz" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/happybirthdayadz.wav", 3) else if msg.content == "!sb airport" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/En-BAW-LHR-boarding.mp3", 2) else if msg.content == "!sb airport de" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Ge-DLH-FRA-boarding.mp3", 2) else if msg.content == "!sb stop" if self.app.soundboard[msg.guild_id] self.app.soundboard[msg.guild_id].stop() delete self.app.soundboard[msg.guild_id] else if msg.content == "!sb help" msg.channel.sendMessage("",{ embed: { title: "Soundboard Commands", description: "**!sb diddly** - Doot Diddly\n **!sb pog** - Play Of The Game\n **!sb kled** - I Find Courage Unpredictable...\n **!sb wonder** - And I sometimes wonder...\n **!sb 1** - Overwatch Announcer: One\n **!sb 2** - Overwatch Announcer: Two\n **!sb 3** - Overwatch Announcer: Three\n **!sb affirmative** - Affirmative\n **!sb gp** - 100% German Power\n **!sb justice** - Justice Rains From Above\n **!sb speed boost** - Speed Boost\n **!sb stop the payload** - Stop The Payload\n **!sb wsr** - Welcome To Summoner's Rift\n **!sb happy birthday adz** - Happy Birthday To Adz\n **!sb drop** - Drop The Beat\n **!sb tears** - Brings Tears\n **!sb balanced** - Balancing Teams\n **!sb ez mode** - Is this easy mode?\n **!sb enemy** - Enemy Slain\n **!sb victory** - Victory\n **!sb defeat** - Defeat\n **!sb pentakill** - PENTAKILL\n **!sb airport** - Airport Announcement\n **!sb airport de** - German Airport Announcement\n\n **!sb stop** - Resets the soundboard, useful if the soundboard commands aren't working" color: 39125 } }) else if msg.content == "!help" msg.channel.sendMessage("",{ embed: { title: "Motorbot Commands", description: "**!voice {guild_id} join {channel_name}** *- join a voice channel, {channel_name} and {guild_id} are optional*\n **!voice {guild_id} leave** *- leave voice channel, {guild_id} are optional*\n **!ban doug** *- bans doug*\n **!kys** *- KYS*\n **heads or tails** *- 50/50 chance*\n **fight me** *- you looking for a fight?*\n **cum on me** *- ...*\n **!random** *- generates a random number between 0 and 100*\n **!sb** *- soundboard (!sb help to get help with the soundboard)*\n **!ping** *- pong (dev test)*\n **!dev** *- bunch of dev status commands*\n **!react** *- react test*\n **!lolstat{.region} {summoner_name}** *- lolstat profile, {.region} is optional*\n **!ow {battlenet id}** *- gets some Overwatch Stats*\n **!triggerTyping** *- triggers typing indicator*\n **!reddit {subreddit}** *- gets the top 5 posts for /r/all, unless subreddit is specified e.g. `!reddit linuxmasterrace`* " color: 46066 } }) else if msg.content == "!ping" msg.channel.sendMessage("pong!") else if msg.content.match(/^\!dev client status/) server = msg.guild_id content = "Motorbot is connected to your gateway server on **"+self.client.internals.gateway+"** with an average ping of **"+Math.round(self.client.internals.avgPing*100)/100+"ms**. The last ping was **"+self.client.internals.pings[self.client.internals.pings.length-1]+"ms**." additionalParams = msg.content.replace(/^\!dev client status\s/gmi,"") if additionalParams == "detailed" table = new Table({ style: {'padding-left':1, 'padding-right':1, head:[], border:[]} }) avgPing = Math.round(self.client.internals.avgPing*100)/100 table.push(["Endpoint",self.client.internals.gateway]) table.push(["Average Ping",avgPing+"ms"]) table.push(["Last Ping",self.client.internals.pings[self.client.internals.pings.length-1]+"ms"]) table.push(["Heartbeats Sent",self.client.internals.pings.length]) table.push(["Sequence",self.client.internals.sequence]) table.push(["Connected Guilds",Object.keys(self.client.guilds).length]) table.push(["Channels",Object.keys(self.client.channels).length]) table.push(["Active Voice Handlers",Object.keys(self.client.voiceHandlers).length]) table.push(["Connection Retry Count",self.client.internals.connection_retry_count]) table.push(["Resuming", self.client.internals.resuming]) content = "```markdown\n"+table.toString()+"\n```" msg.channel.sendMessage(content) else if msg.content.match(/^\!dev voice status/) additionalParams = msg.content.replace(/^\!dev voice status\s/gmi,"") server = msg.guild_id if self.client.voiceHandlers[server] bytes = self.client.voiceHandlers[server].bytesTransmitted units = "Bytes" if bytes > 1024 bytes = (Math.round((bytes/1024)*100)/100) units = "KB" if bytes > 1024 bytes = (Math.round((bytes/1024)*100)/100) units = "MB" if bytes > 1024 bytes = (Math.round((bytes/1024)*100)/100) units = "GB" content = "Motorbot is connected to your voice server on **"+self.client.voiceHandlers[server].endpoint+"** with an average ping of **"+Math.round(self.client.voiceHandlers[server].avgPing*100)/100+"ms**. The last ping was **"+self.client.voiceHandlers[server].pings[self.client.voiceHandlers[server].pings.length-1]+"ms**.\n" if additionalParams == "detailed" table = new Table({ #head: ["Parameter","Value"] style: {'padding-left':1, 'padding-right':1, head:[], border:[]} }) avgPing = (Math.round(self.client.voiceHandlers[server].avgPing*100)/100) connectedTime = (Math.round(((new Date().getTime() - self.client.voiceHandlers[server].connectTime)/1000)*10)/10) table.push(["Endpoint",self.client.voiceHandlers[server].endpoint]) table.push(["Local Port",self.client.voiceHandlers[server].localPort]) table.push(["Average Ping",avgPing+"ms"]) table.push(["Last Ping",self.client.voiceHandlers[server].pings[self.client.voiceHandlers[server].pings.length-1]+"ms"]) table.push(["Heartbeats Sent",self.client.voiceHandlers[server].pings.length]) table.push(["Buffer Size",self.client.voiceHandlers[server].buffer_size]) table.push(["Bytes Transmitted",bytes+" "+units]) table.push(["Sequence",self.client.voiceHandlers[server].sequence]) table.push(["Timestamp",self.client.voiceHandlers[server].timestamp]) table.push(["Source ID (ssrc)",self.client.voiceHandlers[server].ssrc]) table.push(["User ID",self.client.voiceHandlers[server].user_id]) table.push(["Session",self.client.voiceHandlers[server].session_id]) table.push(["Token",self.client.voiceHandlers[server].token]) table.push(["Connected",connectedTime+"s"]) content = "```markdown\n"+table.toString()+"\n```" if !self.client.voiceHandlers[server].pings[0] content += "\n```diff\n- Status: Unknown - Too soon to tell\n```" else if avgPing >= 35 content += "\n```diff\n- Status: Poor - Pings a bit high, switch servers?\n```" else if connectedTime >= 172800 content += "\n```diff\n- Status: Sweating - Been working for at least 48 hours straight\n```" else content += "\n```diff\n+ Status: Awesome\n```" msg.channel.sendMessage(content) else msg.channel.sendMessage("```diff\n- Not Currently in voice channel\n```") else if msg.content == "!react" msg.channel.sendMessage("Reacting!") else if msg.content.match(/^!lolstat(\s|\.euw|\.na|\.br|\.eune|\.kr|\.lan|\.las|\.oce|\.ru|\.tr|\.jp)/gmi) region = "euw" if msg.content.replace(/^!lolstat/gmi,"").indexOf(".") > -1 region = msg.content.replace(/^!lolstat/gmi,"").split(".")[1].split(/\s/gmi)[0] summoner = encodeURI(msg.content.replace(/^!lolstat(\s|\.euw|\.na|\.br|\.eune|\.kr|\.lan|\.las|\.oce|\.ru|\.tr|\.jp)/gmi,"").replace(/\s/gmi,"").toLowerCase()) msg.channel.sendMessageWithFile("",req('https://api.lolstat.net/discord/profile/'+summoner+'/'+region), "profile.png") else if msg.content.match(/^!ow\s/gmi) battle_id = msg.content.replace(/^!ow\s/gmi, "").replace("#","-") req({ url: "https://playoverwatch.com/en-gb/career/pc/eu/"+battle_id }, (error, httpResponse, body) -> console.log "Overwatch Request Complete" if error then console.log error $ = cheerio.load(body) wins = $(".masthead .masthead-detail span").text() if wins quickplayStats = "" $("#quickplay > section.content-box.u-max-width-container.highlights-section > div > ul > li").each((i, elem) -> quickplayStats += $(elem).find(".card > .card-content > .card-copy").text().replace(" - Average","")+": "+$(this).find(".card > .card-content > .card-heading").text()+"\n" ) competitiveStats = "" $("#competitive > section.content-box.u-max-width-container.highlights-section > div > ul > li").each((i, elem) -> competitiveStats += $(elem).find(".card > .card-content > .card-copy").text().replace(" - Average","")+": "+$(this).find(".card > .card-content > .card-heading").text()+"\n" ) msg.channel.reply("",{ embed:{ title: $("#overview-section > div > div.u-max-width-container.row.content-box.gutter-18 > div > div > div.masthead-player > h1").text(), url: "https://playoverwatch.com/en-gb/career/pc/eu/"+battle_id, description: wins, color: 16751872, type: "rich", fields:[{ name: "Quick Play" value: quickplayStats, inline: true },{ name: "Competitive" value: competitiveStats, inline: true }], thumbnail: { url: $("#overview-section > div > div.u-max-width-container.row.content-box.gutter-18 > div > div > div.masthead-player > img").attr("src") } } }) else msg.channel.reply("Couldn't find account :(") ) else if msg.content == "!getMessages" console.log "Getting Messages" msg.channel.getMessages({limit: 5}).then((messages) -> console.log messages[0] ).catch((err) -> console.log err.statusMessage ) else if msg.content == "!getInvites" msg.channel.getInvites().then((invites) -> console.log invites ).catch((err) -> console.log err.statusMessage ) else if msg.content == "!createInvite" msg.channel.createInvite().then((invite) -> console.log invite ).catch((err) -> console.log err.statusMessage ) else if msg.content == "!triggerTyping" msg.channel.triggerTyping() else if msg.content.match(/^\!setStatus\s/gmi) newStatus = msg.content.replace(/^\!setStatus\s/gmi,"") self.client.setStatus(newStatus, 0, "online") else if msg.content.match(/^\!setState\s/gmi) newState = msg.content.replace(/^\!setState\s/gmi,"") if newState == "online" || newState == "offline" || newState == "dnd" || newState == "idle" || newState == "invisible" self.client.setStatus(null, 0, newState) else msg.channel.sendMessage("That state is not recognised, please use a standard state as specified here https://discordapp.com/developers/docs/topics/gateway#update-status") else if msg.content.match(/^setChannelName\s/gmi) name = msg.content.replace(/^setChannelName\s/gmi,"") msg.channel.setChannelName(name) else if msg.content.match(/^\!setUserLimit\s/gmi) user_limit = parseInt(msg.content.replace(/^\!setUserLimit\s/gmi,"")) self.client.channels["194904787924418561"].setUserLimit(user_limit) else if msg.content.match(/^\!test_embed/) msg.channel.sendMessage("",{ embed: { title: "Status: Awesome", #description: "Big ass description" color: 6795119, ### fields:[{ name:"name of field" value:"value of field", inline:true },{ name:"name of field" value:"value of field" inline:false }], footer: { text: "squírrel", icon_url: "https://discordapp.com/api/users/95164972807487488/avatars/de1f84de5db24c6681e8447a8106dfd9.jpg" }### } }) else if msg.content == "Reacting!" && msg.author.id == "<PASSWORD>" msg.addReaction("%F0%9F%91%BB") else if msg.content.match(/http(s|):\/\//gmi) && msg.channel.id == "130734377066954752" console.log "we got a meme bois" setTimeout( () -> msg.addReaction("\:upvote\:429449534389616641") setTimeout( () -> msg.addReaction("\:downvote\:429449638454493187") , 500) , 500) else if msg.content.match(/^\!challenge\s/gmi) challenged_user = msg.content.split(/\s/gmi)[1] challenged_user_id = challenged_user.replace("<","").replace(">","").replace("@","") challenger_user_id = msg.author.id #if challenged_user_id != challenger_user_id msg.channel.sendMessage("<@"+challenger_user_id+"> has challenged <@"+challenged_user_id+"> to a rock paper scissors duel. Both parties type `!rock`, `!paper` or `!scissors` as a DM to <@169554882674556930>") self.challenged[challenged_user_id] = {} self.challenged[challenged_user_id] = { challenge_in_progress: true, challenger: challenger_user_id, choice: undefined } self.challenger[challenger_user_id] ={} self.challenger[challenger_user_id] = { challenge_in_progress: true, challenged: challenged_user_id, channel: msg.channel, choice: undefined } console.log "CHALLENGED_USER: "+challenged_user #else # msg.channel.sendMessage("Sorry <@"+challenger_user_id+">, you can't challenge yourself :(") else if msg.content.match(/^!rock/) self.rockPaperScissors(msg, msg.author.id, "rock") else if msg.content.match(/^!paper/) self.rockPaperScissors(msg, msg.author.id, "paper") else if msg.content.match(/^!scissors/) self.rockPaperScissors(msg, msg.author.id, "scissors") else if msg.content.match(/^\!reddit/) subreddit = "/r/all" cmds = msg.content.replace(/^\!reddit\s/gmi,"") if cmds && cmds != "" && cmds != "!reddit" then subreddit = "/r/"+cmds req.get({url: "https://www.reddit.com"+subreddit+"/hot.json", json: true}, (err, httpResponse, body) -> if err utils.debug("Error occurred getting hot from /r/all", "error") msg.channel.sendMessage("",{embed: { title: "Error Occurred Retrieving Hot Posts from /r/all", color: 6795119 } }) else count = 5 i = 0 if body.data if body.data.children for post in body.data.children if i >= count then break i++ if post.data.thumbnail && post.data.thumbnail != "self" && post.data.thumbnail != "default" && post.data.thumbnail != "spoiler" && post.data.thumbnail.match(/^https\:(.*?)/) msg.channel.sendMessage("",{embed:{ title: "[/"+post.data.subreddit_name_prefixed+"] "+post.data.title, url: "https://www.reddit.com"+post.data.permalink, color: 16728832, type: "rich", fields:[{ name: "Score" value: post.data.score, inline: true },{ name: "Comments" value: post.data.num_comments, inline: true },{ name: "Published" value: moment.unix(post.data.created_utc).format("DD/MM/YYYY [at] HH:mm"), inline: true },{ name: "Author" value: "/u/"+post.data.author, inline: true }], thumbnail: { url: post.data.thumbnail } } }) else msg.channel.sendMessage("",{embed:{ title: "[/"+post.data.subreddit_name_prefixed+"] "+post.data.title, url: "https://www.reddit.com"+post.data.permalink, color: 1601757, type: "rich", fields:[{ name: "Score" value: post.data.score, inline: true },{ name: "Comments" value: post.data.num_comments, inline: true },{ name: "Published" value: moment.unix(post.data.created_utc).format("DD/MM/YYYY [at] HH:mm"), inline: true },{ name: "Author" value: "/u/"+post.data.author, inline: true }] } }) ) msg.delete() else #console.log msg.content #do nothing, aint a command or anything if self.client.channels["432351112616738837"] && msg.author.id != "<PASSWORD>0" d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if self.client.guilds[msg.channel.guild_id] self.client.channels["432351112616738837"].sendMessage(time + " Message sent by <@"+msg.author.id+"> to the <#"+msg.channel_id+"> channel in the "+self.client.guilds[msg.channel.guild_id].name+" guild") else self.client.channels["432351112616738837"].sendMessage(time + " Message sent by <@"+msg.author.id+"> to the <#"+msg.channel_id+"> channel (DM)") ) @client.on("messageUpdate", (msg) -> if self.client.channels["432351112616738837"] && msg.channel_id != "432351112616738837" d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " Message `"+msg.id+"` was updated in the <#"+msg.channel_id+"> channel") ) @client.on("messageDelete", (msg_id, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " desc = time + " Cached Message (`"+msg_id+"`) :link:" self.client.channels["432351112616738837"].sendMessage(time + " Message `"+msg_id+"` was deleted from the <#"+channel.id+"> channel in the "+self.client.guilds[channel.guild_id].name+" guild", { "embed": { "title": desc, "url": "https://motorbot.io/api/message_history/"+msg_id, "color": 38609 } }) ) @client.on("channelCreate", (type, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " The <#"+channel.id+"> channel was created with channel type `"+type+"`") ) @client.on("channelUpdate", (type, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " The <#"+channel.id+"> channel was modified") ) @client.on("channelDelete", (type, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " The channel `"+channel.id+"` was deleted") ) @client.on("channelPinsUpdate", (update) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " Pins updated in channel <#"+update.channel_id+">") ) @client.on("typingStart", (user_id, channel, timestamp) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " <@"+user_id+"> has started typing in the <#"+channel.id+"> channel") ) @client.on("userUpdate", (user_id, username, data) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " <@"+user_id+"> updated their discord profile") ) module.exports = motorbotEventHandler
true
Table = require 'cli-table' keys = require '/var/www/motorbot/keys.json' apiai = require('apiai') apiai = apiai(keys.apiai) #AI for !talk method fs = require 'fs' req = require 'request' moment = require 'moment' cheerio = require 'cheerio' turndown = require 'turndown' class motorbotEventHandler constructor: (@app, @client) -> @setUpEvents() @already_announced = false @challenged = {} @challenger = {} setupSoundboard: (guild_id, filepath, volume = 1) -> self = @ if !self.app.soundboard[guild_id] self.app.client.voiceConnections[guild_id].playFromFile(filepath).then((audioPlayer) -> self.app.soundboard[guild_id] = audioPlayer self.app.org_volume = 0.5 #set default self.app.soundboard[guild_id].on('streamDone', () -> self.app.debug("StreamDone Received") delete self.app.soundboard[guild_id] if self.app.musicPlayers[guild_id] self.app.musicPlayers[guild_id].setVolume(self.app.org_volume) #set back to original volume of music self.app.musicPlayers[guild_id].play() ) self.app.soundboard[guild_id].on('ready', () -> if self.app.musicPlayers[guild_id] self.app.org_volume = self.app.musicPlayers[guild_id].getVolume() self.app.musicPlayers[guild_id].pause() else self.app.soundboard[guild_id].setVolume(volume) self.app.soundboard[guild_id].play() ) self.app.musicPlayers[guild_id].on("paused", () -> if self.app.soundboard[guild_id] self.app.soundboard[guild_id].setVolume(volume) self.app.soundboard[guild_id].play() ) ) else self.app.debug("Soundboard already playing") toTitleCase: (str) -> return str.replace(/\w\S*/g, (txt) -> return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() ); patchListener: (game) -> self = @ if game == "ow" patches = {} p = [] req({ url: "https://playoverwatch.com/en-us/game/patch-notes/pc/" }, (error, httpResponse, body) -> console.log "Overwatch Request Complete" if error then console.log error $ = cheerio.load(body) $(".patch-notes-body").each((i, element) -> p[i] = $(this).attr("id") console.log p[i] desc = $(this).html().replace(/<\/h2>/,'sdfgpoih345e87th').split('sdfgpoih345e87th')[1] patches[$(this).attr("id")] = { patch_id: $(this).attr("id"), title: $(this).find("h1").text(), sub_title: $(this).find("h2").eq(0).text(), desc: desc } ) #find all logged patches patchCollection = self.app.database.collection("patches") patchCollection.find({patch_id: {"$in": p}}).toArray((err, results) -> if err then return console.log err if results[0] console.log "found patches in db" for result in results for patch_id, patch of patches if result.patch_id == patch_id delete patches[patch_id] #remove patch from patches array #process any left patches console.log "processing any left patches" td = new turndown() database_patches = [] for key, new_patch of patches d = new Date() database_patches.push(new_patch) embed_element = { title: self.toTitleCase(new_patch.title), url: "https://playoverwatch.com/en-us/game/patch-notes/pc/#" + new_patch.patch_id, description: new_patch.sub_title + "\n------\n" + td.turndown(new_patch.desc).substring(0, 1000) + "\n\n[Read More](https://playoverwatch.com/en-us/game/patch-notes/pc/#" + new_patch.patch_id+")", color: 16751872, timestamp: d.toISOString(), type: "rich", "footer": { "icon_url": "https://motorbot.io/overwatch_sm.png", "text": "Patch Notification" }, thumbnail: { url: "https://motorbot.io/overwatch_sm.png" } } console.log embed_element self.app.client.channels["438307738250903553"].sendMessage("", { embed: embed_element }) if database_patches.length > 0 patchCollection.insertMany(database_patches) ) ) twitchSubscribeToStream: (user_id) -> # Subscribe to Twitch Webhook Services self = @ req.post({ url: "https://api.twitch.tv/helix/webhooks/hub?hub.mode=subscribe&hub.topic=https://api.twitch.tv/helix/streams?user_id="+user_id+"&hub.callback=https://motorbot.io/twitch/callback&hub.lease_seconds=864000&hub.secret=hexPI:KEY:<KEY>END_PIaver" headers: { "Client-ID": keys.twitch }, json: true }, (error, httpResponse, body) -> self.app.debug("Twitch Webhook Subscription Response Code: "+httpResponse.statusCode, "debug") if error self.app.debug("subscription error to webhook", "error") console.log error ) changeNickname: (guild_id, user_id, user_name, karma) -> # doesn't work for same roles and roles above bots current role ###req({ url: "https://discordapp.com/api/guilds/"+guild_id+"/members/"+user_id, method: "PATCH" headers: { "Authorization": "Bot "+keys.token }, json: true body: { nick: user_name+" ("+karma+")" } }, (err, httpResponse, body) -> if err then console.log err console.log "request complete" console.log body )### rockPaperScissors: (msg, author, choice) -> self = @ compareRPS = (challenged, challengedID, challenger, challengerID, cb) -> outcome = { winner: undefined, challenged: { id: challengedID win: true }, challenger: { id: challengerID win: true } } if challenged.choice == "rock" if challenger.choice == "paper" outcome.challenger.win = true outcome.challenged.win = false outcome.winner = challengerID if challenger.choice == "rock" outcome.challenger.win = true outcome.challenged.win = true outcome.winner = "tie" if challenger.choice == "scissors" outcome.challenger.win = false outcome.challenged.win = true outcome.winner = challengedID else if challenged.choice == "paper" if challenger.choice == "paper" outcome.challenger.win = true outcome.challenged.win = true outcome.winner = "tie" if challenger.choice == "rock" outcome.challenger.win = false outcome.challenged.win = true outcome.winner = challengedID if challenger.choice == "scissors" outcome.challenger.win = true outcome.challenged.win = false outcome.winner = challengerID else if challenged.choice == "scissors" if challenger.choice == "paper" outcome.challenger.win = false outcome.challenged.win = true outcome.winner = challengedID if challenger.choice == "rock" outcome.challenger.win = true outcome.challenged.win = false outcome.winner = challengerID if challenger.choice == "scissors" outcome.challenger.win = true outcome.challenged.win = true outcome.winner = "tie" cb(outcome) if self.challenged[author] self.challenged[author].choice = choice challenger = self.challenger[self.challenged[author].challenger] if self.challenger[self.challenged[author].challenger].choice #both users have made their choice, compare compareRPS(self.challenged[author], author, self.challenger[self.challenged[author].challenger], self.challenged[author].challenger, (outcome) -> if outcome.winner == "tie" challenger.channel.sendMessage("The challenge between <@"+author+"> and <@"+self.challenged[author].challenger+"> resulted in a draw, fight again?") delete self.challenger[self.challenged[author].challenger] delete self.challenged[author] else if self.challenged[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenged[outcome.winner].challenger+">") delete self.challenger[self.challenged[outcome.winner].challenger] delete self.challenged[outcome.winner] else if self.challenger[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenger[outcome.winner].challenged+">") delete self.challenged[self.challenger[outcome.winner].challenged] delete self.challenger[outcome.winner] ) if self.challenger[author] self.challenger[author].choice = choice challenger = self.challenger[author] if self.challenged[self.challenger[author].challenged].choice #both users have made their choice, compare compareRPS(self.challenged[self.challenger[author].challenged], self.challenger[author].challenged, self.challenger[author], author, (outcome) -> if outcome.winner == "tie" challenger.channel.sendMessage("The challenge between <@"+author+"> and <@"+self.challenger[author].challenged+"> resulted in a draw, fight again?") delete self.challenged[self.challenger[author].challenged] delete self.challenger[author] else if self.challenged[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenged[outcome.winner].challenger+">") delete self.challenger[self.challenged[outcome.winner].challenger] delete self.challenged[outcome.winner] else if self.challenger[outcome.winner] challenger.channel.sendMessage("Aaaaaannndd the winner is... <@"+outcome.winner+"> :trophy:, congratulations. Better luck next time <@"+self.challenger[outcome.winner].challenged+">") delete self.challenged[self.challenger[outcome.winner].challenged] delete self.challenger[outcome.winner] ) setUpEvents: () -> self = @ self.twitchSubscribeToStream(22032158) #motorlatitude self.twitchSubscribeToStream(26752266) #mutme self.twitchSubscribeToStream(24991333) #imaqtpie self.twitchSubscribeToStream(22510310) #GDQ #League LCS self.twitchSubscribeToStream(36029255) #RiotGames self.twitchSubscribeToStream(36794584) #RiotGames2 @client.on("ready", () -> self.app.debug("Ready!") ) y = 0 @client.on("guildCreate", (server) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if server.id == "130734377066954752" self.client.channels["432351112616738837"].sendMessage(":x: <@&443191635657097217>","embed": { "title": "MOTORBOT RESTARTED" "description": "Motorbot had to restart either through manual input or due to a fatal error occurring, please consult error logs in console if the latter.", "color": 16724787 }) #self.client.channels["432351112616738837"].sendMessage(time + " Joined Guild: "+server.name+" ("+server.presences.length+" online / "+(parseInt(server.member_count)-server.presences.length)+" offline)") if y == 0 #Listen for patches #setInterval( () -> # self.patchListener("ow") #, 3600000) y = 1 ) @client.on("voiceUpdate_Speaking", (data) -> self.app.websocket.broadcast(JSON.stringify({type: "VOICE_UPDATE_SPEAKING", d:data})) ) voiceStates = {} @client.on("voiceChannelUpdate", (data) -> if data.user_id == '169554882674556930' if data.channel self.app.websocket.broadcast(JSON.stringify({type: "VOICE_UPDATE", d:{status:"JOIN", channel: data.channel.name, channel_id: data.channel.id, channel_obj: data}}, (key, value) -> if key == "client" return undefined else return value )) else self.app.websocket.broadcast(JSON.stringify({type: "VOICE_UPDATE", d:{status:"LEAVE", channel: undefined, channel_id: undefined, channel_obj: data}}, (key, value) -> if key == "client" return undefined else return value )) d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if data.channel if voiceStates[data.user_id] if voiceStates[data.user_id].channel #previously in channel hence channel voice state change #voice state trigger if data.deaf && !voiceStates[data.user_id].deaf #deafened from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> was server deafened in the `"+data.channel.name+"` voice channel") if data.mute && !voiceStates[data.user_id].mute #muted from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> was server muted in the `"+data.channel.name+"` voice channel") if data.self_deaf && !voiceStates[data.user_id].self_deaf #user has deafened himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has deafened them self in the `"+data.channel.name+"` voice channel") if data.self_mute && !voiceStates[data.user_id].self_mute #user has muted himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has muted them self in the `"+data.channel.name+"` voice channel") #voice state trigger reverse if !data.deaf && voiceStates[data.user_id].deaf #undeafened from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer server deafened in the `"+data.channel.name+"` voice channel") if !data.mute && voiceStates[data.user_id].mute #unmuted from server self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer server muted in the `"+data.channel.name+"` voice channel") if !data.self_deaf && voiceStates[data.user_id].self_deaf #user has undeafened himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer deafened in the `"+data.channel.name+"` voice channel") if !data.self_mute && voiceStates[data.user_id].self_mute #user has unmuted himself self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> is no longer muted in the `"+data.channel.name+"` voice channel") else #newly joined self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has joined the `"+data.channel.name+"` voice channel") else self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has joined the `"+data.channel.name+"` voice channel") else self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has left a voice channel") voiceStates[data.user_id] = data ) userStatus = {} @client.on("status", (user_id,status,game,extra_info) -> if extra_info.guild_id == "130734377066954752" #only listening for presence updates in the KTJ guild for now to avoid duplicates across multiple channels if game self.app.debug(user_id+"'s status ("+status+") has changed; "+game.name+"("+game.type+")","notification") else self.app.debug(user_id+"'s status ("+status+") has changed", "notification") d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " gameText = "" statusText = "" additionalString = "" if game extra_info["last_game_update"] = new Date().getTime() if userStatus[user_id] if userStatus[user_id].game if userStatus[user_id].game.name == game.name extra_info["last_game_update"] = userStatus[user_id].last_game_update if game.details additionalString += "\n"+time+" *"+game.details+"*" if game.state additionalString += "\n"+time+" "+game.state if userStatus[user_id] if userStatus[user_id].status == status #no status change, only game update if !game && userStatus[user_id].game if userStatus[user_id].game.type == 0 statusText = " has stopped playing **"+userStatus[user_id].game.name+"** after "+(moment.unix(userStatus[user_id].last_game_update/1000).fromNow()).replace(" ago","") else if userStatus[user_id].game.type == 1 statusText = " has stopped streaming **"+userStatus[user_id].game.name+"** after "+(moment.unix(userStatus[user_id].last_game_update/1000).fromNow()).replace(" ago","") else if userStatus[user_id].game.type == 2 statusText = " has stopped listening to **"+userStatus[user_id].game.name+"** after "+(moment.unix(userStatus[user_id].last_game_update/1000).fromNow()).replace(" ago","") extra_info["last_update"] = userStatus[user_id].last_update else #status change statusText = " was `"+userStatus[user_id].status+"` for "+(moment.unix(userStatus[user_id].last_update/1000).fromNow()).replace(" ago","")+" and is now `"+status+"`" extra_info["last_update"] = new Date().getTime() else #we don't know previous status so assume status change statusText = "'s status has changed to `"+status+"`" extra_info["last_update"] = new Date().getTime() if game && game.type == 0 gameText = " is playing **"+game.name+"**" else if game && game.type == 1 gameText = " is streaming **"+game.name+"**" else if game && game.type == 2 gameText = " is listening to **"+game.name+"**" else gameText = "" #status change if game if userStatus[user_id] if userStatus[user_id].game if userStatus[user_id].game.name == game.name && game.type == 0 gameText = " game presence update :video_game: " else if userStatus[user_id].game.name == game.name && game.type == 2 gameText = " is switching song" someText = if(gameText != "" && statusText != "") then " and"+gameText else gameText if game && game.type == 2 additionalString = "" if game.details additionalString += "\n"+time+" **"+game.details+"**" if game.state additionalString += "\n"+time+" by "+game.state if game.assets.large_text additionalString += "\n"+time+" on "+game.assets.large_text console.log game desc = time+"<@"+user_id+">"+statusText+someText+additionalString thumbnail_url = "" if game.assets if game.assets.large_image thumbnail_id = game.assets.large_image.replace("spotify:","") thumbnail_url = "https://i.scdn.co/image/"+thumbnail_id console.log thumbnail_url self.client.channels["432351112616738837"].sendMessage("","embed": { "description": desc, "color": 2021216, "thumbnail": { "url": thumbnail_url } }) else if statusText == "" && someText == "" && additionalString == "" self.client.channels["432351112616738837"].sendMessage(time+"<@"+user_id+"> is `invisible` and a status refresh event occurred") else self.client.channels["432351112616738837"].sendMessage(time+"<@"+user_id+">"+statusText+someText+additionalString) userStatus[user_id] = extra_info ) @client.on("reaction", (type, data) -> if data.user_id != "169554882674556930" d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if data.emoji.name == "downvote" || data.emoji.name == "upvote" if type == "add" self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has added the `"+data.emoji.name+"` reaction to message `"+data.message_id+"` in channel <#"+data.channel_id+">") #find message for user self.client.channels[data.channel_id].getMessage(data.message_id).then((message) -> author_id = message.author.id karmaCollection = self.app.database.collection("karma_points") karmaCollection.find({"author": author_id}).toArray((err, results) -> if err then return console.log err if results[0] author_karma = results[0].karma else author_karma = 0 if data.emoji.name == "upvote" author_karma += 1 else if data.emoji.name == "downvote" author_karma -= 1 karma_obj = { author: author_id, karma: author_karma } self.client.channels["432351112616738837"].sendMessage(time+"<@"+author_id+"> now has "+author_karma+" karma") karmaCollection.update({author: author_id}, karma_obj, {upsert: true}) self.changeNickname(message.guild_id , author_id, message.author.username, author_karma) ) ).catch((err) -> console.log "Couldn't retrieve message" console.log err ) else if type == "remove" self.client.channels["432351112616738837"].sendMessage(time+"<@"+data.user_id+"> has removed the `"+data.emoji.name+"` reaction on message `"+data.message_id+"` in channel <#"+data.channel_id+">") #find message for user self.client.channels[data.channel_id].getMessage(data.message_id).then((message) -> author_id = message.author.id karmaCollection = self.app.database.collection("karma_points") karmaCollection.find({"author": author_id}).toArray((err, results) -> if err then return console.log err if results[0] author_karma = results[0].karma else author_karma = 0 if data.emoji.name == "upvote" author_karma -= 1 else if data.emoji.name == "downvote" author_karma += 1 karma_obj = { author: author_id, karma: author_karma } self.client.channels["432351112616738837"].sendMessage(time+"<@"+author_id+"> now has "+author_karma+" karma") karmaCollection.update({author: author_id}, karma_obj, {upsert: true}) self.changeNickname(message.guild_id , author_id, message.author.username, author_karma) ) ).catch((err) -> console.log "Couldn't retrieve message" console.log err ) ) @client.on("message", (msg) -> #store all messages messageCollection = self.app.database.collection("messages") db_msg_obj = { id: msg.id, channel_id: msg.channel_id, guild_id: msg.guild_id, author: msg.author, content: msg.content, timestamp: msg.timestamp, edited_timestamp: msg.edited_timestamp, tts: msg.tts, mention_everyone: msg.mention_everyone, mentions: msg.mentions, mention_roles: msg.mention_roles, attachments: msg.attachments, embeds: msg.embeds, reactions: msg.reactions, nonce: msg.nonce, pinned: msg.pinned, webhook_id: msg.webhook_id } messageCollection.update({id: msg.id}, db_msg_obj, {upsert: true}) if msg.content.match(/^\!voice\sjoin/) channelName = msg.content.replace(/^\!voice\sjoin\s/,"") joined = false if channelName for channel in self.client.guilds[msg.guild_id].channels if channel.name == channelName && channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[msg.guild_id] = VoiceConnection ) joined = true break if !joined for channel in self.client.guilds[msg.guild_id].channels if channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[msg.guild_id] = VoiceConnection ) break else if msg.content.match(/^\!voice\s(.*?)\sjoin/) channelName = msg.content.replace(/^\!voice\s(.*?)\sjoin\s/,"") selected_guild_id = msg.content.match(/^\!voice\s(.*?)\sjoin/)[1] console.log msg.author joined = false if self.client.guilds[selected_guild_id] if channelName for channel in self.client.guilds[selected_guild_id].channels if channel.name == channelName && channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[selected_guild_id] = VoiceConnection ) joined = true break if !joined for channel in self.client.guilds[selected_guild_id].channels if channel.type == 2 channel.join().then((VoiceConnection) -> self.app.client.voiceConnections[selected_guild_id] = VoiceConnection ) break else msg.channel.sendMessage("```diff\n- Unknown Server\n```") else if msg.content.match(/^\!voice\s(.*?)\sleave/) selected_guild_id = msg.content.match(/^\!voice\s(.*?)\sleave/)[1] if self.client.guilds[selected_guild_id] self.client.leaveVoiceChannel(selected_guild_id) else msg.channel.sendMessage("```diff\n- Unknown Server\n```") else if msg.content.match(/^!ban doug/gmi) msg.channel.sendMessage("If only I could :rolling_eyes: <@"+msg.author.id+">") else if msg.content.match(/^!kys/gmi) || msg.content.match(/kys/gmi) msg.channel.sendMessage("Calm down before you go and hurt someone <@"+msg.author.id+">") else if msg.content.match(/fight\sme(\sbro|)/gmi) || msg.content.match(/come\sat\sme(\sbro|)/gmi) msg.channel.sendMessage("(ง’̀-‘́)ง") else if msg.content == "!voice leave" self.client.leaveVoiceChannel(msg.guild_id) else if msg.content.match(/heads\sor\stails(\?|)/gmi) if Math.random() >= 0.5 msg.channel.sendMessage(":one: Heads <@"+msg.author.id+">") else msg.channel.sendMessage(":zero: Tails <@"+msg.author.id+">") else if msg.content.match(/\!random/) msg.channel.sendMessage("Random Number: "+(Math.round((Math.random()*100)))) else if msg.content == "!sb diddly" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/DootDiddly.mp3", 5) else if msg.content == "!sb pog" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/play of the game.mp3", 3) else if msg.content == "!sb kled" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Kled.mp3", 3) else if msg.content == "!sb wonder" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/wonder.mp3", 3) else if msg.content == "!sb 1" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/1.mp3", 3) else if msg.content == "!sb 2" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/2.mp3", 3) else if msg.content == "!sb 3" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/3.mp3", 3) else if msg.content == "!sb affirmative" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/affirmative.mp3", 3) else if msg.content == "!sb gp" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/gp.mp3", 3) else if msg.content == "!sb justice" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/justice 3.mp3", 3) else if msg.content == "!sb speed boost" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/speed boost.mp3", 3) else if msg.content == "!sb stop the payload" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/stop the payload.mp3", 3) else if msg.content == "!sb wsr" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/wsr.mp3", 2) else if msg.content == "!sb drop" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/drop_beat.wav", 3) else if msg.content == "!sb tears" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/bings_tears.wav", 3) else if msg.content == "!sb balanced" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/balancing_teams.wav", 3) else if msg.content == "!sb ez mode" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/D.Va_-_Easy_mode.ogg", 3) else if msg.content == "!sb enemy" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Enemy Slain.mp3", 2) else if msg.content == "!sb victory" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Victory.mp3", 2) else if msg.content == "!sb defeat" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Defeat.mp3", 2) else if msg.content == "!sb pentakill" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Pentakill1.mp3", 2) else if msg.content == "!sb happy birthday adz" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/happybirthdayadz.wav", 3) else if msg.content == "!sb airport" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/En-BAW-LHR-boarding.mp3", 2) else if msg.content == "!sb airport de" self.setupSoundboard(msg.guild_id, __dirname+"/soundboard/Ge-DLH-FRA-boarding.mp3", 2) else if msg.content == "!sb stop" if self.app.soundboard[msg.guild_id] self.app.soundboard[msg.guild_id].stop() delete self.app.soundboard[msg.guild_id] else if msg.content == "!sb help" msg.channel.sendMessage("",{ embed: { title: "Soundboard Commands", description: "**!sb diddly** - Doot Diddly\n **!sb pog** - Play Of The Game\n **!sb kled** - I Find Courage Unpredictable...\n **!sb wonder** - And I sometimes wonder...\n **!sb 1** - Overwatch Announcer: One\n **!sb 2** - Overwatch Announcer: Two\n **!sb 3** - Overwatch Announcer: Three\n **!sb affirmative** - Affirmative\n **!sb gp** - 100% German Power\n **!sb justice** - Justice Rains From Above\n **!sb speed boost** - Speed Boost\n **!sb stop the payload** - Stop The Payload\n **!sb wsr** - Welcome To Summoner's Rift\n **!sb happy birthday adz** - Happy Birthday To Adz\n **!sb drop** - Drop The Beat\n **!sb tears** - Brings Tears\n **!sb balanced** - Balancing Teams\n **!sb ez mode** - Is this easy mode?\n **!sb enemy** - Enemy Slain\n **!sb victory** - Victory\n **!sb defeat** - Defeat\n **!sb pentakill** - PENTAKILL\n **!sb airport** - Airport Announcement\n **!sb airport de** - German Airport Announcement\n\n **!sb stop** - Resets the soundboard, useful if the soundboard commands aren't working" color: 39125 } }) else if msg.content == "!help" msg.channel.sendMessage("",{ embed: { title: "Motorbot Commands", description: "**!voice {guild_id} join {channel_name}** *- join a voice channel, {channel_name} and {guild_id} are optional*\n **!voice {guild_id} leave** *- leave voice channel, {guild_id} are optional*\n **!ban doug** *- bans doug*\n **!kys** *- KYS*\n **heads or tails** *- 50/50 chance*\n **fight me** *- you looking for a fight?*\n **cum on me** *- ...*\n **!random** *- generates a random number between 0 and 100*\n **!sb** *- soundboard (!sb help to get help with the soundboard)*\n **!ping** *- pong (dev test)*\n **!dev** *- bunch of dev status commands*\n **!react** *- react test*\n **!lolstat{.region} {summoner_name}** *- lolstat profile, {.region} is optional*\n **!ow {battlenet id}** *- gets some Overwatch Stats*\n **!triggerTyping** *- triggers typing indicator*\n **!reddit {subreddit}** *- gets the top 5 posts for /r/all, unless subreddit is specified e.g. `!reddit linuxmasterrace`* " color: 46066 } }) else if msg.content == "!ping" msg.channel.sendMessage("pong!") else if msg.content.match(/^\!dev client status/) server = msg.guild_id content = "Motorbot is connected to your gateway server on **"+self.client.internals.gateway+"** with an average ping of **"+Math.round(self.client.internals.avgPing*100)/100+"ms**. The last ping was **"+self.client.internals.pings[self.client.internals.pings.length-1]+"ms**." additionalParams = msg.content.replace(/^\!dev client status\s/gmi,"") if additionalParams == "detailed" table = new Table({ style: {'padding-left':1, 'padding-right':1, head:[], border:[]} }) avgPing = Math.round(self.client.internals.avgPing*100)/100 table.push(["Endpoint",self.client.internals.gateway]) table.push(["Average Ping",avgPing+"ms"]) table.push(["Last Ping",self.client.internals.pings[self.client.internals.pings.length-1]+"ms"]) table.push(["Heartbeats Sent",self.client.internals.pings.length]) table.push(["Sequence",self.client.internals.sequence]) table.push(["Connected Guilds",Object.keys(self.client.guilds).length]) table.push(["Channels",Object.keys(self.client.channels).length]) table.push(["Active Voice Handlers",Object.keys(self.client.voiceHandlers).length]) table.push(["Connection Retry Count",self.client.internals.connection_retry_count]) table.push(["Resuming", self.client.internals.resuming]) content = "```markdown\n"+table.toString()+"\n```" msg.channel.sendMessage(content) else if msg.content.match(/^\!dev voice status/) additionalParams = msg.content.replace(/^\!dev voice status\s/gmi,"") server = msg.guild_id if self.client.voiceHandlers[server] bytes = self.client.voiceHandlers[server].bytesTransmitted units = "Bytes" if bytes > 1024 bytes = (Math.round((bytes/1024)*100)/100) units = "KB" if bytes > 1024 bytes = (Math.round((bytes/1024)*100)/100) units = "MB" if bytes > 1024 bytes = (Math.round((bytes/1024)*100)/100) units = "GB" content = "Motorbot is connected to your voice server on **"+self.client.voiceHandlers[server].endpoint+"** with an average ping of **"+Math.round(self.client.voiceHandlers[server].avgPing*100)/100+"ms**. The last ping was **"+self.client.voiceHandlers[server].pings[self.client.voiceHandlers[server].pings.length-1]+"ms**.\n" if additionalParams == "detailed" table = new Table({ #head: ["Parameter","Value"] style: {'padding-left':1, 'padding-right':1, head:[], border:[]} }) avgPing = (Math.round(self.client.voiceHandlers[server].avgPing*100)/100) connectedTime = (Math.round(((new Date().getTime() - self.client.voiceHandlers[server].connectTime)/1000)*10)/10) table.push(["Endpoint",self.client.voiceHandlers[server].endpoint]) table.push(["Local Port",self.client.voiceHandlers[server].localPort]) table.push(["Average Ping",avgPing+"ms"]) table.push(["Last Ping",self.client.voiceHandlers[server].pings[self.client.voiceHandlers[server].pings.length-1]+"ms"]) table.push(["Heartbeats Sent",self.client.voiceHandlers[server].pings.length]) table.push(["Buffer Size",self.client.voiceHandlers[server].buffer_size]) table.push(["Bytes Transmitted",bytes+" "+units]) table.push(["Sequence",self.client.voiceHandlers[server].sequence]) table.push(["Timestamp",self.client.voiceHandlers[server].timestamp]) table.push(["Source ID (ssrc)",self.client.voiceHandlers[server].ssrc]) table.push(["User ID",self.client.voiceHandlers[server].user_id]) table.push(["Session",self.client.voiceHandlers[server].session_id]) table.push(["Token",self.client.voiceHandlers[server].token]) table.push(["Connected",connectedTime+"s"]) content = "```markdown\n"+table.toString()+"\n```" if !self.client.voiceHandlers[server].pings[0] content += "\n```diff\n- Status: Unknown - Too soon to tell\n```" else if avgPing >= 35 content += "\n```diff\n- Status: Poor - Pings a bit high, switch servers?\n```" else if connectedTime >= 172800 content += "\n```diff\n- Status: Sweating - Been working for at least 48 hours straight\n```" else content += "\n```diff\n+ Status: Awesome\n```" msg.channel.sendMessage(content) else msg.channel.sendMessage("```diff\n- Not Currently in voice channel\n```") else if msg.content == "!react" msg.channel.sendMessage("Reacting!") else if msg.content.match(/^!lolstat(\s|\.euw|\.na|\.br|\.eune|\.kr|\.lan|\.las|\.oce|\.ru|\.tr|\.jp)/gmi) region = "euw" if msg.content.replace(/^!lolstat/gmi,"").indexOf(".") > -1 region = msg.content.replace(/^!lolstat/gmi,"").split(".")[1].split(/\s/gmi)[0] summoner = encodeURI(msg.content.replace(/^!lolstat(\s|\.euw|\.na|\.br|\.eune|\.kr|\.lan|\.las|\.oce|\.ru|\.tr|\.jp)/gmi,"").replace(/\s/gmi,"").toLowerCase()) msg.channel.sendMessageWithFile("",req('https://api.lolstat.net/discord/profile/'+summoner+'/'+region), "profile.png") else if msg.content.match(/^!ow\s/gmi) battle_id = msg.content.replace(/^!ow\s/gmi, "").replace("#","-") req({ url: "https://playoverwatch.com/en-gb/career/pc/eu/"+battle_id }, (error, httpResponse, body) -> console.log "Overwatch Request Complete" if error then console.log error $ = cheerio.load(body) wins = $(".masthead .masthead-detail span").text() if wins quickplayStats = "" $("#quickplay > section.content-box.u-max-width-container.highlights-section > div > ul > li").each((i, elem) -> quickplayStats += $(elem).find(".card > .card-content > .card-copy").text().replace(" - Average","")+": "+$(this).find(".card > .card-content > .card-heading").text()+"\n" ) competitiveStats = "" $("#competitive > section.content-box.u-max-width-container.highlights-section > div > ul > li").each((i, elem) -> competitiveStats += $(elem).find(".card > .card-content > .card-copy").text().replace(" - Average","")+": "+$(this).find(".card > .card-content > .card-heading").text()+"\n" ) msg.channel.reply("",{ embed:{ title: $("#overview-section > div > div.u-max-width-container.row.content-box.gutter-18 > div > div > div.masthead-player > h1").text(), url: "https://playoverwatch.com/en-gb/career/pc/eu/"+battle_id, description: wins, color: 16751872, type: "rich", fields:[{ name: "Quick Play" value: quickplayStats, inline: true },{ name: "Competitive" value: competitiveStats, inline: true }], thumbnail: { url: $("#overview-section > div > div.u-max-width-container.row.content-box.gutter-18 > div > div > div.masthead-player > img").attr("src") } } }) else msg.channel.reply("Couldn't find account :(") ) else if msg.content == "!getMessages" console.log "Getting Messages" msg.channel.getMessages({limit: 5}).then((messages) -> console.log messages[0] ).catch((err) -> console.log err.statusMessage ) else if msg.content == "!getInvites" msg.channel.getInvites().then((invites) -> console.log invites ).catch((err) -> console.log err.statusMessage ) else if msg.content == "!createInvite" msg.channel.createInvite().then((invite) -> console.log invite ).catch((err) -> console.log err.statusMessage ) else if msg.content == "!triggerTyping" msg.channel.triggerTyping() else if msg.content.match(/^\!setStatus\s/gmi) newStatus = msg.content.replace(/^\!setStatus\s/gmi,"") self.client.setStatus(newStatus, 0, "online") else if msg.content.match(/^\!setState\s/gmi) newState = msg.content.replace(/^\!setState\s/gmi,"") if newState == "online" || newState == "offline" || newState == "dnd" || newState == "idle" || newState == "invisible" self.client.setStatus(null, 0, newState) else msg.channel.sendMessage("That state is not recognised, please use a standard state as specified here https://discordapp.com/developers/docs/topics/gateway#update-status") else if msg.content.match(/^setChannelName\s/gmi) name = msg.content.replace(/^setChannelName\s/gmi,"") msg.channel.setChannelName(name) else if msg.content.match(/^\!setUserLimit\s/gmi) user_limit = parseInt(msg.content.replace(/^\!setUserLimit\s/gmi,"")) self.client.channels["194904787924418561"].setUserLimit(user_limit) else if msg.content.match(/^\!test_embed/) msg.channel.sendMessage("",{ embed: { title: "Status: Awesome", #description: "Big ass description" color: 6795119, ### fields:[{ name:"name of field" value:"value of field", inline:true },{ name:"name of field" value:"value of field" inline:false }], footer: { text: "squírrel", icon_url: "https://discordapp.com/api/users/95164972807487488/avatars/de1f84de5db24c6681e8447a8106dfd9.jpg" }### } }) else if msg.content == "Reacting!" && msg.author.id == "PI:PASSWORD:<PASSWORD>END_PI" msg.addReaction("%F0%9F%91%BB") else if msg.content.match(/http(s|):\/\//gmi) && msg.channel.id == "130734377066954752" console.log "we got a meme bois" setTimeout( () -> msg.addReaction("\:upvote\:429449534389616641") setTimeout( () -> msg.addReaction("\:downvote\:429449638454493187") , 500) , 500) else if msg.content.match(/^\!challenge\s/gmi) challenged_user = msg.content.split(/\s/gmi)[1] challenged_user_id = challenged_user.replace("<","").replace(">","").replace("@","") challenger_user_id = msg.author.id #if challenged_user_id != challenger_user_id msg.channel.sendMessage("<@"+challenger_user_id+"> has challenged <@"+challenged_user_id+"> to a rock paper scissors duel. Both parties type `!rock`, `!paper` or `!scissors` as a DM to <@169554882674556930>") self.challenged[challenged_user_id] = {} self.challenged[challenged_user_id] = { challenge_in_progress: true, challenger: challenger_user_id, choice: undefined } self.challenger[challenger_user_id] ={} self.challenger[challenger_user_id] = { challenge_in_progress: true, challenged: challenged_user_id, channel: msg.channel, choice: undefined } console.log "CHALLENGED_USER: "+challenged_user #else # msg.channel.sendMessage("Sorry <@"+challenger_user_id+">, you can't challenge yourself :(") else if msg.content.match(/^!rock/) self.rockPaperScissors(msg, msg.author.id, "rock") else if msg.content.match(/^!paper/) self.rockPaperScissors(msg, msg.author.id, "paper") else if msg.content.match(/^!scissors/) self.rockPaperScissors(msg, msg.author.id, "scissors") else if msg.content.match(/^\!reddit/) subreddit = "/r/all" cmds = msg.content.replace(/^\!reddit\s/gmi,"") if cmds && cmds != "" && cmds != "!reddit" then subreddit = "/r/"+cmds req.get({url: "https://www.reddit.com"+subreddit+"/hot.json", json: true}, (err, httpResponse, body) -> if err utils.debug("Error occurred getting hot from /r/all", "error") msg.channel.sendMessage("",{embed: { title: "Error Occurred Retrieving Hot Posts from /r/all", color: 6795119 } }) else count = 5 i = 0 if body.data if body.data.children for post in body.data.children if i >= count then break i++ if post.data.thumbnail && post.data.thumbnail != "self" && post.data.thumbnail != "default" && post.data.thumbnail != "spoiler" && post.data.thumbnail.match(/^https\:(.*?)/) msg.channel.sendMessage("",{embed:{ title: "[/"+post.data.subreddit_name_prefixed+"] "+post.data.title, url: "https://www.reddit.com"+post.data.permalink, color: 16728832, type: "rich", fields:[{ name: "Score" value: post.data.score, inline: true },{ name: "Comments" value: post.data.num_comments, inline: true },{ name: "Published" value: moment.unix(post.data.created_utc).format("DD/MM/YYYY [at] HH:mm"), inline: true },{ name: "Author" value: "/u/"+post.data.author, inline: true }], thumbnail: { url: post.data.thumbnail } } }) else msg.channel.sendMessage("",{embed:{ title: "[/"+post.data.subreddit_name_prefixed+"] "+post.data.title, url: "https://www.reddit.com"+post.data.permalink, color: 1601757, type: "rich", fields:[{ name: "Score" value: post.data.score, inline: true },{ name: "Comments" value: post.data.num_comments, inline: true },{ name: "Published" value: moment.unix(post.data.created_utc).format("DD/MM/YYYY [at] HH:mm"), inline: true },{ name: "Author" value: "/u/"+post.data.author, inline: true }] } }) ) msg.delete() else #console.log msg.content #do nothing, aint a command or anything if self.client.channels["432351112616738837"] && msg.author.id != "PI:PASSWORD:<PASSWORD>END_PI0" d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " if self.client.guilds[msg.channel.guild_id] self.client.channels["432351112616738837"].sendMessage(time + " Message sent by <@"+msg.author.id+"> to the <#"+msg.channel_id+"> channel in the "+self.client.guilds[msg.channel.guild_id].name+" guild") else self.client.channels["432351112616738837"].sendMessage(time + " Message sent by <@"+msg.author.id+"> to the <#"+msg.channel_id+"> channel (DM)") ) @client.on("messageUpdate", (msg) -> if self.client.channels["432351112616738837"] && msg.channel_id != "432351112616738837" d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " Message `"+msg.id+"` was updated in the <#"+msg.channel_id+"> channel") ) @client.on("messageDelete", (msg_id, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " desc = time + " Cached Message (`"+msg_id+"`) :link:" self.client.channels["432351112616738837"].sendMessage(time + " Message `"+msg_id+"` was deleted from the <#"+channel.id+"> channel in the "+self.client.guilds[channel.guild_id].name+" guild", { "embed": { "title": desc, "url": "https://motorbot.io/api/message_history/"+msg_id, "color": 38609 } }) ) @client.on("channelCreate", (type, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " The <#"+channel.id+"> channel was created with channel type `"+type+"`") ) @client.on("channelUpdate", (type, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " The <#"+channel.id+"> channel was modified") ) @client.on("channelDelete", (type, channel) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " The channel `"+channel.id+"` was deleted") ) @client.on("channelPinsUpdate", (update) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " Pins updated in channel <#"+update.channel_id+">") ) @client.on("typingStart", (user_id, channel, timestamp) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " <@"+user_id+"> has started typing in the <#"+channel.id+"> channel") ) @client.on("userUpdate", (user_id, username, data) -> if self.client.channels["432351112616738837"] d = new Date() time = "`["+d.getDate()+"/"+(parseInt(d.getMonth())+1)+"/"+d.getFullYear()+" "+d.toLocaleTimeString()+"]` " self.client.channels["432351112616738837"].sendMessage(time + " <@"+user_id+"> updated their discord profile") ) module.exports = motorbotEventHandler
[ { "context": " width: '300px',\n placeholder: 'Search by Name',\n minimumInputLength: 3,\n ajax:\n ", "end": 1594, "score": 0.5614180564880371, "start": 1590, "tag": "NAME", "value": "Name" } ]
app/assets/javascripts/admin/vocalist_ping.coffee
coronasafe/knowledge
0
handleTargetChanges = -> $('#vocalist_ping_founders').on 'select2:select', () -> clearSelection($('#vocalist_ping_startups')) if $('#vocalist_ping_startups').val() clearSelection($('#vocalist_ping_channel')) if $('#vocalist_ping_channel').val() clearSelection($('#vocalist_ping_levels')) if $('#vocalist_ping_levels').val() $('#vocalist_ping_startups').on 'select2:select', () -> clearSelection($('#vocalist_ping_founders')) if $('#vocalist_ping_founders').val() clearSelection($('#vocalist_ping_channel')) if $('#vocalist_ping_channel').val() clearSelection($('#vocalist_ping_levels')) if $('#vocalist_ping_levels').val() $('#vocalist_ping_levels').on 'select2:select', () -> clearSelection($('#vocalist_ping_founders')) if $('#vocalist_ping_founders').val() clearSelection($('#vocalist_ping_startups')) if $('#vocalist_ping_startups').val() clearSelection($('#vocalist_ping_channel')) if $('#vocalist_ping_channel').val() $('#vocalist_ping_channel').on 'select2:select', () -> clearSelection($('#vocalist_ping_founders')) if $('#vocalist_ping_founders').val() clearSelection($('#vocalist_ping_startups')) if $('#vocalist_ping_startups').val() clearSelection($('#vocalist_ping_levels')) if $('#vocalist_ping_levels').val() initializeSelect2s = -> $('#vocalist_ping_channel').select2(width: '300px'); $('#vocalist_ping_levels').select2(width: '300px'); setupSelect2ForFounder = -> userInput = $('#vocalist_ping_founders') if userInput.length > 0 userInput.select2 width: '300px', placeholder: 'Search by Name', minimumInputLength: 3, ajax: url: '/admin/founders/search_founder', dataType: 'json', delay: 500, data: (params) -> return { q: params.term } , processResults: (data, params) -> return { results: data } cache: true setupSelect2ForStartup = -> userInput = $('#vocalist_ping_startups') if userInput.length > 0 userInput.select2 width: '300px', placeholder: 'Search by Product Name', minimumInputLength: 3, ajax: url: '/admin/startups/search_startup', dataType: 'json', delay: 500, data: (params) -> return { q: params.term } , processResults: (data, params) -> return { results: data } cache: true clearSelection = (element) -> element.val(null).trigger('change') $(document).on 'turbolinks:load', -> if $('#new_vocalist_ping').length initializeSelect2s() handleTargetChanges() setupSelect2ForStartup() setupSelect2ForFounder()
180068
handleTargetChanges = -> $('#vocalist_ping_founders').on 'select2:select', () -> clearSelection($('#vocalist_ping_startups')) if $('#vocalist_ping_startups').val() clearSelection($('#vocalist_ping_channel')) if $('#vocalist_ping_channel').val() clearSelection($('#vocalist_ping_levels')) if $('#vocalist_ping_levels').val() $('#vocalist_ping_startups').on 'select2:select', () -> clearSelection($('#vocalist_ping_founders')) if $('#vocalist_ping_founders').val() clearSelection($('#vocalist_ping_channel')) if $('#vocalist_ping_channel').val() clearSelection($('#vocalist_ping_levels')) if $('#vocalist_ping_levels').val() $('#vocalist_ping_levels').on 'select2:select', () -> clearSelection($('#vocalist_ping_founders')) if $('#vocalist_ping_founders').val() clearSelection($('#vocalist_ping_startups')) if $('#vocalist_ping_startups').val() clearSelection($('#vocalist_ping_channel')) if $('#vocalist_ping_channel').val() $('#vocalist_ping_channel').on 'select2:select', () -> clearSelection($('#vocalist_ping_founders')) if $('#vocalist_ping_founders').val() clearSelection($('#vocalist_ping_startups')) if $('#vocalist_ping_startups').val() clearSelection($('#vocalist_ping_levels')) if $('#vocalist_ping_levels').val() initializeSelect2s = -> $('#vocalist_ping_channel').select2(width: '300px'); $('#vocalist_ping_levels').select2(width: '300px'); setupSelect2ForFounder = -> userInput = $('#vocalist_ping_founders') if userInput.length > 0 userInput.select2 width: '300px', placeholder: 'Search by <NAME>', minimumInputLength: 3, ajax: url: '/admin/founders/search_founder', dataType: 'json', delay: 500, data: (params) -> return { q: params.term } , processResults: (data, params) -> return { results: data } cache: true setupSelect2ForStartup = -> userInput = $('#vocalist_ping_startups') if userInput.length > 0 userInput.select2 width: '300px', placeholder: 'Search by Product Name', minimumInputLength: 3, ajax: url: '/admin/startups/search_startup', dataType: 'json', delay: 500, data: (params) -> return { q: params.term } , processResults: (data, params) -> return { results: data } cache: true clearSelection = (element) -> element.val(null).trigger('change') $(document).on 'turbolinks:load', -> if $('#new_vocalist_ping').length initializeSelect2s() handleTargetChanges() setupSelect2ForStartup() setupSelect2ForFounder()
true
handleTargetChanges = -> $('#vocalist_ping_founders').on 'select2:select', () -> clearSelection($('#vocalist_ping_startups')) if $('#vocalist_ping_startups').val() clearSelection($('#vocalist_ping_channel')) if $('#vocalist_ping_channel').val() clearSelection($('#vocalist_ping_levels')) if $('#vocalist_ping_levels').val() $('#vocalist_ping_startups').on 'select2:select', () -> clearSelection($('#vocalist_ping_founders')) if $('#vocalist_ping_founders').val() clearSelection($('#vocalist_ping_channel')) if $('#vocalist_ping_channel').val() clearSelection($('#vocalist_ping_levels')) if $('#vocalist_ping_levels').val() $('#vocalist_ping_levels').on 'select2:select', () -> clearSelection($('#vocalist_ping_founders')) if $('#vocalist_ping_founders').val() clearSelection($('#vocalist_ping_startups')) if $('#vocalist_ping_startups').val() clearSelection($('#vocalist_ping_channel')) if $('#vocalist_ping_channel').val() $('#vocalist_ping_channel').on 'select2:select', () -> clearSelection($('#vocalist_ping_founders')) if $('#vocalist_ping_founders').val() clearSelection($('#vocalist_ping_startups')) if $('#vocalist_ping_startups').val() clearSelection($('#vocalist_ping_levels')) if $('#vocalist_ping_levels').val() initializeSelect2s = -> $('#vocalist_ping_channel').select2(width: '300px'); $('#vocalist_ping_levels').select2(width: '300px'); setupSelect2ForFounder = -> userInput = $('#vocalist_ping_founders') if userInput.length > 0 userInput.select2 width: '300px', placeholder: 'Search by PI:NAME:<NAME>END_PI', minimumInputLength: 3, ajax: url: '/admin/founders/search_founder', dataType: 'json', delay: 500, data: (params) -> return { q: params.term } , processResults: (data, params) -> return { results: data } cache: true setupSelect2ForStartup = -> userInput = $('#vocalist_ping_startups') if userInput.length > 0 userInput.select2 width: '300px', placeholder: 'Search by Product Name', minimumInputLength: 3, ajax: url: '/admin/startups/search_startup', dataType: 'json', delay: 500, data: (params) -> return { q: params.term } , processResults: (data, params) -> return { results: data } cache: true clearSelection = (element) -> element.val(null).trigger('change') $(document).on 'turbolinks:load', -> if $('#new_vocalist_ping').length initializeSelect2s() handleTargetChanges() setupSelect2ForStartup() setupSelect2ForFounder()
[ { "context": " newItem = collection.template()\n name = \"Joe Test\"\n email = \"test@test.com\"\n blog = \"", "end": 2453, "score": 0.9997832179069519, "start": 2445, "tag": "NAME", "value": "Joe Test" }, { "context": "late()\n name = \"Joe Test\"\n ...
test/attributes.coffee
collection-json/collection-json.js
16
should = require "should" fs = require "fs" _ = require "underscore" cj = require ".." describe "Attributes", -> describe "[Original](http://amundsen.com/media-types/collection/)", -> collection = null data = null before -> data = require "./fixtures/original" beforeEach (done)-> cj.parse data, (error, _collection)-> throw error if error collection = _collection done() describe "[collection](http://amundsen.com/media-types/collection/format/#objects-collection)", -> it "should have a version", -> collection.version.should.equal data.collection.version it "should have an href", -> collection.href.should.equal data.collection.href it "should throw an exception with a bad version number", -> cj.parse {collection: version: "1.1"}, (error, col)-> should.exist error, "No error was returned" it "should throw an exception with a malformed collection", -> cj.parse {version: "1.1"}, (error, col)-> should.exist error, "No error was returned" describe "[error](http://amundsen.com/media-types/collection/format/#objects-error)", -> it "should have an error", -> errorData = require("./fixtures/error") cj.parse errorData, (error, errorCol)-> should.exist error, "An error was not returned" should.exist errorCol, "The collection with the error was not returned" error.title.should.equal errorData.collection.error.title error.code.should.equal errorData.collection.error.code error.message.should.equal errorData.collection.error.message errorCol.error.title.should.equal errorData.collection.error.title errorCol.error.code.should.equal errorData.collection.error.code errorCol.error.message.should.equal errorData.collection.error.message describe "[template](http://amundsen.com/media-types/collection/format/#objects-template)", -> it "should iterate properties template", -> template = collection.template() for key, value of template.form orig = _.find data.collection.template.data, (datum)-> datum.name is key key.should.equal orig.name value.should.equal orig.value template.promptFor(key).should.equal orig.prompt it "should be able to set values", -> newItem = collection.template() name = "Joe Test" email = "test@test.com" blog = "joe.blogger.com" avatar = "http://www.gravatar.com/avatar/dafd213c94afdd64f9dc4fa92f9710ea?s=512" newItem.set "full-name", name newItem.set "email", email newItem.set "blog", blog newItem.set "avatar", avatar newItem.get("full-name").should.equal name newItem.get("email").should.equal email newItem.get("blog").should.equal blog newItem.get("avatar").should.equal avatar it "should return a datum given a name", -> newItem = collection.template() fullName = newItem.datum("full-name") fullName.name.should.equal "full-name" fullName.prompt.should.equal "Full Name" fullName.value.should.equal "Joe" describe "[items](http://amundsen.com/media-types/collection/format/#arrays-items)", -> it "should iterate items", -> for idx, item of collection.items orig = data.collection.items[idx] item.href.should.equal orig.href it "should get a value", -> for idx, item of collection.items orig = data.collection.items[idx] for datum in orig.data itemDatum = item.get(datum.name) should.exist itemDatum, "Item does not have #{datum.name}" itemDatum.should.equal datum.value describe "[queries](http://amundsen.com/media-types/collection/format/#arrays-queries)", -> it "should iterate queries", -> for query in collection.queries orig = _.find data.collection.queries, (_query)-> _query.rel is query.rel query.href.should.equal orig.href query.rel.should.equal orig.rel query.prompt.should.equal orig.prompt it "should be able to set values", -> searchQuery = collection.query "search" searchQuery.set "search", "Testing" searchQuery.get("search").should.equal "Testing" it "should get a query by rel", -> for orig in data.collection.queries searchQuery = collection.query orig.rel searchQuery.href.should.equal orig.href searchQuery.rel.should.equal orig.rel searchQuery.prompt.should.equal orig.prompt describe "[links](http://amundsen.com/media-types/collection/format/#arrays-links)", -> it "should get iterate the links", -> for link in collection.links orig = _.find data.collection.links, (_link)-> _link.rel is link.rel link.href.should.equal orig.href link.rel.should.equal orig.rel link.prompt.should.equal orig.prompt it "should get a link by rel", -> for orig in data.collection.links link = collection.link(orig.rel) link.href.should.equal orig.href link.rel.should.equal orig.rel link.prompt.should.equal orig.prompt describe "[Extensions](https://github.com/mamund/collection-json/tree/master/extensions)", -> describe "[errors](https://github.com/mamund/collection-json/blob/master/extensions/errors.md)", -> it "need tests" describe "[inline](https://github.com/mamund/collection-json/blob/master/extensions/inline.md)", -> it "need tests" describe "[model](https://github.com/mamund/collection-json/blob/master/extensions/model.md)", -> it "need tests" describe "[template-validation](https://github.com/mamund/collection-json/blob/master/extensions/template-validation.md)", -> it "need tests" describe "[templates](https://github.com/mamund/collection-json/blob/master/extensions/templates.md)", -> it "need tests" describe "[uri-templates](https://github.com/mamund/collection-json/blob/master/extensions/uri-templates.md)", -> it "need tests" describe "[value-types](https://github.com/mamund/collection-json/blob/master/extensions/value-types.md)", -> it "need tests"
222233
should = require "should" fs = require "fs" _ = require "underscore" cj = require ".." describe "Attributes", -> describe "[Original](http://amundsen.com/media-types/collection/)", -> collection = null data = null before -> data = require "./fixtures/original" beforeEach (done)-> cj.parse data, (error, _collection)-> throw error if error collection = _collection done() describe "[collection](http://amundsen.com/media-types/collection/format/#objects-collection)", -> it "should have a version", -> collection.version.should.equal data.collection.version it "should have an href", -> collection.href.should.equal data.collection.href it "should throw an exception with a bad version number", -> cj.parse {collection: version: "1.1"}, (error, col)-> should.exist error, "No error was returned" it "should throw an exception with a malformed collection", -> cj.parse {version: "1.1"}, (error, col)-> should.exist error, "No error was returned" describe "[error](http://amundsen.com/media-types/collection/format/#objects-error)", -> it "should have an error", -> errorData = require("./fixtures/error") cj.parse errorData, (error, errorCol)-> should.exist error, "An error was not returned" should.exist errorCol, "The collection with the error was not returned" error.title.should.equal errorData.collection.error.title error.code.should.equal errorData.collection.error.code error.message.should.equal errorData.collection.error.message errorCol.error.title.should.equal errorData.collection.error.title errorCol.error.code.should.equal errorData.collection.error.code errorCol.error.message.should.equal errorData.collection.error.message describe "[template](http://amundsen.com/media-types/collection/format/#objects-template)", -> it "should iterate properties template", -> template = collection.template() for key, value of template.form orig = _.find data.collection.template.data, (datum)-> datum.name is key key.should.equal orig.name value.should.equal orig.value template.promptFor(key).should.equal orig.prompt it "should be able to set values", -> newItem = collection.template() name = "<NAME>" email = "<EMAIL>" blog = "joe.blogger.com" avatar = "http://www.gravatar.com/avatar/dafd213c94afdd64f9dc4fa92f9710ea?s=512" newItem.set "full-name", name newItem.set "email", email newItem.set "blog", blog newItem.set "avatar", avatar newItem.get("full-name").should.equal name newItem.get("email").should.equal email newItem.get("blog").should.equal blog newItem.get("avatar").should.equal avatar it "should return a datum given a name", -> newItem = collection.template() fullName = newItem.datum("full-name") fullName.name.should.equal "full-name" fullName.prompt.should.equal "Full Name" fullName.value.should.equal "<NAME>" describe "[items](http://amundsen.com/media-types/collection/format/#arrays-items)", -> it "should iterate items", -> for idx, item of collection.items orig = data.collection.items[idx] item.href.should.equal orig.href it "should get a value", -> for idx, item of collection.items orig = data.collection.items[idx] for datum in orig.data itemDatum = item.get(datum.name) should.exist itemDatum, "Item does not have #{datum.name}" itemDatum.should.equal datum.value describe "[queries](http://amundsen.com/media-types/collection/format/#arrays-queries)", -> it "should iterate queries", -> for query in collection.queries orig = _.find data.collection.queries, (_query)-> _query.rel is query.rel query.href.should.equal orig.href query.rel.should.equal orig.rel query.prompt.should.equal orig.prompt it "should be able to set values", -> searchQuery = collection.query "search" searchQuery.set "search", "Testing" searchQuery.get("search").should.equal "Testing" it "should get a query by rel", -> for orig in data.collection.queries searchQuery = collection.query orig.rel searchQuery.href.should.equal orig.href searchQuery.rel.should.equal orig.rel searchQuery.prompt.should.equal orig.prompt describe "[links](http://amundsen.com/media-types/collection/format/#arrays-links)", -> it "should get iterate the links", -> for link in collection.links orig = _.find data.collection.links, (_link)-> _link.rel is link.rel link.href.should.equal orig.href link.rel.should.equal orig.rel link.prompt.should.equal orig.prompt it "should get a link by rel", -> for orig in data.collection.links link = collection.link(orig.rel) link.href.should.equal orig.href link.rel.should.equal orig.rel link.prompt.should.equal orig.prompt describe "[Extensions](https://github.com/mamund/collection-json/tree/master/extensions)", -> describe "[errors](https://github.com/mamund/collection-json/blob/master/extensions/errors.md)", -> it "need tests" describe "[inline](https://github.com/mamund/collection-json/blob/master/extensions/inline.md)", -> it "need tests" describe "[model](https://github.com/mamund/collection-json/blob/master/extensions/model.md)", -> it "need tests" describe "[template-validation](https://github.com/mamund/collection-json/blob/master/extensions/template-validation.md)", -> it "need tests" describe "[templates](https://github.com/mamund/collection-json/blob/master/extensions/templates.md)", -> it "need tests" describe "[uri-templates](https://github.com/mamund/collection-json/blob/master/extensions/uri-templates.md)", -> it "need tests" describe "[value-types](https://github.com/mamund/collection-json/blob/master/extensions/value-types.md)", -> it "need tests"
true
should = require "should" fs = require "fs" _ = require "underscore" cj = require ".." describe "Attributes", -> describe "[Original](http://amundsen.com/media-types/collection/)", -> collection = null data = null before -> data = require "./fixtures/original" beforeEach (done)-> cj.parse data, (error, _collection)-> throw error if error collection = _collection done() describe "[collection](http://amundsen.com/media-types/collection/format/#objects-collection)", -> it "should have a version", -> collection.version.should.equal data.collection.version it "should have an href", -> collection.href.should.equal data.collection.href it "should throw an exception with a bad version number", -> cj.parse {collection: version: "1.1"}, (error, col)-> should.exist error, "No error was returned" it "should throw an exception with a malformed collection", -> cj.parse {version: "1.1"}, (error, col)-> should.exist error, "No error was returned" describe "[error](http://amundsen.com/media-types/collection/format/#objects-error)", -> it "should have an error", -> errorData = require("./fixtures/error") cj.parse errorData, (error, errorCol)-> should.exist error, "An error was not returned" should.exist errorCol, "The collection with the error was not returned" error.title.should.equal errorData.collection.error.title error.code.should.equal errorData.collection.error.code error.message.should.equal errorData.collection.error.message errorCol.error.title.should.equal errorData.collection.error.title errorCol.error.code.should.equal errorData.collection.error.code errorCol.error.message.should.equal errorData.collection.error.message describe "[template](http://amundsen.com/media-types/collection/format/#objects-template)", -> it "should iterate properties template", -> template = collection.template() for key, value of template.form orig = _.find data.collection.template.data, (datum)-> datum.name is key key.should.equal orig.name value.should.equal orig.value template.promptFor(key).should.equal orig.prompt it "should be able to set values", -> newItem = collection.template() name = "PI:NAME:<NAME>END_PI" email = "PI:EMAIL:<EMAIL>END_PI" blog = "joe.blogger.com" avatar = "http://www.gravatar.com/avatar/dafd213c94afdd64f9dc4fa92f9710ea?s=512" newItem.set "full-name", name newItem.set "email", email newItem.set "blog", blog newItem.set "avatar", avatar newItem.get("full-name").should.equal name newItem.get("email").should.equal email newItem.get("blog").should.equal blog newItem.get("avatar").should.equal avatar it "should return a datum given a name", -> newItem = collection.template() fullName = newItem.datum("full-name") fullName.name.should.equal "full-name" fullName.prompt.should.equal "Full Name" fullName.value.should.equal "PI:NAME:<NAME>END_PI" describe "[items](http://amundsen.com/media-types/collection/format/#arrays-items)", -> it "should iterate items", -> for idx, item of collection.items orig = data.collection.items[idx] item.href.should.equal orig.href it "should get a value", -> for idx, item of collection.items orig = data.collection.items[idx] for datum in orig.data itemDatum = item.get(datum.name) should.exist itemDatum, "Item does not have #{datum.name}" itemDatum.should.equal datum.value describe "[queries](http://amundsen.com/media-types/collection/format/#arrays-queries)", -> it "should iterate queries", -> for query in collection.queries orig = _.find data.collection.queries, (_query)-> _query.rel is query.rel query.href.should.equal orig.href query.rel.should.equal orig.rel query.prompt.should.equal orig.prompt it "should be able to set values", -> searchQuery = collection.query "search" searchQuery.set "search", "Testing" searchQuery.get("search").should.equal "Testing" it "should get a query by rel", -> for orig in data.collection.queries searchQuery = collection.query orig.rel searchQuery.href.should.equal orig.href searchQuery.rel.should.equal orig.rel searchQuery.prompt.should.equal orig.prompt describe "[links](http://amundsen.com/media-types/collection/format/#arrays-links)", -> it "should get iterate the links", -> for link in collection.links orig = _.find data.collection.links, (_link)-> _link.rel is link.rel link.href.should.equal orig.href link.rel.should.equal orig.rel link.prompt.should.equal orig.prompt it "should get a link by rel", -> for orig in data.collection.links link = collection.link(orig.rel) link.href.should.equal orig.href link.rel.should.equal orig.rel link.prompt.should.equal orig.prompt describe "[Extensions](https://github.com/mamund/collection-json/tree/master/extensions)", -> describe "[errors](https://github.com/mamund/collection-json/blob/master/extensions/errors.md)", -> it "need tests" describe "[inline](https://github.com/mamund/collection-json/blob/master/extensions/inline.md)", -> it "need tests" describe "[model](https://github.com/mamund/collection-json/blob/master/extensions/model.md)", -> it "need tests" describe "[template-validation](https://github.com/mamund/collection-json/blob/master/extensions/template-validation.md)", -> it "need tests" describe "[templates](https://github.com/mamund/collection-json/blob/master/extensions/templates.md)", -> it "need tests" describe "[uri-templates](https://github.com/mamund/collection-json/blob/master/extensions/uri-templates.md)", -> it "need tests" describe "[value-types](https://github.com/mamund/collection-json/blob/master/extensions/value-types.md)", -> it "need tests"
[ { "context": " when 1\n\n console.log \"Doubler\"\n\n delayF.close()\n ", "end": 2316, "score": 0.8464075922966003, "start": 2309, "tag": "NAME", "value": "Doubler" } ]
website/prototypes/audioprocess/src/App.coffee
GyanaPrasannaa/oz-experiment
0
$ -> window.URL = (window.URL || window.webkitURL) navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia) $(document).ready -> console.log "* App ready" # Create michrophone mic = new Mic # Effects Controller effects = { available : { normal : -1, delay : 0, doubler : 1, distortion : 2, flange : 3 } } # Add and position dat.gui gui = new dat.GUI { autoPlace: false } customContainer = $(".dat-gui")[0] customContainer.appendChild gui.domElement # Effects folder effectsF = gui.addFolder "Choose an effect" effectsSelect = effectsF.add effects, 'available', effects.available effectsSelect.listen() effectsF.open() # Delay effect delayF = gui.addFolder "Delay" delayF.add mic, "delayTime", 0.15, 3 # Doubler effect doublerF = gui.addFolder "Doubler" doublerF.add mic, "doublerDelay", 0.1, 1 # Distortion effect distortionF = gui.addFolder "Distortion" distortionF.add mic, "distortionDrive", 0, 40 # Flange effect flangeF = gui.addFolder "Flange" flangeF.add mic, "flangeDelay", 0.001, 0.02, 0.001 flangeF.add mic, "flangeDepth", 0.0005, 0.005, 0.00025 flangeF.add mic, "flangeSpeed", 0.05, 5, 0.05 flangeF.add mic, "flangeFeedback", 0, 1, 0.01 # Change events effectsSelect.onChange ( value ) => switch Number value when -1 console.log "Normal" delayF.close() doublerF.close() distortionF.close() flangeF.close() when 0 console.log "Delay" delayF.open() doublerF.close() distortionF.close() flangeF.close() when 1 console.log "Doubler" delayF.close() doublerF.open() distortionF.close() flangeF.close() when 2 console.log "Distortion" delayF.close() doublerF.close() distortionF.open() flangeF.close() when 3 console.log "Flange" delayF.close() doublerF.close() distortionF.close() flangeF.open() else console.log "none" mic.changeEffect Number value # Default effect effects.available = 1 doublerF.open() # Canvas simple visualizer $("canvas")[0].width = $(document).width() $("canvas")[0].height = $(document).height() - 122
126635
$ -> window.URL = (window.URL || window.webkitURL) navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia) $(document).ready -> console.log "* App ready" # Create michrophone mic = new Mic # Effects Controller effects = { available : { normal : -1, delay : 0, doubler : 1, distortion : 2, flange : 3 } } # Add and position dat.gui gui = new dat.GUI { autoPlace: false } customContainer = $(".dat-gui")[0] customContainer.appendChild gui.domElement # Effects folder effectsF = gui.addFolder "Choose an effect" effectsSelect = effectsF.add effects, 'available', effects.available effectsSelect.listen() effectsF.open() # Delay effect delayF = gui.addFolder "Delay" delayF.add mic, "delayTime", 0.15, 3 # Doubler effect doublerF = gui.addFolder "Doubler" doublerF.add mic, "doublerDelay", 0.1, 1 # Distortion effect distortionF = gui.addFolder "Distortion" distortionF.add mic, "distortionDrive", 0, 40 # Flange effect flangeF = gui.addFolder "Flange" flangeF.add mic, "flangeDelay", 0.001, 0.02, 0.001 flangeF.add mic, "flangeDepth", 0.0005, 0.005, 0.00025 flangeF.add mic, "flangeSpeed", 0.05, 5, 0.05 flangeF.add mic, "flangeFeedback", 0, 1, 0.01 # Change events effectsSelect.onChange ( value ) => switch Number value when -1 console.log "Normal" delayF.close() doublerF.close() distortionF.close() flangeF.close() when 0 console.log "Delay" delayF.open() doublerF.close() distortionF.close() flangeF.close() when 1 console.log "<NAME>" delayF.close() doublerF.open() distortionF.close() flangeF.close() when 2 console.log "Distortion" delayF.close() doublerF.close() distortionF.open() flangeF.close() when 3 console.log "Flange" delayF.close() doublerF.close() distortionF.close() flangeF.open() else console.log "none" mic.changeEffect Number value # Default effect effects.available = 1 doublerF.open() # Canvas simple visualizer $("canvas")[0].width = $(document).width() $("canvas")[0].height = $(document).height() - 122
true
$ -> window.URL = (window.URL || window.webkitURL) navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia) $(document).ready -> console.log "* App ready" # Create michrophone mic = new Mic # Effects Controller effects = { available : { normal : -1, delay : 0, doubler : 1, distortion : 2, flange : 3 } } # Add and position dat.gui gui = new dat.GUI { autoPlace: false } customContainer = $(".dat-gui")[0] customContainer.appendChild gui.domElement # Effects folder effectsF = gui.addFolder "Choose an effect" effectsSelect = effectsF.add effects, 'available', effects.available effectsSelect.listen() effectsF.open() # Delay effect delayF = gui.addFolder "Delay" delayF.add mic, "delayTime", 0.15, 3 # Doubler effect doublerF = gui.addFolder "Doubler" doublerF.add mic, "doublerDelay", 0.1, 1 # Distortion effect distortionF = gui.addFolder "Distortion" distortionF.add mic, "distortionDrive", 0, 40 # Flange effect flangeF = gui.addFolder "Flange" flangeF.add mic, "flangeDelay", 0.001, 0.02, 0.001 flangeF.add mic, "flangeDepth", 0.0005, 0.005, 0.00025 flangeF.add mic, "flangeSpeed", 0.05, 5, 0.05 flangeF.add mic, "flangeFeedback", 0, 1, 0.01 # Change events effectsSelect.onChange ( value ) => switch Number value when -1 console.log "Normal" delayF.close() doublerF.close() distortionF.close() flangeF.close() when 0 console.log "Delay" delayF.open() doublerF.close() distortionF.close() flangeF.close() when 1 console.log "PI:NAME:<NAME>END_PI" delayF.close() doublerF.open() distortionF.close() flangeF.close() when 2 console.log "Distortion" delayF.close() doublerF.close() distortionF.open() flangeF.close() when 3 console.log "Flange" delayF.close() doublerF.close() distortionF.close() flangeF.open() else console.log "none" mic.changeEffect Number value # Default effect effects.available = 1 doublerF.open() # Canvas simple visualizer $("canvas")[0].width = $(document).width() $("canvas")[0].height = $(document).height() - 122
[ { "context": "cement interaction jQuery UI widget\n# (c) 2011 Szaby Gruenwald, IKS Consortium\n# Annotate may be freely dist", "end": 95, "score": 0.9998635649681091, "start": 80, "tag": "NAME", "value": "Szaby Gruenwald" } ]
src/annotate.coffee
IKS/annotate.js
2
### Annotate - a text enhancement interaction jQuery UI widget # (c) 2011 Szaby Gruenwald, IKS Consortium # Annotate may be freely distributed under the MIT license ### # define namespaces ns = rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' enhancer: 'http://fise.iks-project.eu/ontology/' dcterms: 'http://purl.org/dc/terms/' rdfs: 'http://www.w3.org/2000/01/rdf-schema#' skos: 'http://www.w3.org/2004/02/skos/core#' root = this jQuery = root.jQuery Backbone = root.Backbone _ = root._ VIE = root.VIE vie = new VIE() vie.use(new vie.StanbolService({ url : "http://dev.iks-project.eu:8080", proxyDisabled: true })); vie.namespaces.add "skos", ns.skos # In Internet Explorer String.trim is not defined but we're going to use it. String.prototype.trim ?= -> @replace /^\s+|\s+$/g, '' # calling the get with a scope and callback will call cb(entity) with the scope as soon it's available.' class EntityCache constructor: (opts) -> @vie = opts.vie @logger = opts.logger _entities: -> window.entityCache ?= {} get: (uri, scope, success, error) -> uri = uri.replace /^<|>$/g, "" # If entity is stored in the cache already just call cb if @_entities()[uri] and @_entities()[uri].status is "done" if typeof success is "function" success.apply scope, [@_entities()[uri].entity] else if @_entities()[uri] and @_entities()[uri].status is "error" if typeof error is "function" error.apply scope, ["error"] # If the entity is new to the cache else if not @_entities()[uri] # create cache entry @_entities()[uri] = status: "pending" uri: uri cache = @ # make a request to the entity hub @vie.load({entity: uri}).using('stanbol').execute().success (entityArr) => _.defer => cacheEntry = @_entities()[uri] entity = _.detect entityArr, (e) -> true if e.getSubject() is "<#{uri}>" if entity cacheEntry.entity = entity cacheEntry.status = "done" $(cacheEntry).trigger "done", entity else @logger.warn "couldn''t load #{uri}", entityArr cacheEntry.status = "not found" .fail (e) => _.defer => @logger.error "couldn't load #{uri}" cacheEntry = @_entities()[uri] cacheEntry.status = "error" $(cacheEntry).trigger "fail", e if @_entities()[uri] and @_entities()[uri].status is "pending" $( @_entities()[uri] ) .bind "done", (event, entity) -> if typeof success is "function" success.apply scope, [entity] .bind "fail", (event, error) -> if typeof error is "function" error.apply scope, [error] # Give back the last part of a uri for fallback label creation uriSuffix = (uri) -> res = uri.substring uri.lastIndexOf("#") + 1 res.substring res.lastIndexOf("/") + 1 ###################################################### # Annotate widget # makes a content dom element interactively annotatable ###################################################### jQuery.widget 'IKS.annotate', __widgetName: "IKS.annotate" options: # VIE instance to use for (backend) enhancement vie: vie vieServices: ["stanbol"] # Do analyze on instantiation autoAnalyze: false # Keeps continouosly checking in the background, while typing continuousChecking: false # Wait for some time (in ms) for the user not typing, before it starts analyzing. throttleDistance: 5000 # Tooltip can be disabled showTooltip: true # Debug can be enabled debug: false # Define Entity properties for finding depiction depictionProperties: [ "foaf:depiction" "schema:thumbnail" ] # Lookup for a label will inspect these properties of an entity labelProperties: [ "rdfs:label" "skos:prefLabel" "schema:name" "foaf:name" ] # Lookup for a description will inspect these properties of an entity descriptionProperties: [ "rdfs:comment" "skos:note" "schema:description" "skos:definition" property: "skos:broader" makeLabel: (propertyValueArr) -> labels = _(propertyValueArr).map (termUri) -> # extract the last part of the uri termUri .replace(/<.*[\/#](.*)>/, "$1") .replace /_/g, "&nbsp;" "Subcategory of #{labels.join ', '}." , property: "dcterms:subject" makeLabel: (propertyValueArr) -> labels = _(propertyValueArr).map (termUri) -> # extract the last part of the uri termUri .replace(/<.*[\/#](.*)>/, "$1") .replace /_/g, "&nbsp;" "Subject(s): #{labels.join ', '}." ] # If label and description is not available in the user's language # look for a fallback. fallbackLanguage: "en" # namespaces necessary for the widget configuration ns: dbpedia: "http://dbpedia.org/ontology/" skos: "http://www.w3.org/2004/02/skos/core#" # List of enhancement types to filter for typeFilter: null annotationInteractionWidget: "annotationInteraction" # Give a label to your expected enhancement types getTypes: -> [ uri: "#{@ns.dbpedia}Place" label: 'Place' , uri: "#{@ns.dbpedia}Person" label: 'Person' , uri: "#{@ns.dbpedia}Organisation" label: 'Organisation' , uri: "#{@ns.skos}Concept" label: 'Concept' ] # Give a label to the sources the entities come from getSources: -> [ uri: "http://dbpedia.org/resource/" label: "dbpedia" , uri: "http://sws.geonames.org/" label: "geonames" ] # widget specific constructor _create: -> widget = @ # logger can be turned on and off. It will show the real caller line in the log @_logger = if @options.debug then console else info: -> warn: -> error: -> log: -> # widget.entityCache.get(uri, cb) will get and cache the entity from an entityhub @entityCache = new EntityCache vie: @options.vie logger: @_logger if @options.autoAnalyze @enable() unless jQuery().tooltip @options.showTooltip = false @_logger.warn "the used jQuery UI doesn't support tooltips, disabling." @_initExistingAnnotations() _destroy: -> do @disable $( ':iks-annotationselector', @element ).each () -> $(@).annotationSelector 'destroy' if $(@).data().annotationSelector @_destroyExistingAnnotationInteractionWidgets() # analyze the widget element and show text enhancements enable: -> if @options.continuousChecking checkerFn = delayThrottle => @_checkForChanges() , @options.throttleDistance $(@element).bind 'keyup', => checkerFn() @_checkForChanges() _checkForChanges: -> for el in @_findElementsToAnalyze() hash = @_elementHash el unless jQuery(el).data('hash') console.info el, "wasn't analized yet." @_analyze el if jQuery(el).data('hash') and jQuery(el).data('hash') isnt hash console.info el, 'changed, try to get annotations for it.' @_analyze el _elementHash: (el) -> jQuery(el).text().hashCode() _findElementsToAnalyze: -> @_listNonblockElements @element _analyze: (el) -> hash = @_elementHash el # the analyzedDocUri makes the connection between a document state and # the annotations to it. We have to clean up the annotations to any # old document state @options.vie.analyze( element: jQuery el ).using(@options.vieServices) .execute() .success (enhancements) => if @_elementHash(el) is hash console.info 'applying suggestions to', el, enhancements @_applyEnhancements el, enhancements jQuery(el).data 'hash', hash else console.info el, 'changed in the meantime.' @_trigger "success", true .fail (xhr) => @_trigger 'error', xhr @_logger.error "analyze failed", xhr.responseText, xhr _applyEnhancements: (el, enhancements) -> _.defer => # Link TextAnnotation entities to EntityAnnotations entityAnnotations = Stanbol.getEntityAnnotations(enhancements) for entAnn in entityAnnotations textAnns = entAnn.get "dcterms:relation" unless textAnns @_logger.error "For #{entAnn.getSubject()} dcterms:relation is not set! This makes this EntityAnnotation unusable!", entAnn continue for textAnn in _.flatten([textAnns]) textAnn = entAnn.vie.entities.get textAnn unless textAnn instanceof Backbone.Model continue unless textAnn _(_.flatten([textAnn])).each (ta) -> ta.setOrAdd "entityAnnotation": entAnn.getSubject() # Get enhancements textAnnotations = Stanbol.getTextAnnotations(enhancements) textAnnotations = @_filterByType textAnnotations # Remove all textAnnotations without a selected text property textAnnotations = _(textAnnotations) .filter (textEnh) -> if textEnh.getSelectedText and textEnh.getSelectedText() true else false _(textAnnotations) .each (s) => @_logger.info s._enhancement, 'confidence', s.getConfidence(), 'selectedText', s.getSelectedText(), 'type', s.getType(), 'EntityEnhancements', s.getEntityEnhancements() # Process the text enhancements @_processTextEnhancement s, el # Remove all not accepted text enhancement widgets disable: -> $( ':IKS-annotationSelector', @element ).each () -> $(@).annotationSelector 'disable' if $(@).data().annotationSelector _initExistingAnnotations: -> @existingAnnotations = jQuery "a[resource]", @element @_logger.info @existingAnnotations @existingAnnotations[@options.annotationInteractionWidget] @options _destroyExistingAnnotationInteractionWidgets: -> @existingAnnotations[@options.annotationInteractionWidget] "destroy" @existingAnnotations = [] # accept the best (first) suggestion for all text enhancement. acceptAll: (reportCallback) -> report = {updated: [], accepted: 0} $( ':IKS-annotationSelector', @element ).each () -> if $(@).data().annotationSelector res = $(@).annotationSelector 'acceptBestCandidate' if res report.updated.push @ report.accepted++ reportCallback report # Internal methods # Devide an element into smaller chunks that can be analyzed in smaller portions. _listNonblockElements: (el) -> # An element is devidable if the sum of all it's children's text is it's own text. Otherwise it has textnodes that are no dom tags. isDevidable = (el) => sum = "" for child in jQuery(el).children() sum += jQuery(child).text().replace /\s\s*/g, "" jQuery(el).text().replace(/\s\s*/g, "") is sum res = jQuery [] if isDevidable el jQuery(el).children().each (i, ch) => res = res.add @_listNonblockElements(ch) else res = res.add jQuery el res # processTextEnhancement deals with one TextEnhancement in an ancestor element of its occurrence _processTextEnhancement: (textEnh, parentEl) -> if not textEnh.getSelectedText() @_logger.warn "textEnh", textEnh, "doesn't have selected-text!" return el = $ @_getOrCreateDomElement parentEl, textEnh.getSelectedText(), createElement: 'span' createMode: 'existing' context: textEnh.getContext() start: textEnh.getStart() end: textEnh.getEnd() sType = textEnh.getType() or "Other" widget = @ el.addClass('entity') for type in sType el.addClass uriSuffix(type).toLowerCase() if textEnh.getEntityEnhancements().length el.addClass "withSuggestions" for eEnh in textEnh.getEntityEnhancements() eEnhUri = eEnh.getUri() @entityCache.get eEnhUri, eEnh, (entity) => if "<#{eEnhUri}>" is entity.getSubject() @_logger.info "entity #{eEnhUri} is loaded:", entity.as "JSON" else widget._logger.info "forwarded entity for #{eEnhUri} loaded:", entity.getSubject() # Create widget to select from the suggested entities options = @options options.cache = @entityCache options.annotateElement = @element el.annotationSelector( options ) .annotationSelector 'addTextEnhancement', textEnh _filterByType: (textAnnotations) -> return textAnnotations unless @options.typeFilter _.filter textAnnotations, (ta) => return yes if @options.typeFilter in ta.getType() for type in @options.typeFilter return yes if type in ta.getType() # get or create a dom element containing only the occurrence of the found entity _getOrCreateDomElement: (element, text, options = {}) -> # Find occurrence indexes of s in str occurrences = (str, s) -> res = [] last = 0 while str.indexOf(s, last + 1) isnt -1 next = str.indexOf s, last+1 res.push next last = next # Find the nearest number among the nearest = (arr, nr) -> _(arr).sortedIndex nr # Nearest position nearestPosition = (str, s, ind) -> arr = occurrences(str,s) i1 = nearest arr, ind if arr.length is 1 arr[0] else if i1 is arr.length arr[i1-1] else i0 = i1-1 d0 = ind - arr[i0] d1 = arr[i1] - ind if d1 > d0 then arr[i0] else arr[i1] domEl = element textContentOf = (element) -> $(element).text().replace(/\n/g, " ") # find the text node if textContentOf(element).indexOf(text) is -1 @_logger.error "'#{text}' doesn't appear in the text block." return $() start = options.start + textContentOf(element).indexOf textContentOf(element).trim() # Correct small position errors start = nearestPosition textContentOf(element), text, start pos = 0 while textContentOf(domEl).indexOf(text) isnt -1 and domEl.nodeName isnt '#text' domEl = _(domEl.childNodes).detect (el) -> p = textContentOf(el).lastIndexOf text if p >= start - pos true else pos += textContentOf(el).length false if options.createMode is "existing" and textContentOf($(domEl).parent()) is text return $(domEl).parent()[0] else pos = start - pos len = text.length textToCut = textContentOf(domEl).substring(pos, pos+len) if textToCut is text domEl.splitText pos + len newElement = document.createElement options.createElement or 'span' newElement.innerHTML = text $(domEl).parent()[0].replaceChild newElement, domEl.splitText pos $ newElement else @_logger.warn "dom element creation problem: #{textToCut} isnt #{text}" # Similar to the Java String.hashCode() method, it calculates a hash value of the string. String::hashCode = -> hash = 0 return hash if @length is 0 i = 0 while i < @length char = @charCodeAt(i) hash = ((hash << 5) - hash) + char hash = hash & hash i++ hash # For throttling keyup events, this method sets up an event handler function resFn that only triggers the callback function cb after # being called the resFn at least once AND not being called for timout milliseconds. delayThrottle = (cb, timeout) -> timeoutHandler = null resFn = -> if timeoutHandler clearTimeout(timeoutHandler) timeoutHandler = setTimeout -> timeoutHandler = null cb() , timeout
217709
### Annotate - a text enhancement interaction jQuery UI widget # (c) 2011 <NAME>, IKS Consortium # Annotate may be freely distributed under the MIT license ### # define namespaces ns = rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' enhancer: 'http://fise.iks-project.eu/ontology/' dcterms: 'http://purl.org/dc/terms/' rdfs: 'http://www.w3.org/2000/01/rdf-schema#' skos: 'http://www.w3.org/2004/02/skos/core#' root = this jQuery = root.jQuery Backbone = root.Backbone _ = root._ VIE = root.VIE vie = new VIE() vie.use(new vie.StanbolService({ url : "http://dev.iks-project.eu:8080", proxyDisabled: true })); vie.namespaces.add "skos", ns.skos # In Internet Explorer String.trim is not defined but we're going to use it. String.prototype.trim ?= -> @replace /^\s+|\s+$/g, '' # calling the get with a scope and callback will call cb(entity) with the scope as soon it's available.' class EntityCache constructor: (opts) -> @vie = opts.vie @logger = opts.logger _entities: -> window.entityCache ?= {} get: (uri, scope, success, error) -> uri = uri.replace /^<|>$/g, "" # If entity is stored in the cache already just call cb if @_entities()[uri] and @_entities()[uri].status is "done" if typeof success is "function" success.apply scope, [@_entities()[uri].entity] else if @_entities()[uri] and @_entities()[uri].status is "error" if typeof error is "function" error.apply scope, ["error"] # If the entity is new to the cache else if not @_entities()[uri] # create cache entry @_entities()[uri] = status: "pending" uri: uri cache = @ # make a request to the entity hub @vie.load({entity: uri}).using('stanbol').execute().success (entityArr) => _.defer => cacheEntry = @_entities()[uri] entity = _.detect entityArr, (e) -> true if e.getSubject() is "<#{uri}>" if entity cacheEntry.entity = entity cacheEntry.status = "done" $(cacheEntry).trigger "done", entity else @logger.warn "couldn''t load #{uri}", entityArr cacheEntry.status = "not found" .fail (e) => _.defer => @logger.error "couldn't load #{uri}" cacheEntry = @_entities()[uri] cacheEntry.status = "error" $(cacheEntry).trigger "fail", e if @_entities()[uri] and @_entities()[uri].status is "pending" $( @_entities()[uri] ) .bind "done", (event, entity) -> if typeof success is "function" success.apply scope, [entity] .bind "fail", (event, error) -> if typeof error is "function" error.apply scope, [error] # Give back the last part of a uri for fallback label creation uriSuffix = (uri) -> res = uri.substring uri.lastIndexOf("#") + 1 res.substring res.lastIndexOf("/") + 1 ###################################################### # Annotate widget # makes a content dom element interactively annotatable ###################################################### jQuery.widget 'IKS.annotate', __widgetName: "IKS.annotate" options: # VIE instance to use for (backend) enhancement vie: vie vieServices: ["stanbol"] # Do analyze on instantiation autoAnalyze: false # Keeps continouosly checking in the background, while typing continuousChecking: false # Wait for some time (in ms) for the user not typing, before it starts analyzing. throttleDistance: 5000 # Tooltip can be disabled showTooltip: true # Debug can be enabled debug: false # Define Entity properties for finding depiction depictionProperties: [ "foaf:depiction" "schema:thumbnail" ] # Lookup for a label will inspect these properties of an entity labelProperties: [ "rdfs:label" "skos:prefLabel" "schema:name" "foaf:name" ] # Lookup for a description will inspect these properties of an entity descriptionProperties: [ "rdfs:comment" "skos:note" "schema:description" "skos:definition" property: "skos:broader" makeLabel: (propertyValueArr) -> labels = _(propertyValueArr).map (termUri) -> # extract the last part of the uri termUri .replace(/<.*[\/#](.*)>/, "$1") .replace /_/g, "&nbsp;" "Subcategory of #{labels.join ', '}." , property: "dcterms:subject" makeLabel: (propertyValueArr) -> labels = _(propertyValueArr).map (termUri) -> # extract the last part of the uri termUri .replace(/<.*[\/#](.*)>/, "$1") .replace /_/g, "&nbsp;" "Subject(s): #{labels.join ', '}." ] # If label and description is not available in the user's language # look for a fallback. fallbackLanguage: "en" # namespaces necessary for the widget configuration ns: dbpedia: "http://dbpedia.org/ontology/" skos: "http://www.w3.org/2004/02/skos/core#" # List of enhancement types to filter for typeFilter: null annotationInteractionWidget: "annotationInteraction" # Give a label to your expected enhancement types getTypes: -> [ uri: "#{@ns.dbpedia}Place" label: 'Place' , uri: "#{@ns.dbpedia}Person" label: 'Person' , uri: "#{@ns.dbpedia}Organisation" label: 'Organisation' , uri: "#{@ns.skos}Concept" label: 'Concept' ] # Give a label to the sources the entities come from getSources: -> [ uri: "http://dbpedia.org/resource/" label: "dbpedia" , uri: "http://sws.geonames.org/" label: "geonames" ] # widget specific constructor _create: -> widget = @ # logger can be turned on and off. It will show the real caller line in the log @_logger = if @options.debug then console else info: -> warn: -> error: -> log: -> # widget.entityCache.get(uri, cb) will get and cache the entity from an entityhub @entityCache = new EntityCache vie: @options.vie logger: @_logger if @options.autoAnalyze @enable() unless jQuery().tooltip @options.showTooltip = false @_logger.warn "the used jQuery UI doesn't support tooltips, disabling." @_initExistingAnnotations() _destroy: -> do @disable $( ':iks-annotationselector', @element ).each () -> $(@).annotationSelector 'destroy' if $(@).data().annotationSelector @_destroyExistingAnnotationInteractionWidgets() # analyze the widget element and show text enhancements enable: -> if @options.continuousChecking checkerFn = delayThrottle => @_checkForChanges() , @options.throttleDistance $(@element).bind 'keyup', => checkerFn() @_checkForChanges() _checkForChanges: -> for el in @_findElementsToAnalyze() hash = @_elementHash el unless jQuery(el).data('hash') console.info el, "wasn't analized yet." @_analyze el if jQuery(el).data('hash') and jQuery(el).data('hash') isnt hash console.info el, 'changed, try to get annotations for it.' @_analyze el _elementHash: (el) -> jQuery(el).text().hashCode() _findElementsToAnalyze: -> @_listNonblockElements @element _analyze: (el) -> hash = @_elementHash el # the analyzedDocUri makes the connection between a document state and # the annotations to it. We have to clean up the annotations to any # old document state @options.vie.analyze( element: jQuery el ).using(@options.vieServices) .execute() .success (enhancements) => if @_elementHash(el) is hash console.info 'applying suggestions to', el, enhancements @_applyEnhancements el, enhancements jQuery(el).data 'hash', hash else console.info el, 'changed in the meantime.' @_trigger "success", true .fail (xhr) => @_trigger 'error', xhr @_logger.error "analyze failed", xhr.responseText, xhr _applyEnhancements: (el, enhancements) -> _.defer => # Link TextAnnotation entities to EntityAnnotations entityAnnotations = Stanbol.getEntityAnnotations(enhancements) for entAnn in entityAnnotations textAnns = entAnn.get "dcterms:relation" unless textAnns @_logger.error "For #{entAnn.getSubject()} dcterms:relation is not set! This makes this EntityAnnotation unusable!", entAnn continue for textAnn in _.flatten([textAnns]) textAnn = entAnn.vie.entities.get textAnn unless textAnn instanceof Backbone.Model continue unless textAnn _(_.flatten([textAnn])).each (ta) -> ta.setOrAdd "entityAnnotation": entAnn.getSubject() # Get enhancements textAnnotations = Stanbol.getTextAnnotations(enhancements) textAnnotations = @_filterByType textAnnotations # Remove all textAnnotations without a selected text property textAnnotations = _(textAnnotations) .filter (textEnh) -> if textEnh.getSelectedText and textEnh.getSelectedText() true else false _(textAnnotations) .each (s) => @_logger.info s._enhancement, 'confidence', s.getConfidence(), 'selectedText', s.getSelectedText(), 'type', s.getType(), 'EntityEnhancements', s.getEntityEnhancements() # Process the text enhancements @_processTextEnhancement s, el # Remove all not accepted text enhancement widgets disable: -> $( ':IKS-annotationSelector', @element ).each () -> $(@).annotationSelector 'disable' if $(@).data().annotationSelector _initExistingAnnotations: -> @existingAnnotations = jQuery "a[resource]", @element @_logger.info @existingAnnotations @existingAnnotations[@options.annotationInteractionWidget] @options _destroyExistingAnnotationInteractionWidgets: -> @existingAnnotations[@options.annotationInteractionWidget] "destroy" @existingAnnotations = [] # accept the best (first) suggestion for all text enhancement. acceptAll: (reportCallback) -> report = {updated: [], accepted: 0} $( ':IKS-annotationSelector', @element ).each () -> if $(@).data().annotationSelector res = $(@).annotationSelector 'acceptBestCandidate' if res report.updated.push @ report.accepted++ reportCallback report # Internal methods # Devide an element into smaller chunks that can be analyzed in smaller portions. _listNonblockElements: (el) -> # An element is devidable if the sum of all it's children's text is it's own text. Otherwise it has textnodes that are no dom tags. isDevidable = (el) => sum = "" for child in jQuery(el).children() sum += jQuery(child).text().replace /\s\s*/g, "" jQuery(el).text().replace(/\s\s*/g, "") is sum res = jQuery [] if isDevidable el jQuery(el).children().each (i, ch) => res = res.add @_listNonblockElements(ch) else res = res.add jQuery el res # processTextEnhancement deals with one TextEnhancement in an ancestor element of its occurrence _processTextEnhancement: (textEnh, parentEl) -> if not textEnh.getSelectedText() @_logger.warn "textEnh", textEnh, "doesn't have selected-text!" return el = $ @_getOrCreateDomElement parentEl, textEnh.getSelectedText(), createElement: 'span' createMode: 'existing' context: textEnh.getContext() start: textEnh.getStart() end: textEnh.getEnd() sType = textEnh.getType() or "Other" widget = @ el.addClass('entity') for type in sType el.addClass uriSuffix(type).toLowerCase() if textEnh.getEntityEnhancements().length el.addClass "withSuggestions" for eEnh in textEnh.getEntityEnhancements() eEnhUri = eEnh.getUri() @entityCache.get eEnhUri, eEnh, (entity) => if "<#{eEnhUri}>" is entity.getSubject() @_logger.info "entity #{eEnhUri} is loaded:", entity.as "JSON" else widget._logger.info "forwarded entity for #{eEnhUri} loaded:", entity.getSubject() # Create widget to select from the suggested entities options = @options options.cache = @entityCache options.annotateElement = @element el.annotationSelector( options ) .annotationSelector 'addTextEnhancement', textEnh _filterByType: (textAnnotations) -> return textAnnotations unless @options.typeFilter _.filter textAnnotations, (ta) => return yes if @options.typeFilter in ta.getType() for type in @options.typeFilter return yes if type in ta.getType() # get or create a dom element containing only the occurrence of the found entity _getOrCreateDomElement: (element, text, options = {}) -> # Find occurrence indexes of s in str occurrences = (str, s) -> res = [] last = 0 while str.indexOf(s, last + 1) isnt -1 next = str.indexOf s, last+1 res.push next last = next # Find the nearest number among the nearest = (arr, nr) -> _(arr).sortedIndex nr # Nearest position nearestPosition = (str, s, ind) -> arr = occurrences(str,s) i1 = nearest arr, ind if arr.length is 1 arr[0] else if i1 is arr.length arr[i1-1] else i0 = i1-1 d0 = ind - arr[i0] d1 = arr[i1] - ind if d1 > d0 then arr[i0] else arr[i1] domEl = element textContentOf = (element) -> $(element).text().replace(/\n/g, " ") # find the text node if textContentOf(element).indexOf(text) is -1 @_logger.error "'#{text}' doesn't appear in the text block." return $() start = options.start + textContentOf(element).indexOf textContentOf(element).trim() # Correct small position errors start = nearestPosition textContentOf(element), text, start pos = 0 while textContentOf(domEl).indexOf(text) isnt -1 and domEl.nodeName isnt '#text' domEl = _(domEl.childNodes).detect (el) -> p = textContentOf(el).lastIndexOf text if p >= start - pos true else pos += textContentOf(el).length false if options.createMode is "existing" and textContentOf($(domEl).parent()) is text return $(domEl).parent()[0] else pos = start - pos len = text.length textToCut = textContentOf(domEl).substring(pos, pos+len) if textToCut is text domEl.splitText pos + len newElement = document.createElement options.createElement or 'span' newElement.innerHTML = text $(domEl).parent()[0].replaceChild newElement, domEl.splitText pos $ newElement else @_logger.warn "dom element creation problem: #{textToCut} isnt #{text}" # Similar to the Java String.hashCode() method, it calculates a hash value of the string. String::hashCode = -> hash = 0 return hash if @length is 0 i = 0 while i < @length char = @charCodeAt(i) hash = ((hash << 5) - hash) + char hash = hash & hash i++ hash # For throttling keyup events, this method sets up an event handler function resFn that only triggers the callback function cb after # being called the resFn at least once AND not being called for timout milliseconds. delayThrottle = (cb, timeout) -> timeoutHandler = null resFn = -> if timeoutHandler clearTimeout(timeoutHandler) timeoutHandler = setTimeout -> timeoutHandler = null cb() , timeout
true
### Annotate - a text enhancement interaction jQuery UI widget # (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium # Annotate may be freely distributed under the MIT license ### # define namespaces ns = rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' enhancer: 'http://fise.iks-project.eu/ontology/' dcterms: 'http://purl.org/dc/terms/' rdfs: 'http://www.w3.org/2000/01/rdf-schema#' skos: 'http://www.w3.org/2004/02/skos/core#' root = this jQuery = root.jQuery Backbone = root.Backbone _ = root._ VIE = root.VIE vie = new VIE() vie.use(new vie.StanbolService({ url : "http://dev.iks-project.eu:8080", proxyDisabled: true })); vie.namespaces.add "skos", ns.skos # In Internet Explorer String.trim is not defined but we're going to use it. String.prototype.trim ?= -> @replace /^\s+|\s+$/g, '' # calling the get with a scope and callback will call cb(entity) with the scope as soon it's available.' class EntityCache constructor: (opts) -> @vie = opts.vie @logger = opts.logger _entities: -> window.entityCache ?= {} get: (uri, scope, success, error) -> uri = uri.replace /^<|>$/g, "" # If entity is stored in the cache already just call cb if @_entities()[uri] and @_entities()[uri].status is "done" if typeof success is "function" success.apply scope, [@_entities()[uri].entity] else if @_entities()[uri] and @_entities()[uri].status is "error" if typeof error is "function" error.apply scope, ["error"] # If the entity is new to the cache else if not @_entities()[uri] # create cache entry @_entities()[uri] = status: "pending" uri: uri cache = @ # make a request to the entity hub @vie.load({entity: uri}).using('stanbol').execute().success (entityArr) => _.defer => cacheEntry = @_entities()[uri] entity = _.detect entityArr, (e) -> true if e.getSubject() is "<#{uri}>" if entity cacheEntry.entity = entity cacheEntry.status = "done" $(cacheEntry).trigger "done", entity else @logger.warn "couldn''t load #{uri}", entityArr cacheEntry.status = "not found" .fail (e) => _.defer => @logger.error "couldn't load #{uri}" cacheEntry = @_entities()[uri] cacheEntry.status = "error" $(cacheEntry).trigger "fail", e if @_entities()[uri] and @_entities()[uri].status is "pending" $( @_entities()[uri] ) .bind "done", (event, entity) -> if typeof success is "function" success.apply scope, [entity] .bind "fail", (event, error) -> if typeof error is "function" error.apply scope, [error] # Give back the last part of a uri for fallback label creation uriSuffix = (uri) -> res = uri.substring uri.lastIndexOf("#") + 1 res.substring res.lastIndexOf("/") + 1 ###################################################### # Annotate widget # makes a content dom element interactively annotatable ###################################################### jQuery.widget 'IKS.annotate', __widgetName: "IKS.annotate" options: # VIE instance to use for (backend) enhancement vie: vie vieServices: ["stanbol"] # Do analyze on instantiation autoAnalyze: false # Keeps continouosly checking in the background, while typing continuousChecking: false # Wait for some time (in ms) for the user not typing, before it starts analyzing. throttleDistance: 5000 # Tooltip can be disabled showTooltip: true # Debug can be enabled debug: false # Define Entity properties for finding depiction depictionProperties: [ "foaf:depiction" "schema:thumbnail" ] # Lookup for a label will inspect these properties of an entity labelProperties: [ "rdfs:label" "skos:prefLabel" "schema:name" "foaf:name" ] # Lookup for a description will inspect these properties of an entity descriptionProperties: [ "rdfs:comment" "skos:note" "schema:description" "skos:definition" property: "skos:broader" makeLabel: (propertyValueArr) -> labels = _(propertyValueArr).map (termUri) -> # extract the last part of the uri termUri .replace(/<.*[\/#](.*)>/, "$1") .replace /_/g, "&nbsp;" "Subcategory of #{labels.join ', '}." , property: "dcterms:subject" makeLabel: (propertyValueArr) -> labels = _(propertyValueArr).map (termUri) -> # extract the last part of the uri termUri .replace(/<.*[\/#](.*)>/, "$1") .replace /_/g, "&nbsp;" "Subject(s): #{labels.join ', '}." ] # If label and description is not available in the user's language # look for a fallback. fallbackLanguage: "en" # namespaces necessary for the widget configuration ns: dbpedia: "http://dbpedia.org/ontology/" skos: "http://www.w3.org/2004/02/skos/core#" # List of enhancement types to filter for typeFilter: null annotationInteractionWidget: "annotationInteraction" # Give a label to your expected enhancement types getTypes: -> [ uri: "#{@ns.dbpedia}Place" label: 'Place' , uri: "#{@ns.dbpedia}Person" label: 'Person' , uri: "#{@ns.dbpedia}Organisation" label: 'Organisation' , uri: "#{@ns.skos}Concept" label: 'Concept' ] # Give a label to the sources the entities come from getSources: -> [ uri: "http://dbpedia.org/resource/" label: "dbpedia" , uri: "http://sws.geonames.org/" label: "geonames" ] # widget specific constructor _create: -> widget = @ # logger can be turned on and off. It will show the real caller line in the log @_logger = if @options.debug then console else info: -> warn: -> error: -> log: -> # widget.entityCache.get(uri, cb) will get and cache the entity from an entityhub @entityCache = new EntityCache vie: @options.vie logger: @_logger if @options.autoAnalyze @enable() unless jQuery().tooltip @options.showTooltip = false @_logger.warn "the used jQuery UI doesn't support tooltips, disabling." @_initExistingAnnotations() _destroy: -> do @disable $( ':iks-annotationselector', @element ).each () -> $(@).annotationSelector 'destroy' if $(@).data().annotationSelector @_destroyExistingAnnotationInteractionWidgets() # analyze the widget element and show text enhancements enable: -> if @options.continuousChecking checkerFn = delayThrottle => @_checkForChanges() , @options.throttleDistance $(@element).bind 'keyup', => checkerFn() @_checkForChanges() _checkForChanges: -> for el in @_findElementsToAnalyze() hash = @_elementHash el unless jQuery(el).data('hash') console.info el, "wasn't analized yet." @_analyze el if jQuery(el).data('hash') and jQuery(el).data('hash') isnt hash console.info el, 'changed, try to get annotations for it.' @_analyze el _elementHash: (el) -> jQuery(el).text().hashCode() _findElementsToAnalyze: -> @_listNonblockElements @element _analyze: (el) -> hash = @_elementHash el # the analyzedDocUri makes the connection between a document state and # the annotations to it. We have to clean up the annotations to any # old document state @options.vie.analyze( element: jQuery el ).using(@options.vieServices) .execute() .success (enhancements) => if @_elementHash(el) is hash console.info 'applying suggestions to', el, enhancements @_applyEnhancements el, enhancements jQuery(el).data 'hash', hash else console.info el, 'changed in the meantime.' @_trigger "success", true .fail (xhr) => @_trigger 'error', xhr @_logger.error "analyze failed", xhr.responseText, xhr _applyEnhancements: (el, enhancements) -> _.defer => # Link TextAnnotation entities to EntityAnnotations entityAnnotations = Stanbol.getEntityAnnotations(enhancements) for entAnn in entityAnnotations textAnns = entAnn.get "dcterms:relation" unless textAnns @_logger.error "For #{entAnn.getSubject()} dcterms:relation is not set! This makes this EntityAnnotation unusable!", entAnn continue for textAnn in _.flatten([textAnns]) textAnn = entAnn.vie.entities.get textAnn unless textAnn instanceof Backbone.Model continue unless textAnn _(_.flatten([textAnn])).each (ta) -> ta.setOrAdd "entityAnnotation": entAnn.getSubject() # Get enhancements textAnnotations = Stanbol.getTextAnnotations(enhancements) textAnnotations = @_filterByType textAnnotations # Remove all textAnnotations without a selected text property textAnnotations = _(textAnnotations) .filter (textEnh) -> if textEnh.getSelectedText and textEnh.getSelectedText() true else false _(textAnnotations) .each (s) => @_logger.info s._enhancement, 'confidence', s.getConfidence(), 'selectedText', s.getSelectedText(), 'type', s.getType(), 'EntityEnhancements', s.getEntityEnhancements() # Process the text enhancements @_processTextEnhancement s, el # Remove all not accepted text enhancement widgets disable: -> $( ':IKS-annotationSelector', @element ).each () -> $(@).annotationSelector 'disable' if $(@).data().annotationSelector _initExistingAnnotations: -> @existingAnnotations = jQuery "a[resource]", @element @_logger.info @existingAnnotations @existingAnnotations[@options.annotationInteractionWidget] @options _destroyExistingAnnotationInteractionWidgets: -> @existingAnnotations[@options.annotationInteractionWidget] "destroy" @existingAnnotations = [] # accept the best (first) suggestion for all text enhancement. acceptAll: (reportCallback) -> report = {updated: [], accepted: 0} $( ':IKS-annotationSelector', @element ).each () -> if $(@).data().annotationSelector res = $(@).annotationSelector 'acceptBestCandidate' if res report.updated.push @ report.accepted++ reportCallback report # Internal methods # Devide an element into smaller chunks that can be analyzed in smaller portions. _listNonblockElements: (el) -> # An element is devidable if the sum of all it's children's text is it's own text. Otherwise it has textnodes that are no dom tags. isDevidable = (el) => sum = "" for child in jQuery(el).children() sum += jQuery(child).text().replace /\s\s*/g, "" jQuery(el).text().replace(/\s\s*/g, "") is sum res = jQuery [] if isDevidable el jQuery(el).children().each (i, ch) => res = res.add @_listNonblockElements(ch) else res = res.add jQuery el res # processTextEnhancement deals with one TextEnhancement in an ancestor element of its occurrence _processTextEnhancement: (textEnh, parentEl) -> if not textEnh.getSelectedText() @_logger.warn "textEnh", textEnh, "doesn't have selected-text!" return el = $ @_getOrCreateDomElement parentEl, textEnh.getSelectedText(), createElement: 'span' createMode: 'existing' context: textEnh.getContext() start: textEnh.getStart() end: textEnh.getEnd() sType = textEnh.getType() or "Other" widget = @ el.addClass('entity') for type in sType el.addClass uriSuffix(type).toLowerCase() if textEnh.getEntityEnhancements().length el.addClass "withSuggestions" for eEnh in textEnh.getEntityEnhancements() eEnhUri = eEnh.getUri() @entityCache.get eEnhUri, eEnh, (entity) => if "<#{eEnhUri}>" is entity.getSubject() @_logger.info "entity #{eEnhUri} is loaded:", entity.as "JSON" else widget._logger.info "forwarded entity for #{eEnhUri} loaded:", entity.getSubject() # Create widget to select from the suggested entities options = @options options.cache = @entityCache options.annotateElement = @element el.annotationSelector( options ) .annotationSelector 'addTextEnhancement', textEnh _filterByType: (textAnnotations) -> return textAnnotations unless @options.typeFilter _.filter textAnnotations, (ta) => return yes if @options.typeFilter in ta.getType() for type in @options.typeFilter return yes if type in ta.getType() # get or create a dom element containing only the occurrence of the found entity _getOrCreateDomElement: (element, text, options = {}) -> # Find occurrence indexes of s in str occurrences = (str, s) -> res = [] last = 0 while str.indexOf(s, last + 1) isnt -1 next = str.indexOf s, last+1 res.push next last = next # Find the nearest number among the nearest = (arr, nr) -> _(arr).sortedIndex nr # Nearest position nearestPosition = (str, s, ind) -> arr = occurrences(str,s) i1 = nearest arr, ind if arr.length is 1 arr[0] else if i1 is arr.length arr[i1-1] else i0 = i1-1 d0 = ind - arr[i0] d1 = arr[i1] - ind if d1 > d0 then arr[i0] else arr[i1] domEl = element textContentOf = (element) -> $(element).text().replace(/\n/g, " ") # find the text node if textContentOf(element).indexOf(text) is -1 @_logger.error "'#{text}' doesn't appear in the text block." return $() start = options.start + textContentOf(element).indexOf textContentOf(element).trim() # Correct small position errors start = nearestPosition textContentOf(element), text, start pos = 0 while textContentOf(domEl).indexOf(text) isnt -1 and domEl.nodeName isnt '#text' domEl = _(domEl.childNodes).detect (el) -> p = textContentOf(el).lastIndexOf text if p >= start - pos true else pos += textContentOf(el).length false if options.createMode is "existing" and textContentOf($(domEl).parent()) is text return $(domEl).parent()[0] else pos = start - pos len = text.length textToCut = textContentOf(domEl).substring(pos, pos+len) if textToCut is text domEl.splitText pos + len newElement = document.createElement options.createElement or 'span' newElement.innerHTML = text $(domEl).parent()[0].replaceChild newElement, domEl.splitText pos $ newElement else @_logger.warn "dom element creation problem: #{textToCut} isnt #{text}" # Similar to the Java String.hashCode() method, it calculates a hash value of the string. String::hashCode = -> hash = 0 return hash if @length is 0 i = 0 while i < @length char = @charCodeAt(i) hash = ((hash << 5) - hash) + char hash = hash & hash i++ hash # For throttling keyup events, this method sets up an event handler function resFn that only triggers the callback function cb after # being called the resFn at least once AND not being called for timout milliseconds. delayThrottle = (cb, timeout) -> timeoutHandler = null resFn = -> if timeoutHandler clearTimeout(timeoutHandler) timeoutHandler = setTimeout -> timeoutHandler = null cb() , timeout
[ { "context": "excessive browser resizing.\n#\n# MIT License\n#\n# by Mig Reyes, Designer at Basecamp\n# http://twitter.com/migrey", "end": 177, "score": 0.9999018311500549, "start": 168, "tag": "NAME", "value": "Mig Reyes" }, { "context": " Reyes, Designer at Basecamp\n# http://twitt...
jquery.wanker.coffee
migreyes/jquery.wanker
56
# # Wanker 0.1.2 # http://mig.io/makes/wanker # # The web was meant to be read, not squished. # Display a message on excessive browser resizing. # # MIT License # # by Mig Reyes, Designer at Basecamp # http://twitter.com/migreyes # do (jQuery = $) -> $.fn.wanker = (options) -> settings = $.extend delay: 1000 duration: 1500 , options @each -> $message = $(@) mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) unless mobile fired = false start = null elapsed = null timer = null reset = -> fired = false elapsed = null $(window).resize -> if fired elapsed = Math.abs(new Date() - start) else start = new Date() fired = true # Reveal the message after the delay is surpassed. if elapsed > settings.delay then $message.fadeIn() # Countdown timer before closing and resetting. clearTimeout timer if timer timer = setTimeout -> $message.fadeOut() reset() , settings.duration
77245
# # Wanker 0.1.2 # http://mig.io/makes/wanker # # The web was meant to be read, not squished. # Display a message on excessive browser resizing. # # MIT License # # by <NAME>, Designer at Basecamp # http://twitter.com/migreyes # do (jQuery = $) -> $.fn.wanker = (options) -> settings = $.extend delay: 1000 duration: 1500 , options @each -> $message = $(@) mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) unless mobile fired = false start = null elapsed = null timer = null reset = -> fired = false elapsed = null $(window).resize -> if fired elapsed = Math.abs(new Date() - start) else start = new Date() fired = true # Reveal the message after the delay is surpassed. if elapsed > settings.delay then $message.fadeIn() # Countdown timer before closing and resetting. clearTimeout timer if timer timer = setTimeout -> $message.fadeOut() reset() , settings.duration
true
# # Wanker 0.1.2 # http://mig.io/makes/wanker # # The web was meant to be read, not squished. # Display a message on excessive browser resizing. # # MIT License # # by PI:NAME:<NAME>END_PI, Designer at Basecamp # http://twitter.com/migreyes # do (jQuery = $) -> $.fn.wanker = (options) -> settings = $.extend delay: 1000 duration: 1500 , options @each -> $message = $(@) mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) unless mobile fired = false start = null elapsed = null timer = null reset = -> fired = false elapsed = null $(window).resize -> if fired elapsed = Math.abs(new Date() - start) else start = new Date() fired = true # Reveal the message after the delay is surpassed. if elapsed > settings.delay then $message.fadeIn() # Countdown timer before closing and resetting. clearTimeout timer if timer timer = setTimeout -> $message.fadeOut() reset() , settings.duration
[ { "context": "aidTheme theme # hack to solve https://github.com/exupero/saveSvgAsPng/issues/128 problem\n # @elemen", "end": 12829, "score": 0.9995736479759216, "start": 12822, "tag": "USERNAME", "value": "exupero" }, { "context": " doc [printToPDF] function\n # https://githu...
lib/markdown-preview-enhanced-view.coffee
romen/markdown-preview-enhanced
1
{Emitter, CompositeDisposable, File, Directory} = require 'atom' {$, $$$, ScrollView} = require 'atom-space-pen-views' path = require 'path' fs = require 'fs' temp = require('temp').track() {exec} = require 'child_process' pdf = require 'html-pdf' katex = require 'katex' matter = require('gray-matter') {allowUnsafeEval, allowUnsafeNewFunction} = require 'loophole' cheerio = null {loadPreviewTheme} = require './style' plantumlAPI = require './puml' ebookConvert = require './ebook-convert' {loadMathJax} = require './mathjax-wrapper' {pandocConvert} = require './pandoc-convert' markdownConvert = require './markdown-convert' codeChunkAPI = require './code-chunk' CACHE = require './cache' {protocolsWhiteListRegExp} = require './protocols-whitelist' module.exports = class MarkdownPreviewEnhancedView extends ScrollView constructor: (uri, mainModule)-> super @uri = uri @mainModule = mainModule @protocal = 'markdown-preview-enhanced://' @editor = null @tocConfigs = null @scrollMap = null @fileDirectoryPath = null @projectDirectoryPath = null @disposables = null @liveUpdate = true @scrollSync = true @scrollDuration = null @textChanged = false @usePandocParser = false @mathRenderingOption = atom.config.get('markdown-preview-enhanced.mathRenderingOption') @mathRenderingOption = if @mathRenderingOption == 'None' then null else @mathRenderingOption @mathJaxProcessEnvironments = atom.config.get('markdown-preview-enhanced.mathJaxProcessEnvironments') @parseDelay = Date.now() @editorScrollDelay = Date.now() @previewScrollDelay = Date.now() @documentExporterView = null # binded in markdown-preview-enhanced.coffee startMD function # this two variables will be got from './md' @parseMD = null @buildScrollMap = null @processFrontMatter = null # this variable will be got from 'viz.js' @Viz = null # this variable will check if it is the first time to render markdown @firstTimeRenderMarkdowon = true # presentation mode @presentationMode = false @slideConfigs = null # graph data used to save rendered graphs @graphData = null @codeChunksData = {} # files cache for document import @filesCache = {} # when resize the window, clear the editor window.addEventListener 'resize', @resizeEvent.bind(this) # right click event atom.commands.add @element, 'markdown-preview-enhanced:open-in-browser': => @openInBrowser() 'markdown-preview-enhanced:export-to-disk': => @exportToDisk() 'markdown-preview-enhanced:pandoc-document-export': => @pandocDocumentExport() 'markdown-preview-enhanced:save-as-markdown': => @saveAsMarkdown() 'core:copy': => @copyToClipboard() # init settings @settingsDisposables = new CompositeDisposable() @initSettingsEvents() @content: -> @div class: 'markdown-preview-enhanced native-key-bindings', tabindex: -1, style: "background-color: #fff; padding: 32px; color: #222;", => # @p style: 'font-size: 24px', 'loading preview...' @div class: "markdown-spinner", 'Loading Markdown\u2026' getTitle: -> @getFileName() + ' preview' getFileName: -> if @editor @editor.getFileName() else 'unknown' getIconName: -> 'markdown' getURI: -> @uri getProjectDirectoryPath: -> if !@editor return '' editorPath = @editor.getPath() projectDirectories = atom.project.rootDirectories for projectDirectory in projectDirectories if (projectDirectory.contains(editorPath)) # editor belongs to this project return projectDirectory.getPath() return '' setTabTitle: (title)-> tabTitle = $('[data-type="MarkdownPreviewEnhancedView"] div.title') if tabTitle.length tabTitle[0].innerText = title updateTabTitle: -> @setTabTitle(@getTitle()) setMermaidTheme: (mermaidTheme)-> mermaidThemeStyle = fs.readFileSync(path.resolve(__dirname, '../dependencies/mermaid/'+mermaidTheme), {encoding: 'utf-8'}).toString() mermaidStyle = document.getElementById('mermaid-style') if mermaidStyle mermaidStyle.remove() mermaidStyle = document.createElement('style') mermaidStyle.id = 'mermaid-style' document.getElementsByTagName('head')[0].appendChild(mermaidStyle) mermaidStyle.innerHTML = mermaidThemeStyle # render mermaid graphs again # els = @element.getElementsByClassName('mermaid') @graphData?.mermaid_s = [] @renderMarkdown() bindEditor: (editor)-> if not @editor atom.workspace .open @uri, split: 'right', activatePane: false, searchAllPanes: false .then (e)=> previewTheme = atom.config.get('markdown-preview-enhanced.previewTheme') loadPreviewTheme previewTheme, true, ()=> @initEvents(editor) else # save cache CACHE[@editor.getPath()] = { html: @element?.innerHTML or '', codeChunksData: @codeChunksData, graphData: @graphData, presentationMode: @presentationMode, slideConfigs: @slideConfigs, filesCache: @filesCache, } # @element.innerHTML = '<p style="font-size: 24px;"> loading preview... <br>type something if preview doesn\'t render :( </p>' setTimeout(()=> @initEvents(editor) , 0) initEvents: (editor)-> @editor = editor @updateTabTitle() @element.removeAttribute('style') if not @parseMD {@parseMD, @buildScrollMap, @processFrontMatter} = require './md' require '../dependencies/wavedrom/default.js' require '../dependencies/wavedrom/wavedrom.min.js' @tocConfigs = null @scrollMap = null @fileDirectoryPath = @editor.getDirectoryPath() @projectDirectoryPath = @getProjectDirectoryPath() @firstTimeRenderMarkdowon = true @filesCache = {} if @disposables # remove all binded events @disposables.dispose() @disposables = new CompositeDisposable() @initEditorEvent() @initViewEvent() # restore preview d = CACHE[@editor.getPath()] if d @element.innerHTML = d.html @graphData = d.graphData @codeChunksData = d.codeChunksData @presentationMode = d.presentationMode @slideConfigs = d.slideConfigs @filesCache = d.filesCache if @presentationMode @element.setAttribute 'data-presentation-preview-mode', '' else @element.removeAttribute 'data-presentation-preview-mode' @setInitialScrollPos() # console.log 'restore ' + @editor.getPath() # reset back to top button onclick event @element.getElementsByClassName('back-to-top-btn')?[0]?.onclick = ()=> @element.scrollTop = 0 # reset refresh button onclick event @element.getElementsByClassName('refresh-btn')?[0]?.onclick = ()=> @filesCache = {} codeChunkAPI.clearCache() @renderMarkdown() # rebind tag a click event @bindTagAClickEvent() # render plantuml in case @renderPlantUML() # reset code chunks @setupCodeChunks() else @renderMarkdown() @scrollMap = null initEditorEvent: -> editorElement = @editor.getElement() @disposables.add @editor.onDidDestroy ()=> @setTabTitle('unknown preview') if @disposables @disposables.dispose() @disposables = null @editor = null @element.onscroll = null @element.innerHTML = '<p style="font-size: 24px;"> Open a markdown file to start preview </p>' @disposables.add @editor.onDidStopChanging ()=> # @textChanged = true # this line has problem. if @liveUpdate and !@usePandocParser @updateMarkdown() @disposables.add @editor.onDidSave ()=> if not @liveUpdate or @usePandocParser @textChanged = true @updateMarkdown() @disposables.add @editor.onDidChangeModified ()=> if not @liveUpdate or @usePandocParser @textChanged = true @disposables.add editorElement.onDidChangeScrollTop ()=> if !@scrollSync or !@element or @textChanged or !@editor or @presentationMode return if Date.now() < @editorScrollDelay return editorHeight = @editor.getElement().getHeight() firstVisibleScreenRow = @editor.getFirstVisibleScreenRow() lastVisibleScreenRow = firstVisibleScreenRow + Math.floor(editorHeight / @editor.getLineHeightInPixels()) lineNo = Math.floor((firstVisibleScreenRow + lastVisibleScreenRow) / 2) @scrollMap ?= @buildScrollMap(this) # disable markdownHtmlView onscroll @previewScrollDelay = Date.now() + 500 # scroll preview to most top as editor is at most top. return @scrollToPos(0) if firstVisibleScreenRow == 0 # @element.scrollTop = @scrollMap[lineNo] - editorHeight / 2 if lineNo of @scrollMap then @scrollToPos(@scrollMap[lineNo]-editorHeight / 2) # match markdown preview to cursor position @disposables.add @editor.onDidChangeCursorPosition (event)=> if !@scrollSync or !@element or @textChanged return if Date.now() < @parseDelay return # track currnet time to disable onDidChangeScrollTop @editorScrollDelay = Date.now() + 500 # disable preview onscroll @previewScrollDelay = Date.now() + 500 if @presentationMode and @slideConfigs return @scrollSyncForPresentation(event.newBufferPosition.row) if event.oldScreenPosition.row != event.newScreenPosition.row or event.oldScreenPosition.column == 0 lineNo = event.newScreenPosition.row if lineNo <= 1 # first 2nd rows @scrollToPos(0) return else if lineNo >= @editor.getScreenLineCount() - 2 # last 2nd rows @scrollToPos(@element.scrollHeight - 16) return @scrollSyncToLineNo(lineNo) initViewEvent: -> @element.onscroll = ()=> if !@editor or !@scrollSync or @textChanged or @presentationMode return if Date.now() < @previewScrollDelay return if @element.scrollTop == 0 # most top @editorScrollDelay = Date.now() + 500 return @scrollToPos 0, @editor.getElement() top = @element.scrollTop + @element.offsetHeight / 2 # try to find corresponding screen buffer row @scrollMap ?= @buildScrollMap(this) i = 0 j = @scrollMap.length - 1 count = 0 screenRow = -1 while count < 20 if Math.abs(top - @scrollMap[i]) < 20 screenRow = i break else if Math.abs(top - @scrollMap[j]) < 20 screenRow = j break else mid = Math.floor((i + j) / 2) if top > @scrollMap[mid] i = mid else j = mid count++ if screenRow == -1 screenRow = mid @scrollToPos(screenRow * @editor.getLineHeightInPixels() - @element.offsetHeight / 2, @editor.getElement()) # @editor.getElement().setScrollTop # track currnet time to disable onDidChangeScrollTop @editorScrollDelay = Date.now() + 500 initSettingsEvents: -> # break line? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.breakOnSingleNewline', (breakOnSingleNewline)=> @parseDelay = Date.now() # <- fix 'loading preview' stuck bug @renderMarkdown() # typographer? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.enableTypographer', (enableTypographer)=> @renderMarkdown() # liveUpdate? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.liveUpdate', (flag) => @liveUpdate = flag @scrollMap = null # scroll sync? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.scrollSync', (flag) => @scrollSync = flag @scrollMap = null # scroll duration @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.scrollDuration', (duration)=> duration = parseInt(duration) or 0 if duration < 0 @scrollDuration = 120 else @scrollDuration = duration # math? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.mathRenderingOption', (option) => @mathRenderingOption = option @renderMarkdown() # pandoc parser? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.usePandocParser', (flag)=> @usePandocParser = flag @renderMarkdown() # mermaid theme @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.mermaidTheme', (theme) => @setMermaidTheme theme # hack to solve https://github.com/exupero/saveSvgAsPng/issues/128 problem # @element.setAttribute 'data-mermaid-theme', theme # render front matter as table? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.frontMatterRenderingOption', () => @renderMarkdown() # show back to top button? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.showBackToTopButton', (flag)=> @showBackToTopButton = flag if flag @addBackToTopButton() else document.getElementsByClassName('back-to-top-btn')[0]?.remove() scrollSyncForPresentation: (bufferLineNo)-> i = @slideConfigs.length - 1 while i >= 0 if bufferLineNo >= @slideConfigs[i].line break i-=1 slideElement = @element.querySelector(".slide[data-offset=\"#{i}\"]") return if not slideElement # set slide to middle of preview @element.scrollTop = -@element.offsetHeight/2 + (slideElement.offsetTop + slideElement.offsetHeight/2)*parseFloat(slideElement.style.zoom) # lineNo here is screen buffer row. scrollSyncToLineNo: (lineNo)-> @scrollMap ?= @buildScrollMap(this) editorElement = @editor.getElement() firstVisibleScreenRow = @editor.getFirstVisibleScreenRow() posRatio = (lineNo - firstVisibleScreenRow) / (editorElement.getHeight() / @editor.getLineHeightInPixels()) scrollTop = @scrollMap[lineNo] - (if posRatio > 1 then 1 else posRatio) * editorElement.getHeight() scrollTop = 0 if scrollTop < 0 @scrollToPos scrollTop # smooth scroll @element to scrollTop # if editorElement is provided, then editorElement.setScrollTop(scrollTop) scrollToPos: (scrollTop, editorElement=null)-> if @scrollTimeout clearTimeout @scrollTimeout @scrollTimeout = null if not @editor or not @editor.alive or scrollTop < 0 return delay = 10 helper = (duration=0)=> @scrollTimeout = setTimeout => if duration <= 0 if editorElement @editorScrollDelay = Date.now() + 500 editorElement.setScrollTop scrollTop else @previewScrollDelay = Date.now() + 500 @element.scrollTop = scrollTop return if editorElement difference = scrollTop - editorElement.getScrollTop() else difference = scrollTop - @element.scrollTop perTick = difference / duration * delay if editorElement # disable editor scroll @editorScrollDelay = Date.now() + 500 s = editorElement.getScrollTop() + perTick editorElement.setScrollTop s return if s == scrollTop else # disable preview onscroll @previewScrollDelay = Date.now() + 500 @element.scrollTop += perTick return if @element.scrollTop == scrollTop helper duration-delay , delay helper(@scrollDuration) formatStringBeforeParsing: (str)-> @mainModule.hook.chain('on-will-parse-markdown', str) formatStringAfterParsing: (str)-> @mainModule.hook.chain('on-did-parse-markdown', str) updateMarkdown: -> @editorScrollDelay = Date.now() + 500 @previewScrollDelay = Date.now() + 500 @renderMarkdown() renderMarkdown: -> if Date.now() < @parseDelay or !@editor or !@element @textChanged = false return @parseDelay = Date.now() + 200 @parseMD @formatStringBeforeParsing(@editor.getText()), {isForPreview: true, markdownPreview: this, @fileDirectoryPath, @projectDirectoryPath}, ({html, slideConfigs, yamlConfig})=> html = @formatStringAfterParsing(html) if slideConfigs.length html = @parseSlides(html, slideConfigs, yamlConfig) @element.setAttribute 'data-presentation-preview-mode', '' @presentationMode = true @slideConfigs = slideConfigs else @element.removeAttribute 'data-presentation-preview-mode' @presentationMode = false @element.innerHTML = html @graphData = {} @bindEvents() @mainModule.emitter.emit 'on-did-render-preview', {htmlString: html, previewElement: @element} @setInitialScrollPos() @addBackToTopButton() @addRefreshButton() @textChanged = false setInitialScrollPos: -> if @firstTimeRenderMarkdowon @firstTimeRenderMarkdowon = false cursor = @editor.cursors[0] return if not cursor if @presentationMode @scrollSyncForPresentation cursor.getBufferRow() else t = @scrollDuration @scrollDuration = 0 @scrollSyncToLineNo cursor.getScreenRow() @scrollDuration = t addBackToTopButton: -> # TODO: check config # add back to top button #222 if @showBackToTopButton and @element.scrollHeight > @element.offsetHeight backToTopBtn = document.createElement('div') backToTopBtn.classList.add('back-to-top-btn') backToTopBtn.classList.add('btn') backToTopBtn.innerHTML = '<span>⬆︎</span>' @element.appendChild(backToTopBtn) backToTopBtn.onclick = ()=> @element.scrollTop = 0 addRefreshButton: -> refreshBtn = document.createElement('div') refreshBtn.classList.add('refresh-btn') refreshBtn.classList.add('btn') refreshBtn.innerHTML = '<span>⟳</span>' @element.appendChild(refreshBtn) refreshBtn.onclick = ()=> # clear cache @filesCache = {} codeChunkAPI.clearCache() # render again @renderMarkdown() bindEvents: -> @bindTagAClickEvent() @setupCodeChunks() @initTaskList() @renderMermaid() @renderPlantUML() @renderWavedrom() @renderViz() @renderKaTeX() @renderMathJax() @scrollMap = null # <a href="" > ... </a> click event bindTagAClickEvent: ()-> as = @element.getElementsByTagName('a') analyzeHref = (href)=> if href and href[0] == '#' targetElement = @element.querySelector("[id=\"#{href.slice(1)}\"]") # fix number id bug if targetElement a.onclick = ()=> # jump to tag position offsetTop = 0 el = targetElement while el and el != @element offsetTop += el.offsetTop el = el.offsetParent if @element.scrollTop > offsetTop @element.scrollTop = offsetTop - 32 - targetElement.offsetHeight else @element.scrollTop = offsetTop else a.onclick = ()=> return if !href return if href.match(/^(http|https)\:\/\//) # the default behavior will open browser for that url. if path.extname(href) in ['.pdf', '.xls', '.xlsx', '.doc', '.ppt', '.docx', '.pptx'] # issue #97 @openFile href else if href.match(/^file\:\/\/\//) # if href.startsWith 'file:///' openFilePath = href.slice(8) # remove protocal openFilePath = openFilePath.replace(/\.md(\s*)\#(.+)$/, '.md') # remove #anchor atom.workspace.open openFilePath, split: 'left', searchAllPanes: true else @openFile href for a in as href = a.getAttribute('href') analyzeHref(href) setupCodeChunks: ()-> codeChunks = @element.getElementsByClassName('code-chunk') return if !codeChunks.length newCodeChunksData = {} needToSetupChunksId = false setupCodeChunk = (codeChunk)=> dataArgs = codeChunk.getAttribute('data-args') idMatch = dataArgs.match(/\s*id\s*:\s*\"([^\"]*)\"/) if idMatch and idMatch[1] id = idMatch[1] codeChunk.id = 'code_chunk_' + id running = @codeChunksData[id]?.running or false codeChunk.classList.add('running') if running # remove output-div and output-element children = codeChunk.children i = children.length - 1 while i >= 0 child = children[i] if child.classList.contains('output-div') or child.classList.contains('output-element') child.remove() i -= 1 outputDiv = @codeChunksData[id]?.outputDiv outputElement = @codeChunksData[id]?.outputElement codeChunk.appendChild(outputElement) if outputElement codeChunk.appendChild(outputDiv) if outputDiv newCodeChunksData[id] = {running, outputDiv, outputElement} else # id not exist, create new id needToSetupChunksId = true runBtn = codeChunk.getElementsByClassName('run-btn')[0] runBtn?.addEventListener 'click', ()=> @runCodeChunk(codeChunk) runAllBtn = codeChunk.getElementsByClassName('run-all-btn')[0] runAllBtn?.addEventListener 'click', ()=> @runAllCodeChunks() for codeChunk in codeChunks break if needToSetupChunksId setupCodeChunk(codeChunk) if needToSetupChunksId @setupCodeChunksId() @codeChunksData = newCodeChunksData # key is codeChunkId, value is {running, outputDiv} setupCodeChunksId: ()-> buffer = @editor.buffer return if !buffer lines = buffer.lines lineNo = 0 curScreenPos = @editor.getCursorScreenPosition() while lineNo < lines.length line = lines[lineNo] match = line.match(/^\`\`\`\{(.+)\}(\s*)/) if match cmd = match[1] dataArgs = '' i = cmd.indexOf(' ') if i > 0 dataArgs = cmd.slice(i + 1, cmd.length).trim() cmd = cmd.slice(0, i) idMatch = match[1].match(/\s*id\s*:\s*\"([^\"]*)\"/) if !idMatch id = (new Date().getTime()).toString(36) line = line.trimRight() line = line.replace(/}$/, (if !dataArgs then '' else ',') + ' id:"' + id + '"}') @parseDelay = Date.now() + 500 # prevent renderMarkdown buffer.setTextInRange([[lineNo, 0], [lineNo+1, 0]], line + '\n') lineNo += 1 @editor.setCursorScreenPosition(curScreenPos) # restore cursor position. # This will cause Maximum size exceeded # @parseDelay = Date.now() # @renderMarkdown() getNearestCodeChunk: ()-> bufferRow = @editor.getCursorBufferPosition().row codeChunks = @element.getElementsByClassName('code-chunk') i = codeChunks.length - 1 while i >= 0 codeChunk = codeChunks[i] lineNo = parseInt(codeChunk.getAttribute('data-line')) if lineNo <= bufferRow return codeChunk i-=1 return null # return false if meet error # otherwise return # { # cmd, # options, # code, # id, # } parseCodeChunk: (codeChunk)-> code = codeChunk.getAttribute('data-code') dataArgs = codeChunk.getAttribute('data-args') options = null try allowUnsafeEval -> options = eval("({#{dataArgs}})") # options = JSON.parse '{'+dataArgs.replace((/([(\w)|(\-)]+)(:)/g), "\"$1\"$2").replace((/'/g), "\"")+'}' catch error atom.notifications.addError('Invalid options', detail: dataArgs) return false id = options.id # check options.continue if options.continue last = null if options.continue == true codeChunks = @element.getElementsByClassName 'code-chunk' i = codeChunks.length - 1 while i >= 0 if codeChunks[i] == codeChunk last = codeChunks[i - 1] break i-- else # id last = document.getElementById('code_chunk_' + options.continue) if last {code: lastCode, options: lastOptions} = @parseCodeChunk(last) or {} lastOptions = lastOptions or {} code = (lastCode or '') + '\n' + code options = Object.assign({}, lastOptions, options) else atom.notifications.addError('Invalid continue for code chunk ' + (options.id or ''), detail: options.continue.toString()) return false cmd = options.cmd or codeChunk.getAttribute('data-lang') # need to put here because options might be modified before return {cmd, options, code, id} runCodeChunk: (codeChunk=null)-> codeChunk = @getNearestCodeChunk() if not codeChunk return if not codeChunk return if codeChunk.classList.contains('running') parseResult = @parseCodeChunk(codeChunk) return if !parseResult {code, options, cmd, id} = parseResult if !id return atom.notifications.addError('Code chunk error', detail: 'id is not found or just updated.') codeChunk.classList.add('running') if @codeChunksData[id] @codeChunksData[id].running = true else @codeChunksData[id] = {running: true} # check options `element` if options.element outputElement = codeChunk.getElementsByClassName('output-element')?[0] if !outputElement # create and append `output-element` div outputElement = document.createElement 'div' outputElement.classList.add 'output-element' codeChunk.appendChild outputElement outputElement.innerHTML = options.element else codeChunk.getElementsByClassName('output-element')?[0]?.remove() outputElement = null codeChunkAPI.run code, @fileDirectoryPath, cmd, options, (error, data, options)=> # get new codeChunk codeChunk = document.getElementById('code_chunk_' + id) return if not codeChunk codeChunk.classList.remove('running') return if error # or !data data = (data or '').toString() outputDiv = codeChunk.getElementsByClassName('output-div')?[0] if !outputDiv outputDiv = document.createElement 'div' outputDiv.classList.add 'output-div' else outputDiv.innerHTML = '' if options.output == 'html' outputDiv.innerHTML = data else if options.output == 'png' imageElement = document.createElement 'img' imageData = Buffer(data).toString('base64') imageElement.setAttribute 'src', "data:image/png;charset=utf-8;base64,#{imageData}" outputDiv.appendChild imageElement else if options.output == 'markdown' @parseMD data, {@fileDirectoryPath, @projectDirectoryPath}, ({html})=> outputDiv.innerHTML = html @scrollMap = null else if options.output == 'none' outputDiv.remove() outputDiv = null else if data?.length preElement = document.createElement 'pre' preElement.innerText = data preElement.classList.add('editor-colors') preElement.classList.add('lang-text') outputDiv.appendChild preElement if outputDiv codeChunk.appendChild outputDiv @scrollMap = null # check matplotlib | mpl if options.matplotlib or options.mpl scriptElements = outputDiv.getElementsByTagName('script') if scriptElements.length window.d3 ?= require('../dependencies/mpld3/d3.v3.min.js') window.mpld3 ?= require('../dependencies/mpld3/mpld3.v0.3.min.js') for scriptElement in scriptElements code = scriptElement.innerHTML allowUnsafeNewFunction -> allowUnsafeEval -> eval(code) @codeChunksData[id] = {running: false, outputDiv, outputElement} runAllCodeChunks: ()-> codeChunks = @element.getElementsByClassName('code-chunk') for chunk in codeChunks @runCodeChunk(chunk) initTaskList: ()-> checkboxs = @element.getElementsByClassName('task-list-item-checkbox') for checkbox in checkboxs this_ = this checkbox.onclick = ()-> if !this_.editor return checked = this.checked buffer = this_.editor.buffer if !buffer return lineNo = parseInt(this.parentElement.getAttribute('data-line')) line = buffer.lines[lineNo] if checked line = line.replace('[ ]', '[x]') else line = line.replace(/\[(x|X)\]/, '[ ]') this_.parseDelay = Date.now() + 500 buffer.setTextInRange([[lineNo, 0], [lineNo+1, 0]], line + '\n') renderMermaid: ()-> els = @element.getElementsByClassName('mermaid mpe-graph') if els.length @graphData.mermaid_s = Array.prototype.slice.call(els) notProcessedEls = @element.querySelectorAll('.mermaid.mpe-graph:not([data-processed])') if notProcessedEls.length mermaid.init null, notProcessedEls ### # the code below doesn't seem to be working # I think mermaidAPI.render function has bug cb = (el)-> (svgGraph)-> el.innerHTML = svgGraph el.setAttribute 'data-processed', 'true' # the code below is a hackable way to solve mermaid bug el.firstChild.style.height = el.getAttribute('viewbox').split(' ')[3] + 'px' for el in els offset = parseInt(el.getAttribute('data-offset')) el.id = 'mermaid'+offset mermaidAPI.render el.id, el.getAttribute('data-original'), cb(el) ### # disable @element onscroll @previewScrollDelay = Date.now() + 500 renderWavedrom: ()-> els = @element.getElementsByClassName('wavedrom mpe-graph') if els.length @graphData.wavedrom_s = Array.prototype.slice.call(els) # WaveDrom.RenderWaveForm(0, WaveDrom.eva('a0'), 'a') for el in els if el.getAttribute('data-processed') != 'true' offset = parseInt(el.getAttribute('data-offset')) el.id = 'wavedrom'+offset text = el.getAttribute('data-original').trim() continue if not text.length allowUnsafeEval => try content = eval("(#{text})") # eval function here WaveDrom.RenderWaveForm(offset, content, 'wavedrom') el.setAttribute 'data-processed', 'true' @scrollMap = null catch error el.innerText = 'failed to eval WaveDrom code.' # disable @element onscroll @previewScrollDelay = Date.now() + 500 renderPlantUML: ()-> els = @element.getElementsByClassName('plantuml mpe-graph') if els.length @graphData.plantuml_s = Array.prototype.slice.call(els) helper = (el, text)=> plantumlAPI.render text, (outputHTML)=> el.innerHTML = outputHTML el.setAttribute 'data-processed', true @scrollMap = null for el in els if el.getAttribute('data-processed') != 'true' helper(el, el.getAttribute('data-original')) el.innerText = 'rendering graph...\n' renderViz: (element=@element)-> els = element.getElementsByClassName('viz mpe-graph') if els.length @graphData.viz_s = Array.prototype.slice.call(els) @Viz ?= require('../dependencies/viz/viz.js') for el in els if el.getAttribute('data-processed') != 'true' try content = el.getAttribute('data-original') options = {} # check engine content = content.trim().replace /^engine(\s)*[:=]([^\n]+)/, (a, b, c)-> options.engine = c.trim() if c?.trim() in ['circo', 'dot', 'fdp', 'neato', 'osage', 'twopi'] return '' el.innerHTML = @Viz(content, options) # default svg el.setAttribute 'data-processed', true catch error el.innerHTML = error renderMathJax: ()-> return if @mathRenderingOption != 'MathJax' and !@usePandocParser if typeof(MathJax) == 'undefined' return loadMathJax document, ()=> @renderMathJax() if @mathJaxProcessEnvironments or @usePandocParser return MathJax.Hub.Queue ['Typeset', MathJax.Hub, @element], ()=> @scrollMap = null els = @element.getElementsByClassName('mathjax-exps') return if !els.length unprocessedElements = [] for el in els if !el.hasAttribute('data-processed') el.setAttribute 'data-original', el.textContent unprocessedElements.push el callback = ()=> for el in unprocessedElements el.setAttribute 'data-processed', true @scrollMap = null if unprocessedElements.length == els.length MathJax.Hub.Queue ['Typeset', MathJax.Hub, @element], callback else if unprocessedElements.length MathJax.Hub.Typeset unprocessedElements, callback renderKaTeX: ()-> return if @mathRenderingOption != 'KaTeX' els = @element.getElementsByClassName('katex-exps') for el in els if el.hasAttribute('data-processed') continue else displayMode = el.hasAttribute('display-mode') dataOriginal = el.textContent try katex.render(el.textContent, el, {displayMode}) catch error el.innerHTML = "<span style=\"color: #ee7f49; font-weight: 500;\">#{error}</span>" el.setAttribute('data-processed', 'true') el.setAttribute('data-original', dataOriginal) resizeEvent: ()-> @scrollMap = null ### convert './a.txt' '/a.txt' ### resolveFilePath: (filePath='', relative=false)-> if filePath.match(protocolsWhiteListRegExp) return filePath else if filePath.startsWith('/') if relative return path.relative(@fileDirectoryPath, path.resolve(@projectDirectoryPath, '.'+filePath)) else return 'file:///'+path.resolve(@projectDirectoryPath, '.'+filePath) else if relative return filePath else return 'file:///'+path.resolve(@fileDirectoryPath, filePath) ## Utilities openInBrowser: (isForPresentationPrint=false)-> return if not @editor @getHTMLContent offline: true, isForPrint: isForPresentationPrint, (htmlContent)=> temp.open prefix: 'markdown-preview-enhanced', suffix: '.html', (err, info)=> throw err if err fs.write info.fd, htmlContent, (err)=> throw err if err if isForPresentationPrint url = 'file:///' + info.path + '?print-pdf' atom.notifications.addInfo('Please copy and open the link below in Chrome.\nThen Right Click -> Print -> Save as Pdf.', dismissable: true, detail: url) else ## open in browser @openFile info.path exportToDisk: ()-> @documentExporterView.display(this) # open html file in browser or open pdf file in reader ... etc openFile: (filePath)-> if process.platform == 'win32' cmd = 'explorer' else if process.platform == 'darwin' cmd = 'open' else cmd = 'xdg-open' exec "#{cmd} #{filePath}" ## ## {Function} callback (htmlContent) insertCodeChunksResult: (htmlContent)-> # insert outputDiv and outputElement accordingly cheerio ?= require 'cheerio' $ = cheerio.load(htmlContent, {decodeEntities: false}) codeChunks = $('.code-chunk') jsCode = '' requireCache = {} # key is path scriptsStr = "" for codeChunk in codeChunks $codeChunk = $(codeChunk) dataArgs = $codeChunk.attr('data-args').unescape() options = null try allowUnsafeEval -> options = eval("({#{dataArgs}})") catch e continue id = options.id continue if !id cmd = options.cmd or $codeChunk.attr('data-lang') code = $codeChunk.attr('data-code').unescape() outputDiv = @codeChunksData[id]?.outputDiv outputElement = @codeChunksData[id]?.outputElement if outputDiv # append outputDiv result $codeChunk.append("<div class=\"output-div\">#{outputDiv.innerHTML}</div>") if options.matplotlib or options.mpl # remove innerHTML of <div id="fig_..."></div> # this is for fixing mpld3 exporting issue. gs = $('.output-div > div', $codeChunk) if gs for g in gs $g = $(g) if $g.attr('id')?.match(/fig\_/) $g.html('') ss = $('.output-div > script', $codeChunk) if ss for s in ss $s = $(s) c = $s.html() $s.remove() jsCode += (c + '\n') if options.element $codeChunk.append("<div class=\"output-element\">#{options.element}</div>") if cmd == 'javascript' requires = options.require or [] if typeof(requires) == 'string' requires = [requires] requiresStr = "" for requirePath in requires # TODO: css if requirePath.match(/^(http|https)\:\/\//) if (!requireCache[requirePath]) requireCache[requirePath] = true scriptsStr += "<script src=\"#{requirePath}\"></script>\n" else requirePath = path.resolve(@fileDirectoryPath, requirePath) if !requireCache[requirePath] requiresStr += (fs.readFileSync(requirePath, {encoding: 'utf-8'}) + '\n') requireCache[requirePath] = true jsCode += (requiresStr + code + '\n') html = $.html() html += "#{scriptsStr}\n" if scriptsStr html += "<script data-js-code>#{jsCode}</script>" if jsCode return html ## # {Function} callback (htmlContent) getHTMLContent: ({isForPrint, offline, useRelativeImagePath, phantomjsType}, callback)-> isForPrint ?= false offline ?= false useRelativeImagePath ?= false phantomjsType ?= false # pdf | png | jpeg | false return callback() if not @editor mathRenderingOption = atom.config.get('markdown-preview-enhanced.mathRenderingOption') res = @parseMD @formatStringBeforeParsing(@editor.getText()), {useRelativeImagePath, @fileDirectoryPath, @projectDirectoryPath, markdownPreview: this, hideFrontMatter: true}, ({html, yamlConfig, slideConfigs})=> htmlContent = @formatStringAfterParsing(html) yamlConfig = yamlConfig or {} # replace code chunks inside htmlContent htmlContent = @insertCodeChunksResult htmlContent if mathRenderingOption == 'KaTeX' if offline mathStyle = "<link rel=\"stylesheet\" href=\"file:///#{path.resolve(__dirname, '../node_modules/katex/dist/katex.min.css')}\">" else mathStyle = "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css\">" else if mathRenderingOption == 'MathJax' inline = atom.config.get('markdown-preview-enhanced.indicatorForMathRenderingInline') block = atom.config.get('markdown-preview-enhanced.indicatorForMathRenderingBlock') mathJaxProcessEnvironments = atom.config.get('markdown-preview-enhanced.mathJaxProcessEnvironments') if offline mathStyle = " <script type=\"text/x-mathjax-config\"> MathJax.Hub.Config({ messageStyle: 'none', tex2jax: {inlineMath: #{inline}, displayMath: #{block}, processEnvironments: #{mathJaxProcessEnvironments}, processEscapes: true} }); </script> <script type=\"text/javascript\" async src=\"file://#{path.resolve(__dirname, '../dependencies/mathjax/MathJax.js?config=TeX-AMS_CHTML')}\"></script> " else # inlineMath: [ ['$','$'], ["\\(","\\)"] ], # displayMath: [ ['$$','$$'], ["\\[","\\]"] ] mathStyle = " <script type=\"text/x-mathjax-config\"> MathJax.Hub.Config({ messageStyle: 'none', tex2jax: {inlineMath: #{inline}, displayMath: #{block}, processEnvironments: #{mathJaxProcessEnvironments}, processEscapes: true} }); </script> <script type=\"text/javascript\" async src=\"https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML\"></script> " else mathStyle = '' # presentation if slideConfigs.length htmlContent = @parseSlidesForExport(htmlContent, slideConfigs, useRelativeImagePath) if offline presentationScript = " <script src='file:///#{path.resolve(__dirname, '../dependencies/reveal/lib/js/head.min.js')}'></script> <script src='file:///#{path.resolve(__dirname, '../dependencies/reveal/js/reveal.js')}'></script>" else presentationScript = " <script src='https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.4.1/lib/js/head.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.4.1/js/reveal.min.js'></script>" presentationConfig = yamlConfig['presentation'] or {} dependencies = presentationConfig.dependencies or [] if presentationConfig.enableSpeakerNotes if offline dependencies.push {src: path.resolve(__dirname, '../dependencies/reveal/plugin/notes/notes.js'), async: true} else dependencies.push {src: 'revealjs_deps/notes.js', async: true} # TODO: copy notes.js file to corresponding folder presentationConfig.dependencies = dependencies # <link rel=\"stylesheet\" href='file:///#{path.resolve(__dirname, '../dependencies/reveal/reveal.css')}'> presentationStyle = """ <style> #{fs.readFileSync(path.resolve(__dirname, '../dependencies/reveal/reveal.css'))} #{if isForPrint then fs.readFileSync(path.resolve(__dirname, '../dependencies/reveal/pdf.css')) else ''} </style> """ presentationInitScript = """ <script> Reveal.initialize(#{JSON.stringify(Object.assign({margin: 0.1}, presentationConfig))}) </script> """ else presentationScript = '' presentationStyle = '' presentationInitScript = '' # phantomjs phantomjsClass = "" if phantomjsType if phantomjsType == '.pdf' phantomjsClass = 'phantomjs-pdf' else if phantomjsType == '.png' or phantomjsType == '.jpeg' phantomjsClass = 'phantomjs-image' title = @getFileName() title = title.slice(0, title.length - path.extname(title).length) # remove '.md' previewTheme = atom.config.get('markdown-preview-enhanced.previewTheme') if isForPrint and atom.config.get('markdown-preview-enhanced.pdfUseGithub') previewTheme = 'mpe-github-syntax' loadPreviewTheme previewTheme, false, (error, css)=> return callback() if error return callback """ <!DOCTYPE html> <html> <head> <title>#{title}</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> #{presentationStyle} <style> #{css} </style> #{mathStyle} #{presentationScript} </head> <body class=\"markdown-preview-enhanced #{phantomjsClass}\" #{if @presentationMode then 'data-presentation-mode' else ''}> #{htmlContent} </body> #{presentationInitScript} </html> """ # api doc [printToPDF] function # https://github.com/atom/electron/blob/master/docs/api/web-contents.md printPDF: (htmlPath, dest)-> return if not @editor {BrowserWindow} = require('electron').remote win = new BrowserWindow show: false win.loadURL htmlPath # get margins type marginsType = atom.config.get('markdown-preview-enhanced.marginsType') marginsType = if marginsType == 'default margin' then 0 else if marginsType == 'no margin' then 1 else 2 # get orientation landscape = atom.config.get('markdown-preview-enhanced.orientation') == 'landscape' lastIndexOfSlash = dest.lastIndexOf '/' or 0 pdfName = dest.slice(lastIndexOfSlash + 1) win.webContents.on 'did-finish-load', ()=> setTimeout(()=> win.webContents.printToPDF pageSize: atom.config.get('markdown-preview-enhanced.exportPDFPageFormat'), landscape: landscape, printBackground: atom.config.get('markdown-preview-enhanced.printBackground'), marginsType: marginsType, (err, data)=> throw err if err destFile = new File(dest) destFile.create().then (flag)=> destFile.write data atom.notifications.addInfo "File #{pdfName} was created", detail: "path: #{dest}" # open pdf if atom.config.get('markdown-preview-enhanced.pdfOpenAutomatically') @openFile dest , 500) saveAsPDF: (dest)-> return if not @editor if @presentationMode # for presentation, need to print from chrome @openInBrowser(true) return @getHTMLContent isForPrint: true, offline: true, (htmlContent)=> temp.open prefix: 'markdown-preview-enhanced', suffix: '.html', (err, info)=> throw err if err fs.write info.fd, htmlContent, (err)=> throw err if err @printPDF "file://#{info.path}", dest saveAsHTML: (dest, offline=true, useRelativeImagePath)-> return if not @editor @getHTMLContent isForPrint: false, offline: offline, useRelativeImagePath: useRelativeImagePath, (htmlContent)=> htmlFileName = path.basename(dest) # presentation speaker notes # copy dependency files if !offline and htmlContent.indexOf('[{"src":"revealjs_deps/notes.js","async":true}]') >= 0 depsDirName = path.resolve(path.dirname(dest), 'revealjs_deps') depsDir = new Directory(depsDirName) depsDir.create().then (flag)-> true fs.createReadStream(path.resolve(__dirname, '../dependencies/reveal/plugin/notes/notes.js')).pipe(fs.createWriteStream(path.resolve(depsDirName, 'notes.js'))) fs.createReadStream(path.resolve(__dirname, '../dependencies/reveal/plugin/notes/notes.html')).pipe(fs.createWriteStream(path.resolve(depsDirName, 'notes.html'))) destFile = new File(dest) destFile.create().then (flag)-> destFile.write htmlContent atom.notifications.addInfo("File #{htmlFileName} was created", detail: "path: #{dest}") #################################################### ## Presentation ################################################## parseSlides: (html, slideConfigs, yamlConfig)-> slides = html.split '<div class="new-slide"></div>' slides = slides.slice(1) output = '' offset = 0 width = 960 height = 700 if yamlConfig and yamlConfig['presentation'] presentationConfig = yamlConfig['presentation'] width = presentationConfig['width'] or 960 height = presentationConfig['height'] or 700 ratio = height / width * 100 + '%' zoom = (@element.offsetWidth - 128)/width ## 64 is 2*padding for slide in slides # slide = slide.trim() # if slide.length slideConfig = slideConfigs[offset] styleString = '' videoString = '' iframeString = '' if slideConfig['data-background-image'] styleString += "background-image: url('#{@resolveFilePath(slideConfig['data-background-image'])}');" if slideConfig['data-background-size'] styleString += "background-size: #{slideConfig['data-background-size']};" else styleString += "background-size: cover;" if slideConfig['data-background-position'] styleString += "background-position: #{slideConfig['data-background-position']};" else styleString += "background-position: center;" if slideConfig['data-background-repeat'] styleString += "background-repeat: #{slideConfig['data-background-repeat']};" else styleString += "background-repeat: no-repeat;" else if slideConfig['data-background-color'] styleString += "background-color: #{slideConfig['data-background-color']} !important;" else if slideConfig['data-background-video'] videoMuted = slideConfig['data-background-video-muted'] videoLoop = slideConfig['data-background-video-loop'] muted_ = if videoMuted then 'muted' else '' loop_ = if videoLoop then 'loop' else '' videoString = """ <video #{muted_} #{loop_} playsinline autoplay class=\"background-video\" src=\"#{@resolveFilePath(slideConfig['data-background-video'])}\"> </video> """ # <source src=\"#{slideConfig['data-background-video']}\"> else if slideConfig['data-background-iframe'] iframeString = """ <iframe class=\"background-iframe\" src=\"#{@resolveFilePath(slideConfig['data-background-iframe'])}\" frameborder="0" > </iframe> <div class=\"background-iframe-overlay\"></div> """ output += """ <div class='slide' data-offset='#{offset}' style="width: #{width}px; height: #{height}px; zoom: #{zoom}; #{styleString}"> #{videoString} #{iframeString} <section>#{slide}</section> </div> """ offset += 1 # remove <aside class="notes"> ... </aside> output = output.replace(/(<aside\b[^>]*>)[^<>]*(<\/aside>)/ig, '') """ <div class="preview-slides"> #{output} </div> """ parseSlidesForExport: (html, slideConfigs, useRelativeImagePath)-> slides = html.split '<div class="new-slide"></div>' slides = slides.slice(1) output = '' parseAttrString = (slideConfig)=> attrString = '' if slideConfig['data-background-image'] attrString += " data-background-image='#{@resolveFilePath(slideConfig['data-background-image'], useRelativeImagePath)}'" if slideConfig['data-background-size'] attrString += " data-background-size='#{slideConfig['data-background-size']}'" if slideConfig['data-background-position'] attrString += " data-background-position='#{slideConfig['data-background-position']}'" if slideConfig['data-background-repeat'] attrString += " data-background-repeat='#{slideConfig['data-background-repeat']}'" if slideConfig['data-background-color'] attrString += " data-background-color='#{slideConfig['data-background-color']}'" if slideConfig['data-notes'] attrString += " data-notes='#{slideConfig['data-notes']}'" if slideConfig['data-background-video'] attrString += " data-background-video='#{@resolveFilePath(slideConfig['data-background-video'], useRelativeImagePath)}'" if slideConfig['data-background-video-loop'] attrString += " data-background-video-loop" if slideConfig['data-background-video-muted'] attrString += " data-background-video-muted" if slideConfig['data-transition'] attrString += " data-transition='#{slideConfig['data-transition']}'" if slideConfig['data-background-iframe'] attrString += " data-background-iframe='#{@resolveFilePath(slideConfig['data-background-iframe'], useRelativeImagePath)}'" attrString i = 0 while i < slides.length slide = slides[i] slideConfig = slideConfigs[i] attrString = parseAttrString(slideConfig) if !slideConfig['vertical'] if i > 0 and slideConfigs[i-1]['vertical'] # end of vertical slides output += '</section>' if i < slides.length - 1 and slideConfigs[i+1]['vertical'] # start of vertical slides output += "<section>" output += "<section #{attrString}>#{slide}</section>" i += 1 if i > 0 and slideConfigs[i-1]['vertical'] # end of vertical slides output += "</section>" """ <div class="reveal"> <div class="slides"> #{output} </div> </div> """ #################################################### ## PhantomJS ################################################## loadPhantomJSHeaderFooterConfig: ()-> # mermaid_config.js configPath = path.resolve(atom.config.configDirPath, './markdown-preview-enhanced/phantomjs_header_footer_config.js') try delete require.cache[require.resolve(configPath)] # return uncached return require(configPath) or {} catch error configFile = new File(configPath) configFile.create().then (flag)-> if !flag # already exists atom.notifications.addError('Failed to load phantomjs_header_footer_config.js', detail: 'there might be errors in your config file') return configFile.write """ 'use strict' /* configure header and footer (and other options) more information can be found here: https://github.com/marcbachmann/node-html-pdf Attention: this config will override your config in exporter panel. eg: let config = { "header": { "height": "45mm", "contents": '<div style="text-align: center;">Author: Marc Bachmann</div>' }, "footer": { "height": "28mm", "contents": '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>' } } */ // you can edit the 'config' variable below let config = { } module.exports = config || {} """ return {} phantomJSExport: (dest)-> return if not @editor if @presentationMode # for presentation, need to print from chrome @openInBrowser(true) return @getHTMLContent isForPrint: true, offline: true, phantomjsType: path.extname(dest), (htmlContent)=> fileType = atom.config.get('markdown-preview-enhanced.phantomJSExportFileType') format = atom.config.get('markdown-preview-enhanced.exportPDFPageFormat') orientation = atom.config.get('markdown-preview-enhanced.orientation') margin = atom.config.get('markdown-preview-enhanced.phantomJSMargin').trim() if !margin.length margin = '1cm' else margin = margin.split(',').map (m)->m.trim() if margin.length == 1 margin = margin[0] else if margin.length == 2 margin = {'top': margin[0], 'bottom': margin[0], 'left': margin[1], 'right': margin[1]} else if margin.length == 4 margin = {'top': margin[0], 'right': margin[1], 'bottom': margin[2], 'left': margin[3]} else margin = '1cm' # get header and footer config = @loadPhantomJSHeaderFooterConfig() pdf .create htmlContent, Object.assign({type: fileType, format: format, orientation: orientation, border: margin, quality: '75', timeout: 60000, script: path.join(__dirname, '../dependencies/phantomjs/pdf_a4_portrait.js')}, config) .toFile dest, (err, res)=> if err atom.notifications.addError err # open pdf else lastIndexOfSlash = dest.lastIndexOf '/' or 0 fileName = dest.slice(lastIndexOfSlash + 1) atom.notifications.addInfo "File #{fileName} was created", detail: "path: #{dest}" if atom.config.get('markdown-preview-enhanced.pdfOpenAutomatically') @openFile dest ## EBOOK generateEbook: (dest)-> @parseMD @formatStringBeforeParsing(@editor.getText()), {isForEbook: true, @fileDirectoryPath, @projectDirectoryPath, hideFrontMatter:true}, ({html, yamlConfig})=> html = @formatStringAfterParsing(html) ebookConfig = null if yamlConfig ebookConfig = yamlConfig['ebook'] if !ebookConfig return atom.notifications.addError('ebook config not found', detail: 'please insert ebook front-matter to your markdown file') else atom.notifications.addInfo('Your document is being prepared', detail: ':)') if ebookConfig.cover # change cover to absolute path if necessary cover = ebookConfig.cover if cover.startsWith('./') or cover.startsWith('../') cover = path.resolve(@fileDirectoryPath, cover) ebookConfig.cover = cover else if cover.startsWith('/') cover = path.resolve(@projectDirectoryPath, '.'+cover) ebookConfig.cover = cover div = document.createElement('div') div.innerHTML = html structure = [] # {level:0, filePath: 'path to file', heading: '', id: ''} headingOffset = 0 # load the last ul, analyze toc links. getStructure = (ul, level)-> for li in ul.children a = li.children[0]?.getElementsByTagName('a')?[0] continue if not a filePath = a.getAttribute('href') # assume markdown file path heading = a.innerHTML id = 'ebook-heading-id-'+headingOffset structure.push {level: level, filePath: filePath, heading: heading, id: id} headingOffset += 1 a.href = '#'+id # change id if li.childElementCount > 1 getStructure(li.children[1], level+1) children = div.children i = children.length - 1 while i >= 0 if children[i].tagName == 'UL' # find table of contents getStructure(children[i], 0) break i -= 1 outputHTML = div.innerHTML # append files according to structure for obj in structure heading = obj.heading id = obj.id level = obj.level filePath = obj.filePath if filePath.startsWith('file:///') filePath = filePath.slice(8) try text = fs.readFileSync(filePath, {encoding: 'utf-8'}) @parseMD @formatStringBeforeParsing(text), {isForEbook: true, projectDirectoryPath: @projectDirectoryPath, fileDirectoryPath: path.dirname(filePath)}, ({html})=> html = @formatStringAfterParsing(html) # add to TOC div.innerHTML = html if div.childElementCount div.children[0].id = id div.children[0].setAttribute('ebook-toc-level-'+(level+1), '') div.children[0].setAttribute('heading', heading) outputHTML += div.innerHTML catch error atom.notifications.addError('Ebook generation: Failed to load file', detail: filePath + '\n ' + error) return # render viz div.innerHTML = outputHTML @renderViz(div) # download images for .epub and .mobi imagesToDownload = [] if path.extname(dest) in ['.epub', '.mobi'] for img in div.getElementsByTagName('img') src = img.getAttribute('src') if src.startsWith('http://') or src.startsWith('https://') imagesToDownload.push(img) request = require('request') async = require('async') if imagesToDownload.length atom.notifications.addInfo('downloading images...') asyncFunctions = imagesToDownload.map (img)=> (callback)=> httpSrc = img.getAttribute('src') savePath = Math.random().toString(36).substr(2, 9) + '_' + path.basename(httpSrc) savePath = path.resolve(@fileDirectoryPath, savePath) stream = request(httpSrc).pipe(fs.createWriteStream(savePath)) stream.on 'finish', ()-> img.setAttribute 'src', 'file:///'+savePath callback(null, savePath) async.parallel asyncFunctions, (error, downloadedImagePaths=[])=> # convert image to base64 if output html if path.extname(dest) == '.html' # check cover if ebookConfig.cover cover = if ebookConfig.cover[0] == '/' then 'file:///' + ebookConfig.cover else ebookConfig.cover coverImg = document.createElement('img') coverImg.setAttribute('src', cover) div.insertBefore(coverImg, div.firstChild) imageElements = div.getElementsByTagName('img') for img in imageElements src = img.getAttribute('src') if src.startsWith('file:///') src = src.slice(8) imageType = path.extname(src).slice(1) try base64 = new Buffer(fs.readFileSync(src)).toString('base64') img.setAttribute('src', "data:image/#{imageType};charset=utf-8;base64,#{base64}") catch error throw 'Image file not found: ' + src # retrieve html outputHTML = div.innerHTML title = ebookConfig.title or 'no title' mathStyle = '' if outputHTML.indexOf('class="katex"') > 0 if path.extname(dest) == '.html' and ebookConfig.html?.cdn mathStyle = "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css\">" else mathStyle = "<link rel=\"stylesheet\" href=\"file:///#{path.resolve(__dirname, '../node_modules/katex/dist/katex.min.css')}\">" # only use github style for ebook loadPreviewTheme 'mpe-github-syntax', false, (error, css)=> css = '' if error outputHTML = """ <!DOCTYPE html> <html> <head> <title>#{title}</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> #{css} </style> #{mathStyle} </head> <body class=\"markdown-preview-enhanced\"> #{outputHTML} </body> </html> """ fileName = path.basename(dest) # save as html if path.extname(dest) == '.html' fs.writeFile dest, outputHTML, (err)=> throw err if err atom.notifications.addInfo("File #{fileName} was created", detail: "path: #{dest}") return # this func will be called later deleteDownloadedImages = ()-> downloadedImagePaths.forEach (imagePath)-> fs.unlink(imagePath) # use ebook-convert to generate ePub, mobi, PDF. temp.open prefix: 'markdown-preview-enhanced', suffix: '.html', (err, info)=> if err deleteDownloadedImages() throw err fs.write info.fd, outputHTML, (err)=> if err deleteDownloadedImages() throw err ebookConvert info.path, dest, ebookConfig, (err)=> deleteDownloadedImages() throw err if err atom.notifications.addInfo "File #{fileName} was created", detail: "path: #{dest}" pandocDocumentExport: -> {data} = @processFrontMatter(@editor.getText()) content = @editor.getText().trim() if content.startsWith('---\n') end = content.indexOf('---\n', 4) content = content.slice(end+4) pandocConvert content, {@fileDirectoryPath, @projectDirectoryPath, sourceFilePath: @editor.getPath()}, data, (err, outputFilePath)-> if err return atom.notifications.addError 'pandoc error', detail: err atom.notifications.addInfo "File #{path.basename(outputFilePath)} was created", detail: "path: #{outputFilePath}" saveAsMarkdown: ()-> {data} = @processFrontMatter(@editor.getText()) data = data or {} content = @editor.getText().trim() if content.startsWith('---\n') end = content.indexOf('---\n', 4) content = content.slice(end+4) config = data.markdown or {} if !config.image_dir config.image_dir = atom.config.get('markdown-preview-enhanced.imageFolderPath') if !config.path config.path = path.basename(@editor.getPath()).replace(/\.md$/, '_.md') if config.front_matter content = matter.stringify(content, config.front_matter) markdownConvert content, {@projectDirectoryPath, @fileDirectoryPath}, config copyToClipboard: -> return false if not @editor selection = window.getSelection() selectedText = selection.toString() atom.clipboard.write(selectedText) true # Tear down any state and detach destroy: -> @element.remove() @editor = null if @disposables @disposables.dispose() @disposables = null if @settingsDisposables @settingsDisposables.dispose() @settingsDisposables = null # clear CACHE for key of CACHE delete(CACHE[key]) @mainModule.preview = null # unbind getElement: -> @element
214493
{Emitter, CompositeDisposable, File, Directory} = require 'atom' {$, $$$, ScrollView} = require 'atom-space-pen-views' path = require 'path' fs = require 'fs' temp = require('temp').track() {exec} = require 'child_process' pdf = require 'html-pdf' katex = require 'katex' matter = require('gray-matter') {allowUnsafeEval, allowUnsafeNewFunction} = require 'loophole' cheerio = null {loadPreviewTheme} = require './style' plantumlAPI = require './puml' ebookConvert = require './ebook-convert' {loadMathJax} = require './mathjax-wrapper' {pandocConvert} = require './pandoc-convert' markdownConvert = require './markdown-convert' codeChunkAPI = require './code-chunk' CACHE = require './cache' {protocolsWhiteListRegExp} = require './protocols-whitelist' module.exports = class MarkdownPreviewEnhancedView extends ScrollView constructor: (uri, mainModule)-> super @uri = uri @mainModule = mainModule @protocal = 'markdown-preview-enhanced://' @editor = null @tocConfigs = null @scrollMap = null @fileDirectoryPath = null @projectDirectoryPath = null @disposables = null @liveUpdate = true @scrollSync = true @scrollDuration = null @textChanged = false @usePandocParser = false @mathRenderingOption = atom.config.get('markdown-preview-enhanced.mathRenderingOption') @mathRenderingOption = if @mathRenderingOption == 'None' then null else @mathRenderingOption @mathJaxProcessEnvironments = atom.config.get('markdown-preview-enhanced.mathJaxProcessEnvironments') @parseDelay = Date.now() @editorScrollDelay = Date.now() @previewScrollDelay = Date.now() @documentExporterView = null # binded in markdown-preview-enhanced.coffee startMD function # this two variables will be got from './md' @parseMD = null @buildScrollMap = null @processFrontMatter = null # this variable will be got from 'viz.js' @Viz = null # this variable will check if it is the first time to render markdown @firstTimeRenderMarkdowon = true # presentation mode @presentationMode = false @slideConfigs = null # graph data used to save rendered graphs @graphData = null @codeChunksData = {} # files cache for document import @filesCache = {} # when resize the window, clear the editor window.addEventListener 'resize', @resizeEvent.bind(this) # right click event atom.commands.add @element, 'markdown-preview-enhanced:open-in-browser': => @openInBrowser() 'markdown-preview-enhanced:export-to-disk': => @exportToDisk() 'markdown-preview-enhanced:pandoc-document-export': => @pandocDocumentExport() 'markdown-preview-enhanced:save-as-markdown': => @saveAsMarkdown() 'core:copy': => @copyToClipboard() # init settings @settingsDisposables = new CompositeDisposable() @initSettingsEvents() @content: -> @div class: 'markdown-preview-enhanced native-key-bindings', tabindex: -1, style: "background-color: #fff; padding: 32px; color: #222;", => # @p style: 'font-size: 24px', 'loading preview...' @div class: "markdown-spinner", 'Loading Markdown\u2026' getTitle: -> @getFileName() + ' preview' getFileName: -> if @editor @editor.getFileName() else 'unknown' getIconName: -> 'markdown' getURI: -> @uri getProjectDirectoryPath: -> if !@editor return '' editorPath = @editor.getPath() projectDirectories = atom.project.rootDirectories for projectDirectory in projectDirectories if (projectDirectory.contains(editorPath)) # editor belongs to this project return projectDirectory.getPath() return '' setTabTitle: (title)-> tabTitle = $('[data-type="MarkdownPreviewEnhancedView"] div.title') if tabTitle.length tabTitle[0].innerText = title updateTabTitle: -> @setTabTitle(@getTitle()) setMermaidTheme: (mermaidTheme)-> mermaidThemeStyle = fs.readFileSync(path.resolve(__dirname, '../dependencies/mermaid/'+mermaidTheme), {encoding: 'utf-8'}).toString() mermaidStyle = document.getElementById('mermaid-style') if mermaidStyle mermaidStyle.remove() mermaidStyle = document.createElement('style') mermaidStyle.id = 'mermaid-style' document.getElementsByTagName('head')[0].appendChild(mermaidStyle) mermaidStyle.innerHTML = mermaidThemeStyle # render mermaid graphs again # els = @element.getElementsByClassName('mermaid') @graphData?.mermaid_s = [] @renderMarkdown() bindEditor: (editor)-> if not @editor atom.workspace .open @uri, split: 'right', activatePane: false, searchAllPanes: false .then (e)=> previewTheme = atom.config.get('markdown-preview-enhanced.previewTheme') loadPreviewTheme previewTheme, true, ()=> @initEvents(editor) else # save cache CACHE[@editor.getPath()] = { html: @element?.innerHTML or '', codeChunksData: @codeChunksData, graphData: @graphData, presentationMode: @presentationMode, slideConfigs: @slideConfigs, filesCache: @filesCache, } # @element.innerHTML = '<p style="font-size: 24px;"> loading preview... <br>type something if preview doesn\'t render :( </p>' setTimeout(()=> @initEvents(editor) , 0) initEvents: (editor)-> @editor = editor @updateTabTitle() @element.removeAttribute('style') if not @parseMD {@parseMD, @buildScrollMap, @processFrontMatter} = require './md' require '../dependencies/wavedrom/default.js' require '../dependencies/wavedrom/wavedrom.min.js' @tocConfigs = null @scrollMap = null @fileDirectoryPath = @editor.getDirectoryPath() @projectDirectoryPath = @getProjectDirectoryPath() @firstTimeRenderMarkdowon = true @filesCache = {} if @disposables # remove all binded events @disposables.dispose() @disposables = new CompositeDisposable() @initEditorEvent() @initViewEvent() # restore preview d = CACHE[@editor.getPath()] if d @element.innerHTML = d.html @graphData = d.graphData @codeChunksData = d.codeChunksData @presentationMode = d.presentationMode @slideConfigs = d.slideConfigs @filesCache = d.filesCache if @presentationMode @element.setAttribute 'data-presentation-preview-mode', '' else @element.removeAttribute 'data-presentation-preview-mode' @setInitialScrollPos() # console.log 'restore ' + @editor.getPath() # reset back to top button onclick event @element.getElementsByClassName('back-to-top-btn')?[0]?.onclick = ()=> @element.scrollTop = 0 # reset refresh button onclick event @element.getElementsByClassName('refresh-btn')?[0]?.onclick = ()=> @filesCache = {} codeChunkAPI.clearCache() @renderMarkdown() # rebind tag a click event @bindTagAClickEvent() # render plantuml in case @renderPlantUML() # reset code chunks @setupCodeChunks() else @renderMarkdown() @scrollMap = null initEditorEvent: -> editorElement = @editor.getElement() @disposables.add @editor.onDidDestroy ()=> @setTabTitle('unknown preview') if @disposables @disposables.dispose() @disposables = null @editor = null @element.onscroll = null @element.innerHTML = '<p style="font-size: 24px;"> Open a markdown file to start preview </p>' @disposables.add @editor.onDidStopChanging ()=> # @textChanged = true # this line has problem. if @liveUpdate and !@usePandocParser @updateMarkdown() @disposables.add @editor.onDidSave ()=> if not @liveUpdate or @usePandocParser @textChanged = true @updateMarkdown() @disposables.add @editor.onDidChangeModified ()=> if not @liveUpdate or @usePandocParser @textChanged = true @disposables.add editorElement.onDidChangeScrollTop ()=> if !@scrollSync or !@element or @textChanged or !@editor or @presentationMode return if Date.now() < @editorScrollDelay return editorHeight = @editor.getElement().getHeight() firstVisibleScreenRow = @editor.getFirstVisibleScreenRow() lastVisibleScreenRow = firstVisibleScreenRow + Math.floor(editorHeight / @editor.getLineHeightInPixels()) lineNo = Math.floor((firstVisibleScreenRow + lastVisibleScreenRow) / 2) @scrollMap ?= @buildScrollMap(this) # disable markdownHtmlView onscroll @previewScrollDelay = Date.now() + 500 # scroll preview to most top as editor is at most top. return @scrollToPos(0) if firstVisibleScreenRow == 0 # @element.scrollTop = @scrollMap[lineNo] - editorHeight / 2 if lineNo of @scrollMap then @scrollToPos(@scrollMap[lineNo]-editorHeight / 2) # match markdown preview to cursor position @disposables.add @editor.onDidChangeCursorPosition (event)=> if !@scrollSync or !@element or @textChanged return if Date.now() < @parseDelay return # track currnet time to disable onDidChangeScrollTop @editorScrollDelay = Date.now() + 500 # disable preview onscroll @previewScrollDelay = Date.now() + 500 if @presentationMode and @slideConfigs return @scrollSyncForPresentation(event.newBufferPosition.row) if event.oldScreenPosition.row != event.newScreenPosition.row or event.oldScreenPosition.column == 0 lineNo = event.newScreenPosition.row if lineNo <= 1 # first 2nd rows @scrollToPos(0) return else if lineNo >= @editor.getScreenLineCount() - 2 # last 2nd rows @scrollToPos(@element.scrollHeight - 16) return @scrollSyncToLineNo(lineNo) initViewEvent: -> @element.onscroll = ()=> if !@editor or !@scrollSync or @textChanged or @presentationMode return if Date.now() < @previewScrollDelay return if @element.scrollTop == 0 # most top @editorScrollDelay = Date.now() + 500 return @scrollToPos 0, @editor.getElement() top = @element.scrollTop + @element.offsetHeight / 2 # try to find corresponding screen buffer row @scrollMap ?= @buildScrollMap(this) i = 0 j = @scrollMap.length - 1 count = 0 screenRow = -1 while count < 20 if Math.abs(top - @scrollMap[i]) < 20 screenRow = i break else if Math.abs(top - @scrollMap[j]) < 20 screenRow = j break else mid = Math.floor((i + j) / 2) if top > @scrollMap[mid] i = mid else j = mid count++ if screenRow == -1 screenRow = mid @scrollToPos(screenRow * @editor.getLineHeightInPixels() - @element.offsetHeight / 2, @editor.getElement()) # @editor.getElement().setScrollTop # track currnet time to disable onDidChangeScrollTop @editorScrollDelay = Date.now() + 500 initSettingsEvents: -> # break line? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.breakOnSingleNewline', (breakOnSingleNewline)=> @parseDelay = Date.now() # <- fix 'loading preview' stuck bug @renderMarkdown() # typographer? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.enableTypographer', (enableTypographer)=> @renderMarkdown() # liveUpdate? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.liveUpdate', (flag) => @liveUpdate = flag @scrollMap = null # scroll sync? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.scrollSync', (flag) => @scrollSync = flag @scrollMap = null # scroll duration @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.scrollDuration', (duration)=> duration = parseInt(duration) or 0 if duration < 0 @scrollDuration = 120 else @scrollDuration = duration # math? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.mathRenderingOption', (option) => @mathRenderingOption = option @renderMarkdown() # pandoc parser? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.usePandocParser', (flag)=> @usePandocParser = flag @renderMarkdown() # mermaid theme @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.mermaidTheme', (theme) => @setMermaidTheme theme # hack to solve https://github.com/exupero/saveSvgAsPng/issues/128 problem # @element.setAttribute 'data-mermaid-theme', theme # render front matter as table? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.frontMatterRenderingOption', () => @renderMarkdown() # show back to top button? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.showBackToTopButton', (flag)=> @showBackToTopButton = flag if flag @addBackToTopButton() else document.getElementsByClassName('back-to-top-btn')[0]?.remove() scrollSyncForPresentation: (bufferLineNo)-> i = @slideConfigs.length - 1 while i >= 0 if bufferLineNo >= @slideConfigs[i].line break i-=1 slideElement = @element.querySelector(".slide[data-offset=\"#{i}\"]") return if not slideElement # set slide to middle of preview @element.scrollTop = -@element.offsetHeight/2 + (slideElement.offsetTop + slideElement.offsetHeight/2)*parseFloat(slideElement.style.zoom) # lineNo here is screen buffer row. scrollSyncToLineNo: (lineNo)-> @scrollMap ?= @buildScrollMap(this) editorElement = @editor.getElement() firstVisibleScreenRow = @editor.getFirstVisibleScreenRow() posRatio = (lineNo - firstVisibleScreenRow) / (editorElement.getHeight() / @editor.getLineHeightInPixels()) scrollTop = @scrollMap[lineNo] - (if posRatio > 1 then 1 else posRatio) * editorElement.getHeight() scrollTop = 0 if scrollTop < 0 @scrollToPos scrollTop # smooth scroll @element to scrollTop # if editorElement is provided, then editorElement.setScrollTop(scrollTop) scrollToPos: (scrollTop, editorElement=null)-> if @scrollTimeout clearTimeout @scrollTimeout @scrollTimeout = null if not @editor or not @editor.alive or scrollTop < 0 return delay = 10 helper = (duration=0)=> @scrollTimeout = setTimeout => if duration <= 0 if editorElement @editorScrollDelay = Date.now() + 500 editorElement.setScrollTop scrollTop else @previewScrollDelay = Date.now() + 500 @element.scrollTop = scrollTop return if editorElement difference = scrollTop - editorElement.getScrollTop() else difference = scrollTop - @element.scrollTop perTick = difference / duration * delay if editorElement # disable editor scroll @editorScrollDelay = Date.now() + 500 s = editorElement.getScrollTop() + perTick editorElement.setScrollTop s return if s == scrollTop else # disable preview onscroll @previewScrollDelay = Date.now() + 500 @element.scrollTop += perTick return if @element.scrollTop == scrollTop helper duration-delay , delay helper(@scrollDuration) formatStringBeforeParsing: (str)-> @mainModule.hook.chain('on-will-parse-markdown', str) formatStringAfterParsing: (str)-> @mainModule.hook.chain('on-did-parse-markdown', str) updateMarkdown: -> @editorScrollDelay = Date.now() + 500 @previewScrollDelay = Date.now() + 500 @renderMarkdown() renderMarkdown: -> if Date.now() < @parseDelay or !@editor or !@element @textChanged = false return @parseDelay = Date.now() + 200 @parseMD @formatStringBeforeParsing(@editor.getText()), {isForPreview: true, markdownPreview: this, @fileDirectoryPath, @projectDirectoryPath}, ({html, slideConfigs, yamlConfig})=> html = @formatStringAfterParsing(html) if slideConfigs.length html = @parseSlides(html, slideConfigs, yamlConfig) @element.setAttribute 'data-presentation-preview-mode', '' @presentationMode = true @slideConfigs = slideConfigs else @element.removeAttribute 'data-presentation-preview-mode' @presentationMode = false @element.innerHTML = html @graphData = {} @bindEvents() @mainModule.emitter.emit 'on-did-render-preview', {htmlString: html, previewElement: @element} @setInitialScrollPos() @addBackToTopButton() @addRefreshButton() @textChanged = false setInitialScrollPos: -> if @firstTimeRenderMarkdowon @firstTimeRenderMarkdowon = false cursor = @editor.cursors[0] return if not cursor if @presentationMode @scrollSyncForPresentation cursor.getBufferRow() else t = @scrollDuration @scrollDuration = 0 @scrollSyncToLineNo cursor.getScreenRow() @scrollDuration = t addBackToTopButton: -> # TODO: check config # add back to top button #222 if @showBackToTopButton and @element.scrollHeight > @element.offsetHeight backToTopBtn = document.createElement('div') backToTopBtn.classList.add('back-to-top-btn') backToTopBtn.classList.add('btn') backToTopBtn.innerHTML = '<span>⬆︎</span>' @element.appendChild(backToTopBtn) backToTopBtn.onclick = ()=> @element.scrollTop = 0 addRefreshButton: -> refreshBtn = document.createElement('div') refreshBtn.classList.add('refresh-btn') refreshBtn.classList.add('btn') refreshBtn.innerHTML = '<span>⟳</span>' @element.appendChild(refreshBtn) refreshBtn.onclick = ()=> # clear cache @filesCache = {} codeChunkAPI.clearCache() # render again @renderMarkdown() bindEvents: -> @bindTagAClickEvent() @setupCodeChunks() @initTaskList() @renderMermaid() @renderPlantUML() @renderWavedrom() @renderViz() @renderKaTeX() @renderMathJax() @scrollMap = null # <a href="" > ... </a> click event bindTagAClickEvent: ()-> as = @element.getElementsByTagName('a') analyzeHref = (href)=> if href and href[0] == '#' targetElement = @element.querySelector("[id=\"#{href.slice(1)}\"]") # fix number id bug if targetElement a.onclick = ()=> # jump to tag position offsetTop = 0 el = targetElement while el and el != @element offsetTop += el.offsetTop el = el.offsetParent if @element.scrollTop > offsetTop @element.scrollTop = offsetTop - 32 - targetElement.offsetHeight else @element.scrollTop = offsetTop else a.onclick = ()=> return if !href return if href.match(/^(http|https)\:\/\//) # the default behavior will open browser for that url. if path.extname(href) in ['.pdf', '.xls', '.xlsx', '.doc', '.ppt', '.docx', '.pptx'] # issue #97 @openFile href else if href.match(/^file\:\/\/\//) # if href.startsWith 'file:///' openFilePath = href.slice(8) # remove protocal openFilePath = openFilePath.replace(/\.md(\s*)\#(.+)$/, '.md') # remove #anchor atom.workspace.open openFilePath, split: 'left', searchAllPanes: true else @openFile href for a in as href = a.getAttribute('href') analyzeHref(href) setupCodeChunks: ()-> codeChunks = @element.getElementsByClassName('code-chunk') return if !codeChunks.length newCodeChunksData = {} needToSetupChunksId = false setupCodeChunk = (codeChunk)=> dataArgs = codeChunk.getAttribute('data-args') idMatch = dataArgs.match(/\s*id\s*:\s*\"([^\"]*)\"/) if idMatch and idMatch[1] id = idMatch[1] codeChunk.id = 'code_chunk_' + id running = @codeChunksData[id]?.running or false codeChunk.classList.add('running') if running # remove output-div and output-element children = codeChunk.children i = children.length - 1 while i >= 0 child = children[i] if child.classList.contains('output-div') or child.classList.contains('output-element') child.remove() i -= 1 outputDiv = @codeChunksData[id]?.outputDiv outputElement = @codeChunksData[id]?.outputElement codeChunk.appendChild(outputElement) if outputElement codeChunk.appendChild(outputDiv) if outputDiv newCodeChunksData[id] = {running, outputDiv, outputElement} else # id not exist, create new id needToSetupChunksId = true runBtn = codeChunk.getElementsByClassName('run-btn')[0] runBtn?.addEventListener 'click', ()=> @runCodeChunk(codeChunk) runAllBtn = codeChunk.getElementsByClassName('run-all-btn')[0] runAllBtn?.addEventListener 'click', ()=> @runAllCodeChunks() for codeChunk in codeChunks break if needToSetupChunksId setupCodeChunk(codeChunk) if needToSetupChunksId @setupCodeChunksId() @codeChunksData = newCodeChunksData # key is codeChunkId, value is {running, outputDiv} setupCodeChunksId: ()-> buffer = @editor.buffer return if !buffer lines = buffer.lines lineNo = 0 curScreenPos = @editor.getCursorScreenPosition() while lineNo < lines.length line = lines[lineNo] match = line.match(/^\`\`\`\{(.+)\}(\s*)/) if match cmd = match[1] dataArgs = '' i = cmd.indexOf(' ') if i > 0 dataArgs = cmd.slice(i + 1, cmd.length).trim() cmd = cmd.slice(0, i) idMatch = match[1].match(/\s*id\s*:\s*\"([^\"]*)\"/) if !idMatch id = (new Date().getTime()).toString(36) line = line.trimRight() line = line.replace(/}$/, (if !dataArgs then '' else ',') + ' id:"' + id + '"}') @parseDelay = Date.now() + 500 # prevent renderMarkdown buffer.setTextInRange([[lineNo, 0], [lineNo+1, 0]], line + '\n') lineNo += 1 @editor.setCursorScreenPosition(curScreenPos) # restore cursor position. # This will cause Maximum size exceeded # @parseDelay = Date.now() # @renderMarkdown() getNearestCodeChunk: ()-> bufferRow = @editor.getCursorBufferPosition().row codeChunks = @element.getElementsByClassName('code-chunk') i = codeChunks.length - 1 while i >= 0 codeChunk = codeChunks[i] lineNo = parseInt(codeChunk.getAttribute('data-line')) if lineNo <= bufferRow return codeChunk i-=1 return null # return false if meet error # otherwise return # { # cmd, # options, # code, # id, # } parseCodeChunk: (codeChunk)-> code = codeChunk.getAttribute('data-code') dataArgs = codeChunk.getAttribute('data-args') options = null try allowUnsafeEval -> options = eval("({#{dataArgs}})") # options = JSON.parse '{'+dataArgs.replace((/([(\w)|(\-)]+)(:)/g), "\"$1\"$2").replace((/'/g), "\"")+'}' catch error atom.notifications.addError('Invalid options', detail: dataArgs) return false id = options.id # check options.continue if options.continue last = null if options.continue == true codeChunks = @element.getElementsByClassName 'code-chunk' i = codeChunks.length - 1 while i >= 0 if codeChunks[i] == codeChunk last = codeChunks[i - 1] break i-- else # id last = document.getElementById('code_chunk_' + options.continue) if last {code: lastCode, options: lastOptions} = @parseCodeChunk(last) or {} lastOptions = lastOptions or {} code = (lastCode or '') + '\n' + code options = Object.assign({}, lastOptions, options) else atom.notifications.addError('Invalid continue for code chunk ' + (options.id or ''), detail: options.continue.toString()) return false cmd = options.cmd or codeChunk.getAttribute('data-lang') # need to put here because options might be modified before return {cmd, options, code, id} runCodeChunk: (codeChunk=null)-> codeChunk = @getNearestCodeChunk() if not codeChunk return if not codeChunk return if codeChunk.classList.contains('running') parseResult = @parseCodeChunk(codeChunk) return if !parseResult {code, options, cmd, id} = parseResult if !id return atom.notifications.addError('Code chunk error', detail: 'id is not found or just updated.') codeChunk.classList.add('running') if @codeChunksData[id] @codeChunksData[id].running = true else @codeChunksData[id] = {running: true} # check options `element` if options.element outputElement = codeChunk.getElementsByClassName('output-element')?[0] if !outputElement # create and append `output-element` div outputElement = document.createElement 'div' outputElement.classList.add 'output-element' codeChunk.appendChild outputElement outputElement.innerHTML = options.element else codeChunk.getElementsByClassName('output-element')?[0]?.remove() outputElement = null codeChunkAPI.run code, @fileDirectoryPath, cmd, options, (error, data, options)=> # get new codeChunk codeChunk = document.getElementById('code_chunk_' + id) return if not codeChunk codeChunk.classList.remove('running') return if error # or !data data = (data or '').toString() outputDiv = codeChunk.getElementsByClassName('output-div')?[0] if !outputDiv outputDiv = document.createElement 'div' outputDiv.classList.add 'output-div' else outputDiv.innerHTML = '' if options.output == 'html' outputDiv.innerHTML = data else if options.output == 'png' imageElement = document.createElement 'img' imageData = Buffer(data).toString('base64') imageElement.setAttribute 'src', "data:image/png;charset=utf-8;base64,#{imageData}" outputDiv.appendChild imageElement else if options.output == 'markdown' @parseMD data, {@fileDirectoryPath, @projectDirectoryPath}, ({html})=> outputDiv.innerHTML = html @scrollMap = null else if options.output == 'none' outputDiv.remove() outputDiv = null else if data?.length preElement = document.createElement 'pre' preElement.innerText = data preElement.classList.add('editor-colors') preElement.classList.add('lang-text') outputDiv.appendChild preElement if outputDiv codeChunk.appendChild outputDiv @scrollMap = null # check matplotlib | mpl if options.matplotlib or options.mpl scriptElements = outputDiv.getElementsByTagName('script') if scriptElements.length window.d3 ?= require('../dependencies/mpld3/d3.v3.min.js') window.mpld3 ?= require('../dependencies/mpld3/mpld3.v0.3.min.js') for scriptElement in scriptElements code = scriptElement.innerHTML allowUnsafeNewFunction -> allowUnsafeEval -> eval(code) @codeChunksData[id] = {running: false, outputDiv, outputElement} runAllCodeChunks: ()-> codeChunks = @element.getElementsByClassName('code-chunk') for chunk in codeChunks @runCodeChunk(chunk) initTaskList: ()-> checkboxs = @element.getElementsByClassName('task-list-item-checkbox') for checkbox in checkboxs this_ = this checkbox.onclick = ()-> if !this_.editor return checked = this.checked buffer = this_.editor.buffer if !buffer return lineNo = parseInt(this.parentElement.getAttribute('data-line')) line = buffer.lines[lineNo] if checked line = line.replace('[ ]', '[x]') else line = line.replace(/\[(x|X)\]/, '[ ]') this_.parseDelay = Date.now() + 500 buffer.setTextInRange([[lineNo, 0], [lineNo+1, 0]], line + '\n') renderMermaid: ()-> els = @element.getElementsByClassName('mermaid mpe-graph') if els.length @graphData.mermaid_s = Array.prototype.slice.call(els) notProcessedEls = @element.querySelectorAll('.mermaid.mpe-graph:not([data-processed])') if notProcessedEls.length mermaid.init null, notProcessedEls ### # the code below doesn't seem to be working # I think mermaidAPI.render function has bug cb = (el)-> (svgGraph)-> el.innerHTML = svgGraph el.setAttribute 'data-processed', 'true' # the code below is a hackable way to solve mermaid bug el.firstChild.style.height = el.getAttribute('viewbox').split(' ')[3] + 'px' for el in els offset = parseInt(el.getAttribute('data-offset')) el.id = 'mermaid'+offset mermaidAPI.render el.id, el.getAttribute('data-original'), cb(el) ### # disable @element onscroll @previewScrollDelay = Date.now() + 500 renderWavedrom: ()-> els = @element.getElementsByClassName('wavedrom mpe-graph') if els.length @graphData.wavedrom_s = Array.prototype.slice.call(els) # WaveDrom.RenderWaveForm(0, WaveDrom.eva('a0'), 'a') for el in els if el.getAttribute('data-processed') != 'true' offset = parseInt(el.getAttribute('data-offset')) el.id = 'wavedrom'+offset text = el.getAttribute('data-original').trim() continue if not text.length allowUnsafeEval => try content = eval("(#{text})") # eval function here WaveDrom.RenderWaveForm(offset, content, 'wavedrom') el.setAttribute 'data-processed', 'true' @scrollMap = null catch error el.innerText = 'failed to eval WaveDrom code.' # disable @element onscroll @previewScrollDelay = Date.now() + 500 renderPlantUML: ()-> els = @element.getElementsByClassName('plantuml mpe-graph') if els.length @graphData.plantuml_s = Array.prototype.slice.call(els) helper = (el, text)=> plantumlAPI.render text, (outputHTML)=> el.innerHTML = outputHTML el.setAttribute 'data-processed', true @scrollMap = null for el in els if el.getAttribute('data-processed') != 'true' helper(el, el.getAttribute('data-original')) el.innerText = 'rendering graph...\n' renderViz: (element=@element)-> els = element.getElementsByClassName('viz mpe-graph') if els.length @graphData.viz_s = Array.prototype.slice.call(els) @Viz ?= require('../dependencies/viz/viz.js') for el in els if el.getAttribute('data-processed') != 'true' try content = el.getAttribute('data-original') options = {} # check engine content = content.trim().replace /^engine(\s)*[:=]([^\n]+)/, (a, b, c)-> options.engine = c.trim() if c?.trim() in ['circo', 'dot', 'fdp', 'neato', 'osage', 'twopi'] return '' el.innerHTML = @Viz(content, options) # default svg el.setAttribute 'data-processed', true catch error el.innerHTML = error renderMathJax: ()-> return if @mathRenderingOption != 'MathJax' and !@usePandocParser if typeof(MathJax) == 'undefined' return loadMathJax document, ()=> @renderMathJax() if @mathJaxProcessEnvironments or @usePandocParser return MathJax.Hub.Queue ['Typeset', MathJax.Hub, @element], ()=> @scrollMap = null els = @element.getElementsByClassName('mathjax-exps') return if !els.length unprocessedElements = [] for el in els if !el.hasAttribute('data-processed') el.setAttribute 'data-original', el.textContent unprocessedElements.push el callback = ()=> for el in unprocessedElements el.setAttribute 'data-processed', true @scrollMap = null if unprocessedElements.length == els.length MathJax.Hub.Queue ['Typeset', MathJax.Hub, @element], callback else if unprocessedElements.length MathJax.Hub.Typeset unprocessedElements, callback renderKaTeX: ()-> return if @mathRenderingOption != 'KaTeX' els = @element.getElementsByClassName('katex-exps') for el in els if el.hasAttribute('data-processed') continue else displayMode = el.hasAttribute('display-mode') dataOriginal = el.textContent try katex.render(el.textContent, el, {displayMode}) catch error el.innerHTML = "<span style=\"color: #ee7f49; font-weight: 500;\">#{error}</span>" el.setAttribute('data-processed', 'true') el.setAttribute('data-original', dataOriginal) resizeEvent: ()-> @scrollMap = null ### convert './a.txt' '/a.txt' ### resolveFilePath: (filePath='', relative=false)-> if filePath.match(protocolsWhiteListRegExp) return filePath else if filePath.startsWith('/') if relative return path.relative(@fileDirectoryPath, path.resolve(@projectDirectoryPath, '.'+filePath)) else return 'file:///'+path.resolve(@projectDirectoryPath, '.'+filePath) else if relative return filePath else return 'file:///'+path.resolve(@fileDirectoryPath, filePath) ## Utilities openInBrowser: (isForPresentationPrint=false)-> return if not @editor @getHTMLContent offline: true, isForPrint: isForPresentationPrint, (htmlContent)=> temp.open prefix: 'markdown-preview-enhanced', suffix: '.html', (err, info)=> throw err if err fs.write info.fd, htmlContent, (err)=> throw err if err if isForPresentationPrint url = 'file:///' + info.path + '?print-pdf' atom.notifications.addInfo('Please copy and open the link below in Chrome.\nThen Right Click -> Print -> Save as Pdf.', dismissable: true, detail: url) else ## open in browser @openFile info.path exportToDisk: ()-> @documentExporterView.display(this) # open html file in browser or open pdf file in reader ... etc openFile: (filePath)-> if process.platform == 'win32' cmd = 'explorer' else if process.platform == 'darwin' cmd = 'open' else cmd = 'xdg-open' exec "#{cmd} #{filePath}" ## ## {Function} callback (htmlContent) insertCodeChunksResult: (htmlContent)-> # insert outputDiv and outputElement accordingly cheerio ?= require 'cheerio' $ = cheerio.load(htmlContent, {decodeEntities: false}) codeChunks = $('.code-chunk') jsCode = '' requireCache = {} # key is path scriptsStr = "" for codeChunk in codeChunks $codeChunk = $(codeChunk) dataArgs = $codeChunk.attr('data-args').unescape() options = null try allowUnsafeEval -> options = eval("({#{dataArgs}})") catch e continue id = options.id continue if !id cmd = options.cmd or $codeChunk.attr('data-lang') code = $codeChunk.attr('data-code').unescape() outputDiv = @codeChunksData[id]?.outputDiv outputElement = @codeChunksData[id]?.outputElement if outputDiv # append outputDiv result $codeChunk.append("<div class=\"output-div\">#{outputDiv.innerHTML}</div>") if options.matplotlib or options.mpl # remove innerHTML of <div id="fig_..."></div> # this is for fixing mpld3 exporting issue. gs = $('.output-div > div', $codeChunk) if gs for g in gs $g = $(g) if $g.attr('id')?.match(/fig\_/) $g.html('') ss = $('.output-div > script', $codeChunk) if ss for s in ss $s = $(s) c = $s.html() $s.remove() jsCode += (c + '\n') if options.element $codeChunk.append("<div class=\"output-element\">#{options.element}</div>") if cmd == 'javascript' requires = options.require or [] if typeof(requires) == 'string' requires = [requires] requiresStr = "" for requirePath in requires # TODO: css if requirePath.match(/^(http|https)\:\/\//) if (!requireCache[requirePath]) requireCache[requirePath] = true scriptsStr += "<script src=\"#{requirePath}\"></script>\n" else requirePath = path.resolve(@fileDirectoryPath, requirePath) if !requireCache[requirePath] requiresStr += (fs.readFileSync(requirePath, {encoding: 'utf-8'}) + '\n') requireCache[requirePath] = true jsCode += (requiresStr + code + '\n') html = $.html() html += "#{scriptsStr}\n" if scriptsStr html += "<script data-js-code>#{jsCode}</script>" if jsCode return html ## # {Function} callback (htmlContent) getHTMLContent: ({isForPrint, offline, useRelativeImagePath, phantomjsType}, callback)-> isForPrint ?= false offline ?= false useRelativeImagePath ?= false phantomjsType ?= false # pdf | png | jpeg | false return callback() if not @editor mathRenderingOption = atom.config.get('markdown-preview-enhanced.mathRenderingOption') res = @parseMD @formatStringBeforeParsing(@editor.getText()), {useRelativeImagePath, @fileDirectoryPath, @projectDirectoryPath, markdownPreview: this, hideFrontMatter: true}, ({html, yamlConfig, slideConfigs})=> htmlContent = @formatStringAfterParsing(html) yamlConfig = yamlConfig or {} # replace code chunks inside htmlContent htmlContent = @insertCodeChunksResult htmlContent if mathRenderingOption == 'KaTeX' if offline mathStyle = "<link rel=\"stylesheet\" href=\"file:///#{path.resolve(__dirname, '../node_modules/katex/dist/katex.min.css')}\">" else mathStyle = "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css\">" else if mathRenderingOption == 'MathJax' inline = atom.config.get('markdown-preview-enhanced.indicatorForMathRenderingInline') block = atom.config.get('markdown-preview-enhanced.indicatorForMathRenderingBlock') mathJaxProcessEnvironments = atom.config.get('markdown-preview-enhanced.mathJaxProcessEnvironments') if offline mathStyle = " <script type=\"text/x-mathjax-config\"> MathJax.Hub.Config({ messageStyle: 'none', tex2jax: {inlineMath: #{inline}, displayMath: #{block}, processEnvironments: #{mathJaxProcessEnvironments}, processEscapes: true} }); </script> <script type=\"text/javascript\" async src=\"file://#{path.resolve(__dirname, '../dependencies/mathjax/MathJax.js?config=TeX-AMS_CHTML')}\"></script> " else # inlineMath: [ ['$','$'], ["\\(","\\)"] ], # displayMath: [ ['$$','$$'], ["\\[","\\]"] ] mathStyle = " <script type=\"text/x-mathjax-config\"> MathJax.Hub.Config({ messageStyle: 'none', tex2jax: {inlineMath: #{inline}, displayMath: #{block}, processEnvironments: #{mathJaxProcessEnvironments}, processEscapes: true} }); </script> <script type=\"text/javascript\" async src=\"https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML\"></script> " else mathStyle = '' # presentation if slideConfigs.length htmlContent = @parseSlidesForExport(htmlContent, slideConfigs, useRelativeImagePath) if offline presentationScript = " <script src='file:///#{path.resolve(__dirname, '../dependencies/reveal/lib/js/head.min.js')}'></script> <script src='file:///#{path.resolve(__dirname, '../dependencies/reveal/js/reveal.js')}'></script>" else presentationScript = " <script src='https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.4.1/lib/js/head.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.4.1/js/reveal.min.js'></script>" presentationConfig = yamlConfig['presentation'] or {} dependencies = presentationConfig.dependencies or [] if presentationConfig.enableSpeakerNotes if offline dependencies.push {src: path.resolve(__dirname, '../dependencies/reveal/plugin/notes/notes.js'), async: true} else dependencies.push {src: 'revealjs_deps/notes.js', async: true} # TODO: copy notes.js file to corresponding folder presentationConfig.dependencies = dependencies # <link rel=\"stylesheet\" href='file:///#{path.resolve(__dirname, '../dependencies/reveal/reveal.css')}'> presentationStyle = """ <style> #{fs.readFileSync(path.resolve(__dirname, '../dependencies/reveal/reveal.css'))} #{if isForPrint then fs.readFileSync(path.resolve(__dirname, '../dependencies/reveal/pdf.css')) else ''} </style> """ presentationInitScript = """ <script> Reveal.initialize(#{JSON.stringify(Object.assign({margin: 0.1}, presentationConfig))}) </script> """ else presentationScript = '' presentationStyle = '' presentationInitScript = '' # phantomjs phantomjsClass = "" if phantomjsType if phantomjsType == '.pdf' phantomjsClass = 'phantomjs-pdf' else if phantomjsType == '.png' or phantomjsType == '.jpeg' phantomjsClass = 'phantomjs-image' title = @getFileName() title = title.slice(0, title.length - path.extname(title).length) # remove '.md' previewTheme = atom.config.get('markdown-preview-enhanced.previewTheme') if isForPrint and atom.config.get('markdown-preview-enhanced.pdfUseGithub') previewTheme = 'mpe-github-syntax' loadPreviewTheme previewTheme, false, (error, css)=> return callback() if error return callback """ <!DOCTYPE html> <html> <head> <title>#{title}</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> #{presentationStyle} <style> #{css} </style> #{mathStyle} #{presentationScript} </head> <body class=\"markdown-preview-enhanced #{phantomjsClass}\" #{if @presentationMode then 'data-presentation-mode' else ''}> #{htmlContent} </body> #{presentationInitScript} </html> """ # api doc [printToPDF] function # https://github.com/atom/electron/blob/master/docs/api/web-contents.md printPDF: (htmlPath, dest)-> return if not @editor {BrowserWindow} = require('electron').remote win = new BrowserWindow show: false win.loadURL htmlPath # get margins type marginsType = atom.config.get('markdown-preview-enhanced.marginsType') marginsType = if marginsType == 'default margin' then 0 else if marginsType == 'no margin' then 1 else 2 # get orientation landscape = atom.config.get('markdown-preview-enhanced.orientation') == 'landscape' lastIndexOfSlash = dest.lastIndexOf '/' or 0 pdfName = dest.slice(lastIndexOfSlash + 1) win.webContents.on 'did-finish-load', ()=> setTimeout(()=> win.webContents.printToPDF pageSize: atom.config.get('markdown-preview-enhanced.exportPDFPageFormat'), landscape: landscape, printBackground: atom.config.get('markdown-preview-enhanced.printBackground'), marginsType: marginsType, (err, data)=> throw err if err destFile = new File(dest) destFile.create().then (flag)=> destFile.write data atom.notifications.addInfo "File #{pdfName} was created", detail: "path: #{dest}" # open pdf if atom.config.get('markdown-preview-enhanced.pdfOpenAutomatically') @openFile dest , 500) saveAsPDF: (dest)-> return if not @editor if @presentationMode # for presentation, need to print from chrome @openInBrowser(true) return @getHTMLContent isForPrint: true, offline: true, (htmlContent)=> temp.open prefix: 'markdown-preview-enhanced', suffix: '.html', (err, info)=> throw err if err fs.write info.fd, htmlContent, (err)=> throw err if err @printPDF "file://#{info.path}", dest saveAsHTML: (dest, offline=true, useRelativeImagePath)-> return if not @editor @getHTMLContent isForPrint: false, offline: offline, useRelativeImagePath: useRelativeImagePath, (htmlContent)=> htmlFileName = path.basename(dest) # presentation speaker notes # copy dependency files if !offline and htmlContent.indexOf('[{"src":"revealjs_deps/notes.js","async":true}]') >= 0 depsDirName = path.resolve(path.dirname(dest), 'revealjs_deps') depsDir = new Directory(depsDirName) depsDir.create().then (flag)-> true fs.createReadStream(path.resolve(__dirname, '../dependencies/reveal/plugin/notes/notes.js')).pipe(fs.createWriteStream(path.resolve(depsDirName, 'notes.js'))) fs.createReadStream(path.resolve(__dirname, '../dependencies/reveal/plugin/notes/notes.html')).pipe(fs.createWriteStream(path.resolve(depsDirName, 'notes.html'))) destFile = new File(dest) destFile.create().then (flag)-> destFile.write htmlContent atom.notifications.addInfo("File #{htmlFileName} was created", detail: "path: #{dest}") #################################################### ## Presentation ################################################## parseSlides: (html, slideConfigs, yamlConfig)-> slides = html.split '<div class="new-slide"></div>' slides = slides.slice(1) output = '' offset = 0 width = 960 height = 700 if yamlConfig and yamlConfig['presentation'] presentationConfig = yamlConfig['presentation'] width = presentationConfig['width'] or 960 height = presentationConfig['height'] or 700 ratio = height / width * 100 + '%' zoom = (@element.offsetWidth - 128)/width ## 64 is 2*padding for slide in slides # slide = slide.trim() # if slide.length slideConfig = slideConfigs[offset] styleString = '' videoString = '' iframeString = '' if slideConfig['data-background-image'] styleString += "background-image: url('#{@resolveFilePath(slideConfig['data-background-image'])}');" if slideConfig['data-background-size'] styleString += "background-size: #{slideConfig['data-background-size']};" else styleString += "background-size: cover;" if slideConfig['data-background-position'] styleString += "background-position: #{slideConfig['data-background-position']};" else styleString += "background-position: center;" if slideConfig['data-background-repeat'] styleString += "background-repeat: #{slideConfig['data-background-repeat']};" else styleString += "background-repeat: no-repeat;" else if slideConfig['data-background-color'] styleString += "background-color: #{slideConfig['data-background-color']} !important;" else if slideConfig['data-background-video'] videoMuted = slideConfig['data-background-video-muted'] videoLoop = slideConfig['data-background-video-loop'] muted_ = if videoMuted then 'muted' else '' loop_ = if videoLoop then 'loop' else '' videoString = """ <video #{muted_} #{loop_} playsinline autoplay class=\"background-video\" src=\"#{@resolveFilePath(slideConfig['data-background-video'])}\"> </video> """ # <source src=\"#{slideConfig['data-background-video']}\"> else if slideConfig['data-background-iframe'] iframeString = """ <iframe class=\"background-iframe\" src=\"#{@resolveFilePath(slideConfig['data-background-iframe'])}\" frameborder="0" > </iframe> <div class=\"background-iframe-overlay\"></div> """ output += """ <div class='slide' data-offset='#{offset}' style="width: #{width}px; height: #{height}px; zoom: #{zoom}; #{styleString}"> #{videoString} #{iframeString} <section>#{slide}</section> </div> """ offset += 1 # remove <aside class="notes"> ... </aside> output = output.replace(/(<aside\b[^>]*>)[^<>]*(<\/aside>)/ig, '') """ <div class="preview-slides"> #{output} </div> """ parseSlidesForExport: (html, slideConfigs, useRelativeImagePath)-> slides = html.split '<div class="new-slide"></div>' slides = slides.slice(1) output = '' parseAttrString = (slideConfig)=> attrString = '' if slideConfig['data-background-image'] attrString += " data-background-image='#{@resolveFilePath(slideConfig['data-background-image'], useRelativeImagePath)}'" if slideConfig['data-background-size'] attrString += " data-background-size='#{slideConfig['data-background-size']}'" if slideConfig['data-background-position'] attrString += " data-background-position='#{slideConfig['data-background-position']}'" if slideConfig['data-background-repeat'] attrString += " data-background-repeat='#{slideConfig['data-background-repeat']}'" if slideConfig['data-background-color'] attrString += " data-background-color='#{slideConfig['data-background-color']}'" if slideConfig['data-notes'] attrString += " data-notes='#{slideConfig['data-notes']}'" if slideConfig['data-background-video'] attrString += " data-background-video='#{@resolveFilePath(slideConfig['data-background-video'], useRelativeImagePath)}'" if slideConfig['data-background-video-loop'] attrString += " data-background-video-loop" if slideConfig['data-background-video-muted'] attrString += " data-background-video-muted" if slideConfig['data-transition'] attrString += " data-transition='#{slideConfig['data-transition']}'" if slideConfig['data-background-iframe'] attrString += " data-background-iframe='#{@resolveFilePath(slideConfig['data-background-iframe'], useRelativeImagePath)}'" attrString i = 0 while i < slides.length slide = slides[i] slideConfig = slideConfigs[i] attrString = parseAttrString(slideConfig) if !slideConfig['vertical'] if i > 0 and slideConfigs[i-1]['vertical'] # end of vertical slides output += '</section>' if i < slides.length - 1 and slideConfigs[i+1]['vertical'] # start of vertical slides output += "<section>" output += "<section #{attrString}>#{slide}</section>" i += 1 if i > 0 and slideConfigs[i-1]['vertical'] # end of vertical slides output += "</section>" """ <div class="reveal"> <div class="slides"> #{output} </div> </div> """ #################################################### ## PhantomJS ################################################## loadPhantomJSHeaderFooterConfig: ()-> # mermaid_config.js configPath = path.resolve(atom.config.configDirPath, './markdown-preview-enhanced/phantomjs_header_footer_config.js') try delete require.cache[require.resolve(configPath)] # return uncached return require(configPath) or {} catch error configFile = new File(configPath) configFile.create().then (flag)-> if !flag # already exists atom.notifications.addError('Failed to load phantomjs_header_footer_config.js', detail: 'there might be errors in your config file') return configFile.write """ 'use strict' /* configure header and footer (and other options) more information can be found here: https://github.com/marcbachmann/node-html-pdf Attention: this config will override your config in exporter panel. eg: let config = { "header": { "height": "45mm", "contents": '<div style="text-align: center;">Author: <NAME></div>' }, "footer": { "height": "28mm", "contents": '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>' } } */ // you can edit the 'config' variable below let config = { } module.exports = config || {} """ return {} phantomJSExport: (dest)-> return if not @editor if @presentationMode # for presentation, need to print from chrome @openInBrowser(true) return @getHTMLContent isForPrint: true, offline: true, phantomjsType: path.extname(dest), (htmlContent)=> fileType = atom.config.get('markdown-preview-enhanced.phantomJSExportFileType') format = atom.config.get('markdown-preview-enhanced.exportPDFPageFormat') orientation = atom.config.get('markdown-preview-enhanced.orientation') margin = atom.config.get('markdown-preview-enhanced.phantomJSMargin').trim() if !margin.length margin = '1cm' else margin = margin.split(',').map (m)->m.trim() if margin.length == 1 margin = margin[0] else if margin.length == 2 margin = {'top': margin[0], 'bottom': margin[0], 'left': margin[1], 'right': margin[1]} else if margin.length == 4 margin = {'top': margin[0], 'right': margin[1], 'bottom': margin[2], 'left': margin[3]} else margin = '1cm' # get header and footer config = @loadPhantomJSHeaderFooterConfig() pdf .create htmlContent, Object.assign({type: fileType, format: format, orientation: orientation, border: margin, quality: '75', timeout: 60000, script: path.join(__dirname, '../dependencies/phantomjs/pdf_a4_portrait.js')}, config) .toFile dest, (err, res)=> if err atom.notifications.addError err # open pdf else lastIndexOfSlash = dest.lastIndexOf '/' or 0 fileName = dest.slice(lastIndexOfSlash + 1) atom.notifications.addInfo "File #{fileName} was created", detail: "path: #{dest}" if atom.config.get('markdown-preview-enhanced.pdfOpenAutomatically') @openFile dest ## EBOOK generateEbook: (dest)-> @parseMD @formatStringBeforeParsing(@editor.getText()), {isForEbook: true, @fileDirectoryPath, @projectDirectoryPath, hideFrontMatter:true}, ({html, yamlConfig})=> html = @formatStringAfterParsing(html) ebookConfig = null if yamlConfig ebookConfig = yamlConfig['ebook'] if !ebookConfig return atom.notifications.addError('ebook config not found', detail: 'please insert ebook front-matter to your markdown file') else atom.notifications.addInfo('Your document is being prepared', detail: ':)') if ebookConfig.cover # change cover to absolute path if necessary cover = ebookConfig.cover if cover.startsWith('./') or cover.startsWith('../') cover = path.resolve(@fileDirectoryPath, cover) ebookConfig.cover = cover else if cover.startsWith('/') cover = path.resolve(@projectDirectoryPath, '.'+cover) ebookConfig.cover = cover div = document.createElement('div') div.innerHTML = html structure = [] # {level:0, filePath: 'path to file', heading: '', id: ''} headingOffset = 0 # load the last ul, analyze toc links. getStructure = (ul, level)-> for li in ul.children a = li.children[0]?.getElementsByTagName('a')?[0] continue if not a filePath = a.getAttribute('href') # assume markdown file path heading = a.innerHTML id = 'ebook-heading-id-'+headingOffset structure.push {level: level, filePath: filePath, heading: heading, id: id} headingOffset += 1 a.href = '#'+id # change id if li.childElementCount > 1 getStructure(li.children[1], level+1) children = div.children i = children.length - 1 while i >= 0 if children[i].tagName == 'UL' # find table of contents getStructure(children[i], 0) break i -= 1 outputHTML = div.innerHTML # append files according to structure for obj in structure heading = obj.heading id = obj.id level = obj.level filePath = obj.filePath if filePath.startsWith('file:///') filePath = filePath.slice(8) try text = fs.readFileSync(filePath, {encoding: 'utf-8'}) @parseMD @formatStringBeforeParsing(text), {isForEbook: true, projectDirectoryPath: @projectDirectoryPath, fileDirectoryPath: path.dirname(filePath)}, ({html})=> html = @formatStringAfterParsing(html) # add to TOC div.innerHTML = html if div.childElementCount div.children[0].id = id div.children[0].setAttribute('ebook-toc-level-'+(level+1), '') div.children[0].setAttribute('heading', heading) outputHTML += div.innerHTML catch error atom.notifications.addError('Ebook generation: Failed to load file', detail: filePath + '\n ' + error) return # render viz div.innerHTML = outputHTML @renderViz(div) # download images for .epub and .mobi imagesToDownload = [] if path.extname(dest) in ['.epub', '.mobi'] for img in div.getElementsByTagName('img') src = img.getAttribute('src') if src.startsWith('http://') or src.startsWith('https://') imagesToDownload.push(img) request = require('request') async = require('async') if imagesToDownload.length atom.notifications.addInfo('downloading images...') asyncFunctions = imagesToDownload.map (img)=> (callback)=> httpSrc = img.getAttribute('src') savePath = Math.random().toString(36).substr(2, 9) + '_' + path.basename(httpSrc) savePath = path.resolve(@fileDirectoryPath, savePath) stream = request(httpSrc).pipe(fs.createWriteStream(savePath)) stream.on 'finish', ()-> img.setAttribute 'src', 'file:///'+savePath callback(null, savePath) async.parallel asyncFunctions, (error, downloadedImagePaths=[])=> # convert image to base64 if output html if path.extname(dest) == '.html' # check cover if ebookConfig.cover cover = if ebookConfig.cover[0] == '/' then 'file:///' + ebookConfig.cover else ebookConfig.cover coverImg = document.createElement('img') coverImg.setAttribute('src', cover) div.insertBefore(coverImg, div.firstChild) imageElements = div.getElementsByTagName('img') for img in imageElements src = img.getAttribute('src') if src.startsWith('file:///') src = src.slice(8) imageType = path.extname(src).slice(1) try base64 = new Buffer(fs.readFileSync(src)).toString('base64') img.setAttribute('src', "data:image/#{imageType};charset=utf-8;base64,#{base64}") catch error throw 'Image file not found: ' + src # retrieve html outputHTML = div.innerHTML title = ebookConfig.title or 'no title' mathStyle = '' if outputHTML.indexOf('class="katex"') > 0 if path.extname(dest) == '.html' and ebookConfig.html?.cdn mathStyle = "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css\">" else mathStyle = "<link rel=\"stylesheet\" href=\"file:///#{path.resolve(__dirname, '../node_modules/katex/dist/katex.min.css')}\">" # only use github style for ebook loadPreviewTheme 'mpe-github-syntax', false, (error, css)=> css = '' if error outputHTML = """ <!DOCTYPE html> <html> <head> <title>#{title}</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> #{css} </style> #{mathStyle} </head> <body class=\"markdown-preview-enhanced\"> #{outputHTML} </body> </html> """ fileName = path.basename(dest) # save as html if path.extname(dest) == '.html' fs.writeFile dest, outputHTML, (err)=> throw err if err atom.notifications.addInfo("File #{fileName} was created", detail: "path: #{dest}") return # this func will be called later deleteDownloadedImages = ()-> downloadedImagePaths.forEach (imagePath)-> fs.unlink(imagePath) # use ebook-convert to generate ePub, mobi, PDF. temp.open prefix: 'markdown-preview-enhanced', suffix: '.html', (err, info)=> if err deleteDownloadedImages() throw err fs.write info.fd, outputHTML, (err)=> if err deleteDownloadedImages() throw err ebookConvert info.path, dest, ebookConfig, (err)=> deleteDownloadedImages() throw err if err atom.notifications.addInfo "File #{fileName} was created", detail: "path: #{dest}" pandocDocumentExport: -> {data} = @processFrontMatter(@editor.getText()) content = @editor.getText().trim() if content.startsWith('---\n') end = content.indexOf('---\n', 4) content = content.slice(end+4) pandocConvert content, {@fileDirectoryPath, @projectDirectoryPath, sourceFilePath: @editor.getPath()}, data, (err, outputFilePath)-> if err return atom.notifications.addError 'pandoc error', detail: err atom.notifications.addInfo "File #{path.basename(outputFilePath)} was created", detail: "path: #{outputFilePath}" saveAsMarkdown: ()-> {data} = @processFrontMatter(@editor.getText()) data = data or {} content = @editor.getText().trim() if content.startsWith('---\n') end = content.indexOf('---\n', 4) content = content.slice(end+4) config = data.markdown or {} if !config.image_dir config.image_dir = atom.config.get('markdown-preview-enhanced.imageFolderPath') if !config.path config.path = path.basename(@editor.getPath()).replace(/\.md$/, '_.md') if config.front_matter content = matter.stringify(content, config.front_matter) markdownConvert content, {@projectDirectoryPath, @fileDirectoryPath}, config copyToClipboard: -> return false if not @editor selection = window.getSelection() selectedText = selection.toString() atom.clipboard.write(selectedText) true # Tear down any state and detach destroy: -> @element.remove() @editor = null if @disposables @disposables.dispose() @disposables = null if @settingsDisposables @settingsDisposables.dispose() @settingsDisposables = null # clear CACHE for key of CACHE delete(CACHE[key]) @mainModule.preview = null # unbind getElement: -> @element
true
{Emitter, CompositeDisposable, File, Directory} = require 'atom' {$, $$$, ScrollView} = require 'atom-space-pen-views' path = require 'path' fs = require 'fs' temp = require('temp').track() {exec} = require 'child_process' pdf = require 'html-pdf' katex = require 'katex' matter = require('gray-matter') {allowUnsafeEval, allowUnsafeNewFunction} = require 'loophole' cheerio = null {loadPreviewTheme} = require './style' plantumlAPI = require './puml' ebookConvert = require './ebook-convert' {loadMathJax} = require './mathjax-wrapper' {pandocConvert} = require './pandoc-convert' markdownConvert = require './markdown-convert' codeChunkAPI = require './code-chunk' CACHE = require './cache' {protocolsWhiteListRegExp} = require './protocols-whitelist' module.exports = class MarkdownPreviewEnhancedView extends ScrollView constructor: (uri, mainModule)-> super @uri = uri @mainModule = mainModule @protocal = 'markdown-preview-enhanced://' @editor = null @tocConfigs = null @scrollMap = null @fileDirectoryPath = null @projectDirectoryPath = null @disposables = null @liveUpdate = true @scrollSync = true @scrollDuration = null @textChanged = false @usePandocParser = false @mathRenderingOption = atom.config.get('markdown-preview-enhanced.mathRenderingOption') @mathRenderingOption = if @mathRenderingOption == 'None' then null else @mathRenderingOption @mathJaxProcessEnvironments = atom.config.get('markdown-preview-enhanced.mathJaxProcessEnvironments') @parseDelay = Date.now() @editorScrollDelay = Date.now() @previewScrollDelay = Date.now() @documentExporterView = null # binded in markdown-preview-enhanced.coffee startMD function # this two variables will be got from './md' @parseMD = null @buildScrollMap = null @processFrontMatter = null # this variable will be got from 'viz.js' @Viz = null # this variable will check if it is the first time to render markdown @firstTimeRenderMarkdowon = true # presentation mode @presentationMode = false @slideConfigs = null # graph data used to save rendered graphs @graphData = null @codeChunksData = {} # files cache for document import @filesCache = {} # when resize the window, clear the editor window.addEventListener 'resize', @resizeEvent.bind(this) # right click event atom.commands.add @element, 'markdown-preview-enhanced:open-in-browser': => @openInBrowser() 'markdown-preview-enhanced:export-to-disk': => @exportToDisk() 'markdown-preview-enhanced:pandoc-document-export': => @pandocDocumentExport() 'markdown-preview-enhanced:save-as-markdown': => @saveAsMarkdown() 'core:copy': => @copyToClipboard() # init settings @settingsDisposables = new CompositeDisposable() @initSettingsEvents() @content: -> @div class: 'markdown-preview-enhanced native-key-bindings', tabindex: -1, style: "background-color: #fff; padding: 32px; color: #222;", => # @p style: 'font-size: 24px', 'loading preview...' @div class: "markdown-spinner", 'Loading Markdown\u2026' getTitle: -> @getFileName() + ' preview' getFileName: -> if @editor @editor.getFileName() else 'unknown' getIconName: -> 'markdown' getURI: -> @uri getProjectDirectoryPath: -> if !@editor return '' editorPath = @editor.getPath() projectDirectories = atom.project.rootDirectories for projectDirectory in projectDirectories if (projectDirectory.contains(editorPath)) # editor belongs to this project return projectDirectory.getPath() return '' setTabTitle: (title)-> tabTitle = $('[data-type="MarkdownPreviewEnhancedView"] div.title') if tabTitle.length tabTitle[0].innerText = title updateTabTitle: -> @setTabTitle(@getTitle()) setMermaidTheme: (mermaidTheme)-> mermaidThemeStyle = fs.readFileSync(path.resolve(__dirname, '../dependencies/mermaid/'+mermaidTheme), {encoding: 'utf-8'}).toString() mermaidStyle = document.getElementById('mermaid-style') if mermaidStyle mermaidStyle.remove() mermaidStyle = document.createElement('style') mermaidStyle.id = 'mermaid-style' document.getElementsByTagName('head')[0].appendChild(mermaidStyle) mermaidStyle.innerHTML = mermaidThemeStyle # render mermaid graphs again # els = @element.getElementsByClassName('mermaid') @graphData?.mermaid_s = [] @renderMarkdown() bindEditor: (editor)-> if not @editor atom.workspace .open @uri, split: 'right', activatePane: false, searchAllPanes: false .then (e)=> previewTheme = atom.config.get('markdown-preview-enhanced.previewTheme') loadPreviewTheme previewTheme, true, ()=> @initEvents(editor) else # save cache CACHE[@editor.getPath()] = { html: @element?.innerHTML or '', codeChunksData: @codeChunksData, graphData: @graphData, presentationMode: @presentationMode, slideConfigs: @slideConfigs, filesCache: @filesCache, } # @element.innerHTML = '<p style="font-size: 24px;"> loading preview... <br>type something if preview doesn\'t render :( </p>' setTimeout(()=> @initEvents(editor) , 0) initEvents: (editor)-> @editor = editor @updateTabTitle() @element.removeAttribute('style') if not @parseMD {@parseMD, @buildScrollMap, @processFrontMatter} = require './md' require '../dependencies/wavedrom/default.js' require '../dependencies/wavedrom/wavedrom.min.js' @tocConfigs = null @scrollMap = null @fileDirectoryPath = @editor.getDirectoryPath() @projectDirectoryPath = @getProjectDirectoryPath() @firstTimeRenderMarkdowon = true @filesCache = {} if @disposables # remove all binded events @disposables.dispose() @disposables = new CompositeDisposable() @initEditorEvent() @initViewEvent() # restore preview d = CACHE[@editor.getPath()] if d @element.innerHTML = d.html @graphData = d.graphData @codeChunksData = d.codeChunksData @presentationMode = d.presentationMode @slideConfigs = d.slideConfigs @filesCache = d.filesCache if @presentationMode @element.setAttribute 'data-presentation-preview-mode', '' else @element.removeAttribute 'data-presentation-preview-mode' @setInitialScrollPos() # console.log 'restore ' + @editor.getPath() # reset back to top button onclick event @element.getElementsByClassName('back-to-top-btn')?[0]?.onclick = ()=> @element.scrollTop = 0 # reset refresh button onclick event @element.getElementsByClassName('refresh-btn')?[0]?.onclick = ()=> @filesCache = {} codeChunkAPI.clearCache() @renderMarkdown() # rebind tag a click event @bindTagAClickEvent() # render plantuml in case @renderPlantUML() # reset code chunks @setupCodeChunks() else @renderMarkdown() @scrollMap = null initEditorEvent: -> editorElement = @editor.getElement() @disposables.add @editor.onDidDestroy ()=> @setTabTitle('unknown preview') if @disposables @disposables.dispose() @disposables = null @editor = null @element.onscroll = null @element.innerHTML = '<p style="font-size: 24px;"> Open a markdown file to start preview </p>' @disposables.add @editor.onDidStopChanging ()=> # @textChanged = true # this line has problem. if @liveUpdate and !@usePandocParser @updateMarkdown() @disposables.add @editor.onDidSave ()=> if not @liveUpdate or @usePandocParser @textChanged = true @updateMarkdown() @disposables.add @editor.onDidChangeModified ()=> if not @liveUpdate or @usePandocParser @textChanged = true @disposables.add editorElement.onDidChangeScrollTop ()=> if !@scrollSync or !@element or @textChanged or !@editor or @presentationMode return if Date.now() < @editorScrollDelay return editorHeight = @editor.getElement().getHeight() firstVisibleScreenRow = @editor.getFirstVisibleScreenRow() lastVisibleScreenRow = firstVisibleScreenRow + Math.floor(editorHeight / @editor.getLineHeightInPixels()) lineNo = Math.floor((firstVisibleScreenRow + lastVisibleScreenRow) / 2) @scrollMap ?= @buildScrollMap(this) # disable markdownHtmlView onscroll @previewScrollDelay = Date.now() + 500 # scroll preview to most top as editor is at most top. return @scrollToPos(0) if firstVisibleScreenRow == 0 # @element.scrollTop = @scrollMap[lineNo] - editorHeight / 2 if lineNo of @scrollMap then @scrollToPos(@scrollMap[lineNo]-editorHeight / 2) # match markdown preview to cursor position @disposables.add @editor.onDidChangeCursorPosition (event)=> if !@scrollSync or !@element or @textChanged return if Date.now() < @parseDelay return # track currnet time to disable onDidChangeScrollTop @editorScrollDelay = Date.now() + 500 # disable preview onscroll @previewScrollDelay = Date.now() + 500 if @presentationMode and @slideConfigs return @scrollSyncForPresentation(event.newBufferPosition.row) if event.oldScreenPosition.row != event.newScreenPosition.row or event.oldScreenPosition.column == 0 lineNo = event.newScreenPosition.row if lineNo <= 1 # first 2nd rows @scrollToPos(0) return else if lineNo >= @editor.getScreenLineCount() - 2 # last 2nd rows @scrollToPos(@element.scrollHeight - 16) return @scrollSyncToLineNo(lineNo) initViewEvent: -> @element.onscroll = ()=> if !@editor or !@scrollSync or @textChanged or @presentationMode return if Date.now() < @previewScrollDelay return if @element.scrollTop == 0 # most top @editorScrollDelay = Date.now() + 500 return @scrollToPos 0, @editor.getElement() top = @element.scrollTop + @element.offsetHeight / 2 # try to find corresponding screen buffer row @scrollMap ?= @buildScrollMap(this) i = 0 j = @scrollMap.length - 1 count = 0 screenRow = -1 while count < 20 if Math.abs(top - @scrollMap[i]) < 20 screenRow = i break else if Math.abs(top - @scrollMap[j]) < 20 screenRow = j break else mid = Math.floor((i + j) / 2) if top > @scrollMap[mid] i = mid else j = mid count++ if screenRow == -1 screenRow = mid @scrollToPos(screenRow * @editor.getLineHeightInPixels() - @element.offsetHeight / 2, @editor.getElement()) # @editor.getElement().setScrollTop # track currnet time to disable onDidChangeScrollTop @editorScrollDelay = Date.now() + 500 initSettingsEvents: -> # break line? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.breakOnSingleNewline', (breakOnSingleNewline)=> @parseDelay = Date.now() # <- fix 'loading preview' stuck bug @renderMarkdown() # typographer? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.enableTypographer', (enableTypographer)=> @renderMarkdown() # liveUpdate? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.liveUpdate', (flag) => @liveUpdate = flag @scrollMap = null # scroll sync? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.scrollSync', (flag) => @scrollSync = flag @scrollMap = null # scroll duration @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.scrollDuration', (duration)=> duration = parseInt(duration) or 0 if duration < 0 @scrollDuration = 120 else @scrollDuration = duration # math? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.mathRenderingOption', (option) => @mathRenderingOption = option @renderMarkdown() # pandoc parser? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.usePandocParser', (flag)=> @usePandocParser = flag @renderMarkdown() # mermaid theme @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.mermaidTheme', (theme) => @setMermaidTheme theme # hack to solve https://github.com/exupero/saveSvgAsPng/issues/128 problem # @element.setAttribute 'data-mermaid-theme', theme # render front matter as table? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.frontMatterRenderingOption', () => @renderMarkdown() # show back to top button? @settingsDisposables.add atom.config.observe 'markdown-preview-enhanced.showBackToTopButton', (flag)=> @showBackToTopButton = flag if flag @addBackToTopButton() else document.getElementsByClassName('back-to-top-btn')[0]?.remove() scrollSyncForPresentation: (bufferLineNo)-> i = @slideConfigs.length - 1 while i >= 0 if bufferLineNo >= @slideConfigs[i].line break i-=1 slideElement = @element.querySelector(".slide[data-offset=\"#{i}\"]") return if not slideElement # set slide to middle of preview @element.scrollTop = -@element.offsetHeight/2 + (slideElement.offsetTop + slideElement.offsetHeight/2)*parseFloat(slideElement.style.zoom) # lineNo here is screen buffer row. scrollSyncToLineNo: (lineNo)-> @scrollMap ?= @buildScrollMap(this) editorElement = @editor.getElement() firstVisibleScreenRow = @editor.getFirstVisibleScreenRow() posRatio = (lineNo - firstVisibleScreenRow) / (editorElement.getHeight() / @editor.getLineHeightInPixels()) scrollTop = @scrollMap[lineNo] - (if posRatio > 1 then 1 else posRatio) * editorElement.getHeight() scrollTop = 0 if scrollTop < 0 @scrollToPos scrollTop # smooth scroll @element to scrollTop # if editorElement is provided, then editorElement.setScrollTop(scrollTop) scrollToPos: (scrollTop, editorElement=null)-> if @scrollTimeout clearTimeout @scrollTimeout @scrollTimeout = null if not @editor or not @editor.alive or scrollTop < 0 return delay = 10 helper = (duration=0)=> @scrollTimeout = setTimeout => if duration <= 0 if editorElement @editorScrollDelay = Date.now() + 500 editorElement.setScrollTop scrollTop else @previewScrollDelay = Date.now() + 500 @element.scrollTop = scrollTop return if editorElement difference = scrollTop - editorElement.getScrollTop() else difference = scrollTop - @element.scrollTop perTick = difference / duration * delay if editorElement # disable editor scroll @editorScrollDelay = Date.now() + 500 s = editorElement.getScrollTop() + perTick editorElement.setScrollTop s return if s == scrollTop else # disable preview onscroll @previewScrollDelay = Date.now() + 500 @element.scrollTop += perTick return if @element.scrollTop == scrollTop helper duration-delay , delay helper(@scrollDuration) formatStringBeforeParsing: (str)-> @mainModule.hook.chain('on-will-parse-markdown', str) formatStringAfterParsing: (str)-> @mainModule.hook.chain('on-did-parse-markdown', str) updateMarkdown: -> @editorScrollDelay = Date.now() + 500 @previewScrollDelay = Date.now() + 500 @renderMarkdown() renderMarkdown: -> if Date.now() < @parseDelay or !@editor or !@element @textChanged = false return @parseDelay = Date.now() + 200 @parseMD @formatStringBeforeParsing(@editor.getText()), {isForPreview: true, markdownPreview: this, @fileDirectoryPath, @projectDirectoryPath}, ({html, slideConfigs, yamlConfig})=> html = @formatStringAfterParsing(html) if slideConfigs.length html = @parseSlides(html, slideConfigs, yamlConfig) @element.setAttribute 'data-presentation-preview-mode', '' @presentationMode = true @slideConfigs = slideConfigs else @element.removeAttribute 'data-presentation-preview-mode' @presentationMode = false @element.innerHTML = html @graphData = {} @bindEvents() @mainModule.emitter.emit 'on-did-render-preview', {htmlString: html, previewElement: @element} @setInitialScrollPos() @addBackToTopButton() @addRefreshButton() @textChanged = false setInitialScrollPos: -> if @firstTimeRenderMarkdowon @firstTimeRenderMarkdowon = false cursor = @editor.cursors[0] return if not cursor if @presentationMode @scrollSyncForPresentation cursor.getBufferRow() else t = @scrollDuration @scrollDuration = 0 @scrollSyncToLineNo cursor.getScreenRow() @scrollDuration = t addBackToTopButton: -> # TODO: check config # add back to top button #222 if @showBackToTopButton and @element.scrollHeight > @element.offsetHeight backToTopBtn = document.createElement('div') backToTopBtn.classList.add('back-to-top-btn') backToTopBtn.classList.add('btn') backToTopBtn.innerHTML = '<span>⬆︎</span>' @element.appendChild(backToTopBtn) backToTopBtn.onclick = ()=> @element.scrollTop = 0 addRefreshButton: -> refreshBtn = document.createElement('div') refreshBtn.classList.add('refresh-btn') refreshBtn.classList.add('btn') refreshBtn.innerHTML = '<span>⟳</span>' @element.appendChild(refreshBtn) refreshBtn.onclick = ()=> # clear cache @filesCache = {} codeChunkAPI.clearCache() # render again @renderMarkdown() bindEvents: -> @bindTagAClickEvent() @setupCodeChunks() @initTaskList() @renderMermaid() @renderPlantUML() @renderWavedrom() @renderViz() @renderKaTeX() @renderMathJax() @scrollMap = null # <a href="" > ... </a> click event bindTagAClickEvent: ()-> as = @element.getElementsByTagName('a') analyzeHref = (href)=> if href and href[0] == '#' targetElement = @element.querySelector("[id=\"#{href.slice(1)}\"]") # fix number id bug if targetElement a.onclick = ()=> # jump to tag position offsetTop = 0 el = targetElement while el and el != @element offsetTop += el.offsetTop el = el.offsetParent if @element.scrollTop > offsetTop @element.scrollTop = offsetTop - 32 - targetElement.offsetHeight else @element.scrollTop = offsetTop else a.onclick = ()=> return if !href return if href.match(/^(http|https)\:\/\//) # the default behavior will open browser for that url. if path.extname(href) in ['.pdf', '.xls', '.xlsx', '.doc', '.ppt', '.docx', '.pptx'] # issue #97 @openFile href else if href.match(/^file\:\/\/\//) # if href.startsWith 'file:///' openFilePath = href.slice(8) # remove protocal openFilePath = openFilePath.replace(/\.md(\s*)\#(.+)$/, '.md') # remove #anchor atom.workspace.open openFilePath, split: 'left', searchAllPanes: true else @openFile href for a in as href = a.getAttribute('href') analyzeHref(href) setupCodeChunks: ()-> codeChunks = @element.getElementsByClassName('code-chunk') return if !codeChunks.length newCodeChunksData = {} needToSetupChunksId = false setupCodeChunk = (codeChunk)=> dataArgs = codeChunk.getAttribute('data-args') idMatch = dataArgs.match(/\s*id\s*:\s*\"([^\"]*)\"/) if idMatch and idMatch[1] id = idMatch[1] codeChunk.id = 'code_chunk_' + id running = @codeChunksData[id]?.running or false codeChunk.classList.add('running') if running # remove output-div and output-element children = codeChunk.children i = children.length - 1 while i >= 0 child = children[i] if child.classList.contains('output-div') or child.classList.contains('output-element') child.remove() i -= 1 outputDiv = @codeChunksData[id]?.outputDiv outputElement = @codeChunksData[id]?.outputElement codeChunk.appendChild(outputElement) if outputElement codeChunk.appendChild(outputDiv) if outputDiv newCodeChunksData[id] = {running, outputDiv, outputElement} else # id not exist, create new id needToSetupChunksId = true runBtn = codeChunk.getElementsByClassName('run-btn')[0] runBtn?.addEventListener 'click', ()=> @runCodeChunk(codeChunk) runAllBtn = codeChunk.getElementsByClassName('run-all-btn')[0] runAllBtn?.addEventListener 'click', ()=> @runAllCodeChunks() for codeChunk in codeChunks break if needToSetupChunksId setupCodeChunk(codeChunk) if needToSetupChunksId @setupCodeChunksId() @codeChunksData = newCodeChunksData # key is codeChunkId, value is {running, outputDiv} setupCodeChunksId: ()-> buffer = @editor.buffer return if !buffer lines = buffer.lines lineNo = 0 curScreenPos = @editor.getCursorScreenPosition() while lineNo < lines.length line = lines[lineNo] match = line.match(/^\`\`\`\{(.+)\}(\s*)/) if match cmd = match[1] dataArgs = '' i = cmd.indexOf(' ') if i > 0 dataArgs = cmd.slice(i + 1, cmd.length).trim() cmd = cmd.slice(0, i) idMatch = match[1].match(/\s*id\s*:\s*\"([^\"]*)\"/) if !idMatch id = (new Date().getTime()).toString(36) line = line.trimRight() line = line.replace(/}$/, (if !dataArgs then '' else ',') + ' id:"' + id + '"}') @parseDelay = Date.now() + 500 # prevent renderMarkdown buffer.setTextInRange([[lineNo, 0], [lineNo+1, 0]], line + '\n') lineNo += 1 @editor.setCursorScreenPosition(curScreenPos) # restore cursor position. # This will cause Maximum size exceeded # @parseDelay = Date.now() # @renderMarkdown() getNearestCodeChunk: ()-> bufferRow = @editor.getCursorBufferPosition().row codeChunks = @element.getElementsByClassName('code-chunk') i = codeChunks.length - 1 while i >= 0 codeChunk = codeChunks[i] lineNo = parseInt(codeChunk.getAttribute('data-line')) if lineNo <= bufferRow return codeChunk i-=1 return null # return false if meet error # otherwise return # { # cmd, # options, # code, # id, # } parseCodeChunk: (codeChunk)-> code = codeChunk.getAttribute('data-code') dataArgs = codeChunk.getAttribute('data-args') options = null try allowUnsafeEval -> options = eval("({#{dataArgs}})") # options = JSON.parse '{'+dataArgs.replace((/([(\w)|(\-)]+)(:)/g), "\"$1\"$2").replace((/'/g), "\"")+'}' catch error atom.notifications.addError('Invalid options', detail: dataArgs) return false id = options.id # check options.continue if options.continue last = null if options.continue == true codeChunks = @element.getElementsByClassName 'code-chunk' i = codeChunks.length - 1 while i >= 0 if codeChunks[i] == codeChunk last = codeChunks[i - 1] break i-- else # id last = document.getElementById('code_chunk_' + options.continue) if last {code: lastCode, options: lastOptions} = @parseCodeChunk(last) or {} lastOptions = lastOptions or {} code = (lastCode or '') + '\n' + code options = Object.assign({}, lastOptions, options) else atom.notifications.addError('Invalid continue for code chunk ' + (options.id or ''), detail: options.continue.toString()) return false cmd = options.cmd or codeChunk.getAttribute('data-lang') # need to put here because options might be modified before return {cmd, options, code, id} runCodeChunk: (codeChunk=null)-> codeChunk = @getNearestCodeChunk() if not codeChunk return if not codeChunk return if codeChunk.classList.contains('running') parseResult = @parseCodeChunk(codeChunk) return if !parseResult {code, options, cmd, id} = parseResult if !id return atom.notifications.addError('Code chunk error', detail: 'id is not found or just updated.') codeChunk.classList.add('running') if @codeChunksData[id] @codeChunksData[id].running = true else @codeChunksData[id] = {running: true} # check options `element` if options.element outputElement = codeChunk.getElementsByClassName('output-element')?[0] if !outputElement # create and append `output-element` div outputElement = document.createElement 'div' outputElement.classList.add 'output-element' codeChunk.appendChild outputElement outputElement.innerHTML = options.element else codeChunk.getElementsByClassName('output-element')?[0]?.remove() outputElement = null codeChunkAPI.run code, @fileDirectoryPath, cmd, options, (error, data, options)=> # get new codeChunk codeChunk = document.getElementById('code_chunk_' + id) return if not codeChunk codeChunk.classList.remove('running') return if error # or !data data = (data or '').toString() outputDiv = codeChunk.getElementsByClassName('output-div')?[0] if !outputDiv outputDiv = document.createElement 'div' outputDiv.classList.add 'output-div' else outputDiv.innerHTML = '' if options.output == 'html' outputDiv.innerHTML = data else if options.output == 'png' imageElement = document.createElement 'img' imageData = Buffer(data).toString('base64') imageElement.setAttribute 'src', "data:image/png;charset=utf-8;base64,#{imageData}" outputDiv.appendChild imageElement else if options.output == 'markdown' @parseMD data, {@fileDirectoryPath, @projectDirectoryPath}, ({html})=> outputDiv.innerHTML = html @scrollMap = null else if options.output == 'none' outputDiv.remove() outputDiv = null else if data?.length preElement = document.createElement 'pre' preElement.innerText = data preElement.classList.add('editor-colors') preElement.classList.add('lang-text') outputDiv.appendChild preElement if outputDiv codeChunk.appendChild outputDiv @scrollMap = null # check matplotlib | mpl if options.matplotlib or options.mpl scriptElements = outputDiv.getElementsByTagName('script') if scriptElements.length window.d3 ?= require('../dependencies/mpld3/d3.v3.min.js') window.mpld3 ?= require('../dependencies/mpld3/mpld3.v0.3.min.js') for scriptElement in scriptElements code = scriptElement.innerHTML allowUnsafeNewFunction -> allowUnsafeEval -> eval(code) @codeChunksData[id] = {running: false, outputDiv, outputElement} runAllCodeChunks: ()-> codeChunks = @element.getElementsByClassName('code-chunk') for chunk in codeChunks @runCodeChunk(chunk) initTaskList: ()-> checkboxs = @element.getElementsByClassName('task-list-item-checkbox') for checkbox in checkboxs this_ = this checkbox.onclick = ()-> if !this_.editor return checked = this.checked buffer = this_.editor.buffer if !buffer return lineNo = parseInt(this.parentElement.getAttribute('data-line')) line = buffer.lines[lineNo] if checked line = line.replace('[ ]', '[x]') else line = line.replace(/\[(x|X)\]/, '[ ]') this_.parseDelay = Date.now() + 500 buffer.setTextInRange([[lineNo, 0], [lineNo+1, 0]], line + '\n') renderMermaid: ()-> els = @element.getElementsByClassName('mermaid mpe-graph') if els.length @graphData.mermaid_s = Array.prototype.slice.call(els) notProcessedEls = @element.querySelectorAll('.mermaid.mpe-graph:not([data-processed])') if notProcessedEls.length mermaid.init null, notProcessedEls ### # the code below doesn't seem to be working # I think mermaidAPI.render function has bug cb = (el)-> (svgGraph)-> el.innerHTML = svgGraph el.setAttribute 'data-processed', 'true' # the code below is a hackable way to solve mermaid bug el.firstChild.style.height = el.getAttribute('viewbox').split(' ')[3] + 'px' for el in els offset = parseInt(el.getAttribute('data-offset')) el.id = 'mermaid'+offset mermaidAPI.render el.id, el.getAttribute('data-original'), cb(el) ### # disable @element onscroll @previewScrollDelay = Date.now() + 500 renderWavedrom: ()-> els = @element.getElementsByClassName('wavedrom mpe-graph') if els.length @graphData.wavedrom_s = Array.prototype.slice.call(els) # WaveDrom.RenderWaveForm(0, WaveDrom.eva('a0'), 'a') for el in els if el.getAttribute('data-processed') != 'true' offset = parseInt(el.getAttribute('data-offset')) el.id = 'wavedrom'+offset text = el.getAttribute('data-original').trim() continue if not text.length allowUnsafeEval => try content = eval("(#{text})") # eval function here WaveDrom.RenderWaveForm(offset, content, 'wavedrom') el.setAttribute 'data-processed', 'true' @scrollMap = null catch error el.innerText = 'failed to eval WaveDrom code.' # disable @element onscroll @previewScrollDelay = Date.now() + 500 renderPlantUML: ()-> els = @element.getElementsByClassName('plantuml mpe-graph') if els.length @graphData.plantuml_s = Array.prototype.slice.call(els) helper = (el, text)=> plantumlAPI.render text, (outputHTML)=> el.innerHTML = outputHTML el.setAttribute 'data-processed', true @scrollMap = null for el in els if el.getAttribute('data-processed') != 'true' helper(el, el.getAttribute('data-original')) el.innerText = 'rendering graph...\n' renderViz: (element=@element)-> els = element.getElementsByClassName('viz mpe-graph') if els.length @graphData.viz_s = Array.prototype.slice.call(els) @Viz ?= require('../dependencies/viz/viz.js') for el in els if el.getAttribute('data-processed') != 'true' try content = el.getAttribute('data-original') options = {} # check engine content = content.trim().replace /^engine(\s)*[:=]([^\n]+)/, (a, b, c)-> options.engine = c.trim() if c?.trim() in ['circo', 'dot', 'fdp', 'neato', 'osage', 'twopi'] return '' el.innerHTML = @Viz(content, options) # default svg el.setAttribute 'data-processed', true catch error el.innerHTML = error renderMathJax: ()-> return if @mathRenderingOption != 'MathJax' and !@usePandocParser if typeof(MathJax) == 'undefined' return loadMathJax document, ()=> @renderMathJax() if @mathJaxProcessEnvironments or @usePandocParser return MathJax.Hub.Queue ['Typeset', MathJax.Hub, @element], ()=> @scrollMap = null els = @element.getElementsByClassName('mathjax-exps') return if !els.length unprocessedElements = [] for el in els if !el.hasAttribute('data-processed') el.setAttribute 'data-original', el.textContent unprocessedElements.push el callback = ()=> for el in unprocessedElements el.setAttribute 'data-processed', true @scrollMap = null if unprocessedElements.length == els.length MathJax.Hub.Queue ['Typeset', MathJax.Hub, @element], callback else if unprocessedElements.length MathJax.Hub.Typeset unprocessedElements, callback renderKaTeX: ()-> return if @mathRenderingOption != 'KaTeX' els = @element.getElementsByClassName('katex-exps') for el in els if el.hasAttribute('data-processed') continue else displayMode = el.hasAttribute('display-mode') dataOriginal = el.textContent try katex.render(el.textContent, el, {displayMode}) catch error el.innerHTML = "<span style=\"color: #ee7f49; font-weight: 500;\">#{error}</span>" el.setAttribute('data-processed', 'true') el.setAttribute('data-original', dataOriginal) resizeEvent: ()-> @scrollMap = null ### convert './a.txt' '/a.txt' ### resolveFilePath: (filePath='', relative=false)-> if filePath.match(protocolsWhiteListRegExp) return filePath else if filePath.startsWith('/') if relative return path.relative(@fileDirectoryPath, path.resolve(@projectDirectoryPath, '.'+filePath)) else return 'file:///'+path.resolve(@projectDirectoryPath, '.'+filePath) else if relative return filePath else return 'file:///'+path.resolve(@fileDirectoryPath, filePath) ## Utilities openInBrowser: (isForPresentationPrint=false)-> return if not @editor @getHTMLContent offline: true, isForPrint: isForPresentationPrint, (htmlContent)=> temp.open prefix: 'markdown-preview-enhanced', suffix: '.html', (err, info)=> throw err if err fs.write info.fd, htmlContent, (err)=> throw err if err if isForPresentationPrint url = 'file:///' + info.path + '?print-pdf' atom.notifications.addInfo('Please copy and open the link below in Chrome.\nThen Right Click -> Print -> Save as Pdf.', dismissable: true, detail: url) else ## open in browser @openFile info.path exportToDisk: ()-> @documentExporterView.display(this) # open html file in browser or open pdf file in reader ... etc openFile: (filePath)-> if process.platform == 'win32' cmd = 'explorer' else if process.platform == 'darwin' cmd = 'open' else cmd = 'xdg-open' exec "#{cmd} #{filePath}" ## ## {Function} callback (htmlContent) insertCodeChunksResult: (htmlContent)-> # insert outputDiv and outputElement accordingly cheerio ?= require 'cheerio' $ = cheerio.load(htmlContent, {decodeEntities: false}) codeChunks = $('.code-chunk') jsCode = '' requireCache = {} # key is path scriptsStr = "" for codeChunk in codeChunks $codeChunk = $(codeChunk) dataArgs = $codeChunk.attr('data-args').unescape() options = null try allowUnsafeEval -> options = eval("({#{dataArgs}})") catch e continue id = options.id continue if !id cmd = options.cmd or $codeChunk.attr('data-lang') code = $codeChunk.attr('data-code').unescape() outputDiv = @codeChunksData[id]?.outputDiv outputElement = @codeChunksData[id]?.outputElement if outputDiv # append outputDiv result $codeChunk.append("<div class=\"output-div\">#{outputDiv.innerHTML}</div>") if options.matplotlib or options.mpl # remove innerHTML of <div id="fig_..."></div> # this is for fixing mpld3 exporting issue. gs = $('.output-div > div', $codeChunk) if gs for g in gs $g = $(g) if $g.attr('id')?.match(/fig\_/) $g.html('') ss = $('.output-div > script', $codeChunk) if ss for s in ss $s = $(s) c = $s.html() $s.remove() jsCode += (c + '\n') if options.element $codeChunk.append("<div class=\"output-element\">#{options.element}</div>") if cmd == 'javascript' requires = options.require or [] if typeof(requires) == 'string' requires = [requires] requiresStr = "" for requirePath in requires # TODO: css if requirePath.match(/^(http|https)\:\/\//) if (!requireCache[requirePath]) requireCache[requirePath] = true scriptsStr += "<script src=\"#{requirePath}\"></script>\n" else requirePath = path.resolve(@fileDirectoryPath, requirePath) if !requireCache[requirePath] requiresStr += (fs.readFileSync(requirePath, {encoding: 'utf-8'}) + '\n') requireCache[requirePath] = true jsCode += (requiresStr + code + '\n') html = $.html() html += "#{scriptsStr}\n" if scriptsStr html += "<script data-js-code>#{jsCode}</script>" if jsCode return html ## # {Function} callback (htmlContent) getHTMLContent: ({isForPrint, offline, useRelativeImagePath, phantomjsType}, callback)-> isForPrint ?= false offline ?= false useRelativeImagePath ?= false phantomjsType ?= false # pdf | png | jpeg | false return callback() if not @editor mathRenderingOption = atom.config.get('markdown-preview-enhanced.mathRenderingOption') res = @parseMD @formatStringBeforeParsing(@editor.getText()), {useRelativeImagePath, @fileDirectoryPath, @projectDirectoryPath, markdownPreview: this, hideFrontMatter: true}, ({html, yamlConfig, slideConfigs})=> htmlContent = @formatStringAfterParsing(html) yamlConfig = yamlConfig or {} # replace code chunks inside htmlContent htmlContent = @insertCodeChunksResult htmlContent if mathRenderingOption == 'KaTeX' if offline mathStyle = "<link rel=\"stylesheet\" href=\"file:///#{path.resolve(__dirname, '../node_modules/katex/dist/katex.min.css')}\">" else mathStyle = "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css\">" else if mathRenderingOption == 'MathJax' inline = atom.config.get('markdown-preview-enhanced.indicatorForMathRenderingInline') block = atom.config.get('markdown-preview-enhanced.indicatorForMathRenderingBlock') mathJaxProcessEnvironments = atom.config.get('markdown-preview-enhanced.mathJaxProcessEnvironments') if offline mathStyle = " <script type=\"text/x-mathjax-config\"> MathJax.Hub.Config({ messageStyle: 'none', tex2jax: {inlineMath: #{inline}, displayMath: #{block}, processEnvironments: #{mathJaxProcessEnvironments}, processEscapes: true} }); </script> <script type=\"text/javascript\" async src=\"file://#{path.resolve(__dirname, '../dependencies/mathjax/MathJax.js?config=TeX-AMS_CHTML')}\"></script> " else # inlineMath: [ ['$','$'], ["\\(","\\)"] ], # displayMath: [ ['$$','$$'], ["\\[","\\]"] ] mathStyle = " <script type=\"text/x-mathjax-config\"> MathJax.Hub.Config({ messageStyle: 'none', tex2jax: {inlineMath: #{inline}, displayMath: #{block}, processEnvironments: #{mathJaxProcessEnvironments}, processEscapes: true} }); </script> <script type=\"text/javascript\" async src=\"https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML\"></script> " else mathStyle = '' # presentation if slideConfigs.length htmlContent = @parseSlidesForExport(htmlContent, slideConfigs, useRelativeImagePath) if offline presentationScript = " <script src='file:///#{path.resolve(__dirname, '../dependencies/reveal/lib/js/head.min.js')}'></script> <script src='file:///#{path.resolve(__dirname, '../dependencies/reveal/js/reveal.js')}'></script>" else presentationScript = " <script src='https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.4.1/lib/js/head.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.4.1/js/reveal.min.js'></script>" presentationConfig = yamlConfig['presentation'] or {} dependencies = presentationConfig.dependencies or [] if presentationConfig.enableSpeakerNotes if offline dependencies.push {src: path.resolve(__dirname, '../dependencies/reveal/plugin/notes/notes.js'), async: true} else dependencies.push {src: 'revealjs_deps/notes.js', async: true} # TODO: copy notes.js file to corresponding folder presentationConfig.dependencies = dependencies # <link rel=\"stylesheet\" href='file:///#{path.resolve(__dirname, '../dependencies/reveal/reveal.css')}'> presentationStyle = """ <style> #{fs.readFileSync(path.resolve(__dirname, '../dependencies/reveal/reveal.css'))} #{if isForPrint then fs.readFileSync(path.resolve(__dirname, '../dependencies/reveal/pdf.css')) else ''} </style> """ presentationInitScript = """ <script> Reveal.initialize(#{JSON.stringify(Object.assign({margin: 0.1}, presentationConfig))}) </script> """ else presentationScript = '' presentationStyle = '' presentationInitScript = '' # phantomjs phantomjsClass = "" if phantomjsType if phantomjsType == '.pdf' phantomjsClass = 'phantomjs-pdf' else if phantomjsType == '.png' or phantomjsType == '.jpeg' phantomjsClass = 'phantomjs-image' title = @getFileName() title = title.slice(0, title.length - path.extname(title).length) # remove '.md' previewTheme = atom.config.get('markdown-preview-enhanced.previewTheme') if isForPrint and atom.config.get('markdown-preview-enhanced.pdfUseGithub') previewTheme = 'mpe-github-syntax' loadPreviewTheme previewTheme, false, (error, css)=> return callback() if error return callback """ <!DOCTYPE html> <html> <head> <title>#{title}</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> #{presentationStyle} <style> #{css} </style> #{mathStyle} #{presentationScript} </head> <body class=\"markdown-preview-enhanced #{phantomjsClass}\" #{if @presentationMode then 'data-presentation-mode' else ''}> #{htmlContent} </body> #{presentationInitScript} </html> """ # api doc [printToPDF] function # https://github.com/atom/electron/blob/master/docs/api/web-contents.md printPDF: (htmlPath, dest)-> return if not @editor {BrowserWindow} = require('electron').remote win = new BrowserWindow show: false win.loadURL htmlPath # get margins type marginsType = atom.config.get('markdown-preview-enhanced.marginsType') marginsType = if marginsType == 'default margin' then 0 else if marginsType == 'no margin' then 1 else 2 # get orientation landscape = atom.config.get('markdown-preview-enhanced.orientation') == 'landscape' lastIndexOfSlash = dest.lastIndexOf '/' or 0 pdfName = dest.slice(lastIndexOfSlash + 1) win.webContents.on 'did-finish-load', ()=> setTimeout(()=> win.webContents.printToPDF pageSize: atom.config.get('markdown-preview-enhanced.exportPDFPageFormat'), landscape: landscape, printBackground: atom.config.get('markdown-preview-enhanced.printBackground'), marginsType: marginsType, (err, data)=> throw err if err destFile = new File(dest) destFile.create().then (flag)=> destFile.write data atom.notifications.addInfo "File #{pdfName} was created", detail: "path: #{dest}" # open pdf if atom.config.get('markdown-preview-enhanced.pdfOpenAutomatically') @openFile dest , 500) saveAsPDF: (dest)-> return if not @editor if @presentationMode # for presentation, need to print from chrome @openInBrowser(true) return @getHTMLContent isForPrint: true, offline: true, (htmlContent)=> temp.open prefix: 'markdown-preview-enhanced', suffix: '.html', (err, info)=> throw err if err fs.write info.fd, htmlContent, (err)=> throw err if err @printPDF "file://#{info.path}", dest saveAsHTML: (dest, offline=true, useRelativeImagePath)-> return if not @editor @getHTMLContent isForPrint: false, offline: offline, useRelativeImagePath: useRelativeImagePath, (htmlContent)=> htmlFileName = path.basename(dest) # presentation speaker notes # copy dependency files if !offline and htmlContent.indexOf('[{"src":"revealjs_deps/notes.js","async":true}]') >= 0 depsDirName = path.resolve(path.dirname(dest), 'revealjs_deps') depsDir = new Directory(depsDirName) depsDir.create().then (flag)-> true fs.createReadStream(path.resolve(__dirname, '../dependencies/reveal/plugin/notes/notes.js')).pipe(fs.createWriteStream(path.resolve(depsDirName, 'notes.js'))) fs.createReadStream(path.resolve(__dirname, '../dependencies/reveal/plugin/notes/notes.html')).pipe(fs.createWriteStream(path.resolve(depsDirName, 'notes.html'))) destFile = new File(dest) destFile.create().then (flag)-> destFile.write htmlContent atom.notifications.addInfo("File #{htmlFileName} was created", detail: "path: #{dest}") #################################################### ## Presentation ################################################## parseSlides: (html, slideConfigs, yamlConfig)-> slides = html.split '<div class="new-slide"></div>' slides = slides.slice(1) output = '' offset = 0 width = 960 height = 700 if yamlConfig and yamlConfig['presentation'] presentationConfig = yamlConfig['presentation'] width = presentationConfig['width'] or 960 height = presentationConfig['height'] or 700 ratio = height / width * 100 + '%' zoom = (@element.offsetWidth - 128)/width ## 64 is 2*padding for slide in slides # slide = slide.trim() # if slide.length slideConfig = slideConfigs[offset] styleString = '' videoString = '' iframeString = '' if slideConfig['data-background-image'] styleString += "background-image: url('#{@resolveFilePath(slideConfig['data-background-image'])}');" if slideConfig['data-background-size'] styleString += "background-size: #{slideConfig['data-background-size']};" else styleString += "background-size: cover;" if slideConfig['data-background-position'] styleString += "background-position: #{slideConfig['data-background-position']};" else styleString += "background-position: center;" if slideConfig['data-background-repeat'] styleString += "background-repeat: #{slideConfig['data-background-repeat']};" else styleString += "background-repeat: no-repeat;" else if slideConfig['data-background-color'] styleString += "background-color: #{slideConfig['data-background-color']} !important;" else if slideConfig['data-background-video'] videoMuted = slideConfig['data-background-video-muted'] videoLoop = slideConfig['data-background-video-loop'] muted_ = if videoMuted then 'muted' else '' loop_ = if videoLoop then 'loop' else '' videoString = """ <video #{muted_} #{loop_} playsinline autoplay class=\"background-video\" src=\"#{@resolveFilePath(slideConfig['data-background-video'])}\"> </video> """ # <source src=\"#{slideConfig['data-background-video']}\"> else if slideConfig['data-background-iframe'] iframeString = """ <iframe class=\"background-iframe\" src=\"#{@resolveFilePath(slideConfig['data-background-iframe'])}\" frameborder="0" > </iframe> <div class=\"background-iframe-overlay\"></div> """ output += """ <div class='slide' data-offset='#{offset}' style="width: #{width}px; height: #{height}px; zoom: #{zoom}; #{styleString}"> #{videoString} #{iframeString} <section>#{slide}</section> </div> """ offset += 1 # remove <aside class="notes"> ... </aside> output = output.replace(/(<aside\b[^>]*>)[^<>]*(<\/aside>)/ig, '') """ <div class="preview-slides"> #{output} </div> """ parseSlidesForExport: (html, slideConfigs, useRelativeImagePath)-> slides = html.split '<div class="new-slide"></div>' slides = slides.slice(1) output = '' parseAttrString = (slideConfig)=> attrString = '' if slideConfig['data-background-image'] attrString += " data-background-image='#{@resolveFilePath(slideConfig['data-background-image'], useRelativeImagePath)}'" if slideConfig['data-background-size'] attrString += " data-background-size='#{slideConfig['data-background-size']}'" if slideConfig['data-background-position'] attrString += " data-background-position='#{slideConfig['data-background-position']}'" if slideConfig['data-background-repeat'] attrString += " data-background-repeat='#{slideConfig['data-background-repeat']}'" if slideConfig['data-background-color'] attrString += " data-background-color='#{slideConfig['data-background-color']}'" if slideConfig['data-notes'] attrString += " data-notes='#{slideConfig['data-notes']}'" if slideConfig['data-background-video'] attrString += " data-background-video='#{@resolveFilePath(slideConfig['data-background-video'], useRelativeImagePath)}'" if slideConfig['data-background-video-loop'] attrString += " data-background-video-loop" if slideConfig['data-background-video-muted'] attrString += " data-background-video-muted" if slideConfig['data-transition'] attrString += " data-transition='#{slideConfig['data-transition']}'" if slideConfig['data-background-iframe'] attrString += " data-background-iframe='#{@resolveFilePath(slideConfig['data-background-iframe'], useRelativeImagePath)}'" attrString i = 0 while i < slides.length slide = slides[i] slideConfig = slideConfigs[i] attrString = parseAttrString(slideConfig) if !slideConfig['vertical'] if i > 0 and slideConfigs[i-1]['vertical'] # end of vertical slides output += '</section>' if i < slides.length - 1 and slideConfigs[i+1]['vertical'] # start of vertical slides output += "<section>" output += "<section #{attrString}>#{slide}</section>" i += 1 if i > 0 and slideConfigs[i-1]['vertical'] # end of vertical slides output += "</section>" """ <div class="reveal"> <div class="slides"> #{output} </div> </div> """ #################################################### ## PhantomJS ################################################## loadPhantomJSHeaderFooterConfig: ()-> # mermaid_config.js configPath = path.resolve(atom.config.configDirPath, './markdown-preview-enhanced/phantomjs_header_footer_config.js') try delete require.cache[require.resolve(configPath)] # return uncached return require(configPath) or {} catch error configFile = new File(configPath) configFile.create().then (flag)-> if !flag # already exists atom.notifications.addError('Failed to load phantomjs_header_footer_config.js', detail: 'there might be errors in your config file') return configFile.write """ 'use strict' /* configure header and footer (and other options) more information can be found here: https://github.com/marcbachmann/node-html-pdf Attention: this config will override your config in exporter panel. eg: let config = { "header": { "height": "45mm", "contents": '<div style="text-align: center;">Author: PI:NAME:<NAME>END_PI</div>' }, "footer": { "height": "28mm", "contents": '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>' } } */ // you can edit the 'config' variable below let config = { } module.exports = config || {} """ return {} phantomJSExport: (dest)-> return if not @editor if @presentationMode # for presentation, need to print from chrome @openInBrowser(true) return @getHTMLContent isForPrint: true, offline: true, phantomjsType: path.extname(dest), (htmlContent)=> fileType = atom.config.get('markdown-preview-enhanced.phantomJSExportFileType') format = atom.config.get('markdown-preview-enhanced.exportPDFPageFormat') orientation = atom.config.get('markdown-preview-enhanced.orientation') margin = atom.config.get('markdown-preview-enhanced.phantomJSMargin').trim() if !margin.length margin = '1cm' else margin = margin.split(',').map (m)->m.trim() if margin.length == 1 margin = margin[0] else if margin.length == 2 margin = {'top': margin[0], 'bottom': margin[0], 'left': margin[1], 'right': margin[1]} else if margin.length == 4 margin = {'top': margin[0], 'right': margin[1], 'bottom': margin[2], 'left': margin[3]} else margin = '1cm' # get header and footer config = @loadPhantomJSHeaderFooterConfig() pdf .create htmlContent, Object.assign({type: fileType, format: format, orientation: orientation, border: margin, quality: '75', timeout: 60000, script: path.join(__dirname, '../dependencies/phantomjs/pdf_a4_portrait.js')}, config) .toFile dest, (err, res)=> if err atom.notifications.addError err # open pdf else lastIndexOfSlash = dest.lastIndexOf '/' or 0 fileName = dest.slice(lastIndexOfSlash + 1) atom.notifications.addInfo "File #{fileName} was created", detail: "path: #{dest}" if atom.config.get('markdown-preview-enhanced.pdfOpenAutomatically') @openFile dest ## EBOOK generateEbook: (dest)-> @parseMD @formatStringBeforeParsing(@editor.getText()), {isForEbook: true, @fileDirectoryPath, @projectDirectoryPath, hideFrontMatter:true}, ({html, yamlConfig})=> html = @formatStringAfterParsing(html) ebookConfig = null if yamlConfig ebookConfig = yamlConfig['ebook'] if !ebookConfig return atom.notifications.addError('ebook config not found', detail: 'please insert ebook front-matter to your markdown file') else atom.notifications.addInfo('Your document is being prepared', detail: ':)') if ebookConfig.cover # change cover to absolute path if necessary cover = ebookConfig.cover if cover.startsWith('./') or cover.startsWith('../') cover = path.resolve(@fileDirectoryPath, cover) ebookConfig.cover = cover else if cover.startsWith('/') cover = path.resolve(@projectDirectoryPath, '.'+cover) ebookConfig.cover = cover div = document.createElement('div') div.innerHTML = html structure = [] # {level:0, filePath: 'path to file', heading: '', id: ''} headingOffset = 0 # load the last ul, analyze toc links. getStructure = (ul, level)-> for li in ul.children a = li.children[0]?.getElementsByTagName('a')?[0] continue if not a filePath = a.getAttribute('href') # assume markdown file path heading = a.innerHTML id = 'ebook-heading-id-'+headingOffset structure.push {level: level, filePath: filePath, heading: heading, id: id} headingOffset += 1 a.href = '#'+id # change id if li.childElementCount > 1 getStructure(li.children[1], level+1) children = div.children i = children.length - 1 while i >= 0 if children[i].tagName == 'UL' # find table of contents getStructure(children[i], 0) break i -= 1 outputHTML = div.innerHTML # append files according to structure for obj in structure heading = obj.heading id = obj.id level = obj.level filePath = obj.filePath if filePath.startsWith('file:///') filePath = filePath.slice(8) try text = fs.readFileSync(filePath, {encoding: 'utf-8'}) @parseMD @formatStringBeforeParsing(text), {isForEbook: true, projectDirectoryPath: @projectDirectoryPath, fileDirectoryPath: path.dirname(filePath)}, ({html})=> html = @formatStringAfterParsing(html) # add to TOC div.innerHTML = html if div.childElementCount div.children[0].id = id div.children[0].setAttribute('ebook-toc-level-'+(level+1), '') div.children[0].setAttribute('heading', heading) outputHTML += div.innerHTML catch error atom.notifications.addError('Ebook generation: Failed to load file', detail: filePath + '\n ' + error) return # render viz div.innerHTML = outputHTML @renderViz(div) # download images for .epub and .mobi imagesToDownload = [] if path.extname(dest) in ['.epub', '.mobi'] for img in div.getElementsByTagName('img') src = img.getAttribute('src') if src.startsWith('http://') or src.startsWith('https://') imagesToDownload.push(img) request = require('request') async = require('async') if imagesToDownload.length atom.notifications.addInfo('downloading images...') asyncFunctions = imagesToDownload.map (img)=> (callback)=> httpSrc = img.getAttribute('src') savePath = Math.random().toString(36).substr(2, 9) + '_' + path.basename(httpSrc) savePath = path.resolve(@fileDirectoryPath, savePath) stream = request(httpSrc).pipe(fs.createWriteStream(savePath)) stream.on 'finish', ()-> img.setAttribute 'src', 'file:///'+savePath callback(null, savePath) async.parallel asyncFunctions, (error, downloadedImagePaths=[])=> # convert image to base64 if output html if path.extname(dest) == '.html' # check cover if ebookConfig.cover cover = if ebookConfig.cover[0] == '/' then 'file:///' + ebookConfig.cover else ebookConfig.cover coverImg = document.createElement('img') coverImg.setAttribute('src', cover) div.insertBefore(coverImg, div.firstChild) imageElements = div.getElementsByTagName('img') for img in imageElements src = img.getAttribute('src') if src.startsWith('file:///') src = src.slice(8) imageType = path.extname(src).slice(1) try base64 = new Buffer(fs.readFileSync(src)).toString('base64') img.setAttribute('src', "data:image/#{imageType};charset=utf-8;base64,#{base64}") catch error throw 'Image file not found: ' + src # retrieve html outputHTML = div.innerHTML title = ebookConfig.title or 'no title' mathStyle = '' if outputHTML.indexOf('class="katex"') > 0 if path.extname(dest) == '.html' and ebookConfig.html?.cdn mathStyle = "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css\">" else mathStyle = "<link rel=\"stylesheet\" href=\"file:///#{path.resolve(__dirname, '../node_modules/katex/dist/katex.min.css')}\">" # only use github style for ebook loadPreviewTheme 'mpe-github-syntax', false, (error, css)=> css = '' if error outputHTML = """ <!DOCTYPE html> <html> <head> <title>#{title}</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> #{css} </style> #{mathStyle} </head> <body class=\"markdown-preview-enhanced\"> #{outputHTML} </body> </html> """ fileName = path.basename(dest) # save as html if path.extname(dest) == '.html' fs.writeFile dest, outputHTML, (err)=> throw err if err atom.notifications.addInfo("File #{fileName} was created", detail: "path: #{dest}") return # this func will be called later deleteDownloadedImages = ()-> downloadedImagePaths.forEach (imagePath)-> fs.unlink(imagePath) # use ebook-convert to generate ePub, mobi, PDF. temp.open prefix: 'markdown-preview-enhanced', suffix: '.html', (err, info)=> if err deleteDownloadedImages() throw err fs.write info.fd, outputHTML, (err)=> if err deleteDownloadedImages() throw err ebookConvert info.path, dest, ebookConfig, (err)=> deleteDownloadedImages() throw err if err atom.notifications.addInfo "File #{fileName} was created", detail: "path: #{dest}" pandocDocumentExport: -> {data} = @processFrontMatter(@editor.getText()) content = @editor.getText().trim() if content.startsWith('---\n') end = content.indexOf('---\n', 4) content = content.slice(end+4) pandocConvert content, {@fileDirectoryPath, @projectDirectoryPath, sourceFilePath: @editor.getPath()}, data, (err, outputFilePath)-> if err return atom.notifications.addError 'pandoc error', detail: err atom.notifications.addInfo "File #{path.basename(outputFilePath)} was created", detail: "path: #{outputFilePath}" saveAsMarkdown: ()-> {data} = @processFrontMatter(@editor.getText()) data = data or {} content = @editor.getText().trim() if content.startsWith('---\n') end = content.indexOf('---\n', 4) content = content.slice(end+4) config = data.markdown or {} if !config.image_dir config.image_dir = atom.config.get('markdown-preview-enhanced.imageFolderPath') if !config.path config.path = path.basename(@editor.getPath()).replace(/\.md$/, '_.md') if config.front_matter content = matter.stringify(content, config.front_matter) markdownConvert content, {@projectDirectoryPath, @fileDirectoryPath}, config copyToClipboard: -> return false if not @editor selection = window.getSelection() selectedText = selection.toString() atom.clipboard.write(selectedText) true # Tear down any state and detach destroy: -> @element.remove() @editor = null if @disposables @disposables.dispose() @disposables = null if @settingsDisposables @settingsDisposables.dispose() @settingsDisposables = null # clear CACHE for key of CACHE delete(CACHE[key]) @mainModule.preview = null # unbind getElement: -> @element
[ { "context": "esourceful.define 'widget' \n\nWidget.create name: 'FooBar'\n", "end": 128, "score": 0.5783683061599731, "start": 122, "tag": "NAME", "value": "FooBar" } ]
node_modules/ethercalc/node_modules/zappajs/node_modules/coffeecup/examples/flatiron/mvc/src/models/widget.coffee
kurakuradave/Etherboard
21
resourceful = require 'resourceful' # Widget module.exports = Widget = resourceful.define 'widget' Widget.create name: 'FooBar'
198061
resourceful = require 'resourceful' # Widget module.exports = Widget = resourceful.define 'widget' Widget.create name: '<NAME>'
true
resourceful = require 'resourceful' # Widget module.exports = Widget = resourceful.define 'widget' Widget.create name: 'PI:NAME:<NAME>END_PI'
[ { "context": "\n const me = Object.create(person);\n me.name = \"Matthew\"; // \"name\" is a property set on \"me\", but not on", "end": 1921, "score": 0.9994121789932251, "start": 1914, "tag": "NAME", "value": "Matthew" } ]
dev/intertype/src/basics.test.coffee
loveencounterflow/hengist
0
'use strict' ############################################################################################################ # njs_util = require 'util' njs_path = require 'path' # njs_fs = require 'fs' #........................................................................................................... CND = require 'cnd' rpr = CND.rpr.bind CND badge = 'INTERTYPE/tests/basics' log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge whisper = CND.get_logger 'whisper', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge praise = CND.get_logger 'praise', badge echo = CND.echo.bind CND #........................................................................................................... test = require 'guy-test' INTERTYPE = require '../../../apps/intertype' { Intertype, } = INTERTYPE { intersection_of } = require '../../../apps/intertype/lib/helpers' #----------------------------------------------------------------------------------------------------------- @[ "_prototype keys" ] = ( T ) -> isa = @ x = foo: 42 bar: 108 y = Object.create x y.bar = 'something' y.baz = 'other thing' ``` const person = { isHuman: false, printIntroduction: function () { console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`); } }; const me = Object.create(person); me.name = "Matthew"; // "name" is a property set on "me", but not on "person" me.isHuman = true; // inherited properties can be overwritten me.printIntroduction(); ``` # urge me.prototype? # urge me.__proto__? info 'µ1', rpr isa.generator_function isa.all_own_keys_of info 'µ2', rpr isa.values_of isa.all_own_keys_of 'abc' info 'µ3', rpr isa.values_of isa.all_keys_of 'abc' info 'µ4', rpr isa.values_of isa.all_keys_of x info 'µ5', rpr isa.values_of isa.all_keys_of y info 'µ5', rpr isa.values_of isa.all_keys_of y, true info 'µ6', rpr isa.values_of isa.all_keys_of me info 'µ7', rpr isa.values_of isa.all_keys_of {} info 'µ8', rpr isa.values_of isa.all_keys_of Object.create null info 'µ9', isa.keys_of me info 'µ9', rpr isa.values_of isa.keys_of me # info 'µ10', rpr ( k for k of me ) # info 'µ11', rpr Object.keys me # info 'µ12', isa.values_of isa.all_own_keys_of true # info 'µ13', isa.values_of isa.all_own_keys_of undefined # info 'µ14', isa.values_of isa.all_own_keys_of null # debug '' + rpr Object.create null # debug isa.values_of isa.all_keys_of Object:: #----------------------------------------------------------------------------------------------------------- @[ "isa" ] = ( T, done ) -> intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ "isa( 'callable', 'xxx' )", false, null, ] [ "isa( 'callable', function () {} )", true, null, ] [ "isa( 'callable', async function () { await 42 } )", true, null, ] [ "isa( 'callable', function* () { yield 42 } )", true, null, ] [ "isa( 'callable', ( function* () { yield 42 } )() )", false, null, ] [ "isa( 'date', new Date() )", true, null, ] [ "isa( 'date', true )", false, null, ] [ "isa( 'date', 'helo' )", false, null, ] [ "isa( 'date', 2 )", false, null, ] [ "isa( 'date', Date.now() )", false, null, ] [ "isa( 'finite', 123 )", true, null, ] [ "isa( 'global', global )", true, null, ] [ "isa( 'integer', 123 )", true, null, ] [ "isa( 'integer', 42 )", true, null, ] [ "isa( 'float', 123 )", true, null, ] [ "isa( 'float', 42 )", true, null, ] [ "isa( 'float', 123 )", true, null, ] [ "isa( 'float', 42 )", true, null, ] [ "isa( 'float', NaN )", false, null, ] [ "isa( 'float', NaN )", false, null, ] [ "isa( 'safeinteger', 123 )", true, null, ] [ "isa( 'text', 'x' )", true, null, ] [ "isa( 'text', NaN )", false, null, ] [ "isa.even( 42 )", true, null, ] [ "isa.finite( 123 )", true, null, ] [ "isa.integer( 123 )", true, null, ] [ "isa.integer( 42 )", true, null, ] [ "isa.weakmap( new WeakMap() )", true, null, ] [ "isa.map( new Map() )", true, null, ] [ "isa.set( new Set() )", true, null, ] [ "isa.date( new Date() )", true, null, ] [ "isa.error( new Error() )", true, null, ] [ "isa.list( [] )", true, null, ] [ "isa.boolean( true )", true, null, ] [ "isa.boolean( false )", true, null, ] [ "isa.function( ( () => {} ) )", true, null, ] [ "isa.asyncfunction( ( async () => { await f() } ) )", true, null, ] [ "isa.null( null )", true, null, ] [ "isa.text( 'helo' )", true, null, ] [ "isa.chr( ' ' )", true, null, ] [ "isa.chr( 'x' )", true, null, ] [ "isa.chr( '' )", false, null, ] [ "isa.chr( 'ab' )", false, null, ] [ "isa.chr( '𪜀' )", true, null, ] [ "isa.undefined( undefined )", true, null, ] [ "isa.global( global )", true, null, ] [ "isa.regex( /^xxx$/g )", true, null, ] [ "isa.object( {} )", true, null, ] [ "isa.nan( NaN )", true, null, ] [ "isa.infinity( 1 / 0 )", true, null, ] [ "isa.infinity( -1 / 0 )", true, null, ] [ "isa.float( 12345 )", true, null, ] [ "isa.buffer( new Buffer( 'xyz' ) )", true, null, ] [ "isa.uint8array( new Buffer( 'xyz' ) )", true, null, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = eval probe # log rpr [ probe, result, ] # resolve result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "type_of" ] = ( T, done ) -> intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ "type_of( new WeakMap() )", 'weakmap', null, ] [ "type_of( new Map() )", 'map', null, ] [ "type_of( new Set() )", 'set', null, ] [ "type_of( new Date() )", 'date', null, ] [ "type_of( new Error() )", 'error', null, ] [ "type_of( [] )", 'list', null, ] [ "type_of( true )", 'boolean', null, ] [ "type_of( false )", 'boolean', null, ] [ "type_of( ( () => {} ) )", 'function', null, ] [ "type_of( ( async () => { await f() } ) )", 'asyncfunction', null, ] [ "type_of( null )", 'null', null, ] [ "type_of( 'helo' )", 'text', null, ] [ "type_of( undefined )", 'undefined', null, ] [ "type_of( global )", 'global', null, ] [ "type_of( /^xxx$/g )", 'regex', null, ] [ "type_of( {} )", 'object', null, ] [ "type_of( NaN )", 'nan', null, ] [ "type_of( 1 / 0 )", 'infinity', null, ] [ "type_of( -1 / 0 )", 'infinity', null, ] [ "type_of( 12345 )", 'float', null, ] [ "type_of( 'xxx' )", 'text', null, ] [ "type_of( function () {} )", 'function', null, ] [ "type_of( async function () { await 42 } )", 'asyncfunction', null, ] [ "type_of( function* () { yield 42 } )", 'generatorfunction', null, ] [ "type_of( ( function* () { yield 42 } )() )", 'generator', null, ] [ "type_of( 123 )", 'float', null, ] [ "type_of( 42 )", 'float', null, ] [ "type_of( [] )", 'list', null, ] [ "type_of( global )", 'global', null, ] [ "type_of( new Date() )", 'date', null, ] [ "type_of( {} )", 'object', null, ] [ "type_of( new Buffer( 'helo' ) )", 'buffer', null, ] [ "type_of( new ArrayBuffer( 42 ) )", 'arraybuffer', null, ] [ "type_of( new Int8Array( 5 ) )", 'int8array', null, ] [ "type_of( new Uint8Array( 5 ) )", 'uint8array', null, ] [ "type_of( new Uint8ClampedArray( 5 ) )", 'uint8clampedarray', null, ] [ "type_of( new Int16Array( 5 ) )", 'int16array', null, ] [ "type_of( new Uint16Array( 5 ) )", 'uint16array', null, ] [ "type_of( new Int32Array( 5 ) )", 'int32array', null, ] [ "type_of( new Uint32Array( 5 ) )", 'uint32array', null, ] [ "type_of( new Float32Array( 5 ) )", 'float32array', null, ] [ "type_of( new Float64Array( 5 ) )", 'float64array', null, ] [ "type_of( new Promise( ( rslv, rjct ) => {} ) )", 'promise', null, ] [ "type_of( async function* () { await f(); yield 42; } )", 'asyncgeneratorfunction', null, ] [ "type_of( ( async function* () { await f(); yield 42; } )() )", 'asyncgenerator', null, ] [ "type_of( new Number( 42 ) )", "wrapper", ] [ "type_of( new String( '42' ) )", "wrapper", ] [ "type_of( new Boolean( true ) )", "wrapper", ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = eval probe # log rpr [ probe, result, ] # resolve result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate" ] = ( T, done ) -> intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ "validate( 'callable', 'xxx' )", false, 'not a valid callable', ] [ "validate( 'callable', ( function* () { yield 42 } )() )", false, 'not a valid callable', ] [ "validate( 'date', true )", false, 'not a valid date', ] [ "validate( 'date', 'helo' )", false, 'not a valid date', ] [ "validate( 'date', 2 )", false, 'not a valid date', ] [ "validate( 'date', Date.now() )", false, 'not a valid date', ] [ "validate( 'float', NaN )", false, 'not a valid float', ] [ "validate( 'float', NaN )", false, 'not a valid float', ] [ "validate( 'text', NaN )", false, 'not a valid text', ] [ "validate( 'callable', function () {} )", true, null, ] [ "validate( 'callable', async function () { await 42 } )", true, null, ] [ "validate( 'callable', function* () { yield 42 } )", true, null, ] [ "validate( 'date', new Date() )", true, null, ] [ "validate( 'finite', 123 )", true, null, ] [ "validate( 'global', global )", true, null, ] [ "validate( 'integer', 123 )", true, null, ] [ "validate( 'integer', 42 )", true, null, ] [ "validate( 'float', 123 )", true, null, ] [ "validate( 'float', 42 )", true, null, ] [ "validate( 'safeinteger', 123 )", true, null, ] [ "validate( 'text', 'x' )", true, null, ] [ "validate.even( 42 )", true, null, ] [ "validate.finite( 123 )", true, null, ] [ "validate.integer( 123 )", true, null, ] [ "validate.integer( 42 )", true, null, ] [ "validate.float( 123 )", true, null, ] [ "validate.safeinteger( 123 )", true, null, ] [ "validate.weakmap( new WeakMap() )", true, null, ] [ "validate.map( new Map() )", true, null, ] [ "validate.set( new Set() )", true, null, ] [ "validate.date( new Date() )", true, null, ] [ "validate.error( new Error() )", true, null, ] [ "validate.list( [] )", true, null, ] [ "validate.boolean( true )", true, null, ] [ "validate.boolean( false )", true, null, ] [ "validate.function( ( () => {} ) )", true, null, ] [ "validate.asyncfunction( ( async () => { await f() } ) )", true, null, ] [ "validate.null( null )", true, null, ] [ "validate.text( 'helo' )", true, null, ] [ "validate.undefined( undefined )", true, null, ] [ "validate.global( global )", true, null, ] [ "validate.regex( /^xxx$/g )", true, null, ] [ "validate.object( {} )", true, null, ] [ "validate.nan( NaN )", true, null, ] [ "validate.infinity( 1 / 0 )", true, null, ] [ "validate.infinity( -1 / 0 )", true, null, ] [ "validate.float( 12345 )", true, null, ] [ "validate.buffer( new Buffer( 'xyz' ) )", true, null, ] [ "validate.uint8array( new Buffer( 'xyz' ) )", true, null, ] [ "validate.promise( new Promise( ( rslv, rjct ) => {} ) )", true, null, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = eval probe # log rpr [ probe, result, ] # resolve result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "types_of" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... prms = new Promise ( rslv, rjct ) => return probes_and_matchers = [ [123, ["cardinal","finite","frozen","integer","nonnegative","notunset","float","float","numeric","odd","positive","safeinteger","sealed","truthy"],null] [124, ["cardinal","even","finite","frozen","integer","nonnegative","notunset","float","float","numeric","positive","safeinteger","sealed","truthy"],null] [0, ["cardinal","even","falsy","finite","frozen","integer","nonnegative","nonpositive","notunset","float","float","numeric","safeinteger","sealed","zero"],null] [true, ["boolean","frozen","notunset","sealed","truthy"],null] [null, ["falsy","frozen","null","sealed","unset"],null] [undefined, ["falsy","frozen","sealed","undefined","unset"],null] [{}, ["empty","extensible","notunset","object","truthy"],null] [[], ["empty","extensible","list","notunset","truthy"],null] [ prms, ["nativepromise","promise","thenable"], null ] ] #......................................................................................................... # debug intersection_of [ 1, 2, 3, ], [ 'a', 3, 1, ] for [ probe, matcher, error, ] in probes_and_matchers matcher = matcher.sort() await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = types_of probe result = intersection_of matcher, result # help '^334^', matcher.sort() # urge '^334^', intersection_of matcher, result # urge '^334^', result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "size_of" ] = ( T, done ) -> # debug ( new Buffer '𣁬', ), ( '𣁬'.codePointAt 0 ).toString 16 # debug ( new Buffer '𡉜', ), ( '𡉜'.codePointAt 0 ).toString 16 # debug ( new Buffer '𠑹', ), ( '𠑹'.codePointAt 0 ).toString 16 # debug ( new Buffer '𠅁', ), ( '𠅁'.codePointAt 0 ).toString 16 ### TAINT re-implement types object, pod ### # T.eq ( isa.size_of { '~isa': 'XYZ/yadda', 'foo': 42, 'bar': 108, 'baz': 3, } ), 4 #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ [ 1, 2, 3, 4, ] ], 4, null, ] [[ new Buffer [ 1, 2, 3, 4, ] ], 4, null, ] [[ '𣁬𡉜𠑹𠅁' ], 2 * ( Array.from '𣁬𡉜𠑹𠅁' ).length, null, ] [[ '𣁬𡉜𠑹𠅁', 'codepoints' ], ( Array.from '𣁬𡉜𠑹𠅁' ).length, null, ] [[ '𣁬𡉜𠑹𠅁', 'codeunits' ], 2 * ( Array.from '𣁬𡉜𠑹𠅁' ).length, null, ] [[ '𣁬𡉜𠑹𠅁', 'bytes' ], ( new Buffer '𣁬𡉜𠑹𠅁', 'utf-8' ).length, null, ] [[ 'abcdefghijklmnopqrstuvwxyz' ], 26, null, ] [[ 'abcdefghijklmnopqrstuvwxyz', 'codepoints' ], 26, null, ] [[ 'abcdefghijklmnopqrstuvwxyz', 'codeunits' ], 26, null, ] [[ 'abcdefghijklmnopqrstuvwxyz', 'bytes' ], 26, null, ] [[ 'ä' ], 1, null, ] [[ 'ä', 'codepoints' ], 1, null, ] [[ 'ä', 'codeunits' ], 1, null, ] [[ 'ä', 'bytes' ], 2, null, ] [[ new Map [ [ 'foo', 42, ], [ 'bar', 108, ], ] ], 2, null, ] [[ new Set [ 'foo', 42, 'bar', 108, ] ], 4, null, ] [[ { 'foo': 42, 'bar': 108, 'baz': 3, } ], 3, null, ] [[ { 'foo': null, 'bar': 108, 'baz': 3, } ], 3, null, ] [[ { 'foo': undefined, 'bar': 108, 'baz': 3, } ], 3, null, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers # debug 'µ22900', probe await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = size_of probe... resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "export to target" ] = ( T, done ) -> #......................................................................................................... target = {} intertype = new Intertype() return_value = intertype.export target T.ok return_value is target target.declare 'sometype', ( x ) -> ( @isa.text x ) and ( x.startsWith ':' ) # debug 'µ44333', target # debug 'µ44333', target.isa.sometype 'sometext' # debug 'µ44333', target.isa.sometype ':sometext' done() return null later = -> ### info 'µ01-47', xrpr all_keys_of [ null, ] X = {} X.x = true X.spec = {} X.spec.spec_of_X = true Y = Object.create X Y.y = true Y.spec = Object.create X.spec Y.spec.spec_of_Y = true debug X, rpr ( k for k of X ) debug X.spec, rpr ( k for k of X.spec ) debug Y, rpr ( k for k of Y ) debug Y.spec, rpr ( k for k of Y.spec ) Y.spec.spec_of_X = false info X.spec.spec_of_X info X.spec.spec_of_Y info Y.spec.spec_of_X info Y.spec.spec_of_Y ### #----------------------------------------------------------------------------------------------------------- @[ "cast" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare cast all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', 'float', 123, ], 123, ] [[ 'float', 'integer', 123, ], 123, ] [[ 'float', 'integer', 23.9, ], 24, ] [[ 'boolean', 'float', true, ], 1, ] [[ 'boolean', 'float', false, ], 0, ] [[ 'float', 'boolean', 0, ], false, ] [[ 'float', 'boolean', 1, ], true, ] [[ 'float', 'boolean', -154.7, ], true, ] [[ 'float', 'text', 123, ], '123', ] [[ 'boolean', 'text', true, ], 'true', ] [[ 'null', 'text', null, ], 'null', ] [[ 'int10text', 'text', '1245', ], '1245', ] [[ 'int16text', 'text', '1245', ], '1245', ] [[ 'int10text', 'float', '1245', ], 1245, ] [[ 'int16text', 'float', '1245', ], 4677, ] [[ 'int16text', 'int2text', '7', ], '111', ] [[ 'float', 'null', 0, ], null,'unable to cast a float as null', ] [[ 'float', 'null', 1, ], null,'unable to cast a float as null', ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers #......................................................................................................... await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type_a, type_b, x, ] = probe result = cast type_a, type_b, x resolve result return null #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type_a, type_b, x, ] = probe result = cast[ type_a ] type_b, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa_optional" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa_optional validate_optional } = intertype.export() #......................................................................................................... T.eq ( isa_optional.integer null ), true T.eq ( isa_optional.integer 1234 ), true T.eq ( isa_optional.integer '1234' ), false T.eq ( isa_optional.integer true ), false T.eq ( isa_optional.integer false ), false T.eq ( isa_optional.integer undefined ), true T.eq ( isa_optional.integer new Date() ), false T.eq ( isa_optional.integer [] ), false #......................................................................................................... try validate_optional.nonempty_text null T.ok true catch error T.fail 'testcase-434653746' #......................................................................................................... try validate_optional.nonempty_text 'yes' T.ok true catch error T.fail 'testcase-434653747' #......................................................................................................... try validate_optional.nonempty_text 12.4 T.fail 'testcase-434653748' catch error T.ok true #......................................................................................................... try validate_optional.nonempty_text false T.fail 'testcase-434653749' catch error T.ok true #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa.list_of A" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], false, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = isa.list_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa.list_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa isa_list_of validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], false, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = isa_list_of[ type ] x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa_object_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa isa_object_of validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', { x: 123, }, ], true, ] [[ 'integer', { x: 123, }, ], true, ] [[ 'integer', { x: 1, y: 2, a: 3, c: 123.5, }, ], false, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = isa_object_of[ type ] x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate.list_of A" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], null, "not a valid list_of" ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = validate.list_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate.list_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate isa_list_of validate_list_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], null, "not a valid list_of" ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = validate_list_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate.object_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate isa_object_of validate_object_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', { x: 123, }, ], true, ] [[ 'integer', { x: 123, }, ], true, ] [[ 'integer', { x: 1, y: 2, a: 3, c: 123.5, }, ], null, "not a valid object_of", ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = validate_object_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "vnr, int32" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa declare validate isa_list_of validate_list_of } = intertype.export() #......................................................................................................... T.ok isa.int32 1234 T.ok isa.int32 -1234 T.ok not isa.int32 1.3 T.ok isa.vnr [ -1234, ] T.ok isa_list_of.int32 [ -1234, ] T.ok isa_list_of.int32 [] T.ok isa.vnr [ -1234, 7e20, ] T.ok isa.vnr [ -Infinity, ] T.ok isa.vnr [ +Infinity, ] T.ok isa.vnr [ +Infinity, 1, ] T.ok isa.infloat +1234567.665553 T.ok isa.infloat -1234567.665553 T.ok isa.infloat +Infinity T.ok isa.infloat -Infinity T.ok not isa.vnr Int32Array.from [ -1234, ] done() return null #----------------------------------------------------------------------------------------------------------- @[ "check(): validation with intermediate results (experiment)" ] = ( T, done ) -> #......................................................................................................... PATH = require 'path' FS = require 'fs' intertype = new Intertype() { isa validate declare } = intertype.export() sad = Symbol 'sad' # will be made attribute of `intertype` #......................................................................................................... is_sad = ( x ) -> ( x is sad ) or ( x instanceof Error ) or ( ( isa.object x ) and ( x[ sad ] is true ) ) is_happy = ( x ) -> not is_sad x sadden = ( x ) -> { [sad]: true, _: x, } #......................................................................................................... check = new Proxy {}, get: ( t, k ) -> ( P... ) -> return fn unless isa.callable fn = t[ k ] return try ( fn P... ) catch error then error set: ( t, k, v ) -> t[ k ] = v delete: ( t, k, v ) -> delete t[ k ] check.foo = 42 check.foo check.integer = ( x ) -> validate.integer x debug '^336552^', check.integer 42 debug '^336552^', check.integer 42.5 #......................................................................................................... check_fso_exists = ( path, stats = null ) -> try ( stats ? FS.statSync path ) catch error then error #......................................................................................................... check_is_file = ( path, stats = null ) -> ### Checks if `path` exists, points to a file, is readable, and parses as a JSON file Malfunction Risks: * see `check_fso_exists()` &c. * FS-related race conditions, including * longish timeouts for paths pointing to non-local or otherwise misbehaving FS resources. ### #....................................................................................................... ### in this case, `stats` is `sad` when `check_fso_exists()` fails; in the general case, it could be any manner of object whose computation required effort, so we want to keep it; we document that fact by aliasing it as `bad`: ### return bad if is_sad ( bad = stats = check_fso_exists path, stats ) return stats if stats.isFile() return sadden "not a file: #{path}" #......................................................................................................... check_is_json_file = ( path ) -> ### Checks if `path` exists, points to a file, is readable, and is parsable as a JSON file; as a side-effect, returns the result of parsing when successful. Malfunction Risks: * see `check_is_file()` &c. * file will be read and parsed synchronously; as such, an arbitrary amount of time and space could be required in case `path` points to a large file and/or is slow to parse ### # return bad if is_sad ( bad = stats = check_is_file path, stats ) return try ( JSON.parse FS.readFileSync path ) catch error then error #......................................................................................................... debug '^377332-1^', is_sad sad debug '^377332-6^', is_sad { [sad]: true, } debug '^377332-7^', is_sad new Error "wat" debug '^377332-2^', is_sad 42 debug '^377332-3^', is_sad false debug '^377332-4^', is_sad null debug '^377332-5^', is_sad { [sad]: false, } paths = [ PATH.resolve PATH.join __dirname, '../../package.json' PATH.resolve PATH.join __dirname, '../../XXXXX' ] for path in paths R = null loop # break if ( R = check_fso_exists path, R ) is sad # break if ( R = check_is_file path, R ) is sad break if is_sad ( R = check_is_json_file path, R ) break if is_sad R then warn "fails with", ( rpr R )[ ... 80 ] else help "is JSON file; contents:", ( rpr R )[ ... 100 ] warn '^99282^', ( error = check_fso_exists 'XXXXX' ).code, CND.grey error.message warn '^99282^', ( error = check_is_file 'XXXXX' ).code, CND.grey error.message warn '^99282^', ( error = check_is_json_file 'XXXXX' ).code, CND.grey error.message #......................................................................................................... ### Turning a type declaration into a check ### check_integer = ( x ) -> return try x if ( validate.integer x ) catch error then error isa_integer = ( x ) -> is_happy check_integer x validate_integer = ( x ) -> if is_happy ( R = check_integer x ) then return R else throw R #......................................................................................................... debug '^333442^', check_integer 42 debug '^333442^', ( rpr check_integer 42.5 )[ .. 80 ] debug '^333442^', isa_integer 42 debug '^333442^', isa_integer 42.5 # debug stats # [ type, x, ] = probe # result = validate_list_of type, x # T.eq result, matcher done() return null #----------------------------------------------------------------------------------------------------------- @[ "check(): validation with intermediate results (for reals)" ] = ( T, done ) -> #......................................................................................................... PATH = require 'path' FS = require 'fs' intertype = new Intertype() { isa validate check sad is_sad is_happy sadden type_of types_of declare declare_check } = intertype.export() #......................................................................................................... declare_check 'dvsbl_2_3', ( x ) -> validate.even x return x %% 3 is 0 #......................................................................................................... T.eq ( is_happy check 'integer', 42 ), true T.eq ( is_happy check 'dvsbl_2_3', 42 ), true T.eq ( is_happy check 'dvsbl_2_3', 2 * 3 ), true T.eq ( is_happy check.integer 42 ), true T.eq ( is_happy check.dvsbl_2_3 42 ), true T.eq ( is_happy check.dvsbl_2_3 2 * 3 ), true #......................................................................................................... T.eq ( check 'dvsbl_2_3', 42 ), true T.eq ( check 'dvsbl_2_3', 2 * 3 ), true #......................................................................................................... T.eq ( check 'integer', 42 ), true T.eq ( check.integer 42 ), true #......................................................................................................... T.eq ( check.dvsbl_2_3 42 ), true T.eq ( check.dvsbl_2_3 2 * 3 ), true #......................................................................................................... T.eq ( is_happy check 'integer', 42.5 ), false T.eq ( is_happy check.integer 42.5 ), false T.eq ( is_happy check 'dvsbl_2_3', 43 ), false T.eq ( is_happy check.dvsbl_2_3 43 ), false #......................................................................................................... T.eq ( check 'integer', 42.5 ), sad T.eq ( check.integer 42.5 ), sad #......................................................................................................... T.ok isa.error ( check 'dvsbl_2_3', 43 ) T.ok isa.error ( check.dvsbl_2_3 43 ) # #......................................................................................................... # declare 'fs_stats', tests: # 'x is an object': ( x ) -> @isa.object x # 'x.size is a cardinal': ( x ) -> @isa.cardinal x.size # 'x.atimeMs is a float': ( x ) -> @isa.float x.atimeMs # 'x.atime is a date': ( x ) -> @isa.date x.atime # #......................................................................................................... # ### NOTE: will throw error unless path exists, error is implicitly caught, represents sad path ### # declare_check 'fso_exists', ( path, stats = null ) -> FS.statSync path # # try ( stats ? FS.statSync path ) catch error then error # #......................................................................................................... # declare_check 'is_file', ( path, stats = null ) -> # return bad if is_sad ( bad = stats = @check.fso_exists path, stats ) # return stats if stats.isFile() # return sadden "not a file: #{path}" # #......................................................................................................... # declare_check 'is_json_file', ( path ) -> # return try ( JSON.parse FS.readFileSync path ) catch error then error #......................................................................................................... ### overloading 'path' here, obviously ### happy_path = PATH.resolve PATH.join __dirname, '../../../package.json' sad_path = 'xxxxx' happy_fso_exists = check.fso_exists happy_path happy_is_file = check.is_file happy_path happy_is_json_file = check.is_json_file happy_path sad_fso_exists = check.fso_exists sad_path sad_is_file = check.is_file sad_path sad_is_json_file = check.is_json_file sad_path T.ok is_happy happy_fso_exists T.ok is_happy happy_is_file T.ok is_happy happy_is_json_file T.ok is_sad sad_fso_exists T.ok is_sad sad_is_file T.ok is_sad sad_is_json_file T.ok isa.fs_stats happy_fso_exists T.ok isa.fs_stats happy_is_file T.ok isa.object happy_is_json_file T.ok isa.error sad_fso_exists T.ok isa.error sad_is_file T.ok isa.error sad_is_json_file T.eq sad_fso_exists.code, 'ENOENT' T.eq sad_is_file.code, 'ENOENT' T.eq sad_is_json_file.code, 'ENOENT' #......................................................................................................... done() #----------------------------------------------------------------------------------------------------------- @[ "check(): complain on name collision" ] = ( T, done ) -> #......................................................................................................... PATH = require 'path' FS = require 'fs' intertype = new Intertype() { isa validate check sad is_sad is_happy sadden type_of types_of declare declare_check } = intertype.export() #......................................................................................................... declare_check 'dvsbl_2_3', ( x ) -> validate.even x return x %% 3 is 0 #......................................................................................................... T.throws /check 'dvsbl_2_3' already declared/, -> declare_check 'dvsbl_2_3', ( x ) -> validate.even x return x %% 3 is 0 #......................................................................................................... done() #----------------------------------------------------------------------------------------------------------- @[ "types_of() includes happy, sad" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare sad sadden all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ 123, [ 'happy', 'float', ], null, ] [ 124, [ 'happy', 'float', ], null, ] [ 0, [ 'happy', 'float', ], null, ] [ true, [ 'boolean', 'happy', ], null, ] [ null, [ 'happy', 'null', ], null, ] [ undefined, [ 'happy', 'undefined', ], null, ] [ {}, [ 'happy', 'object', ], null, ] [ [], [ 'happy', 'list', ], null, ] [ sad, [ 'sad', 'symbol', ], null, ] [ new Error(), [ 'error', 'sad', ], null, ] [ { [sad]: true, _: null, }, [ 'object', 'sad', 'saddened', ], null, ] [ ( sadden null ), [ 'object', 'sad', 'saddened', ], null, ] ] #......................................................................................................... # debug intersection_of [ 1, 2, 3, ], [ 'a', 3, 1, ] for [ probe, matcher, error, ] in probes_and_matchers matcher.sort() await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = intersection_of matcher, types_of probe # log rpr [ probe, result, ] # resolve result resolve result return null #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "unsadden" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare sad sadden unsadden all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ { [sad]: true, _: null, }, null, null, ] [ ( sadden 129282 ), 129282, null, ] [ 333, 333, null, ] [ sad, null, "not a valid saddened", ] [ ( new Error() ), null, "not a valid saddened", ] ] #......................................................................................................... # debug intersection_of [ 1, 2, 3, ], [ 'a', 3, 1, ] for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> resolve unsadden probe return null #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa.immediate, nowait" ] = ( T, done ) -> intertype = new Intertype() { isa types_of type_of validate nowait } = intertype.export() #......................................................................................................... try T.ok 'immediate' not in ( types_of new Promise -> ) catch error then T.fail 'testcase-171615' try T.ok 'immediate' not in ( types_of { then: -> } ) catch error then T.fail 'testcase-171616' try T.ok 'immediate' in ( types_of 42 ) catch error then T.fail 'testcase-171617' #......................................................................................................... try T.eq ( isa.immediate null ), true catch error then T.fail 'testcase-171618' try T.eq ( isa.immediate 12.34 ), true catch error then T.fail 'testcase-171619' try T.eq ( isa.immediate undefined ), true catch error then T.fail 'testcase-171620' try T.eq ( isa.immediate new Promise -> ), false catch error then T.fail 'testcase-171621' #......................................................................................................... try ( validate.immediate 42 ) catch error then T.fail 'testcase-171622' try ( validate.immediate undefined ) catch error then T.fail 'testcase-171623' try ( validate.immediate null ) catch error then T.fail 'testcase-171624' try ( validate.immediate 1 * '#' ) catch error then T.fail 'testcase-171625' #......................................................................................................... T.throws /not a valid immediate/, -> validate.immediate x = ( new Promise -> ) # validate.immediate x = ( new Promise -> ) try ( r = nowait ( ( x ) -> x ** 2 ) 5 ) catch error then T.fail 'testcase-171626' T.eq r, 25 T.throws /not a valid immediate/, -> r = nowait ( -> new Promise -> )() done() # #----------------------------------------------------------------------------------------------------------- # @[ "equality checks" ] = ( T, done ) -> # ### TAINT bug: when this test runs as only one, no problem; when run after some of the above, # `equals` check throws error `Error: ENOENT: no such file or directory, open 'equals'` (!!!) ### # intertype = new Intertype() # { isa # check } = intertype.export() # urge '^8873^', rpr ( k for k of intertype.export() ) # debug '^22231^', check.equals 3, 3 # debug '^22231^', check.equals 3, 4 # done() if done? #----------------------------------------------------------------------------------------------------------- @[ "equals" ] = ( T, done ) -> intertype = new Intertype() { isa check equals } = intertype.export() ### TAINT copy more extensive tests from CND, `js_eq`? ### re = /expected at least 2 arguments/ try equals 3 catch error warn error.message if re.test error.message then T.ok true else T.fail "expected error #{rpr re}, got #{rpr error.message}" T.fail "expected error, got none" unless error? T.eq ( equals 3, 3 ), true T.eq ( equals 3, 4 ), false T.eq ( equals ( new Map [ [ 1, 2, ], ]), ( new Map [ [ 1, 2, ], ]) ), true T.eq ( equals ( new Set [ [ 1, 2, ], ]), ( new Set [ [ 1, 2, ], ]) ), true T.eq ( equals ( new Map [ [ 1, 2, ], ]), ( new Map [ [ 1, 3, ], ]) ), false T.eq ( equals ( new Set [ [ 1, 2, ], ]), ( new Set [ [ 1, 3, ], ]) ), false done() if done? #----------------------------------------------------------------------------------------------------------- @[ "numerical types" ] = ( T, done ) -> intertype = new Intertype() { isa type_of check equals } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ 'nan', [ 23, false ], ] [ 'finite', [ 23, true ], ] [ 'integer', [ 23, true ], ] [ 'safeinteger', [ 23, true ], ] [ 'numeric', [ 23, true ], ] [ 'even', [ 23, false ], ] [ 'odd', [ 23, true ], ] [ 'cardinal', [ 23, true ], ] [ 'nonnegative', [ 23, true ], ] [ 'positive', [ 23, true ], ] [ 'positive_integer', [ 23, true ], ] [ 'negative_integer', [ 23, false ], ] [ 'zero', [ 23, false ], ] [ 'infinity', [ 23, false ], ] [ 'infloat', [ 23, true ], ] [ 'nonpositive', [ 23, false ], ] [ 'negative', [ 23, false ], ] [ 'positive_float', [ 23, true ], ] [ 'negative_float', [ 23, false ], ] ] #......................................................................................................... error = null for [ type, pairs..., ] in probes_and_matchers for [ value, matcher, ] in pairs probe = [ type, value, ] await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> resolve isa[ type ] value return null #......................................................................................................... done() if done? # type_of 1e32 ), 'float' # [ 'float', [ 23, false ], ] #----------------------------------------------------------------------------------------------------------- @[ "real-life example 1" ] = ( T, done ) -> types = new Intertype() { isa type_of types_of validate check equals } = types.export() #......................................................................................................... types.declare 'intershop_rpc_settings', tests: "x is a object": ( x ) -> @isa.object x "x.host is a nonempty_text": ( x ) -> @isa.nonempty_text x.host "x.port is a cardinal": ( x ) -> @isa.cardinal x.port "x.show_counts is a boolean": ( x ) -> @isa.boolean x.show_counts "x.count_interval is a positive_integer": ( x ) -> @isa.positive_integer x.count_interval "x.socket_log_all is a boolean": ( x ) -> @isa.boolean x.socket_log_all "x.socketserver_log_all is a boolean": ( x ) -> @isa.boolean x.socketserver_log_all "x.logging is a boolean or a function": ( x ) -> ( @isa.boolean x.logging ) or ( @isa.function x.logging ) #......................................................................................................... _defaults = Object.freeze host: 'localhost' port: 23001 show_counts: true count_interval: 1000 socket_log_all: false socketserver_log_all: false logging: true #......................................................................................................... debug types_of _defaults.count_interval T.ok isa.intershop_rpc_settings _defaults done() # [ 'float', [ 23, false ], ] #----------------------------------------------------------------------------------------------------------- @[ "real-life example 2" ] = ( T, done ) -> types = new Intertype() { isa declare type_of types_of validate check equals } = types.export() #......................................................................................................... declare 'intershop_cli_psql_run_selector', tests: "x is a nonempty_text": ( x ) -> @isa.nonempty_text x "x must be '-c' or '-f'": ( x ) -> x in [ '-c', '-f', ] #......................................................................................................... # debug types_of '-c' # debug types_of '-x' T.eq ( isa.intershop_cli_psql_run_selector '-f' ), true T.eq ( isa.intershop_cli_psql_run_selector '-c' ), true T.eq ( isa.intershop_cli_psql_run_selector 'xxx' ), false T.eq ( isa.intershop_cli_psql_run_selector '' ), false try validate.intershop_cli_psql_run_selector '-f' T.ok true catch error T.fail error.message try validate.some_unknown_type '-f' T.fail "expected an error, but statement passed" catch error T.ok /violates.*is a known type/.test error.message done() ############################################################################################################ unless module.parent? test @ # test @[ "check(): complain on name collision" ] # @[ "check(): complain on name collision" ]() # test @[ "size_of" ] # test @[ "numerical types" ] # test @[ "real-life example 2" ] # test @[ "equals" ] # @[ "equality checks" ]() # test @[ "isa.immediate, nowait" ] # test @[ "types_of() includes happy, sad" ] # @[ "types_of() includes happy, sad" ]() # test @[ "check(): validation with intermediate results (experiment)" ] # test @[ "check(): validation with intermediate results (for reals)" ] # test @[ "types_of" ] # test @[ "vnr, int32" ] # test @[ "cast" ] # test @[ "isa.list_of A" ] # test @[ "isa.list_of B" ] # test @[ "isa_object_of B" ] # test @[ "validate.object_of B" ] # test @[ "validate.list_of A" ] # test @[ "validate.list_of B" ]
5018
'use strict' ############################################################################################################ # njs_util = require 'util' njs_path = require 'path' # njs_fs = require 'fs' #........................................................................................................... CND = require 'cnd' rpr = CND.rpr.bind CND badge = 'INTERTYPE/tests/basics' log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge whisper = CND.get_logger 'whisper', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge praise = CND.get_logger 'praise', badge echo = CND.echo.bind CND #........................................................................................................... test = require 'guy-test' INTERTYPE = require '../../../apps/intertype' { Intertype, } = INTERTYPE { intersection_of } = require '../../../apps/intertype/lib/helpers' #----------------------------------------------------------------------------------------------------------- @[ "_prototype keys" ] = ( T ) -> isa = @ x = foo: 42 bar: 108 y = Object.create x y.bar = 'something' y.baz = 'other thing' ``` const person = { isHuman: false, printIntroduction: function () { console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`); } }; const me = Object.create(person); me.name = "<NAME>"; // "name" is a property set on "me", but not on "person" me.isHuman = true; // inherited properties can be overwritten me.printIntroduction(); ``` # urge me.prototype? # urge me.__proto__? info 'µ1', rpr isa.generator_function isa.all_own_keys_of info 'µ2', rpr isa.values_of isa.all_own_keys_of 'abc' info 'µ3', rpr isa.values_of isa.all_keys_of 'abc' info 'µ4', rpr isa.values_of isa.all_keys_of x info 'µ5', rpr isa.values_of isa.all_keys_of y info 'µ5', rpr isa.values_of isa.all_keys_of y, true info 'µ6', rpr isa.values_of isa.all_keys_of me info 'µ7', rpr isa.values_of isa.all_keys_of {} info 'µ8', rpr isa.values_of isa.all_keys_of Object.create null info 'µ9', isa.keys_of me info 'µ9', rpr isa.values_of isa.keys_of me # info 'µ10', rpr ( k for k of me ) # info 'µ11', rpr Object.keys me # info 'µ12', isa.values_of isa.all_own_keys_of true # info 'µ13', isa.values_of isa.all_own_keys_of undefined # info 'µ14', isa.values_of isa.all_own_keys_of null # debug '' + rpr Object.create null # debug isa.values_of isa.all_keys_of Object:: #----------------------------------------------------------------------------------------------------------- @[ "isa" ] = ( T, done ) -> intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ "isa( 'callable', 'xxx' )", false, null, ] [ "isa( 'callable', function () {} )", true, null, ] [ "isa( 'callable', async function () { await 42 } )", true, null, ] [ "isa( 'callable', function* () { yield 42 } )", true, null, ] [ "isa( 'callable', ( function* () { yield 42 } )() )", false, null, ] [ "isa( 'date', new Date() )", true, null, ] [ "isa( 'date', true )", false, null, ] [ "isa( 'date', 'helo' )", false, null, ] [ "isa( 'date', 2 )", false, null, ] [ "isa( 'date', Date.now() )", false, null, ] [ "isa( 'finite', 123 )", true, null, ] [ "isa( 'global', global )", true, null, ] [ "isa( 'integer', 123 )", true, null, ] [ "isa( 'integer', 42 )", true, null, ] [ "isa( 'float', 123 )", true, null, ] [ "isa( 'float', 42 )", true, null, ] [ "isa( 'float', 123 )", true, null, ] [ "isa( 'float', 42 )", true, null, ] [ "isa( 'float', NaN )", false, null, ] [ "isa( 'float', NaN )", false, null, ] [ "isa( 'safeinteger', 123 )", true, null, ] [ "isa( 'text', 'x' )", true, null, ] [ "isa( 'text', NaN )", false, null, ] [ "isa.even( 42 )", true, null, ] [ "isa.finite( 123 )", true, null, ] [ "isa.integer( 123 )", true, null, ] [ "isa.integer( 42 )", true, null, ] [ "isa.weakmap( new WeakMap() )", true, null, ] [ "isa.map( new Map() )", true, null, ] [ "isa.set( new Set() )", true, null, ] [ "isa.date( new Date() )", true, null, ] [ "isa.error( new Error() )", true, null, ] [ "isa.list( [] )", true, null, ] [ "isa.boolean( true )", true, null, ] [ "isa.boolean( false )", true, null, ] [ "isa.function( ( () => {} ) )", true, null, ] [ "isa.asyncfunction( ( async () => { await f() } ) )", true, null, ] [ "isa.null( null )", true, null, ] [ "isa.text( 'helo' )", true, null, ] [ "isa.chr( ' ' )", true, null, ] [ "isa.chr( 'x' )", true, null, ] [ "isa.chr( '' )", false, null, ] [ "isa.chr( 'ab' )", false, null, ] [ "isa.chr( '𪜀' )", true, null, ] [ "isa.undefined( undefined )", true, null, ] [ "isa.global( global )", true, null, ] [ "isa.regex( /^xxx$/g )", true, null, ] [ "isa.object( {} )", true, null, ] [ "isa.nan( NaN )", true, null, ] [ "isa.infinity( 1 / 0 )", true, null, ] [ "isa.infinity( -1 / 0 )", true, null, ] [ "isa.float( 12345 )", true, null, ] [ "isa.buffer( new Buffer( 'xyz' ) )", true, null, ] [ "isa.uint8array( new Buffer( 'xyz' ) )", true, null, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = eval probe # log rpr [ probe, result, ] # resolve result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "type_of" ] = ( T, done ) -> intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ "type_of( new WeakMap() )", 'weakmap', null, ] [ "type_of( new Map() )", 'map', null, ] [ "type_of( new Set() )", 'set', null, ] [ "type_of( new Date() )", 'date', null, ] [ "type_of( new Error() )", 'error', null, ] [ "type_of( [] )", 'list', null, ] [ "type_of( true )", 'boolean', null, ] [ "type_of( false )", 'boolean', null, ] [ "type_of( ( () => {} ) )", 'function', null, ] [ "type_of( ( async () => { await f() } ) )", 'asyncfunction', null, ] [ "type_of( null )", 'null', null, ] [ "type_of( 'helo' )", 'text', null, ] [ "type_of( undefined )", 'undefined', null, ] [ "type_of( global )", 'global', null, ] [ "type_of( /^xxx$/g )", 'regex', null, ] [ "type_of( {} )", 'object', null, ] [ "type_of( NaN )", 'nan', null, ] [ "type_of( 1 / 0 )", 'infinity', null, ] [ "type_of( -1 / 0 )", 'infinity', null, ] [ "type_of( 12345 )", 'float', null, ] [ "type_of( 'xxx' )", 'text', null, ] [ "type_of( function () {} )", 'function', null, ] [ "type_of( async function () { await 42 } )", 'asyncfunction', null, ] [ "type_of( function* () { yield 42 } )", 'generatorfunction', null, ] [ "type_of( ( function* () { yield 42 } )() )", 'generator', null, ] [ "type_of( 123 )", 'float', null, ] [ "type_of( 42 )", 'float', null, ] [ "type_of( [] )", 'list', null, ] [ "type_of( global )", 'global', null, ] [ "type_of( new Date() )", 'date', null, ] [ "type_of( {} )", 'object', null, ] [ "type_of( new Buffer( 'helo' ) )", 'buffer', null, ] [ "type_of( new ArrayBuffer( 42 ) )", 'arraybuffer', null, ] [ "type_of( new Int8Array( 5 ) )", 'int8array', null, ] [ "type_of( new Uint8Array( 5 ) )", 'uint8array', null, ] [ "type_of( new Uint8ClampedArray( 5 ) )", 'uint8clampedarray', null, ] [ "type_of( new Int16Array( 5 ) )", 'int16array', null, ] [ "type_of( new Uint16Array( 5 ) )", 'uint16array', null, ] [ "type_of( new Int32Array( 5 ) )", 'int32array', null, ] [ "type_of( new Uint32Array( 5 ) )", 'uint32array', null, ] [ "type_of( new Float32Array( 5 ) )", 'float32array', null, ] [ "type_of( new Float64Array( 5 ) )", 'float64array', null, ] [ "type_of( new Promise( ( rslv, rjct ) => {} ) )", 'promise', null, ] [ "type_of( async function* () { await f(); yield 42; } )", 'asyncgeneratorfunction', null, ] [ "type_of( ( async function* () { await f(); yield 42; } )() )", 'asyncgenerator', null, ] [ "type_of( new Number( 42 ) )", "wrapper", ] [ "type_of( new String( '42' ) )", "wrapper", ] [ "type_of( new Boolean( true ) )", "wrapper", ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = eval probe # log rpr [ probe, result, ] # resolve result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate" ] = ( T, done ) -> intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ "validate( 'callable', 'xxx' )", false, 'not a valid callable', ] [ "validate( 'callable', ( function* () { yield 42 } )() )", false, 'not a valid callable', ] [ "validate( 'date', true )", false, 'not a valid date', ] [ "validate( 'date', 'helo' )", false, 'not a valid date', ] [ "validate( 'date', 2 )", false, 'not a valid date', ] [ "validate( 'date', Date.now() )", false, 'not a valid date', ] [ "validate( 'float', NaN )", false, 'not a valid float', ] [ "validate( 'float', NaN )", false, 'not a valid float', ] [ "validate( 'text', NaN )", false, 'not a valid text', ] [ "validate( 'callable', function () {} )", true, null, ] [ "validate( 'callable', async function () { await 42 } )", true, null, ] [ "validate( 'callable', function* () { yield 42 } )", true, null, ] [ "validate( 'date', new Date() )", true, null, ] [ "validate( 'finite', 123 )", true, null, ] [ "validate( 'global', global )", true, null, ] [ "validate( 'integer', 123 )", true, null, ] [ "validate( 'integer', 42 )", true, null, ] [ "validate( 'float', 123 )", true, null, ] [ "validate( 'float', 42 )", true, null, ] [ "validate( 'safeinteger', 123 )", true, null, ] [ "validate( 'text', 'x' )", true, null, ] [ "validate.even( 42 )", true, null, ] [ "validate.finite( 123 )", true, null, ] [ "validate.integer( 123 )", true, null, ] [ "validate.integer( 42 )", true, null, ] [ "validate.float( 123 )", true, null, ] [ "validate.safeinteger( 123 )", true, null, ] [ "validate.weakmap( new WeakMap() )", true, null, ] [ "validate.map( new Map() )", true, null, ] [ "validate.set( new Set() )", true, null, ] [ "validate.date( new Date() )", true, null, ] [ "validate.error( new Error() )", true, null, ] [ "validate.list( [] )", true, null, ] [ "validate.boolean( true )", true, null, ] [ "validate.boolean( false )", true, null, ] [ "validate.function( ( () => {} ) )", true, null, ] [ "validate.asyncfunction( ( async () => { await f() } ) )", true, null, ] [ "validate.null( null )", true, null, ] [ "validate.text( 'helo' )", true, null, ] [ "validate.undefined( undefined )", true, null, ] [ "validate.global( global )", true, null, ] [ "validate.regex( /^xxx$/g )", true, null, ] [ "validate.object( {} )", true, null, ] [ "validate.nan( NaN )", true, null, ] [ "validate.infinity( 1 / 0 )", true, null, ] [ "validate.infinity( -1 / 0 )", true, null, ] [ "validate.float( 12345 )", true, null, ] [ "validate.buffer( new Buffer( 'xyz' ) )", true, null, ] [ "validate.uint8array( new Buffer( 'xyz' ) )", true, null, ] [ "validate.promise( new Promise( ( rslv, rjct ) => {} ) )", true, null, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = eval probe # log rpr [ probe, result, ] # resolve result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "types_of" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... prms = new Promise ( rslv, rjct ) => return probes_and_matchers = [ [123, ["cardinal","finite","frozen","integer","nonnegative","notunset","float","float","numeric","odd","positive","safeinteger","sealed","truthy"],null] [124, ["cardinal","even","finite","frozen","integer","nonnegative","notunset","float","float","numeric","positive","safeinteger","sealed","truthy"],null] [0, ["cardinal","even","falsy","finite","frozen","integer","nonnegative","nonpositive","notunset","float","float","numeric","safeinteger","sealed","zero"],null] [true, ["boolean","frozen","notunset","sealed","truthy"],null] [null, ["falsy","frozen","null","sealed","unset"],null] [undefined, ["falsy","frozen","sealed","undefined","unset"],null] [{}, ["empty","extensible","notunset","object","truthy"],null] [[], ["empty","extensible","list","notunset","truthy"],null] [ prms, ["nativepromise","promise","thenable"], null ] ] #......................................................................................................... # debug intersection_of [ 1, 2, 3, ], [ 'a', 3, 1, ] for [ probe, matcher, error, ] in probes_and_matchers matcher = matcher.sort() await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = types_of probe result = intersection_of matcher, result # help '^334^', matcher.sort() # urge '^334^', intersection_of matcher, result # urge '^334^', result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "size_of" ] = ( T, done ) -> # debug ( new Buffer '𣁬', ), ( '𣁬'.codePointAt 0 ).toString 16 # debug ( new Buffer '𡉜', ), ( '𡉜'.codePointAt 0 ).toString 16 # debug ( new Buffer '𠑹', ), ( '𠑹'.codePointAt 0 ).toString 16 # debug ( new Buffer '𠅁', ), ( '𠅁'.codePointAt 0 ).toString 16 ### TAINT re-implement types object, pod ### # T.eq ( isa.size_of { '~isa': 'XYZ/yadda', 'foo': 42, 'bar': 108, 'baz': 3, } ), 4 #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ [ 1, 2, 3, 4, ] ], 4, null, ] [[ new Buffer [ 1, 2, 3, 4, ] ], 4, null, ] [[ '𣁬𡉜𠑹𠅁' ], 2 * ( Array.from '𣁬𡉜𠑹𠅁' ).length, null, ] [[ '𣁬𡉜𠑹𠅁', 'codepoints' ], ( Array.from '𣁬𡉜𠑹𠅁' ).length, null, ] [[ '𣁬𡉜𠑹𠅁', 'codeunits' ], 2 * ( Array.from '𣁬𡉜𠑹𠅁' ).length, null, ] [[ '𣁬𡉜𠑹𠅁', 'bytes' ], ( new Buffer '𣁬𡉜𠑹𠅁', 'utf-8' ).length, null, ] [[ 'abcdefghijklmnopqrstuvwxyz' ], 26, null, ] [[ 'abcdefghijklmnopqrstuvwxyz', 'codepoints' ], 26, null, ] [[ 'abcdefghijklmnopqrstuvwxyz', 'codeunits' ], 26, null, ] [[ 'abcdefghijklmnopqrstuvwxyz', 'bytes' ], 26, null, ] [[ 'ä' ], 1, null, ] [[ 'ä', 'codepoints' ], 1, null, ] [[ 'ä', 'codeunits' ], 1, null, ] [[ 'ä', 'bytes' ], 2, null, ] [[ new Map [ [ 'foo', 42, ], [ 'bar', 108, ], ] ], 2, null, ] [[ new Set [ 'foo', 42, 'bar', 108, ] ], 4, null, ] [[ { 'foo': 42, 'bar': 108, 'baz': 3, } ], 3, null, ] [[ { 'foo': null, 'bar': 108, 'baz': 3, } ], 3, null, ] [[ { 'foo': undefined, 'bar': 108, 'baz': 3, } ], 3, null, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers # debug 'µ22900', probe await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = size_of probe... resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "export to target" ] = ( T, done ) -> #......................................................................................................... target = {} intertype = new Intertype() return_value = intertype.export target T.ok return_value is target target.declare 'sometype', ( x ) -> ( @isa.text x ) and ( x.startsWith ':' ) # debug 'µ44333', target # debug 'µ44333', target.isa.sometype 'sometext' # debug 'µ44333', target.isa.sometype ':sometext' done() return null later = -> ### info 'µ01-47', xrpr all_keys_of [ null, ] X = {} X.x = true X.spec = {} X.spec.spec_of_X = true Y = Object.create X Y.y = true Y.spec = Object.create X.spec Y.spec.spec_of_Y = true debug X, rpr ( k for k of X ) debug X.spec, rpr ( k for k of X.spec ) debug Y, rpr ( k for k of Y ) debug Y.spec, rpr ( k for k of Y.spec ) Y.spec.spec_of_X = false info X.spec.spec_of_X info X.spec.spec_of_Y info Y.spec.spec_of_X info Y.spec.spec_of_Y ### #----------------------------------------------------------------------------------------------------------- @[ "cast" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare cast all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', 'float', 123, ], 123, ] [[ 'float', 'integer', 123, ], 123, ] [[ 'float', 'integer', 23.9, ], 24, ] [[ 'boolean', 'float', true, ], 1, ] [[ 'boolean', 'float', false, ], 0, ] [[ 'float', 'boolean', 0, ], false, ] [[ 'float', 'boolean', 1, ], true, ] [[ 'float', 'boolean', -154.7, ], true, ] [[ 'float', 'text', 123, ], '123', ] [[ 'boolean', 'text', true, ], 'true', ] [[ 'null', 'text', null, ], 'null', ] [[ 'int10text', 'text', '1245', ], '1245', ] [[ 'int16text', 'text', '1245', ], '1245', ] [[ 'int10text', 'float', '1245', ], 1245, ] [[ 'int16text', 'float', '1245', ], 4677, ] [[ 'int16text', 'int2text', '7', ], '111', ] [[ 'float', 'null', 0, ], null,'unable to cast a float as null', ] [[ 'float', 'null', 1, ], null,'unable to cast a float as null', ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers #......................................................................................................... await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type_a, type_b, x, ] = probe result = cast type_a, type_b, x resolve result return null #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type_a, type_b, x, ] = probe result = cast[ type_a ] type_b, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa_optional" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa_optional validate_optional } = intertype.export() #......................................................................................................... T.eq ( isa_optional.integer null ), true T.eq ( isa_optional.integer 1234 ), true T.eq ( isa_optional.integer '1234' ), false T.eq ( isa_optional.integer true ), false T.eq ( isa_optional.integer false ), false T.eq ( isa_optional.integer undefined ), true T.eq ( isa_optional.integer new Date() ), false T.eq ( isa_optional.integer [] ), false #......................................................................................................... try validate_optional.nonempty_text null T.ok true catch error T.fail 'testcase-434653746' #......................................................................................................... try validate_optional.nonempty_text 'yes' T.ok true catch error T.fail 'testcase-434653747' #......................................................................................................... try validate_optional.nonempty_text 12.4 T.fail 'testcase-434653748' catch error T.ok true #......................................................................................................... try validate_optional.nonempty_text false T.fail 'testcase-434653749' catch error T.ok true #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa.list_of A" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], false, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = isa.list_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa.list_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa isa_list_of validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], false, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = isa_list_of[ type ] x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa_object_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa isa_object_of validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', { x: 123, }, ], true, ] [[ 'integer', { x: 123, }, ], true, ] [[ 'integer', { x: 1, y: 2, a: 3, c: 123.5, }, ], false, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = isa_object_of[ type ] x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate.list_of A" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], null, "not a valid list_of" ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = validate.list_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate.list_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate isa_list_of validate_list_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], null, "not a valid list_of" ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = validate_list_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate.object_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate isa_object_of validate_object_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', { x: 123, }, ], true, ] [[ 'integer', { x: 123, }, ], true, ] [[ 'integer', { x: 1, y: 2, a: 3, c: 123.5, }, ], null, "not a valid object_of", ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = validate_object_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "vnr, int32" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa declare validate isa_list_of validate_list_of } = intertype.export() #......................................................................................................... T.ok isa.int32 1234 T.ok isa.int32 -1234 T.ok not isa.int32 1.3 T.ok isa.vnr [ -1234, ] T.ok isa_list_of.int32 [ -1234, ] T.ok isa_list_of.int32 [] T.ok isa.vnr [ -1234, 7e20, ] T.ok isa.vnr [ -Infinity, ] T.ok isa.vnr [ +Infinity, ] T.ok isa.vnr [ +Infinity, 1, ] T.ok isa.infloat +1234567.665553 T.ok isa.infloat -1234567.665553 T.ok isa.infloat +Infinity T.ok isa.infloat -Infinity T.ok not isa.vnr Int32Array.from [ -1234, ] done() return null #----------------------------------------------------------------------------------------------------------- @[ "check(): validation with intermediate results (experiment)" ] = ( T, done ) -> #......................................................................................................... PATH = require 'path' FS = require 'fs' intertype = new Intertype() { isa validate declare } = intertype.export() sad = Symbol 'sad' # will be made attribute of `intertype` #......................................................................................................... is_sad = ( x ) -> ( x is sad ) or ( x instanceof Error ) or ( ( isa.object x ) and ( x[ sad ] is true ) ) is_happy = ( x ) -> not is_sad x sadden = ( x ) -> { [sad]: true, _: x, } #......................................................................................................... check = new Proxy {}, get: ( t, k ) -> ( P... ) -> return fn unless isa.callable fn = t[ k ] return try ( fn P... ) catch error then error set: ( t, k, v ) -> t[ k ] = v delete: ( t, k, v ) -> delete t[ k ] check.foo = 42 check.foo check.integer = ( x ) -> validate.integer x debug '^336552^', check.integer 42 debug '^336552^', check.integer 42.5 #......................................................................................................... check_fso_exists = ( path, stats = null ) -> try ( stats ? FS.statSync path ) catch error then error #......................................................................................................... check_is_file = ( path, stats = null ) -> ### Checks if `path` exists, points to a file, is readable, and parses as a JSON file Malfunction Risks: * see `check_fso_exists()` &c. * FS-related race conditions, including * longish timeouts for paths pointing to non-local or otherwise misbehaving FS resources. ### #....................................................................................................... ### in this case, `stats` is `sad` when `check_fso_exists()` fails; in the general case, it could be any manner of object whose computation required effort, so we want to keep it; we document that fact by aliasing it as `bad`: ### return bad if is_sad ( bad = stats = check_fso_exists path, stats ) return stats if stats.isFile() return sadden "not a file: #{path}" #......................................................................................................... check_is_json_file = ( path ) -> ### Checks if `path` exists, points to a file, is readable, and is parsable as a JSON file; as a side-effect, returns the result of parsing when successful. Malfunction Risks: * see `check_is_file()` &c. * file will be read and parsed synchronously; as such, an arbitrary amount of time and space could be required in case `path` points to a large file and/or is slow to parse ### # return bad if is_sad ( bad = stats = check_is_file path, stats ) return try ( JSON.parse FS.readFileSync path ) catch error then error #......................................................................................................... debug '^377332-1^', is_sad sad debug '^377332-6^', is_sad { [sad]: true, } debug '^377332-7^', is_sad new Error "wat" debug '^377332-2^', is_sad 42 debug '^377332-3^', is_sad false debug '^377332-4^', is_sad null debug '^377332-5^', is_sad { [sad]: false, } paths = [ PATH.resolve PATH.join __dirname, '../../package.json' PATH.resolve PATH.join __dirname, '../../XXXXX' ] for path in paths R = null loop # break if ( R = check_fso_exists path, R ) is sad # break if ( R = check_is_file path, R ) is sad break if is_sad ( R = check_is_json_file path, R ) break if is_sad R then warn "fails with", ( rpr R )[ ... 80 ] else help "is JSON file; contents:", ( rpr R )[ ... 100 ] warn '^99282^', ( error = check_fso_exists 'XXXXX' ).code, CND.grey error.message warn '^99282^', ( error = check_is_file 'XXXXX' ).code, CND.grey error.message warn '^99282^', ( error = check_is_json_file 'XXXXX' ).code, CND.grey error.message #......................................................................................................... ### Turning a type declaration into a check ### check_integer = ( x ) -> return try x if ( validate.integer x ) catch error then error isa_integer = ( x ) -> is_happy check_integer x validate_integer = ( x ) -> if is_happy ( R = check_integer x ) then return R else throw R #......................................................................................................... debug '^333442^', check_integer 42 debug '^333442^', ( rpr check_integer 42.5 )[ .. 80 ] debug '^333442^', isa_integer 42 debug '^333442^', isa_integer 42.5 # debug stats # [ type, x, ] = probe # result = validate_list_of type, x # T.eq result, matcher done() return null #----------------------------------------------------------------------------------------------------------- @[ "check(): validation with intermediate results (for reals)" ] = ( T, done ) -> #......................................................................................................... PATH = require 'path' FS = require 'fs' intertype = new Intertype() { isa validate check sad is_sad is_happy sadden type_of types_of declare declare_check } = intertype.export() #......................................................................................................... declare_check 'dvsbl_2_3', ( x ) -> validate.even x return x %% 3 is 0 #......................................................................................................... T.eq ( is_happy check 'integer', 42 ), true T.eq ( is_happy check 'dvsbl_2_3', 42 ), true T.eq ( is_happy check 'dvsbl_2_3', 2 * 3 ), true T.eq ( is_happy check.integer 42 ), true T.eq ( is_happy check.dvsbl_2_3 42 ), true T.eq ( is_happy check.dvsbl_2_3 2 * 3 ), true #......................................................................................................... T.eq ( check 'dvsbl_2_3', 42 ), true T.eq ( check 'dvsbl_2_3', 2 * 3 ), true #......................................................................................................... T.eq ( check 'integer', 42 ), true T.eq ( check.integer 42 ), true #......................................................................................................... T.eq ( check.dvsbl_2_3 42 ), true T.eq ( check.dvsbl_2_3 2 * 3 ), true #......................................................................................................... T.eq ( is_happy check 'integer', 42.5 ), false T.eq ( is_happy check.integer 42.5 ), false T.eq ( is_happy check 'dvsbl_2_3', 43 ), false T.eq ( is_happy check.dvsbl_2_3 43 ), false #......................................................................................................... T.eq ( check 'integer', 42.5 ), sad T.eq ( check.integer 42.5 ), sad #......................................................................................................... T.ok isa.error ( check 'dvsbl_2_3', 43 ) T.ok isa.error ( check.dvsbl_2_3 43 ) # #......................................................................................................... # declare 'fs_stats', tests: # 'x is an object': ( x ) -> @isa.object x # 'x.size is a cardinal': ( x ) -> @isa.cardinal x.size # 'x.atimeMs is a float': ( x ) -> @isa.float x.atimeMs # 'x.atime is a date': ( x ) -> @isa.date x.atime # #......................................................................................................... # ### NOTE: will throw error unless path exists, error is implicitly caught, represents sad path ### # declare_check 'fso_exists', ( path, stats = null ) -> FS.statSync path # # try ( stats ? FS.statSync path ) catch error then error # #......................................................................................................... # declare_check 'is_file', ( path, stats = null ) -> # return bad if is_sad ( bad = stats = @check.fso_exists path, stats ) # return stats if stats.isFile() # return sadden "not a file: #{path}" # #......................................................................................................... # declare_check 'is_json_file', ( path ) -> # return try ( JSON.parse FS.readFileSync path ) catch error then error #......................................................................................................... ### overloading 'path' here, obviously ### happy_path = PATH.resolve PATH.join __dirname, '../../../package.json' sad_path = 'xxxxx' happy_fso_exists = check.fso_exists happy_path happy_is_file = check.is_file happy_path happy_is_json_file = check.is_json_file happy_path sad_fso_exists = check.fso_exists sad_path sad_is_file = check.is_file sad_path sad_is_json_file = check.is_json_file sad_path T.ok is_happy happy_fso_exists T.ok is_happy happy_is_file T.ok is_happy happy_is_json_file T.ok is_sad sad_fso_exists T.ok is_sad sad_is_file T.ok is_sad sad_is_json_file T.ok isa.fs_stats happy_fso_exists T.ok isa.fs_stats happy_is_file T.ok isa.object happy_is_json_file T.ok isa.error sad_fso_exists T.ok isa.error sad_is_file T.ok isa.error sad_is_json_file T.eq sad_fso_exists.code, 'ENOENT' T.eq sad_is_file.code, 'ENOENT' T.eq sad_is_json_file.code, 'ENOENT' #......................................................................................................... done() #----------------------------------------------------------------------------------------------------------- @[ "check(): complain on name collision" ] = ( T, done ) -> #......................................................................................................... PATH = require 'path' FS = require 'fs' intertype = new Intertype() { isa validate check sad is_sad is_happy sadden type_of types_of declare declare_check } = intertype.export() #......................................................................................................... declare_check 'dvsbl_2_3', ( x ) -> validate.even x return x %% 3 is 0 #......................................................................................................... T.throws /check 'dvsbl_2_3' already declared/, -> declare_check 'dvsbl_2_3', ( x ) -> validate.even x return x %% 3 is 0 #......................................................................................................... done() #----------------------------------------------------------------------------------------------------------- @[ "types_of() includes happy, sad" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare sad sadden all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ 123, [ 'happy', 'float', ], null, ] [ 124, [ 'happy', 'float', ], null, ] [ 0, [ 'happy', 'float', ], null, ] [ true, [ 'boolean', 'happy', ], null, ] [ null, [ 'happy', 'null', ], null, ] [ undefined, [ 'happy', 'undefined', ], null, ] [ {}, [ 'happy', 'object', ], null, ] [ [], [ 'happy', 'list', ], null, ] [ sad, [ 'sad', 'symbol', ], null, ] [ new Error(), [ 'error', 'sad', ], null, ] [ { [sad]: true, _: null, }, [ 'object', 'sad', 'saddened', ], null, ] [ ( sadden null ), [ 'object', 'sad', 'saddened', ], null, ] ] #......................................................................................................... # debug intersection_of [ 1, 2, 3, ], [ 'a', 3, 1, ] for [ probe, matcher, error, ] in probes_and_matchers matcher.sort() await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = intersection_of matcher, types_of probe # log rpr [ probe, result, ] # resolve result resolve result return null #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "unsadden" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare sad sadden unsadden all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ { [sad]: true, _: null, }, null, null, ] [ ( sadden 129282 ), 129282, null, ] [ 333, 333, null, ] [ sad, null, "not a valid saddened", ] [ ( new Error() ), null, "not a valid saddened", ] ] #......................................................................................................... # debug intersection_of [ 1, 2, 3, ], [ 'a', 3, 1, ] for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> resolve unsadden probe return null #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa.immediate, nowait" ] = ( T, done ) -> intertype = new Intertype() { isa types_of type_of validate nowait } = intertype.export() #......................................................................................................... try T.ok 'immediate' not in ( types_of new Promise -> ) catch error then T.fail 'testcase-171615' try T.ok 'immediate' not in ( types_of { then: -> } ) catch error then T.fail 'testcase-171616' try T.ok 'immediate' in ( types_of 42 ) catch error then T.fail 'testcase-171617' #......................................................................................................... try T.eq ( isa.immediate null ), true catch error then T.fail 'testcase-171618' try T.eq ( isa.immediate 12.34 ), true catch error then T.fail 'testcase-171619' try T.eq ( isa.immediate undefined ), true catch error then T.fail 'testcase-171620' try T.eq ( isa.immediate new Promise -> ), false catch error then T.fail 'testcase-171621' #......................................................................................................... try ( validate.immediate 42 ) catch error then T.fail 'testcase-171622' try ( validate.immediate undefined ) catch error then T.fail 'testcase-171623' try ( validate.immediate null ) catch error then T.fail 'testcase-171624' try ( validate.immediate 1 * '#' ) catch error then T.fail 'testcase-171625' #......................................................................................................... T.throws /not a valid immediate/, -> validate.immediate x = ( new Promise -> ) # validate.immediate x = ( new Promise -> ) try ( r = nowait ( ( x ) -> x ** 2 ) 5 ) catch error then T.fail 'testcase-171626' T.eq r, 25 T.throws /not a valid immediate/, -> r = nowait ( -> new Promise -> )() done() # #----------------------------------------------------------------------------------------------------------- # @[ "equality checks" ] = ( T, done ) -> # ### TAINT bug: when this test runs as only one, no problem; when run after some of the above, # `equals` check throws error `Error: ENOENT: no such file or directory, open 'equals'` (!!!) ### # intertype = new Intertype() # { isa # check } = intertype.export() # urge '^8873^', rpr ( k for k of intertype.export() ) # debug '^22231^', check.equals 3, 3 # debug '^22231^', check.equals 3, 4 # done() if done? #----------------------------------------------------------------------------------------------------------- @[ "equals" ] = ( T, done ) -> intertype = new Intertype() { isa check equals } = intertype.export() ### TAINT copy more extensive tests from CND, `js_eq`? ### re = /expected at least 2 arguments/ try equals 3 catch error warn error.message if re.test error.message then T.ok true else T.fail "expected error #{rpr re}, got #{rpr error.message}" T.fail "expected error, got none" unless error? T.eq ( equals 3, 3 ), true T.eq ( equals 3, 4 ), false T.eq ( equals ( new Map [ [ 1, 2, ], ]), ( new Map [ [ 1, 2, ], ]) ), true T.eq ( equals ( new Set [ [ 1, 2, ], ]), ( new Set [ [ 1, 2, ], ]) ), true T.eq ( equals ( new Map [ [ 1, 2, ], ]), ( new Map [ [ 1, 3, ], ]) ), false T.eq ( equals ( new Set [ [ 1, 2, ], ]), ( new Set [ [ 1, 3, ], ]) ), false done() if done? #----------------------------------------------------------------------------------------------------------- @[ "numerical types" ] = ( T, done ) -> intertype = new Intertype() { isa type_of check equals } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ 'nan', [ 23, false ], ] [ 'finite', [ 23, true ], ] [ 'integer', [ 23, true ], ] [ 'safeinteger', [ 23, true ], ] [ 'numeric', [ 23, true ], ] [ 'even', [ 23, false ], ] [ 'odd', [ 23, true ], ] [ 'cardinal', [ 23, true ], ] [ 'nonnegative', [ 23, true ], ] [ 'positive', [ 23, true ], ] [ 'positive_integer', [ 23, true ], ] [ 'negative_integer', [ 23, false ], ] [ 'zero', [ 23, false ], ] [ 'infinity', [ 23, false ], ] [ 'infloat', [ 23, true ], ] [ 'nonpositive', [ 23, false ], ] [ 'negative', [ 23, false ], ] [ 'positive_float', [ 23, true ], ] [ 'negative_float', [ 23, false ], ] ] #......................................................................................................... error = null for [ type, pairs..., ] in probes_and_matchers for [ value, matcher, ] in pairs probe = [ type, value, ] await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> resolve isa[ type ] value return null #......................................................................................................... done() if done? # type_of 1e32 ), 'float' # [ 'float', [ 23, false ], ] #----------------------------------------------------------------------------------------------------------- @[ "real-life example 1" ] = ( T, done ) -> types = new Intertype() { isa type_of types_of validate check equals } = types.export() #......................................................................................................... types.declare 'intershop_rpc_settings', tests: "x is a object": ( x ) -> @isa.object x "x.host is a nonempty_text": ( x ) -> @isa.nonempty_text x.host "x.port is a cardinal": ( x ) -> @isa.cardinal x.port "x.show_counts is a boolean": ( x ) -> @isa.boolean x.show_counts "x.count_interval is a positive_integer": ( x ) -> @isa.positive_integer x.count_interval "x.socket_log_all is a boolean": ( x ) -> @isa.boolean x.socket_log_all "x.socketserver_log_all is a boolean": ( x ) -> @isa.boolean x.socketserver_log_all "x.logging is a boolean or a function": ( x ) -> ( @isa.boolean x.logging ) or ( @isa.function x.logging ) #......................................................................................................... _defaults = Object.freeze host: 'localhost' port: 23001 show_counts: true count_interval: 1000 socket_log_all: false socketserver_log_all: false logging: true #......................................................................................................... debug types_of _defaults.count_interval T.ok isa.intershop_rpc_settings _defaults done() # [ 'float', [ 23, false ], ] #----------------------------------------------------------------------------------------------------------- @[ "real-life example 2" ] = ( T, done ) -> types = new Intertype() { isa declare type_of types_of validate check equals } = types.export() #......................................................................................................... declare 'intershop_cli_psql_run_selector', tests: "x is a nonempty_text": ( x ) -> @isa.nonempty_text x "x must be '-c' or '-f'": ( x ) -> x in [ '-c', '-f', ] #......................................................................................................... # debug types_of '-c' # debug types_of '-x' T.eq ( isa.intershop_cli_psql_run_selector '-f' ), true T.eq ( isa.intershop_cli_psql_run_selector '-c' ), true T.eq ( isa.intershop_cli_psql_run_selector 'xxx' ), false T.eq ( isa.intershop_cli_psql_run_selector '' ), false try validate.intershop_cli_psql_run_selector '-f' T.ok true catch error T.fail error.message try validate.some_unknown_type '-f' T.fail "expected an error, but statement passed" catch error T.ok /violates.*is a known type/.test error.message done() ############################################################################################################ unless module.parent? test @ # test @[ "check(): complain on name collision" ] # @[ "check(): complain on name collision" ]() # test @[ "size_of" ] # test @[ "numerical types" ] # test @[ "real-life example 2" ] # test @[ "equals" ] # @[ "equality checks" ]() # test @[ "isa.immediate, nowait" ] # test @[ "types_of() includes happy, sad" ] # @[ "types_of() includes happy, sad" ]() # test @[ "check(): validation with intermediate results (experiment)" ] # test @[ "check(): validation with intermediate results (for reals)" ] # test @[ "types_of" ] # test @[ "vnr, int32" ] # test @[ "cast" ] # test @[ "isa.list_of A" ] # test @[ "isa.list_of B" ] # test @[ "isa_object_of B" ] # test @[ "validate.object_of B" ] # test @[ "validate.list_of A" ] # test @[ "validate.list_of B" ]
true
'use strict' ############################################################################################################ # njs_util = require 'util' njs_path = require 'path' # njs_fs = require 'fs' #........................................................................................................... CND = require 'cnd' rpr = CND.rpr.bind CND badge = 'INTERTYPE/tests/basics' log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge whisper = CND.get_logger 'whisper', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge praise = CND.get_logger 'praise', badge echo = CND.echo.bind CND #........................................................................................................... test = require 'guy-test' INTERTYPE = require '../../../apps/intertype' { Intertype, } = INTERTYPE { intersection_of } = require '../../../apps/intertype/lib/helpers' #----------------------------------------------------------------------------------------------------------- @[ "_prototype keys" ] = ( T ) -> isa = @ x = foo: 42 bar: 108 y = Object.create x y.bar = 'something' y.baz = 'other thing' ``` const person = { isHuman: false, printIntroduction: function () { console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`); } }; const me = Object.create(person); me.name = "PI:NAME:<NAME>END_PI"; // "name" is a property set on "me", but not on "person" me.isHuman = true; // inherited properties can be overwritten me.printIntroduction(); ``` # urge me.prototype? # urge me.__proto__? info 'µ1', rpr isa.generator_function isa.all_own_keys_of info 'µ2', rpr isa.values_of isa.all_own_keys_of 'abc' info 'µ3', rpr isa.values_of isa.all_keys_of 'abc' info 'µ4', rpr isa.values_of isa.all_keys_of x info 'µ5', rpr isa.values_of isa.all_keys_of y info 'µ5', rpr isa.values_of isa.all_keys_of y, true info 'µ6', rpr isa.values_of isa.all_keys_of me info 'µ7', rpr isa.values_of isa.all_keys_of {} info 'µ8', rpr isa.values_of isa.all_keys_of Object.create null info 'µ9', isa.keys_of me info 'µ9', rpr isa.values_of isa.keys_of me # info 'µ10', rpr ( k for k of me ) # info 'µ11', rpr Object.keys me # info 'µ12', isa.values_of isa.all_own_keys_of true # info 'µ13', isa.values_of isa.all_own_keys_of undefined # info 'µ14', isa.values_of isa.all_own_keys_of null # debug '' + rpr Object.create null # debug isa.values_of isa.all_keys_of Object:: #----------------------------------------------------------------------------------------------------------- @[ "isa" ] = ( T, done ) -> intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ "isa( 'callable', 'xxx' )", false, null, ] [ "isa( 'callable', function () {} )", true, null, ] [ "isa( 'callable', async function () { await 42 } )", true, null, ] [ "isa( 'callable', function* () { yield 42 } )", true, null, ] [ "isa( 'callable', ( function* () { yield 42 } )() )", false, null, ] [ "isa( 'date', new Date() )", true, null, ] [ "isa( 'date', true )", false, null, ] [ "isa( 'date', 'helo' )", false, null, ] [ "isa( 'date', 2 )", false, null, ] [ "isa( 'date', Date.now() )", false, null, ] [ "isa( 'finite', 123 )", true, null, ] [ "isa( 'global', global )", true, null, ] [ "isa( 'integer', 123 )", true, null, ] [ "isa( 'integer', 42 )", true, null, ] [ "isa( 'float', 123 )", true, null, ] [ "isa( 'float', 42 )", true, null, ] [ "isa( 'float', 123 )", true, null, ] [ "isa( 'float', 42 )", true, null, ] [ "isa( 'float', NaN )", false, null, ] [ "isa( 'float', NaN )", false, null, ] [ "isa( 'safeinteger', 123 )", true, null, ] [ "isa( 'text', 'x' )", true, null, ] [ "isa( 'text', NaN )", false, null, ] [ "isa.even( 42 )", true, null, ] [ "isa.finite( 123 )", true, null, ] [ "isa.integer( 123 )", true, null, ] [ "isa.integer( 42 )", true, null, ] [ "isa.weakmap( new WeakMap() )", true, null, ] [ "isa.map( new Map() )", true, null, ] [ "isa.set( new Set() )", true, null, ] [ "isa.date( new Date() )", true, null, ] [ "isa.error( new Error() )", true, null, ] [ "isa.list( [] )", true, null, ] [ "isa.boolean( true )", true, null, ] [ "isa.boolean( false )", true, null, ] [ "isa.function( ( () => {} ) )", true, null, ] [ "isa.asyncfunction( ( async () => { await f() } ) )", true, null, ] [ "isa.null( null )", true, null, ] [ "isa.text( 'helo' )", true, null, ] [ "isa.chr( ' ' )", true, null, ] [ "isa.chr( 'x' )", true, null, ] [ "isa.chr( '' )", false, null, ] [ "isa.chr( 'ab' )", false, null, ] [ "isa.chr( '𪜀' )", true, null, ] [ "isa.undefined( undefined )", true, null, ] [ "isa.global( global )", true, null, ] [ "isa.regex( /^xxx$/g )", true, null, ] [ "isa.object( {} )", true, null, ] [ "isa.nan( NaN )", true, null, ] [ "isa.infinity( 1 / 0 )", true, null, ] [ "isa.infinity( -1 / 0 )", true, null, ] [ "isa.float( 12345 )", true, null, ] [ "isa.buffer( new Buffer( 'xyz' ) )", true, null, ] [ "isa.uint8array( new Buffer( 'xyz' ) )", true, null, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = eval probe # log rpr [ probe, result, ] # resolve result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "type_of" ] = ( T, done ) -> intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ "type_of( new WeakMap() )", 'weakmap', null, ] [ "type_of( new Map() )", 'map', null, ] [ "type_of( new Set() )", 'set', null, ] [ "type_of( new Date() )", 'date', null, ] [ "type_of( new Error() )", 'error', null, ] [ "type_of( [] )", 'list', null, ] [ "type_of( true )", 'boolean', null, ] [ "type_of( false )", 'boolean', null, ] [ "type_of( ( () => {} ) )", 'function', null, ] [ "type_of( ( async () => { await f() } ) )", 'asyncfunction', null, ] [ "type_of( null )", 'null', null, ] [ "type_of( 'helo' )", 'text', null, ] [ "type_of( undefined )", 'undefined', null, ] [ "type_of( global )", 'global', null, ] [ "type_of( /^xxx$/g )", 'regex', null, ] [ "type_of( {} )", 'object', null, ] [ "type_of( NaN )", 'nan', null, ] [ "type_of( 1 / 0 )", 'infinity', null, ] [ "type_of( -1 / 0 )", 'infinity', null, ] [ "type_of( 12345 )", 'float', null, ] [ "type_of( 'xxx' )", 'text', null, ] [ "type_of( function () {} )", 'function', null, ] [ "type_of( async function () { await 42 } )", 'asyncfunction', null, ] [ "type_of( function* () { yield 42 } )", 'generatorfunction', null, ] [ "type_of( ( function* () { yield 42 } )() )", 'generator', null, ] [ "type_of( 123 )", 'float', null, ] [ "type_of( 42 )", 'float', null, ] [ "type_of( [] )", 'list', null, ] [ "type_of( global )", 'global', null, ] [ "type_of( new Date() )", 'date', null, ] [ "type_of( {} )", 'object', null, ] [ "type_of( new Buffer( 'helo' ) )", 'buffer', null, ] [ "type_of( new ArrayBuffer( 42 ) )", 'arraybuffer', null, ] [ "type_of( new Int8Array( 5 ) )", 'int8array', null, ] [ "type_of( new Uint8Array( 5 ) )", 'uint8array', null, ] [ "type_of( new Uint8ClampedArray( 5 ) )", 'uint8clampedarray', null, ] [ "type_of( new Int16Array( 5 ) )", 'int16array', null, ] [ "type_of( new Uint16Array( 5 ) )", 'uint16array', null, ] [ "type_of( new Int32Array( 5 ) )", 'int32array', null, ] [ "type_of( new Uint32Array( 5 ) )", 'uint32array', null, ] [ "type_of( new Float32Array( 5 ) )", 'float32array', null, ] [ "type_of( new Float64Array( 5 ) )", 'float64array', null, ] [ "type_of( new Promise( ( rslv, rjct ) => {} ) )", 'promise', null, ] [ "type_of( async function* () { await f(); yield 42; } )", 'asyncgeneratorfunction', null, ] [ "type_of( ( async function* () { await f(); yield 42; } )() )", 'asyncgenerator', null, ] [ "type_of( new Number( 42 ) )", "wrapper", ] [ "type_of( new String( '42' ) )", "wrapper", ] [ "type_of( new Boolean( true ) )", "wrapper", ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = eval probe # log rpr [ probe, result, ] # resolve result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate" ] = ( T, done ) -> intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ "validate( 'callable', 'xxx' )", false, 'not a valid callable', ] [ "validate( 'callable', ( function* () { yield 42 } )() )", false, 'not a valid callable', ] [ "validate( 'date', true )", false, 'not a valid date', ] [ "validate( 'date', 'helo' )", false, 'not a valid date', ] [ "validate( 'date', 2 )", false, 'not a valid date', ] [ "validate( 'date', Date.now() )", false, 'not a valid date', ] [ "validate( 'float', NaN )", false, 'not a valid float', ] [ "validate( 'float', NaN )", false, 'not a valid float', ] [ "validate( 'text', NaN )", false, 'not a valid text', ] [ "validate( 'callable', function () {} )", true, null, ] [ "validate( 'callable', async function () { await 42 } )", true, null, ] [ "validate( 'callable', function* () { yield 42 } )", true, null, ] [ "validate( 'date', new Date() )", true, null, ] [ "validate( 'finite', 123 )", true, null, ] [ "validate( 'global', global )", true, null, ] [ "validate( 'integer', 123 )", true, null, ] [ "validate( 'integer', 42 )", true, null, ] [ "validate( 'float', 123 )", true, null, ] [ "validate( 'float', 42 )", true, null, ] [ "validate( 'safeinteger', 123 )", true, null, ] [ "validate( 'text', 'x' )", true, null, ] [ "validate.even( 42 )", true, null, ] [ "validate.finite( 123 )", true, null, ] [ "validate.integer( 123 )", true, null, ] [ "validate.integer( 42 )", true, null, ] [ "validate.float( 123 )", true, null, ] [ "validate.safeinteger( 123 )", true, null, ] [ "validate.weakmap( new WeakMap() )", true, null, ] [ "validate.map( new Map() )", true, null, ] [ "validate.set( new Set() )", true, null, ] [ "validate.date( new Date() )", true, null, ] [ "validate.error( new Error() )", true, null, ] [ "validate.list( [] )", true, null, ] [ "validate.boolean( true )", true, null, ] [ "validate.boolean( false )", true, null, ] [ "validate.function( ( () => {} ) )", true, null, ] [ "validate.asyncfunction( ( async () => { await f() } ) )", true, null, ] [ "validate.null( null )", true, null, ] [ "validate.text( 'helo' )", true, null, ] [ "validate.undefined( undefined )", true, null, ] [ "validate.global( global )", true, null, ] [ "validate.regex( /^xxx$/g )", true, null, ] [ "validate.object( {} )", true, null, ] [ "validate.nan( NaN )", true, null, ] [ "validate.infinity( 1 / 0 )", true, null, ] [ "validate.infinity( -1 / 0 )", true, null, ] [ "validate.float( 12345 )", true, null, ] [ "validate.buffer( new Buffer( 'xyz' ) )", true, null, ] [ "validate.uint8array( new Buffer( 'xyz' ) )", true, null, ] [ "validate.promise( new Promise( ( rslv, rjct ) => {} ) )", true, null, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = eval probe # log rpr [ probe, result, ] # resolve result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "types_of" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... prms = new Promise ( rslv, rjct ) => return probes_and_matchers = [ [123, ["cardinal","finite","frozen","integer","nonnegative","notunset","float","float","numeric","odd","positive","safeinteger","sealed","truthy"],null] [124, ["cardinal","even","finite","frozen","integer","nonnegative","notunset","float","float","numeric","positive","safeinteger","sealed","truthy"],null] [0, ["cardinal","even","falsy","finite","frozen","integer","nonnegative","nonpositive","notunset","float","float","numeric","safeinteger","sealed","zero"],null] [true, ["boolean","frozen","notunset","sealed","truthy"],null] [null, ["falsy","frozen","null","sealed","unset"],null] [undefined, ["falsy","frozen","sealed","undefined","unset"],null] [{}, ["empty","extensible","notunset","object","truthy"],null] [[], ["empty","extensible","list","notunset","truthy"],null] [ prms, ["nativepromise","promise","thenable"], null ] ] #......................................................................................................... # debug intersection_of [ 1, 2, 3, ], [ 'a', 3, 1, ] for [ probe, matcher, error, ] in probes_and_matchers matcher = matcher.sort() await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = types_of probe result = intersection_of matcher, result # help '^334^', matcher.sort() # urge '^334^', intersection_of matcher, result # urge '^334^', result resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "size_of" ] = ( T, done ) -> # debug ( new Buffer '𣁬', ), ( '𣁬'.codePointAt 0 ).toString 16 # debug ( new Buffer '𡉜', ), ( '𡉜'.codePointAt 0 ).toString 16 # debug ( new Buffer '𠑹', ), ( '𠑹'.codePointAt 0 ).toString 16 # debug ( new Buffer '𠅁', ), ( '𠅁'.codePointAt 0 ).toString 16 ### TAINT re-implement types object, pod ### # T.eq ( isa.size_of { '~isa': 'XYZ/yadda', 'foo': 42, 'bar': 108, 'baz': 3, } ), 4 #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ [ 1, 2, 3, 4, ] ], 4, null, ] [[ new Buffer [ 1, 2, 3, 4, ] ], 4, null, ] [[ '𣁬𡉜𠑹𠅁' ], 2 * ( Array.from '𣁬𡉜𠑹𠅁' ).length, null, ] [[ '𣁬𡉜𠑹𠅁', 'codepoints' ], ( Array.from '𣁬𡉜𠑹𠅁' ).length, null, ] [[ '𣁬𡉜𠑹𠅁', 'codeunits' ], 2 * ( Array.from '𣁬𡉜𠑹𠅁' ).length, null, ] [[ '𣁬𡉜𠑹𠅁', 'bytes' ], ( new Buffer '𣁬𡉜𠑹𠅁', 'utf-8' ).length, null, ] [[ 'abcdefghijklmnopqrstuvwxyz' ], 26, null, ] [[ 'abcdefghijklmnopqrstuvwxyz', 'codepoints' ], 26, null, ] [[ 'abcdefghijklmnopqrstuvwxyz', 'codeunits' ], 26, null, ] [[ 'abcdefghijklmnopqrstuvwxyz', 'bytes' ], 26, null, ] [[ 'ä' ], 1, null, ] [[ 'ä', 'codepoints' ], 1, null, ] [[ 'ä', 'codeunits' ], 1, null, ] [[ 'ä', 'bytes' ], 2, null, ] [[ new Map [ [ 'foo', 42, ], [ 'bar', 108, ], ] ], 2, null, ] [[ new Set [ 'foo', 42, 'bar', 108, ] ], 4, null, ] [[ { 'foo': 42, 'bar': 108, 'baz': 3, } ], 3, null, ] [[ { 'foo': null, 'bar': 108, 'baz': 3, } ], 3, null, ] [[ { 'foo': undefined, 'bar': 108, 'baz': 3, } ], 3, null, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers # debug 'µ22900', probe await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = size_of probe... resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "export to target" ] = ( T, done ) -> #......................................................................................................... target = {} intertype = new Intertype() return_value = intertype.export target T.ok return_value is target target.declare 'sometype', ( x ) -> ( @isa.text x ) and ( x.startsWith ':' ) # debug 'µ44333', target # debug 'µ44333', target.isa.sometype 'sometext' # debug 'µ44333', target.isa.sometype ':sometext' done() return null later = -> ### info 'µ01-47', xrpr all_keys_of [ null, ] X = {} X.x = true X.spec = {} X.spec.spec_of_X = true Y = Object.create X Y.y = true Y.spec = Object.create X.spec Y.spec.spec_of_Y = true debug X, rpr ( k for k of X ) debug X.spec, rpr ( k for k of X.spec ) debug Y, rpr ( k for k of Y ) debug Y.spec, rpr ( k for k of Y.spec ) Y.spec.spec_of_X = false info X.spec.spec_of_X info X.spec.spec_of_Y info Y.spec.spec_of_X info Y.spec.spec_of_Y ### #----------------------------------------------------------------------------------------------------------- @[ "cast" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare cast all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', 'float', 123, ], 123, ] [[ 'float', 'integer', 123, ], 123, ] [[ 'float', 'integer', 23.9, ], 24, ] [[ 'boolean', 'float', true, ], 1, ] [[ 'boolean', 'float', false, ], 0, ] [[ 'float', 'boolean', 0, ], false, ] [[ 'float', 'boolean', 1, ], true, ] [[ 'float', 'boolean', -154.7, ], true, ] [[ 'float', 'text', 123, ], '123', ] [[ 'boolean', 'text', true, ], 'true', ] [[ 'null', 'text', null, ], 'null', ] [[ 'int10text', 'text', '1245', ], '1245', ] [[ 'int16text', 'text', '1245', ], '1245', ] [[ 'int10text', 'float', '1245', ], 1245, ] [[ 'int16text', 'float', '1245', ], 4677, ] [[ 'int16text', 'int2text', '7', ], '111', ] [[ 'float', 'null', 0, ], null,'unable to cast a float as null', ] [[ 'float', 'null', 1, ], null,'unable to cast a float as null', ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers #......................................................................................................... await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type_a, type_b, x, ] = probe result = cast type_a, type_b, x resolve result return null #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type_a, type_b, x, ] = probe result = cast[ type_a ] type_b, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa_optional" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa_optional validate_optional } = intertype.export() #......................................................................................................... T.eq ( isa_optional.integer null ), true T.eq ( isa_optional.integer 1234 ), true T.eq ( isa_optional.integer '1234' ), false T.eq ( isa_optional.integer true ), false T.eq ( isa_optional.integer false ), false T.eq ( isa_optional.integer undefined ), true T.eq ( isa_optional.integer new Date() ), false T.eq ( isa_optional.integer [] ), false #......................................................................................................... try validate_optional.nonempty_text null T.ok true catch error T.fail 'testcase-434653746' #......................................................................................................... try validate_optional.nonempty_text 'yes' T.ok true catch error T.fail 'testcase-434653747' #......................................................................................................... try validate_optional.nonempty_text 12.4 T.fail 'testcase-434653748' catch error T.ok true #......................................................................................................... try validate_optional.nonempty_text false T.fail 'testcase-434653749' catch error T.ok true #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa.list_of A" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], false, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = isa.list_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa.list_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa isa_list_of validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], false, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = isa_list_of[ type ] x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa_object_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa isa_object_of validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', { x: 123, }, ], true, ] [[ 'integer', { x: 123, }, ], true, ] [[ 'integer', { x: 1, y: 2, a: 3, c: 123.5, }, ], false, ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = isa_object_of[ type ] x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate.list_of A" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], null, "not a valid list_of" ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = validate.list_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate.list_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate isa_list_of validate_list_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', [ 123, ], ], true, ] [[ 'integer', [ 123, ], ], true, ] [[ 'integer', [ 1,2,3,123.5, ], ], null, "not a valid list_of" ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = validate_list_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "validate.object_of B" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate isa_object_of validate_object_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [[ 'float', { x: 123, }, ], true, ] [[ 'integer', { x: 123, }, ], true, ] [[ 'integer', { x: 1, y: 2, a: 3, c: 123.5, }, ], null, "not a valid object_of", ] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ type, x, ] = probe result = validate_object_of type, x resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "vnr, int32" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa declare validate isa_list_of validate_list_of } = intertype.export() #......................................................................................................... T.ok isa.int32 1234 T.ok isa.int32 -1234 T.ok not isa.int32 1.3 T.ok isa.vnr [ -1234, ] T.ok isa_list_of.int32 [ -1234, ] T.ok isa_list_of.int32 [] T.ok isa.vnr [ -1234, 7e20, ] T.ok isa.vnr [ -Infinity, ] T.ok isa.vnr [ +Infinity, ] T.ok isa.vnr [ +Infinity, 1, ] T.ok isa.infloat +1234567.665553 T.ok isa.infloat -1234567.665553 T.ok isa.infloat +Infinity T.ok isa.infloat -Infinity T.ok not isa.vnr Int32Array.from [ -1234, ] done() return null #----------------------------------------------------------------------------------------------------------- @[ "check(): validation with intermediate results (experiment)" ] = ( T, done ) -> #......................................................................................................... PATH = require 'path' FS = require 'fs' intertype = new Intertype() { isa validate declare } = intertype.export() sad = Symbol 'sad' # will be made attribute of `intertype` #......................................................................................................... is_sad = ( x ) -> ( x is sad ) or ( x instanceof Error ) or ( ( isa.object x ) and ( x[ sad ] is true ) ) is_happy = ( x ) -> not is_sad x sadden = ( x ) -> { [sad]: true, _: x, } #......................................................................................................... check = new Proxy {}, get: ( t, k ) -> ( P... ) -> return fn unless isa.callable fn = t[ k ] return try ( fn P... ) catch error then error set: ( t, k, v ) -> t[ k ] = v delete: ( t, k, v ) -> delete t[ k ] check.foo = 42 check.foo check.integer = ( x ) -> validate.integer x debug '^336552^', check.integer 42 debug '^336552^', check.integer 42.5 #......................................................................................................... check_fso_exists = ( path, stats = null ) -> try ( stats ? FS.statSync path ) catch error then error #......................................................................................................... check_is_file = ( path, stats = null ) -> ### Checks if `path` exists, points to a file, is readable, and parses as a JSON file Malfunction Risks: * see `check_fso_exists()` &c. * FS-related race conditions, including * longish timeouts for paths pointing to non-local or otherwise misbehaving FS resources. ### #....................................................................................................... ### in this case, `stats` is `sad` when `check_fso_exists()` fails; in the general case, it could be any manner of object whose computation required effort, so we want to keep it; we document that fact by aliasing it as `bad`: ### return bad if is_sad ( bad = stats = check_fso_exists path, stats ) return stats if stats.isFile() return sadden "not a file: #{path}" #......................................................................................................... check_is_json_file = ( path ) -> ### Checks if `path` exists, points to a file, is readable, and is parsable as a JSON file; as a side-effect, returns the result of parsing when successful. Malfunction Risks: * see `check_is_file()` &c. * file will be read and parsed synchronously; as such, an arbitrary amount of time and space could be required in case `path` points to a large file and/or is slow to parse ### # return bad if is_sad ( bad = stats = check_is_file path, stats ) return try ( JSON.parse FS.readFileSync path ) catch error then error #......................................................................................................... debug '^377332-1^', is_sad sad debug '^377332-6^', is_sad { [sad]: true, } debug '^377332-7^', is_sad new Error "wat" debug '^377332-2^', is_sad 42 debug '^377332-3^', is_sad false debug '^377332-4^', is_sad null debug '^377332-5^', is_sad { [sad]: false, } paths = [ PATH.resolve PATH.join __dirname, '../../package.json' PATH.resolve PATH.join __dirname, '../../XXXXX' ] for path in paths R = null loop # break if ( R = check_fso_exists path, R ) is sad # break if ( R = check_is_file path, R ) is sad break if is_sad ( R = check_is_json_file path, R ) break if is_sad R then warn "fails with", ( rpr R )[ ... 80 ] else help "is JSON file; contents:", ( rpr R )[ ... 100 ] warn '^99282^', ( error = check_fso_exists 'XXXXX' ).code, CND.grey error.message warn '^99282^', ( error = check_is_file 'XXXXX' ).code, CND.grey error.message warn '^99282^', ( error = check_is_json_file 'XXXXX' ).code, CND.grey error.message #......................................................................................................... ### Turning a type declaration into a check ### check_integer = ( x ) -> return try x if ( validate.integer x ) catch error then error isa_integer = ( x ) -> is_happy check_integer x validate_integer = ( x ) -> if is_happy ( R = check_integer x ) then return R else throw R #......................................................................................................... debug '^333442^', check_integer 42 debug '^333442^', ( rpr check_integer 42.5 )[ .. 80 ] debug '^333442^', isa_integer 42 debug '^333442^', isa_integer 42.5 # debug stats # [ type, x, ] = probe # result = validate_list_of type, x # T.eq result, matcher done() return null #----------------------------------------------------------------------------------------------------------- @[ "check(): validation with intermediate results (for reals)" ] = ( T, done ) -> #......................................................................................................... PATH = require 'path' FS = require 'fs' intertype = new Intertype() { isa validate check sad is_sad is_happy sadden type_of types_of declare declare_check } = intertype.export() #......................................................................................................... declare_check 'dvsbl_2_3', ( x ) -> validate.even x return x %% 3 is 0 #......................................................................................................... T.eq ( is_happy check 'integer', 42 ), true T.eq ( is_happy check 'dvsbl_2_3', 42 ), true T.eq ( is_happy check 'dvsbl_2_3', 2 * 3 ), true T.eq ( is_happy check.integer 42 ), true T.eq ( is_happy check.dvsbl_2_3 42 ), true T.eq ( is_happy check.dvsbl_2_3 2 * 3 ), true #......................................................................................................... T.eq ( check 'dvsbl_2_3', 42 ), true T.eq ( check 'dvsbl_2_3', 2 * 3 ), true #......................................................................................................... T.eq ( check 'integer', 42 ), true T.eq ( check.integer 42 ), true #......................................................................................................... T.eq ( check.dvsbl_2_3 42 ), true T.eq ( check.dvsbl_2_3 2 * 3 ), true #......................................................................................................... T.eq ( is_happy check 'integer', 42.5 ), false T.eq ( is_happy check.integer 42.5 ), false T.eq ( is_happy check 'dvsbl_2_3', 43 ), false T.eq ( is_happy check.dvsbl_2_3 43 ), false #......................................................................................................... T.eq ( check 'integer', 42.5 ), sad T.eq ( check.integer 42.5 ), sad #......................................................................................................... T.ok isa.error ( check 'dvsbl_2_3', 43 ) T.ok isa.error ( check.dvsbl_2_3 43 ) # #......................................................................................................... # declare 'fs_stats', tests: # 'x is an object': ( x ) -> @isa.object x # 'x.size is a cardinal': ( x ) -> @isa.cardinal x.size # 'x.atimeMs is a float': ( x ) -> @isa.float x.atimeMs # 'x.atime is a date': ( x ) -> @isa.date x.atime # #......................................................................................................... # ### NOTE: will throw error unless path exists, error is implicitly caught, represents sad path ### # declare_check 'fso_exists', ( path, stats = null ) -> FS.statSync path # # try ( stats ? FS.statSync path ) catch error then error # #......................................................................................................... # declare_check 'is_file', ( path, stats = null ) -> # return bad if is_sad ( bad = stats = @check.fso_exists path, stats ) # return stats if stats.isFile() # return sadden "not a file: #{path}" # #......................................................................................................... # declare_check 'is_json_file', ( path ) -> # return try ( JSON.parse FS.readFileSync path ) catch error then error #......................................................................................................... ### overloading 'path' here, obviously ### happy_path = PATH.resolve PATH.join __dirname, '../../../package.json' sad_path = 'xxxxx' happy_fso_exists = check.fso_exists happy_path happy_is_file = check.is_file happy_path happy_is_json_file = check.is_json_file happy_path sad_fso_exists = check.fso_exists sad_path sad_is_file = check.is_file sad_path sad_is_json_file = check.is_json_file sad_path T.ok is_happy happy_fso_exists T.ok is_happy happy_is_file T.ok is_happy happy_is_json_file T.ok is_sad sad_fso_exists T.ok is_sad sad_is_file T.ok is_sad sad_is_json_file T.ok isa.fs_stats happy_fso_exists T.ok isa.fs_stats happy_is_file T.ok isa.object happy_is_json_file T.ok isa.error sad_fso_exists T.ok isa.error sad_is_file T.ok isa.error sad_is_json_file T.eq sad_fso_exists.code, 'ENOENT' T.eq sad_is_file.code, 'ENOENT' T.eq sad_is_json_file.code, 'ENOENT' #......................................................................................................... done() #----------------------------------------------------------------------------------------------------------- @[ "check(): complain on name collision" ] = ( T, done ) -> #......................................................................................................... PATH = require 'path' FS = require 'fs' intertype = new Intertype() { isa validate check sad is_sad is_happy sadden type_of types_of declare declare_check } = intertype.export() #......................................................................................................... declare_check 'dvsbl_2_3', ( x ) -> validate.even x return x %% 3 is 0 #......................................................................................................... T.throws /check 'dvsbl_2_3' already declared/, -> declare_check 'dvsbl_2_3', ( x ) -> validate.even x return x %% 3 is 0 #......................................................................................................... done() #----------------------------------------------------------------------------------------------------------- @[ "types_of() includes happy, sad" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare sad sadden all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ 123, [ 'happy', 'float', ], null, ] [ 124, [ 'happy', 'float', ], null, ] [ 0, [ 'happy', 'float', ], null, ] [ true, [ 'boolean', 'happy', ], null, ] [ null, [ 'happy', 'null', ], null, ] [ undefined, [ 'happy', 'undefined', ], null, ] [ {}, [ 'happy', 'object', ], null, ] [ [], [ 'happy', 'list', ], null, ] [ sad, [ 'sad', 'symbol', ], null, ] [ new Error(), [ 'error', 'sad', ], null, ] [ { [sad]: true, _: null, }, [ 'object', 'sad', 'saddened', ], null, ] [ ( sadden null ), [ 'object', 'sad', 'saddened', ], null, ] ] #......................................................................................................... # debug intersection_of [ 1, 2, 3, ], [ 'a', 3, 1, ] for [ probe, matcher, error, ] in probes_and_matchers matcher.sort() await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = intersection_of matcher, types_of probe # log rpr [ probe, result, ] # resolve result resolve result return null #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "unsadden" ] = ( T, done ) -> #......................................................................................................... intertype = new Intertype() { isa validate type_of types_of size_of declare sad sadden unsadden all_keys_of } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ { [sad]: true, _: null, }, null, null, ] [ ( sadden 129282 ), 129282, null, ] [ 333, 333, null, ] [ sad, null, "not a valid saddened", ] [ ( new Error() ), null, "not a valid saddened", ] ] #......................................................................................................... # debug intersection_of [ 1, 2, 3, ], [ 'a', 3, 1, ] for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> resolve unsadden probe return null #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "isa.immediate, nowait" ] = ( T, done ) -> intertype = new Intertype() { isa types_of type_of validate nowait } = intertype.export() #......................................................................................................... try T.ok 'immediate' not in ( types_of new Promise -> ) catch error then T.fail 'testcase-171615' try T.ok 'immediate' not in ( types_of { then: -> } ) catch error then T.fail 'testcase-171616' try T.ok 'immediate' in ( types_of 42 ) catch error then T.fail 'testcase-171617' #......................................................................................................... try T.eq ( isa.immediate null ), true catch error then T.fail 'testcase-171618' try T.eq ( isa.immediate 12.34 ), true catch error then T.fail 'testcase-171619' try T.eq ( isa.immediate undefined ), true catch error then T.fail 'testcase-171620' try T.eq ( isa.immediate new Promise -> ), false catch error then T.fail 'testcase-171621' #......................................................................................................... try ( validate.immediate 42 ) catch error then T.fail 'testcase-171622' try ( validate.immediate undefined ) catch error then T.fail 'testcase-171623' try ( validate.immediate null ) catch error then T.fail 'testcase-171624' try ( validate.immediate 1 * '#' ) catch error then T.fail 'testcase-171625' #......................................................................................................... T.throws /not a valid immediate/, -> validate.immediate x = ( new Promise -> ) # validate.immediate x = ( new Promise -> ) try ( r = nowait ( ( x ) -> x ** 2 ) 5 ) catch error then T.fail 'testcase-171626' T.eq r, 25 T.throws /not a valid immediate/, -> r = nowait ( -> new Promise -> )() done() # #----------------------------------------------------------------------------------------------------------- # @[ "equality checks" ] = ( T, done ) -> # ### TAINT bug: when this test runs as only one, no problem; when run after some of the above, # `equals` check throws error `Error: ENOENT: no such file or directory, open 'equals'` (!!!) ### # intertype = new Intertype() # { isa # check } = intertype.export() # urge '^8873^', rpr ( k for k of intertype.export() ) # debug '^22231^', check.equals 3, 3 # debug '^22231^', check.equals 3, 4 # done() if done? #----------------------------------------------------------------------------------------------------------- @[ "equals" ] = ( T, done ) -> intertype = new Intertype() { isa check equals } = intertype.export() ### TAINT copy more extensive tests from CND, `js_eq`? ### re = /expected at least 2 arguments/ try equals 3 catch error warn error.message if re.test error.message then T.ok true else T.fail "expected error #{rpr re}, got #{rpr error.message}" T.fail "expected error, got none" unless error? T.eq ( equals 3, 3 ), true T.eq ( equals 3, 4 ), false T.eq ( equals ( new Map [ [ 1, 2, ], ]), ( new Map [ [ 1, 2, ], ]) ), true T.eq ( equals ( new Set [ [ 1, 2, ], ]), ( new Set [ [ 1, 2, ], ]) ), true T.eq ( equals ( new Map [ [ 1, 2, ], ]), ( new Map [ [ 1, 3, ], ]) ), false T.eq ( equals ( new Set [ [ 1, 2, ], ]), ( new Set [ [ 1, 3, ], ]) ), false done() if done? #----------------------------------------------------------------------------------------------------------- @[ "numerical types" ] = ( T, done ) -> intertype = new Intertype() { isa type_of check equals } = intertype.export() #......................................................................................................... probes_and_matchers = [ [ 'nan', [ 23, false ], ] [ 'finite', [ 23, true ], ] [ 'integer', [ 23, true ], ] [ 'safeinteger', [ 23, true ], ] [ 'numeric', [ 23, true ], ] [ 'even', [ 23, false ], ] [ 'odd', [ 23, true ], ] [ 'cardinal', [ 23, true ], ] [ 'nonnegative', [ 23, true ], ] [ 'positive', [ 23, true ], ] [ 'positive_integer', [ 23, true ], ] [ 'negative_integer', [ 23, false ], ] [ 'zero', [ 23, false ], ] [ 'infinity', [ 23, false ], ] [ 'infloat', [ 23, true ], ] [ 'nonpositive', [ 23, false ], ] [ 'negative', [ 23, false ], ] [ 'positive_float', [ 23, true ], ] [ 'negative_float', [ 23, false ], ] ] #......................................................................................................... error = null for [ type, pairs..., ] in probes_and_matchers for [ value, matcher, ] in pairs probe = [ type, value, ] await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> resolve isa[ type ] value return null #......................................................................................................... done() if done? # type_of 1e32 ), 'float' # [ 'float', [ 23, false ], ] #----------------------------------------------------------------------------------------------------------- @[ "real-life example 1" ] = ( T, done ) -> types = new Intertype() { isa type_of types_of validate check equals } = types.export() #......................................................................................................... types.declare 'intershop_rpc_settings', tests: "x is a object": ( x ) -> @isa.object x "x.host is a nonempty_text": ( x ) -> @isa.nonempty_text x.host "x.port is a cardinal": ( x ) -> @isa.cardinal x.port "x.show_counts is a boolean": ( x ) -> @isa.boolean x.show_counts "x.count_interval is a positive_integer": ( x ) -> @isa.positive_integer x.count_interval "x.socket_log_all is a boolean": ( x ) -> @isa.boolean x.socket_log_all "x.socketserver_log_all is a boolean": ( x ) -> @isa.boolean x.socketserver_log_all "x.logging is a boolean or a function": ( x ) -> ( @isa.boolean x.logging ) or ( @isa.function x.logging ) #......................................................................................................... _defaults = Object.freeze host: 'localhost' port: 23001 show_counts: true count_interval: 1000 socket_log_all: false socketserver_log_all: false logging: true #......................................................................................................... debug types_of _defaults.count_interval T.ok isa.intershop_rpc_settings _defaults done() # [ 'float', [ 23, false ], ] #----------------------------------------------------------------------------------------------------------- @[ "real-life example 2" ] = ( T, done ) -> types = new Intertype() { isa declare type_of types_of validate check equals } = types.export() #......................................................................................................... declare 'intershop_cli_psql_run_selector', tests: "x is a nonempty_text": ( x ) -> @isa.nonempty_text x "x must be '-c' or '-f'": ( x ) -> x in [ '-c', '-f', ] #......................................................................................................... # debug types_of '-c' # debug types_of '-x' T.eq ( isa.intershop_cli_psql_run_selector '-f' ), true T.eq ( isa.intershop_cli_psql_run_selector '-c' ), true T.eq ( isa.intershop_cli_psql_run_selector 'xxx' ), false T.eq ( isa.intershop_cli_psql_run_selector '' ), false try validate.intershop_cli_psql_run_selector '-f' T.ok true catch error T.fail error.message try validate.some_unknown_type '-f' T.fail "expected an error, but statement passed" catch error T.ok /violates.*is a known type/.test error.message done() ############################################################################################################ unless module.parent? test @ # test @[ "check(): complain on name collision" ] # @[ "check(): complain on name collision" ]() # test @[ "size_of" ] # test @[ "numerical types" ] # test @[ "real-life example 2" ] # test @[ "equals" ] # @[ "equality checks" ]() # test @[ "isa.immediate, nowait" ] # test @[ "types_of() includes happy, sad" ] # @[ "types_of() includes happy, sad" ]() # test @[ "check(): validation with intermediate results (experiment)" ] # test @[ "check(): validation with intermediate results (for reals)" ] # test @[ "types_of" ] # test @[ "vnr, int32" ] # test @[ "cast" ] # test @[ "isa.list_of A" ] # test @[ "isa.list_of B" ] # test @[ "isa_object_of B" ] # test @[ "validate.object_of B" ] # test @[ "validate.list_of A" ] # test @[ "validate.list_of B" ]
[ { "context": "###\n * bag\n * getbag.io\n *\n * Copyright (c) 2015 Ryan Gaus\n * Licensed under the MIT license.\n###\nuuid = req", "end": 58, "score": 0.9998330473899841, "start": 49, "tag": "NAME", "value": "Ryan Gaus" } ]
src/controllers/foodstuff_controller.coffee
1egoman/bag-node
0
### * bag * getbag.io * * Copyright (c) 2015 Ryan Gaus * Licensed under the MIT license. ### uuid = require "uuid" Foodstuff = require "../models/foodstuff_model" # get a foodstuff of all lists # GET /foodstuff exports.index = (req, res) -> query = Foodstuff.find $or: [ private: false , user: req.user._id private: true ] .sort date: -1 # limit quantity and a start index query = query.skip parseInt req.body.start if req.body?.start query = query.limit parseInt req.body.limit if req.body?.limit # limit by user if req.body?.user if req.body.user is "me" query = query.find user: req.user._id else query = query.find user: req.body.user query.exec (err, data) -> if err res.send status: "bag.error.foodstuff.index" error: err else res.send status: "bag.success.foodstuff.index" data: data exports.new = (req, res) -> res.send "Not supported." # create a new foodstuff # POST /foodstuff exports.create = (req, res) -> foodstuff_params = req.body?.foodstuff # verify the foodstuff if foodstuff_params and \ foodstuff_params.name? and \ foodstuff_params.desc? and \ foodstuff_params.price? and \ foodstuff_params.tags? foodstuff_params.user = req.user._id if req.user?._id # if the foodstuff is public, make it unverified foodstuff_params.verified = false # private recipe check_priv = (foodstuff_params, done) -> if foodstuff_params.private and req.user.plan > 0 foodstuff_params.private = true # format the price with a custom store foodstuff_params.stores = custom: price: foodstuff_params.price # are we on a plan with a fixed amount of foodstuffs? if req.user.plan is 1 Foodstuff.find user: req.user._id private: true , (err, total, n) -> if err or total.length >= 10 res.send status: "bag.error.foodstuff.create" error: err or "Reached max private foodstuffs." else done foodstuff_params else done foodstuff_params # unpaid users cannot make private recipes else foodstuff_params.private = false done foodstuff_params # check to be sure that we can create a private foodstuff check_priv foodstuff_params, (foodstuff_params) -> # create the foodstuff foodstuff = new Foodstuff foodstuff_params foodstuff.save (err) -> if err res.send status: "bag.error.foodstuff.create" error: err else res.send status: "bag.success.foodstuff.create" private: foodstuff_params.private data: foodstuff else res.send status: "bag.error.foodstuff.create" error: "all the required elements weren't there." # get a foodstuff with the specified id # GET /foodstuff/:list exports.show = (req, res) -> Foodstuff.findOne _id: req.params.foodstuff, (err, data) -> if err res.send status: "bag.error.foodstuff.show" error: err else res.send status: "bag.success.foodstuff.show" data: data exports.edit = (req, res) -> res.send "Not supported." # update a foodstuff # PUT /foodstuff/:list exports.update = (req, res) -> Foodstuff.findOne _id: req.params.foodstuff, (err, data) -> if err res.send status: "bag.error.foodstuff.update" error: err else data[k] = v for k, v of req.body?.foodstuff data.save (err) -> if err res.send status: "bag.error.foodstuff.update" data: err else res.send status: "bag.success.foodstuff.update" data: data # delete a foodstuff # DELETE /foodstuff/:list exports.destroy = (req, res) -> Foodstuff.remove _id: req.params.foodstuff private: true , (err, data) -> console.log data if err res.send status: "bag.error.foodstuff.delete" error: err else res.send status: "bag.success.foodstuff.delete" # search for a foodstuff using the given search query (req.params.foodstuff) exports.search = (req, res) -> if not req.params?.foodstuff res.send status: "bag.error.foodstuff.search" error: "No needle." else Foodstuff.find $or: [ private: false name: $regex: new RegExp req.params.foodstuff, 'i' , user: req.user._id private: true name: $regex: new RegExp req.params.foodstuff, 'i' ] , (err, data) -> if err res.send status: "bag.error.foodstuff.search" error: err else res.send status: "bag.success.foodstuff.search" data: data
223153
### * bag * getbag.io * * Copyright (c) 2015 <NAME> * Licensed under the MIT license. ### uuid = require "uuid" Foodstuff = require "../models/foodstuff_model" # get a foodstuff of all lists # GET /foodstuff exports.index = (req, res) -> query = Foodstuff.find $or: [ private: false , user: req.user._id private: true ] .sort date: -1 # limit quantity and a start index query = query.skip parseInt req.body.start if req.body?.start query = query.limit parseInt req.body.limit if req.body?.limit # limit by user if req.body?.user if req.body.user is "me" query = query.find user: req.user._id else query = query.find user: req.body.user query.exec (err, data) -> if err res.send status: "bag.error.foodstuff.index" error: err else res.send status: "bag.success.foodstuff.index" data: data exports.new = (req, res) -> res.send "Not supported." # create a new foodstuff # POST /foodstuff exports.create = (req, res) -> foodstuff_params = req.body?.foodstuff # verify the foodstuff if foodstuff_params and \ foodstuff_params.name? and \ foodstuff_params.desc? and \ foodstuff_params.price? and \ foodstuff_params.tags? foodstuff_params.user = req.user._id if req.user?._id # if the foodstuff is public, make it unverified foodstuff_params.verified = false # private recipe check_priv = (foodstuff_params, done) -> if foodstuff_params.private and req.user.plan > 0 foodstuff_params.private = true # format the price with a custom store foodstuff_params.stores = custom: price: foodstuff_params.price # are we on a plan with a fixed amount of foodstuffs? if req.user.plan is 1 Foodstuff.find user: req.user._id private: true , (err, total, n) -> if err or total.length >= 10 res.send status: "bag.error.foodstuff.create" error: err or "Reached max private foodstuffs." else done foodstuff_params else done foodstuff_params # unpaid users cannot make private recipes else foodstuff_params.private = false done foodstuff_params # check to be sure that we can create a private foodstuff check_priv foodstuff_params, (foodstuff_params) -> # create the foodstuff foodstuff = new Foodstuff foodstuff_params foodstuff.save (err) -> if err res.send status: "bag.error.foodstuff.create" error: err else res.send status: "bag.success.foodstuff.create" private: foodstuff_params.private data: foodstuff else res.send status: "bag.error.foodstuff.create" error: "all the required elements weren't there." # get a foodstuff with the specified id # GET /foodstuff/:list exports.show = (req, res) -> Foodstuff.findOne _id: req.params.foodstuff, (err, data) -> if err res.send status: "bag.error.foodstuff.show" error: err else res.send status: "bag.success.foodstuff.show" data: data exports.edit = (req, res) -> res.send "Not supported." # update a foodstuff # PUT /foodstuff/:list exports.update = (req, res) -> Foodstuff.findOne _id: req.params.foodstuff, (err, data) -> if err res.send status: "bag.error.foodstuff.update" error: err else data[k] = v for k, v of req.body?.foodstuff data.save (err) -> if err res.send status: "bag.error.foodstuff.update" data: err else res.send status: "bag.success.foodstuff.update" data: data # delete a foodstuff # DELETE /foodstuff/:list exports.destroy = (req, res) -> Foodstuff.remove _id: req.params.foodstuff private: true , (err, data) -> console.log data if err res.send status: "bag.error.foodstuff.delete" error: err else res.send status: "bag.success.foodstuff.delete" # search for a foodstuff using the given search query (req.params.foodstuff) exports.search = (req, res) -> if not req.params?.foodstuff res.send status: "bag.error.foodstuff.search" error: "No needle." else Foodstuff.find $or: [ private: false name: $regex: new RegExp req.params.foodstuff, 'i' , user: req.user._id private: true name: $regex: new RegExp req.params.foodstuff, 'i' ] , (err, data) -> if err res.send status: "bag.error.foodstuff.search" error: err else res.send status: "bag.success.foodstuff.search" data: data
true
### * bag * getbag.io * * Copyright (c) 2015 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### uuid = require "uuid" Foodstuff = require "../models/foodstuff_model" # get a foodstuff of all lists # GET /foodstuff exports.index = (req, res) -> query = Foodstuff.find $or: [ private: false , user: req.user._id private: true ] .sort date: -1 # limit quantity and a start index query = query.skip parseInt req.body.start if req.body?.start query = query.limit parseInt req.body.limit if req.body?.limit # limit by user if req.body?.user if req.body.user is "me" query = query.find user: req.user._id else query = query.find user: req.body.user query.exec (err, data) -> if err res.send status: "bag.error.foodstuff.index" error: err else res.send status: "bag.success.foodstuff.index" data: data exports.new = (req, res) -> res.send "Not supported." # create a new foodstuff # POST /foodstuff exports.create = (req, res) -> foodstuff_params = req.body?.foodstuff # verify the foodstuff if foodstuff_params and \ foodstuff_params.name? and \ foodstuff_params.desc? and \ foodstuff_params.price? and \ foodstuff_params.tags? foodstuff_params.user = req.user._id if req.user?._id # if the foodstuff is public, make it unverified foodstuff_params.verified = false # private recipe check_priv = (foodstuff_params, done) -> if foodstuff_params.private and req.user.plan > 0 foodstuff_params.private = true # format the price with a custom store foodstuff_params.stores = custom: price: foodstuff_params.price # are we on a plan with a fixed amount of foodstuffs? if req.user.plan is 1 Foodstuff.find user: req.user._id private: true , (err, total, n) -> if err or total.length >= 10 res.send status: "bag.error.foodstuff.create" error: err or "Reached max private foodstuffs." else done foodstuff_params else done foodstuff_params # unpaid users cannot make private recipes else foodstuff_params.private = false done foodstuff_params # check to be sure that we can create a private foodstuff check_priv foodstuff_params, (foodstuff_params) -> # create the foodstuff foodstuff = new Foodstuff foodstuff_params foodstuff.save (err) -> if err res.send status: "bag.error.foodstuff.create" error: err else res.send status: "bag.success.foodstuff.create" private: foodstuff_params.private data: foodstuff else res.send status: "bag.error.foodstuff.create" error: "all the required elements weren't there." # get a foodstuff with the specified id # GET /foodstuff/:list exports.show = (req, res) -> Foodstuff.findOne _id: req.params.foodstuff, (err, data) -> if err res.send status: "bag.error.foodstuff.show" error: err else res.send status: "bag.success.foodstuff.show" data: data exports.edit = (req, res) -> res.send "Not supported." # update a foodstuff # PUT /foodstuff/:list exports.update = (req, res) -> Foodstuff.findOne _id: req.params.foodstuff, (err, data) -> if err res.send status: "bag.error.foodstuff.update" error: err else data[k] = v for k, v of req.body?.foodstuff data.save (err) -> if err res.send status: "bag.error.foodstuff.update" data: err else res.send status: "bag.success.foodstuff.update" data: data # delete a foodstuff # DELETE /foodstuff/:list exports.destroy = (req, res) -> Foodstuff.remove _id: req.params.foodstuff private: true , (err, data) -> console.log data if err res.send status: "bag.error.foodstuff.delete" error: err else res.send status: "bag.success.foodstuff.delete" # search for a foodstuff using the given search query (req.params.foodstuff) exports.search = (req, res) -> if not req.params?.foodstuff res.send status: "bag.error.foodstuff.search" error: "No needle." else Foodstuff.find $or: [ private: false name: $regex: new RegExp req.params.foodstuff, 'i' , user: req.user._id private: true name: $regex: new RegExp req.params.foodstuff, 'i' ] , (err, data) -> if err res.send status: "bag.error.foodstuff.search" error: err else res.send status: "bag.success.foodstuff.search" data: data
[ { "context": " if i == 0\n parties_message += \"#{name}\"\n else\n parties_message += \"", "end": 1772, "score": 0.8918324112892151, "start": 1768, "tag": "NAME", "value": "name" } ]
src/boardgames.coffee
uramonk/bdg_bot
0
storage = require('./storage') module.exports = { getBoardgames: (robot) -> boardgames = storage.getBoardgames(robot) boardgames.sort (a, b) -> if a.id < b.id -1 else 1 return boardgames getBoardgamesByPlayerNum: (robot, player_num) -> boardgames = storage.getBoardgames(robot) new_boardgames = [] boardgames.sort (a, b) -> if a.id < b.id -1 else 1 .map (item) -> min = item.min max = item.max if min <= player_num && player_num <= max new_boardgames.push(item) return new_boardgames getBoardgameListMessage: (boardgames) -> boardgames_message = '' boardgames.map (item) -> id = item.id name = item.name min = item.min max = item.max if min == max boardgames_message += "#{id}: #{name}, プレイ人数: #{min}人\n" else boardgames_message += "#{id}: #{name}, プレイ人数: #{min}〜#{max}人\n" return boardgames_message getParties: (robot) -> parties = storage.getParties(robot) parties.sort (a, b) -> if a.id < b.id -1 else 1 return parties getPartyListMessage: (parties) -> parties_message = '' parties.map (item) -> id = item.id day = item.day time = item.time min = item.min max = item.max participants = item.participants parties_message += "[#{id}] 開催日: #{day} #{time}\n" parties_message += " 参加者: " if participants.length == 0 parties_message += "いません" else i = 0 participants.map (item) -> name = item t_name = name.slice(1) name = name.slice(0, 1) + "." + t_name if i == 0 parties_message += "#{name}" else parties_message += ", #{name}" i += 1 parties_message += "\n" return parties_message }
10961
storage = require('./storage') module.exports = { getBoardgames: (robot) -> boardgames = storage.getBoardgames(robot) boardgames.sort (a, b) -> if a.id < b.id -1 else 1 return boardgames getBoardgamesByPlayerNum: (robot, player_num) -> boardgames = storage.getBoardgames(robot) new_boardgames = [] boardgames.sort (a, b) -> if a.id < b.id -1 else 1 .map (item) -> min = item.min max = item.max if min <= player_num && player_num <= max new_boardgames.push(item) return new_boardgames getBoardgameListMessage: (boardgames) -> boardgames_message = '' boardgames.map (item) -> id = item.id name = item.name min = item.min max = item.max if min == max boardgames_message += "#{id}: #{name}, プレイ人数: #{min}人\n" else boardgames_message += "#{id}: #{name}, プレイ人数: #{min}〜#{max}人\n" return boardgames_message getParties: (robot) -> parties = storage.getParties(robot) parties.sort (a, b) -> if a.id < b.id -1 else 1 return parties getPartyListMessage: (parties) -> parties_message = '' parties.map (item) -> id = item.id day = item.day time = item.time min = item.min max = item.max participants = item.participants parties_message += "[#{id}] 開催日: #{day} #{time}\n" parties_message += " 参加者: " if participants.length == 0 parties_message += "いません" else i = 0 participants.map (item) -> name = item t_name = name.slice(1) name = name.slice(0, 1) + "." + t_name if i == 0 parties_message += "#{<NAME>}" else parties_message += ", #{name}" i += 1 parties_message += "\n" return parties_message }
true
storage = require('./storage') module.exports = { getBoardgames: (robot) -> boardgames = storage.getBoardgames(robot) boardgames.sort (a, b) -> if a.id < b.id -1 else 1 return boardgames getBoardgamesByPlayerNum: (robot, player_num) -> boardgames = storage.getBoardgames(robot) new_boardgames = [] boardgames.sort (a, b) -> if a.id < b.id -1 else 1 .map (item) -> min = item.min max = item.max if min <= player_num && player_num <= max new_boardgames.push(item) return new_boardgames getBoardgameListMessage: (boardgames) -> boardgames_message = '' boardgames.map (item) -> id = item.id name = item.name min = item.min max = item.max if min == max boardgames_message += "#{id}: #{name}, プレイ人数: #{min}人\n" else boardgames_message += "#{id}: #{name}, プレイ人数: #{min}〜#{max}人\n" return boardgames_message getParties: (robot) -> parties = storage.getParties(robot) parties.sort (a, b) -> if a.id < b.id -1 else 1 return parties getPartyListMessage: (parties) -> parties_message = '' parties.map (item) -> id = item.id day = item.day time = item.time min = item.min max = item.max participants = item.participants parties_message += "[#{id}] 開催日: #{day} #{time}\n" parties_message += " 参加者: " if participants.length == 0 parties_message += "いません" else i = 0 participants.map (item) -> name = item t_name = name.slice(1) name = name.slice(0, 1) + "." + t_name if i == 0 parties_message += "#{PI:NAME:<NAME>END_PI}" else parties_message += ", #{name}" i += 1 parties_message += "\n" return parties_message }
[ { "context": "'comment': 'based on asp textmate bundle by Rich Barton'\n'fileTypes': [\n 'brs'\n]\n'name': 'BrightScript'\n", "end": 55, "score": 0.9998878836631775, "start": 44, "tag": "NAME", "value": "Rich Barton" } ]
grammars/brightscript.cson
Eldelshell/language-brs
1
'comment': 'based on asp textmate bundle by Rich Barton' 'fileTypes': [ 'brs' ] 'name': 'BrightScript' 'patterns': [ { 'captures': '1': 'name': 'storage.type.function.brs' '2': 'name': 'entity.name.function.brs' '3': 'name': 'punctuation.definition.parameters.brs' '4': 'name': 'variable.parameter.function.brs' '5': 'name': 'punctuation.definition.parameters.brs' 'match': '^\\s*((?i:function|sub))\\s*([a-zA-Z_]\\w*)\\s*(\\()([^)]*)(\\)).*\\n?' 'name': 'meta.function.brs' } { 'begin': '(^[ \\t]+)?(?=\')' 'beginCaptures': '1': 'name': 'punctuation.whitespace.comment.leading.brs' 'end': '(?!\\G)' 'patterns': [ { 'begin': '\'' 'beginCaptures': '0': 'name': 'punctuation.definition.comment.brs' 'end': '\\n' 'name': 'comment.line.apostrophe.brs' } ] } { 'begin': '(^[ \\t]+)?(?=REM )' 'beginCaptures': '1': 'name': 'punctuation.whitespace.comment.leading.brs' 'end': '(?!\\G)' 'patterns': [ { 'begin': 'REM ' 'beginCaptures': '0': 'name': 'punctuation.definition.comment.brs' 'end': '\\n' 'name': 'comment.line.rem.brs' } ] } { 'match': '(?i:\\b(If|Then|Else|ElseIf|End If|endif|While|For|To|Each|In|Step|Case|Return|Continue|Do|Until|Loop|Next|With|Exit Do|Exit For|Exit Function|Exit Property|Exit Sub|End For)\\b)' 'name': 'keyword.control.brs' } { 'match': '=|>=|<|>|<|<>|\\+|-|\\*|\\^|&|\\b(?i:(Mod|And|Not|Or|Xor|Is))\\b' 'name': 'keyword.operator.brs' } { 'match': '(?i:\\b(Call|Class|Const|Dim|Redim|Function|Sub|End sub|End Function|Let|As)\\b)' 'name': 'storage.type.brs' } { 'match': '(?i:\\b(False|True|Invalid)\\b)' 'name': 'constant.language.brs' } { 'begin': '"' 'beginCaptures': '0': 'name': 'punctuation.definition.string.begin.brs' 'end': '"(?!")' 'endCaptures': '0': 'name': 'punctuation.definition.string.end.brs' 'name': 'string.quoted.double.brs' 'patterns': [ { 'match': '""' 'name': 'constant.character.escape.apostrophe.brs' } ] } { 'captures': '1': 'name': 'punctuation.definition.variable.brs' 'match': '(\\$)[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*?\\b' 'name': 'variable.other.brs' } { 'match': '(?i:\\b(CreateObject|type|getInterface|substitute|readASCIIFile|GetGlobalAA|Box|Run|Eval|GetLastRunCompileError|GetLastRunRuntimeError|Sleep|Wait|FindMemberFunction|Uptime|RebootSystem|ListDir|ReadAsciiFile|WriteAsciiFile|CopyFile|MoveFile|MatchFile|DeleteFile|DeleteDirectory|CreateDirectory|FormatDrive|StrTol|RunGarbageCollector|ParseJson|FormatJson)\\b)' 'name': 'support.class.collection.brs' } { 'match': '(?i:\\b(String|Integer|Object|Variant|Float|Double|Dynamic|roArray|roAssociativeArray|roBoolean|roBrSub|roByteArray|roDatagramEvent|roFloat|roGlobal|roInt|roInvalid|roList|roMessagePort)\\b)' 'name': 'support.function.brs' } { 'match': '(?i:\\b(Ucase|Lcase|Asc|Chr|Instr|Left|Len|Mid|Right|Str|Strl|String|Stringl|Val|Substitute)\\b)' 'name': 'support.function.string.brs' } { 'match': '(?i:\\b(Abs|Atn|Cdbl|Cint|Cos|Csng|Exp|Fix|Int|Log|Rnd|Sgn|Sin|Sqr|Tan)\\b)' 'name': 'support.function.math.brs' } { 'match': '\\b((0(x|X)[0-9a-fA-F]*)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f)?\\b' 'name': 'constant.numeric.brs' } { 'match': '(?-i)\\b[A-Z(_)]+\\b' 'name': 'constant.caps.brs' } { 'include': 'text.html.basic' } ] 'scopeName': 'source.brs'
36801
'comment': 'based on asp textmate bundle by <NAME>' 'fileTypes': [ 'brs' ] 'name': 'BrightScript' 'patterns': [ { 'captures': '1': 'name': 'storage.type.function.brs' '2': 'name': 'entity.name.function.brs' '3': 'name': 'punctuation.definition.parameters.brs' '4': 'name': 'variable.parameter.function.brs' '5': 'name': 'punctuation.definition.parameters.brs' 'match': '^\\s*((?i:function|sub))\\s*([a-zA-Z_]\\w*)\\s*(\\()([^)]*)(\\)).*\\n?' 'name': 'meta.function.brs' } { 'begin': '(^[ \\t]+)?(?=\')' 'beginCaptures': '1': 'name': 'punctuation.whitespace.comment.leading.brs' 'end': '(?!\\G)' 'patterns': [ { 'begin': '\'' 'beginCaptures': '0': 'name': 'punctuation.definition.comment.brs' 'end': '\\n' 'name': 'comment.line.apostrophe.brs' } ] } { 'begin': '(^[ \\t]+)?(?=REM )' 'beginCaptures': '1': 'name': 'punctuation.whitespace.comment.leading.brs' 'end': '(?!\\G)' 'patterns': [ { 'begin': 'REM ' 'beginCaptures': '0': 'name': 'punctuation.definition.comment.brs' 'end': '\\n' 'name': 'comment.line.rem.brs' } ] } { 'match': '(?i:\\b(If|Then|Else|ElseIf|End If|endif|While|For|To|Each|In|Step|Case|Return|Continue|Do|Until|Loop|Next|With|Exit Do|Exit For|Exit Function|Exit Property|Exit Sub|End For)\\b)' 'name': 'keyword.control.brs' } { 'match': '=|>=|<|>|<|<>|\\+|-|\\*|\\^|&|\\b(?i:(Mod|And|Not|Or|Xor|Is))\\b' 'name': 'keyword.operator.brs' } { 'match': '(?i:\\b(Call|Class|Const|Dim|Redim|Function|Sub|End sub|End Function|Let|As)\\b)' 'name': 'storage.type.brs' } { 'match': '(?i:\\b(False|True|Invalid)\\b)' 'name': 'constant.language.brs' } { 'begin': '"' 'beginCaptures': '0': 'name': 'punctuation.definition.string.begin.brs' 'end': '"(?!")' 'endCaptures': '0': 'name': 'punctuation.definition.string.end.brs' 'name': 'string.quoted.double.brs' 'patterns': [ { 'match': '""' 'name': 'constant.character.escape.apostrophe.brs' } ] } { 'captures': '1': 'name': 'punctuation.definition.variable.brs' 'match': '(\\$)[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*?\\b' 'name': 'variable.other.brs' } { 'match': '(?i:\\b(CreateObject|type|getInterface|substitute|readASCIIFile|GetGlobalAA|Box|Run|Eval|GetLastRunCompileError|GetLastRunRuntimeError|Sleep|Wait|FindMemberFunction|Uptime|RebootSystem|ListDir|ReadAsciiFile|WriteAsciiFile|CopyFile|MoveFile|MatchFile|DeleteFile|DeleteDirectory|CreateDirectory|FormatDrive|StrTol|RunGarbageCollector|ParseJson|FormatJson)\\b)' 'name': 'support.class.collection.brs' } { 'match': '(?i:\\b(String|Integer|Object|Variant|Float|Double|Dynamic|roArray|roAssociativeArray|roBoolean|roBrSub|roByteArray|roDatagramEvent|roFloat|roGlobal|roInt|roInvalid|roList|roMessagePort)\\b)' 'name': 'support.function.brs' } { 'match': '(?i:\\b(Ucase|Lcase|Asc|Chr|Instr|Left|Len|Mid|Right|Str|Strl|String|Stringl|Val|Substitute)\\b)' 'name': 'support.function.string.brs' } { 'match': '(?i:\\b(Abs|Atn|Cdbl|Cint|Cos|Csng|Exp|Fix|Int|Log|Rnd|Sgn|Sin|Sqr|Tan)\\b)' 'name': 'support.function.math.brs' } { 'match': '\\b((0(x|X)[0-9a-fA-F]*)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f)?\\b' 'name': 'constant.numeric.brs' } { 'match': '(?-i)\\b[A-Z(_)]+\\b' 'name': 'constant.caps.brs' } { 'include': 'text.html.basic' } ] 'scopeName': 'source.brs'
true
'comment': 'based on asp textmate bundle by PI:NAME:<NAME>END_PI' 'fileTypes': [ 'brs' ] 'name': 'BrightScript' 'patterns': [ { 'captures': '1': 'name': 'storage.type.function.brs' '2': 'name': 'entity.name.function.brs' '3': 'name': 'punctuation.definition.parameters.brs' '4': 'name': 'variable.parameter.function.brs' '5': 'name': 'punctuation.definition.parameters.brs' 'match': '^\\s*((?i:function|sub))\\s*([a-zA-Z_]\\w*)\\s*(\\()([^)]*)(\\)).*\\n?' 'name': 'meta.function.brs' } { 'begin': '(^[ \\t]+)?(?=\')' 'beginCaptures': '1': 'name': 'punctuation.whitespace.comment.leading.brs' 'end': '(?!\\G)' 'patterns': [ { 'begin': '\'' 'beginCaptures': '0': 'name': 'punctuation.definition.comment.brs' 'end': '\\n' 'name': 'comment.line.apostrophe.brs' } ] } { 'begin': '(^[ \\t]+)?(?=REM )' 'beginCaptures': '1': 'name': 'punctuation.whitespace.comment.leading.brs' 'end': '(?!\\G)' 'patterns': [ { 'begin': 'REM ' 'beginCaptures': '0': 'name': 'punctuation.definition.comment.brs' 'end': '\\n' 'name': 'comment.line.rem.brs' } ] } { 'match': '(?i:\\b(If|Then|Else|ElseIf|End If|endif|While|For|To|Each|In|Step|Case|Return|Continue|Do|Until|Loop|Next|With|Exit Do|Exit For|Exit Function|Exit Property|Exit Sub|End For)\\b)' 'name': 'keyword.control.brs' } { 'match': '=|>=|<|>|<|<>|\\+|-|\\*|\\^|&|\\b(?i:(Mod|And|Not|Or|Xor|Is))\\b' 'name': 'keyword.operator.brs' } { 'match': '(?i:\\b(Call|Class|Const|Dim|Redim|Function|Sub|End sub|End Function|Let|As)\\b)' 'name': 'storage.type.brs' } { 'match': '(?i:\\b(False|True|Invalid)\\b)' 'name': 'constant.language.brs' } { 'begin': '"' 'beginCaptures': '0': 'name': 'punctuation.definition.string.begin.brs' 'end': '"(?!")' 'endCaptures': '0': 'name': 'punctuation.definition.string.end.brs' 'name': 'string.quoted.double.brs' 'patterns': [ { 'match': '""' 'name': 'constant.character.escape.apostrophe.brs' } ] } { 'captures': '1': 'name': 'punctuation.definition.variable.brs' 'match': '(\\$)[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*?\\b' 'name': 'variable.other.brs' } { 'match': '(?i:\\b(CreateObject|type|getInterface|substitute|readASCIIFile|GetGlobalAA|Box|Run|Eval|GetLastRunCompileError|GetLastRunRuntimeError|Sleep|Wait|FindMemberFunction|Uptime|RebootSystem|ListDir|ReadAsciiFile|WriteAsciiFile|CopyFile|MoveFile|MatchFile|DeleteFile|DeleteDirectory|CreateDirectory|FormatDrive|StrTol|RunGarbageCollector|ParseJson|FormatJson)\\b)' 'name': 'support.class.collection.brs' } { 'match': '(?i:\\b(String|Integer|Object|Variant|Float|Double|Dynamic|roArray|roAssociativeArray|roBoolean|roBrSub|roByteArray|roDatagramEvent|roFloat|roGlobal|roInt|roInvalid|roList|roMessagePort)\\b)' 'name': 'support.function.brs' } { 'match': '(?i:\\b(Ucase|Lcase|Asc|Chr|Instr|Left|Len|Mid|Right|Str|Strl|String|Stringl|Val|Substitute)\\b)' 'name': 'support.function.string.brs' } { 'match': '(?i:\\b(Abs|Atn|Cdbl|Cint|Cos|Csng|Exp|Fix|Int|Log|Rnd|Sgn|Sin|Sqr|Tan)\\b)' 'name': 'support.function.math.brs' } { 'match': '\\b((0(x|X)[0-9a-fA-F]*)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f)?\\b' 'name': 'constant.numeric.brs' } { 'match': '(?-i)\\b[A-Z(_)]+\\b' 'name': 'constant.caps.brs' } { 'include': 'text.html.basic' } ] 'scopeName': 'source.brs'
[ { "context": "valid to and from parameters', ->\n to.is -> \"stenver1010@gmail.com\"\n from.is -> \"stenver1010@gmail.com\"\n\n ", "end": 456, "score": 0.9999262094497681, "start": 435, "tag": "EMAIL", "value": "stenver1010@gmail.com" }, { "context": "o.is -> \"stenver...
test/email_test.coffee
stenver/node-mailing-service
0
require './test_helper' Email = require './../lib/models/email' describe 'Email', -> to = memo().is -> from = memo().is -> cc = memo().is -> subject = memo().is -> text = memo().is -> parameters = memo().is -> {to: to(), from: from(), cc: cc(), subject: subject(), text: text()} email = memo().is -> new Email(parameters()) describe '#isValid', -> context 'with valid to and from parameters', -> to.is -> "stenver1010@gmail.com" from.is -> "stenver1010@gmail.com" it 'returns true', -> expect(email().isValid()).to.equal(true) context 'with display name on to and from', -> to.is -> "stenver <stenver1010@gmail.com>" from.is -> "stenver <stenver1010@gmail.com>" it 'returns true', -> expect(email().isValid()).to.equal(true) context 'with multiple receivers', -> to.is -> "stenver <stenver1010@gmail.com>, example <example@gmail.com>" it 'returns true', -> expect(email().isValid()).to.equal(true) context 'with invalid parameters', -> to.is -> "stenver1010" from.is -> "stenver1010" it 'returns false', -> expect(email().isValid()).to.equal(false)
165438
require './test_helper' Email = require './../lib/models/email' describe 'Email', -> to = memo().is -> from = memo().is -> cc = memo().is -> subject = memo().is -> text = memo().is -> parameters = memo().is -> {to: to(), from: from(), cc: cc(), subject: subject(), text: text()} email = memo().is -> new Email(parameters()) describe '#isValid', -> context 'with valid to and from parameters', -> to.is -> "<EMAIL>" from.is -> "<EMAIL>" it 'returns true', -> expect(email().isValid()).to.equal(true) context 'with display name on to and from', -> to.is -> "<NAME> <<EMAIL>>" from.is -> "<NAME> <<EMAIL>>" it 'returns true', -> expect(email().isValid()).to.equal(true) context 'with multiple receivers', -> to.is -> "<NAME> <<EMAIL>>, example <<EMAIL>>" it 'returns true', -> expect(email().isValid()).to.equal(true) context 'with invalid parameters', -> to.is -> "stenver1010" from.is -> "stenver1010" it 'returns false', -> expect(email().isValid()).to.equal(false)
true
require './test_helper' Email = require './../lib/models/email' describe 'Email', -> to = memo().is -> from = memo().is -> cc = memo().is -> subject = memo().is -> text = memo().is -> parameters = memo().is -> {to: to(), from: from(), cc: cc(), subject: subject(), text: text()} email = memo().is -> new Email(parameters()) describe '#isValid', -> context 'with valid to and from parameters', -> to.is -> "PI:EMAIL:<EMAIL>END_PI" from.is -> "PI:EMAIL:<EMAIL>END_PI" it 'returns true', -> expect(email().isValid()).to.equal(true) context 'with display name on to and from', -> to.is -> "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" from.is -> "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" it 'returns true', -> expect(email().isValid()).to.equal(true) context 'with multiple receivers', -> to.is -> "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>, example <PI:EMAIL:<EMAIL>END_PI>" it 'returns true', -> expect(email().isValid()).to.equal(true) context 'with invalid parameters', -> to.is -> "stenver1010" from.is -> "stenver1010" it 'returns false', -> expect(email().isValid()).to.equal(false)
[ { "context": " 'hindent:prettify-fundamental'}\n {label: 'Chris Done', command: 'hindent:prettify-chris-done'}\n ", "end": 2122, "score": 0.9983229637145996, "start": 2112, "tag": "NAME", "value": "Chris Done" }, { "context": ": 'hindent:prettify-chris-done'}\n {l...
atom/hindent.coffee
ocharles/hindent
301
{CompositeDisposable} = require 'atom' {BufferedProcess} = require 'atom' {dirname} = require 'path' {statSync} = require 'fs' prettify = (style, text, workingDirectory, {onComplete, onFailure}) -> lines = [] proc = new BufferedProcess command: 'hindent' args: ['--style', style] options: cwd: workingDirectory stdout: (line) -> lines.push(line) exit: -> onComplete?(lines.join('')) proc.onWillThrowError ({error, handle}) -> atom.notifications.addError "Hindent could not spawn", detail: "#{error}" onFailure?() handle() proc.process.stdin.write(text) proc.process.stdin.end() prettifyFile = (style, editor, format = 'haskell') -> [firstCursor, cursors...] = editor.getCursors().map (cursor) -> cursor.getBufferPosition() try workDir = dirname(editor.getPath()) if not statSync(workDir).isDirectory() workDir = '.' catch workDir = '.' prettify style, editor.getText(), workDir, onComplete: (text) -> editor.setText(text) if editor.getLastCursor()? editor.getLastCursor().setBufferPosition firstCursor, autoscroll: false cursors.forEach (cursor) -> editor.addCursorAtBufferPosition cursor, autoscroll: false module.exports = Hindent = disposables: null menu: null activate: (state) -> @disposables = new CompositeDisposable @menu = new CompositeDisposable @disposables.add \ atom.commands.add 'atom-text-editor[data-grammar~="haskell"]', 'hindent:prettify-fundamental': ({target}) => prettifyFile 'fundamental', target.getModel() 'hindent:prettify-chris-done': ({target}) => prettifyFile 'chris-done', target.getModel() 'hindent:prettify-johan-tibell': ({target}) => prettifyFile 'johan-tibell', target.getModel() 'hindent:prettify-gibiansky': ({target}) => prettifyFile 'gibiansky', target.getModel() @menu.add atom.menu.add [ label: 'hindent' submenu : [ {label: 'Fundamental', command: 'hindent:prettify-fundamental'} {label: 'Chris Done', command: 'hindent:prettify-chris-done'} {label: 'Johan Tibell', command: 'hindent:prettify-johan-tibell'} {label: 'Gibiansky', command: 'hindent:prettify-gibiansky'} ] ] deactivate: -> @disposables.dispose() @disposables = null @clearMenu() clearMenu: -> @menu.dispose() @menu = null atom.menu.update()
151490
{CompositeDisposable} = require 'atom' {BufferedProcess} = require 'atom' {dirname} = require 'path' {statSync} = require 'fs' prettify = (style, text, workingDirectory, {onComplete, onFailure}) -> lines = [] proc = new BufferedProcess command: 'hindent' args: ['--style', style] options: cwd: workingDirectory stdout: (line) -> lines.push(line) exit: -> onComplete?(lines.join('')) proc.onWillThrowError ({error, handle}) -> atom.notifications.addError "Hindent could not spawn", detail: "#{error}" onFailure?() handle() proc.process.stdin.write(text) proc.process.stdin.end() prettifyFile = (style, editor, format = 'haskell') -> [firstCursor, cursors...] = editor.getCursors().map (cursor) -> cursor.getBufferPosition() try workDir = dirname(editor.getPath()) if not statSync(workDir).isDirectory() workDir = '.' catch workDir = '.' prettify style, editor.getText(), workDir, onComplete: (text) -> editor.setText(text) if editor.getLastCursor()? editor.getLastCursor().setBufferPosition firstCursor, autoscroll: false cursors.forEach (cursor) -> editor.addCursorAtBufferPosition cursor, autoscroll: false module.exports = Hindent = disposables: null menu: null activate: (state) -> @disposables = new CompositeDisposable @menu = new CompositeDisposable @disposables.add \ atom.commands.add 'atom-text-editor[data-grammar~="haskell"]', 'hindent:prettify-fundamental': ({target}) => prettifyFile 'fundamental', target.getModel() 'hindent:prettify-chris-done': ({target}) => prettifyFile 'chris-done', target.getModel() 'hindent:prettify-johan-tibell': ({target}) => prettifyFile 'johan-tibell', target.getModel() 'hindent:prettify-gibiansky': ({target}) => prettifyFile 'gibiansky', target.getModel() @menu.add atom.menu.add [ label: 'hindent' submenu : [ {label: 'Fundamental', command: 'hindent:prettify-fundamental'} {label: '<NAME>', command: 'hindent:prettify-chris-done'} {label: '<NAME>', command: 'hindent:prettify-johan-tibell'} {label: 'G<NAME>ians<NAME>', command: 'hindent:prettify-gibiansky'} ] ] deactivate: -> @disposables.dispose() @disposables = null @clearMenu() clearMenu: -> @menu.dispose() @menu = null atom.menu.update()
true
{CompositeDisposable} = require 'atom' {BufferedProcess} = require 'atom' {dirname} = require 'path' {statSync} = require 'fs' prettify = (style, text, workingDirectory, {onComplete, onFailure}) -> lines = [] proc = new BufferedProcess command: 'hindent' args: ['--style', style] options: cwd: workingDirectory stdout: (line) -> lines.push(line) exit: -> onComplete?(lines.join('')) proc.onWillThrowError ({error, handle}) -> atom.notifications.addError "Hindent could not spawn", detail: "#{error}" onFailure?() handle() proc.process.stdin.write(text) proc.process.stdin.end() prettifyFile = (style, editor, format = 'haskell') -> [firstCursor, cursors...] = editor.getCursors().map (cursor) -> cursor.getBufferPosition() try workDir = dirname(editor.getPath()) if not statSync(workDir).isDirectory() workDir = '.' catch workDir = '.' prettify style, editor.getText(), workDir, onComplete: (text) -> editor.setText(text) if editor.getLastCursor()? editor.getLastCursor().setBufferPosition firstCursor, autoscroll: false cursors.forEach (cursor) -> editor.addCursorAtBufferPosition cursor, autoscroll: false module.exports = Hindent = disposables: null menu: null activate: (state) -> @disposables = new CompositeDisposable @menu = new CompositeDisposable @disposables.add \ atom.commands.add 'atom-text-editor[data-grammar~="haskell"]', 'hindent:prettify-fundamental': ({target}) => prettifyFile 'fundamental', target.getModel() 'hindent:prettify-chris-done': ({target}) => prettifyFile 'chris-done', target.getModel() 'hindent:prettify-johan-tibell': ({target}) => prettifyFile 'johan-tibell', target.getModel() 'hindent:prettify-gibiansky': ({target}) => prettifyFile 'gibiansky', target.getModel() @menu.add atom.menu.add [ label: 'hindent' submenu : [ {label: 'Fundamental', command: 'hindent:prettify-fundamental'} {label: 'PI:NAME:<NAME>END_PI', command: 'hindent:prettify-chris-done'} {label: 'PI:NAME:<NAME>END_PI', command: 'hindent:prettify-johan-tibell'} {label: 'GPI:NAME:<NAME>END_PIiansPI:NAME:<NAME>END_PI', command: 'hindent:prettify-gibiansky'} ] ] deactivate: -> @disposables.dispose() @disposables = null @clearMenu() clearMenu: -> @menu.dispose() @menu = null atom.menu.update()
[ { "context": "# @fileoverview Tests for no-undef rule.\n# @author Mark Macdonald\n###\n\n'use strict'\n\n#-----------------------------", "end": 70, "score": 0.9998291730880737, "start": 56, "tag": "NAME", "value": "Mark Macdonald" }, { "context": "tions of readonly are removed: http...
src/tests/rules/no-undef.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-undef rule. # @author Mark Macdonald ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-undef' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-undef', rule, valid: [ ''' a = 1 b = 2 a ''' '###global b### f = -> b' , code: '-> b', globals: b: no , ''' ###global b a:false### a -> b a ''' ''' a = -> a() ''' '(b) -> b' ''' a = null a = 1 a++ ''' ''' a = null -> a = 1 ''' '###global b:true### b++' , # '###eslint-env browser### window' code: 'window' env: browser: yes , # '###eslint-env node### require("a")' code: 'require("a")' env: node: yes , ''' Object isNaN() ''' 'toString()' 'hasOwnProperty()' ''' (stuffToEval) -> ultimateAnswer = null ultimateAnswer = 42 eval stuffToEval ''' 'typeof a' 'typeof (a)' 'b = typeof a' "typeof a is 'undefined'" "if typeof a is 'undefined' then ;" , code: ''' -> [a, b=4] = [1, 2] return {a, b} ''' , code: 'toString = 1' , code: '(...foo) -> return foo' , code: ''' React = null App = null a = 1 React.render(<App attr={a} />) ''' , code: ''' console = null [1,2,3].forEach (obj) => console.log(obj) ''' , code: ''' Foo = null class Bar extends Foo constructor: -> super() ''' , code: ''' import Warning from '../lib/warning' warn = new Warning 'text' ''' , code: ''' import * as Warning from '../lib/warning' warn = new Warning('text') ''' , code: ''' a = null [a] = [0] ''' , code: ''' a = null ({a} = {}) ''' , code: '{b: a} = {}' , code: ''' obj = null [obj.a, obj.b] = [0, 1] ''' , code: 'URLSearchParams', env: browser: yes , code: 'Intl', env: browser: yes , code: 'IntersectionObserver', env: browser: yes , code: 'Credential', env: browser: yes , code: 'requestIdleCallback', env: browser: yes , code: 'customElements', env: browser: yes , code: 'PromiseRejectionEvent', env: browser: yes , # Notifications of readonly are removed: https://github.com/eslint/eslint/issues/4504 '###global b:false### -> b = 1' , code: 'f = -> b = 1', globals: b: no , '###global b:false### -> b++' '###global b### b = 1' '###global b:false### b = 1' 'Array = 1' , # # new.target: https://github.com/eslint/eslint/issues/5420 # code: ''' # class A # constructor: -> new.target # ''' # Experimental, code: ''' {bacon, ...others} = stuff foo(others) ''' globals: stuff: no, foo: no , code: '[a] = [0]' , code: '{a} = {}' , code: '{b: a} = {}' , 'a = 1' ''' astHelpers = containsStyleSheetObject: (node) -> right = node?.init ? node?.right ''' ''' class A prop: 3 ''' ''' try catch e e ''' ''' a = null a?.get x: 10 ''' ''' @?.get x: 10 ''' ''' do (b = (c) -> c) -> a: 3 ?.a ''' ''' class A category: (type: 'string') ''' ] invalid: [ code: "if (typeof anUndefinedVar is 'string') then ;" options: [typeof: yes] errors: [message: "'anUndefinedVar' is not defined.", type: 'Identifier'] , code: 'a = b' errors: [message: "'b' is not defined.", type: 'Identifier'] , code: '-> b' errors: [message: "'b' is not defined.", type: 'Identifier'] , code: 'window' errors: [message: "'window' is not defined.", type: 'Identifier'] , code: 'require "a"' errors: [message: "'require' is not defined.", type: 'Identifier'] , code: ''' React = null React.render <img attr={a} /> ''' errors: [message: "'a' is not defined."] , code: ''' React = null App = null React.render(<App attr={a} />) ''' errors: [message: "'a' is not defined."] , code: '[obj.a, obj.b] = [0, 1]' errors: [ message: "'obj' is not defined." , message: "'obj' is not defined." ] , # Experimental code: ''' c = 0 a = {...b, c} ''' errors: [message: "'b' is not defined."] , code: ''' class A prop: b ''' errors: [message: "'b' is not defined."] , code: ''' class A [b]: 1 ''' errors: [message: "'b' is not defined."] ]
78287
###* # @fileoverview Tests for no-undef rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-undef' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-undef', rule, valid: [ ''' a = 1 b = 2 a ''' '###global b### f = -> b' , code: '-> b', globals: b: no , ''' ###global b a:false### a -> b a ''' ''' a = -> a() ''' '(b) -> b' ''' a = null a = 1 a++ ''' ''' a = null -> a = 1 ''' '###global b:true### b++' , # '###eslint-env browser### window' code: 'window' env: browser: yes , # '###eslint-env node### require("a")' code: 'require("a")' env: node: yes , ''' Object isNaN() ''' 'toString()' 'hasOwnProperty()' ''' (stuffToEval) -> ultimateAnswer = null ultimateAnswer = 42 eval stuffToEval ''' 'typeof a' 'typeof (a)' 'b = typeof a' "typeof a is 'undefined'" "if typeof a is 'undefined' then ;" , code: ''' -> [a, b=4] = [1, 2] return {a, b} ''' , code: 'toString = 1' , code: '(...foo) -> return foo' , code: ''' React = null App = null a = 1 React.render(<App attr={a} />) ''' , code: ''' console = null [1,2,3].forEach (obj) => console.log(obj) ''' , code: ''' Foo = null class Bar extends Foo constructor: -> super() ''' , code: ''' import Warning from '../lib/warning' warn = new Warning 'text' ''' , code: ''' import * as Warning from '../lib/warning' warn = new Warning('text') ''' , code: ''' a = null [a] = [0] ''' , code: ''' a = null ({a} = {}) ''' , code: '{b: a} = {}' , code: ''' obj = null [obj.a, obj.b] = [0, 1] ''' , code: 'URLSearchParams', env: browser: yes , code: 'Intl', env: browser: yes , code: 'IntersectionObserver', env: browser: yes , code: 'Credential', env: browser: yes , code: 'requestIdleCallback', env: browser: yes , code: 'customElements', env: browser: yes , code: 'PromiseRejectionEvent', env: browser: yes , # Notifications of readonly are removed: https://github.com/eslint/eslint/issues/4504 '###global b:false### -> b = 1' , code: 'f = -> b = 1', globals: b: no , '###global b:false### -> b++' '###global b### b = 1' '###global b:false### b = 1' 'Array = 1' , # # new.target: https://github.com/eslint/eslint/issues/5420 # code: ''' # class A # constructor: -> new.target # ''' # Experimental, code: ''' {bacon, ...others} = stuff foo(others) ''' globals: stuff: no, foo: no , code: '[a] = [0]' , code: '{a} = {}' , code: '{b: a} = {}' , 'a = 1' ''' astHelpers = containsStyleSheetObject: (node) -> right = node?.init ? node?.right ''' ''' class A prop: 3 ''' ''' try catch e e ''' ''' a = null a?.get x: 10 ''' ''' @?.get x: 10 ''' ''' do (b = (c) -> c) -> a: 3 ?.a ''' ''' class A category: (type: 'string') ''' ] invalid: [ code: "if (typeof anUndefinedVar is 'string') then ;" options: [typeof: yes] errors: [message: "'anUndefinedVar' is not defined.", type: 'Identifier'] , code: 'a = b' errors: [message: "'b' is not defined.", type: 'Identifier'] , code: '-> b' errors: [message: "'b' is not defined.", type: 'Identifier'] , code: 'window' errors: [message: "'window' is not defined.", type: 'Identifier'] , code: 'require "a"' errors: [message: "'require' is not defined.", type: 'Identifier'] , code: ''' React = null React.render <img attr={a} /> ''' errors: [message: "'a' is not defined."] , code: ''' React = null App = null React.render(<App attr={a} />) ''' errors: [message: "'a' is not defined."] , code: '[obj.a, obj.b] = [0, 1]' errors: [ message: "'obj' is not defined." , message: "'obj' is not defined." ] , # Experimental code: ''' c = 0 a = {...b, c} ''' errors: [message: "'b' is not defined."] , code: ''' class A prop: b ''' errors: [message: "'b' is not defined."] , code: ''' class A [b]: 1 ''' errors: [message: "'b' is not defined."] ]
true
###* # @fileoverview Tests for no-undef rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-undef' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-undef', rule, valid: [ ''' a = 1 b = 2 a ''' '###global b### f = -> b' , code: '-> b', globals: b: no , ''' ###global b a:false### a -> b a ''' ''' a = -> a() ''' '(b) -> b' ''' a = null a = 1 a++ ''' ''' a = null -> a = 1 ''' '###global b:true### b++' , # '###eslint-env browser### window' code: 'window' env: browser: yes , # '###eslint-env node### require("a")' code: 'require("a")' env: node: yes , ''' Object isNaN() ''' 'toString()' 'hasOwnProperty()' ''' (stuffToEval) -> ultimateAnswer = null ultimateAnswer = 42 eval stuffToEval ''' 'typeof a' 'typeof (a)' 'b = typeof a' "typeof a is 'undefined'" "if typeof a is 'undefined' then ;" , code: ''' -> [a, b=4] = [1, 2] return {a, b} ''' , code: 'toString = 1' , code: '(...foo) -> return foo' , code: ''' React = null App = null a = 1 React.render(<App attr={a} />) ''' , code: ''' console = null [1,2,3].forEach (obj) => console.log(obj) ''' , code: ''' Foo = null class Bar extends Foo constructor: -> super() ''' , code: ''' import Warning from '../lib/warning' warn = new Warning 'text' ''' , code: ''' import * as Warning from '../lib/warning' warn = new Warning('text') ''' , code: ''' a = null [a] = [0] ''' , code: ''' a = null ({a} = {}) ''' , code: '{b: a} = {}' , code: ''' obj = null [obj.a, obj.b] = [0, 1] ''' , code: 'URLSearchParams', env: browser: yes , code: 'Intl', env: browser: yes , code: 'IntersectionObserver', env: browser: yes , code: 'Credential', env: browser: yes , code: 'requestIdleCallback', env: browser: yes , code: 'customElements', env: browser: yes , code: 'PromiseRejectionEvent', env: browser: yes , # Notifications of readonly are removed: https://github.com/eslint/eslint/issues/4504 '###global b:false### -> b = 1' , code: 'f = -> b = 1', globals: b: no , '###global b:false### -> b++' '###global b### b = 1' '###global b:false### b = 1' 'Array = 1' , # # new.target: https://github.com/eslint/eslint/issues/5420 # code: ''' # class A # constructor: -> new.target # ''' # Experimental, code: ''' {bacon, ...others} = stuff foo(others) ''' globals: stuff: no, foo: no , code: '[a] = [0]' , code: '{a} = {}' , code: '{b: a} = {}' , 'a = 1' ''' astHelpers = containsStyleSheetObject: (node) -> right = node?.init ? node?.right ''' ''' class A prop: 3 ''' ''' try catch e e ''' ''' a = null a?.get x: 10 ''' ''' @?.get x: 10 ''' ''' do (b = (c) -> c) -> a: 3 ?.a ''' ''' class A category: (type: 'string') ''' ] invalid: [ code: "if (typeof anUndefinedVar is 'string') then ;" options: [typeof: yes] errors: [message: "'anUndefinedVar' is not defined.", type: 'Identifier'] , code: 'a = b' errors: [message: "'b' is not defined.", type: 'Identifier'] , code: '-> b' errors: [message: "'b' is not defined.", type: 'Identifier'] , code: 'window' errors: [message: "'window' is not defined.", type: 'Identifier'] , code: 'require "a"' errors: [message: "'require' is not defined.", type: 'Identifier'] , code: ''' React = null React.render <img attr={a} /> ''' errors: [message: "'a' is not defined."] , code: ''' React = null App = null React.render(<App attr={a} />) ''' errors: [message: "'a' is not defined."] , code: '[obj.a, obj.b] = [0, 1]' errors: [ message: "'obj' is not defined." , message: "'obj' is not defined." ] , # Experimental code: ''' c = 0 a = {...b, c} ''' errors: [message: "'b' is not defined."] , code: ''' class A prop: b ''' errors: [message: "'b' is not defined."] , code: ''' class A [b]: 1 ''' errors: [message: "'b' is not defined."] ]
[ { "context": "KNAME_MAX_LENGTH\n # username = req.body.username\n password = req.body.password\n verif", "end": 5581, "score": 0.8745445609092712, "start": 5573, "tag": "USERNAME", "value": "username" }, { "context": " = req.body.username\n password ...
src/routes/user.coffee
lly5401/dhcseltalkserver
1
express = require 'express' co = require 'co' _ = require 'underscore' moment = require 'moment' rongCloud = require 'rongcloud-sdk' qiniu = require 'qiniu' Config = require '../conf' Session = require '../util/session' Utility = require('../util/util').Utility APIResult = require('../util/util').APIResult # 引用数据库对象和模型 [sequelize, User, Blacklist, Friendship, Group, GroupMember, GroupSync, DataVersion, VerificationCode, LoginLog] = require '../db' MAX_GROUP_MEMBER_COUNT = 500 NICKNAME_MIN_LENGTH = 1 NICKNAME_MAX_LENGTH = 32 PORTRAIT_URI_MIN_LENGTH = 12 PORTRAIT_URI_MAX_LENGTH = 256 PASSWORD_MIN_LENGTH = 6 PASSWORD_MAX_LENGTH = 20 # 初始化融云 Server API SDK rongCloud.init Config.RONGCLOUD_APP_KEY, Config.RONGCLOUD_APP_SECRET router = express.Router() validator = sequelize.Validator # 国际电话区号和国家代码对应关系 regionMap = '86': 'zh-CN' # 获取新 Token 并更新到数据库 getToken = (userId, nickname, portraitUri) -> new Promise (resolve, reject) -> rongCloud.user.getToken Utility.encodeId(userId), nickname, portraitUri, (err, resultText) -> if err return reject err result = JSON.parse resultText if result.code isnt 200 return reject new Error 'RongCloud Server API Error Code: ' + result.code # 更新到数据库 User.update rongCloudToken: result.token , where: id: userId .then -> resolve result.token .catch (error) -> reject error # 发送验证码 router.post '/send_code', (req, res, next) -> region = req.body.region phone = req.body.phone # 如果在融云开发者后台开启图形验证码,需要校验 verifyId 和 verifyCode。 # verifyId = req.body.verify_id # verifyCode = req.body.verify_code # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone.toString(), regionMap[region] return res.status(400).send 'Invalid region and phone number.' VerificationCode.getByPhone region, phone .then (verification) -> if verification timeDiff = Math.floor((Date.now() - verification.updatedAt.getTime()) / 1000) # 频率限制为 1 分钟 1 条,开发测试环境中 5 秒 1 条 if req.app.get('env') is 'development' subtraction = moment().subtract(5, 's') else subtraction = moment().subtract(1, 'm') if subtraction.isBefore verification.updatedAt return res.send new APIResult 5000, null, 'Throttle limit exceeded.' code = _.random 1000, 9999 # 生产环境下才发送短信 if req.app.get('env') is 'development' VerificationCode.upsert region: region phone: phone sessionId: '' .then -> return res.send new APIResult 200 else # 需要在融云开发者后台申请短信验证码签名,然后选择短信模板 Id rongCloud.sms.sendCode region, phone, Config.RONGCLOUD_SMS_REGISTER_TEMPLATE_ID, (err, resultText) -> if err return next err result = JSON.parse resultText if result.code isnt 200 return next new Error 'RongCloud Server API Error Code: ' + result.code VerificationCode.upsert region: region phone: phone sessionId: result.sessionId .then -> res.send new APIResult 200 .catch next # 验证验证码 router.post '/verify_code', (req, res, next) -> phone = req.body.phone region = req.body.region code = req.body.code # TODO: 频率限制,防止爆破 VerificationCode.getByPhone region, phone .then (verification) -> if not verification return res.status(404).send 'Unknown phone number.' # 验证码过期时间为 2 分钟 else if moment().subtract(2, 'm').isAfter verification.updatedAt res.send new APIResult 2000, null, 'Verification code expired.' # 开发环境下支持万能验证码 else if req.app.get('env') is 'development' and code is '9999' res.send new APIResult 200, verification_token: verification.token else rongCloud.sms.verifyCode verification.sessionId, code, (err, resultText) -> if err # Hack for invalid 430 HTTP status code to avoid unuseful error log. errorMessage = err.message if errorMessage is 'Unsuccessful HTTP response' or errorMessage is 'Too Many Requests' return res.status(err.statusCode).send errorMessage else return next err result = JSON.parse resultText if result.code isnt 200 return next new Error 'RongCloud Server API Error Code: ' + result.code if result.success res.send new APIResult 200, verification_token: verification.token else res.send new APIResult 1000, null, 'Invalid verification code.' .catch next # # 检查用户名是否可以注册 # router.post '/check_username_available', (req, res, next) -> # username = req.body.username # # User.checkUsernameAvailable username # .then (result) -> # if result # res.send new APIResult 200, true # else # res.send new APIResult 200, false, 'Username has already existed.' # .catch next # 检查手机号是否可以注册 router.post '/check_phone_available', (req, res, next) -> region = req.body.region phone = req.body.phone # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone.toString(), regionMap[region] return res.status(400).send 'Invalid region and phone number.' User.checkPhoneAvailable region, phone .then (result) -> if result res.send new APIResult 200, true else res.send new APIResult 200, false, 'Phone number has already existed.' .catch next # 用户注册 router.post '/register', (req, res, next) -> nickname = Utility.xss req.body.nickname, NICKNAME_MAX_LENGTH # username = req.body.username password = req.body.password verificationToken = req.body.verification_token if password.indexOf(' ') > 0 return res.status(400).send 'Password must have no space.' if not validator.isLength nickname, NICKNAME_MIN_LENGTH, NICKNAME_MAX_LENGTH return res.status(400).send 'Length of nickname invalid.' if not validator.isLength password, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH return res.status(400).send 'Length of password invalid.' if not validator.isUUID verificationToken return res.status(400).send 'Invalid verification_token.' VerificationCode.getByToken verificationToken .then (verification) -> if not verification return res.status(404).send 'Unknown verification_token.' # User.checkUsernameAvailable username # .then (result) -> # if result User.checkPhoneAvailable verification.region, verification.phone .then (result) -> if result salt = Utility.random 1000, 9999 hash = Utility.hash password, salt sequelize.transaction (t) -> User.create nickname: nickname # username: username region: verification.region phone: verification.phone passwordHash: hash passwordSalt: salt.toString() , transaction: t .then (user) -> DataVersion.create userId: user.id, transaction: t .then -> Session.setAuthCookie res, user.id Session.setNicknameToCache user.id, nickname res.send new APIResult 200, Utility.encodeResults id: user.id else res.status(400).send 'Phone number has already existed.' # else # res.status(403).send 'Username has already existed.' .catch next # 用户登录 router.post '/login', (req, res, next) -> region = req.body.region phone = req.body.phone password = req.body.password # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone, regionMap[region] return res.status(400).send 'Invalid region and phone number.' User.findOne where: region: region phone: phone attributes: [ 'id' 'passwordHash' 'passwordSalt' 'nickname' 'portraitUri' 'rongCloudToken' ] .then (user) -> errorMessage = 'Invalid phone or password.' if not user res.send new APIResult 1000, null, errorMessage else # passwordHash = Utility.hash password, user.passwordSalt # if passwordHash isnt user.passwordHash # return res.send new APIResult 1000, null, errorMessage Session.setAuthCookie res, user.id Session.setNicknameToCache user.id, user.nickname GroupMember.findAll where: memberId: user.id attributes: [] include: model: Group where: deletedAt: null attributes: [ 'id' 'name' ] .then (groups) -> Utility.log 'Sync groups: %j', groups groupIdNamePairs = {} groups.forEach (group) -> groupIdNamePairs[Utility.encodeId(group.group.id)] = group.group.name Utility.log 'Sync groups: %j', groupIdNamePairs rongCloud.group.sync Utility.encodeId(user.id), groupIdNamePairs, (err, resultText) -> if err Utility.logError 'Error sync user\'s group list failed: %s', err .catch (error) -> Utility.logError 'Sync groups error: ', error if user.rongCloudToken is '' if req.app.get('env') is 'development' return res.send new APIResult 200, Utility.encodeResults id: user.id, token: 'fake token' getToken user.id, user.nickname, user.portraitUri .then (token) -> res.send new APIResult 200, Utility.encodeResults id: user.id, token: token else res.send new APIResult 200, Utility.encodeResults id: user.id, token: user.rongCloudToken .catch next # 用户注销 router.post '/logout', (req, res) -> res.clearCookie Config.AUTH_COOKIE_NAME res.send new APIResult 200 # 通过手机验证码设置新密码 router.post '/reset_password', (req, res, next) -> password = req.body.password verificationToken = req.body.verification_token if (password.indexOf(' ') != -1) return res.status(400).send 'Password must have no space.' if not validator.isLength password, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH return res.status(400).send 'Length of password invalid.' if not validator.isUUID verificationToken return res.status(400).send 'Invalid verification_token.' VerificationCode.getByToken verificationToken .then (verification) -> if not verification return res.status(404).send 'Unknown verification_token.' salt = _.random 1000, 9999 hash = Utility.hash password, salt User.update passwordHash: hash passwordSalt: salt.toString() , where: region: verification.region phone: verification.phone .then -> res.send new APIResult 200 .catch next # 当前用户通过旧密码设置新密码 router.post '/change_password', (req, res, next) -> newPassword = req.body.newPassword oldPassword = req.body.oldPassword if (newPassword.indexOf(' ') != -1) return res.status(400).send 'New password must have no space.' if not validator.isLength newPassword, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH return res.status(400).send 'Invalid new password length.' User.findById Session.getCurrentUserId req, attributes: [ 'id' 'passwordHash' 'passwordSalt' ] .then (user) -> oldHash = Utility.hash oldPassword, user.passwordSalt if oldHash isnt user.passwordHash return res.send new APIResult 1000, null, 'Wrong old password.' newSalt = _.random 1000, 9999 newHash = Utility.hash newPassword, newSalt user.update passwordHash: newHash passwordSalt: newSalt.toString() .then -> res.send new APIResult 200 .catch next # 设置自己的昵称 router.post '/set_nickname', (req, res, next) -> nickname = Utility.xss req.body.nickname, NICKNAME_MAX_LENGTH if not validator.isLength nickname, NICKNAME_MIN_LENGTH, NICKNAME_MAX_LENGTH return res.status(400).send 'Invalid nickname length.' currentUserId = Session.getCurrentUserId req timestamp = Date.now() User.update nickname: nickname timestamp: timestamp , where: id: currentUserId .then -> # 更新到融云服务器 rongCloud.user.refresh Utility.encodeId(currentUserId), nickname, null, (err, resultText) -> if err Utility.logError 'RongCloud Server API Error: ', err.message result = JSON.parse resultText if result.code isnt 200 Utility.logError 'RongCloud Server API Error Code: ', result.code Session.setNicknameToCache currentUserId, nickname Promise.all [ DataVersion.updateUserVersion currentUserId, timestamp , DataVersion.updateAllFriendshipVersion currentUserId, timestamp ] .then -> res.send new APIResult 200 .catch next # 设置用户头像地址 router.post '/set_portrait_uri', (req, res, next) -> portraitUri = Utility.xss req.body.portraitUri, PORTRAIT_URI_MAX_LENGTH if not validator.isURL portraitUri, { protocols: ['http', 'https'], require_protocol: true } return res.status(400).send 'Invalid portraitUri format.' if not validator.isLength portraitUri, PORTRAIT_URI_MIN_LENGTH, PORTRAIT_URI_MAX_LENGTH return res.status(400).send 'Invalid portraitUri length.' currentUserId = Session.getCurrentUserId req timestamp = Date.now() User.update portraitUri: portraitUri timestamp: timestamp , where: id: currentUserId .then -> # 更新到融云服务器 rongCloud.user.refresh Utility.encodeId(currentUserId), null, portraitUri, (err, resultText) -> if err Utility.logError 'RongCloud Server API Error: ', err.message result = JSON.parse resultText if result.code isnt 200 Utility.logError 'RongCloud Server API Error Code: ', result.code Promise.all [ DataVersion.updateUserVersion currentUserId, timestamp , DataVersion.updateAllFriendshipVersion currentUserId, timestamp ] .then -> res.send new APIResult 200 .catch next # 将好友加入黑名单 router.post '/add_to_blacklist', (req, res, next) -> friendId = req.body.friendId encodedFriendId = req.body.encodedFriendId currentUserId = Session.getCurrentUserId req timestamp = Date.now() User.checkUserExists friendId .then (result) -> if result # 先调用融云服务器接口 rongCloud.user.blacklist.add Utility.encodeId(currentUserId), encodedFriendId, (err, resultText) -> # 如果失败直接返回,不保存到数据库 if err next err else Blacklist.upsert userId: currentUserId friendId: friendId status: true timestamp: timestamp .then -> # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp .then -> res.send new APIResult 200 else res.status(404).send 'friendId is not an available userId.' .catch next # 将好友从黑名单中移除 router.post '/remove_from_blacklist', (req, res, next) -> friendId = req.body.friendId encodedFriendId = req.body.encodedFriendId currentUserId = Session.getCurrentUserId req timestamp = Date.now() # 先调用融云服务器接口 rongCloud.user.blacklist.remove Utility.encodeId(currentUserId), encodedFriendId, (err, resultText) -> # 如果失败直接返回,不保存到数据库 if err next err else Blacklist.update status: false timestamp: timestamp , where: userId: currentUserId friendId: friendId .then -> # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp .then -> res.send new APIResult 200 .catch next # 上传用户通讯录 router.post '/upload_contacts', (req, res, next) -> contacts = req.body # TODO: Not implements. res.status(404).send 'Not implements.' # 获取融云 Token router.get '/get_token', (req, res, next) -> User.findById Session.getCurrentUserId req, attributes: [ 'id' 'nickname' 'portraitUri' ] .then (user) -> # 调用 Server API SDK 获取 Token getToken user.id, user.nickname, user.portraitUri .then (token) -> res.send new APIResult 200, Utility.encodeResults { userId: user.id, token: token }, 'userId' .catch next # 获取云存储所用 Token router.get '/get_image_token', (req, res, next) -> qiniu.conf.ACCESS_KEY = Config.QINIU_ACCESS_KEY qiniu.conf.SECRET_KEY = Config.QINIU_SECRET_KEY putPolicy = new qiniu.rs.PutPolicy Config.QINIU_BUCKET_NAME token = putPolicy.token() res.send new APIResult 200, { target: 'qiniu', domain: Config.QINIU_BUCKET_DOMAIN, token: token } # 获取短信图形验证码 router.get '/get_sms_img_code', (req, res, next) -> rongCloud.sms.getImgCode Config.RONGCLOUD_APP_KEY, (err, resultText) -> if err return next err result = JSON.parse resultText if result.code isnt 200 return next new Error 'RongCloud Server API Error Code: ' + result.code res.send new APIResult 200, { url: result.url, verifyId: result.verifyId } # 获取当前用户黑名单列表 router.get '/blacklist', (req, res, next) -> currentUserId = Session.getCurrentUserId req timestamp = Date.now() Blacklist.findAll where: userId: currentUserId friendId: $ne: 0 status: true attributes: [] include: model: User attributes: [ 'id' 'nickname' 'portraitUri' 'updatedAt' # 为节约服务端资源,客户端自己按照 updatedAt 排序 ] .then (dbBlacklist) -> # 调用融云服务器接口,获取服务端数据,并和本地做同步 rongCloud.user.blacklist.query Utility.encodeId(currentUserId), (err, resultText) -> if err # 如果失败直接忽略 Utility.logError 'Error: request server blacklist failed: %s', err else result = JSON.parse(resultText) if result.code is 200 hasDirtyData = false serverBlacklistUserIds = result.users dbBlacklistUserIds = dbBlacklist.map (blacklist) -> if blacklist.user blacklist.user.id else hasDirtyData = true null # 如果有脏数据,输出到 Log 中 if hasDirtyData Utility.log 'Dirty blacklist data %j', dbBlacklist # 检查和修复数据库中黑名单数据的缺失 serverBlacklistUserIds.forEach (encodedUserId) -> userId = Utility.decodeIds encodedUserId if dbBlacklistUserIds.indexOf(userId) is -1 # 数据库中缺失,添加上这个数据 Blacklist.create userId: currentUserId friendId: userId status: true timestamp: timestamp .then -> # 不需要处理成功和失败回调 Utility.log 'Sync: fix user blacklist, add %s -> %s from db.', currentUserId, userId # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp .catch -> # 可能会有云端的脏数据,导致 userId 不存在,直接忽略了 # 检查和修复数据库中黑名单脏数据(多余) dbBlacklistUserIds.forEach (userId) -> if userId and serverBlacklistUserIds.indexOf(Utility.encodeId(userId)) is -1 # 数据库中的脏数据,删除掉 Blacklist.update status: false timestamp: timestamp , where: userId: currentUserId friendId: userId .then -> Utility.log 'Sync: fix user blacklist, remove %s -> %s from db.', currentUserId, userId # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp res.send new APIResult 200, Utility.encodeResults dbBlacklist, [['user', 'id']] .catch next # 获取当前用户所属群组列表 router.get '/groups', (req, res, next) -> GroupMember.findAll where: memberId: Session.getCurrentUserId req attributes: [ 'role' ] include: [ model: Group attributes: [ 'id' 'name' 'portraitUri' 'creatorId' 'memberCount' 'maxMemberCount' ] ] .then (groups) -> res.send new APIResult 200, Utility.encodeResults groups, [['group', 'id'], ['group', 'creatorId']] .catch next # 同步用户的好友、黑名单、群组、群组成员数据 # 客户端的调用时机:客户端打开时 router.get '/sync/:version', (req, res, next) -> version = req.params.version if not validator.isInt version return res.status(400).send 'Version parameter is not integer.' user = blacklist = friends = groups = groupMembers = null maxVersions = [] currentUserId = Session.getCurrentUserId req DataVersion.findById currentUserId .then (dataVersion) -> co -> # 获取变化的用户(自己)信息 if dataVersion.userVersion > version user = yield User.findById currentUserId, attributes: [ 'id' 'nickname' 'portraitUri' 'timestamp' ] # 获取变化的黑名单信息 if dataVersion.blacklistVersion > version blacklist = yield Blacklist.findAll where: userId: currentUserId timestamp: $gt: version attributes: [ 'friendId' 'status' 'timestamp' ] # 获取变化的好友信息 if dataVersion.friendshipVersion > version friends = yield Friendship.findAll where: userId: currentUserId timestamp: $gt: version attributes: [ 'friendId' 'displayName' 'status' 'timestamp' ] # 获取变化的当前用户加入的群组信息 if dataVersion.groupVersion > version groups = yield GroupMember.findAll where: memberId: currentUserId timestamp: $gt: version attributes: [ 'displayName' 'role' 'isDeleted' ] include: [ model: Group attributes: [ 'id' 'name' 'portraitUri' 'timestamp' ] ] # 获取变化的当前用户加入的群组成员信息 if dataVersion.groupVersion > version groupMembers = yield GroupMember.findAll where: memberId: currentUserId timestamp: $gt: version attributes: [ 'groupId' 'memberId' 'displayName' 'role' 'isDeleted' 'timestamp' ] include: [ model: User attributes: [ 'nickname' 'portraitUri' ] ] maxVersions.push(user.timestamp) if user maxVersions.push(_.max(blacklist, (item) -> item.timestamp).timestamp) if blacklist maxVersions.push(_.max(friends, (item) -> item.timestamp).timestamp) if friends maxVersions.push(_.max(groups, (item) -> item.group.timestamp).group.timestamp) if groups maxVersions.push(_.max(groupMembers, (item) -> item.timestamp).timestamp) if groupMembers Utility.log 'maxVersions: %j', maxVersions res.send new APIResult 200, version: _.max(maxVersions) # 最大的版本号 user: user blacklist: blacklist friends: friends groups: groups group_members: groupMembers .catch next # 批量获取用户信息 router.get '/batch', (req, res, next) -> ids = req.query.id ids = [ids] if not Array.isArray ids ids = Utility.decodeIds ids User.findAll where: id: $in: ids attributes: [ 'id' 'nickname' 'portraitUri' ] .then (users) -> res.send new APIResult 200, Utility.encodeResults users .catch next # 获取用户信息 router.get '/:id', (req, res, next) -> userId = req.params.id userId = Utility.decodeIds userId User.findById userId, attributes: [ 'id' 'nickname' 'portraitUri' ] .then (user) -> if not user return res.status(404).send 'Unknown user.' res.send new APIResult 200, Utility.encodeResults user .catch next # 根据手机号查找用户信息 router.get '/find/:region/:phone', (req, res, next) -> region = req.params.region phone = req.params.phone # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone, regionMap[region] return res.status(400).send 'Invalid region and phone number.' User.findOne where: region: region phone: phone attributes: [ 'id' 'nickname' 'portraitUri' ] .then (user) -> if not user return res.status(404).send 'Unknown user.' res.send new APIResult 200, Utility.encodeResults user .catch next module.exports = router
155425
express = require 'express' co = require 'co' _ = require 'underscore' moment = require 'moment' rongCloud = require 'rongcloud-sdk' qiniu = require 'qiniu' Config = require '../conf' Session = require '../util/session' Utility = require('../util/util').Utility APIResult = require('../util/util').APIResult # 引用数据库对象和模型 [sequelize, User, Blacklist, Friendship, Group, GroupMember, GroupSync, DataVersion, VerificationCode, LoginLog] = require '../db' MAX_GROUP_MEMBER_COUNT = 500 NICKNAME_MIN_LENGTH = 1 NICKNAME_MAX_LENGTH = 32 PORTRAIT_URI_MIN_LENGTH = 12 PORTRAIT_URI_MAX_LENGTH = 256 PASSWORD_MIN_LENGTH = 6 PASSWORD_MAX_LENGTH = 20 # 初始化融云 Server API SDK rongCloud.init Config.RONGCLOUD_APP_KEY, Config.RONGCLOUD_APP_SECRET router = express.Router() validator = sequelize.Validator # 国际电话区号和国家代码对应关系 regionMap = '86': 'zh-CN' # 获取新 Token 并更新到数据库 getToken = (userId, nickname, portraitUri) -> new Promise (resolve, reject) -> rongCloud.user.getToken Utility.encodeId(userId), nickname, portraitUri, (err, resultText) -> if err return reject err result = JSON.parse resultText if result.code isnt 200 return reject new Error 'RongCloud Server API Error Code: ' + result.code # 更新到数据库 User.update rongCloudToken: result.token , where: id: userId .then -> resolve result.token .catch (error) -> reject error # 发送验证码 router.post '/send_code', (req, res, next) -> region = req.body.region phone = req.body.phone # 如果在融云开发者后台开启图形验证码,需要校验 verifyId 和 verifyCode。 # verifyId = req.body.verify_id # verifyCode = req.body.verify_code # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone.toString(), regionMap[region] return res.status(400).send 'Invalid region and phone number.' VerificationCode.getByPhone region, phone .then (verification) -> if verification timeDiff = Math.floor((Date.now() - verification.updatedAt.getTime()) / 1000) # 频率限制为 1 分钟 1 条,开发测试环境中 5 秒 1 条 if req.app.get('env') is 'development' subtraction = moment().subtract(5, 's') else subtraction = moment().subtract(1, 'm') if subtraction.isBefore verification.updatedAt return res.send new APIResult 5000, null, 'Throttle limit exceeded.' code = _.random 1000, 9999 # 生产环境下才发送短信 if req.app.get('env') is 'development' VerificationCode.upsert region: region phone: phone sessionId: '' .then -> return res.send new APIResult 200 else # 需要在融云开发者后台申请短信验证码签名,然后选择短信模板 Id rongCloud.sms.sendCode region, phone, Config.RONGCLOUD_SMS_REGISTER_TEMPLATE_ID, (err, resultText) -> if err return next err result = JSON.parse resultText if result.code isnt 200 return next new Error 'RongCloud Server API Error Code: ' + result.code VerificationCode.upsert region: region phone: phone sessionId: result.sessionId .then -> res.send new APIResult 200 .catch next # 验证验证码 router.post '/verify_code', (req, res, next) -> phone = req.body.phone region = req.body.region code = req.body.code # TODO: 频率限制,防止爆破 VerificationCode.getByPhone region, phone .then (verification) -> if not verification return res.status(404).send 'Unknown phone number.' # 验证码过期时间为 2 分钟 else if moment().subtract(2, 'm').isAfter verification.updatedAt res.send new APIResult 2000, null, 'Verification code expired.' # 开发环境下支持万能验证码 else if req.app.get('env') is 'development' and code is '9999' res.send new APIResult 200, verification_token: verification.token else rongCloud.sms.verifyCode verification.sessionId, code, (err, resultText) -> if err # Hack for invalid 430 HTTP status code to avoid unuseful error log. errorMessage = err.message if errorMessage is 'Unsuccessful HTTP response' or errorMessage is 'Too Many Requests' return res.status(err.statusCode).send errorMessage else return next err result = JSON.parse resultText if result.code isnt 200 return next new Error 'RongCloud Server API Error Code: ' + result.code if result.success res.send new APIResult 200, verification_token: verification.token else res.send new APIResult 1000, null, 'Invalid verification code.' .catch next # # 检查用户名是否可以注册 # router.post '/check_username_available', (req, res, next) -> # username = req.body.username # # User.checkUsernameAvailable username # .then (result) -> # if result # res.send new APIResult 200, true # else # res.send new APIResult 200, false, 'Username has already existed.' # .catch next # 检查手机号是否可以注册 router.post '/check_phone_available', (req, res, next) -> region = req.body.region phone = req.body.phone # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone.toString(), regionMap[region] return res.status(400).send 'Invalid region and phone number.' User.checkPhoneAvailable region, phone .then (result) -> if result res.send new APIResult 200, true else res.send new APIResult 200, false, 'Phone number has already existed.' .catch next # 用户注册 router.post '/register', (req, res, next) -> nickname = Utility.xss req.body.nickname, NICKNAME_MAX_LENGTH # username = req.body.username password = <PASSWORD> verificationToken = req.body.verification_token if password.indexOf(' ') > 0 return res.status(400).send 'Password must have no space.' if not validator.isLength nickname, NICKNAME_MIN_LENGTH, NICKNAME_MAX_LENGTH return res.status(400).send 'Length of nickname invalid.' if not validator.isLength password, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH return res.status(400).send 'Length of password invalid.' if not validator.isUUID verificationToken return res.status(400).send 'Invalid verification_token.' VerificationCode.getByToken verificationToken .then (verification) -> if not verification return res.status(404).send 'Unknown verification_token.' # User.checkUsernameAvailable username # .then (result) -> # if result User.checkPhoneAvailable verification.region, verification.phone .then (result) -> if result salt = Utility.random 1000, 9999 hash = Utility.hash password, salt sequelize.transaction (t) -> User.create nickname: nickname # username: username region: verification.region phone: verification.phone passwordHash: hash passwordSalt: salt.toString() , transaction: t .then (user) -> DataVersion.create userId: user.id, transaction: t .then -> Session.setAuthCookie res, user.id Session.setNicknameToCache user.id, nickname res.send new APIResult 200, Utility.encodeResults id: user.id else res.status(400).send 'Phone number has already existed.' # else # res.status(403).send 'Username has already existed.' .catch next # 用户登录 router.post '/login', (req, res, next) -> region = req.body.region phone = req.body.phone password = req.body.password # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone, regionMap[region] return res.status(400).send 'Invalid region and phone number.' User.findOne where: region: region phone: phone attributes: [ 'id' 'passwordHash' 'passwordSalt' 'nickname' 'portraitUri' 'rongCloudToken' ] .then (user) -> errorMessage = 'Invalid phone or password.' if not user res.send new APIResult 1000, null, errorMessage else # passwordHash = Utility.hash password, user.passwordSalt # if passwordHash isnt user.passwordHash # return res.send new APIResult 1000, null, errorMessage Session.setAuthCookie res, user.id Session.setNicknameToCache user.id, user.nickname GroupMember.findAll where: memberId: user.id attributes: [] include: model: Group where: deletedAt: null attributes: [ 'id' 'name' ] .then (groups) -> Utility.log 'Sync groups: %j', groups groupIdNamePairs = {} groups.forEach (group) -> groupIdNamePairs[Utility.encodeId(group.group.id)] = group.group.name Utility.log 'Sync groups: %j', groupIdNamePairs rongCloud.group.sync Utility.encodeId(user.id), groupIdNamePairs, (err, resultText) -> if err Utility.logError 'Error sync user\'s group list failed: %s', err .catch (error) -> Utility.logError 'Sync groups error: ', error if user.rongCloudToken is '' if req.app.get('env') is 'development' return res.send new APIResult 200, Utility.encodeResults id: user.id, token: 'fake token' getToken user.id, user.nickname, user.portraitUri .then (token) -> res.send new APIResult 200, Utility.encodeResults id: user.id, token: token else res.send new APIResult 200, Utility.encodeResults id: user.id, token: user.rongCloudToken .catch next # 用户注销 router.post '/logout', (req, res) -> res.clearCookie Config.AUTH_COOKIE_NAME res.send new APIResult 200 # 通过手机验证码设置新密码 router.post '/reset_password', (req, res, next) -> password = req.body.password verificationToken = req.body.verification_token if (password.indexOf(' ') != -1) return res.status(400).send 'Password must have no space.' if not validator.isLength password, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH return res.status(400).send 'Length of password invalid.' if not validator.isUUID verificationToken return res.status(400).send 'Invalid verification_token.' VerificationCode.getByToken verificationToken .then (verification) -> if not verification return res.status(404).send 'Unknown verification_token.' salt = _.random 1000, 9999 hash = Utility.hash password, salt User.update passwordHash: hash passwordSalt: salt.toString() , where: region: verification.region phone: verification.phone .then -> res.send new APIResult 200 .catch next # 当前用户通过旧密码设置新密码 router.post '/change_password', (req, res, next) -> newPassword = req.body.newPassword oldPassword = req.body.oldPassword if (newPassword.indexOf(' ') != -1) return res.status(400).send 'New password must have no space.' if not validator.isLength newPassword, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH return res.status(400).send 'Invalid new password length.' User.findById Session.getCurrentUserId req, attributes: [ 'id' 'passwordHash' 'passwordSalt' ] .then (user) -> oldHash = Utility.hash oldPassword, user.passwordSalt if oldHash isnt user.passwordHash return res.send new APIResult 1000, null, 'Wrong old password.' newSalt = _.random 1000, 9999 newHash = Utility.hash newPassword, newSalt user.update passwordHash: newHash passwordSalt: newSalt.toString() .then -> res.send new APIResult 200 .catch next # 设置自己的昵称 router.post '/set_nickname', (req, res, next) -> nickname = Utility.xss req.body.nickname, NICKNAME_MAX_LENGTH if not validator.isLength nickname, NICKNAME_MIN_LENGTH, NICKNAME_MAX_LENGTH return res.status(400).send 'Invalid nickname length.' currentUserId = Session.getCurrentUserId req timestamp = Date.now() User.update nickname: nickname timestamp: timestamp , where: id: currentUserId .then -> # 更新到融云服务器 rongCloud.user.refresh Utility.encodeId(currentUserId), nickname, null, (err, resultText) -> if err Utility.logError 'RongCloud Server API Error: ', err.message result = JSON.parse resultText if result.code isnt 200 Utility.logError 'RongCloud Server API Error Code: ', result.code Session.setNicknameToCache currentUserId, nickname Promise.all [ DataVersion.updateUserVersion currentUserId, timestamp , DataVersion.updateAllFriendshipVersion currentUserId, timestamp ] .then -> res.send new APIResult 200 .catch next # 设置用户头像地址 router.post '/set_portrait_uri', (req, res, next) -> portraitUri = Utility.xss req.body.portraitUri, PORTRAIT_URI_MAX_LENGTH if not validator.isURL portraitUri, { protocols: ['http', 'https'], require_protocol: true } return res.status(400).send 'Invalid portraitUri format.' if not validator.isLength portraitUri, PORTRAIT_URI_MIN_LENGTH, PORTRAIT_URI_MAX_LENGTH return res.status(400).send 'Invalid portraitUri length.' currentUserId = Session.getCurrentUserId req timestamp = Date.now() User.update portraitUri: portraitUri timestamp: timestamp , where: id: currentUserId .then -> # 更新到融云服务器 rongCloud.user.refresh Utility.encodeId(currentUserId), null, portraitUri, (err, resultText) -> if err Utility.logError 'RongCloud Server API Error: ', err.message result = JSON.parse resultText if result.code isnt 200 Utility.logError 'RongCloud Server API Error Code: ', result.code Promise.all [ DataVersion.updateUserVersion currentUserId, timestamp , DataVersion.updateAllFriendshipVersion currentUserId, timestamp ] .then -> res.send new APIResult 200 .catch next # 将好友加入黑名单 router.post '/add_to_blacklist', (req, res, next) -> friendId = req.body.friendId encodedFriendId = req.body.encodedFriendId currentUserId = Session.getCurrentUserId req timestamp = Date.now() User.checkUserExists friendId .then (result) -> if result # 先调用融云服务器接口 rongCloud.user.blacklist.add Utility.encodeId(currentUserId), encodedFriendId, (err, resultText) -> # 如果失败直接返回,不保存到数据库 if err next err else Blacklist.upsert userId: currentUserId friendId: friendId status: true timestamp: timestamp .then -> # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp .then -> res.send new APIResult 200 else res.status(404).send 'friendId is not an available userId.' .catch next # 将好友从黑名单中移除 router.post '/remove_from_blacklist', (req, res, next) -> friendId = req.body.friendId encodedFriendId = req.body.encodedFriendId currentUserId = Session.getCurrentUserId req timestamp = Date.now() # 先调用融云服务器接口 rongCloud.user.blacklist.remove Utility.encodeId(currentUserId), encodedFriendId, (err, resultText) -> # 如果失败直接返回,不保存到数据库 if err next err else Blacklist.update status: false timestamp: timestamp , where: userId: currentUserId friendId: friendId .then -> # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp .then -> res.send new APIResult 200 .catch next # 上传用户通讯录 router.post '/upload_contacts', (req, res, next) -> contacts = req.body # TODO: Not implements. res.status(404).send 'Not implements.' # 获取融云 Token router.get '/get_token', (req, res, next) -> User.findById Session.getCurrentUserId req, attributes: [ 'id' 'nickname' 'portraitUri' ] .then (user) -> # 调用 Server API SDK 获取 Token getToken user.id, user.nickname, user.portraitUri .then (token) -> res.send new APIResult 200, Utility.encodeResults { userId: user.id, token: token }, 'userId' .catch next # 获取云存储所用 Token router.get '/get_image_token', (req, res, next) -> qiniu.conf.ACCESS_KEY = Config.QINIU_ACCESS_KEY qiniu.conf.SECRET_KEY = Config.QINIU_SECRET_KEY putPolicy = new qiniu.rs.PutPolicy Config.QINIU_BUCKET_NAME token = putPolicy.token() res.send new APIResult 200, { target: 'qiniu', domain: Config.QINIU_BUCKET_DOMAIN, token: token } # 获取短信图形验证码 router.get '/get_sms_img_code', (req, res, next) -> rongCloud.sms.getImgCode Config.RONGCLOUD_APP_KEY, (err, resultText) -> if err return next err result = JSON.parse resultText if result.code isnt 200 return next new Error 'RongCloud Server API Error Code: ' + result.code res.send new APIResult 200, { url: result.url, verifyId: result.verifyId } # 获取当前用户黑名单列表 router.get '/blacklist', (req, res, next) -> currentUserId = Session.getCurrentUserId req timestamp = Date.now() Blacklist.findAll where: userId: currentUserId friendId: $ne: 0 status: true attributes: [] include: model: User attributes: [ 'id' 'nickname' 'portraitUri' 'updatedAt' # 为节约服务端资源,客户端自己按照 updatedAt 排序 ] .then (dbBlacklist) -> # 调用融云服务器接口,获取服务端数据,并和本地做同步 rongCloud.user.blacklist.query Utility.encodeId(currentUserId), (err, resultText) -> if err # 如果失败直接忽略 Utility.logError 'Error: request server blacklist failed: %s', err else result = JSON.parse(resultText) if result.code is 200 hasDirtyData = false serverBlacklistUserIds = result.users dbBlacklistUserIds = dbBlacklist.map (blacklist) -> if blacklist.user blacklist.user.id else hasDirtyData = true null # 如果有脏数据,输出到 Log 中 if hasDirtyData Utility.log 'Dirty blacklist data %j', dbBlacklist # 检查和修复数据库中黑名单数据的缺失 serverBlacklistUserIds.forEach (encodedUserId) -> userId = Utility.decodeIds encodedUserId if dbBlacklistUserIds.indexOf(userId) is -1 # 数据库中缺失,添加上这个数据 Blacklist.create userId: currentUserId friendId: userId status: true timestamp: timestamp .then -> # 不需要处理成功和失败回调 Utility.log 'Sync: fix user blacklist, add %s -> %s from db.', currentUserId, userId # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp .catch -> # 可能会有云端的脏数据,导致 userId 不存在,直接忽略了 # 检查和修复数据库中黑名单脏数据(多余) dbBlacklistUserIds.forEach (userId) -> if userId and serverBlacklistUserIds.indexOf(Utility.encodeId(userId)) is -1 # 数据库中的脏数据,删除掉 Blacklist.update status: false timestamp: timestamp , where: userId: currentUserId friendId: userId .then -> Utility.log 'Sync: fix user blacklist, remove %s -> %s from db.', currentUserId, userId # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp res.send new APIResult 200, Utility.encodeResults dbBlacklist, [['user', 'id']] .catch next # 获取当前用户所属群组列表 router.get '/groups', (req, res, next) -> GroupMember.findAll where: memberId: Session.getCurrentUserId req attributes: [ 'role' ] include: [ model: Group attributes: [ 'id' 'name' 'portraitUri' 'creatorId' 'memberCount' 'maxMemberCount' ] ] .then (groups) -> res.send new APIResult 200, Utility.encodeResults groups, [['group', 'id'], ['group', 'creatorId']] .catch next # 同步用户的好友、黑名单、群组、群组成员数据 # 客户端的调用时机:客户端打开时 router.get '/sync/:version', (req, res, next) -> version = req.params.version if not validator.isInt version return res.status(400).send 'Version parameter is not integer.' user = blacklist = friends = groups = groupMembers = null maxVersions = [] currentUserId = Session.getCurrentUserId req DataVersion.findById currentUserId .then (dataVersion) -> co -> # 获取变化的用户(自己)信息 if dataVersion.userVersion > version user = yield User.findById currentUserId, attributes: [ 'id' 'nickname' 'portraitUri' 'timestamp' ] # 获取变化的黑名单信息 if dataVersion.blacklistVersion > version blacklist = yield Blacklist.findAll where: userId: currentUserId timestamp: $gt: version attributes: [ 'friendId' 'status' 'timestamp' ] # 获取变化的好友信息 if dataVersion.friendshipVersion > version friends = yield Friendship.findAll where: userId: currentUserId timestamp: $gt: version attributes: [ 'friendId' 'displayName' 'status' 'timestamp' ] # 获取变化的当前用户加入的群组信息 if dataVersion.groupVersion > version groups = yield GroupMember.findAll where: memberId: currentUserId timestamp: $gt: version attributes: [ 'displayName' 'role' 'isDeleted' ] include: [ model: Group attributes: [ 'id' 'name' 'portraitUri' 'timestamp' ] ] # 获取变化的当前用户加入的群组成员信息 if dataVersion.groupVersion > version groupMembers = yield GroupMember.findAll where: memberId: currentUserId timestamp: $gt: version attributes: [ 'groupId' 'memberId' 'displayName' 'role' 'isDeleted' 'timestamp' ] include: [ model: User attributes: [ 'nickname' 'portraitUri' ] ] maxVersions.push(user.timestamp) if user maxVersions.push(_.max(blacklist, (item) -> item.timestamp).timestamp) if blacklist maxVersions.push(_.max(friends, (item) -> item.timestamp).timestamp) if friends maxVersions.push(_.max(groups, (item) -> item.group.timestamp).group.timestamp) if groups maxVersions.push(_.max(groupMembers, (item) -> item.timestamp).timestamp) if groupMembers Utility.log 'maxVersions: %j', maxVersions res.send new APIResult 200, version: _.max(maxVersions) # 最大的版本号 user: user blacklist: blacklist friends: friends groups: groups group_members: groupMembers .catch next # 批量获取用户信息 router.get '/batch', (req, res, next) -> ids = req.query.id ids = [ids] if not Array.isArray ids ids = Utility.decodeIds ids User.findAll where: id: $in: ids attributes: [ 'id' 'nickname' 'portraitUri' ] .then (users) -> res.send new APIResult 200, Utility.encodeResults users .catch next # 获取用户信息 router.get '/:id', (req, res, next) -> userId = req.params.id userId = Utility.decodeIds userId User.findById userId, attributes: [ 'id' 'nickname' 'portraitUri' ] .then (user) -> if not user return res.status(404).send 'Unknown user.' res.send new APIResult 200, Utility.encodeResults user .catch next # 根据手机号查找用户信息 router.get '/find/:region/:phone', (req, res, next) -> region = req.params.region phone = req.params.phone # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone, regionMap[region] return res.status(400).send 'Invalid region and phone number.' User.findOne where: region: region phone: phone attributes: [ 'id' 'nickname' 'portraitUri' ] .then (user) -> if not user return res.status(404).send 'Unknown user.' res.send new APIResult 200, Utility.encodeResults user .catch next module.exports = router
true
express = require 'express' co = require 'co' _ = require 'underscore' moment = require 'moment' rongCloud = require 'rongcloud-sdk' qiniu = require 'qiniu' Config = require '../conf' Session = require '../util/session' Utility = require('../util/util').Utility APIResult = require('../util/util').APIResult # 引用数据库对象和模型 [sequelize, User, Blacklist, Friendship, Group, GroupMember, GroupSync, DataVersion, VerificationCode, LoginLog] = require '../db' MAX_GROUP_MEMBER_COUNT = 500 NICKNAME_MIN_LENGTH = 1 NICKNAME_MAX_LENGTH = 32 PORTRAIT_URI_MIN_LENGTH = 12 PORTRAIT_URI_MAX_LENGTH = 256 PASSWORD_MIN_LENGTH = 6 PASSWORD_MAX_LENGTH = 20 # 初始化融云 Server API SDK rongCloud.init Config.RONGCLOUD_APP_KEY, Config.RONGCLOUD_APP_SECRET router = express.Router() validator = sequelize.Validator # 国际电话区号和国家代码对应关系 regionMap = '86': 'zh-CN' # 获取新 Token 并更新到数据库 getToken = (userId, nickname, portraitUri) -> new Promise (resolve, reject) -> rongCloud.user.getToken Utility.encodeId(userId), nickname, portraitUri, (err, resultText) -> if err return reject err result = JSON.parse resultText if result.code isnt 200 return reject new Error 'RongCloud Server API Error Code: ' + result.code # 更新到数据库 User.update rongCloudToken: result.token , where: id: userId .then -> resolve result.token .catch (error) -> reject error # 发送验证码 router.post '/send_code', (req, res, next) -> region = req.body.region phone = req.body.phone # 如果在融云开发者后台开启图形验证码,需要校验 verifyId 和 verifyCode。 # verifyId = req.body.verify_id # verifyCode = req.body.verify_code # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone.toString(), regionMap[region] return res.status(400).send 'Invalid region and phone number.' VerificationCode.getByPhone region, phone .then (verification) -> if verification timeDiff = Math.floor((Date.now() - verification.updatedAt.getTime()) / 1000) # 频率限制为 1 分钟 1 条,开发测试环境中 5 秒 1 条 if req.app.get('env') is 'development' subtraction = moment().subtract(5, 's') else subtraction = moment().subtract(1, 'm') if subtraction.isBefore verification.updatedAt return res.send new APIResult 5000, null, 'Throttle limit exceeded.' code = _.random 1000, 9999 # 生产环境下才发送短信 if req.app.get('env') is 'development' VerificationCode.upsert region: region phone: phone sessionId: '' .then -> return res.send new APIResult 200 else # 需要在融云开发者后台申请短信验证码签名,然后选择短信模板 Id rongCloud.sms.sendCode region, phone, Config.RONGCLOUD_SMS_REGISTER_TEMPLATE_ID, (err, resultText) -> if err return next err result = JSON.parse resultText if result.code isnt 200 return next new Error 'RongCloud Server API Error Code: ' + result.code VerificationCode.upsert region: region phone: phone sessionId: result.sessionId .then -> res.send new APIResult 200 .catch next # 验证验证码 router.post '/verify_code', (req, res, next) -> phone = req.body.phone region = req.body.region code = req.body.code # TODO: 频率限制,防止爆破 VerificationCode.getByPhone region, phone .then (verification) -> if not verification return res.status(404).send 'Unknown phone number.' # 验证码过期时间为 2 分钟 else if moment().subtract(2, 'm').isAfter verification.updatedAt res.send new APIResult 2000, null, 'Verification code expired.' # 开发环境下支持万能验证码 else if req.app.get('env') is 'development' and code is '9999' res.send new APIResult 200, verification_token: verification.token else rongCloud.sms.verifyCode verification.sessionId, code, (err, resultText) -> if err # Hack for invalid 430 HTTP status code to avoid unuseful error log. errorMessage = err.message if errorMessage is 'Unsuccessful HTTP response' or errorMessage is 'Too Many Requests' return res.status(err.statusCode).send errorMessage else return next err result = JSON.parse resultText if result.code isnt 200 return next new Error 'RongCloud Server API Error Code: ' + result.code if result.success res.send new APIResult 200, verification_token: verification.token else res.send new APIResult 1000, null, 'Invalid verification code.' .catch next # # 检查用户名是否可以注册 # router.post '/check_username_available', (req, res, next) -> # username = req.body.username # # User.checkUsernameAvailable username # .then (result) -> # if result # res.send new APIResult 200, true # else # res.send new APIResult 200, false, 'Username has already existed.' # .catch next # 检查手机号是否可以注册 router.post '/check_phone_available', (req, res, next) -> region = req.body.region phone = req.body.phone # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone.toString(), regionMap[region] return res.status(400).send 'Invalid region and phone number.' User.checkPhoneAvailable region, phone .then (result) -> if result res.send new APIResult 200, true else res.send new APIResult 200, false, 'Phone number has already existed.' .catch next # 用户注册 router.post '/register', (req, res, next) -> nickname = Utility.xss req.body.nickname, NICKNAME_MAX_LENGTH # username = req.body.username password = PI:PASSWORD:<PASSWORD>END_PI verificationToken = req.body.verification_token if password.indexOf(' ') > 0 return res.status(400).send 'Password must have no space.' if not validator.isLength nickname, NICKNAME_MIN_LENGTH, NICKNAME_MAX_LENGTH return res.status(400).send 'Length of nickname invalid.' if not validator.isLength password, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH return res.status(400).send 'Length of password invalid.' if not validator.isUUID verificationToken return res.status(400).send 'Invalid verification_token.' VerificationCode.getByToken verificationToken .then (verification) -> if not verification return res.status(404).send 'Unknown verification_token.' # User.checkUsernameAvailable username # .then (result) -> # if result User.checkPhoneAvailable verification.region, verification.phone .then (result) -> if result salt = Utility.random 1000, 9999 hash = Utility.hash password, salt sequelize.transaction (t) -> User.create nickname: nickname # username: username region: verification.region phone: verification.phone passwordHash: hash passwordSalt: salt.toString() , transaction: t .then (user) -> DataVersion.create userId: user.id, transaction: t .then -> Session.setAuthCookie res, user.id Session.setNicknameToCache user.id, nickname res.send new APIResult 200, Utility.encodeResults id: user.id else res.status(400).send 'Phone number has already existed.' # else # res.status(403).send 'Username has already existed.' .catch next # 用户登录 router.post '/login', (req, res, next) -> region = req.body.region phone = req.body.phone password = req.body.password # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone, regionMap[region] return res.status(400).send 'Invalid region and phone number.' User.findOne where: region: region phone: phone attributes: [ 'id' 'passwordHash' 'passwordSalt' 'nickname' 'portraitUri' 'rongCloudToken' ] .then (user) -> errorMessage = 'Invalid phone or password.' if not user res.send new APIResult 1000, null, errorMessage else # passwordHash = Utility.hash password, user.passwordSalt # if passwordHash isnt user.passwordHash # return res.send new APIResult 1000, null, errorMessage Session.setAuthCookie res, user.id Session.setNicknameToCache user.id, user.nickname GroupMember.findAll where: memberId: user.id attributes: [] include: model: Group where: deletedAt: null attributes: [ 'id' 'name' ] .then (groups) -> Utility.log 'Sync groups: %j', groups groupIdNamePairs = {} groups.forEach (group) -> groupIdNamePairs[Utility.encodeId(group.group.id)] = group.group.name Utility.log 'Sync groups: %j', groupIdNamePairs rongCloud.group.sync Utility.encodeId(user.id), groupIdNamePairs, (err, resultText) -> if err Utility.logError 'Error sync user\'s group list failed: %s', err .catch (error) -> Utility.logError 'Sync groups error: ', error if user.rongCloudToken is '' if req.app.get('env') is 'development' return res.send new APIResult 200, Utility.encodeResults id: user.id, token: 'fake token' getToken user.id, user.nickname, user.portraitUri .then (token) -> res.send new APIResult 200, Utility.encodeResults id: user.id, token: token else res.send new APIResult 200, Utility.encodeResults id: user.id, token: user.rongCloudToken .catch next # 用户注销 router.post '/logout', (req, res) -> res.clearCookie Config.AUTH_COOKIE_NAME res.send new APIResult 200 # 通过手机验证码设置新密码 router.post '/reset_password', (req, res, next) -> password = req.body.password verificationToken = req.body.verification_token if (password.indexOf(' ') != -1) return res.status(400).send 'Password must have no space.' if not validator.isLength password, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH return res.status(400).send 'Length of password invalid.' if not validator.isUUID verificationToken return res.status(400).send 'Invalid verification_token.' VerificationCode.getByToken verificationToken .then (verification) -> if not verification return res.status(404).send 'Unknown verification_token.' salt = _.random 1000, 9999 hash = Utility.hash password, salt User.update passwordHash: hash passwordSalt: salt.toString() , where: region: verification.region phone: verification.phone .then -> res.send new APIResult 200 .catch next # 当前用户通过旧密码设置新密码 router.post '/change_password', (req, res, next) -> newPassword = req.body.newPassword oldPassword = req.body.oldPassword if (newPassword.indexOf(' ') != -1) return res.status(400).send 'New password must have no space.' if not validator.isLength newPassword, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH return res.status(400).send 'Invalid new password length.' User.findById Session.getCurrentUserId req, attributes: [ 'id' 'passwordHash' 'passwordSalt' ] .then (user) -> oldHash = Utility.hash oldPassword, user.passwordSalt if oldHash isnt user.passwordHash return res.send new APIResult 1000, null, 'Wrong old password.' newSalt = _.random 1000, 9999 newHash = Utility.hash newPassword, newSalt user.update passwordHash: newHash passwordSalt: newSalt.toString() .then -> res.send new APIResult 200 .catch next # 设置自己的昵称 router.post '/set_nickname', (req, res, next) -> nickname = Utility.xss req.body.nickname, NICKNAME_MAX_LENGTH if not validator.isLength nickname, NICKNAME_MIN_LENGTH, NICKNAME_MAX_LENGTH return res.status(400).send 'Invalid nickname length.' currentUserId = Session.getCurrentUserId req timestamp = Date.now() User.update nickname: nickname timestamp: timestamp , where: id: currentUserId .then -> # 更新到融云服务器 rongCloud.user.refresh Utility.encodeId(currentUserId), nickname, null, (err, resultText) -> if err Utility.logError 'RongCloud Server API Error: ', err.message result = JSON.parse resultText if result.code isnt 200 Utility.logError 'RongCloud Server API Error Code: ', result.code Session.setNicknameToCache currentUserId, nickname Promise.all [ DataVersion.updateUserVersion currentUserId, timestamp , DataVersion.updateAllFriendshipVersion currentUserId, timestamp ] .then -> res.send new APIResult 200 .catch next # 设置用户头像地址 router.post '/set_portrait_uri', (req, res, next) -> portraitUri = Utility.xss req.body.portraitUri, PORTRAIT_URI_MAX_LENGTH if not validator.isURL portraitUri, { protocols: ['http', 'https'], require_protocol: true } return res.status(400).send 'Invalid portraitUri format.' if not validator.isLength portraitUri, PORTRAIT_URI_MIN_LENGTH, PORTRAIT_URI_MAX_LENGTH return res.status(400).send 'Invalid portraitUri length.' currentUserId = Session.getCurrentUserId req timestamp = Date.now() User.update portraitUri: portraitUri timestamp: timestamp , where: id: currentUserId .then -> # 更新到融云服务器 rongCloud.user.refresh Utility.encodeId(currentUserId), null, portraitUri, (err, resultText) -> if err Utility.logError 'RongCloud Server API Error: ', err.message result = JSON.parse resultText if result.code isnt 200 Utility.logError 'RongCloud Server API Error Code: ', result.code Promise.all [ DataVersion.updateUserVersion currentUserId, timestamp , DataVersion.updateAllFriendshipVersion currentUserId, timestamp ] .then -> res.send new APIResult 200 .catch next # 将好友加入黑名单 router.post '/add_to_blacklist', (req, res, next) -> friendId = req.body.friendId encodedFriendId = req.body.encodedFriendId currentUserId = Session.getCurrentUserId req timestamp = Date.now() User.checkUserExists friendId .then (result) -> if result # 先调用融云服务器接口 rongCloud.user.blacklist.add Utility.encodeId(currentUserId), encodedFriendId, (err, resultText) -> # 如果失败直接返回,不保存到数据库 if err next err else Blacklist.upsert userId: currentUserId friendId: friendId status: true timestamp: timestamp .then -> # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp .then -> res.send new APIResult 200 else res.status(404).send 'friendId is not an available userId.' .catch next # 将好友从黑名单中移除 router.post '/remove_from_blacklist', (req, res, next) -> friendId = req.body.friendId encodedFriendId = req.body.encodedFriendId currentUserId = Session.getCurrentUserId req timestamp = Date.now() # 先调用融云服务器接口 rongCloud.user.blacklist.remove Utility.encodeId(currentUserId), encodedFriendId, (err, resultText) -> # 如果失败直接返回,不保存到数据库 if err next err else Blacklist.update status: false timestamp: timestamp , where: userId: currentUserId friendId: friendId .then -> # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp .then -> res.send new APIResult 200 .catch next # 上传用户通讯录 router.post '/upload_contacts', (req, res, next) -> contacts = req.body # TODO: Not implements. res.status(404).send 'Not implements.' # 获取融云 Token router.get '/get_token', (req, res, next) -> User.findById Session.getCurrentUserId req, attributes: [ 'id' 'nickname' 'portraitUri' ] .then (user) -> # 调用 Server API SDK 获取 Token getToken user.id, user.nickname, user.portraitUri .then (token) -> res.send new APIResult 200, Utility.encodeResults { userId: user.id, token: token }, 'userId' .catch next # 获取云存储所用 Token router.get '/get_image_token', (req, res, next) -> qiniu.conf.ACCESS_KEY = Config.QINIU_ACCESS_KEY qiniu.conf.SECRET_KEY = Config.QINIU_SECRET_KEY putPolicy = new qiniu.rs.PutPolicy Config.QINIU_BUCKET_NAME token = putPolicy.token() res.send new APIResult 200, { target: 'qiniu', domain: Config.QINIU_BUCKET_DOMAIN, token: token } # 获取短信图形验证码 router.get '/get_sms_img_code', (req, res, next) -> rongCloud.sms.getImgCode Config.RONGCLOUD_APP_KEY, (err, resultText) -> if err return next err result = JSON.parse resultText if result.code isnt 200 return next new Error 'RongCloud Server API Error Code: ' + result.code res.send new APIResult 200, { url: result.url, verifyId: result.verifyId } # 获取当前用户黑名单列表 router.get '/blacklist', (req, res, next) -> currentUserId = Session.getCurrentUserId req timestamp = Date.now() Blacklist.findAll where: userId: currentUserId friendId: $ne: 0 status: true attributes: [] include: model: User attributes: [ 'id' 'nickname' 'portraitUri' 'updatedAt' # 为节约服务端资源,客户端自己按照 updatedAt 排序 ] .then (dbBlacklist) -> # 调用融云服务器接口,获取服务端数据,并和本地做同步 rongCloud.user.blacklist.query Utility.encodeId(currentUserId), (err, resultText) -> if err # 如果失败直接忽略 Utility.logError 'Error: request server blacklist failed: %s', err else result = JSON.parse(resultText) if result.code is 200 hasDirtyData = false serverBlacklistUserIds = result.users dbBlacklistUserIds = dbBlacklist.map (blacklist) -> if blacklist.user blacklist.user.id else hasDirtyData = true null # 如果有脏数据,输出到 Log 中 if hasDirtyData Utility.log 'Dirty blacklist data %j', dbBlacklist # 检查和修复数据库中黑名单数据的缺失 serverBlacklistUserIds.forEach (encodedUserId) -> userId = Utility.decodeIds encodedUserId if dbBlacklistUserIds.indexOf(userId) is -1 # 数据库中缺失,添加上这个数据 Blacklist.create userId: currentUserId friendId: userId status: true timestamp: timestamp .then -> # 不需要处理成功和失败回调 Utility.log 'Sync: fix user blacklist, add %s -> %s from db.', currentUserId, userId # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp .catch -> # 可能会有云端的脏数据,导致 userId 不存在,直接忽略了 # 检查和修复数据库中黑名单脏数据(多余) dbBlacklistUserIds.forEach (userId) -> if userId and serverBlacklistUserIds.indexOf(Utility.encodeId(userId)) is -1 # 数据库中的脏数据,删除掉 Blacklist.update status: false timestamp: timestamp , where: userId: currentUserId friendId: userId .then -> Utility.log 'Sync: fix user blacklist, remove %s -> %s from db.', currentUserId, userId # 更新版本号(时间戳) DataVersion.updateBlacklistVersion currentUserId, timestamp res.send new APIResult 200, Utility.encodeResults dbBlacklist, [['user', 'id']] .catch next # 获取当前用户所属群组列表 router.get '/groups', (req, res, next) -> GroupMember.findAll where: memberId: Session.getCurrentUserId req attributes: [ 'role' ] include: [ model: Group attributes: [ 'id' 'name' 'portraitUri' 'creatorId' 'memberCount' 'maxMemberCount' ] ] .then (groups) -> res.send new APIResult 200, Utility.encodeResults groups, [['group', 'id'], ['group', 'creatorId']] .catch next # 同步用户的好友、黑名单、群组、群组成员数据 # 客户端的调用时机:客户端打开时 router.get '/sync/:version', (req, res, next) -> version = req.params.version if not validator.isInt version return res.status(400).send 'Version parameter is not integer.' user = blacklist = friends = groups = groupMembers = null maxVersions = [] currentUserId = Session.getCurrentUserId req DataVersion.findById currentUserId .then (dataVersion) -> co -> # 获取变化的用户(自己)信息 if dataVersion.userVersion > version user = yield User.findById currentUserId, attributes: [ 'id' 'nickname' 'portraitUri' 'timestamp' ] # 获取变化的黑名单信息 if dataVersion.blacklistVersion > version blacklist = yield Blacklist.findAll where: userId: currentUserId timestamp: $gt: version attributes: [ 'friendId' 'status' 'timestamp' ] # 获取变化的好友信息 if dataVersion.friendshipVersion > version friends = yield Friendship.findAll where: userId: currentUserId timestamp: $gt: version attributes: [ 'friendId' 'displayName' 'status' 'timestamp' ] # 获取变化的当前用户加入的群组信息 if dataVersion.groupVersion > version groups = yield GroupMember.findAll where: memberId: currentUserId timestamp: $gt: version attributes: [ 'displayName' 'role' 'isDeleted' ] include: [ model: Group attributes: [ 'id' 'name' 'portraitUri' 'timestamp' ] ] # 获取变化的当前用户加入的群组成员信息 if dataVersion.groupVersion > version groupMembers = yield GroupMember.findAll where: memberId: currentUserId timestamp: $gt: version attributes: [ 'groupId' 'memberId' 'displayName' 'role' 'isDeleted' 'timestamp' ] include: [ model: User attributes: [ 'nickname' 'portraitUri' ] ] maxVersions.push(user.timestamp) if user maxVersions.push(_.max(blacklist, (item) -> item.timestamp).timestamp) if blacklist maxVersions.push(_.max(friends, (item) -> item.timestamp).timestamp) if friends maxVersions.push(_.max(groups, (item) -> item.group.timestamp).group.timestamp) if groups maxVersions.push(_.max(groupMembers, (item) -> item.timestamp).timestamp) if groupMembers Utility.log 'maxVersions: %j', maxVersions res.send new APIResult 200, version: _.max(maxVersions) # 最大的版本号 user: user blacklist: blacklist friends: friends groups: groups group_members: groupMembers .catch next # 批量获取用户信息 router.get '/batch', (req, res, next) -> ids = req.query.id ids = [ids] if not Array.isArray ids ids = Utility.decodeIds ids User.findAll where: id: $in: ids attributes: [ 'id' 'nickname' 'portraitUri' ] .then (users) -> res.send new APIResult 200, Utility.encodeResults users .catch next # 获取用户信息 router.get '/:id', (req, res, next) -> userId = req.params.id userId = Utility.decodeIds userId User.findById userId, attributes: [ 'id' 'nickname' 'portraitUri' ] .then (user) -> if not user return res.status(404).send 'Unknown user.' res.send new APIResult 200, Utility.encodeResults user .catch next # 根据手机号查找用户信息 router.get '/find/:region/:phone', (req, res, next) -> region = req.params.region phone = req.params.phone # 如果不是合法的手机号,直接返回,省去查询数据库的步骤 if not validator.isMobilePhone phone, regionMap[region] return res.status(400).send 'Invalid region and phone number.' User.findOne where: region: region phone: phone attributes: [ 'id' 'nickname' 'portraitUri' ] .then (user) -> if not user return res.status(404).send 'Unknown user.' res.send new APIResult 200, Utility.encodeResults user .catch next module.exports = router
[ { "context": "calhost'\n username: process.env.USERNAME || 'admin'\n password: process.env.PASSWORD || '9999'\n ", "end": 342, "score": 0.9951281547546387, "start": 337, "tag": "USERNAME", "value": "admin" }, { "context": "e: process.env.USERNAME || 'admin'\n password:...
test/ptz.coffee
unm4sk1g/onvif
1
synthTest = not process.env.HOSTNAME assert = require 'assert' onvif = require('../lib/onvif') serverMockup = require('./serverMockup') if synthTest util = require('util') describe 'PTZ', () -> cam = null before (done) -> options = { hostname: process.env.HOSTNAME || 'localhost' username: process.env.USERNAME || 'admin' password: process.env.PASSWORD || '9999' port: if process.env.PORT then parseInt(process.env.PORT) else 10101 } cam = new onvif.Cam options, done describe 'getPresets', () -> it 'should return array of preset objects and sets them to #presets', (done) -> cam.getPresets {}, (err, data) -> assert.equal err, null assert.ok Object.keys(data).every (presetName) -> typeof data[presetName] == 'string' assert.equal cam.presets, data done() it 'should return array of preset objects and sets them to #presets without options', (done) -> cam.getPresets (err, data) -> assert.equal err, null assert.ok Object.keys(data).every (presetName) -> typeof data[presetName] == 'string' assert.equal cam.presets, data done() if synthTest it 'should work with one preset', (done) -> serverMockup.conf.one = true cam.getPresets (err, data) -> assert.equal err, null assert.ok Object.keys(data).every (presetName) -> typeof data[presetName] == 'string' assert.equal cam.presets, data delete serverMockup.conf.one done() describe 'gotoPreset', () -> it 'should just run', (done) -> cam.gotoPreset {preset: Object.keys(cam.profiles)[0]}, (err, data) -> assert.equal err, null done() it 'should run with speed definition', (done) -> cam.gotoPreset {preset: Object.keys(cam.profiles)[0], speed: 0.1}, (err, data) -> assert.equal err, null done() describe 'setPreset', () -> it 'should run with preset name (new)', (done) -> cam.setPreset {presetName: 'testPreset'}, (err, data) -> assert.equal err, null done() it 'should run with preset token (update)', (done) -> cam.setPreset {presetToken: 1}, (err, data) -> assert.equal err, null done() describe 'removePreset', () -> it 'should just run', (done) -> cam.removePreset {presetToken: Object.keys(cam.profiles)[0]}, (err, data) -> assert.equal err, null done() describe 'gotoHomePosition', () -> it 'should just run', (done) -> cam.gotoHomePosition {speed: {x: 1.0, y: 1.0, zoom: 1.0}}, (err, data) -> assert.equal err, null done() describe 'setHomePosition', () -> it 'should just run', (done) -> cam.setHomePosition {}, (err, data) -> assert.equal err, null done() describe 'absolute move', () -> it 'should returns empty RelativeResponseObject', (done) -> cam.absoluteMove { x: 1 y: 1 zoom: 1 }, done it 'should works without callback', () -> cam.absoluteMove { x: 0 y: 0 zoom: 1 } describe 'relative move', () -> it 'should returns empty RelativeResponseObject', (done) -> cam.relativeMove { speed: { x: 0.1 y: 0.1 } x: 1 y: 1 zoom: 1 }, done it 'should works without callback', () -> cam.relativeMove { speed: { x: 0.1 y: 0.1 } x: 1 y: 1 zoom: 1 } describe 'continuous move', () -> it 'should returns empty ContinuousResponseObject', (done) -> cam.continuousMove { x: 0.1 y: 0.1 zoom: 0 }, done it 'should set ommited pan-tilt parameters to zero', (done) -> cam.continuousMove { x: 0.1 zoom: 0 }, done describe 'stop', () -> it 'should stop all movements when options are ommited', (done) -> cam.stop done it 'should stop only zoom movement', (done) -> cam.stop {zoom: true}, done it 'should stop only pan-tilt movement', (done) -> cam.stop {panTilt: true}, done it 'should stop all movements', (done) -> cam.stop {zoom: true, panTilt: true}, done it 'should work without callback', (done) -> cam.stop {} cam.stop() done() describe 'getStatus', () -> it 'should returns position status', (done) -> cam.getStatus {}, (err, data) -> assert.equal err, null done()
199583
synthTest = not process.env.HOSTNAME assert = require 'assert' onvif = require('../lib/onvif') serverMockup = require('./serverMockup') if synthTest util = require('util') describe 'PTZ', () -> cam = null before (done) -> options = { hostname: process.env.HOSTNAME || 'localhost' username: process.env.USERNAME || 'admin' password: <PASSWORD> || '<PASSWORD>' port: if process.env.PORT then parseInt(process.env.PORT) else 10101 } cam = new onvif.Cam options, done describe 'getPresets', () -> it 'should return array of preset objects and sets them to #presets', (done) -> cam.getPresets {}, (err, data) -> assert.equal err, null assert.ok Object.keys(data).every (presetName) -> typeof data[presetName] == 'string' assert.equal cam.presets, data done() it 'should return array of preset objects and sets them to #presets without options', (done) -> cam.getPresets (err, data) -> assert.equal err, null assert.ok Object.keys(data).every (presetName) -> typeof data[presetName] == 'string' assert.equal cam.presets, data done() if synthTest it 'should work with one preset', (done) -> serverMockup.conf.one = true cam.getPresets (err, data) -> assert.equal err, null assert.ok Object.keys(data).every (presetName) -> typeof data[presetName] == 'string' assert.equal cam.presets, data delete serverMockup.conf.one done() describe 'gotoPreset', () -> it 'should just run', (done) -> cam.gotoPreset {preset: Object.keys(cam.profiles)[0]}, (err, data) -> assert.equal err, null done() it 'should run with speed definition', (done) -> cam.gotoPreset {preset: Object.keys(cam.profiles)[0], speed: 0.1}, (err, data) -> assert.equal err, null done() describe 'setPreset', () -> it 'should run with preset name (new)', (done) -> cam.setPreset {presetName: 'testPreset'}, (err, data) -> assert.equal err, null done() it 'should run with preset token (update)', (done) -> cam.setPreset {presetToken: 1}, (err, data) -> assert.equal err, null done() describe 'removePreset', () -> it 'should just run', (done) -> cam.removePreset {presetToken: Object.keys(cam.profiles)[0]}, (err, data) -> assert.equal err, null done() describe 'gotoHomePosition', () -> it 'should just run', (done) -> cam.gotoHomePosition {speed: {x: 1.0, y: 1.0, zoom: 1.0}}, (err, data) -> assert.equal err, null done() describe 'setHomePosition', () -> it 'should just run', (done) -> cam.setHomePosition {}, (err, data) -> assert.equal err, null done() describe 'absolute move', () -> it 'should returns empty RelativeResponseObject', (done) -> cam.absoluteMove { x: 1 y: 1 zoom: 1 }, done it 'should works without callback', () -> cam.absoluteMove { x: 0 y: 0 zoom: 1 } describe 'relative move', () -> it 'should returns empty RelativeResponseObject', (done) -> cam.relativeMove { speed: { x: 0.1 y: 0.1 } x: 1 y: 1 zoom: 1 }, done it 'should works without callback', () -> cam.relativeMove { speed: { x: 0.1 y: 0.1 } x: 1 y: 1 zoom: 1 } describe 'continuous move', () -> it 'should returns empty ContinuousResponseObject', (done) -> cam.continuousMove { x: 0.1 y: 0.1 zoom: 0 }, done it 'should set ommited pan-tilt parameters to zero', (done) -> cam.continuousMove { x: 0.1 zoom: 0 }, done describe 'stop', () -> it 'should stop all movements when options are ommited', (done) -> cam.stop done it 'should stop only zoom movement', (done) -> cam.stop {zoom: true}, done it 'should stop only pan-tilt movement', (done) -> cam.stop {panTilt: true}, done it 'should stop all movements', (done) -> cam.stop {zoom: true, panTilt: true}, done it 'should work without callback', (done) -> cam.stop {} cam.stop() done() describe 'getStatus', () -> it 'should returns position status', (done) -> cam.getStatus {}, (err, data) -> assert.equal err, null done()
true
synthTest = not process.env.HOSTNAME assert = require 'assert' onvif = require('../lib/onvif') serverMockup = require('./serverMockup') if synthTest util = require('util') describe 'PTZ', () -> cam = null before (done) -> options = { hostname: process.env.HOSTNAME || 'localhost' username: process.env.USERNAME || 'admin' password: PI:PASSWORD:<PASSWORD>END_PI || 'PI:PASSWORD:<PASSWORD>END_PI' port: if process.env.PORT then parseInt(process.env.PORT) else 10101 } cam = new onvif.Cam options, done describe 'getPresets', () -> it 'should return array of preset objects and sets them to #presets', (done) -> cam.getPresets {}, (err, data) -> assert.equal err, null assert.ok Object.keys(data).every (presetName) -> typeof data[presetName] == 'string' assert.equal cam.presets, data done() it 'should return array of preset objects and sets them to #presets without options', (done) -> cam.getPresets (err, data) -> assert.equal err, null assert.ok Object.keys(data).every (presetName) -> typeof data[presetName] == 'string' assert.equal cam.presets, data done() if synthTest it 'should work with one preset', (done) -> serverMockup.conf.one = true cam.getPresets (err, data) -> assert.equal err, null assert.ok Object.keys(data).every (presetName) -> typeof data[presetName] == 'string' assert.equal cam.presets, data delete serverMockup.conf.one done() describe 'gotoPreset', () -> it 'should just run', (done) -> cam.gotoPreset {preset: Object.keys(cam.profiles)[0]}, (err, data) -> assert.equal err, null done() it 'should run with speed definition', (done) -> cam.gotoPreset {preset: Object.keys(cam.profiles)[0], speed: 0.1}, (err, data) -> assert.equal err, null done() describe 'setPreset', () -> it 'should run with preset name (new)', (done) -> cam.setPreset {presetName: 'testPreset'}, (err, data) -> assert.equal err, null done() it 'should run with preset token (update)', (done) -> cam.setPreset {presetToken: 1}, (err, data) -> assert.equal err, null done() describe 'removePreset', () -> it 'should just run', (done) -> cam.removePreset {presetToken: Object.keys(cam.profiles)[0]}, (err, data) -> assert.equal err, null done() describe 'gotoHomePosition', () -> it 'should just run', (done) -> cam.gotoHomePosition {speed: {x: 1.0, y: 1.0, zoom: 1.0}}, (err, data) -> assert.equal err, null done() describe 'setHomePosition', () -> it 'should just run', (done) -> cam.setHomePosition {}, (err, data) -> assert.equal err, null done() describe 'absolute move', () -> it 'should returns empty RelativeResponseObject', (done) -> cam.absoluteMove { x: 1 y: 1 zoom: 1 }, done it 'should works without callback', () -> cam.absoluteMove { x: 0 y: 0 zoom: 1 } describe 'relative move', () -> it 'should returns empty RelativeResponseObject', (done) -> cam.relativeMove { speed: { x: 0.1 y: 0.1 } x: 1 y: 1 zoom: 1 }, done it 'should works without callback', () -> cam.relativeMove { speed: { x: 0.1 y: 0.1 } x: 1 y: 1 zoom: 1 } describe 'continuous move', () -> it 'should returns empty ContinuousResponseObject', (done) -> cam.continuousMove { x: 0.1 y: 0.1 zoom: 0 }, done it 'should set ommited pan-tilt parameters to zero', (done) -> cam.continuousMove { x: 0.1 zoom: 0 }, done describe 'stop', () -> it 'should stop all movements when options are ommited', (done) -> cam.stop done it 'should stop only zoom movement', (done) -> cam.stop {zoom: true}, done it 'should stop only pan-tilt movement', (done) -> cam.stop {panTilt: true}, done it 'should stop all movements', (done) -> cam.stop {zoom: true, panTilt: true}, done it 'should work without callback', (done) -> cam.stop {} cam.stop() done() describe 'getStatus', () -> it 'should returns position status', (done) -> cam.getStatus {}, (err, data) -> assert.equal err, null done()
[ { "context": "dex))\n\n contains: (string, target) ->\n # TODO(david): Make this not do a linear scan\n return this.", "end": 1208, "score": 0.8347347378730774, "start": 1203, "tag": "NAME", "value": "david" }, { "context": "contains_by_id: (string, target_id) ->\n # TODO(d...
src/public/javascripts/lib/woot.coffee
dwetterau/group-edit
1
define ['lib/constants'], (constants) -> initialize_string: () -> begin_character = id: name: '' number: 0 visible: false value: '' end_character = id: name: '' number: 1 visible: false value: '' return [begin_character, end_character] length: (string) -> return string.length get_character: (string, index) -> return string[index] compare_id: (id1, id2) -> if id1.name == id2.name return id1.number - id2.number else if id1.name < id2.name return -1 else if id1.name > id2.name return 1 else throw Error('Programming Error in compare_id') get_position: (string, target_id) -> for character, index in string if character.id.name == target_id.name and character.id.number == target_id.number return index return -1 insert: (string, character, index) -> string.splice(index, 0, character) set_visible: (string, index, visible) -> string[index].visible = visible sub_sequence: (string, start_index, end_index) -> return (c.id for c in string.slice(start_index + 1, end_index)) contains: (string, target) -> # TODO(david): Make this not do a linear scan return this.get_position(string, target.id) != -1 contains_by_id: (string, target_id) -> # TODO(david): Make this a fast lookup return this.get_position(string, target_id) != -1 value: (string) -> visible_string = '' for character in string if character.visible visible_string += character.value return visible_string ith_visible: (string, index) -> index_seen = -1 for character in string if character.visible index_seen += 1 if index_seen == index return character return null string_index_to_ith: (string, string_index) -> index_seen = -1 string_index_seen = -1 for character in string string_index_seen += 1 if character.visible index_seen += 1 if string_index == string_index_seen return index_seen return index_seen generate_insert: (index, visible_string, participant_name, sequence_number, string) -> before_character = this.ith_visible(string, index - 1) after_character = this.ith_visible(string, index) if not before_character before_character = string[0] if not after_character after_character = string[this.length(string) - 1] woot_character = id: number: sequence_number name: participant_name visible: true value: visible_string before_id: before_character.id after_id: after_character.id return woot_character generate_delete: (index, string) -> return this.ith_visible(string, index) execute_operation: (operation, character, string) -> if not this.is_executable operation, character, string return false if operation == constants.DELETE_OPERATION this.integrate_delete string, character else if operation == constants.INSERT_OPERATION this.integrate_insert string, character else throw Error("Unknown operation type") return true is_executable: (operation, character, string) -> if operation == constants.DELETE_OPERATION return this.contains string, character else if operation == constants.INSERT_OPERATION return this.contains_by_id(string, character.before_id) and this.contains_by_id(string, character.after_id) else throw Error("Unknown operation type") integrate_delete: (string, character) -> index = this.get_position(string, character.id) if index == -1 throw Error("Delete preconditions not met") this.set_visible string, index, false integrate_insert: (string, character) -> insert_position = this.determine_insert_position( string, character, character.before_id, character.after_id) this.insert string, character, insert_position determine_insert_position: (string, character, before_id, after_id) -> # Get the before and after character indices before_index = this.get_position string, before_id after_index = this.get_position string, after_id if before_index == -1 or after_index == -1 throw Error("Insert preconditions not met") sub_sequence = this.sub_sequence(string, before_index, after_index) if sub_sequence.length == 0 return after_index else # Add on the before and after indices again sub_sequence.unshift before_id sub_sequence.push after_id i = 1 while i < sub_sequence.length - 1 and this.compare_id(sub_sequence[i], character.id) < 0 i += 1 this.determine_insert_position string, character, sub_sequence[i - 1], sub_sequence[i]
101577
define ['lib/constants'], (constants) -> initialize_string: () -> begin_character = id: name: '' number: 0 visible: false value: '' end_character = id: name: '' number: 1 visible: false value: '' return [begin_character, end_character] length: (string) -> return string.length get_character: (string, index) -> return string[index] compare_id: (id1, id2) -> if id1.name == id2.name return id1.number - id2.number else if id1.name < id2.name return -1 else if id1.name > id2.name return 1 else throw Error('Programming Error in compare_id') get_position: (string, target_id) -> for character, index in string if character.id.name == target_id.name and character.id.number == target_id.number return index return -1 insert: (string, character, index) -> string.splice(index, 0, character) set_visible: (string, index, visible) -> string[index].visible = visible sub_sequence: (string, start_index, end_index) -> return (c.id for c in string.slice(start_index + 1, end_index)) contains: (string, target) -> # TODO(<NAME>): Make this not do a linear scan return this.get_position(string, target.id) != -1 contains_by_id: (string, target_id) -> # TODO(<NAME>): Make this a fast lookup return this.get_position(string, target_id) != -1 value: (string) -> visible_string = '' for character in string if character.visible visible_string += character.value return visible_string ith_visible: (string, index) -> index_seen = -1 for character in string if character.visible index_seen += 1 if index_seen == index return character return null string_index_to_ith: (string, string_index) -> index_seen = -1 string_index_seen = -1 for character in string string_index_seen += 1 if character.visible index_seen += 1 if string_index == string_index_seen return index_seen return index_seen generate_insert: (index, visible_string, participant_name, sequence_number, string) -> before_character = this.ith_visible(string, index - 1) after_character = this.ith_visible(string, index) if not before_character before_character = string[0] if not after_character after_character = string[this.length(string) - 1] woot_character = id: number: sequence_number name: <NAME> visible: true value: visible_string before_id: before_character.id after_id: after_character.id return woot_character generate_delete: (index, string) -> return this.ith_visible(string, index) execute_operation: (operation, character, string) -> if not this.is_executable operation, character, string return false if operation == constants.DELETE_OPERATION this.integrate_delete string, character else if operation == constants.INSERT_OPERATION this.integrate_insert string, character else throw Error("Unknown operation type") return true is_executable: (operation, character, string) -> if operation == constants.DELETE_OPERATION return this.contains string, character else if operation == constants.INSERT_OPERATION return this.contains_by_id(string, character.before_id) and this.contains_by_id(string, character.after_id) else throw Error("Unknown operation type") integrate_delete: (string, character) -> index = this.get_position(string, character.id) if index == -1 throw Error("Delete preconditions not met") this.set_visible string, index, false integrate_insert: (string, character) -> insert_position = this.determine_insert_position( string, character, character.before_id, character.after_id) this.insert string, character, insert_position determine_insert_position: (string, character, before_id, after_id) -> # Get the before and after character indices before_index = this.get_position string, before_id after_index = this.get_position string, after_id if before_index == -1 or after_index == -1 throw Error("Insert preconditions not met") sub_sequence = this.sub_sequence(string, before_index, after_index) if sub_sequence.length == 0 return after_index else # Add on the before and after indices again sub_sequence.unshift before_id sub_sequence.push after_id i = 1 while i < sub_sequence.length - 1 and this.compare_id(sub_sequence[i], character.id) < 0 i += 1 this.determine_insert_position string, character, sub_sequence[i - 1], sub_sequence[i]
true
define ['lib/constants'], (constants) -> initialize_string: () -> begin_character = id: name: '' number: 0 visible: false value: '' end_character = id: name: '' number: 1 visible: false value: '' return [begin_character, end_character] length: (string) -> return string.length get_character: (string, index) -> return string[index] compare_id: (id1, id2) -> if id1.name == id2.name return id1.number - id2.number else if id1.name < id2.name return -1 else if id1.name > id2.name return 1 else throw Error('Programming Error in compare_id') get_position: (string, target_id) -> for character, index in string if character.id.name == target_id.name and character.id.number == target_id.number return index return -1 insert: (string, character, index) -> string.splice(index, 0, character) set_visible: (string, index, visible) -> string[index].visible = visible sub_sequence: (string, start_index, end_index) -> return (c.id for c in string.slice(start_index + 1, end_index)) contains: (string, target) -> # TODO(PI:NAME:<NAME>END_PI): Make this not do a linear scan return this.get_position(string, target.id) != -1 contains_by_id: (string, target_id) -> # TODO(PI:NAME:<NAME>END_PI): Make this a fast lookup return this.get_position(string, target_id) != -1 value: (string) -> visible_string = '' for character in string if character.visible visible_string += character.value return visible_string ith_visible: (string, index) -> index_seen = -1 for character in string if character.visible index_seen += 1 if index_seen == index return character return null string_index_to_ith: (string, string_index) -> index_seen = -1 string_index_seen = -1 for character in string string_index_seen += 1 if character.visible index_seen += 1 if string_index == string_index_seen return index_seen return index_seen generate_insert: (index, visible_string, participant_name, sequence_number, string) -> before_character = this.ith_visible(string, index - 1) after_character = this.ith_visible(string, index) if not before_character before_character = string[0] if not after_character after_character = string[this.length(string) - 1] woot_character = id: number: sequence_number name: PI:NAME:<NAME>END_PI visible: true value: visible_string before_id: before_character.id after_id: after_character.id return woot_character generate_delete: (index, string) -> return this.ith_visible(string, index) execute_operation: (operation, character, string) -> if not this.is_executable operation, character, string return false if operation == constants.DELETE_OPERATION this.integrate_delete string, character else if operation == constants.INSERT_OPERATION this.integrate_insert string, character else throw Error("Unknown operation type") return true is_executable: (operation, character, string) -> if operation == constants.DELETE_OPERATION return this.contains string, character else if operation == constants.INSERT_OPERATION return this.contains_by_id(string, character.before_id) and this.contains_by_id(string, character.after_id) else throw Error("Unknown operation type") integrate_delete: (string, character) -> index = this.get_position(string, character.id) if index == -1 throw Error("Delete preconditions not met") this.set_visible string, index, false integrate_insert: (string, character) -> insert_position = this.determine_insert_position( string, character, character.before_id, character.after_id) this.insert string, character, insert_position determine_insert_position: (string, character, before_id, after_id) -> # Get the before and after character indices before_index = this.get_position string, before_id after_index = this.get_position string, after_id if before_index == -1 or after_index == -1 throw Error("Insert preconditions not met") sub_sequence = this.sub_sequence(string, before_index, after_index) if sub_sequence.length == 0 return after_index else # Add on the before and after indices again sub_sequence.unshift before_id sub_sequence.push after_id i = 1 while i < sub_sequence.length - 1 and this.compare_id(sub_sequence[i], character.id) < 0 i += 1 this.determine_insert_position string, character, sub_sequence[i - 1], sub_sequence[i]
[ { "context": "k()\n\n setupFollowButton: (model, el) ->\n key = model.id\n @followButtonViews ?= {}\n @followButtonVie", "end": 2138, "score": 0.9795193076133728, "start": 2130, "tag": "KEY", "value": "model.id" } ]
src/desktop/apps/artsy_primer/personalize/client/views/categories.coffee
kanaabe/force
0
_ = require 'underscore' StepView = require './step.coffee' Items = require '../../../../../collections/items.coffee' Gene = require '../../../../../models/gene.coffee' { setSkipLabel } = require '../mixins/followable.coffee' { FollowButton, Following } = require '../../../../../components/follow_button/index.coffee' template = -> require('../../templates/categories.jade') arguments... categoryTemplate = -> require('../../templates/category.jade') arguments... module.exports = class CategoriesView extends StepView setIds: '1': '5407293572616943604a0c00' # http://admin.artsy.net/set/5407293572616943604a0c00 '2': '53bb0cd872616978b7621200' # http://admin.artsy.net/set/53bb0cd872616978b7621200 # Level 3 users *currently* don't hit this step '3': '53bb0cd872616978b7621200' # http://admin.artsy.net/set/53bb0cd872616978b7621200 setSkipLabel: setSkipLabel events: 'click .artsy-primer-personalize-category': 'followCategory' 'click .artsy-primer-personalize-secondary-category': 'followCategory' initialize: (options) -> super @following = new Following null, kind: 'gene' @categories = new Items [], id: @setIds[@state.get('current_level')], item_type: 'FeaturedLink' @categories.fetch() @listenToOnce @categories, 'sync', @bootstrap @listenTo @following, 'add', (follow) -> $(".follow-button[data-id=#{follow.get('gene').id}]") .parent() .find '.artsy-primer-personalize-following-overlay' .addClass 'is-clicked' @listenTo @following, 'remove', (follow) -> $(".follow-button[data-id=#{follow.get('gene').id}]") .parent() .find '.artsy-primer-personalize-following-overlay' .removeClass 'is-clicked' bootstrap: -> @$('#artsy-primer-personalize-categories').html @setupCategories @categories @$('#artsy-primer-personalize-category-anything-else').show() @setupFollowButtons @categories (@$textarea = @$('textarea')).one 'input', (e) => @setSkipLabel() followCategory: (e) -> $(e.currentTarget).find('.follow-button').click() setupFollowButton: (model, el) -> key = model.id @followButtonViews ?= {} @followButtonViews[key].remove() if @followButtonViews[key]? @followButtonViews[key] = new FollowButton context_page: "Personalize page" modelName: 'Gene' model: model el: el following: @following setupFollowButtons: (categories) -> @following.syncFollows categories.pluck('gene_id') categories.each (category) => model = new Gene id: category.get 'gene_id' el = @$(".follow-button[data-id=#{category.get('gene_id')}]") button = @setupFollowButton model, el @listenTo button, 'click', @setSkipLabel, this setupCategories: (categories) -> categories.each (category) -> # Set gene_id based on the slugs category.set('gene_id', category.get('href').replace '/gene/', '') @renderCategories categories renderCategories: (categories) -> categories.map((category) -> categoryTemplate category: category ).join '' advance: -> @user.set notes: @$textarea.val() if @$textarea super render: -> @$el.html template(state: @state) this remove: -> if @categories.fullCollection? then @categories.fullCollection.map (category) => @followButtonViews[category.get 'gene_id']?.remove() super
203708
_ = require 'underscore' StepView = require './step.coffee' Items = require '../../../../../collections/items.coffee' Gene = require '../../../../../models/gene.coffee' { setSkipLabel } = require '../mixins/followable.coffee' { FollowButton, Following } = require '../../../../../components/follow_button/index.coffee' template = -> require('../../templates/categories.jade') arguments... categoryTemplate = -> require('../../templates/category.jade') arguments... module.exports = class CategoriesView extends StepView setIds: '1': '5407293572616943604a0c00' # http://admin.artsy.net/set/5407293572616943604a0c00 '2': '53bb0cd872616978b7621200' # http://admin.artsy.net/set/53bb0cd872616978b7621200 # Level 3 users *currently* don't hit this step '3': '53bb0cd872616978b7621200' # http://admin.artsy.net/set/53bb0cd872616978b7621200 setSkipLabel: setSkipLabel events: 'click .artsy-primer-personalize-category': 'followCategory' 'click .artsy-primer-personalize-secondary-category': 'followCategory' initialize: (options) -> super @following = new Following null, kind: 'gene' @categories = new Items [], id: @setIds[@state.get('current_level')], item_type: 'FeaturedLink' @categories.fetch() @listenToOnce @categories, 'sync', @bootstrap @listenTo @following, 'add', (follow) -> $(".follow-button[data-id=#{follow.get('gene').id}]") .parent() .find '.artsy-primer-personalize-following-overlay' .addClass 'is-clicked' @listenTo @following, 'remove', (follow) -> $(".follow-button[data-id=#{follow.get('gene').id}]") .parent() .find '.artsy-primer-personalize-following-overlay' .removeClass 'is-clicked' bootstrap: -> @$('#artsy-primer-personalize-categories').html @setupCategories @categories @$('#artsy-primer-personalize-category-anything-else').show() @setupFollowButtons @categories (@$textarea = @$('textarea')).one 'input', (e) => @setSkipLabel() followCategory: (e) -> $(e.currentTarget).find('.follow-button').click() setupFollowButton: (model, el) -> key = <KEY> @followButtonViews ?= {} @followButtonViews[key].remove() if @followButtonViews[key]? @followButtonViews[key] = new FollowButton context_page: "Personalize page" modelName: 'Gene' model: model el: el following: @following setupFollowButtons: (categories) -> @following.syncFollows categories.pluck('gene_id') categories.each (category) => model = new Gene id: category.get 'gene_id' el = @$(".follow-button[data-id=#{category.get('gene_id')}]") button = @setupFollowButton model, el @listenTo button, 'click', @setSkipLabel, this setupCategories: (categories) -> categories.each (category) -> # Set gene_id based on the slugs category.set('gene_id', category.get('href').replace '/gene/', '') @renderCategories categories renderCategories: (categories) -> categories.map((category) -> categoryTemplate category: category ).join '' advance: -> @user.set notes: @$textarea.val() if @$textarea super render: -> @$el.html template(state: @state) this remove: -> if @categories.fullCollection? then @categories.fullCollection.map (category) => @followButtonViews[category.get 'gene_id']?.remove() super
true
_ = require 'underscore' StepView = require './step.coffee' Items = require '../../../../../collections/items.coffee' Gene = require '../../../../../models/gene.coffee' { setSkipLabel } = require '../mixins/followable.coffee' { FollowButton, Following } = require '../../../../../components/follow_button/index.coffee' template = -> require('../../templates/categories.jade') arguments... categoryTemplate = -> require('../../templates/category.jade') arguments... module.exports = class CategoriesView extends StepView setIds: '1': '5407293572616943604a0c00' # http://admin.artsy.net/set/5407293572616943604a0c00 '2': '53bb0cd872616978b7621200' # http://admin.artsy.net/set/53bb0cd872616978b7621200 # Level 3 users *currently* don't hit this step '3': '53bb0cd872616978b7621200' # http://admin.artsy.net/set/53bb0cd872616978b7621200 setSkipLabel: setSkipLabel events: 'click .artsy-primer-personalize-category': 'followCategory' 'click .artsy-primer-personalize-secondary-category': 'followCategory' initialize: (options) -> super @following = new Following null, kind: 'gene' @categories = new Items [], id: @setIds[@state.get('current_level')], item_type: 'FeaturedLink' @categories.fetch() @listenToOnce @categories, 'sync', @bootstrap @listenTo @following, 'add', (follow) -> $(".follow-button[data-id=#{follow.get('gene').id}]") .parent() .find '.artsy-primer-personalize-following-overlay' .addClass 'is-clicked' @listenTo @following, 'remove', (follow) -> $(".follow-button[data-id=#{follow.get('gene').id}]") .parent() .find '.artsy-primer-personalize-following-overlay' .removeClass 'is-clicked' bootstrap: -> @$('#artsy-primer-personalize-categories').html @setupCategories @categories @$('#artsy-primer-personalize-category-anything-else').show() @setupFollowButtons @categories (@$textarea = @$('textarea')).one 'input', (e) => @setSkipLabel() followCategory: (e) -> $(e.currentTarget).find('.follow-button').click() setupFollowButton: (model, el) -> key = PI:KEY:<KEY>END_PI @followButtonViews ?= {} @followButtonViews[key].remove() if @followButtonViews[key]? @followButtonViews[key] = new FollowButton context_page: "Personalize page" modelName: 'Gene' model: model el: el following: @following setupFollowButtons: (categories) -> @following.syncFollows categories.pluck('gene_id') categories.each (category) => model = new Gene id: category.get 'gene_id' el = @$(".follow-button[data-id=#{category.get('gene_id')}]") button = @setupFollowButton model, el @listenTo button, 'click', @setSkipLabel, this setupCategories: (categories) -> categories.each (category) -> # Set gene_id based on the slugs category.set('gene_id', category.get('href').replace '/gene/', '') @renderCategories categories renderCategories: (categories) -> categories.map((category) -> categoryTemplate category: category ).join '' advance: -> @user.set notes: @$textarea.val() if @$textarea super render: -> @$el.html template(state: @state) this remove: -> if @categories.fullCollection? then @categories.fullCollection.map (category) => @followButtonViews[category.get 'gene_id']?.remove() super
[ { "context": "\nnikita = require '@nikitajs/core'\n{cmd} = require '../src/query'\n{tags, ssh, ", "end": 28, "score": 0.8258736729621887, "start": 26, "tag": "USERNAME", "value": "js" }, { "context": "res_user_3'\n .db.user\n username: 'postgres_user_3'\n pas...
packages/db/test/database.coffee
DanielJohnHarty/node-nikita
1
nikita = require '@nikitajs/core' {cmd} = require '../src/query' {tags, ssh, db} = require './test' they = require('ssh2-they').configure ssh... return unless tags.db for engine, _ of db then do (engine) -> describe "db.database #{engine}", -> they 'add new database', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_0a' .db.database.remove 'postgres_db_0b' .db.database database: 'postgres_db_0a' .db.database 'postgres_db_0b' .db.database.remove 'postgres_db_0a' .db.database.remove 'postgres_db_0b' .promise() they 'status not modified new database', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_1' .db.database 'postgres_db_1' .db.database 'postgres_db_1', (err, {status}) -> status.should.be.false() unless err .db.database.remove 'postgres_db_1' .promise() describe 'user', -> they 'which is existing', ({ssh}) -> nikita ssh: ssh db: db[engine] debug: true .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .db.user username: 'postgres_user_3' password: 'postgres_user_3' .db.database database: 'postgres_db_3' user: 'postgres_user_3' .system.execute cmd: switch engine when 'mariadb', 'mysql' then cmd(db[engine], database: 'mysql', "SELECT user FROM db WHERE db='postgres_db_3';") + " | grep 'postgres_user_3'" when 'postgresql' then cmd(db[engine], database: 'postgres_db_3', '\\l') + " | egrep '^postgres_user_3='" , (err, {status}) -> status.should.be.true() unless err .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .promise() they 'honors status', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .db.user username: 'postgres_user_3' password: 'postgres_user_3' .db.database database: 'postgres_db_3' .db.database database: 'postgres_db_3' user: 'postgres_user_3' , (err, {status}) -> status.should.be.true() .db.database database: 'postgres_db_3' user: 'postgres_user_3' , (err, {status}) -> status.should.be.false() .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .promise() they 'which is not existing', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_4' .db.user.remove 'postgres_user_4' .db.database database: 'postgres_db_4' user: 'postgres_user_4' relax: true , (err) -> err.message.should.eql 'DB user does not exists: postgres_user_4' .db.database.remove 'postgres_db_4' .db.user.remove 'postgres_user_4' .promise()
157504
nikita = require '@nikitajs/core' {cmd} = require '../src/query' {tags, ssh, db} = require './test' they = require('ssh2-they').configure ssh... return unless tags.db for engine, _ of db then do (engine) -> describe "db.database #{engine}", -> they 'add new database', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_0a' .db.database.remove 'postgres_db_0b' .db.database database: 'postgres_db_0a' .db.database 'postgres_db_0b' .db.database.remove 'postgres_db_0a' .db.database.remove 'postgres_db_0b' .promise() they 'status not modified new database', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_1' .db.database 'postgres_db_1' .db.database 'postgres_db_1', (err, {status}) -> status.should.be.false() unless err .db.database.remove 'postgres_db_1' .promise() describe 'user', -> they 'which is existing', ({ssh}) -> nikita ssh: ssh db: db[engine] debug: true .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .db.user username: 'postgres_user_3' password: '<PASSWORD>' .db.database database: 'postgres_db_3' user: 'postgres_user_3' .system.execute cmd: switch engine when 'mariadb', 'mysql' then cmd(db[engine], database: 'mysql', "SELECT user FROM db WHERE db='postgres_db_3';") + " | grep 'postgres_user_3'" when 'postgresql' then cmd(db[engine], database: 'postgres_db_3', '\\l') + " | egrep '^postgres_user_3='" , (err, {status}) -> status.should.be.true() unless err .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .promise() they 'honors status', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .db.user username: 'postgres_user_3' password: '<PASSWORD>' .db.database database: 'postgres_db_3' .db.database database: 'postgres_db_3' user: 'postgres_user_3' , (err, {status}) -> status.should.be.true() .db.database database: 'postgres_db_3' user: 'postgres_user_3' , (err, {status}) -> status.should.be.false() .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .promise() they 'which is not existing', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_4' .db.user.remove 'postgres_user_4' .db.database database: 'postgres_db_4' user: 'postgres_user_4' relax: true , (err) -> err.message.should.eql 'DB user does not exists: postgres_user_4' .db.database.remove 'postgres_db_4' .db.user.remove 'postgres_user_4' .promise()
true
nikita = require '@nikitajs/core' {cmd} = require '../src/query' {tags, ssh, db} = require './test' they = require('ssh2-they').configure ssh... return unless tags.db for engine, _ of db then do (engine) -> describe "db.database #{engine}", -> they 'add new database', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_0a' .db.database.remove 'postgres_db_0b' .db.database database: 'postgres_db_0a' .db.database 'postgres_db_0b' .db.database.remove 'postgres_db_0a' .db.database.remove 'postgres_db_0b' .promise() they 'status not modified new database', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_1' .db.database 'postgres_db_1' .db.database 'postgres_db_1', (err, {status}) -> status.should.be.false() unless err .db.database.remove 'postgres_db_1' .promise() describe 'user', -> they 'which is existing', ({ssh}) -> nikita ssh: ssh db: db[engine] debug: true .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .db.user username: 'postgres_user_3' password: 'PI:PASSWORD:<PASSWORD>END_PI' .db.database database: 'postgres_db_3' user: 'postgres_user_3' .system.execute cmd: switch engine when 'mariadb', 'mysql' then cmd(db[engine], database: 'mysql', "SELECT user FROM db WHERE db='postgres_db_3';") + " | grep 'postgres_user_3'" when 'postgresql' then cmd(db[engine], database: 'postgres_db_3', '\\l') + " | egrep '^postgres_user_3='" , (err, {status}) -> status.should.be.true() unless err .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .promise() they 'honors status', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .db.user username: 'postgres_user_3' password: 'PI:PASSWORD:<PASSWORD>END_PI' .db.database database: 'postgres_db_3' .db.database database: 'postgres_db_3' user: 'postgres_user_3' , (err, {status}) -> status.should.be.true() .db.database database: 'postgres_db_3' user: 'postgres_user_3' , (err, {status}) -> status.should.be.false() .db.database.remove 'postgres_db_3' .db.user.remove 'postgres_user_3' .promise() they 'which is not existing', ({ssh}) -> nikita ssh: ssh db: db[engine] .db.database.remove 'postgres_db_4' .db.user.remove 'postgres_user_4' .db.database database: 'postgres_db_4' user: 'postgres_user_4' relax: true , (err) -> err.message.should.eql 'DB user does not exists: postgres_user_4' .db.database.remove 'postgres_db_4' .db.user.remove 'postgres_user_4' .promise()
[ { "context": "tom = Test.Ajax.Customer.createFromValues({name: 'Tom'})\n Test.Ajax.Customer.registerServerId(Te", "end": 1504, "score": 0.7967078685760498, "start": 1501, "tag": "NAME", "value": "Tom" }, { "context": "tom = Test.Ajax.Customer.createFromValues({name: 'Tom'})\n ...
src/spec/ajax-spec.coffee
creativeprogramming/mozart
1
Test = {} Test.Ajax = {} Test.Ajax.getId = -> Math.round(Math.random()*9999999) describe 'Mozart.Ajax', -> beforeEach -> Test.server = sinon.fakeServer.create() Test.Ajax.Customer = Mozart.Model.create { modelName: 'Customer' } Test.Ajax.Customer.attributes { 'name': 'string' } Test.Ajax.Customer.ajax { url: '/test/customers', interface: 'rest' } Test.Ajax.Store = Mozart.Model.create { modelName: 'Store' } Test.Ajax.Store.attributes { 'name': 'string' } Test.Ajax.Store.ajax { url: '/test/stores', interface: 'rest' } Test.Ajax.Product = Mozart.Model.create { modelName: 'Product' } Test.Ajax.Product.attributes { 'name': 'string' } Test.Ajax.Product.ajax { url: '/test/products', interface: 'rest' } Test.Ajax.Order = Mozart.Model.create { modelName: 'Order' } Test.Ajax.Order.ajax { url: '/test/orders', interface: 'rest' } Test.Ajax.Store.hasMany Test.Ajax.Product, 'products' Test.Ajax.Product.belongsTo Test.Ajax.Store, 'store' Test.Ajax.Order.belongsToPoly [Test.Ajax.Store, Test.Ajax.Customer], 'from', 'from_id', 'from_type' afterEach -> Test.server.restore() describe 'ajax core', -> it 'should provide the ajax model extension method', -> expect(Test.Ajax.Customer.url).toEqual('/test/customers') expect(Test.Ajax.Customer.interface).toEqual('rest') describe 'server id mapping methods', -> beforeEach -> Test.Ajax.tom = Test.Ajax.Customer.createFromValues({name: 'Tom'}) Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id, '1236') Test.Ajax.bigcom = Test.Ajax.Store.createFromValues({name: 'Bigcom'}) Test.Ajax.Store.registerServerId(Test.Ajax.bigcom.id, '2348') it 'should provide the registerServerId method on model', -> expect(Test.Ajax.Customer.getClientId('1236')).toEqual(Test.Ajax.tom.id) it 'should provide the unRegisterServerId method on model', -> Test.Ajax.Customer.unRegisterServerId(Test.Ajax.tom.id, '1236') expect(Test.Ajax.Customer.getClientId('1236')).toEqual(undefined) it 'should provide the getServerId method on model', -> expect(Test.Ajax.Customer.getServerId(Test.Ajax.tom.id)).toEqual('1236') it 'should provide the getServerId method on instance', -> expect(Test.Ajax.tom.getServerId()).toEqual('1236') it 'should provide the getClientId method', -> expect(Test.Ajax.Customer.getClientId('1236')).toEqual(Test.Ajax.tom.id) it 'should not pollute other models when registering server ids', -> expect(Test.Ajax.Customer.getClientId('2348')).toEqual(undefined) expect(Test.Ajax.Customer.getServerId(Test.Ajax.bigcom.id)).toEqual(undefined) expect(Test.Ajax.Store.getClientId('1236')).toEqual(undefined) expect(Test.Ajax.Store.getServerId(Test.Ajax.tom.id)).toEqual(undefined) describe 'server integration', -> beforeEach -> Test.Ajax.tom = Test.Ajax.Customer.createFromValues({name: 'Tom'}) Test.Ajax.jason = Test.Ajax.Customer.initInstance({name: 'Jason'}) Test.Ajax.tomId = Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id, Test.Ajax.getId()) Test.Ajax.subcaller = onLoad: -> onLoadAll: -> onCreate: -> onUpdate: -> onDestroy: -> onChange: -> it 'should load all from server on model load', -> runs -> Test.server.respondWith("GET", "/test/customers", [ 200, { "Content-Type": "application/json" }, '[ { "id": 456345, "name": "Jason O\'Conal" }, { "id": 345346, "name": "Scott Christopher" }, { "id": 234235, "name": "Drew Karrasch" }, { "id": 876976, "name": "Luke Eller" }, { "id": 786788, "name": "Chris Roper" }, { "id": 123884, "name": "Pascal Zajac" }]' ] ) spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.Ajax.Customer.loadAll() Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onChange.calls.length > 0), "onChange not fired", 1000) runs -> expect(Test.Ajax.subcaller.onChange).toHaveBeenCalled() jason = Test.Ajax.Customer.findByAttribute("name","Jason O'Conal")[0] expect(jason).not.toBeNull() expect(jason.getServerId()).toEqual(456345) expect(Test.Ajax.Customer.findByAttribute("name","Jason O'Conal")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","Scott Christopher")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","Drew Karrasch")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","Luke Eller")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","Chris Roper")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","Pascal Zajac")).not.toBeNull() it 'should load data from server on load with id', -> runs -> Test.server.respondWith("GET", "/test/customers/7732", [ 200, { "Content-Type": "application/json" }, '{ "id": 7732, "name": "Tim Massey" }' ]) spyOn(Test.Ajax.subcaller,'onLoad') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('loadComplete', Test.Ajax.subcaller.onLoad) Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.Ajax.Customer.load(7732) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onChange.calls.length > 0), "onChange not fired", 1000) runs -> expect(Test.Ajax.subcaller.onLoad).toHaveBeenCalled() expect(Test.Ajax.subcaller.onChange).toHaveBeenCalled() instid = Test.Ajax.Customer.getClientId(7732) expect(instid).not.toBeNull() instance = Test.Ajax.Customer.findById(instid) expect(instance.name).toEqual('Tim Massey') it 'should load data from server on instance load', -> runs -> Test.server.respondWith("GET", "/test/customers/2346", [ 200, { "Content-Type": "application/json" }, '{ "id": 2346, "name": "Tom Cully" }' ]) Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id,2346) spyOn(Test.Ajax.subcaller,'onLoad') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('loadComplete', Test.Ajax.subcaller.onLoad) Test.Ajax.tom.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.Ajax.tom.load() Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onChange.calls.length > 0), "onChange not fired", 1000) runs -> expect(Test.Ajax.subcaller.onLoad).toHaveBeenCalledWith(Test.Ajax.tom, undefined) expect(Test.Ajax.subcaller.onChange).toHaveBeenCalled() expect(Test.Ajax.tom.name).toEqual("Tom Cully") expect(Test.Ajax.tom.getServerId()).toEqual(2346) it 'should post data to server on save when instance isn\'t registered', -> runs -> Test.server.respondWith("POST", "/test/customers", [ 200, { "Content-Type": "application/json" }, '{ "id": 3012 }' ]) spyOn(Test.Ajax.subcaller,'onCreate') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('createComplete', Test.Ajax.subcaller.onCreate) Test.Ajax.jason.save() Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onCreate.calls.length > 0), "onCreate not fired", 1000) runs -> expect(Test.Ajax.subcaller.onCreate).toHaveBeenCalled() expect(Test.Ajax.subcaller.onChange).not.toHaveBeenCalled() serverId = Test.Ajax.Customer.getServerId(Test.Ajax.jason.id) expect(serverId).toEqual(3012) it 'should put data to server on save', -> runs -> Test.server.respondWith(/\/customers\/(\d+)/, (xhr, id) -> xhr.respond(200, { "Content-Type": "application/json" }, '[{ "id": ' + id + ' }]') ) spyOn(Test.Ajax.subcaller,'onUpdate') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('updateComplete', Test.Ajax.subcaller.onUpdate) Test.Ajax.tom.set('name','Thomas Hugh Cully') Test.Ajax.tom.save() Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onUpdate.calls.length > 0), "onUpdate not fired", 1000) runs -> expect(Test.Ajax.subcaller.onUpdate).toHaveBeenCalledWith(Test.Ajax.tom, undefined) expect(Test.Ajax.subcaller.onChange).not.toHaveBeenCalled() it 'should destroy on server and unregister on destroy', -> runs -> Test.server.respondWith(/\/customers\/(\d+)/, (xhr, id) -> xhr.respond(200, { "Content-Type": "application/json" }, '[{ "id": ' + id + ' }]') ) spyOn(Test.Ajax.subcaller,'onDestroy') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('destroyComplete', Test.Ajax.subcaller.onDestroy) Test.Ajax.tom.destroy() Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onDestroy.calls.length > 0), "onDestroy not fired", 1000) runs -> expect(Test.Ajax.subcaller.onDestroy).toHaveBeenCalledWith(Test.Ajax.tomId, undefined) expect(Test.Ajax.Customer.getClientId(Test.Ajax.tomId)).not.toBeDefined() expect(Test.Ajax.subcaller.onChange).not.toHaveBeenCalled() describe 'model client -> server object mapping', -> beforeEach -> Test.Ajax.tom = Test.Ajax.Customer.createFromValues({name: 'Tom'}) Test.Ajax.tomId = Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id,Test.Ajax.getId()) describe 'for simple objects', -> it 'should provide the toServerObject method', -> object = Test.Ajax.Customer.toServerObject(Test.Ajax.tom) expect(object).not.toBe(Test.Ajax.tom) expect(object.name).toEqual(Test.Ajax.tom.name) expect(object.id).not.toEqual(Test.Ajax.tom.id) expect(object.id).toEqual(Test.Ajax.tomId) it 'should provide the toClientObject method, when the clientside instance does not exist', -> Test.Ajax.chrisID = Test.Ajax.getId() object = { id: Test.Ajax.chrisID name: 'Chris' } clientObject = Test.Ajax.Customer.toClientObject(object) expect(clientObject.id).toEqual(undefined) expect(Test.Ajax.Customer.records[clientObject.id]).toEqual(undefined) expect(clientObject.name).toEqual('Chris') expect(clientObject.id).not.toEqual(Test.Ajax.chrisID) it 'should provide the toClientObject method, when the clientside instance does exist', -> object = { id: Test.Ajax.tomId name: 'Tony' } clientObject = Test.Ajax.Customer.toClientObject(object) expect(Test.Ajax.Customer.records[clientObject.id]).toBe(Test.Ajax.tom) expect(clientObject.name).toEqual('Tony') expect(clientObject.id).not.toEqual(Test.Ajax.tomId) describe 'for objects with foreign keys', -> beforeEach -> Test.Ajax.bcId = Test.Ajax.getId() Test.Ajax.bc = Test.Ajax.Store.createFromValues({name: 'BigCom'}) Test.Ajax.Store.registerServerId(Test.Ajax.bc.id, Test.Ajax.bcId) Test.Ajax.shoeId = Test.Ajax.getId() Test.Ajax.shoe = Test.Ajax.Product.createFromValues { name: 'Red Shoe' } Test.Ajax.Product.registerServerId(Test.Ajax.shoe.id, Test.Ajax.shoeId) Test.Ajax.hatId = Test.Ajax.getId() Test.Ajax.hat = Test.Ajax.Product.createFromValues { name: 'Blue Hat' } Test.Ajax.Product.registerServerId(Test.Ajax.hat.id, Test.Ajax.hatId) Test.Ajax.scarf = Test.Ajax.Product.createFromValues { name: 'Green Scarf' } # No Scarf ServerId = unsaved to server. Test.Ajax.tomId = Test.Ajax.getId() Test.Ajax.tom = Test.Ajax.Customer.createFromValues { name: 'Tom' } Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id, Test.Ajax.tomId) Test.Ajax.shoeOrderId = Test.Ajax.getId() Test.Ajax.shoeOrder = Test.Ajax.Order.createFromValues( { name: 'Customer Shoe Order' }) Test.Ajax.Order.registerServerId(Test.Ajax.shoeOrder.id, Test.Ajax.shoeOrderId) Test.Ajax.shoeSupplyOrderId = Test.Ajax.getId() Test.Ajax.shoeSupplyOrder = Test.Ajax.Order.createFromValues( { name: 'Store Shoe Order'}) Test.Ajax.Order.registerServerId(Test.Ajax.shoeSupplyOrder.id, Test.Ajax.shoeSupplyOrderId) Test.Ajax.bc.products().add(Test.Ajax.shoe) Test.Ajax.bc.products().add(Test.Ajax.hat) Test.Ajax.bc.products().add(Test.Ajax.scarf) Test.Ajax.shoeOrder.from(Test.Ajax.tom) #Test.Ajax.shoeSupplyOrder.from(Test.Ajax.bc) it 'should translate non-poly fks properly in toServerObject method', -> object = { id: Test.Ajax.shoeId name: 'Old Shoe' store_id: Test.Ajax.bcId } clientObject = Test.Ajax.Product.toClientObject(object) expect(Test.Ajax.Product.records[clientObject.id]).toBe(Test.Ajax.shoe) expect(Test.Ajax.Store.records[clientObject.store_id]).toBe(Test.Ajax.bc) it 'should translate non-poly fks in toServerObject when fk is null', -> object = { id: Test.Ajax.shoeId name: 'Old Shoe' store_id: null } clientObject = Test.Ajax.Product.toClientObject(object) expect(Test.Ajax.Product.records[clientObject.id]).toBe(Test.Ajax.shoe) expect(clientObject.store_id).toBeNull() it 'should translate poly fks properly in toServerObject method', -> object = { name: 'Old Shoe' from_id: Test.Ajax.tomId from_type: 'Customer' } clientObject = Test.Ajax.Order.toClientObject(object) expect(Test.Ajax.Customer.records[clientObject.from_id]).toBe(Test.Ajax.tom) object = { name: 'Old Shoe' from_id: Test.Ajax.bcId from_type: 'Store' } clientObject = Test.Ajax.Order.toClientObject(object) expect(Test.Ajax.Store.records[clientObject.from_id]).toBe(Test.Ajax.bc) it 'should translate non-poly fks in toServerObject when fk is null', -> object = { name: 'Old Shoe' from_id: null from_type: null } clientObject = Test.Ajax.Order.toClientObject(object) expect(clientObject.from_id).toBeNull() describe 'Nested Objects', -> beforeEach -> Test.Ajax.Nested = Mozart.Model.create { modelName: 'Nested' } Test.Ajax.Nested.attributes { 'name': 'string', 'nested':'object' } Test.Ajax.Nested.ajax { url: '/test/nestedjson', interface: 'rest' } it 'should read a nested object', -> runs -> Test.server.respondWith(/\/test\/nestedjson\/(\d+)/, (xhr, id) -> xhr.respond(200, { "Content-Type": "application/json" }, JSON.stringify({ id: id, name: 'horse', nested: { test1:1, test2: 2, listof: [1,2,3] } })) ) Test.Ajax.Nested.load(2) Test.server.respond() waits(200) runs -> x = Test.Ajax.Nested.all()[0] expect(x.name).toEqual('horse') expect(x.nested.test1).toEqual(1) expect(x.nested.test2).toEqual(2) expect(x.nested.listof.length).toEqual(3)
159907
Test = {} Test.Ajax = {} Test.Ajax.getId = -> Math.round(Math.random()*9999999) describe 'Mozart.Ajax', -> beforeEach -> Test.server = sinon.fakeServer.create() Test.Ajax.Customer = Mozart.Model.create { modelName: 'Customer' } Test.Ajax.Customer.attributes { 'name': 'string' } Test.Ajax.Customer.ajax { url: '/test/customers', interface: 'rest' } Test.Ajax.Store = Mozart.Model.create { modelName: 'Store' } Test.Ajax.Store.attributes { 'name': 'string' } Test.Ajax.Store.ajax { url: '/test/stores', interface: 'rest' } Test.Ajax.Product = Mozart.Model.create { modelName: 'Product' } Test.Ajax.Product.attributes { 'name': 'string' } Test.Ajax.Product.ajax { url: '/test/products', interface: 'rest' } Test.Ajax.Order = Mozart.Model.create { modelName: 'Order' } Test.Ajax.Order.ajax { url: '/test/orders', interface: 'rest' } Test.Ajax.Store.hasMany Test.Ajax.Product, 'products' Test.Ajax.Product.belongsTo Test.Ajax.Store, 'store' Test.Ajax.Order.belongsToPoly [Test.Ajax.Store, Test.Ajax.Customer], 'from', 'from_id', 'from_type' afterEach -> Test.server.restore() describe 'ajax core', -> it 'should provide the ajax model extension method', -> expect(Test.Ajax.Customer.url).toEqual('/test/customers') expect(Test.Ajax.Customer.interface).toEqual('rest') describe 'server id mapping methods', -> beforeEach -> Test.Ajax.tom = Test.Ajax.Customer.createFromValues({name: '<NAME>'}) Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id, '1236') Test.Ajax.bigcom = Test.Ajax.Store.createFromValues({name: 'Bigcom'}) Test.Ajax.Store.registerServerId(Test.Ajax.bigcom.id, '2348') it 'should provide the registerServerId method on model', -> expect(Test.Ajax.Customer.getClientId('1236')).toEqual(Test.Ajax.tom.id) it 'should provide the unRegisterServerId method on model', -> Test.Ajax.Customer.unRegisterServerId(Test.Ajax.tom.id, '1236') expect(Test.Ajax.Customer.getClientId('1236')).toEqual(undefined) it 'should provide the getServerId method on model', -> expect(Test.Ajax.Customer.getServerId(Test.Ajax.tom.id)).toEqual('1236') it 'should provide the getServerId method on instance', -> expect(Test.Ajax.tom.getServerId()).toEqual('1236') it 'should provide the getClientId method', -> expect(Test.Ajax.Customer.getClientId('1236')).toEqual(Test.Ajax.tom.id) it 'should not pollute other models when registering server ids', -> expect(Test.Ajax.Customer.getClientId('2348')).toEqual(undefined) expect(Test.Ajax.Customer.getServerId(Test.Ajax.bigcom.id)).toEqual(undefined) expect(Test.Ajax.Store.getClientId('1236')).toEqual(undefined) expect(Test.Ajax.Store.getServerId(Test.Ajax.tom.id)).toEqual(undefined) describe 'server integration', -> beforeEach -> Test.Ajax.tom = Test.Ajax.Customer.createFromValues({name: '<NAME>'}) Test.Ajax.jason = Test.Ajax.Customer.initInstance({name: '<NAME>'}) Test.Ajax.tomId = Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id, Test.Ajax.getId()) Test.Ajax.subcaller = onLoad: -> onLoadAll: -> onCreate: -> onUpdate: -> onDestroy: -> onChange: -> it 'should load all from server on model load', -> runs -> Test.server.respondWith("GET", "/test/customers", [ 200, { "Content-Type": "application/json" }, '[ { "id": 456345, "name": "<NAME>" }, { "id": 345346, "name": "<NAME>" }, { "id": 234235, "name": "<NAME>" }, { "id": 876976, "name": "<NAME>" }, { "id": 786788, "name": "<NAME>" }, { "id": 123884, "name": "<NAME>" }]' ] ) spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.Ajax.Customer.loadAll() Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onChange.calls.length > 0), "onChange not fired", 1000) runs -> expect(Test.Ajax.subcaller.onChange).toHaveBeenCalled() jason = Test.Ajax.Customer.findByAttribute("name","<NAME>")[0] expect(jason).not.toBeNull() expect(jason.getServerId()).toEqual(456345) expect(Test.Ajax.Customer.findByAttribute("name","<NAME>")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","<NAME>")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","<NAME>")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","<NAME>")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","<NAME>")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","<NAME>")).not.toBeNull() it 'should load data from server on load with id', -> runs -> Test.server.respondWith("GET", "/test/customers/7732", [ 200, { "Content-Type": "application/json" }, '{ "id": 7732, "name": "<NAME>" }' ]) spyOn(Test.Ajax.subcaller,'onLoad') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('loadComplete', Test.Ajax.subcaller.onLoad) Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.Ajax.Customer.load(7732) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onChange.calls.length > 0), "onChange not fired", 1000) runs -> expect(Test.Ajax.subcaller.onLoad).toHaveBeenCalled() expect(Test.Ajax.subcaller.onChange).toHaveBeenCalled() instid = Test.Ajax.Customer.getClientId(7732) expect(instid).not.toBeNull() instance = Test.Ajax.Customer.findById(instid) expect(instance.name).toEqual('<NAME>') it 'should load data from server on instance load', -> runs -> Test.server.respondWith("GET", "/test/customers/2346", [ 200, { "Content-Type": "application/json" }, '{ "id": 2346, "name": "<NAME>" }' ]) Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id,2346) spyOn(Test.Ajax.subcaller,'onLoad') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('loadComplete', Test.Ajax.subcaller.onLoad) Test.Ajax.tom.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.Ajax.tom.load() Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onChange.calls.length > 0), "onChange not fired", 1000) runs -> expect(Test.Ajax.subcaller.onLoad).toHaveBeenCalledWith(Test.Ajax.tom, undefined) expect(Test.Ajax.subcaller.onChange).toHaveBeenCalled() expect(Test.Ajax.tom.name).toEqual("<NAME>") expect(Test.Ajax.tom.getServerId()).toEqual(2346) it 'should post data to server on save when instance isn\'t registered', -> runs -> Test.server.respondWith("POST", "/test/customers", [ 200, { "Content-Type": "application/json" }, '{ "id": 3012 }' ]) spyOn(Test.Ajax.subcaller,'onCreate') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('createComplete', Test.Ajax.subcaller.onCreate) Test.Ajax.jason.save() Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onCreate.calls.length > 0), "onCreate not fired", 1000) runs -> expect(Test.Ajax.subcaller.onCreate).toHaveBeenCalled() expect(Test.Ajax.subcaller.onChange).not.toHaveBeenCalled() serverId = Test.Ajax.Customer.getServerId(Test.Ajax.jason.id) expect(serverId).toEqual(3012) it 'should put data to server on save', -> runs -> Test.server.respondWith(/\/customers\/(\d+)/, (xhr, id) -> xhr.respond(200, { "Content-Type": "application/json" }, '[{ "id": ' + id + ' }]') ) spyOn(Test.Ajax.subcaller,'onUpdate') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('updateComplete', Test.Ajax.subcaller.onUpdate) Test.Ajax.tom.set('name','<NAME>') Test.Ajax.tom.save() Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onUpdate.calls.length > 0), "onUpdate not fired", 1000) runs -> expect(Test.Ajax.subcaller.onUpdate).toHaveBeenCalledWith(Test.Ajax.tom, undefined) expect(Test.Ajax.subcaller.onChange).not.toHaveBeenCalled() it 'should destroy on server and unregister on destroy', -> runs -> Test.server.respondWith(/\/customers\/(\d+)/, (xhr, id) -> xhr.respond(200, { "Content-Type": "application/json" }, '[{ "id": ' + id + ' }]') ) spyOn(Test.Ajax.subcaller,'onDestroy') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('destroyComplete', Test.Ajax.subcaller.onDestroy) Test.Ajax.tom.destroy() Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onDestroy.calls.length > 0), "onDestroy not fired", 1000) runs -> expect(Test.Ajax.subcaller.onDestroy).toHaveBeenCalledWith(Test.Ajax.tomId, undefined) expect(Test.Ajax.Customer.getClientId(Test.Ajax.tomId)).not.toBeDefined() expect(Test.Ajax.subcaller.onChange).not.toHaveBeenCalled() describe 'model client -> server object mapping', -> beforeEach -> Test.Ajax.tom = Test.Ajax.Customer.createFromValues({name: '<NAME>'}) Test.Ajax.tomId = Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id,Test.Ajax.getId()) describe 'for simple objects', -> it 'should provide the toServerObject method', -> object = Test.Ajax.Customer.toServerObject(Test.Ajax.tom) expect(object).not.toBe(Test.Ajax.tom) expect(object.name).toEqual(Test.Ajax.tom.name) expect(object.id).not.toEqual(Test.Ajax.tom.id) expect(object.id).toEqual(Test.Ajax.tomId) it 'should provide the toClientObject method, when the clientside instance does not exist', -> Test.Ajax.chrisID = Test.Ajax.getId() object = { id: Test.Ajax.chrisID name: '<NAME>' } clientObject = Test.Ajax.Customer.toClientObject(object) expect(clientObject.id).toEqual(undefined) expect(Test.Ajax.Customer.records[clientObject.id]).toEqual(undefined) expect(clientObject.name).toEqual('<NAME>') expect(clientObject.id).not.toEqual(Test.Ajax.chrisID) it 'should provide the toClientObject method, when the clientside instance does exist', -> object = { id: Test.Ajax.tomId name: '<NAME>' } clientObject = Test.Ajax.Customer.toClientObject(object) expect(Test.Ajax.Customer.records[clientObject.id]).toBe(Test.Ajax.tom) expect(clientObject.name).toEqual('<NAME>') expect(clientObject.id).not.toEqual(Test.Ajax.tomId) describe 'for objects with foreign keys', -> beforeEach -> Test.Ajax.bcId = Test.Ajax.getId() Test.Ajax.bc = Test.Ajax.Store.createFromValues({name: 'BigCom'}) Test.Ajax.Store.registerServerId(Test.Ajax.bc.id, Test.Ajax.bcId) Test.Ajax.shoeId = Test.Ajax.getId() Test.Ajax.shoe = Test.Ajax.Product.createFromValues { name: 'Red Shoe' } Test.Ajax.Product.registerServerId(Test.Ajax.shoe.id, Test.Ajax.shoeId) Test.Ajax.hatId = Test.Ajax.getId() Test.Ajax.hat = Test.Ajax.Product.createFromValues { name: 'Blue Hat' } Test.Ajax.Product.registerServerId(Test.Ajax.hat.id, Test.Ajax.hatId) Test.Ajax.scarf = Test.Ajax.Product.createFromValues { name: 'Green Scarf' } # No Scarf ServerId = unsaved to server. Test.Ajax.tomId = Test.Ajax.getId() Test.Ajax.tom = Test.Ajax.Customer.createFromValues { name: '<NAME>' } Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id, Test.Ajax.tomId) Test.Ajax.shoeOrderId = Test.Ajax.getId() Test.Ajax.shoeOrder = Test.Ajax.Order.createFromValues( { name: 'Customer Shoe Order' }) Test.Ajax.Order.registerServerId(Test.Ajax.shoeOrder.id, Test.Ajax.shoeOrderId) Test.Ajax.shoeSupplyOrderId = Test.Ajax.getId() Test.Ajax.shoeSupplyOrder = Test.Ajax.Order.createFromValues( { name: 'Store Shoe Order'}) Test.Ajax.Order.registerServerId(Test.Ajax.shoeSupplyOrder.id, Test.Ajax.shoeSupplyOrderId) Test.Ajax.bc.products().add(Test.Ajax.shoe) Test.Ajax.bc.products().add(Test.Ajax.hat) Test.Ajax.bc.products().add(Test.Ajax.scarf) Test.Ajax.shoeOrder.from(Test.Ajax.tom) #Test.Ajax.shoeSupplyOrder.from(Test.Ajax.bc) it 'should translate non-poly fks properly in toServerObject method', -> object = { id: Test.Ajax.shoeId name: '<NAME>' store_id: Test.Ajax.bcId } clientObject = Test.Ajax.Product.toClientObject(object) expect(Test.Ajax.Product.records[clientObject.id]).toBe(Test.Ajax.shoe) expect(Test.Ajax.Store.records[clientObject.store_id]).toBe(Test.Ajax.bc) it 'should translate non-poly fks in toServerObject when fk is null', -> object = { id: Test.Ajax.shoeId name: '<NAME>' store_id: null } clientObject = Test.Ajax.Product.toClientObject(object) expect(Test.Ajax.Product.records[clientObject.id]).toBe(Test.Ajax.shoe) expect(clientObject.store_id).toBeNull() it 'should translate poly fks properly in toServerObject method', -> object = { name: '<NAME>' from_id: Test.Ajax.tomId from_type: 'Customer' } clientObject = Test.Ajax.Order.toClientObject(object) expect(Test.Ajax.Customer.records[clientObject.from_id]).toBe(Test.Ajax.tom) object = { name: '<NAME>' from_id: Test.Ajax.bcId from_type: 'Store' } clientObject = Test.Ajax.Order.toClientObject(object) expect(Test.Ajax.Store.records[clientObject.from_id]).toBe(Test.Ajax.bc) it 'should translate non-poly fks in toServerObject when fk is null', -> object = { name: '<NAME>' from_id: null from_type: null } clientObject = Test.Ajax.Order.toClientObject(object) expect(clientObject.from_id).toBeNull() describe 'Nested Objects', -> beforeEach -> Test.Ajax.Nested = Mozart.Model.create { modelName: 'Nested' } Test.Ajax.Nested.attributes { 'name': 'string', 'nested':'object' } Test.Ajax.Nested.ajax { url: '/test/nestedjson', interface: 'rest' } it 'should read a nested object', -> runs -> Test.server.respondWith(/\/test\/nestedjson\/(\d+)/, (xhr, id) -> xhr.respond(200, { "Content-Type": "application/json" }, JSON.stringify({ id: id, name: '<NAME>', nested: { test1:1, test2: 2, listof: [1,2,3] } })) ) Test.Ajax.Nested.load(2) Test.server.respond() waits(200) runs -> x = Test.Ajax.Nested.all()[0] expect(x.name).toEqual('horse') expect(x.nested.test1).toEqual(1) expect(x.nested.test2).toEqual(2) expect(x.nested.listof.length).toEqual(3)
true
Test = {} Test.Ajax = {} Test.Ajax.getId = -> Math.round(Math.random()*9999999) describe 'Mozart.Ajax', -> beforeEach -> Test.server = sinon.fakeServer.create() Test.Ajax.Customer = Mozart.Model.create { modelName: 'Customer' } Test.Ajax.Customer.attributes { 'name': 'string' } Test.Ajax.Customer.ajax { url: '/test/customers', interface: 'rest' } Test.Ajax.Store = Mozart.Model.create { modelName: 'Store' } Test.Ajax.Store.attributes { 'name': 'string' } Test.Ajax.Store.ajax { url: '/test/stores', interface: 'rest' } Test.Ajax.Product = Mozart.Model.create { modelName: 'Product' } Test.Ajax.Product.attributes { 'name': 'string' } Test.Ajax.Product.ajax { url: '/test/products', interface: 'rest' } Test.Ajax.Order = Mozart.Model.create { modelName: 'Order' } Test.Ajax.Order.ajax { url: '/test/orders', interface: 'rest' } Test.Ajax.Store.hasMany Test.Ajax.Product, 'products' Test.Ajax.Product.belongsTo Test.Ajax.Store, 'store' Test.Ajax.Order.belongsToPoly [Test.Ajax.Store, Test.Ajax.Customer], 'from', 'from_id', 'from_type' afterEach -> Test.server.restore() describe 'ajax core', -> it 'should provide the ajax model extension method', -> expect(Test.Ajax.Customer.url).toEqual('/test/customers') expect(Test.Ajax.Customer.interface).toEqual('rest') describe 'server id mapping methods', -> beforeEach -> Test.Ajax.tom = Test.Ajax.Customer.createFromValues({name: 'PI:NAME:<NAME>END_PI'}) Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id, '1236') Test.Ajax.bigcom = Test.Ajax.Store.createFromValues({name: 'Bigcom'}) Test.Ajax.Store.registerServerId(Test.Ajax.bigcom.id, '2348') it 'should provide the registerServerId method on model', -> expect(Test.Ajax.Customer.getClientId('1236')).toEqual(Test.Ajax.tom.id) it 'should provide the unRegisterServerId method on model', -> Test.Ajax.Customer.unRegisterServerId(Test.Ajax.tom.id, '1236') expect(Test.Ajax.Customer.getClientId('1236')).toEqual(undefined) it 'should provide the getServerId method on model', -> expect(Test.Ajax.Customer.getServerId(Test.Ajax.tom.id)).toEqual('1236') it 'should provide the getServerId method on instance', -> expect(Test.Ajax.tom.getServerId()).toEqual('1236') it 'should provide the getClientId method', -> expect(Test.Ajax.Customer.getClientId('1236')).toEqual(Test.Ajax.tom.id) it 'should not pollute other models when registering server ids', -> expect(Test.Ajax.Customer.getClientId('2348')).toEqual(undefined) expect(Test.Ajax.Customer.getServerId(Test.Ajax.bigcom.id)).toEqual(undefined) expect(Test.Ajax.Store.getClientId('1236')).toEqual(undefined) expect(Test.Ajax.Store.getServerId(Test.Ajax.tom.id)).toEqual(undefined) describe 'server integration', -> beforeEach -> Test.Ajax.tom = Test.Ajax.Customer.createFromValues({name: 'PI:NAME:<NAME>END_PI'}) Test.Ajax.jason = Test.Ajax.Customer.initInstance({name: 'PI:NAME:<NAME>END_PI'}) Test.Ajax.tomId = Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id, Test.Ajax.getId()) Test.Ajax.subcaller = onLoad: -> onLoadAll: -> onCreate: -> onUpdate: -> onDestroy: -> onChange: -> it 'should load all from server on model load', -> runs -> Test.server.respondWith("GET", "/test/customers", [ 200, { "Content-Type": "application/json" }, '[ { "id": 456345, "name": "PI:NAME:<NAME>END_PI" }, { "id": 345346, "name": "PI:NAME:<NAME>END_PI" }, { "id": 234235, "name": "PI:NAME:<NAME>END_PI" }, { "id": 876976, "name": "PI:NAME:<NAME>END_PI" }, { "id": 786788, "name": "PI:NAME:<NAME>END_PI" }, { "id": 123884, "name": "PI:NAME:<NAME>END_PI" }]' ] ) spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.Ajax.Customer.loadAll() Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onChange.calls.length > 0), "onChange not fired", 1000) runs -> expect(Test.Ajax.subcaller.onChange).toHaveBeenCalled() jason = Test.Ajax.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")[0] expect(jason).not.toBeNull() expect(jason.getServerId()).toEqual(456345) expect(Test.Ajax.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).not.toBeNull() expect(Test.Ajax.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).not.toBeNull() it 'should load data from server on load with id', -> runs -> Test.server.respondWith("GET", "/test/customers/7732", [ 200, { "Content-Type": "application/json" }, '{ "id": 7732, "name": "PI:NAME:<NAME>END_PI" }' ]) spyOn(Test.Ajax.subcaller,'onLoad') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('loadComplete', Test.Ajax.subcaller.onLoad) Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.Ajax.Customer.load(7732) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onChange.calls.length > 0), "onChange not fired", 1000) runs -> expect(Test.Ajax.subcaller.onLoad).toHaveBeenCalled() expect(Test.Ajax.subcaller.onChange).toHaveBeenCalled() instid = Test.Ajax.Customer.getClientId(7732) expect(instid).not.toBeNull() instance = Test.Ajax.Customer.findById(instid) expect(instance.name).toEqual('PI:NAME:<NAME>END_PI') it 'should load data from server on instance load', -> runs -> Test.server.respondWith("GET", "/test/customers/2346", [ 200, { "Content-Type": "application/json" }, '{ "id": 2346, "name": "PI:NAME:<NAME>END_PI" }' ]) Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id,2346) spyOn(Test.Ajax.subcaller,'onLoad') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('loadComplete', Test.Ajax.subcaller.onLoad) Test.Ajax.tom.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.Ajax.tom.load() Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onChange.calls.length > 0), "onChange not fired", 1000) runs -> expect(Test.Ajax.subcaller.onLoad).toHaveBeenCalledWith(Test.Ajax.tom, undefined) expect(Test.Ajax.subcaller.onChange).toHaveBeenCalled() expect(Test.Ajax.tom.name).toEqual("PI:NAME:<NAME>END_PI") expect(Test.Ajax.tom.getServerId()).toEqual(2346) it 'should post data to server on save when instance isn\'t registered', -> runs -> Test.server.respondWith("POST", "/test/customers", [ 200, { "Content-Type": "application/json" }, '{ "id": 3012 }' ]) spyOn(Test.Ajax.subcaller,'onCreate') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('createComplete', Test.Ajax.subcaller.onCreate) Test.Ajax.jason.save() Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onCreate.calls.length > 0), "onCreate not fired", 1000) runs -> expect(Test.Ajax.subcaller.onCreate).toHaveBeenCalled() expect(Test.Ajax.subcaller.onChange).not.toHaveBeenCalled() serverId = Test.Ajax.Customer.getServerId(Test.Ajax.jason.id) expect(serverId).toEqual(3012) it 'should put data to server on save', -> runs -> Test.server.respondWith(/\/customers\/(\d+)/, (xhr, id) -> xhr.respond(200, { "Content-Type": "application/json" }, '[{ "id": ' + id + ' }]') ) spyOn(Test.Ajax.subcaller,'onUpdate') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('updateComplete', Test.Ajax.subcaller.onUpdate) Test.Ajax.tom.set('name','PI:NAME:<NAME>END_PI') Test.Ajax.tom.save() Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onUpdate.calls.length > 0), "onUpdate not fired", 1000) runs -> expect(Test.Ajax.subcaller.onUpdate).toHaveBeenCalledWith(Test.Ajax.tom, undefined) expect(Test.Ajax.subcaller.onChange).not.toHaveBeenCalled() it 'should destroy on server and unregister on destroy', -> runs -> Test.server.respondWith(/\/customers\/(\d+)/, (xhr, id) -> xhr.respond(200, { "Content-Type": "application/json" }, '[{ "id": ' + id + ' }]') ) spyOn(Test.Ajax.subcaller,'onDestroy') spyOn(Test.Ajax.subcaller,'onChange') Test.Ajax.Customer.subscribeOnce('destroyComplete', Test.Ajax.subcaller.onDestroy) Test.Ajax.tom.destroy() Test.Ajax.Customer.subscribeOnce('change', Test.Ajax.subcaller.onChange) Test.server.respond() waitsFor((-> Test.Ajax.subcaller.onDestroy.calls.length > 0), "onDestroy not fired", 1000) runs -> expect(Test.Ajax.subcaller.onDestroy).toHaveBeenCalledWith(Test.Ajax.tomId, undefined) expect(Test.Ajax.Customer.getClientId(Test.Ajax.tomId)).not.toBeDefined() expect(Test.Ajax.subcaller.onChange).not.toHaveBeenCalled() describe 'model client -> server object mapping', -> beforeEach -> Test.Ajax.tom = Test.Ajax.Customer.createFromValues({name: 'PI:NAME:<NAME>END_PI'}) Test.Ajax.tomId = Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id,Test.Ajax.getId()) describe 'for simple objects', -> it 'should provide the toServerObject method', -> object = Test.Ajax.Customer.toServerObject(Test.Ajax.tom) expect(object).not.toBe(Test.Ajax.tom) expect(object.name).toEqual(Test.Ajax.tom.name) expect(object.id).not.toEqual(Test.Ajax.tom.id) expect(object.id).toEqual(Test.Ajax.tomId) it 'should provide the toClientObject method, when the clientside instance does not exist', -> Test.Ajax.chrisID = Test.Ajax.getId() object = { id: Test.Ajax.chrisID name: 'PI:NAME:<NAME>END_PI' } clientObject = Test.Ajax.Customer.toClientObject(object) expect(clientObject.id).toEqual(undefined) expect(Test.Ajax.Customer.records[clientObject.id]).toEqual(undefined) expect(clientObject.name).toEqual('PI:NAME:<NAME>END_PI') expect(clientObject.id).not.toEqual(Test.Ajax.chrisID) it 'should provide the toClientObject method, when the clientside instance does exist', -> object = { id: Test.Ajax.tomId name: 'PI:NAME:<NAME>END_PI' } clientObject = Test.Ajax.Customer.toClientObject(object) expect(Test.Ajax.Customer.records[clientObject.id]).toBe(Test.Ajax.tom) expect(clientObject.name).toEqual('PI:NAME:<NAME>END_PI') expect(clientObject.id).not.toEqual(Test.Ajax.tomId) describe 'for objects with foreign keys', -> beforeEach -> Test.Ajax.bcId = Test.Ajax.getId() Test.Ajax.bc = Test.Ajax.Store.createFromValues({name: 'BigCom'}) Test.Ajax.Store.registerServerId(Test.Ajax.bc.id, Test.Ajax.bcId) Test.Ajax.shoeId = Test.Ajax.getId() Test.Ajax.shoe = Test.Ajax.Product.createFromValues { name: 'Red Shoe' } Test.Ajax.Product.registerServerId(Test.Ajax.shoe.id, Test.Ajax.shoeId) Test.Ajax.hatId = Test.Ajax.getId() Test.Ajax.hat = Test.Ajax.Product.createFromValues { name: 'Blue Hat' } Test.Ajax.Product.registerServerId(Test.Ajax.hat.id, Test.Ajax.hatId) Test.Ajax.scarf = Test.Ajax.Product.createFromValues { name: 'Green Scarf' } # No Scarf ServerId = unsaved to server. Test.Ajax.tomId = Test.Ajax.getId() Test.Ajax.tom = Test.Ajax.Customer.createFromValues { name: 'PI:NAME:<NAME>END_PI' } Test.Ajax.Customer.registerServerId(Test.Ajax.tom.id, Test.Ajax.tomId) Test.Ajax.shoeOrderId = Test.Ajax.getId() Test.Ajax.shoeOrder = Test.Ajax.Order.createFromValues( { name: 'Customer Shoe Order' }) Test.Ajax.Order.registerServerId(Test.Ajax.shoeOrder.id, Test.Ajax.shoeOrderId) Test.Ajax.shoeSupplyOrderId = Test.Ajax.getId() Test.Ajax.shoeSupplyOrder = Test.Ajax.Order.createFromValues( { name: 'Store Shoe Order'}) Test.Ajax.Order.registerServerId(Test.Ajax.shoeSupplyOrder.id, Test.Ajax.shoeSupplyOrderId) Test.Ajax.bc.products().add(Test.Ajax.shoe) Test.Ajax.bc.products().add(Test.Ajax.hat) Test.Ajax.bc.products().add(Test.Ajax.scarf) Test.Ajax.shoeOrder.from(Test.Ajax.tom) #Test.Ajax.shoeSupplyOrder.from(Test.Ajax.bc) it 'should translate non-poly fks properly in toServerObject method', -> object = { id: Test.Ajax.shoeId name: 'PI:NAME:<NAME>END_PI' store_id: Test.Ajax.bcId } clientObject = Test.Ajax.Product.toClientObject(object) expect(Test.Ajax.Product.records[clientObject.id]).toBe(Test.Ajax.shoe) expect(Test.Ajax.Store.records[clientObject.store_id]).toBe(Test.Ajax.bc) it 'should translate non-poly fks in toServerObject when fk is null', -> object = { id: Test.Ajax.shoeId name: 'PI:NAME:<NAME>END_PI' store_id: null } clientObject = Test.Ajax.Product.toClientObject(object) expect(Test.Ajax.Product.records[clientObject.id]).toBe(Test.Ajax.shoe) expect(clientObject.store_id).toBeNull() it 'should translate poly fks properly in toServerObject method', -> object = { name: 'PI:NAME:<NAME>END_PI' from_id: Test.Ajax.tomId from_type: 'Customer' } clientObject = Test.Ajax.Order.toClientObject(object) expect(Test.Ajax.Customer.records[clientObject.from_id]).toBe(Test.Ajax.tom) object = { name: 'PI:NAME:<NAME>END_PI' from_id: Test.Ajax.bcId from_type: 'Store' } clientObject = Test.Ajax.Order.toClientObject(object) expect(Test.Ajax.Store.records[clientObject.from_id]).toBe(Test.Ajax.bc) it 'should translate non-poly fks in toServerObject when fk is null', -> object = { name: 'PI:NAME:<NAME>END_PI' from_id: null from_type: null } clientObject = Test.Ajax.Order.toClientObject(object) expect(clientObject.from_id).toBeNull() describe 'Nested Objects', -> beforeEach -> Test.Ajax.Nested = Mozart.Model.create { modelName: 'Nested' } Test.Ajax.Nested.attributes { 'name': 'string', 'nested':'object' } Test.Ajax.Nested.ajax { url: '/test/nestedjson', interface: 'rest' } it 'should read a nested object', -> runs -> Test.server.respondWith(/\/test\/nestedjson\/(\d+)/, (xhr, id) -> xhr.respond(200, { "Content-Type": "application/json" }, JSON.stringify({ id: id, name: 'PI:NAME:<NAME>END_PI', nested: { test1:1, test2: 2, listof: [1,2,3] } })) ) Test.Ajax.Nested.load(2) Test.server.respond() waits(200) runs -> x = Test.Ajax.Nested.all()[0] expect(x.name).toEqual('horse') expect(x.nested.test1).toEqual(1) expect(x.nested.test2).toEqual(2) expect(x.nested.listof.length).toEqual(3)
[ { "context": " [\"do\", \"re\", \"mi\", \"fa\", \"so\"]\n\n singers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\n bitlist = [\n ", "end": 782, "score": 0.5679575800895691, "start": 776, "tag": "NAME", "value": "Jagger" }, { "context": "mi\", \"fa\", \"so\"]\n\n singer...
src/examples.coffee
gokmen/coffeepad
22
# # Examples taken from coffeescript.org # module.exports = [ { title: "Overview" content: """ # Assignment: number = 42 opposite = true # Conditions: number = -42 if opposite # Functions: square = (x) -> x * x # Arrays: list = [1, 2, 3, 4, 5] # Objects: math = root: Math.sqrt square: square cube: (x) -> x * square x # Splats: race = (winner, runners...) -> print winner, runners # Existence: alert "I knew it!" if elvis? # Array comprehensions: cubes = (math.cube num for num in list) """ } { title: "Objects and Arrays" content: """ song = ["do", "re", "mi", "fa", "so"] singers = {Jagger: "Rock", Elvis: "Roll"} bitlist = [ 1, 0, 1 0, 0, 1 1, 1, 0 ] kids = brother: name: "Max" age: 11 sister: name: "Ida" age: 9 """ } { title: "Splats" content: """ gold = silver = rest = "unknown" awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "Michael Phelps" "Liu Xiang" "Yao Ming" "Allyson Felix" "Shawn Johnson" "Roman Sebrle" "Guo Jingjing" "Tyson Gay" "Asafa Powell" "Usain Bolt" ] awardMedals contenders... alert "Gold: " + gold alert "Silver: " + silver alert "The Field: " + rest """ } { title: "Loops and Comprehensions" content: """ # Functions eat = (food)-> console.log food menu = (num, dish)-> console.info num, dish # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' """ } ]
214254
# # Examples taken from coffeescript.org # module.exports = [ { title: "Overview" content: """ # Assignment: number = 42 opposite = true # Conditions: number = -42 if opposite # Functions: square = (x) -> x * x # Arrays: list = [1, 2, 3, 4, 5] # Objects: math = root: Math.sqrt square: square cube: (x) -> x * square x # Splats: race = (winner, runners...) -> print winner, runners # Existence: alert "I knew it!" if elvis? # Array comprehensions: cubes = (math.cube num for num in list) """ } { title: "Objects and Arrays" content: """ song = ["do", "re", "mi", "fa", "so"] singers = {<NAME>: "Rock", <NAME>vis: "Roll"} bitlist = [ 1, 0, 1 0, 0, 1 1, 1, 0 ] kids = brother: name: "<NAME>" age: 11 sister: name: "<NAME>" age: 9 """ } { title: "Splats" content: """ gold = silver = rest = "unknown" awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" ] awardMedals contenders... alert "Gold: " + gold alert "Silver: " + silver alert "The Field: " + rest """ } { title: "Loops and Comprehensions" content: """ # Functions eat = (food)-> console.log food menu = (num, dish)-> console.info num, dish # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' """ } ]
true
# # Examples taken from coffeescript.org # module.exports = [ { title: "Overview" content: """ # Assignment: number = 42 opposite = true # Conditions: number = -42 if opposite # Functions: square = (x) -> x * x # Arrays: list = [1, 2, 3, 4, 5] # Objects: math = root: Math.sqrt square: square cube: (x) -> x * square x # Splats: race = (winner, runners...) -> print winner, runners # Existence: alert "I knew it!" if elvis? # Array comprehensions: cubes = (math.cube num for num in list) """ } { title: "Objects and Arrays" content: """ song = ["do", "re", "mi", "fa", "so"] singers = {PI:NAME:<NAME>END_PI: "Rock", PI:NAME:<NAME>END_PIvis: "Roll"} bitlist = [ 1, 0, 1 0, 0, 1 1, 1, 0 ] kids = brother: name: "PI:NAME:<NAME>END_PI" age: 11 sister: name: "PI:NAME:<NAME>END_PI" age: 9 """ } { title: "Splats" content: """ gold = silver = rest = "unknown" awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ] awardMedals contenders... alert "Gold: " + gold alert "Silver: " + silver alert "The Field: " + rest """ } { title: "Loops and Comprehensions" content: """ # Functions eat = (food)-> console.log food menu = (num, dish)-> console.info num, dish # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' """ } ]
[ { "context": " https://on-premises.com\n#\n# Copyright (c) 2019 Alex Williams, Unscramble <license@unscramble.jp>\n# MIT Licen", "end": 127, "score": 0.9997629523277283, "start": 114, "tag": "NAME", "value": "Alex Williams" }, { "context": "# Copyright (c) 2019 Alex Williams, ...
src/on-prem-meta.coffee
on-prem/on-prem-meta-node
1
# Official On-Prem Meta REST API client and helper library # https://on-premises.com # # Copyright (c) 2019 Alex Williams, Unscramble <license@unscramble.jp> # MIT Licensed createHash = require('crypto').createHash createHmac = require('crypto').createHmac needle = require 'needle' formData = require 'form-data' fs = require 'fs' needle.defaults user_agent: 'nodeclient-on-prem-meta/1.5.0' response_timeout: 10000 # 10 seconds exports.makeSHA256 = (string) -> createHash('sha256') .update(string) .digest 'hex' exports.makeHMAC = (string, key) -> createHmac('sha256', key) .update(string) .digest 'hex' # Global variables settings = prefix: process.env.ON_PREM_META_PREFIX || "meta" # example: admin host: process.env.ON_PREM_META_HOST || throw "Environment variable 'ON_PREM_META_HOST' required" # example: meta.yourdomain.com:443 insecure: if process.env.ON_PREM_META_INSECURE is "true" then false else true tokenhash: this.makeSHA256 process.env.ON_PREM_META_APITOKEN || throw "Environment variable 'ON_PREM_META_APITOKEN' required" # example: yourtoken options = rejectUnauthorized: settings.insecure exports.settings = settings exports.options = options exports.buildRequest = (params = {method: 'GET', endpoint: 'version'}, callback) -> endpoint = "/api/v1/#{settings.prefix}/#{params.endpoint}" switch params.method.toUpperCase() when 'GET' data = params.query ? {} data.hash = this.makeHMAC("#{params.method.toUpperCase()}#{endpoint}", settings.tokenhash) return callback null, method: params.method.toUpperCase() uri: "https://#{settings.host}#{endpoint}" data: data options: options when 'POST' data = new formData() data.append 'hash', this.makeHMAC("#{params.method.toUpperCase()}#{endpoint}", settings.tokenhash) data.append name, val for name, val of params.query # append params data.append file, val.data, val.filename for file, val of params.files # append files options.headers = data.getHeaders() return callback null, method: params.method.toUpperCase() uri: "https://#{settings.host}#{endpoint}" data: data options: options else return callback new Error 'Invalid request method' exports.apiCall = (params, callback) -> req = needle.request params.method, params.uri params.data params.options (err, res, data) -> return callback err, res, data # returns a callback with the version of the API exports.getVersion = (callback) => this.buildRequest undefined, (error, result) => unless error this.apiCall result, (err, res, data) => unless err callback data.version # returns a callback with an error in arg1, or the builddate in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.buildOVA = (application, parameters, callback) => this.getVersion (version) => apiParams = method: 'POST' endpoint: 'builds' files: app: filename: 'app.tcz' data: fs.readFileSync(application) query: parameters this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 202 and res.statusMessage is 'Accepted' if version >= '1.13.1' callback null, data.builddate # builddate added in v1.13.1 else callback null, data.Location.split("=")[1] # parse the Location to get the builddate else callback data exports.getStatus = (build, callback) => this.getVersion (version) => apiParams = method: 'GET' endpoint: 'builds/status' query: builddate: build log: 0 if version >= '1.13.1' # log parameter added in v1.13.1 this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 202 and res.statusMessage is 'Accepted' callback null, { status: 'queued' } else if res.statusCode is 200 and data callback null, data else callback data # returns a callback with and error in arg1, or the status in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.pollStatus = (build, status = {}, callback) => switch status.status when 'success', 'failed' return status.status else this.getStatus build, (err, res) => if err callback err else if res.status is 'success' callback null, this.pollStatus build, res else if res.status is 'failed' callback null, this.pollStatus build, res else run = () => this.pollStatus build, res, (error, result) -> callback error if error callback null, result # wait 5 seconds between each request setTimeout run, 5000 # returns a callback with an error in arg1, or the list of downloads in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.getDownloads = (build, callback) => apiParams = method: 'GET' endpoint: 'downloads' query: builddate: build this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 200 and res.statusMessage is 'OK' downloads = for i, url in data.downloads "https://#{settings.host}#{i.url}" callback null, downloads.join('\n') else callback data # returns a callback with an error in arg1, or 'OK' in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.cancelBuild = (build, callback) => apiParams = method: 'POST' endpoint: 'builds/cancel' query: builddate: build this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 200 and res.statusMessage is 'OK' callback null, res.statusMessage else callback data
194483
# Official On-Prem Meta REST API client and helper library # https://on-premises.com # # Copyright (c) 2019 <NAME>, Unscramble <<EMAIL>> # MIT Licensed createHash = require('crypto').createHash createHmac = require('crypto').createHmac needle = require 'needle' formData = require 'form-data' fs = require 'fs' needle.defaults user_agent: 'nodeclient-on-prem-meta/1.5.0' response_timeout: 10000 # 10 seconds exports.makeSHA256 = (string) -> createHash('sha256') .update(string) .digest 'hex' exports.makeHMAC = (string, key) -> createHmac('sha256', key) .update(string) .digest 'hex' # Global variables settings = prefix: process.env.ON_PREM_META_PREFIX || "meta" # example: admin host: process.env.ON_PREM_META_HOST || throw "Environment variable 'ON_PREM_META_HOST' required" # example: meta.yourdomain.com:443 insecure: if process.env.ON_PREM_META_INSECURE is "true" then false else true tokenhash: this.makeSHA256 process.env.ON_PREM_META_APITOKEN || throw "Environment variable 'ON_PREM_META_APITOKEN' required" # example: yourtoken options = rejectUnauthorized: settings.insecure exports.settings = settings exports.options = options exports.buildRequest = (params = {method: 'GET', endpoint: 'version'}, callback) -> endpoint = "/api/v1/#{settings.prefix}/#{params.endpoint}" switch params.method.toUpperCase() when 'GET' data = params.query ? {} data.hash = this.makeHMAC("#{params.method.toUpperCase()}#{endpoint}", settings.tokenhash) return callback null, method: params.method.toUpperCase() uri: "https://#{settings.host}#{endpoint}" data: data options: options when 'POST' data = new formData() data.append 'hash', this.makeHMAC("#{params.method.toUpperCase()}#{endpoint}", settings.tokenhash) data.append name, val for name, val of params.query # append params data.append file, val.data, val.filename for file, val of params.files # append files options.headers = data.getHeaders() return callback null, method: params.method.toUpperCase() uri: "https://#{settings.host}#{endpoint}" data: data options: options else return callback new Error 'Invalid request method' exports.apiCall = (params, callback) -> req = needle.request params.method, params.uri params.data params.options (err, res, data) -> return callback err, res, data # returns a callback with the version of the API exports.getVersion = (callback) => this.buildRequest undefined, (error, result) => unless error this.apiCall result, (err, res, data) => unless err callback data.version # returns a callback with an error in arg1, or the builddate in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.buildOVA = (application, parameters, callback) => this.getVersion (version) => apiParams = method: 'POST' endpoint: 'builds' files: app: filename: 'app.tcz' data: fs.readFileSync(application) query: parameters this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 202 and res.statusMessage is 'Accepted' if version >= '1.13.1' callback null, data.builddate # builddate added in v1.13.1 else callback null, data.Location.split("=")[1] # parse the Location to get the builddate else callback data exports.getStatus = (build, callback) => this.getVersion (version) => apiParams = method: 'GET' endpoint: 'builds/status' query: builddate: build log: 0 if version >= '1.13.1' # log parameter added in v1.13.1 this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 202 and res.statusMessage is 'Accepted' callback null, { status: 'queued' } else if res.statusCode is 200 and data callback null, data else callback data # returns a callback with and error in arg1, or the status in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.pollStatus = (build, status = {}, callback) => switch status.status when 'success', 'failed' return status.status else this.getStatus build, (err, res) => if err callback err else if res.status is 'success' callback null, this.pollStatus build, res else if res.status is 'failed' callback null, this.pollStatus build, res else run = () => this.pollStatus build, res, (error, result) -> callback error if error callback null, result # wait 5 seconds between each request setTimeout run, 5000 # returns a callback with an error in arg1, or the list of downloads in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.getDownloads = (build, callback) => apiParams = method: 'GET' endpoint: 'downloads' query: builddate: build this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 200 and res.statusMessage is 'OK' downloads = for i, url in data.downloads "https://#{settings.host}#{i.url}" callback null, downloads.join('\n') else callback data # returns a callback with an error in arg1, or 'OK' in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.cancelBuild = (build, callback) => apiParams = method: 'POST' endpoint: 'builds/cancel' query: builddate: build this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 200 and res.statusMessage is 'OK' callback null, res.statusMessage else callback data
true
# Official On-Prem Meta REST API client and helper library # https://on-premises.com # # Copyright (c) 2019 PI:NAME:<NAME>END_PI, Unscramble <PI:EMAIL:<EMAIL>END_PI> # MIT Licensed createHash = require('crypto').createHash createHmac = require('crypto').createHmac needle = require 'needle' formData = require 'form-data' fs = require 'fs' needle.defaults user_agent: 'nodeclient-on-prem-meta/1.5.0' response_timeout: 10000 # 10 seconds exports.makeSHA256 = (string) -> createHash('sha256') .update(string) .digest 'hex' exports.makeHMAC = (string, key) -> createHmac('sha256', key) .update(string) .digest 'hex' # Global variables settings = prefix: process.env.ON_PREM_META_PREFIX || "meta" # example: admin host: process.env.ON_PREM_META_HOST || throw "Environment variable 'ON_PREM_META_HOST' required" # example: meta.yourdomain.com:443 insecure: if process.env.ON_PREM_META_INSECURE is "true" then false else true tokenhash: this.makeSHA256 process.env.ON_PREM_META_APITOKEN || throw "Environment variable 'ON_PREM_META_APITOKEN' required" # example: yourtoken options = rejectUnauthorized: settings.insecure exports.settings = settings exports.options = options exports.buildRequest = (params = {method: 'GET', endpoint: 'version'}, callback) -> endpoint = "/api/v1/#{settings.prefix}/#{params.endpoint}" switch params.method.toUpperCase() when 'GET' data = params.query ? {} data.hash = this.makeHMAC("#{params.method.toUpperCase()}#{endpoint}", settings.tokenhash) return callback null, method: params.method.toUpperCase() uri: "https://#{settings.host}#{endpoint}" data: data options: options when 'POST' data = new formData() data.append 'hash', this.makeHMAC("#{params.method.toUpperCase()}#{endpoint}", settings.tokenhash) data.append name, val for name, val of params.query # append params data.append file, val.data, val.filename for file, val of params.files # append files options.headers = data.getHeaders() return callback null, method: params.method.toUpperCase() uri: "https://#{settings.host}#{endpoint}" data: data options: options else return callback new Error 'Invalid request method' exports.apiCall = (params, callback) -> req = needle.request params.method, params.uri params.data params.options (err, res, data) -> return callback err, res, data # returns a callback with the version of the API exports.getVersion = (callback) => this.buildRequest undefined, (error, result) => unless error this.apiCall result, (err, res, data) => unless err callback data.version # returns a callback with an error in arg1, or the builddate in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.buildOVA = (application, parameters, callback) => this.getVersion (version) => apiParams = method: 'POST' endpoint: 'builds' files: app: filename: 'app.tcz' data: fs.readFileSync(application) query: parameters this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 202 and res.statusMessage is 'Accepted' if version >= '1.13.1' callback null, data.builddate # builddate added in v1.13.1 else callback null, data.Location.split("=")[1] # parse the Location to get the builddate else callback data exports.getStatus = (build, callback) => this.getVersion (version) => apiParams = method: 'GET' endpoint: 'builds/status' query: builddate: build log: 0 if version >= '1.13.1' # log parameter added in v1.13.1 this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 202 and res.statusMessage is 'Accepted' callback null, { status: 'queued' } else if res.statusCode is 200 and data callback null, data else callback data # returns a callback with and error in arg1, or the status in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.pollStatus = (build, status = {}, callback) => switch status.status when 'success', 'failed' return status.status else this.getStatus build, (err, res) => if err callback err else if res.status is 'success' callback null, this.pollStatus build, res else if res.status is 'failed' callback null, this.pollStatus build, res else run = () => this.pollStatus build, res, (error, result) -> callback error if error callback null, result # wait 5 seconds between each request setTimeout run, 5000 # returns a callback with an error in arg1, or the list of downloads in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.getDownloads = (build, callback) => apiParams = method: 'GET' endpoint: 'downloads' query: builddate: build this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 200 and res.statusMessage is 'OK' downloads = for i, url in data.downloads "https://#{settings.host}#{i.url}" callback null, downloads.join('\n') else callback data # returns a callback with an error in arg1, or 'OK' in arg2 # the error is an Error object if non-HTTP related # the error is the request result if 404 or other HTTP error code (4xx or 5xx) exports.cancelBuild = (build, callback) => apiParams = method: 'POST' endpoint: 'builds/cancel' query: builddate: build this.buildRequest apiParams, (error, result) => callback error if error this.apiCall result, (err, res, data) -> if err callback new Error err else if res.statusCode is 200 and res.statusMessage is 'OK' callback null, res.statusMessage else callback data
[ { "context": "ame is updated', ->\n gus = Puppy.create(name: 'gus')\n gus.bind 'update:name', spy\n gus.updateA", "end": 323, "score": 0.9986554980278015, "start": 320, "tag": "NAME", "value": "gus" }, { "context": "pdate:name', spy\n gus.updateAttribute('name', 'henry')\...
spec/attributeTracking_spec.coffee
ryggrad/Ryggrad
0
describe "Model Attribute Tracking", -> Puppy = undefined spy = undefined beforeEach -> class Puppy extends Ryggrad.Model @configure("Puppy", "name") @extend Ryggrad.AttributeTracking spy = sinon.spy() it 'fires an update:name event when name is updated', -> gus = Puppy.create(name: 'gus') gus.bind 'update:name', spy gus.updateAttribute('name', 'henry') spy.should.have.been.called it "doesn't fire an update:name event if the new name isn't different", -> gus = Puppy.create(name: 'gus') gus.bind 'update:name', spy gus.updateAttribute('name', 'gus') spy.called.should.be.false it "works with refreshed models", -> Puppy.refresh({name: 'gus', id: 1}) gus = Puppy.find(1) gus.bind 'update:name', spy gus.updateAttribute('name', 'jake') spy.called.should.be.true it "doesn't fire an event when an attribute is updated with an equivalent object", -> Puppy.refresh({name: {first: 'Henry', last: 'Lloyd'}, id: 1}) henry = Puppy.find(1) henry.bind 'update:name', spy henry.updateAttribute('name', {first: 'Henry', last: "Lloyd"}) spy.called.should.be.false
177955
describe "Model Attribute Tracking", -> Puppy = undefined spy = undefined beforeEach -> class Puppy extends Ryggrad.Model @configure("Puppy", "name") @extend Ryggrad.AttributeTracking spy = sinon.spy() it 'fires an update:name event when name is updated', -> gus = Puppy.create(name: '<NAME>') gus.bind 'update:name', spy gus.updateAttribute('name', '<NAME>') spy.should.have.been.called it "doesn't fire an update:name event if the new name isn't different", -> gus = Puppy.create(name: '<NAME>') gus.bind 'update:name', spy gus.updateAttribute('name', '<NAME>') spy.called.should.be.false it "works with refreshed models", -> Puppy.refresh({name: '<NAME>', id: 1}) gus = Puppy.find(1) gus.bind 'update:name', spy gus.updateAttribute('name', '<NAME>') spy.called.should.be.true it "doesn't fire an event when an attribute is updated with an equivalent object", -> Puppy.refresh({name: {first: '<NAME>', last: '<NAME>'}, id: 1}) henry = Puppy.find(1) henry.bind 'update:name', spy henry.updateAttribute('name', {first: '<NAME>', last: "<NAME>"}) spy.called.should.be.false
true
describe "Model Attribute Tracking", -> Puppy = undefined spy = undefined beforeEach -> class Puppy extends Ryggrad.Model @configure("Puppy", "name") @extend Ryggrad.AttributeTracking spy = sinon.spy() it 'fires an update:name event when name is updated', -> gus = Puppy.create(name: 'PI:NAME:<NAME>END_PI') gus.bind 'update:name', spy gus.updateAttribute('name', 'PI:NAME:<NAME>END_PI') spy.should.have.been.called it "doesn't fire an update:name event if the new name isn't different", -> gus = Puppy.create(name: 'PI:NAME:<NAME>END_PI') gus.bind 'update:name', spy gus.updateAttribute('name', 'PI:NAME:<NAME>END_PI') spy.called.should.be.false it "works with refreshed models", -> Puppy.refresh({name: 'PI:NAME:<NAME>END_PI', id: 1}) gus = Puppy.find(1) gus.bind 'update:name', spy gus.updateAttribute('name', 'PI:NAME:<NAME>END_PI') spy.called.should.be.true it "doesn't fire an event when an attribute is updated with an equivalent object", -> Puppy.refresh({name: {first: 'PI:NAME:<NAME>END_PI', last: 'PI:NAME:<NAME>END_PI'}, id: 1}) henry = Puppy.find(1) henry.bind 'update:name', spy henry.updateAttribute('name', {first: 'PI:NAME:<NAME>END_PI', last: "PI:NAME:<NAME>END_PI"}) spy.called.should.be.false
[ { "context": "ier')\n\tRocketChat.models.OAuthApps.insert\n\t\t_id: 'zapier'\n\t\tname: 'Zapier'\n\t\tactive: false\n\t\tclientId: 'za", "end": 103, "score": 0.9989492297172546, "start": 97, "tag": "USERNAME", "value": "zapier" }, { "context": ".models.OAuthApps.insert\n\t\t_id: 'zap...
packages/rocketchat-oauth2-server-config/oauth/server/default-services.coffee
Cosecha/rocket-chat-stable
2
if not RocketChat.models.OAuthApps.findOne('zapier') RocketChat.models.OAuthApps.insert _id: 'zapier' name: 'Zapier' active: false clientId: 'zapier' clientSecret: 'RTK6TlndaCIolhQhZ7_KHIGOKj41RnlaOq_o-7JKwLr' redirectUri: 'https://zapier.com/dashboard/auth/oauth/return/AppIDAPI/' _createdAt: new Date _createdBy: _id: 'system' username: 'system'
122310
if not RocketChat.models.OAuthApps.findOne('zapier') RocketChat.models.OAuthApps.insert _id: 'zapier' name: '<NAME>' active: false clientId: 'zapier' clientSecret: '<KEY>' redirectUri: 'https://zapier.com/dashboard/auth/oauth/return/AppIDAPI/' _createdAt: new Date _createdBy: _id: 'system' username: 'system'
true
if not RocketChat.models.OAuthApps.findOne('zapier') RocketChat.models.OAuthApps.insert _id: 'zapier' name: 'PI:NAME:<NAME>END_PI' active: false clientId: 'zapier' clientSecret: 'PI:KEY:<KEY>END_PI' redirectUri: 'https://zapier.com/dashboard/auth/oauth/return/AppIDAPI/' _createdAt: new Date _createdBy: _id: 'system' username: 'system'
[ { "context": "d: -> ~~(Math.random() * 1000)\n username: 'testuser'\n email: 'testuser@test.com'\n", "end": 89, "score": 0.9996036291122437, "start": 81, "tag": "USERNAME", "value": "testuser" }, { "context": "dom() * 1000)\n username: 'testuser'\n email: 'testuser@te...
test/unit/factories/user.coffee
learric/CollegiateRivals
3
FactoryGirl.define 'user', id: -> ~~(Math.random() * 1000) username: 'testuser' email: 'testuser@test.com'
2565
FactoryGirl.define 'user', id: -> ~~(Math.random() * 1000) username: 'testuser' email: '<EMAIL>'
true
FactoryGirl.define 'user', id: -> ~~(Math.random() * 1000) username: 'testuser' email: 'PI:EMAIL:<EMAIL>END_PI'
[ { "context": " for browser in browsers\n key = \"SL-#{browser.browserName.replace \" \", \"_\"}-#{browser.ve", "end": 1310, "score": 0.8140568733215332, "start": 1305, "tag": "KEY", "value": "SL-#{" }, { "context": " key = \"SL-#{browser.browserName.replace \" \", ...
public/pb-assets/frameworks/fine-uploader-master/lib/browsers.coffee
ubilli/popibay-s3
0
# Browsers, for testing browsers = [ browserName: "chrome" platform: "Linux" version: "28" , browserName: "firefox" platform: "Linux" version: "26" , browserName: "android" platform: "Linux" version: "4.0" , browserName: "safari" platform: "OS X 10.8" version: "6" , browserName: "safari" platform: "OS X 10.6" version: "5" , browserName: "iphone" platform: "OS X 10.8" version: "6" , # browserName: "iphone" # platform: "OS X 10.9" # version: "7" # , browserName: "internet explorer" platform: "Windows 8.1" version: "11" , browserName: "internet explorer" platform: "Windows 8" version: "10" , browserName: "internet explorer" platform: "Windows 7" version: "9" , browserName: "internet explorer" platform: "Windows 7" version: "8" , browserName: "internet explorer" platform: "Windows XP" version: "7" ] if (exports) exports.modules = browsers exports.sauceBrowsers = sauceBrowsers = do -> b = {} for browser in browsers key = "SL-#{browser.browserName.replace " ", "_"}-#{browser.version || ''}-#{browser.platform.replace " ", "_"}" key = key.replace " ", "_" b[key] = base: 'SauceLabs' browserName: browser.browserName version: browser.version platform: browser.platform return b exports.sauceBrowserKeys = do -> res = [] for k of sauceBrowsers res.push k return res
63284
# Browsers, for testing browsers = [ browserName: "chrome" platform: "Linux" version: "28" , browserName: "firefox" platform: "Linux" version: "26" , browserName: "android" platform: "Linux" version: "4.0" , browserName: "safari" platform: "OS X 10.8" version: "6" , browserName: "safari" platform: "OS X 10.6" version: "5" , browserName: "iphone" platform: "OS X 10.8" version: "6" , # browserName: "iphone" # platform: "OS X 10.9" # version: "7" # , browserName: "internet explorer" platform: "Windows 8.1" version: "11" , browserName: "internet explorer" platform: "Windows 8" version: "10" , browserName: "internet explorer" platform: "Windows 7" version: "9" , browserName: "internet explorer" platform: "Windows 7" version: "8" , browserName: "internet explorer" platform: "Windows XP" version: "7" ] if (exports) exports.modules = browsers exports.sauceBrowsers = sauceBrowsers = do -> b = {} for browser in browsers key = "<KEY>browser.browserName.replace " ", "_<KEY>"}-#{browser.version || ''<KEY>}-#{browser.platform.replace " ", "_"}" key = key.replace " ", "_" b[key] = base: 'SauceLabs' browserName: browser.browserName version: browser.version platform: browser.platform return b exports.sauceBrowserKeys = do -> res = [] for k of sauceBrowsers res.push k return res
true
# Browsers, for testing browsers = [ browserName: "chrome" platform: "Linux" version: "28" , browserName: "firefox" platform: "Linux" version: "26" , browserName: "android" platform: "Linux" version: "4.0" , browserName: "safari" platform: "OS X 10.8" version: "6" , browserName: "safari" platform: "OS X 10.6" version: "5" , browserName: "iphone" platform: "OS X 10.8" version: "6" , # browserName: "iphone" # platform: "OS X 10.9" # version: "7" # , browserName: "internet explorer" platform: "Windows 8.1" version: "11" , browserName: "internet explorer" platform: "Windows 8" version: "10" , browserName: "internet explorer" platform: "Windows 7" version: "9" , browserName: "internet explorer" platform: "Windows 7" version: "8" , browserName: "internet explorer" platform: "Windows XP" version: "7" ] if (exports) exports.modules = browsers exports.sauceBrowsers = sauceBrowsers = do -> b = {} for browser in browsers key = "PI:KEY:<KEY>END_PIbrowser.browserName.replace " ", "_PI:KEY:<KEY>END_PI"}-#{browser.version || ''PI:KEY:<KEY>END_PI}-#{browser.platform.replace " ", "_"}" key = key.replace " ", "_" b[key] = base: 'SauceLabs' browserName: browser.browserName version: browser.version platform: browser.platform return b exports.sauceBrowserKeys = do -> res = [] for k of sauceBrowsers res.push k return res
[ { "context": "# LANGUAGE: Coffeescript\n# AUTHOR: Shelby Stanton\n# GITHUB: https://github.com/Minimilk93**/\n\nconso", "end": 49, "score": 0.9998952746391296, "start": 35, "tag": "NAME", "value": "Shelby Stanton" }, { "context": "THOR: Shelby Stanton\n# GITHUB: https://github.com/Mi...
scripts/HelloWorld.coffee
breezage/Hacktoberfest-1
0
# LANGUAGE: Coffeescript # AUTHOR: Shelby Stanton # GITHUB: https://github.com/Minimilk93**/ console.log "Hello, World!"
121113
# LANGUAGE: Coffeescript # AUTHOR: <NAME> # GITHUB: https://github.com/Minimilk93**/ console.log "Hello, World!"
true
# LANGUAGE: Coffeescript # AUTHOR: PI:NAME:<NAME>END_PI # GITHUB: https://github.com/Minimilk93**/ console.log "Hello, World!"
[ { "context": "llow usage of specific boolean keywords.\n# @author Julian Rosse\n###\n'use strict'\n\n#------------------------------", "end": 116, "score": 0.9998445510864258, "start": 104, "tag": "NAME", "value": "Julian Rosse" } ]
src/tests/rules/boolean-keywords.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview This rule should require or disallow usage of specific boolean keywords. # @author Julian Rosse ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/boolean-keywords' {RuleTester} = require 'eslint' path = require 'path' error = (unexpected, replacement) -> if replacement? messageId: 'unexpected-fixable' data: { unexpected replacement } else messageId: 'unexpected' data: { unexpected } #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'boolean-keywords', rule, valid: [ code: 'yes or no' options: [allow: ['yes', 'no']] , code: 'on or off' options: [allow: ['on', 'off']] , code: 'true or false' options: [allow: ['true', 'false']] , code: 'yes or no' options: [disallow: ['true', 'false']] , code: 'yes or no' options: [disallow: ['on', 'off']] , code: 'yes or no' options: [disallow: ['on', 'off', 'true']] , code: 'on or off' options: [disallow: ['yes', 'no']] , code: 'on or off' options: [disallow: ['true', 'false']] , code: 'true' options: [disallow: ['yes', 'no']] , code: 'false' options: [disallow: ['on', 'off']] ] invalid: [ code: 'a is true' output: 'a is yes' options: [allow: ['yes', 'no']] errors: [error 'true', 'yes'] , code: 'a is true' output: 'a is yes' options: [disallow: ['true', 'false', 'on']] errors: [error 'true', 'yes'] , code: 'a is false' output: 'a is no' options: [allow: ['yes', 'no']] errors: [error 'false', 'no'] , code: 'a is false' output: 'a is no' options: [disallow: ['true', 'false', 'on', 'off']] errors: [error 'false', 'no'] , code: 'a is on' output: 'a is yes' options: [allow: ['yes', 'no']] errors: [error 'on', 'yes'] , code: 'a is on' output: 'a is yes' options: [disallow: ['true', 'false', 'on', 'off']] errors: [error 'on', 'yes'] , code: 'a is off' output: 'a is no' options: [allow: ['yes', 'no']] errors: [error 'off', 'no'] , code: 'a is off' output: 'a is no' options: [disallow: ['true', 'false', 'on', 'off']] errors: [error 'off', 'no'] , code: 'a and true' output: 'a and on' options: [allow: ['on', 'off']] errors: [error 'true', 'on'] , code: 'a and yes' output: 'a and true' options: [disallow: ['yes', 'no', 'on', 'off']] errors: [error 'yes', 'true'] , code: 'a and false' output: 'a and off' options: [allow: ['on', 'off']] errors: [error 'false', 'off'] , code: 'a and no' output: 'a and false' options: [disallow: ['yes', 'no', 'on', 'off']] errors: [error 'no', 'false'] , # can't fix when multiple allowed options code: 'false' output: 'false' options: [allow: ['yes', 'no', 'on', 'off']] errors: [error 'false'] , code: 'not false' output: 'not false' options: [disallow: ['true', 'false']] errors: [error 'false'] ]
67440
###* # @fileoverview This rule should require or disallow usage of specific boolean keywords. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/boolean-keywords' {RuleTester} = require 'eslint' path = require 'path' error = (unexpected, replacement) -> if replacement? messageId: 'unexpected-fixable' data: { unexpected replacement } else messageId: 'unexpected' data: { unexpected } #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'boolean-keywords', rule, valid: [ code: 'yes or no' options: [allow: ['yes', 'no']] , code: 'on or off' options: [allow: ['on', 'off']] , code: 'true or false' options: [allow: ['true', 'false']] , code: 'yes or no' options: [disallow: ['true', 'false']] , code: 'yes or no' options: [disallow: ['on', 'off']] , code: 'yes or no' options: [disallow: ['on', 'off', 'true']] , code: 'on or off' options: [disallow: ['yes', 'no']] , code: 'on or off' options: [disallow: ['true', 'false']] , code: 'true' options: [disallow: ['yes', 'no']] , code: 'false' options: [disallow: ['on', 'off']] ] invalid: [ code: 'a is true' output: 'a is yes' options: [allow: ['yes', 'no']] errors: [error 'true', 'yes'] , code: 'a is true' output: 'a is yes' options: [disallow: ['true', 'false', 'on']] errors: [error 'true', 'yes'] , code: 'a is false' output: 'a is no' options: [allow: ['yes', 'no']] errors: [error 'false', 'no'] , code: 'a is false' output: 'a is no' options: [disallow: ['true', 'false', 'on', 'off']] errors: [error 'false', 'no'] , code: 'a is on' output: 'a is yes' options: [allow: ['yes', 'no']] errors: [error 'on', 'yes'] , code: 'a is on' output: 'a is yes' options: [disallow: ['true', 'false', 'on', 'off']] errors: [error 'on', 'yes'] , code: 'a is off' output: 'a is no' options: [allow: ['yes', 'no']] errors: [error 'off', 'no'] , code: 'a is off' output: 'a is no' options: [disallow: ['true', 'false', 'on', 'off']] errors: [error 'off', 'no'] , code: 'a and true' output: 'a and on' options: [allow: ['on', 'off']] errors: [error 'true', 'on'] , code: 'a and yes' output: 'a and true' options: [disallow: ['yes', 'no', 'on', 'off']] errors: [error 'yes', 'true'] , code: 'a and false' output: 'a and off' options: [allow: ['on', 'off']] errors: [error 'false', 'off'] , code: 'a and no' output: 'a and false' options: [disallow: ['yes', 'no', 'on', 'off']] errors: [error 'no', 'false'] , # can't fix when multiple allowed options code: 'false' output: 'false' options: [allow: ['yes', 'no', 'on', 'off']] errors: [error 'false'] , code: 'not false' output: 'not false' options: [disallow: ['true', 'false']] errors: [error 'false'] ]
true
###* # @fileoverview This rule should require or disallow usage of specific boolean keywords. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/boolean-keywords' {RuleTester} = require 'eslint' path = require 'path' error = (unexpected, replacement) -> if replacement? messageId: 'unexpected-fixable' data: { unexpected replacement } else messageId: 'unexpected' data: { unexpected } #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'boolean-keywords', rule, valid: [ code: 'yes or no' options: [allow: ['yes', 'no']] , code: 'on or off' options: [allow: ['on', 'off']] , code: 'true or false' options: [allow: ['true', 'false']] , code: 'yes or no' options: [disallow: ['true', 'false']] , code: 'yes or no' options: [disallow: ['on', 'off']] , code: 'yes or no' options: [disallow: ['on', 'off', 'true']] , code: 'on or off' options: [disallow: ['yes', 'no']] , code: 'on or off' options: [disallow: ['true', 'false']] , code: 'true' options: [disallow: ['yes', 'no']] , code: 'false' options: [disallow: ['on', 'off']] ] invalid: [ code: 'a is true' output: 'a is yes' options: [allow: ['yes', 'no']] errors: [error 'true', 'yes'] , code: 'a is true' output: 'a is yes' options: [disallow: ['true', 'false', 'on']] errors: [error 'true', 'yes'] , code: 'a is false' output: 'a is no' options: [allow: ['yes', 'no']] errors: [error 'false', 'no'] , code: 'a is false' output: 'a is no' options: [disallow: ['true', 'false', 'on', 'off']] errors: [error 'false', 'no'] , code: 'a is on' output: 'a is yes' options: [allow: ['yes', 'no']] errors: [error 'on', 'yes'] , code: 'a is on' output: 'a is yes' options: [disallow: ['true', 'false', 'on', 'off']] errors: [error 'on', 'yes'] , code: 'a is off' output: 'a is no' options: [allow: ['yes', 'no']] errors: [error 'off', 'no'] , code: 'a is off' output: 'a is no' options: [disallow: ['true', 'false', 'on', 'off']] errors: [error 'off', 'no'] , code: 'a and true' output: 'a and on' options: [allow: ['on', 'off']] errors: [error 'true', 'on'] , code: 'a and yes' output: 'a and true' options: [disallow: ['yes', 'no', 'on', 'off']] errors: [error 'yes', 'true'] , code: 'a and false' output: 'a and off' options: [allow: ['on', 'off']] errors: [error 'false', 'off'] , code: 'a and no' output: 'a and false' options: [disallow: ['yes', 'no', 'on', 'off']] errors: [error 'no', 'false'] , # can't fix when multiple allowed options code: 'false' output: 'false' options: [allow: ['yes', 'no', 'on', 'off']] errors: [error 'false'] , code: 'not false' output: 'not false' options: [disallow: ['true', 'false']] errors: [error 'false'] ]
[ { "context": "\n\n@namespace Quo.Gestures\n@class Rotation\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\n\n", "end": 140, "score": 0.9998871088027954, "start": 119, "tag": "NAME", "value": "Javier Jimenez Villar" }, { "context": "s\n@class Rot...
source/quo.gestures.rotation.coffee
lguzzon/QuoJS
558
### Quo Rotation Gestures: rotate, rotating, rotateLeft, rotateRight @namespace Quo.Gestures @class Rotation @author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi ### "use strict" Quo.Gestures.add name : "rotation" events : ["rotate", "rotating", "rotateLeft", "rotateRight"] handler : do (base = Quo.Gestures) -> GAP = 5 ROTATION_LIMIT = 20 _target = null _num_rotations = 0 _start = null _last = null start = (target, data) -> if data.length is 2 _target = target _num_rotations = 0 _start = _rotation(data[0], data[1]) move = (target, data) -> if _start and data.length is 2 delta = _rotation(data[0], data[1]) - _start if _last and Math.abs(_last.delta - delta) > ROTATION_LIMIT delta += (360 * _sign(_last.delta)) if Math.abs(delta) > 360 _num_rotations++ delta -= (360 * _sign(_last.delta)) _last = {touches: data, delta: delta, rotationsCount: _num_rotations} _check(true) cancel = end = (target, data) -> if _start and _last _check(false) _target = null _num_rotations = 0 _start = null _last = null _start = null _sign = (num) -> if num < 0 then -1 else 1 _rotation = (A, B) -> theta = Math.atan2(A.y-B.y, A.x-B.x) (if theta < 0 then theta + 2 * Math.PI else theta) * 180 / Math.PI _check = (moving) -> if moving base.trigger _target, "rotating", _last else if Math.abs(_last.delta) > GAP base.trigger _target, "rotate", _last ev = if _last.delta > 0 then "rotateRight" else "rotateLeft" base.trigger _target, ev, _last start: start move: move end: end
70045
### Quo Rotation Gestures: rotate, rotating, rotateLeft, rotateRight @namespace Quo.Gestures @class Rotation @author <NAME> <<EMAIL>> || @soyjavi ### "use strict" Quo.Gestures.add name : "rotation" events : ["rotate", "rotating", "rotateLeft", "rotateRight"] handler : do (base = Quo.Gestures) -> GAP = 5 ROTATION_LIMIT = 20 _target = null _num_rotations = 0 _start = null _last = null start = (target, data) -> if data.length is 2 _target = target _num_rotations = 0 _start = _rotation(data[0], data[1]) move = (target, data) -> if _start and data.length is 2 delta = _rotation(data[0], data[1]) - _start if _last and Math.abs(_last.delta - delta) > ROTATION_LIMIT delta += (360 * _sign(_last.delta)) if Math.abs(delta) > 360 _num_rotations++ delta -= (360 * _sign(_last.delta)) _last = {touches: data, delta: delta, rotationsCount: _num_rotations} _check(true) cancel = end = (target, data) -> if _start and _last _check(false) _target = null _num_rotations = 0 _start = null _last = null _start = null _sign = (num) -> if num < 0 then -1 else 1 _rotation = (A, B) -> theta = Math.atan2(A.y-B.y, A.x-B.x) (if theta < 0 then theta + 2 * Math.PI else theta) * 180 / Math.PI _check = (moving) -> if moving base.trigger _target, "rotating", _last else if Math.abs(_last.delta) > GAP base.trigger _target, "rotate", _last ev = if _last.delta > 0 then "rotateRight" else "rotateLeft" base.trigger _target, ev, _last start: start move: move end: end
true
### Quo Rotation Gestures: rotate, rotating, rotateLeft, rotateRight @namespace Quo.Gestures @class Rotation @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi ### "use strict" Quo.Gestures.add name : "rotation" events : ["rotate", "rotating", "rotateLeft", "rotateRight"] handler : do (base = Quo.Gestures) -> GAP = 5 ROTATION_LIMIT = 20 _target = null _num_rotations = 0 _start = null _last = null start = (target, data) -> if data.length is 2 _target = target _num_rotations = 0 _start = _rotation(data[0], data[1]) move = (target, data) -> if _start and data.length is 2 delta = _rotation(data[0], data[1]) - _start if _last and Math.abs(_last.delta - delta) > ROTATION_LIMIT delta += (360 * _sign(_last.delta)) if Math.abs(delta) > 360 _num_rotations++ delta -= (360 * _sign(_last.delta)) _last = {touches: data, delta: delta, rotationsCount: _num_rotations} _check(true) cancel = end = (target, data) -> if _start and _last _check(false) _target = null _num_rotations = 0 _start = null _last = null _start = null _sign = (num) -> if num < 0 then -1 else 1 _rotation = (A, B) -> theta = Math.atan2(A.y-B.y, A.x-B.x) (if theta < 0 then theta + 2 * Math.PI else theta) * 180 / Math.PI _check = (moving) -> if moving base.trigger _target, "rotating", _last else if Math.abs(_last.delta) > GAP base.trigger _target, "rotate", _last ev = if _last.delta > 0 then "rotateRight" else "rotateLeft" base.trigger _target, ev, _last start: start move: move end: end
[ { "context": "ssNode = {type: 'device', uuid : \"12345\", token: \"45678\"}\n @scope.stopProcess(@fakeProcessNode)\n ", "end": 1645, "score": 0.763421893119812, "start": 1640, "tag": "KEY", "value": "45678" }, { "context": " = {type: 'octoblu:flow', uuid : \"12345\", token: \...
test/angular/controllers/process-controller-spec.coffee
octoblu/octoblu-frontend
5
describe 'ProcessController', -> beforeEach -> class FakeProcessNodeService constructor: (@q) -> @processNodesDefer = @q.defer() @getProcessNodes = sinon.stub().returns @processNodesDefer.promise @stopProcess = sinon.stub().returns @q.when() @startProcess = sinon.stub().returns @q.when() class FakeFlowService constructor: -> @start = sinon.spy() @stop = sinon.spy() module 'octobluApp' inject ($controller, $rootScope, $q) => @q = $q @scope = $rootScope.$new() @fakeProcessNodeService = new FakeProcessNodeService @q @fakeFlowService = new FakeFlowService @q @sut = $controller('ProcessController', { $scope : @scope ProcessNodeService : @fakeProcessNodeService, FlowService : @fakeFlowService, }) describe "when the user has no configured nodes available", -> beforeEach -> @fakeProcessNodeService.processNodesDefer.resolve [] @scope.$digest() it "should set processNodes to an empty array", -> expect(@scope.processNodes).to.deep.equal [] describe "when the user does have configured nodes available", -> beforeEach -> @fakeProcessNodeService.processNodesDefer.resolve [1,2,3] @scope.$digest() it "should set processNodes to a populated array", -> expect(@scope.processNodes).to.deep.equal [1,2,3] describe "stopProcess", -> it "should exist", -> expect(@scope.stopProcess).to.exist describe 'when called with a device', -> beforeEach -> @fakeProcessNode = {type: 'device', uuid : "12345", token: "45678"} @scope.stopProcess(@fakeProcessNode) @scope.$digest() it 'should call ProcessNodeService with a device', -> expect(@fakeProcessNodeService.stopProcess).to.have.been.calledWith(@fakeProcessNode) describe 'when called with a flow', -> beforeEach -> @fakeProcessNode = {type: 'octoblu:flow', uuid : "12345", token: "45678"} @scope.stopProcess(@fakeProcessNode) @scope.$digest() it 'should call FlowService.stop with a flow', -> expect(@fakeFlowService.stop).to.have.been.calledWith({ flowId: @fakeProcessNode.uuid }) describe "startProcess", -> it "should exist", -> expect(@scope.startProcess).to.exist describe 'when called with a device', -> beforeEach -> @fakeProcessNode = {type: 'device', uuid : "12345", token: "45678"} @scope.startProcess(@fakeProcessNode) @scope.$digest() it 'should call ProcessNodeService with a device', -> expect(@fakeProcessNodeService.startProcess).to.have.been.calledWith(@fakeProcessNode) describe 'when called with a flow', -> beforeEach -> @fakeProcessNode = {type: 'octoblu:flow', uuid : "12345", token: "45678"} @scope.startProcess(@fakeProcessNode) @scope.$digest() it 'should call FlowService.start with a flow', -> expect(@fakeFlowService.start).to.have.been.calledWith({ flowId: @fakeProcessNode.uuid }) describe 'resetMessageCounter', -> describe 'updating', -> beforeEach -> @device = {messagesReceived: 123, messagesSent: 123, totalMessagesReceived: 7, totalMessagesSent: 8, messagesSentOverTime: [0], messagesReceivedOverTime : [0]} @fakeProcessNodeService.processNodesDefer.resolve [@device] @scope.$digest() @scope.resetMessageCounter() it 'should set messagesReceived to zero', -> expect(@device.messagesReceived).to.equal 0 it 'should set totalMessagesReceived to messagesReceived', -> expect(@device.totalMessagesReceived).to.equal 130 it 'should append messagesReceived to messagesReceivedOverTime', -> expect(@device.messagesReceivedOverTime).to.deep.equal [0,123] it 'should set messagesSent to zero', -> expect(@device.messagesSent).to.equal 0 it 'should set totalMessagesSent to messagesSent', -> expect(@device.totalMessagesSent).to.equal 131 it 'should append messagesSent to messagesSentOverTime', -> expect(@device.messagesSentOverTime).to.deep.equal [0,123] describe 'when messagesSentOverTime and messagesReceivedOverTime is full', -> beforeEach -> @device = {messagesReceived: 11, messagesSent: 11, totalMessagesReceived: 7, totalMessagesSent: 8, messagesSentOverTime: [1,2,3,4,5,6,7,8,9,10], messagesReceivedOverTime : [1,2,3,4,5,6,7,8,9,10]} @fakeProcessNodeService.processNodesDefer.resolve [@device] @scope.$digest() @scope.resetMessageCounter() it 'should limit size of messagesSentOverTime to 10', -> expect(@device.messagesSentOverTime).to.deep.equal [2,3,4,5,6,7,8,9,10,11] it 'should limit size of messagesReceivedOverTime to 10', -> expect(@device.messagesReceivedOverTime).to.deep.equal [2,3,4,5,6,7,8,9,10,11] describe 'getUptime', -> it 'should return null if not online', -> expect(@scope.getUptime(false)).to.equal null it 'should return null if online and onlineSince is undefined', -> expect(@scope.getUptime(true, undefined)).to.equal null it 'should return a string if online and onlineSince is defined', -> expect(@scope.getUptime(true, new Date())).not.to.equal null describe 'setSortProcess', -> describe 'by default', -> it "should set sortProcesses to name", -> expect(@scope.sortProcesses).to.equal 'name' it "should set sortAscending to true", -> expect(@scope.sortAscending).to.be.true describe 'when called for the first time', -> beforeEach -> @scope.setSortProcess 'Foo' it "should set sortProcess on the scope", -> expect(@scope.sortProcesses).to.equal 'Foo' describe 'when called with the same name twice', -> beforeEach -> @scope.setSortProcess 'Foo' @scope.setSortProcess 'Foo' it "should set sortAscending to false", -> expect(@scope.sortAscending).to.be.false describe 'when called with the same name thrice', -> beforeEach -> @scope.setSortProcess 'Foo' @scope.setSortProcess 'Foo' @scope.setSortProcess 'Foo' it "should set sortAscending to true", -> expect(@scope.sortAscending).to.be.true describe 'when called with a different name', -> beforeEach -> @scope.setSortProcess 'Foo' @scope.setSortProcess 'Bar' it "should set sortAscending to true", -> expect(@scope.sortAscending).to.be.true
188560
describe 'ProcessController', -> beforeEach -> class FakeProcessNodeService constructor: (@q) -> @processNodesDefer = @q.defer() @getProcessNodes = sinon.stub().returns @processNodesDefer.promise @stopProcess = sinon.stub().returns @q.when() @startProcess = sinon.stub().returns @q.when() class FakeFlowService constructor: -> @start = sinon.spy() @stop = sinon.spy() module 'octobluApp' inject ($controller, $rootScope, $q) => @q = $q @scope = $rootScope.$new() @fakeProcessNodeService = new FakeProcessNodeService @q @fakeFlowService = new FakeFlowService @q @sut = $controller('ProcessController', { $scope : @scope ProcessNodeService : @fakeProcessNodeService, FlowService : @fakeFlowService, }) describe "when the user has no configured nodes available", -> beforeEach -> @fakeProcessNodeService.processNodesDefer.resolve [] @scope.$digest() it "should set processNodes to an empty array", -> expect(@scope.processNodes).to.deep.equal [] describe "when the user does have configured nodes available", -> beforeEach -> @fakeProcessNodeService.processNodesDefer.resolve [1,2,3] @scope.$digest() it "should set processNodes to a populated array", -> expect(@scope.processNodes).to.deep.equal [1,2,3] describe "stopProcess", -> it "should exist", -> expect(@scope.stopProcess).to.exist describe 'when called with a device', -> beforeEach -> @fakeProcessNode = {type: 'device', uuid : "12345", token: "<KEY>"} @scope.stopProcess(@fakeProcessNode) @scope.$digest() it 'should call ProcessNodeService with a device', -> expect(@fakeProcessNodeService.stopProcess).to.have.been.calledWith(@fakeProcessNode) describe 'when called with a flow', -> beforeEach -> @fakeProcessNode = {type: 'octoblu:flow', uuid : "12345", token: "<KEY>8"} @scope.stopProcess(@fakeProcessNode) @scope.$digest() it 'should call FlowService.stop with a flow', -> expect(@fakeFlowService.stop).to.have.been.calledWith({ flowId: @fakeProcessNode.uuid }) describe "startProcess", -> it "should exist", -> expect(@scope.startProcess).to.exist describe 'when called with a device', -> beforeEach -> @fakeProcessNode = {type: 'device', uuid : "12345", token: "<KEY>"} @scope.startProcess(@fakeProcessNode) @scope.$digest() it 'should call ProcessNodeService with a device', -> expect(@fakeProcessNodeService.startProcess).to.have.been.calledWith(@fakeProcessNode) describe 'when called with a flow', -> beforeEach -> @fakeProcessNode = {type: 'octoblu:flow', uuid : "12345", token: "<KEY>"} @scope.startProcess(@fakeProcessNode) @scope.$digest() it 'should call FlowService.start with a flow', -> expect(@fakeFlowService.start).to.have.been.calledWith({ flowId: @fakeProcessNode.uuid }) describe 'resetMessageCounter', -> describe 'updating', -> beforeEach -> @device = {messagesReceived: 123, messagesSent: 123, totalMessagesReceived: 7, totalMessagesSent: 8, messagesSentOverTime: [0], messagesReceivedOverTime : [0]} @fakeProcessNodeService.processNodesDefer.resolve [@device] @scope.$digest() @scope.resetMessageCounter() it 'should set messagesReceived to zero', -> expect(@device.messagesReceived).to.equal 0 it 'should set totalMessagesReceived to messagesReceived', -> expect(@device.totalMessagesReceived).to.equal 130 it 'should append messagesReceived to messagesReceivedOverTime', -> expect(@device.messagesReceivedOverTime).to.deep.equal [0,123] it 'should set messagesSent to zero', -> expect(@device.messagesSent).to.equal 0 it 'should set totalMessagesSent to messagesSent', -> expect(@device.totalMessagesSent).to.equal 131 it 'should append messagesSent to messagesSentOverTime', -> expect(@device.messagesSentOverTime).to.deep.equal [0,123] describe 'when messagesSentOverTime and messagesReceivedOverTime is full', -> beforeEach -> @device = {messagesReceived: 11, messagesSent: 11, totalMessagesReceived: 7, totalMessagesSent: 8, messagesSentOverTime: [1,2,3,4,5,6,7,8,9,10], messagesReceivedOverTime : [1,2,3,4,5,6,7,8,9,10]} @fakeProcessNodeService.processNodesDefer.resolve [@device] @scope.$digest() @scope.resetMessageCounter() it 'should limit size of messagesSentOverTime to 10', -> expect(@device.messagesSentOverTime).to.deep.equal [2,3,4,5,6,7,8,9,10,11] it 'should limit size of messagesReceivedOverTime to 10', -> expect(@device.messagesReceivedOverTime).to.deep.equal [2,3,4,5,6,7,8,9,10,11] describe 'getUptime', -> it 'should return null if not online', -> expect(@scope.getUptime(false)).to.equal null it 'should return null if online and onlineSince is undefined', -> expect(@scope.getUptime(true, undefined)).to.equal null it 'should return a string if online and onlineSince is defined', -> expect(@scope.getUptime(true, new Date())).not.to.equal null describe 'setSortProcess', -> describe 'by default', -> it "should set sortProcesses to name", -> expect(@scope.sortProcesses).to.equal 'name' it "should set sortAscending to true", -> expect(@scope.sortAscending).to.be.true describe 'when called for the first time', -> beforeEach -> @scope.setSortProcess 'Foo' it "should set sortProcess on the scope", -> expect(@scope.sortProcesses).to.equal 'Foo' describe 'when called with the same name twice', -> beforeEach -> @scope.setSortProcess 'Foo' @scope.setSortProcess 'Foo' it "should set sortAscending to false", -> expect(@scope.sortAscending).to.be.false describe 'when called with the same name thrice', -> beforeEach -> @scope.setSortProcess 'Foo' @scope.setSortProcess 'Foo' @scope.setSortProcess 'Foo' it "should set sortAscending to true", -> expect(@scope.sortAscending).to.be.true describe 'when called with a different name', -> beforeEach -> @scope.setSortProcess 'Foo' @scope.setSortProcess 'Bar' it "should set sortAscending to true", -> expect(@scope.sortAscending).to.be.true
true
describe 'ProcessController', -> beforeEach -> class FakeProcessNodeService constructor: (@q) -> @processNodesDefer = @q.defer() @getProcessNodes = sinon.stub().returns @processNodesDefer.promise @stopProcess = sinon.stub().returns @q.when() @startProcess = sinon.stub().returns @q.when() class FakeFlowService constructor: -> @start = sinon.spy() @stop = sinon.spy() module 'octobluApp' inject ($controller, $rootScope, $q) => @q = $q @scope = $rootScope.$new() @fakeProcessNodeService = new FakeProcessNodeService @q @fakeFlowService = new FakeFlowService @q @sut = $controller('ProcessController', { $scope : @scope ProcessNodeService : @fakeProcessNodeService, FlowService : @fakeFlowService, }) describe "when the user has no configured nodes available", -> beforeEach -> @fakeProcessNodeService.processNodesDefer.resolve [] @scope.$digest() it "should set processNodes to an empty array", -> expect(@scope.processNodes).to.deep.equal [] describe "when the user does have configured nodes available", -> beforeEach -> @fakeProcessNodeService.processNodesDefer.resolve [1,2,3] @scope.$digest() it "should set processNodes to a populated array", -> expect(@scope.processNodes).to.deep.equal [1,2,3] describe "stopProcess", -> it "should exist", -> expect(@scope.stopProcess).to.exist describe 'when called with a device', -> beforeEach -> @fakeProcessNode = {type: 'device', uuid : "12345", token: "PI:KEY:<KEY>END_PI"} @scope.stopProcess(@fakeProcessNode) @scope.$digest() it 'should call ProcessNodeService with a device', -> expect(@fakeProcessNodeService.stopProcess).to.have.been.calledWith(@fakeProcessNode) describe 'when called with a flow', -> beforeEach -> @fakeProcessNode = {type: 'octoblu:flow', uuid : "12345", token: "PI:KEY:<KEY>END_PI8"} @scope.stopProcess(@fakeProcessNode) @scope.$digest() it 'should call FlowService.stop with a flow', -> expect(@fakeFlowService.stop).to.have.been.calledWith({ flowId: @fakeProcessNode.uuid }) describe "startProcess", -> it "should exist", -> expect(@scope.startProcess).to.exist describe 'when called with a device', -> beforeEach -> @fakeProcessNode = {type: 'device', uuid : "12345", token: "PI:PASSWORD:<KEY>END_PI"} @scope.startProcess(@fakeProcessNode) @scope.$digest() it 'should call ProcessNodeService with a device', -> expect(@fakeProcessNodeService.startProcess).to.have.been.calledWith(@fakeProcessNode) describe 'when called with a flow', -> beforeEach -> @fakeProcessNode = {type: 'octoblu:flow', uuid : "12345", token: "PI:PASSWORD:<KEY>END_PI"} @scope.startProcess(@fakeProcessNode) @scope.$digest() it 'should call FlowService.start with a flow', -> expect(@fakeFlowService.start).to.have.been.calledWith({ flowId: @fakeProcessNode.uuid }) describe 'resetMessageCounter', -> describe 'updating', -> beforeEach -> @device = {messagesReceived: 123, messagesSent: 123, totalMessagesReceived: 7, totalMessagesSent: 8, messagesSentOverTime: [0], messagesReceivedOverTime : [0]} @fakeProcessNodeService.processNodesDefer.resolve [@device] @scope.$digest() @scope.resetMessageCounter() it 'should set messagesReceived to zero', -> expect(@device.messagesReceived).to.equal 0 it 'should set totalMessagesReceived to messagesReceived', -> expect(@device.totalMessagesReceived).to.equal 130 it 'should append messagesReceived to messagesReceivedOverTime', -> expect(@device.messagesReceivedOverTime).to.deep.equal [0,123] it 'should set messagesSent to zero', -> expect(@device.messagesSent).to.equal 0 it 'should set totalMessagesSent to messagesSent', -> expect(@device.totalMessagesSent).to.equal 131 it 'should append messagesSent to messagesSentOverTime', -> expect(@device.messagesSentOverTime).to.deep.equal [0,123] describe 'when messagesSentOverTime and messagesReceivedOverTime is full', -> beforeEach -> @device = {messagesReceived: 11, messagesSent: 11, totalMessagesReceived: 7, totalMessagesSent: 8, messagesSentOverTime: [1,2,3,4,5,6,7,8,9,10], messagesReceivedOverTime : [1,2,3,4,5,6,7,8,9,10]} @fakeProcessNodeService.processNodesDefer.resolve [@device] @scope.$digest() @scope.resetMessageCounter() it 'should limit size of messagesSentOverTime to 10', -> expect(@device.messagesSentOverTime).to.deep.equal [2,3,4,5,6,7,8,9,10,11] it 'should limit size of messagesReceivedOverTime to 10', -> expect(@device.messagesReceivedOverTime).to.deep.equal [2,3,4,5,6,7,8,9,10,11] describe 'getUptime', -> it 'should return null if not online', -> expect(@scope.getUptime(false)).to.equal null it 'should return null if online and onlineSince is undefined', -> expect(@scope.getUptime(true, undefined)).to.equal null it 'should return a string if online and onlineSince is defined', -> expect(@scope.getUptime(true, new Date())).not.to.equal null describe 'setSortProcess', -> describe 'by default', -> it "should set sortProcesses to name", -> expect(@scope.sortProcesses).to.equal 'name' it "should set sortAscending to true", -> expect(@scope.sortAscending).to.be.true describe 'when called for the first time', -> beforeEach -> @scope.setSortProcess 'Foo' it "should set sortProcess on the scope", -> expect(@scope.sortProcesses).to.equal 'Foo' describe 'when called with the same name twice', -> beforeEach -> @scope.setSortProcess 'Foo' @scope.setSortProcess 'Foo' it "should set sortAscending to false", -> expect(@scope.sortAscending).to.be.false describe 'when called with the same name thrice', -> beforeEach -> @scope.setSortProcess 'Foo' @scope.setSortProcess 'Foo' @scope.setSortProcess 'Foo' it "should set sortAscending to true", -> expect(@scope.sortAscending).to.be.true describe 'when called with a different name', -> beforeEach -> @scope.setSortProcess 'Foo' @scope.setSortProcess 'Bar' it "should set sortAscending to true", -> expect(@scope.sortAscending).to.be.true
[ { "context": "ystem http://glawn.org\n#\n# Copyright (c) 2012,2013 Eamonn O'Brien-Strain All rights\n# reserved. This program and the accom", "end": 109, "score": 0.9998981952667236, "start": 88, "tag": "NAME", "value": "Eamonn O'Brien-Strain" }, { "context": "ipse.org/legal/epl-v10....
test-coffee/mainSpec.coffee
eobrain/glan
0
### # This file is part of the Glan system http://glawn.org # # Copyright (c) 2012,2013 Eamonn O'Brien-Strain All rights # reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Eamonn O'Brien-Strain e@obrain.com - initial author ###
118185
### # This file is part of the Glan system http://glawn.org # # Copyright (c) 2012,2013 <NAME> All rights # reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # <NAME> <EMAIL> - initial author ###
true
### # This file is part of the Glan system http://glawn.org # # Copyright (c) 2012,2013 PI:NAME:<NAME>END_PI All rights # reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI - initial author ###
[ { "context": "tModules.like(likeElms, {\n csrfToken: \"foobar\",\n likeText: \"foo like ({count})\",\n ", "end": 1067, "score": 0.5742654800415039, "start": 1061, "tag": "KEY", "value": "foobar" } ]
spirit/core/static/spirit/scripts/test/suites/like-spec.coffee
Ke-xueting/Spirit
974
describe "like plugin tests", -> likeElms = null likes = null post = null responseData = null beforeEach -> document.body.innerHTML = """ <div> <ul> <li><a class="js-like" href="/foo/create/" data-count="0"><i class="fa fa-heart"></i> like</a></li> </ul> </div> <div> <ul> <li><a class="js-like" href="foo/delete/" data-count="1"><i class="fa fa-heart"></i> remove like</a></li> </ul> </div> """ responseData = {url_create: '/create/foo'} post = spyOn(global, 'fetch') post.and.callFake( -> { then: (func) -> data = func({ok: true, json: -> responseData}) return { then: (func) -> func(data) return {catch: -> {then: (func) -> func()}} } }) likeElms = document.querySelectorAll('.js-like') likes = stModules.like(likeElms, { csrfToken: "foobar", likeText: "foo like ({count})", removeLikeText: "foo remove like ({count})" }) it "can create the like", -> post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(true) expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(post.calls.argsFor(0)[1].body.get('csrfmiddlewaretoken')).toEqual("foobar") it "can create and remove the like", -> # create post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") # remove post.calls.reset() responseData = {url_create: "/foo/create/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/delete/') expect(likeElms[0].textContent).toEqual("foo like (0)") # create again... and so on... post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") it "will tell about an api change", -> responseData = {unknown: null} likeElms[0].click() expect(likeElms[0].textContent).toEqual("api error") it "prevents from multiple posts while sending", -> post.and.callFake( -> {then: -> {then: -> {catch: -> {then: -> }}}}) likeElms[0].click() # next click should do nothing post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(false) it "prevents the default click behaviour", -> evt = document.createEvent("HTMLEvents") evt.initEvent("click", false, true) stopPropagation = spyOn(evt, 'stopPropagation') preventDefault = spyOn(evt, 'preventDefault') likeElms[0].dispatchEvent(evt) expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled()
59260
describe "like plugin tests", -> likeElms = null likes = null post = null responseData = null beforeEach -> document.body.innerHTML = """ <div> <ul> <li><a class="js-like" href="/foo/create/" data-count="0"><i class="fa fa-heart"></i> like</a></li> </ul> </div> <div> <ul> <li><a class="js-like" href="foo/delete/" data-count="1"><i class="fa fa-heart"></i> remove like</a></li> </ul> </div> """ responseData = {url_create: '/create/foo'} post = spyOn(global, 'fetch') post.and.callFake( -> { then: (func) -> data = func({ok: true, json: -> responseData}) return { then: (func) -> func(data) return {catch: -> {then: (func) -> func()}} } }) likeElms = document.querySelectorAll('.js-like') likes = stModules.like(likeElms, { csrfToken: "<KEY>", likeText: "foo like ({count})", removeLikeText: "foo remove like ({count})" }) it "can create the like", -> post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(true) expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(post.calls.argsFor(0)[1].body.get('csrfmiddlewaretoken')).toEqual("foobar") it "can create and remove the like", -> # create post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") # remove post.calls.reset() responseData = {url_create: "/foo/create/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/delete/') expect(likeElms[0].textContent).toEqual("foo like (0)") # create again... and so on... post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") it "will tell about an api change", -> responseData = {unknown: null} likeElms[0].click() expect(likeElms[0].textContent).toEqual("api error") it "prevents from multiple posts while sending", -> post.and.callFake( -> {then: -> {then: -> {catch: -> {then: -> }}}}) likeElms[0].click() # next click should do nothing post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(false) it "prevents the default click behaviour", -> evt = document.createEvent("HTMLEvents") evt.initEvent("click", false, true) stopPropagation = spyOn(evt, 'stopPropagation') preventDefault = spyOn(evt, 'preventDefault') likeElms[0].dispatchEvent(evt) expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled()
true
describe "like plugin tests", -> likeElms = null likes = null post = null responseData = null beforeEach -> document.body.innerHTML = """ <div> <ul> <li><a class="js-like" href="/foo/create/" data-count="0"><i class="fa fa-heart"></i> like</a></li> </ul> </div> <div> <ul> <li><a class="js-like" href="foo/delete/" data-count="1"><i class="fa fa-heart"></i> remove like</a></li> </ul> </div> """ responseData = {url_create: '/create/foo'} post = spyOn(global, 'fetch') post.and.callFake( -> { then: (func) -> data = func({ok: true, json: -> responseData}) return { then: (func) -> func(data) return {catch: -> {then: (func) -> func()}} } }) likeElms = document.querySelectorAll('.js-like') likes = stModules.like(likeElms, { csrfToken: "PI:KEY:<KEY>END_PI", likeText: "foo like ({count})", removeLikeText: "foo remove like ({count})" }) it "can create the like", -> post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(true) expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(post.calls.argsFor(0)[1].body.get('csrfmiddlewaretoken')).toEqual("foobar") it "can create and remove the like", -> # create post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") # remove post.calls.reset() responseData = {url_create: "/foo/create/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/delete/') expect(likeElms[0].textContent).toEqual("foo like (0)") # create again... and so on... post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") it "will tell about an api change", -> responseData = {unknown: null} likeElms[0].click() expect(likeElms[0].textContent).toEqual("api error") it "prevents from multiple posts while sending", -> post.and.callFake( -> {then: -> {then: -> {catch: -> {then: -> }}}}) likeElms[0].click() # next click should do nothing post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(false) it "prevents the default click behaviour", -> evt = document.createEvent("HTMLEvents") evt.initEvent("click", false, true) stopPropagation = spyOn(evt, 'stopPropagation') preventDefault = spyOn(evt, 'preventDefault') likeElms[0].dispatchEvent(evt) expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled()
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999162554740906, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/profile-page/rank-count.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import * as React from 'react' import { div } from 'react-dom-factories' el = React.createElement ranks = XH: 'ssh' X: 'ss' SH: 'sh' S: 's' A: 'a' export class RankCount extends React.PureComponent render: => div className: 'profile-rank-count', @renderRankCountEntry(name, grade) for name, grade of ranks renderRankCountEntry: (name, grade) => div key: name className: 'profile-rank-count__item' div className: "score-rank score-rank--#{name} score-rank--profile-page" osu.formatNumber(@props.stats.grade_counts[grade])
37900
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import * as React from 'react' import { div } from 'react-dom-factories' el = React.createElement ranks = XH: 'ssh' X: 'ss' SH: 'sh' S: 's' A: 'a' export class RankCount extends React.PureComponent render: => div className: 'profile-rank-count', @renderRankCountEntry(name, grade) for name, grade of ranks renderRankCountEntry: (name, grade) => div key: name className: 'profile-rank-count__item' div className: "score-rank score-rank--#{name} score-rank--profile-page" osu.formatNumber(@props.stats.grade_counts[grade])
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import * as React from 'react' import { div } from 'react-dom-factories' el = React.createElement ranks = XH: 'ssh' X: 'ss' SH: 'sh' S: 's' A: 'a' export class RankCount extends React.PureComponent render: => div className: 'profile-rank-count', @renderRankCountEntry(name, grade) for name, grade of ranks renderRankCountEntry: (name, grade) => div key: name className: 'profile-rank-count__item' div className: "score-rank score-rank--#{name} score-rank--profile-page" osu.formatNumber(@props.stats.grade_counts[grade])
[ { "context": "e:3},\n\t\t\t\t{label:\"expert\", value:4}]\n\n\t\tkeys = ({\"label\":key, \"level\":value, \"options\":options} for key, value", "end": 2870, "score": 0.6508926749229431, "start": 2860, "tag": "KEY", "value": "label\":key" }, { "context": "expert\", value:4}]\n\n\t\tke...
client/components/script/tags.coffee
MooqitaSFH/worklearn
0
############################################################# # functions ############################################################# ############################################################# _get_value = (template_instance) -> value = get_field_value template_instance.data if not value value = template_instance.tag_data.get() return value ############################################################# _split_tags = (tag_line) -> tags_in = tag_line.split "," tags = {} for tag in tags_in if tag == "" continue el = tag.split ":" tags[el[0]] = el[1] | 0 return tags ############################################################# _update_tags = (old_tags, new_tags) -> res = [] for tag, level of new_tags res.push(tag + ":" + (level | old_tags[tag])) return res.join "," ############################################################# _update_tag = (old_tags, new_tag) -> res = [] for tag, level of old_tags if tag == new_tag.label level = new_tag.level res.push tag + ":" + level return res.join "," ############################################################# _set_value = (template_instance, event, value) -> self = template_instance.data old = get_field_value self if not old template_instance.tag_data.set value return field = self.field collection = self.collection_name item_id = self.item_id set_field collection, item_id, field, value ############################################################# Template.tags.onCreated -> this.tag_data = new ReactiveVar("") ######################################################### Template.tags.events "change .edit-field": (event) -> instance = Template.instance() value = _get_value instance old_tags = _split_tags value new_tags = _split_tags event.target.value value = _update_tags old_tags, new_tags _set_value instance, event, value "change .tags": (event) -> instance = Template.instance() value = _get_value instance old_tags = _split_tags value target = event.target selected = target.options[target.selectedIndex] new_tag = {"label": this.label, "level": selected.value} value = _update_tag old_tags, new_tag _set_value instance, event, value ############################################################# Template.tags.helpers clean: () -> value = _get_value Template.instance() return value tag_line: () -> value = _get_value Template.instance() tags = _split_tags value keys = Object.keys tags return keys.join ",", keys tags: () -> instance = Template.instance() options = instance.data.rating_options value = _get_value instance tags = _split_tags value if not options options = [ {label:"not selected", value:0}, {label:"basic", value:1}, {label:"intermediate", value:2}, {label:"advanced", value:3}, {label:"expert", value:4}] keys = ({"label":key, "level":value, "options":options} for key, value of tags) return keys ############################################################# # Tag ############################################################# ############################################################# Template.tag.helpers options: ()-> opt = Template.instance().data.options return opt is_selected: (val) -> data = Template.instance().data if String(val) == String(data.level) return "selected" return ""
206825
############################################################# # functions ############################################################# ############################################################# _get_value = (template_instance) -> value = get_field_value template_instance.data if not value value = template_instance.tag_data.get() return value ############################################################# _split_tags = (tag_line) -> tags_in = tag_line.split "," tags = {} for tag in tags_in if tag == "" continue el = tag.split ":" tags[el[0]] = el[1] | 0 return tags ############################################################# _update_tags = (old_tags, new_tags) -> res = [] for tag, level of new_tags res.push(tag + ":" + (level | old_tags[tag])) return res.join "," ############################################################# _update_tag = (old_tags, new_tag) -> res = [] for tag, level of old_tags if tag == new_tag.label level = new_tag.level res.push tag + ":" + level return res.join "," ############################################################# _set_value = (template_instance, event, value) -> self = template_instance.data old = get_field_value self if not old template_instance.tag_data.set value return field = self.field collection = self.collection_name item_id = self.item_id set_field collection, item_id, field, value ############################################################# Template.tags.onCreated -> this.tag_data = new ReactiveVar("") ######################################################### Template.tags.events "change .edit-field": (event) -> instance = Template.instance() value = _get_value instance old_tags = _split_tags value new_tags = _split_tags event.target.value value = _update_tags old_tags, new_tags _set_value instance, event, value "change .tags": (event) -> instance = Template.instance() value = _get_value instance old_tags = _split_tags value target = event.target selected = target.options[target.selectedIndex] new_tag = {"label": this.label, "level": selected.value} value = _update_tag old_tags, new_tag _set_value instance, event, value ############################################################# Template.tags.helpers clean: () -> value = _get_value Template.instance() return value tag_line: () -> value = _get_value Template.instance() tags = _split_tags value keys = Object.keys tags return keys.join ",", keys tags: () -> instance = Template.instance() options = instance.data.rating_options value = _get_value instance tags = _split_tags value if not options options = [ {label:"not selected", value:0}, {label:"basic", value:1}, {label:"intermediate", value:2}, {label:"advanced", value:3}, {label:"expert", value:4}] keys = ({"<KEY>, "level":<KEY>, "options":options} for key, value of tags) return keys ############################################################# # Tag ############################################################# ############################################################# Template.tag.helpers options: ()-> opt = Template.instance().data.options return opt is_selected: (val) -> data = Template.instance().data if String(val) == String(data.level) return "selected" return ""
true
############################################################# # functions ############################################################# ############################################################# _get_value = (template_instance) -> value = get_field_value template_instance.data if not value value = template_instance.tag_data.get() return value ############################################################# _split_tags = (tag_line) -> tags_in = tag_line.split "," tags = {} for tag in tags_in if tag == "" continue el = tag.split ":" tags[el[0]] = el[1] | 0 return tags ############################################################# _update_tags = (old_tags, new_tags) -> res = [] for tag, level of new_tags res.push(tag + ":" + (level | old_tags[tag])) return res.join "," ############################################################# _update_tag = (old_tags, new_tag) -> res = [] for tag, level of old_tags if tag == new_tag.label level = new_tag.level res.push tag + ":" + level return res.join "," ############################################################# _set_value = (template_instance, event, value) -> self = template_instance.data old = get_field_value self if not old template_instance.tag_data.set value return field = self.field collection = self.collection_name item_id = self.item_id set_field collection, item_id, field, value ############################################################# Template.tags.onCreated -> this.tag_data = new ReactiveVar("") ######################################################### Template.tags.events "change .edit-field": (event) -> instance = Template.instance() value = _get_value instance old_tags = _split_tags value new_tags = _split_tags event.target.value value = _update_tags old_tags, new_tags _set_value instance, event, value "change .tags": (event) -> instance = Template.instance() value = _get_value instance old_tags = _split_tags value target = event.target selected = target.options[target.selectedIndex] new_tag = {"label": this.label, "level": selected.value} value = _update_tag old_tags, new_tag _set_value instance, event, value ############################################################# Template.tags.helpers clean: () -> value = _get_value Template.instance() return value tag_line: () -> value = _get_value Template.instance() tags = _split_tags value keys = Object.keys tags return keys.join ",", keys tags: () -> instance = Template.instance() options = instance.data.rating_options value = _get_value instance tags = _split_tags value if not options options = [ {label:"not selected", value:0}, {label:"basic", value:1}, {label:"intermediate", value:2}, {label:"advanced", value:3}, {label:"expert", value:4}] keys = ({"PI:KEY:<KEY>END_PI, "level":PI:KEY:<KEY>END_PI, "options":options} for key, value of tags) return keys ############################################################# # Tag ############################################################# ############################################################# Template.tag.helpers options: ()-> opt = Template.instance().data.options return opt is_selected: (val) -> data = Template.instance().data if String(val) == String(data.level) return "selected" return ""
[ { "context": " }\n\n mapsProvider.configure {\n key: 'AIzaSyBQMyvtbd56MQd_wYshtcKvht0rNMbJXEg'\n libraries: 'weather,geometry,visualizati", "end": 1162, "score": 0.9997546672821045, "start": 1123, "tag": "KEY", "value": "AIzaSyBQMyvtbd56MQd_wYshtcKvht0rNMbJXEg" } ]
client/lib/beesnearme.coffee
recursivefaults/beesnearme
0
angular.module 'bees-near-me', [ 'angular-meteor', 'ngRoute', 'accounts.ui', 'uiGmapgoogle-maps' ] angular.module('bees-near-me').config ['$routeProvider', 'uiGmapGoogleMapApiProvider', ($routeProvider, mapsProvider) -> $routeProvider.when '/', { templateUrl: 'client/landing/landing.html' controller: 'LandingPageController' } $routeProvider.when '/register_keeper', { templateUrl: 'client/landing/register_keeper.html' controller: 'SigninController' controllerAs: "signin" } $routeProvider.when '/register_swarm', { templateUrl: 'client/landing/register_swarm.html' controller: 'RegistrationController' controllerAs: "registrar" } $routeProvider.when '/map', { templateUrl: 'client/map/map.html' controller: 'MapController' controllerAs: "map" } $routeProvider.when '/swarms/:swarm_id', { templateUrl: 'client/landing/register_swarm.html' controller: 'RegistrationController' controllerAs: "registrar" } mapsProvider.configure { key: 'AIzaSyBQMyvtbd56MQd_wYshtcKvht0rNMbJXEg' libraries: 'weather,geometry,visualization' } ]
205035
angular.module 'bees-near-me', [ 'angular-meteor', 'ngRoute', 'accounts.ui', 'uiGmapgoogle-maps' ] angular.module('bees-near-me').config ['$routeProvider', 'uiGmapGoogleMapApiProvider', ($routeProvider, mapsProvider) -> $routeProvider.when '/', { templateUrl: 'client/landing/landing.html' controller: 'LandingPageController' } $routeProvider.when '/register_keeper', { templateUrl: 'client/landing/register_keeper.html' controller: 'SigninController' controllerAs: "signin" } $routeProvider.when '/register_swarm', { templateUrl: 'client/landing/register_swarm.html' controller: 'RegistrationController' controllerAs: "registrar" } $routeProvider.when '/map', { templateUrl: 'client/map/map.html' controller: 'MapController' controllerAs: "map" } $routeProvider.when '/swarms/:swarm_id', { templateUrl: 'client/landing/register_swarm.html' controller: 'RegistrationController' controllerAs: "registrar" } mapsProvider.configure { key: '<KEY>' libraries: 'weather,geometry,visualization' } ]
true
angular.module 'bees-near-me', [ 'angular-meteor', 'ngRoute', 'accounts.ui', 'uiGmapgoogle-maps' ] angular.module('bees-near-me').config ['$routeProvider', 'uiGmapGoogleMapApiProvider', ($routeProvider, mapsProvider) -> $routeProvider.when '/', { templateUrl: 'client/landing/landing.html' controller: 'LandingPageController' } $routeProvider.when '/register_keeper', { templateUrl: 'client/landing/register_keeper.html' controller: 'SigninController' controllerAs: "signin" } $routeProvider.when '/register_swarm', { templateUrl: 'client/landing/register_swarm.html' controller: 'RegistrationController' controllerAs: "registrar" } $routeProvider.when '/map', { templateUrl: 'client/map/map.html' controller: 'MapController' controllerAs: "map" } $routeProvider.when '/swarms/:swarm_id', { templateUrl: 'client/landing/register_swarm.html' controller: 'RegistrationController' controllerAs: "registrar" } mapsProvider.configure { key: 'PI:KEY:<KEY>END_PI' libraries: 'weather,geometry,visualization' } ]
[ { "context": "(event, tmpl) ->\n Curves.insert {\n name: 'New curve'\n chartId: @_id\n }, App.handleError", "end": 668, "score": 0.8301689028739929, "start": 665, "tag": "NAME", "value": "New" } ]
client/templates/chart-editor/curves/curves.coffee
JSSolutions/Dataforce
2
Template.Curves.onCreated -> #stores faded in curves and prevents self collapsing after collection update @collapsedCurves = new Mongo.Collection null #it used in curve-type-chooser and in curve editor itself @curveTypes = [ {caption: 'Line', type: 'line', icon: 'fa-line-chart'} {caption: 'Column', type: 'column', icon: 'fa-bar-chart'} {caption: 'Area', type: 'area', icon: 'fa-area-chart'} {caption: 'Pie', type: 'pie', icon: 'fa-pie-chart'} ] Template.Curves.helpers curves: -> Curves.find {chartId: @_id}, sort: {createdAt: 1} Template.Curves.events 'click .new-curve-button': (event, tmpl) -> Curves.insert { name: 'New curve' chartId: @_id }, App.handleError (id) -> tmpl.collapsedCurves.insert {curveId: id}
108564
Template.Curves.onCreated -> #stores faded in curves and prevents self collapsing after collection update @collapsedCurves = new Mongo.Collection null #it used in curve-type-chooser and in curve editor itself @curveTypes = [ {caption: 'Line', type: 'line', icon: 'fa-line-chart'} {caption: 'Column', type: 'column', icon: 'fa-bar-chart'} {caption: 'Area', type: 'area', icon: 'fa-area-chart'} {caption: 'Pie', type: 'pie', icon: 'fa-pie-chart'} ] Template.Curves.helpers curves: -> Curves.find {chartId: @_id}, sort: {createdAt: 1} Template.Curves.events 'click .new-curve-button': (event, tmpl) -> Curves.insert { name: '<NAME> curve' chartId: @_id }, App.handleError (id) -> tmpl.collapsedCurves.insert {curveId: id}
true
Template.Curves.onCreated -> #stores faded in curves and prevents self collapsing after collection update @collapsedCurves = new Mongo.Collection null #it used in curve-type-chooser and in curve editor itself @curveTypes = [ {caption: 'Line', type: 'line', icon: 'fa-line-chart'} {caption: 'Column', type: 'column', icon: 'fa-bar-chart'} {caption: 'Area', type: 'area', icon: 'fa-area-chart'} {caption: 'Pie', type: 'pie', icon: 'fa-pie-chart'} ] Template.Curves.helpers curves: -> Curves.find {chartId: @_id}, sort: {createdAt: 1} Template.Curves.events 'click .new-curve-button': (event, tmpl) -> Curves.insert { name: 'PI:NAME:<NAME>END_PI curve' chartId: @_id }, App.handleError (id) -> tmpl.collapsedCurves.insert {curveId: id}
[ { "context": "eScript\n\nThe MIT License (MIT)\n\nCopyright (c) 2015 Muyiwa Olurin (Anthony)\n\nPermission is hereby granted, free of ", "end": 82, "score": 0.9998787641525269, "start": 69, "tag": "NAME", "value": "Muyiwa Olurin" }, { "context": " License (MIT)\n\nCopyright (c) 2015 ...
heatmap.coffee
muyiwaolurin/heatmap-table
11
###* HeatMap CoffeeScript The MIT License (MIT) Copyright (c) 2015 Muyiwa Olurin (Anthony) 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. Ref [1] http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb ### 'use strict'; _componentToHex = (color) -> hex = color.toString(16) (if hex.length is 1 then '0' + hex else hex) _rgbtoHex = (r, g, b) -> '#' + _componentToHex(r) + _componentToHex(g) + _componentToHex(b) #Get Maximum and Minimum value out of an array #http://ejohn.org/blog/fast-javascript-maxmin/ _max = (array) -> Math.max.apply Math, array _min = (array) -> Math.min.apply Math, array _average = (array) -> summation = 0 i = 0 while i < array.length summation += parseFloat(array[i]) # base 10 i++ average = summation / array.length Math.round average _sort = (array) -> array.sort() _mode = (array) -> counter = {} mode = [] max = 0 array = array.sort() array[Math.round(array.length / 2)] #Color Scheme Function # This function should select the right color scheme from the dropdown widget. _colorScheme = (scheme) -> firstColor = undefined secondColor = undefined thirdColor = undefined firstColor = [] secondColor = [] thirdColor = [] switch scheme when 'GYR' firstColor = [ 243, 81, 88 ] secondColor = [ 254, 233, 144 ] thirdColor = [ 84, 180, 104 ] when 'RYG' firstColor = [ 84, 180, 104 ] secondColor = [ 254, 233, 144 ] thirdColor = [ 243, 81, 88 ] when 'GWR' firstColor = [ 243, 81, 88 ] secondColor = [ 256, 256, 256 ] thirdColor = [ 84, 180, 104 ] else firstColor = [ 243, 81, 88 ] secondColor = [ 254, 233, 144 ] thirdColor = [ 84, 180, 104 ] firstColor: firstColor secondColor: secondColor thirdColor: thirdColor @ColorScale = (tablename, classname) -> scheme = '' changeSelect = $('select#color-scale-select') changeSelect.change () -> scheme = $('#color-scale-select option:selected').val() _heatmap(tablename, classname, scheme) return true ## Call HEATMAP _heatmap(tablename, classname, scheme) _heatmap = (tablename, classname, scheme) -> console.log 'HeatMap Started ... ' piaArray = $('table#'+tablename+' tbody td.' + classname).map(-> parseFloat $(this).text() ).get() max = _max(piaArray) ave = _average(piaArray) min = _min(piaArray) mod = _mode(piaArray) getColorScheme = _colorScheme(scheme) ## X-'s' xr = getColorScheme.firstColor[0] xg = getColorScheme.firstColor[1] xb = getColorScheme.firstColor[2] ## A-'s' ar = getColorScheme.secondColor[0] ag = getColorScheme.secondColor[1] ab = getColorScheme.secondColor[2] ## Y-'s' yr = getColorScheme.thirdColor[0] yg = getColorScheme.thirdColor[1] yb = getColorScheme.thirdColor[2] n = 100 $('table#'+tablename+' tbody td.' + classname).each -> value = parseFloat($(this).text()) if value < mod pos = parseInt((Math.round(((value - min) / (mod - min)) * 100)).toFixed(0)) red = parseInt((xr + ((pos * (ar - xr)) / (n - 1))).toFixed(0)) green = parseInt((xg + ((pos * (ag - xg)) / (n - 1))).toFixed(0)) blue = parseInt((xb + ((pos * (ab - xb)) / (n - 1))).toFixed(0)) clr = _rgbtoHex(red, green, blue) $(this).css backgroundColor: clr if value is mod red = ar green = ag blue = ab clr = _rgbtoHex(red, green, blue) $(this).css backgroundColor: clr if value > mod pos = parseInt((Math.round(((value - mod) / (max - mod)) * 100)).toFixed(0)) red = parseInt((ar + ((pos * (yr - ar)) / (n - 1))).toFixed(0)) green = parseInt((ag + ((pos * (yg - ag)) / (n - 1))).toFixed(0)) blue = parseInt((ab + ((pos * (yb - ab)) / (n - 1))).toFixed(0)) clr = _rgbtoHex(red, green, blue) $(this).css backgroundColor: clr return
76651
###* HeatMap CoffeeScript The MIT License (MIT) Copyright (c) 2015 <NAME> (<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. Ref [1] http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb ### 'use strict'; _componentToHex = (color) -> hex = color.toString(16) (if hex.length is 1 then '0' + hex else hex) _rgbtoHex = (r, g, b) -> '#' + _componentToHex(r) + _componentToHex(g) + _componentToHex(b) #Get Maximum and Minimum value out of an array #http://ejohn.org/blog/fast-javascript-maxmin/ _max = (array) -> Math.max.apply Math, array _min = (array) -> Math.min.apply Math, array _average = (array) -> summation = 0 i = 0 while i < array.length summation += parseFloat(array[i]) # base 10 i++ average = summation / array.length Math.round average _sort = (array) -> array.sort() _mode = (array) -> counter = {} mode = [] max = 0 array = array.sort() array[Math.round(array.length / 2)] #Color Scheme Function # This function should select the right color scheme from the dropdown widget. _colorScheme = (scheme) -> firstColor = undefined secondColor = undefined thirdColor = undefined firstColor = [] secondColor = [] thirdColor = [] switch scheme when 'GYR' firstColor = [ 243, 81, 88 ] secondColor = [ 254, 233, 144 ] thirdColor = [ 84, 180, 104 ] when 'RYG' firstColor = [ 84, 180, 104 ] secondColor = [ 254, 233, 144 ] thirdColor = [ 243, 81, 88 ] when 'GWR' firstColor = [ 243, 81, 88 ] secondColor = [ 256, 256, 256 ] thirdColor = [ 84, 180, 104 ] else firstColor = [ 243, 81, 88 ] secondColor = [ 254, 233, 144 ] thirdColor = [ 84, 180, 104 ] firstColor: firstColor secondColor: secondColor thirdColor: thirdColor @ColorScale = (tablename, classname) -> scheme = '' changeSelect = $('select#color-scale-select') changeSelect.change () -> scheme = $('#color-scale-select option:selected').val() _heatmap(tablename, classname, scheme) return true ## Call HEATMAP _heatmap(tablename, classname, scheme) _heatmap = (tablename, classname, scheme) -> console.log 'HeatMap Started ... ' piaArray = $('table#'+tablename+' tbody td.' + classname).map(-> parseFloat $(this).text() ).get() max = _max(piaArray) ave = _average(piaArray) min = _min(piaArray) mod = _mode(piaArray) getColorScheme = _colorScheme(scheme) ## X-'s' xr = getColorScheme.firstColor[0] xg = getColorScheme.firstColor[1] xb = getColorScheme.firstColor[2] ## A-'s' ar = getColorScheme.secondColor[0] ag = getColorScheme.secondColor[1] ab = getColorScheme.secondColor[2] ## Y-'s' yr = getColorScheme.thirdColor[0] yg = getColorScheme.thirdColor[1] yb = getColorScheme.thirdColor[2] n = 100 $('table#'+tablename+' tbody td.' + classname).each -> value = parseFloat($(this).text()) if value < mod pos = parseInt((Math.round(((value - min) / (mod - min)) * 100)).toFixed(0)) red = parseInt((xr + ((pos * (ar - xr)) / (n - 1))).toFixed(0)) green = parseInt((xg + ((pos * (ag - xg)) / (n - 1))).toFixed(0)) blue = parseInt((xb + ((pos * (ab - xb)) / (n - 1))).toFixed(0)) clr = _rgbtoHex(red, green, blue) $(this).css backgroundColor: clr if value is mod red = ar green = ag blue = ab clr = _rgbtoHex(red, green, blue) $(this).css backgroundColor: clr if value > mod pos = parseInt((Math.round(((value - mod) / (max - mod)) * 100)).toFixed(0)) red = parseInt((ar + ((pos * (yr - ar)) / (n - 1))).toFixed(0)) green = parseInt((ag + ((pos * (yg - ag)) / (n - 1))).toFixed(0)) blue = parseInt((ab + ((pos * (yb - ab)) / (n - 1))).toFixed(0)) clr = _rgbtoHex(red, green, blue) $(this).css backgroundColor: clr return
true
###* HeatMap CoffeeScript The MIT License (MIT) Copyright (c) 2015 PI:NAME:<NAME>END_PI (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. Ref [1] http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb ### 'use strict'; _componentToHex = (color) -> hex = color.toString(16) (if hex.length is 1 then '0' + hex else hex) _rgbtoHex = (r, g, b) -> '#' + _componentToHex(r) + _componentToHex(g) + _componentToHex(b) #Get Maximum and Minimum value out of an array #http://ejohn.org/blog/fast-javascript-maxmin/ _max = (array) -> Math.max.apply Math, array _min = (array) -> Math.min.apply Math, array _average = (array) -> summation = 0 i = 0 while i < array.length summation += parseFloat(array[i]) # base 10 i++ average = summation / array.length Math.round average _sort = (array) -> array.sort() _mode = (array) -> counter = {} mode = [] max = 0 array = array.sort() array[Math.round(array.length / 2)] #Color Scheme Function # This function should select the right color scheme from the dropdown widget. _colorScheme = (scheme) -> firstColor = undefined secondColor = undefined thirdColor = undefined firstColor = [] secondColor = [] thirdColor = [] switch scheme when 'GYR' firstColor = [ 243, 81, 88 ] secondColor = [ 254, 233, 144 ] thirdColor = [ 84, 180, 104 ] when 'RYG' firstColor = [ 84, 180, 104 ] secondColor = [ 254, 233, 144 ] thirdColor = [ 243, 81, 88 ] when 'GWR' firstColor = [ 243, 81, 88 ] secondColor = [ 256, 256, 256 ] thirdColor = [ 84, 180, 104 ] else firstColor = [ 243, 81, 88 ] secondColor = [ 254, 233, 144 ] thirdColor = [ 84, 180, 104 ] firstColor: firstColor secondColor: secondColor thirdColor: thirdColor @ColorScale = (tablename, classname) -> scheme = '' changeSelect = $('select#color-scale-select') changeSelect.change () -> scheme = $('#color-scale-select option:selected').val() _heatmap(tablename, classname, scheme) return true ## Call HEATMAP _heatmap(tablename, classname, scheme) _heatmap = (tablename, classname, scheme) -> console.log 'HeatMap Started ... ' piaArray = $('table#'+tablename+' tbody td.' + classname).map(-> parseFloat $(this).text() ).get() max = _max(piaArray) ave = _average(piaArray) min = _min(piaArray) mod = _mode(piaArray) getColorScheme = _colorScheme(scheme) ## X-'s' xr = getColorScheme.firstColor[0] xg = getColorScheme.firstColor[1] xb = getColorScheme.firstColor[2] ## A-'s' ar = getColorScheme.secondColor[0] ag = getColorScheme.secondColor[1] ab = getColorScheme.secondColor[2] ## Y-'s' yr = getColorScheme.thirdColor[0] yg = getColorScheme.thirdColor[1] yb = getColorScheme.thirdColor[2] n = 100 $('table#'+tablename+' tbody td.' + classname).each -> value = parseFloat($(this).text()) if value < mod pos = parseInt((Math.round(((value - min) / (mod - min)) * 100)).toFixed(0)) red = parseInt((xr + ((pos * (ar - xr)) / (n - 1))).toFixed(0)) green = parseInt((xg + ((pos * (ag - xg)) / (n - 1))).toFixed(0)) blue = parseInt((xb + ((pos * (ab - xb)) / (n - 1))).toFixed(0)) clr = _rgbtoHex(red, green, blue) $(this).css backgroundColor: clr if value is mod red = ar green = ag blue = ab clr = _rgbtoHex(red, green, blue) $(this).css backgroundColor: clr if value > mod pos = parseInt((Math.round(((value - mod) / (max - mod)) * 100)).toFixed(0)) red = parseInt((ar + ((pos * (yr - ar)) / (n - 1))).toFixed(0)) green = parseInt((ag + ((pos * (yg - ag)) / (n - 1))).toFixed(0)) blue = parseInt((ab + ((pos * (yb - ab)) / (n - 1))).toFixed(0)) clr = _rgbtoHex(red, green, blue) $(this).css backgroundColor: clr return
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9986198544502258, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "s = []\n @handle = null\n @errno = 0\n \n # FIXME(bnoordhuis) Polymorphic return type for ...
lib/cluster.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. Worker = (options) -> return new Worker(options) unless this instanceof Worker EventEmitter.call this options = {} unless util.isObject(options) @suicide = `undefined` @state = options.state or "none" @id = options.id | 0 if options.process @process = options.process @process.on "error", @emit.bind(this, "error") @process.on "message", @emit.bind(this, "message") return # Master/worker specific methods are defined in the *Init() functions. SharedHandle = (key, address, port, addressType, backlog, fd) -> @key = key @workers = [] @handle = null @errno = 0 # FIXME(bnoordhuis) Polymorphic return type for lack of a better solution. rval = undefined if addressType is "udp4" or addressType is "udp6" rval = dgram._createSocketHandle(address, port, addressType, fd) else rval = net._createServerHandle(address, port, addressType, fd) if util.isNumber(rval) @errno = rval else @handle = rval return # Start a round-robin server. Master accepts connections and distributes # them over the workers. RoundRobinHandle = (key, address, port, addressType, backlog, fd) -> @key = key @all = {} @free = [] @handles = [] @handle = null @server = net.createServer(assert.fail) if fd >= 0 @server.listen fd: fd else if port >= 0 @server.listen port, address else # UNIX socket path. @server.listen address self = this @server.once "listening", -> self.handle = self.server._handle self.handle.onconnection = self.distribute.bind(self) self.server._handle = null self.server = null return return # TODO(bnoordhuis) Check err. # UNIX socket. # In case there are connections pending. # Still busy binding. # Hack: translate 'EADDRINUSE' error string back to numeric error code. # It works but ideally we'd have some backchannel between the net and # cluster modules for stuff like this. # Worker is closing (or has closed) the server. # Add to ready queue again. # Worker is shutting down. Send to another. masterInit = -> # XXX(bnoordhuis) Fold cluster.schedulingPolicy into cluster.settings? # FIXME Round-robin doesn't perform well on Windows right now due to the # way IOCP is wired up. Bert is going to fix that, eventually. # Leave it to the operating system. # Master distributes connections. # Keyed on address:port:etc. When a worker dies, we walk over the handles # and remove() the worker from each one. remove() may do a linear scan # itself so we might end up with an O(n*m) operation. Ergo, FIXME. # Tell V8 to write profile data for each process to a separate file. # Without --logfile=v8-%p.log, everything ends up in a single, unusable # file. (Unusable because what V8 logs are memory addresses and each # process has its own memory mappings.) # Freeze policy. # Send debug signal only if not started in debug mode, this helps a lot # on windows, because RegisterDebugHandler is not called when node starts # with --debug.* arg. createWorkerProcess = (id, env) -> workerEnv = util._extend({}, process.env) execArgv = cluster.settings.execArgv.slice() debugPort = process.debugPort + id hasDebugArg = false workerEnv = util._extend(workerEnv, env) workerEnv.NODE_UNIQUE_ID = "" + id i = 0 while i < execArgv.length match = execArgv[i].match(/^(--debug|--debug-brk)(=\d+)?$/) if match execArgv[i] = match[1] + "=" + debugPort hasDebugArg = true i++ execArgv = ["--debug-port=" + debugPort].concat(execArgv) unless hasDebugArg fork cluster.settings.exec, cluster.settings.args, env: workerEnv silent: cluster.settings.silent execArgv: execArgv gid: cluster.settings.gid uid: cluster.settings.uid # # * Remove the worker from the workers list only # * if it has disconnected, otherwise we might # * still want to access it. # # # * Now is a good time to remove the handles # * associated with this worker because it is # * not connected to the master anymore. # # # * Remove the worker from the workers list only # * if its process has exited. Otherwise, we might # * still want to access it. # onmessage = (message, handle) -> worker = this if message.act is "online" online worker else if message.act is "queryServer" queryServer worker, message else if message.act is "listening" listening worker, message else if message.act is "suicide" worker.suicide = true else close worker, message if message.act is "close" return online = (worker) -> worker.state = "online" worker.emit "online" cluster.emit "online", worker return queryServer = (worker, message) -> args = [ message.address message.port message.addressType message.fd ] key = args.join(":") handle = handles[key] if util.isUndefined(handle) constructor = RoundRobinHandle # UDP is exempt from round-robin connection balancing for what should # be obvious reasons: it's connectionless. There is nothing to send to # the workers except raw datagrams and that's pointless. constructor = SharedHandle if schedulingPolicy isnt SCHED_RR or message.addressType is "udp4" or message.addressType is "udp6" handles[key] = handle = new constructor(key, message.address, message.port, message.addressType, message.backlog, message.fd) handle.data = message.data unless handle.data # Set custom server data handle.add worker, (errno, reply, handle) -> reply = util._extend( errno: errno key: key ack: message.seq data: handles[key].data , reply) delete handles[key] if errno # Gives other workers a chance to retry. send worker, reply, handle return return listening = (worker, message) -> info = addressType: message.addressType address: message.address port: message.port fd: message.fd worker.state = "listening" worker.emit "listening", info cluster.emit "listening", worker, info return # Round-robin only. Server in worker is closing, remove from list. close = (worker, message) -> key = message.key handle = handles[key] delete handles[key] if handle.remove(worker) return send = (worker, message, handle, cb) -> sendHelper worker.process, message, handle, cb return cluster.workers = {} intercom = new EventEmitter cluster.settings = {} schedulingPolicy = none: SCHED_NONE rr: SCHED_RR [{process.env.NODE_CLUSTER_SCHED_POLICY}] schedulingPolicy = (if (process.platform is "win32") then SCHED_NONE else SCHED_RR) if util.isUndefined(schedulingPolicy) cluster.schedulingPolicy = schedulingPolicy cluster.SCHED_NONE = SCHED_NONE cluster.SCHED_RR = SCHED_RR handles = {} initialized = false cluster.setupMaster = (options) -> settings = args: process.argv.slice(2) exec: process.argv[1] execArgv: process.execArgv silent: false settings = util._extend(settings, cluster.settings) settings = util._extend(settings, options or {}) settings.execArgv = settings.execArgv.concat(["--logfile=v8-%p.log"]) if settings.execArgv.some((s) -> /^--prof/.test s ) and not settings.execArgv.some((s) -> /^--logfile=/.test s ) cluster.settings = settings if initialized is true return process.nextTick(-> cluster.emit "setup", settings return ) initialized = true schedulingPolicy = cluster.schedulingPolicy assert schedulingPolicy is SCHED_NONE or schedulingPolicy is SCHED_RR, "Bad cluster.schedulingPolicy: " + schedulingPolicy hasDebugArg = process.execArgv.some((argv) -> /^(--debug|--debug-brk)(=\d+)?$/.test argv ) process.nextTick -> cluster.emit "setup", settings return return if hasDebugArg process.on "internalMessage", (message) -> return if message.cmd isnt "NODE_DEBUG_ENABLED" key = undefined for key of cluster.workers worker = cluster.workers[key] if worker.state is "online" process._debugProcess worker.process.pid else worker.once "online", -> process._debugProcess @process.pid return return return ids = 0 cluster.fork = (env) -> removeWorker = (worker) -> assert worker delete cluster.workers[worker.id] if Object.keys(cluster.workers).length is 0 assert Object.keys(handles).length is 0, "Resource leak detected." intercom.emit "disconnect" return removeHandlesForWorker = (worker) -> assert worker for key of handles handle = handles[key] delete handles[key] if handle.remove(worker) return cluster.setupMaster() id = ++ids workerProcess = createWorkerProcess(id, env) worker = new Worker( id: id process: workerProcess ) worker.process.once "exit", (exitCode, signalCode) -> removeWorker worker unless worker.isConnected() worker.suicide = !!worker.suicide worker.state = "dead" worker.emit "exit", exitCode, signalCode cluster.emit "exit", worker, exitCode, signalCode return worker.process.once "disconnect", -> removeHandlesForWorker worker removeWorker worker if worker.isDead() worker.suicide = !!worker.suicide worker.state = "disconnected" worker.emit "disconnect" cluster.emit "disconnect", worker return worker.process.on "internalMessage", internal(worker, onmessage) process.nextTick -> cluster.emit "fork", worker return cluster.workers[worker.id] = worker worker cluster.disconnect = (cb) -> workers = Object.keys(cluster.workers) if workers.length is 0 process.nextTick intercom.emit.bind(intercom, "disconnect") else for key of workers key = workers[key] cluster.workers[key].disconnect() intercom.once "disconnect", cb if cb return Worker::disconnect = -> @suicide = true send this, act: "disconnect" return Worker::destroy = (signo) -> signo = signo or "SIGTERM" proc = @process if @isConnected() @once "disconnect", proc.kill.bind(proc, signo) @disconnect() return proc.kill signo return return workerInit = -> # Called from src/node.js # Unexpected disconnect, master exited, or some such nastiness, so # worker exits immediately. # obj is a net#Server or a dgram#Socket object. # Set custom data on handle (i.e. tls tickets key) # Shared listen socket. # Round-robin. # Shared listen socket. shared = (message, handle, cb) -> key = message.key # Monkey-patch the close() method so we can keep track of when it's # closed. Avoids resource leaks when the handle is short-lived. close = handle.close handle.close = -> delete handles[key] close.apply this, arguments assert util.isUndefined(handles[key]) handles[key] = handle cb message.errno, handle return # Round-robin. Master distributes handles across workers. rr = (message, cb) -> listen = (backlog) -> # TODO(bnoordhuis) Send a message to the master that tells it to # update the backlog size. The actual backlog should probably be # the largest requested size by any worker. 0 close = -> # lib/net.js treats server._handle.close() as effectively synchronous. # That means there is a time window between the call to close() and # the ack by the master process in which we can still receive handles. # onconnection() below handles that by sending those handles back to # the master. return if util.isUndefined(key) send act: "close" key: key delete handles[key] key = `undefined` return getsockname = (out) -> util._extend out, message.sockname if key 0 return cb(message.errno, null) if message.errno key = message.key # Faux handle. Mimics a TCPWrap with just enough fidelity to get away # with it. Fools net.Server into thinking that it's backed by a real # handle. handle = close: close listen: listen handle.getsockname = getsockname if message.sockname # TCP handles only. assert util.isUndefined(handles[key]) handles[key] = handle cb 0, handle return # Round-robin connection. onconnection = (message, handle) -> key = message.key server = handles[key] accepted = not util.isUndefined(server) send ack: message.seq accepted: accepted server.onconnection 0, handle if accepted return send = (message, cb) -> sendHelper process, message, null, cb return handles = {} cluster._setupWorker = -> onmessage = (message, handle) -> if message.act is "newconn" onconnection message, handle else worker.disconnect() if message.act is "disconnect" return worker = new Worker( id: +process.env.NODE_UNIQUE_ID | 0 process: process state: "online" ) cluster.worker = worker process.once "disconnect", -> process.exit 0 unless worker.suicide return process.on "internalMessage", internal(worker, onmessage) send act: "online" return cluster._getServer = (obj, address, port, addressType, fd, cb) -> message = addressType: addressType address: address port: port act: "queryServer" fd: fd data: null message.data = obj._getServerData() if obj._getServerData send message, (reply, handle) -> obj._setServerData reply.data if obj._setServerData if handle shared reply, handle, cb else rr reply, cb return obj.once "listening", -> cluster.worker.state = "listening" address = obj.address() message.act = "listening" message.port = address and address.port or port send message return return Worker::disconnect = -> @suicide = true for key of handles handle = handles[key] delete handles[key] handle.close() process.disconnect() return Worker::destroy = -> @suicide = true process.exit 0 unless @isConnected() exit = process.exit.bind(null, 0) send act: "suicide" , exit process.once "disconnect", exit process.disconnect() return return sendHelper = (proc, message, handle, cb) -> # Mark message as internal. See INTERNAL_PREFIX in lib/child_process.js message = util._extend( cmd: "NODE_CLUSTER" , message) callbacks[seq] = cb if cb message.seq = seq seq += 1 proc.send message, handle return # Returns an internalMessage listener that hands off normal messages # to the callback but intercepts and redirects ACK messages. internal = (worker, cb) -> (message, handle) -> return if message.cmd isnt "NODE_CLUSTER" fn = cb unless util.isUndefined(message.ack) fn = callbacks[message.ack] delete callbacks[message.ack] fn.apply worker, arguments return "use strict" EventEmitter = require("events").EventEmitter assert = require("assert") dgram = require("dgram") fork = require("child_process").fork net = require("net") util = require("util") SCHED_NONE = 1 SCHED_RR = 2 cluster = new EventEmitter module.exports = cluster cluster.Worker = Worker cluster.isWorker = ("NODE_UNIQUE_ID" of process.env) cluster.isMaster = (cluster.isWorker is false) util.inherits Worker, EventEmitter Worker::kill = -> @destroy.apply this, arguments return Worker::send = -> @process.send.apply @process, arguments return Worker::isDead = isDead = -> @process.exitCode? or @process.signalCode? Worker::isConnected = isConnected = -> @process.connected SharedHandle::add = (worker, send) -> assert @workers.indexOf(worker) is -1 @workers.push worker send @errno, null, @handle return SharedHandle::remove = (worker) -> index = @workers.indexOf(worker) assert index isnt -1 @workers.splice index, 1 return false if @workers.length isnt 0 @handle.close() @handle = null true RoundRobinHandle::add = (worker, send) -> done = -> if self.handle.getsockname out = {} err = self.handle.getsockname(out) send null, sockname: out , null else send null, null, null self.handoff worker return assert worker.id of @all is false @all[worker.id] = worker self = this return done() if util.isNull(@server) @server.once "listening", done @server.once "error", (err) -> errno = process.binding("uv")["UV_" + err.errno] send errno, null return return RoundRobinHandle::remove = (worker) -> return false if worker.id of @all is false delete @all[worker.id] index = @free.indexOf(worker) @free.splice index, 1 if index isnt -1 return false if Object.getOwnPropertyNames(@all).length isnt 0 handle = undefined while handle = @handles.shift() handle.close() @handle.close() @handle = null true RoundRobinHandle::distribute = (err, handle) -> @handles.push handle worker = @free.shift() @handoff worker if worker return RoundRobinHandle::handoff = (worker) -> return if worker.id of @all is false handle = @handles.shift() if util.isUndefined(handle) @free.push worker return message = act: "newconn" key: @key self = this sendHelper worker.process, message, handle, (reply) -> if reply.accepted handle.close() else self.distribute 0, handle self.handoff worker return return if cluster.isMaster masterInit() else workerInit() seq = 0 callbacks = {}
185112
# 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. Worker = (options) -> return new Worker(options) unless this instanceof Worker EventEmitter.call this options = {} unless util.isObject(options) @suicide = `undefined` @state = options.state or "none" @id = options.id | 0 if options.process @process = options.process @process.on "error", @emit.bind(this, "error") @process.on "message", @emit.bind(this, "message") return # Master/worker specific methods are defined in the *Init() functions. SharedHandle = (key, address, port, addressType, backlog, fd) -> @key = key @workers = [] @handle = null @errno = 0 # FIXME(bnoordhuis) Polymorphic return type for lack of a better solution. rval = undefined if addressType is "udp4" or addressType is "udp6" rval = dgram._createSocketHandle(address, port, addressType, fd) else rval = net._createServerHandle(address, port, addressType, fd) if util.isNumber(rval) @errno = rval else @handle = rval return # Start a round-robin server. Master accepts connections and distributes # them over the workers. RoundRobinHandle = (key, address, port, addressType, backlog, fd) -> @key = key @all = {} @free = [] @handles = [] @handle = null @server = net.createServer(assert.fail) if fd >= 0 @server.listen fd: fd else if port >= 0 @server.listen port, address else # UNIX socket path. @server.listen address self = this @server.once "listening", -> self.handle = self.server._handle self.handle.onconnection = self.distribute.bind(self) self.server._handle = null self.server = null return return # TODO(bnoordhuis) Check err. # UNIX socket. # In case there are connections pending. # Still busy binding. # Hack: translate 'EADDRINUSE' error string back to numeric error code. # It works but ideally we'd have some backchannel between the net and # cluster modules for stuff like this. # Worker is closing (or has closed) the server. # Add to ready queue again. # Worker is shutting down. Send to another. masterInit = -> # XXX(bnoordhuis) Fold cluster.schedulingPolicy into cluster.settings? # FIXME Round-robin doesn't perform well on Windows right now due to the # way IOCP is wired up. Bert is going to fix that, eventually. # Leave it to the operating system. # Master distributes connections. # Keyed on address:port:etc. When a worker dies, we walk over the handles # and remove() the worker from each one. remove() may do a linear scan # itself so we might end up with an O(n*m) operation. Ergo, FIXME. # Tell V8 to write profile data for each process to a separate file. # Without --logfile=v8-%p.log, everything ends up in a single, unusable # file. (Unusable because what V8 logs are memory addresses and each # process has its own memory mappings.) # Freeze policy. # Send debug signal only if not started in debug mode, this helps a lot # on windows, because RegisterDebugHandler is not called when node starts # with --debug.* arg. createWorkerProcess = (id, env) -> workerEnv = util._extend({}, process.env) execArgv = cluster.settings.execArgv.slice() debugPort = process.debugPort + id hasDebugArg = false workerEnv = util._extend(workerEnv, env) workerEnv.NODE_UNIQUE_ID = "" + id i = 0 while i < execArgv.length match = execArgv[i].match(/^(--debug|--debug-brk)(=\d+)?$/) if match execArgv[i] = match[1] + "=" + debugPort hasDebugArg = true i++ execArgv = ["--debug-port=" + debugPort].concat(execArgv) unless hasDebugArg fork cluster.settings.exec, cluster.settings.args, env: workerEnv silent: cluster.settings.silent execArgv: execArgv gid: cluster.settings.gid uid: cluster.settings.uid # # * Remove the worker from the workers list only # * if it has disconnected, otherwise we might # * still want to access it. # # # * Now is a good time to remove the handles # * associated with this worker because it is # * not connected to the master anymore. # # # * Remove the worker from the workers list only # * if its process has exited. Otherwise, we might # * still want to access it. # onmessage = (message, handle) -> worker = this if message.act is "online" online worker else if message.act is "queryServer" queryServer worker, message else if message.act is "listening" listening worker, message else if message.act is "suicide" worker.suicide = true else close worker, message if message.act is "close" return online = (worker) -> worker.state = "online" worker.emit "online" cluster.emit "online", worker return queryServer = (worker, message) -> args = [ message.address message.port message.addressType message.fd ] key = args.join(":") handle = handles[key] if util.isUndefined(handle) constructor = RoundRobinHandle # UDP is exempt from round-robin connection balancing for what should # be obvious reasons: it's connectionless. There is nothing to send to # the workers except raw datagrams and that's pointless. constructor = SharedHandle if schedulingPolicy isnt SCHED_RR or message.addressType is "udp4" or message.addressType is "udp6" handles[key] = handle = new constructor(key, message.address, message.port, message.addressType, message.backlog, message.fd) handle.data = message.data unless handle.data # Set custom server data handle.add worker, (errno, reply, handle) -> reply = util._extend( errno: errno key: key ack: message.seq data: handles[key].data , reply) delete handles[key] if errno # Gives other workers a chance to retry. send worker, reply, handle return return listening = (worker, message) -> info = addressType: message.addressType address: message.address port: message.port fd: message.fd worker.state = "listening" worker.emit "listening", info cluster.emit "listening", worker, info return # Round-robin only. Server in worker is closing, remove from list. close = (worker, message) -> key = message.key handle = handles[key] delete handles[key] if handle.remove(worker) return send = (worker, message, handle, cb) -> sendHelper worker.process, message, handle, cb return cluster.workers = {} intercom = new EventEmitter cluster.settings = {} schedulingPolicy = none: SCHED_NONE rr: SCHED_RR [{process.env.NODE_CLUSTER_SCHED_POLICY}] schedulingPolicy = (if (process.platform is "win32") then SCHED_NONE else SCHED_RR) if util.isUndefined(schedulingPolicy) cluster.schedulingPolicy = schedulingPolicy cluster.SCHED_NONE = SCHED_NONE cluster.SCHED_RR = SCHED_RR handles = {} initialized = false cluster.setupMaster = (options) -> settings = args: process.argv.slice(2) exec: process.argv[1] execArgv: process.execArgv silent: false settings = util._extend(settings, cluster.settings) settings = util._extend(settings, options or {}) settings.execArgv = settings.execArgv.concat(["--logfile=v8-%p.log"]) if settings.execArgv.some((s) -> /^--prof/.test s ) and not settings.execArgv.some((s) -> /^--logfile=/.test s ) cluster.settings = settings if initialized is true return process.nextTick(-> cluster.emit "setup", settings return ) initialized = true schedulingPolicy = cluster.schedulingPolicy assert schedulingPolicy is SCHED_NONE or schedulingPolicy is SCHED_RR, "Bad cluster.schedulingPolicy: " + schedulingPolicy hasDebugArg = process.execArgv.some((argv) -> /^(--debug|--debug-brk)(=\d+)?$/.test argv ) process.nextTick -> cluster.emit "setup", settings return return if hasDebugArg process.on "internalMessage", (message) -> return if message.cmd isnt "NODE_DEBUG_ENABLED" key = undefined for key of cluster.workers worker = cluster.workers[key] if worker.state is "online" process._debugProcess worker.process.pid else worker.once "online", -> process._debugProcess @process.pid return return return ids = 0 cluster.fork = (env) -> removeWorker = (worker) -> assert worker delete cluster.workers[worker.id] if Object.keys(cluster.workers).length is 0 assert Object.keys(handles).length is 0, "Resource leak detected." intercom.emit "disconnect" return removeHandlesForWorker = (worker) -> assert worker for key of handles handle = handles[key] delete handles[key] if handle.remove(worker) return cluster.setupMaster() id = ++ids workerProcess = createWorkerProcess(id, env) worker = new Worker( id: id process: workerProcess ) worker.process.once "exit", (exitCode, signalCode) -> removeWorker worker unless worker.isConnected() worker.suicide = !!worker.suicide worker.state = "dead" worker.emit "exit", exitCode, signalCode cluster.emit "exit", worker, exitCode, signalCode return worker.process.once "disconnect", -> removeHandlesForWorker worker removeWorker worker if worker.isDead() worker.suicide = !!worker.suicide worker.state = "disconnected" worker.emit "disconnect" cluster.emit "disconnect", worker return worker.process.on "internalMessage", internal(worker, onmessage) process.nextTick -> cluster.emit "fork", worker return cluster.workers[worker.id] = worker worker cluster.disconnect = (cb) -> workers = Object.keys(cluster.workers) if workers.length is 0 process.nextTick intercom.emit.bind(intercom, "disconnect") else for key of workers key = workers[key] cluster.workers[key].disconnect() intercom.once "disconnect", cb if cb return Worker::disconnect = -> @suicide = true send this, act: "disconnect" return Worker::destroy = (signo) -> signo = signo or "SIGTERM" proc = @process if @isConnected() @once "disconnect", proc.kill.bind(proc, signo) @disconnect() return proc.kill signo return return workerInit = -> # Called from src/node.js # Unexpected disconnect, master exited, or some such nastiness, so # worker exits immediately. # obj is a net#Server or a dgram#Socket object. # Set custom data on handle (i.e. tls tickets key) # Shared listen socket. # Round-robin. # Shared listen socket. shared = (message, handle, cb) -> key = message.key # Monkey-patch the close() method so we can keep track of when it's # closed. Avoids resource leaks when the handle is short-lived. close = handle.close handle.close = -> delete handles[key] close.apply this, arguments assert util.isUndefined(handles[key]) handles[key] = handle cb message.errno, handle return # Round-robin. Master distributes handles across workers. rr = (message, cb) -> listen = (backlog) -> # TODO(bnoordhuis) Send a message to the master that tells it to # update the backlog size. The actual backlog should probably be # the largest requested size by any worker. 0 close = -> # lib/net.js treats server._handle.close() as effectively synchronous. # That means there is a time window between the call to close() and # the ack by the master process in which we can still receive handles. # onconnection() below handles that by sending those handles back to # the master. return if util.isUndefined(key) send act: "close" key: key delete handles[key] key = `<KEY>` return getsockname = (out) -> util._extend out, message.sockname if key 0 return cb(message.errno, null) if message.errno key = message.key # Faux handle. Mimics a TCPWrap with just enough fidelity to get away # with it. Fools net.Server into thinking that it's backed by a real # handle. handle = close: close listen: listen handle.getsockname = getsockname if message.sockname # TCP handles only. assert util.isUndefined(handles[key]) handles[key] = handle cb 0, handle return # Round-robin connection. onconnection = (message, handle) -> key = <KEY>.key server = handles[key] accepted = not util.isUndefined(server) send ack: message.seq accepted: accepted server.onconnection 0, handle if accepted return send = (message, cb) -> sendHelper process, message, null, cb return handles = {} cluster._setupWorker = -> onmessage = (message, handle) -> if message.act is "newconn" onconnection message, handle else worker.disconnect() if message.act is "disconnect" return worker = new Worker( id: +process.env.NODE_UNIQUE_ID | 0 process: process state: "online" ) cluster.worker = worker process.once "disconnect", -> process.exit 0 unless worker.suicide return process.on "internalMessage", internal(worker, onmessage) send act: "online" return cluster._getServer = (obj, address, port, addressType, fd, cb) -> message = addressType: addressType address: address port: port act: "queryServer" fd: fd data: null message.data = obj._getServerData() if obj._getServerData send message, (reply, handle) -> obj._setServerData reply.data if obj._setServerData if handle shared reply, handle, cb else rr reply, cb return obj.once "listening", -> cluster.worker.state = "listening" address = obj.address() message.act = "listening" message.port = address and address.port or port send message return return Worker::disconnect = -> @suicide = true for key of handles handle = handles[key] delete handles[key] handle.close() process.disconnect() return Worker::destroy = -> @suicide = true process.exit 0 unless @isConnected() exit = process.exit.bind(null, 0) send act: "suicide" , exit process.once "disconnect", exit process.disconnect() return return sendHelper = (proc, message, handle, cb) -> # Mark message as internal. See INTERNAL_PREFIX in lib/child_process.js message = util._extend( cmd: "NODE_CLUSTER" , message) callbacks[seq] = cb if cb message.seq = seq seq += 1 proc.send message, handle return # Returns an internalMessage listener that hands off normal messages # to the callback but intercepts and redirects ACK messages. internal = (worker, cb) -> (message, handle) -> return if message.cmd isnt "NODE_CLUSTER" fn = cb unless util.isUndefined(message.ack) fn = callbacks[message.ack] delete callbacks[message.ack] fn.apply worker, arguments return "use strict" EventEmitter = require("events").EventEmitter assert = require("assert") dgram = require("dgram") fork = require("child_process").fork net = require("net") util = require("util") SCHED_NONE = 1 SCHED_RR = 2 cluster = new EventEmitter module.exports = cluster cluster.Worker = Worker cluster.isWorker = ("NODE_UNIQUE_ID" of process.env) cluster.isMaster = (cluster.isWorker is false) util.inherits Worker, EventEmitter Worker::kill = -> @destroy.apply this, arguments return Worker::send = -> @process.send.apply @process, arguments return Worker::isDead = isDead = -> @process.exitCode? or @process.signalCode? Worker::isConnected = isConnected = -> @process.connected SharedHandle::add = (worker, send) -> assert @workers.indexOf(worker) is -1 @workers.push worker send @errno, null, @handle return SharedHandle::remove = (worker) -> index = @workers.indexOf(worker) assert index isnt -1 @workers.splice index, 1 return false if @workers.length isnt 0 @handle.close() @handle = null true RoundRobinHandle::add = (worker, send) -> done = -> if self.handle.getsockname out = {} err = self.handle.getsockname(out) send null, sockname: out , null else send null, null, null self.handoff worker return assert worker.id of @all is false @all[worker.id] = worker self = this return done() if util.isNull(@server) @server.once "listening", done @server.once "error", (err) -> errno = process.binding("uv")["UV_" + err.errno] send errno, null return return RoundRobinHandle::remove = (worker) -> return false if worker.id of @all is false delete @all[worker.id] index = @free.indexOf(worker) @free.splice index, 1 if index isnt -1 return false if Object.getOwnPropertyNames(@all).length isnt 0 handle = undefined while handle = @handles.shift() handle.close() @handle.close() @handle = null true RoundRobinHandle::distribute = (err, handle) -> @handles.push handle worker = @free.shift() @handoff worker if worker return RoundRobinHandle::handoff = (worker) -> return if worker.id of @all is false handle = @handles.shift() if util.isUndefined(handle) @free.push worker return message = act: "newconn" key: @key self = this sendHelper worker.process, message, handle, (reply) -> if reply.accepted handle.close() else self.distribute 0, handle self.handoff worker return return if cluster.isMaster masterInit() else workerInit() seq = 0 callbacks = {}
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. Worker = (options) -> return new Worker(options) unless this instanceof Worker EventEmitter.call this options = {} unless util.isObject(options) @suicide = `undefined` @state = options.state or "none" @id = options.id | 0 if options.process @process = options.process @process.on "error", @emit.bind(this, "error") @process.on "message", @emit.bind(this, "message") return # Master/worker specific methods are defined in the *Init() functions. SharedHandle = (key, address, port, addressType, backlog, fd) -> @key = key @workers = [] @handle = null @errno = 0 # FIXME(bnoordhuis) Polymorphic return type for lack of a better solution. rval = undefined if addressType is "udp4" or addressType is "udp6" rval = dgram._createSocketHandle(address, port, addressType, fd) else rval = net._createServerHandle(address, port, addressType, fd) if util.isNumber(rval) @errno = rval else @handle = rval return # Start a round-robin server. Master accepts connections and distributes # them over the workers. RoundRobinHandle = (key, address, port, addressType, backlog, fd) -> @key = key @all = {} @free = [] @handles = [] @handle = null @server = net.createServer(assert.fail) if fd >= 0 @server.listen fd: fd else if port >= 0 @server.listen port, address else # UNIX socket path. @server.listen address self = this @server.once "listening", -> self.handle = self.server._handle self.handle.onconnection = self.distribute.bind(self) self.server._handle = null self.server = null return return # TODO(bnoordhuis) Check err. # UNIX socket. # In case there are connections pending. # Still busy binding. # Hack: translate 'EADDRINUSE' error string back to numeric error code. # It works but ideally we'd have some backchannel between the net and # cluster modules for stuff like this. # Worker is closing (or has closed) the server. # Add to ready queue again. # Worker is shutting down. Send to another. masterInit = -> # XXX(bnoordhuis) Fold cluster.schedulingPolicy into cluster.settings? # FIXME Round-robin doesn't perform well on Windows right now due to the # way IOCP is wired up. Bert is going to fix that, eventually. # Leave it to the operating system. # Master distributes connections. # Keyed on address:port:etc. When a worker dies, we walk over the handles # and remove() the worker from each one. remove() may do a linear scan # itself so we might end up with an O(n*m) operation. Ergo, FIXME. # Tell V8 to write profile data for each process to a separate file. # Without --logfile=v8-%p.log, everything ends up in a single, unusable # file. (Unusable because what V8 logs are memory addresses and each # process has its own memory mappings.) # Freeze policy. # Send debug signal only if not started in debug mode, this helps a lot # on windows, because RegisterDebugHandler is not called when node starts # with --debug.* arg. createWorkerProcess = (id, env) -> workerEnv = util._extend({}, process.env) execArgv = cluster.settings.execArgv.slice() debugPort = process.debugPort + id hasDebugArg = false workerEnv = util._extend(workerEnv, env) workerEnv.NODE_UNIQUE_ID = "" + id i = 0 while i < execArgv.length match = execArgv[i].match(/^(--debug|--debug-brk)(=\d+)?$/) if match execArgv[i] = match[1] + "=" + debugPort hasDebugArg = true i++ execArgv = ["--debug-port=" + debugPort].concat(execArgv) unless hasDebugArg fork cluster.settings.exec, cluster.settings.args, env: workerEnv silent: cluster.settings.silent execArgv: execArgv gid: cluster.settings.gid uid: cluster.settings.uid # # * Remove the worker from the workers list only # * if it has disconnected, otherwise we might # * still want to access it. # # # * Now is a good time to remove the handles # * associated with this worker because it is # * not connected to the master anymore. # # # * Remove the worker from the workers list only # * if its process has exited. Otherwise, we might # * still want to access it. # onmessage = (message, handle) -> worker = this if message.act is "online" online worker else if message.act is "queryServer" queryServer worker, message else if message.act is "listening" listening worker, message else if message.act is "suicide" worker.suicide = true else close worker, message if message.act is "close" return online = (worker) -> worker.state = "online" worker.emit "online" cluster.emit "online", worker return queryServer = (worker, message) -> args = [ message.address message.port message.addressType message.fd ] key = args.join(":") handle = handles[key] if util.isUndefined(handle) constructor = RoundRobinHandle # UDP is exempt from round-robin connection balancing for what should # be obvious reasons: it's connectionless. There is nothing to send to # the workers except raw datagrams and that's pointless. constructor = SharedHandle if schedulingPolicy isnt SCHED_RR or message.addressType is "udp4" or message.addressType is "udp6" handles[key] = handle = new constructor(key, message.address, message.port, message.addressType, message.backlog, message.fd) handle.data = message.data unless handle.data # Set custom server data handle.add worker, (errno, reply, handle) -> reply = util._extend( errno: errno key: key ack: message.seq data: handles[key].data , reply) delete handles[key] if errno # Gives other workers a chance to retry. send worker, reply, handle return return listening = (worker, message) -> info = addressType: message.addressType address: message.address port: message.port fd: message.fd worker.state = "listening" worker.emit "listening", info cluster.emit "listening", worker, info return # Round-robin only. Server in worker is closing, remove from list. close = (worker, message) -> key = message.key handle = handles[key] delete handles[key] if handle.remove(worker) return send = (worker, message, handle, cb) -> sendHelper worker.process, message, handle, cb return cluster.workers = {} intercom = new EventEmitter cluster.settings = {} schedulingPolicy = none: SCHED_NONE rr: SCHED_RR [{process.env.NODE_CLUSTER_SCHED_POLICY}] schedulingPolicy = (if (process.platform is "win32") then SCHED_NONE else SCHED_RR) if util.isUndefined(schedulingPolicy) cluster.schedulingPolicy = schedulingPolicy cluster.SCHED_NONE = SCHED_NONE cluster.SCHED_RR = SCHED_RR handles = {} initialized = false cluster.setupMaster = (options) -> settings = args: process.argv.slice(2) exec: process.argv[1] execArgv: process.execArgv silent: false settings = util._extend(settings, cluster.settings) settings = util._extend(settings, options or {}) settings.execArgv = settings.execArgv.concat(["--logfile=v8-%p.log"]) if settings.execArgv.some((s) -> /^--prof/.test s ) and not settings.execArgv.some((s) -> /^--logfile=/.test s ) cluster.settings = settings if initialized is true return process.nextTick(-> cluster.emit "setup", settings return ) initialized = true schedulingPolicy = cluster.schedulingPolicy assert schedulingPolicy is SCHED_NONE or schedulingPolicy is SCHED_RR, "Bad cluster.schedulingPolicy: " + schedulingPolicy hasDebugArg = process.execArgv.some((argv) -> /^(--debug|--debug-brk)(=\d+)?$/.test argv ) process.nextTick -> cluster.emit "setup", settings return return if hasDebugArg process.on "internalMessage", (message) -> return if message.cmd isnt "NODE_DEBUG_ENABLED" key = undefined for key of cluster.workers worker = cluster.workers[key] if worker.state is "online" process._debugProcess worker.process.pid else worker.once "online", -> process._debugProcess @process.pid return return return ids = 0 cluster.fork = (env) -> removeWorker = (worker) -> assert worker delete cluster.workers[worker.id] if Object.keys(cluster.workers).length is 0 assert Object.keys(handles).length is 0, "Resource leak detected." intercom.emit "disconnect" return removeHandlesForWorker = (worker) -> assert worker for key of handles handle = handles[key] delete handles[key] if handle.remove(worker) return cluster.setupMaster() id = ++ids workerProcess = createWorkerProcess(id, env) worker = new Worker( id: id process: workerProcess ) worker.process.once "exit", (exitCode, signalCode) -> removeWorker worker unless worker.isConnected() worker.suicide = !!worker.suicide worker.state = "dead" worker.emit "exit", exitCode, signalCode cluster.emit "exit", worker, exitCode, signalCode return worker.process.once "disconnect", -> removeHandlesForWorker worker removeWorker worker if worker.isDead() worker.suicide = !!worker.suicide worker.state = "disconnected" worker.emit "disconnect" cluster.emit "disconnect", worker return worker.process.on "internalMessage", internal(worker, onmessage) process.nextTick -> cluster.emit "fork", worker return cluster.workers[worker.id] = worker worker cluster.disconnect = (cb) -> workers = Object.keys(cluster.workers) if workers.length is 0 process.nextTick intercom.emit.bind(intercom, "disconnect") else for key of workers key = workers[key] cluster.workers[key].disconnect() intercom.once "disconnect", cb if cb return Worker::disconnect = -> @suicide = true send this, act: "disconnect" return Worker::destroy = (signo) -> signo = signo or "SIGTERM" proc = @process if @isConnected() @once "disconnect", proc.kill.bind(proc, signo) @disconnect() return proc.kill signo return return workerInit = -> # Called from src/node.js # Unexpected disconnect, master exited, or some such nastiness, so # worker exits immediately. # obj is a net#Server or a dgram#Socket object. # Set custom data on handle (i.e. tls tickets key) # Shared listen socket. # Round-robin. # Shared listen socket. shared = (message, handle, cb) -> key = message.key # Monkey-patch the close() method so we can keep track of when it's # closed. Avoids resource leaks when the handle is short-lived. close = handle.close handle.close = -> delete handles[key] close.apply this, arguments assert util.isUndefined(handles[key]) handles[key] = handle cb message.errno, handle return # Round-robin. Master distributes handles across workers. rr = (message, cb) -> listen = (backlog) -> # TODO(bnoordhuis) Send a message to the master that tells it to # update the backlog size. The actual backlog should probably be # the largest requested size by any worker. 0 close = -> # lib/net.js treats server._handle.close() as effectively synchronous. # That means there is a time window between the call to close() and # the ack by the master process in which we can still receive handles. # onconnection() below handles that by sending those handles back to # the master. return if util.isUndefined(key) send act: "close" key: key delete handles[key] key = `PI:KEY:<KEY>END_PI` return getsockname = (out) -> util._extend out, message.sockname if key 0 return cb(message.errno, null) if message.errno key = message.key # Faux handle. Mimics a TCPWrap with just enough fidelity to get away # with it. Fools net.Server into thinking that it's backed by a real # handle. handle = close: close listen: listen handle.getsockname = getsockname if message.sockname # TCP handles only. assert util.isUndefined(handles[key]) handles[key] = handle cb 0, handle return # Round-robin connection. onconnection = (message, handle) -> key = PI:KEY:<KEY>END_PI.key server = handles[key] accepted = not util.isUndefined(server) send ack: message.seq accepted: accepted server.onconnection 0, handle if accepted return send = (message, cb) -> sendHelper process, message, null, cb return handles = {} cluster._setupWorker = -> onmessage = (message, handle) -> if message.act is "newconn" onconnection message, handle else worker.disconnect() if message.act is "disconnect" return worker = new Worker( id: +process.env.NODE_UNIQUE_ID | 0 process: process state: "online" ) cluster.worker = worker process.once "disconnect", -> process.exit 0 unless worker.suicide return process.on "internalMessage", internal(worker, onmessage) send act: "online" return cluster._getServer = (obj, address, port, addressType, fd, cb) -> message = addressType: addressType address: address port: port act: "queryServer" fd: fd data: null message.data = obj._getServerData() if obj._getServerData send message, (reply, handle) -> obj._setServerData reply.data if obj._setServerData if handle shared reply, handle, cb else rr reply, cb return obj.once "listening", -> cluster.worker.state = "listening" address = obj.address() message.act = "listening" message.port = address and address.port or port send message return return Worker::disconnect = -> @suicide = true for key of handles handle = handles[key] delete handles[key] handle.close() process.disconnect() return Worker::destroy = -> @suicide = true process.exit 0 unless @isConnected() exit = process.exit.bind(null, 0) send act: "suicide" , exit process.once "disconnect", exit process.disconnect() return return sendHelper = (proc, message, handle, cb) -> # Mark message as internal. See INTERNAL_PREFIX in lib/child_process.js message = util._extend( cmd: "NODE_CLUSTER" , message) callbacks[seq] = cb if cb message.seq = seq seq += 1 proc.send message, handle return # Returns an internalMessage listener that hands off normal messages # to the callback but intercepts and redirects ACK messages. internal = (worker, cb) -> (message, handle) -> return if message.cmd isnt "NODE_CLUSTER" fn = cb unless util.isUndefined(message.ack) fn = callbacks[message.ack] delete callbacks[message.ack] fn.apply worker, arguments return "use strict" EventEmitter = require("events").EventEmitter assert = require("assert") dgram = require("dgram") fork = require("child_process").fork net = require("net") util = require("util") SCHED_NONE = 1 SCHED_RR = 2 cluster = new EventEmitter module.exports = cluster cluster.Worker = Worker cluster.isWorker = ("NODE_UNIQUE_ID" of process.env) cluster.isMaster = (cluster.isWorker is false) util.inherits Worker, EventEmitter Worker::kill = -> @destroy.apply this, arguments return Worker::send = -> @process.send.apply @process, arguments return Worker::isDead = isDead = -> @process.exitCode? or @process.signalCode? Worker::isConnected = isConnected = -> @process.connected SharedHandle::add = (worker, send) -> assert @workers.indexOf(worker) is -1 @workers.push worker send @errno, null, @handle return SharedHandle::remove = (worker) -> index = @workers.indexOf(worker) assert index isnt -1 @workers.splice index, 1 return false if @workers.length isnt 0 @handle.close() @handle = null true RoundRobinHandle::add = (worker, send) -> done = -> if self.handle.getsockname out = {} err = self.handle.getsockname(out) send null, sockname: out , null else send null, null, null self.handoff worker return assert worker.id of @all is false @all[worker.id] = worker self = this return done() if util.isNull(@server) @server.once "listening", done @server.once "error", (err) -> errno = process.binding("uv")["UV_" + err.errno] send errno, null return return RoundRobinHandle::remove = (worker) -> return false if worker.id of @all is false delete @all[worker.id] index = @free.indexOf(worker) @free.splice index, 1 if index isnt -1 return false if Object.getOwnPropertyNames(@all).length isnt 0 handle = undefined while handle = @handles.shift() handle.close() @handle.close() @handle = null true RoundRobinHandle::distribute = (err, handle) -> @handles.push handle worker = @free.shift() @handoff worker if worker return RoundRobinHandle::handoff = (worker) -> return if worker.id of @all is false handle = @handles.shift() if util.isUndefined(handle) @free.push worker return message = act: "newconn" key: @key self = this sendHelper worker.process, message, handle, (reply) -> if reply.accepted handle.close() else self.distribute 0, handle self.handoff worker return return if cluster.isMaster masterInit() else workerInit() seq = 0 callbacks = {}
[ { "context": "3-2014 TheGrid (Rituwall Inc.)\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed und", "end": 129, "score": 0.9998405575752258, "start": 116, "tag": "NAME", "value": "Henri Bergius" }, { "context": "(Rituwall Inc.)\n# (c) 2011-2012 He...
src/lib/AsyncComponent.coffee
ensonic/noflo
1
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2014 TheGrid (Rituwall Inc.) # (c) 2011-2012 Henri Bergius, Nemein # NoFlo may be freely distributed under the MIT license # # Baseclass for components dealing with asynchronous I/O operations. Supports # throttling. port = require "./Port" component = require "./Component" class AsyncComponent extends component.Component constructor: (@inPortName="in", @outPortName="out", @errPortName="error") -> unless @inPorts[@inPortName] throw new Error "no inPort named '#{@inPortName}'" unless @outPorts[@outPortName] throw new Error "no outPort named '#{@outPortName}'" @load = 0 @q = [] @errorGroups = [] @outPorts.load = new port.Port() @inPorts[@inPortName].on "begingroup", (group) => return @q.push { name: "begingroup", data: group } if @load > 0 @errorGroups.push group @outPorts[@outPortName].beginGroup group @inPorts[@inPortName].on "endgroup", => return @q.push { name: "endgroup" } if @load > 0 @errorGroups.pop() @outPorts[@outPortName].endGroup() @inPorts[@inPortName].on "disconnect", => return @q.push { name: "disconnect" } if @load > 0 @outPorts[@outPortName].disconnect() @errorGroups = [] @outPorts.load.disconnect() if @outPorts.load.isAttached() @inPorts[@inPortName].on "data", (data) => return @q.push { name: "data", data: data } if @q.length > 0 @processData data processData: (data) -> @incrementLoad() @doAsync data, (err) => @error err, @errorGroups, @errPortName if err @decrementLoad() incrementLoad: -> @load++ @outPorts.load.send @load if @outPorts.load.isAttached() @outPorts.load.disconnect() if @outPorts.load.isAttached() doAsync: (data, callback) -> callback new Error "AsyncComponents must implement doAsync" decrementLoad: -> throw new Error "load cannot be negative" if @load == 0 @load-- @outPorts.load.send @load if @outPorts.load.isAttached() @outPorts.load.disconnect() if @outPorts.load.isAttached() if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1 # nextTick is faster than setTimeout on Node.js process.nextTick => @processQueue() else setTimeout => do @processQueue , 0 processQueue: -> if @load > 0 return processedData = false while @q.length > 0 event = @q[0] switch event.name when "begingroup" return if processedData @outPorts[@outPortName].beginGroup event.data @errorGroups.push event.data @q.shift() when "endgroup" return if processedData @outPorts[@outPortName].endGroup() @errorGroups.pop() @q.shift() when "disconnect" return if processedData @outPorts[@outPortName].disconnect() @outPorts.load.disconnect() if @outPorts.load.isAttached() @errorGroups = [] @q.shift() when "data" @processData event.data @q.shift() processedData = true shutdown: -> @q = [] @errorGroups = [] exports.AsyncComponent = AsyncComponent
154355
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2014 TheGrid (Rituwall Inc.) # (c) 2011-2012 <NAME>, <NAME> # NoFlo may be freely distributed under the MIT license # # Baseclass for components dealing with asynchronous I/O operations. Supports # throttling. port = require "./Port" component = require "./Component" class AsyncComponent extends component.Component constructor: (@inPortName="in", @outPortName="out", @errPortName="error") -> unless @inPorts[@inPortName] throw new Error "no inPort named '#{@inPortName}'" unless @outPorts[@outPortName] throw new Error "no outPort named '#{@outPortName}'" @load = 0 @q = [] @errorGroups = [] @outPorts.load = new port.Port() @inPorts[@inPortName].on "begingroup", (group) => return @q.push { name: "begingroup", data: group } if @load > 0 @errorGroups.push group @outPorts[@outPortName].beginGroup group @inPorts[@inPortName].on "endgroup", => return @q.push { name: "endgroup" } if @load > 0 @errorGroups.pop() @outPorts[@outPortName].endGroup() @inPorts[@inPortName].on "disconnect", => return @q.push { name: "disconnect" } if @load > 0 @outPorts[@outPortName].disconnect() @errorGroups = [] @outPorts.load.disconnect() if @outPorts.load.isAttached() @inPorts[@inPortName].on "data", (data) => return @q.push { name: "data", data: data } if @q.length > 0 @processData data processData: (data) -> @incrementLoad() @doAsync data, (err) => @error err, @errorGroups, @errPortName if err @decrementLoad() incrementLoad: -> @load++ @outPorts.load.send @load if @outPorts.load.isAttached() @outPorts.load.disconnect() if @outPorts.load.isAttached() doAsync: (data, callback) -> callback new Error "AsyncComponents must implement doAsync" decrementLoad: -> throw new Error "load cannot be negative" if @load == 0 @load-- @outPorts.load.send @load if @outPorts.load.isAttached() @outPorts.load.disconnect() if @outPorts.load.isAttached() if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1 # nextTick is faster than setTimeout on Node.js process.nextTick => @processQueue() else setTimeout => do @processQueue , 0 processQueue: -> if @load > 0 return processedData = false while @q.length > 0 event = @q[0] switch event.name when "begingroup" return if processedData @outPorts[@outPortName].beginGroup event.data @errorGroups.push event.data @q.shift() when "endgroup" return if processedData @outPorts[@outPortName].endGroup() @errorGroups.pop() @q.shift() when "disconnect" return if processedData @outPorts[@outPortName].disconnect() @outPorts.load.disconnect() if @outPorts.load.isAttached() @errorGroups = [] @q.shift() when "data" @processData event.data @q.shift() processedData = true shutdown: -> @q = [] @errorGroups = [] exports.AsyncComponent = AsyncComponent
true
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2014 TheGrid (Rituwall Inc.) # (c) 2011-2012 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI # NoFlo may be freely distributed under the MIT license # # Baseclass for components dealing with asynchronous I/O operations. Supports # throttling. port = require "./Port" component = require "./Component" class AsyncComponent extends component.Component constructor: (@inPortName="in", @outPortName="out", @errPortName="error") -> unless @inPorts[@inPortName] throw new Error "no inPort named '#{@inPortName}'" unless @outPorts[@outPortName] throw new Error "no outPort named '#{@outPortName}'" @load = 0 @q = [] @errorGroups = [] @outPorts.load = new port.Port() @inPorts[@inPortName].on "begingroup", (group) => return @q.push { name: "begingroup", data: group } if @load > 0 @errorGroups.push group @outPorts[@outPortName].beginGroup group @inPorts[@inPortName].on "endgroup", => return @q.push { name: "endgroup" } if @load > 0 @errorGroups.pop() @outPorts[@outPortName].endGroup() @inPorts[@inPortName].on "disconnect", => return @q.push { name: "disconnect" } if @load > 0 @outPorts[@outPortName].disconnect() @errorGroups = [] @outPorts.load.disconnect() if @outPorts.load.isAttached() @inPorts[@inPortName].on "data", (data) => return @q.push { name: "data", data: data } if @q.length > 0 @processData data processData: (data) -> @incrementLoad() @doAsync data, (err) => @error err, @errorGroups, @errPortName if err @decrementLoad() incrementLoad: -> @load++ @outPorts.load.send @load if @outPorts.load.isAttached() @outPorts.load.disconnect() if @outPorts.load.isAttached() doAsync: (data, callback) -> callback new Error "AsyncComponents must implement doAsync" decrementLoad: -> throw new Error "load cannot be negative" if @load == 0 @load-- @outPorts.load.send @load if @outPorts.load.isAttached() @outPorts.load.disconnect() if @outPorts.load.isAttached() if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1 # nextTick is faster than setTimeout on Node.js process.nextTick => @processQueue() else setTimeout => do @processQueue , 0 processQueue: -> if @load > 0 return processedData = false while @q.length > 0 event = @q[0] switch event.name when "begingroup" return if processedData @outPorts[@outPortName].beginGroup event.data @errorGroups.push event.data @q.shift() when "endgroup" return if processedData @outPorts[@outPortName].endGroup() @errorGroups.pop() @q.shift() when "disconnect" return if processedData @outPorts[@outPortName].disconnect() @outPorts.load.disconnect() if @outPorts.load.isAttached() @errorGroups = [] @q.shift() when "data" @processData event.data @q.shift() processedData = true shutdown: -> @q = [] @errorGroups = [] exports.AsyncComponent = AsyncComponent
[ { "context": " message\n # return\n\n pusher = new Pusher('98d6e8e3a6d1437792da', { encrypted: true })\n cha", "end": 3206, "score": 0.48868468403816223, "start": 3205, "tag": "USERNAME", "value": "9" }, { "context": "message\n # return\n\n pusher = new Pusher('98d...
app/assets/javascripts/linked_accounts.js.coffee
l85m/trym
1
@waitForPlaidToAddUser = (linkedAccountPath) -> if $('#new_linked_account').is(':visible') submit_button_text = 'Link Account' current_form = 'credentials' else submit_button_text = 'Continue' current_form = 'mfa' submit_button = $('#' + current_form + '-submit-button') error_container = $('#' + current_form + '-error-container') form_container = $('#' + current_form + '-form-container') submit_button.html '<i class=\'fa fa-cog fa-spin fa-fw\'></i>Working</button>' # this function will run each 1000 ms until stopped with clearInterval() i = setInterval((-> $.ajax url: linkedAccountPath dataType: 'json' success: (json) -> if json.last_api_response == null else if json.last_api_response.response_code == '200' clearInterval i $('.modal-content').animate { height: '305px' }, 1100 form_container.fadeOut 1000, -> $('#link-success-container').fadeIn() return else if json.last_api_response.response_code == '201' clearInterval i form_container.fadeOut 500, -> submit_button.html submit_button_text $('label[for=\'linked_account_mfa_response\']').text json.mfa_prompt $('#linked_account_mfa_response').val '' $('#mfa-form-container').fadeIn() return else clearInterval i submit_button.html submit_button_text flash_error_button submit_button error_container.html '<p class=\'form-errors\'>' + json.error_message + '</p>' return error: -> # on error, stop execution submit_button.html submit_button_text flash_error_button submit_button error_container.html '<p class=\'form-errors\'>Could not communicate with server, please try again</p>' clearInterval i return return ), 1000) #update user for syncing/analyzing account @updateLinkedAccountStatus = (data) -> if data.message.flash != '' $.jGrowl data.message.flash, header: '<i class=\'fa fa-credit-card\'></i> ' + data.linked_account_name sticky: true if $('#linked-account-index').is(":visible") row = $("li[data-linked-account-id=" + data.linked_account_id + "]") button = '<a class="btn btn-primary-o btn-responsive linked-account-button"></a>' button = row.find(".linked-account-button").parent().html(button).find("a") button.html( "<i class='fa fa fa-" + data.message.button_icon + "'></i> " + data.message.button_text ) button.attr('href',data.message.button_link) if data.message.button_disabled_state == "false" button.removeAttr('disabled') else button.attr('disabled','disabled') button.removeData("toggle").removeData("title") button.removeAttr("data-toggle").removeAttr("data-title") button.parent().tooltip('destroy') if data.message.button_tooltip != '' button.parent().tooltip({title:data.message.button_tooltip}) $ -> if $('#whoami').length # Pusher.log = (message) -> # if window.console and window.console.log # window.console.log message # return pusher = new Pusher('98d6e8e3a6d1437792da', { encrypted: true }) channel = pusher.subscribe('private-user-' + $('#whoami').data("user-id") + '-channel') channel.bind 'linked-account-notifications', (data) -> updateLinkedAccountStatus(data) return
177942
@waitForPlaidToAddUser = (linkedAccountPath) -> if $('#new_linked_account').is(':visible') submit_button_text = 'Link Account' current_form = 'credentials' else submit_button_text = 'Continue' current_form = 'mfa' submit_button = $('#' + current_form + '-submit-button') error_container = $('#' + current_form + '-error-container') form_container = $('#' + current_form + '-form-container') submit_button.html '<i class=\'fa fa-cog fa-spin fa-fw\'></i>Working</button>' # this function will run each 1000 ms until stopped with clearInterval() i = setInterval((-> $.ajax url: linkedAccountPath dataType: 'json' success: (json) -> if json.last_api_response == null else if json.last_api_response.response_code == '200' clearInterval i $('.modal-content').animate { height: '305px' }, 1100 form_container.fadeOut 1000, -> $('#link-success-container').fadeIn() return else if json.last_api_response.response_code == '201' clearInterval i form_container.fadeOut 500, -> submit_button.html submit_button_text $('label[for=\'linked_account_mfa_response\']').text json.mfa_prompt $('#linked_account_mfa_response').val '' $('#mfa-form-container').fadeIn() return else clearInterval i submit_button.html submit_button_text flash_error_button submit_button error_container.html '<p class=\'form-errors\'>' + json.error_message + '</p>' return error: -> # on error, stop execution submit_button.html submit_button_text flash_error_button submit_button error_container.html '<p class=\'form-errors\'>Could not communicate with server, please try again</p>' clearInterval i return return ), 1000) #update user for syncing/analyzing account @updateLinkedAccountStatus = (data) -> if data.message.flash != '' $.jGrowl data.message.flash, header: '<i class=\'fa fa-credit-card\'></i> ' + data.linked_account_name sticky: true if $('#linked-account-index').is(":visible") row = $("li[data-linked-account-id=" + data.linked_account_id + "]") button = '<a class="btn btn-primary-o btn-responsive linked-account-button"></a>' button = row.find(".linked-account-button").parent().html(button).find("a") button.html( "<i class='fa fa fa-" + data.message.button_icon + "'></i> " + data.message.button_text ) button.attr('href',data.message.button_link) if data.message.button_disabled_state == "false" button.removeAttr('disabled') else button.attr('disabled','disabled') button.removeData("toggle").removeData("title") button.removeAttr("data-toggle").removeAttr("data-title") button.parent().tooltip('destroy') if data.message.button_tooltip != '' button.parent().tooltip({title:data.message.button_tooltip}) $ -> if $('#whoami').length # Pusher.log = (message) -> # if window.console and window.console.log # window.console.log message # return pusher = new Pusher('9<PASSWORD>', { encrypted: true }) channel = pusher.subscribe('private-user-' + $('#whoami').data("user-id") + '-channel') channel.bind 'linked-account-notifications', (data) -> updateLinkedAccountStatus(data) return
true
@waitForPlaidToAddUser = (linkedAccountPath) -> if $('#new_linked_account').is(':visible') submit_button_text = 'Link Account' current_form = 'credentials' else submit_button_text = 'Continue' current_form = 'mfa' submit_button = $('#' + current_form + '-submit-button') error_container = $('#' + current_form + '-error-container') form_container = $('#' + current_form + '-form-container') submit_button.html '<i class=\'fa fa-cog fa-spin fa-fw\'></i>Working</button>' # this function will run each 1000 ms until stopped with clearInterval() i = setInterval((-> $.ajax url: linkedAccountPath dataType: 'json' success: (json) -> if json.last_api_response == null else if json.last_api_response.response_code == '200' clearInterval i $('.modal-content').animate { height: '305px' }, 1100 form_container.fadeOut 1000, -> $('#link-success-container').fadeIn() return else if json.last_api_response.response_code == '201' clearInterval i form_container.fadeOut 500, -> submit_button.html submit_button_text $('label[for=\'linked_account_mfa_response\']').text json.mfa_prompt $('#linked_account_mfa_response').val '' $('#mfa-form-container').fadeIn() return else clearInterval i submit_button.html submit_button_text flash_error_button submit_button error_container.html '<p class=\'form-errors\'>' + json.error_message + '</p>' return error: -> # on error, stop execution submit_button.html submit_button_text flash_error_button submit_button error_container.html '<p class=\'form-errors\'>Could not communicate with server, please try again</p>' clearInterval i return return ), 1000) #update user for syncing/analyzing account @updateLinkedAccountStatus = (data) -> if data.message.flash != '' $.jGrowl data.message.flash, header: '<i class=\'fa fa-credit-card\'></i> ' + data.linked_account_name sticky: true if $('#linked-account-index').is(":visible") row = $("li[data-linked-account-id=" + data.linked_account_id + "]") button = '<a class="btn btn-primary-o btn-responsive linked-account-button"></a>' button = row.find(".linked-account-button").parent().html(button).find("a") button.html( "<i class='fa fa fa-" + data.message.button_icon + "'></i> " + data.message.button_text ) button.attr('href',data.message.button_link) if data.message.button_disabled_state == "false" button.removeAttr('disabled') else button.attr('disabled','disabled') button.removeData("toggle").removeData("title") button.removeAttr("data-toggle").removeAttr("data-title") button.parent().tooltip('destroy') if data.message.button_tooltip != '' button.parent().tooltip({title:data.message.button_tooltip}) $ -> if $('#whoami').length # Pusher.log = (message) -> # if window.console and window.console.log # window.console.log message # return pusher = new Pusher('9PI:PASSWORD:<PASSWORD>END_PI', { encrypted: true }) channel = pusher.subscribe('private-user-' + $('#whoami').data("user-id") + '-channel') channel.bind 'linked-account-notifications', (data) -> updateLinkedAccountStatus(data) return
[ { "context": " at the start', =>\n @document.setValue('test123')\n\n deleteRange = new Range(0, 0, 0, 4)\n\n ", "end": 2532, "score": 0.4773072600364685, "start": 2530, "tag": "PASSWORD", "value": "23" }, { "context": " the middle', =>\n @document.setValue('testing12...
spec/javascripts/adapters/ace_adapter_spec.coffee
ball-hayden/CollaborateAce
0
#= require ace/ace #= require collaborate describe 'Adapters.TextAreaAdapter', -> Range = ace.require('ace/range').Range beforeEach => fixture.set('<div id="editor"></div>') @cable = Cable.createConsumer "ws://localhost:28080" @collaborate = new Collaborate(@cable, 'DocumentChannel', 'body') @collaborativeAttribute = @collaborate.addAttribute('body') @editor = ace.edit('editor') @session = @editor.getSession() @document = @session.getDocument() @adapter = new Collaborate.Adapters.AceAdapter(@collaborativeAttribute, @editor) it 'should respond to text changes', => spyOn(@collaborativeAttribute, 'localOperation') position = @document.indexToPosition(0) @document.insert(position, 'Test') expect(@collaborativeAttribute.localOperation).toHaveBeenCalled() describe 'generating an OT operation from a text change', => beforeEach => spyOn(@collaborativeAttribute, 'localOperation') it 'should be able to insert new text', => position = @document.indexToPosition(0) @document.insert(position, 'Test') expectedOperation = (new ot.TextOperation()).insert('Test') expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle insert operations at the beginning of the existing text', => @document.setValue('ing') position = @document.indexToPosition(0) @document.insert(position, 'Test') expectedOperation = (new ot.TextOperation()).insert('Test').retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle insert operations in the middle of the existing text', => @document.setValue('test123') position = @document.indexToPosition(4) @document.insert(position, 'ing') expectedOperation = (new ot.TextOperation()).retain(4).insert('ing').retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle insert operations at the end of the existing text', => @document.setValue('test') position = @document.indexToPosition(4) @document.insert(position, 'ing\n\n123') expectedOperation = (new ot.TextOperation()).retain(4).insert('ing\n\n123') expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle delete operations at the start', => @document.setValue('test123') deleteRange = new Range(0, 0, 0, 4) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).delete(4).retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle delete operations in the middle', => @document.setValue('testing123') deleteRange = new Range(0, 4, 0, 7) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).retain(4).delete(3).retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle delete operations at the end', => @document.setValue('testing') deleteRange = new Range(0, 4, 0, 7) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).retain(4).delete(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to delete all text', => @document.setValue('testing') deleteRange = new Range(0, 0, 0, 7) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).delete(7) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) describe 'applying remote changes', => beforeEach => @document.setValue('test') spyOn(@collaborativeAttribute, 'localOperation') operation = (new ot.TextOperation()).retain(4).insert('ing') @adapter.applyRemoteOperation(operation) it 'should update the content of the textArea', => expect(@document.getValue()).toEqual('testing') it 'should not call localOperation', => expect(@collaborativeAttribute.localOperation).not.toHaveBeenCalled()
29357
#= require ace/ace #= require collaborate describe 'Adapters.TextAreaAdapter', -> Range = ace.require('ace/range').Range beforeEach => fixture.set('<div id="editor"></div>') @cable = Cable.createConsumer "ws://localhost:28080" @collaborate = new Collaborate(@cable, 'DocumentChannel', 'body') @collaborativeAttribute = @collaborate.addAttribute('body') @editor = ace.edit('editor') @session = @editor.getSession() @document = @session.getDocument() @adapter = new Collaborate.Adapters.AceAdapter(@collaborativeAttribute, @editor) it 'should respond to text changes', => spyOn(@collaborativeAttribute, 'localOperation') position = @document.indexToPosition(0) @document.insert(position, 'Test') expect(@collaborativeAttribute.localOperation).toHaveBeenCalled() describe 'generating an OT operation from a text change', => beforeEach => spyOn(@collaborativeAttribute, 'localOperation') it 'should be able to insert new text', => position = @document.indexToPosition(0) @document.insert(position, 'Test') expectedOperation = (new ot.TextOperation()).insert('Test') expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle insert operations at the beginning of the existing text', => @document.setValue('ing') position = @document.indexToPosition(0) @document.insert(position, 'Test') expectedOperation = (new ot.TextOperation()).insert('Test').retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle insert operations in the middle of the existing text', => @document.setValue('test123') position = @document.indexToPosition(4) @document.insert(position, 'ing') expectedOperation = (new ot.TextOperation()).retain(4).insert('ing').retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle insert operations at the end of the existing text', => @document.setValue('test') position = @document.indexToPosition(4) @document.insert(position, 'ing\n\n123') expectedOperation = (new ot.TextOperation()).retain(4).insert('ing\n\n123') expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle delete operations at the start', => @document.setValue('test1<PASSWORD>') deleteRange = new Range(0, 0, 0, 4) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).delete(4).retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle delete operations in the middle', => @document.setValue('testing<PASSWORD>') deleteRange = new Range(0, 4, 0, 7) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).retain(4).delete(3).retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle delete operations at the end', => @document.setValue('testing') deleteRange = new Range(0, 4, 0, 7) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).retain(4).delete(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to delete all text', => @document.setValue('testing') deleteRange = new Range(0, 0, 0, 7) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).delete(7) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) describe 'applying remote changes', => beforeEach => @document.setValue('test') spyOn(@collaborativeAttribute, 'localOperation') operation = (new ot.TextOperation()).retain(4).insert('ing') @adapter.applyRemoteOperation(operation) it 'should update the content of the textArea', => expect(@document.getValue()).toEqual('testing') it 'should not call localOperation', => expect(@collaborativeAttribute.localOperation).not.toHaveBeenCalled()
true
#= require ace/ace #= require collaborate describe 'Adapters.TextAreaAdapter', -> Range = ace.require('ace/range').Range beforeEach => fixture.set('<div id="editor"></div>') @cable = Cable.createConsumer "ws://localhost:28080" @collaborate = new Collaborate(@cable, 'DocumentChannel', 'body') @collaborativeAttribute = @collaborate.addAttribute('body') @editor = ace.edit('editor') @session = @editor.getSession() @document = @session.getDocument() @adapter = new Collaborate.Adapters.AceAdapter(@collaborativeAttribute, @editor) it 'should respond to text changes', => spyOn(@collaborativeAttribute, 'localOperation') position = @document.indexToPosition(0) @document.insert(position, 'Test') expect(@collaborativeAttribute.localOperation).toHaveBeenCalled() describe 'generating an OT operation from a text change', => beforeEach => spyOn(@collaborativeAttribute, 'localOperation') it 'should be able to insert new text', => position = @document.indexToPosition(0) @document.insert(position, 'Test') expectedOperation = (new ot.TextOperation()).insert('Test') expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle insert operations at the beginning of the existing text', => @document.setValue('ing') position = @document.indexToPosition(0) @document.insert(position, 'Test') expectedOperation = (new ot.TextOperation()).insert('Test').retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle insert operations in the middle of the existing text', => @document.setValue('test123') position = @document.indexToPosition(4) @document.insert(position, 'ing') expectedOperation = (new ot.TextOperation()).retain(4).insert('ing').retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle insert operations at the end of the existing text', => @document.setValue('test') position = @document.indexToPosition(4) @document.insert(position, 'ing\n\n123') expectedOperation = (new ot.TextOperation()).retain(4).insert('ing\n\n123') expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle delete operations at the start', => @document.setValue('test1PI:PASSWORD:<PASSWORD>END_PI') deleteRange = new Range(0, 0, 0, 4) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).delete(4).retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle delete operations in the middle', => @document.setValue('testingPI:PASSWORD:<PASSWORD>END_PI') deleteRange = new Range(0, 4, 0, 7) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).retain(4).delete(3).retain(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to handle delete operations at the end', => @document.setValue('testing') deleteRange = new Range(0, 4, 0, 7) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).retain(4).delete(3) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) it 'should be able to delete all text', => @document.setValue('testing') deleteRange = new Range(0, 0, 0, 7) @document.remove(deleteRange) expectedOperation = (new ot.TextOperation()).delete(7) expect(@collaborativeAttribute.localOperation).toHaveBeenCalledWith(expectedOperation) describe 'applying remote changes', => beforeEach => @document.setValue('test') spyOn(@collaborativeAttribute, 'localOperation') operation = (new ot.TextOperation()).retain(4).insert('ing') @adapter.applyRemoteOperation(operation) it 'should update the content of the textArea', => expect(@document.getValue()).toEqual('testing') it 'should not call localOperation', => expect(@collaborativeAttribute.localOperation).not.toHaveBeenCalled()
[ { "context": "\t\t\turl: @v1Url=\"http://overleaf.com\"\n\t\t\t\t\t\tuser: \"sharelatex\"\n\t\t\t\t\t\tpass: \"password\"\n\t\t\t\toverleaf:\n\t\t\t\t\thost: ", "end": 1460, "score": 0.9218829870223999, "start": 1450, "tag": "USERNAME", "value": "sharelatex" }, { "context": "erleaf.c...
test/unit/coffee/Templates/TemplatesControllerTests.coffee
davidmehren/web-sharelatex
0
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = '../../../../app/js/Features/Templates/TemplatesController' describe 'TemplatesController', -> project_id = "213432" beforeEach -> @request = sinon.stub() @request.returns { pipe:-> on:-> } @fs = { unlink : sinon.stub() createWriteStream : sinon.stub().returns(on:(_, cb)->cb()) } @ProjectUploadManager = {createProjectFromZipArchive : sinon.stub().callsArgWith(3, null, {_id:project_id})} @dumpFolder = "dump/path" @ProjectOptionsHandler = {setCompiler:sinon.stub().callsArgWith(2)} @uuid = "1234" @ProjectDetailsHandler = getProjectDescription:sinon.stub() @Project = update: sinon.stub().callsArgWith(3, null) @controller = SandboxedModule.require modulePath, requires: '../../../js/Features/Uploads/ProjectUploadManager':@ProjectUploadManager '../../../js/Features/Project/ProjectOptionsHandler':@ProjectOptionsHandler '../../../js/Features/Authentication/AuthenticationController': @AuthenticationController = {getLoggedInUserId: sinon.stub()} './TemplatesPublisher':@TemplatesPublisher "logger-sharelatex": log:-> err:-> "settings-sharelatex": path: dumpFolder:@dumpFolder siteUrl: @siteUrl = "http://localhost:3000" apis: v1: url: @v1Url="http://overleaf.com" user: "sharelatex" pass: "password" overleaf: host: @v1Url "uuid":v4:=>@uuid "request": @request "fs":@fs "../../../../app/js/models/Project": {Project: @Project} @zipUrl = "%2Ftemplates%2F52fb86a81ae1e566597a25f6%2Fv%2F4%2Fzip&templateName=Moderncv%20Banking&compiler=pdflatex" @templateName = "project name here" @user_id = "1234" @req = session: user: _id:@user_id templateData: zipUrl: @zipUrl templateName: @templateName @redirect = {} @AuthenticationController.getLoggedInUserId.returns(@user_id) describe 'v1Templates', -> it "should fetch zip from v1 based on template id", (done)-> @templateVersionId = 15 @req.body = {templateVersionId: @templateVersionId} redirect = => @request.calledWith("#{@v1Url}/api/v1/sharelatex/templates/#{@templateVersionId}").should.equal true done() res = redirect:redirect @controller.createProjectFromV1Template @req, res
203411
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = '../../../../app/js/Features/Templates/TemplatesController' describe 'TemplatesController', -> project_id = "213432" beforeEach -> @request = sinon.stub() @request.returns { pipe:-> on:-> } @fs = { unlink : sinon.stub() createWriteStream : sinon.stub().returns(on:(_, cb)->cb()) } @ProjectUploadManager = {createProjectFromZipArchive : sinon.stub().callsArgWith(3, null, {_id:project_id})} @dumpFolder = "dump/path" @ProjectOptionsHandler = {setCompiler:sinon.stub().callsArgWith(2)} @uuid = "1234" @ProjectDetailsHandler = getProjectDescription:sinon.stub() @Project = update: sinon.stub().callsArgWith(3, null) @controller = SandboxedModule.require modulePath, requires: '../../../js/Features/Uploads/ProjectUploadManager':@ProjectUploadManager '../../../js/Features/Project/ProjectOptionsHandler':@ProjectOptionsHandler '../../../js/Features/Authentication/AuthenticationController': @AuthenticationController = {getLoggedInUserId: sinon.stub()} './TemplatesPublisher':@TemplatesPublisher "logger-sharelatex": log:-> err:-> "settings-sharelatex": path: dumpFolder:@dumpFolder siteUrl: @siteUrl = "http://localhost:3000" apis: v1: url: @v1Url="http://overleaf.com" user: "sharelatex" pass: "<PASSWORD>" overleaf: host: @v1Url "uuid":v4:=>@uuid "request": @request "fs":@fs "../../../../app/js/models/Project": {Project: @Project} @zipUrl = "%2Ftemplates%2F52fb86a81ae1e566597a25f6%2Fv%2F4%2Fzip&templateName=Moderncv%20Banking&compiler=pdflatex" @templateName = "project name here" @user_id = "1234" @req = session: user: _id:@user_id templateData: zipUrl: @zipUrl templateName: @templateName @redirect = {} @AuthenticationController.getLoggedInUserId.returns(@user_id) describe 'v1Templates', -> it "should fetch zip from v1 based on template id", (done)-> @templateVersionId = 15 @req.body = {templateVersionId: @templateVersionId} redirect = => @request.calledWith("#{@v1Url}/api/v1/sharelatex/templates/#{@templateVersionId}").should.equal true done() res = redirect:redirect @controller.createProjectFromV1Template @req, res
true
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = '../../../../app/js/Features/Templates/TemplatesController' describe 'TemplatesController', -> project_id = "213432" beforeEach -> @request = sinon.stub() @request.returns { pipe:-> on:-> } @fs = { unlink : sinon.stub() createWriteStream : sinon.stub().returns(on:(_, cb)->cb()) } @ProjectUploadManager = {createProjectFromZipArchive : sinon.stub().callsArgWith(3, null, {_id:project_id})} @dumpFolder = "dump/path" @ProjectOptionsHandler = {setCompiler:sinon.stub().callsArgWith(2)} @uuid = "1234" @ProjectDetailsHandler = getProjectDescription:sinon.stub() @Project = update: sinon.stub().callsArgWith(3, null) @controller = SandboxedModule.require modulePath, requires: '../../../js/Features/Uploads/ProjectUploadManager':@ProjectUploadManager '../../../js/Features/Project/ProjectOptionsHandler':@ProjectOptionsHandler '../../../js/Features/Authentication/AuthenticationController': @AuthenticationController = {getLoggedInUserId: sinon.stub()} './TemplatesPublisher':@TemplatesPublisher "logger-sharelatex": log:-> err:-> "settings-sharelatex": path: dumpFolder:@dumpFolder siteUrl: @siteUrl = "http://localhost:3000" apis: v1: url: @v1Url="http://overleaf.com" user: "sharelatex" pass: "PI:PASSWORD:<PASSWORD>END_PI" overleaf: host: @v1Url "uuid":v4:=>@uuid "request": @request "fs":@fs "../../../../app/js/models/Project": {Project: @Project} @zipUrl = "%2Ftemplates%2F52fb86a81ae1e566597a25f6%2Fv%2F4%2Fzip&templateName=Moderncv%20Banking&compiler=pdflatex" @templateName = "project name here" @user_id = "1234" @req = session: user: _id:@user_id templateData: zipUrl: @zipUrl templateName: @templateName @redirect = {} @AuthenticationController.getLoggedInUserId.returns(@user_id) describe 'v1Templates', -> it "should fetch zip from v1 based on template id", (done)-> @templateVersionId = 15 @req.body = {templateVersionId: @templateVersionId} redirect = => @request.calledWith("#{@v1Url}/api/v1/sharelatex/templates/#{@templateVersionId}").should.equal true done() res = redirect:redirect @controller.createProjectFromV1Template @req, res
[ { "context": "le code\n selfValue = {getItems: -> {'name': 'Bob', 'shortName': true}}\n method = aether.creat", "end": 5448, "score": 0.9988555908203125, "start": 5445, "tag": "NAME", "value": "Bob" }, { "context": "isPython and l._isPython\n return f({'p1': 'Bob'}, ...
test/python_spec.coffee
basicer/aether
0
Aether = require '../aether' describe "Python test suite", -> describe "Basics", -> aether = new Aether language: "python" it "return 1000", -> code = """ return 1000 """ aether.transpile(code) expect(aether.run()).toEqual 1000 it "simple if", -> code = """ if False: return 2000 return 1000 """ aether.transpile(code) expect(aether.run()).toBe(1000) it "multiple elif", -> code = """ x = 4 if x == 2: x += 1 return '2' elif x == 44564: x += 1 return '44564' elif x == 4: x += 1 return '4' """ aether.transpile(code) expect(aether.run()).toBe('4') it "mathmetics order", -> code = """ return (2*2 + 2/2 - 2*2/2) """ aether.transpile(code) expect(aether.run()).toBe(3) it "fibonacci function", -> code = """ def fib(n): if n < 2: return n else: return fib(n - 1) + fib(n - 2) chupacabra = fib(6) return chupacabra """ aether.transpile(code) expect(aether.run()).toBe(8) it "for loop", -> code = """ data = [4, 2, 65, 7] total = 0 for d in data: total += d return total """ aether.transpile(code) expect(aether.run()).toBe(78) it "bubble sort", -> code = """ import random def createShuffled(n): r = n * 10 + 1 shuffle = [] for i in range(n): item = int(r * random.random()) shuffle.append(item) return shuffle def bubbleSort(data): sorted = False while not sorted: sorted = True for i in range(len(data) - 1): if data[i] > data[i + 1]: t = data[i] data[i] = data[i + 1] data[i + 1] = t sorted = False return data def isSorted(data): for i in range(len(data) - 1): if data[i] > data[i + 1]: return False return True data = createShuffled(10) bubbleSort(data) return isSorted(data) """ aether.transpile(code) expect(aether.run()).toBe(true) it "dictionary", -> code = """ d = {'p1': 'prop1'} return d['p1'] """ aether.transpile(code) expect(aether.run()).toBe('prop1') it "class", -> code = """ class MyClass: i = 123 def __init__(self, i): self.i = i def f(self): return self.i x = MyClass(456) return x.f() """ aether.transpile(code) expect(aether.run()).toEqual(456) it "L[0:2]", -> code = """ L = [1, 45, 6, -9] return L[0:2] """ aether.transpile(code) expect(aether.run()).toEqual([1, 45]) it "L[f(2)::9 - (2 * 5)]", -> code = """ def f(x): return x L = [0, 1, 2, 3, 4] return L[f(2)::9 - (2 * 5)] """ aether.transpile(code) expect(aether.run()).toEqual([2, 1, 0]) it "T[-1:-3:-1]", -> code = """ T = (0, 1, 2, 3, 4) return T[-1:-3:-1] """ aether.transpile(code) expect(aether.run()).toEqual([4, 3]) it "[str(round(pi, i)) for i in range(1, 6)]", -> code = """ pi = 3.1415926 L = [str(round(pi, i)) for i in range(1, 6)] return L """ aether.transpile(code) expect(aether.run()).toEqual(['3.1', '3.14', '3.142', '3.1416', '3.14159']) it "[(x*2, y) for x in range(4) if x > 1 for y in range(2)]", -> code = """ L = [(x*2, y) for x in range(4) if x > 1 for y in range(2)] return L[1] """ aether.transpile(code) expect(aether.run()).toEqual([4, 1]) it "range(0, 10, 4)", -> code = """ return range(0, 10, 4) """ aether.transpile(code) expect(aether.run()).toEqual([0, 4, 8]) it "sequence operations", -> code = """ a = [1] b = a + [2] b *= 2 return b """ aether.transpile(code) expect(aether.run()).toEqual([1, 2, 1, 2]) it "default and keyword fn arguments", -> code = """ def f(a=4, b=7, c=10): return a + b + c return f(4, c=2, b=1) """ aether.transpile(code) expect(aether.run()).toEqual(7) it "*args and **kwargs", -> code = """ def f(x, y=5, z=8, *a, **b): return x + y + z + sum(a) + sum([b[k] for k in b]) return f(1, 2, 3, 4, 5, a=10, b=100) """ aether.transpile(code) expect(aether.run()).toEqual(125) it "Protected API returns Python list", -> code =""" items = self.getItems() if items._isPython: return items.count(3) return 'not a Python object' """ aether = new Aether language: "python", protectAPI: true aether.transpile code selfValue = {getItems: -> [3, 3, 4, 3, 5, 6, 3]} method = aether.createMethod selfValue expect(aether.run(method)).toEqual(4) it "Protected API returns Python dict", -> code =""" items = self.getItems() if items._isPython: return items.length return 'not a Python object' """ aether = new Aether language: "python", protectAPI: true aether.transpile code selfValue = {getItems: -> {'name': 'Bob', 'shortName': true}} method = aether.createMethod selfValue expect(aether.run(method)).toEqual(2) it "Pass Python arguments to inner functions", -> code =""" def f(d, l): return d._isPython and l._isPython return f({'p1': 'Bob'}, ['Python', 'is', 'fun.', True]) """ aether = new Aether language: "python", protectAPI: true aether.transpile code expect(aether.run()).toEqual(true) describe "Conflicts", -> it "doesn't interfere with type property", -> code = """ d = {'type': 'merino wool'} return d['type'] """ aether = new Aether language: "python", protectAPI: true aether.transpile(code) expect(aether.run()).toBe('merino wool') describe "Usage", -> it "self.doStuff via thisValue param", -> history = [] log = (s) -> history.push s moveDown = -> history.push 'moveDown' thisValue = {say: log, moveDown: moveDown} aetherOptions = { language: 'python' } aether = new Aether aetherOptions code = """ self.moveDown() self.say('hello') """ aether.transpile code method = aether.createMethod thisValue aether.run method expect(history).toEqual(['moveDown', 'hello']) it "Math is fun?", -> thisValue = {} aetherOptions = { language: 'python' } aether = new Aether aetherOptions code = """ return Math.abs(-3) == abs(-3) """ aether.transpile code method = aether.createMethod thisValue expect(aether.run(method)).toEqual(true) it "self.getItems()", -> history = [] getItems = -> [{'pos':1}, {'pos':4}, {'pos':3}, {'pos':5}] move = (i) -> history.push i thisValue = {getItems: getItems, move: move} aetherOptions = { language: 'python' } code = """ items = self.getItems() for item in items: self.move(item['pos']) """ aether = new Aether aetherOptions aether.transpile code method = aether.createMethod thisValue aether.run method expect(history).toEqual([1, 4, 3, 5]) describe "parseDammit! & Ranges", -> aether = new Aether language: "python" it "Bad indent", -> code = """ def fn(): x = 45 x += 5 return x return fn() """ aether.transpile(code) result = aether.run() expect(aether.problems.errors.length).toEqual(1) expect(/Unexpected indent/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 21, row : 2, col : 2 }, { ofs : 23, row : 2, col : 4 } ]) expect(result).toEqual(50) xit "Bad indent after comment", -> # https://github.com/codecombat/aether/issues/116 code = """ def fn(): x = 45 # Bummer x += 5 return x return fn() """ aether.transpile(code) result = aether.run() expect(aether.problems.errors.length).toEqual(1) expect(/Unexpected indent/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 32, row : 3, col : 2 }, { ofs : 34, row : 3, col : 4 } ]) expect(result).toEqual(50) it "Transpile error, missing )", -> code = """ def fn(): return 45 x = fn( return x """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(/Unexpected token/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 29, row : 2, col : 7 }, { ofs : 30, row : 2, col : 8 } ]) result = aether.run() expect(result).toEqual(45) it "Missing self: x() row 0", -> code = """x()""" aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.x`.") expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 3, row: 0, col: 3 } ]) it "Missing self: x() row 1", -> code = """ y = 5 x() """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.x`.") expect(aether.problems.errors[0].range).toEqual([ { ofs: 6, row: 1, col: 0 }, { ofs: 9, row: 1, col: 3 } ]) it "Missing self: x() row 3", -> code = """ y = 5 s = 'some other stuff' if y is 5: x() """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.x`.") expect(aether.problems.errors[0].range).toEqual([ { ofs: 42, row: 3, col: 2 }, { ofs: 45, row: 3, col: 5 } ]) it "self.getItems missing parentheses", -> code = """ self.getItems """ aether = new Aether language: 'python', problemContext: thisMethods: ['getItems'] aether.transpile code aether.run() expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual('self.getItems has no effect. It needs parentheses: self.getItems()') expect(aether.problems.errors[0].range).toEqual([ { ofs : 0, row : 0, col : 0 }, { ofs : 13, row : 0, col : 13 } ]) it "self.getItems missing parentheses row 1", -> code = """ x = 5 self.getItems """ aether = new Aether language: 'python', problemContext: thisMethods: ['getItems'] aether.transpile code aether.run() expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual('self.getItems has no effect. It needs parentheses: self.getItems()') expect(aether.problems.errors[0].range).toEqual([ { ofs : 6, row : 1, col : 0 }, { ofs : 19, row : 1, col : 13 } ]) it "Incomplete string", -> code = """ s = 'hi return s """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(/Unterminated string constant/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 4, row : 0, col : 4 }, { ofs : 7, row : 0, col : 7 } ]) result = aether.run() expect(result).toEqual('hi') it "Runtime ReferenceError", -> code = """ x = 5 y = x + z """ aether.transpile(code) aether.run() expect(aether.problems.errors.length).toEqual(1) expect(/ReferenceError/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 14, row : 1, col : 8 }, { ofs : 15, row : 1, col : 9 } ]) describe "Simple loop", -> it "loop:", -> code = """ total = 0 loop: total += 1 if total is 10: break; return total """ aether = new Aether language: "python", simpleLoops: true aether.transpile(code) expect(aether.run()).toEqual(10) xit "one line", -> # Blocked by https://github.com/differentmatt/filbert/issues/41 code = """ total = 0 loop: total += 12; break; return total """ aether = new Aether language: "python", simpleLoops: true aether.transpile(code) expect(aether.run()).toEqual(12) xit "loop :", -> # Blocked by https://github.com/codecombat/aether/issues/108 code = """ total = 0 loop : total += 23; break; return total """ aether = new Aether language: "python", simpleLoops: true aether.transpile(code) expect(aether.run()).toEqual(23) it "Conditional yielding", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ while True: self.slay(); break; loop: self.slay(); if self.getKillCount() >= 5: break; while True: self.slay(); break; """ aether.transpile code f = aether.createFunction() gen = f.apply dude for i in [1..6] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i expect(gen.next().done).toEqual true expect(dude.killCount).toEqual 6 it "Conditional yielding empty loop", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ x = 0 loop: x += 1 if x >= 3: break """ aether.transpile code f = aether.createFunction() gen = f.apply dude expect(gen.next().done).toEqual false expect(gen.next().done).toEqual false expect(gen.next().done).toEqual true it "Conditional yielding mixed loops", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ loop: self.slay() if self.getKillCount() >= 5: break x = 0 loop: x += 1 if x > 10: break loop: self.slay() if self.getKillCount() >= 15: break while True: self.slay() break """ aether.transpile code f = aether.createFunction() gen = f.apply dude for i in [1..5] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i for i in [1..10] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual 5 for i in [6..15] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i expect(gen.next().done).toEqual false expect(dude.killCount).toEqual 16 expect(gen.next().done).toEqual true expect(dude.killCount).toEqual 16 it "Conditional yielding nested loops", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ # outer auto yield, inner yield x = 0 loop: y = 0 loop: self.slay() y += 1 if y >= 2: break x += 1 if x >= 3: break # outer yield, inner auto yield x = 0 loop: self.slay() y = 0 loop: y += 1 if y >= 4: break x += 1 if x >= 5: break # outer and inner auto yield x = 0 loop: y = 0 loop: y += 1 if y >= 6: break x += 1 if x >= 7: break # outer and inner yields x = 0 loop: self.slay() y = 0 loop: self.slay() y += 1 if y >= 9: break x += 1 if x >= 8: break """ aether.transpile code f = aether.createFunction() gen = f.apply dude # NOTE: auto yield loops break before invisible automatic yield # outer auto yield, inner yield for i in [1..3] for j in [1..2] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual (i - 1) * 2 + j expect(gen.next().done).toEqual false if i < 3 expect(dude.killCount).toEqual 6 # outer yield, inner auto yield killOffset = dude.killCount for i in [1..5] for j in [1..3] expect(gen.next().done).toEqual false expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i + killOffset expect(dude.killCount).toEqual 6 + 5 # outer and inner auto yield killOffset = dude.killCount for i in [1..7] for j in [1..5] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual killOffset expect(gen.next().done).toEqual false if i < 7 expect(dude.killCount).toEqual 6 + 5 + 0 # outer and inner yields killOffset = dude.killCount for i in [1..8] expect(gen.next().done).toEqual false for j in [1..9] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual (i - 1) * 9 + i + j + killOffset expect(dude.killCount).toEqual 6 + 5 + 0 + 80 expect(gen.next().done).toEqual true expect(dude.killCount).toEqual 91 it "Empty loop", -> code = """ loop: x = 5 """ aether = new Aether language: "python", simpleLoops: true aether.transpile code expect(aether.problems.warnings.length).toEqual(1) expect(aether.problems.warnings[0].type).toEqual('transpile') expect(aether.problems.warnings[0].message).toEqual("Empty loop. Put 4 spaces in front of statements inside loops.") it "Empty if", -> code = """ if True: x = 5 """ aether = new Aether language: "python", simpleLoops: true aether.transpile code expect(aether.problems.warnings.length).toEqual(1) expect(aether.problems.warnings[0].type).toEqual('transpile') expect(aether.problems.warnings[0].message).toEqual("Empty if statement. Put 4 spaces in front of statements inside the if statement.") it "convertToNativeType", -> globals = foo: -> o = p1: 34, p2: 'Bob' Object.defineProperty o, 'health', value: 42 code = """ myObj = self.foo() return myObj.health """ aether = new Aether language: "python", simpleLoops: true, yieldConditionally: true aether.transpile code f = aether.createFunction() gen = f.apply globals result = gen.next() expect(aether.problems.errors.length).toEqual(0) expect(result.value).toEqual(42) # TODO: simple loop in a function # TODO: blocked by https://github.com/codecombat/aether/issues/48
110824
Aether = require '../aether' describe "Python test suite", -> describe "Basics", -> aether = new Aether language: "python" it "return 1000", -> code = """ return 1000 """ aether.transpile(code) expect(aether.run()).toEqual 1000 it "simple if", -> code = """ if False: return 2000 return 1000 """ aether.transpile(code) expect(aether.run()).toBe(1000) it "multiple elif", -> code = """ x = 4 if x == 2: x += 1 return '2' elif x == 44564: x += 1 return '44564' elif x == 4: x += 1 return '4' """ aether.transpile(code) expect(aether.run()).toBe('4') it "mathmetics order", -> code = """ return (2*2 + 2/2 - 2*2/2) """ aether.transpile(code) expect(aether.run()).toBe(3) it "fibonacci function", -> code = """ def fib(n): if n < 2: return n else: return fib(n - 1) + fib(n - 2) chupacabra = fib(6) return chupacabra """ aether.transpile(code) expect(aether.run()).toBe(8) it "for loop", -> code = """ data = [4, 2, 65, 7] total = 0 for d in data: total += d return total """ aether.transpile(code) expect(aether.run()).toBe(78) it "bubble sort", -> code = """ import random def createShuffled(n): r = n * 10 + 1 shuffle = [] for i in range(n): item = int(r * random.random()) shuffle.append(item) return shuffle def bubbleSort(data): sorted = False while not sorted: sorted = True for i in range(len(data) - 1): if data[i] > data[i + 1]: t = data[i] data[i] = data[i + 1] data[i + 1] = t sorted = False return data def isSorted(data): for i in range(len(data) - 1): if data[i] > data[i + 1]: return False return True data = createShuffled(10) bubbleSort(data) return isSorted(data) """ aether.transpile(code) expect(aether.run()).toBe(true) it "dictionary", -> code = """ d = {'p1': 'prop1'} return d['p1'] """ aether.transpile(code) expect(aether.run()).toBe('prop1') it "class", -> code = """ class MyClass: i = 123 def __init__(self, i): self.i = i def f(self): return self.i x = MyClass(456) return x.f() """ aether.transpile(code) expect(aether.run()).toEqual(456) it "L[0:2]", -> code = """ L = [1, 45, 6, -9] return L[0:2] """ aether.transpile(code) expect(aether.run()).toEqual([1, 45]) it "L[f(2)::9 - (2 * 5)]", -> code = """ def f(x): return x L = [0, 1, 2, 3, 4] return L[f(2)::9 - (2 * 5)] """ aether.transpile(code) expect(aether.run()).toEqual([2, 1, 0]) it "T[-1:-3:-1]", -> code = """ T = (0, 1, 2, 3, 4) return T[-1:-3:-1] """ aether.transpile(code) expect(aether.run()).toEqual([4, 3]) it "[str(round(pi, i)) for i in range(1, 6)]", -> code = """ pi = 3.1415926 L = [str(round(pi, i)) for i in range(1, 6)] return L """ aether.transpile(code) expect(aether.run()).toEqual(['3.1', '3.14', '3.142', '3.1416', '3.14159']) it "[(x*2, y) for x in range(4) if x > 1 for y in range(2)]", -> code = """ L = [(x*2, y) for x in range(4) if x > 1 for y in range(2)] return L[1] """ aether.transpile(code) expect(aether.run()).toEqual([4, 1]) it "range(0, 10, 4)", -> code = """ return range(0, 10, 4) """ aether.transpile(code) expect(aether.run()).toEqual([0, 4, 8]) it "sequence operations", -> code = """ a = [1] b = a + [2] b *= 2 return b """ aether.transpile(code) expect(aether.run()).toEqual([1, 2, 1, 2]) it "default and keyword fn arguments", -> code = """ def f(a=4, b=7, c=10): return a + b + c return f(4, c=2, b=1) """ aether.transpile(code) expect(aether.run()).toEqual(7) it "*args and **kwargs", -> code = """ def f(x, y=5, z=8, *a, **b): return x + y + z + sum(a) + sum([b[k] for k in b]) return f(1, 2, 3, 4, 5, a=10, b=100) """ aether.transpile(code) expect(aether.run()).toEqual(125) it "Protected API returns Python list", -> code =""" items = self.getItems() if items._isPython: return items.count(3) return 'not a Python object' """ aether = new Aether language: "python", protectAPI: true aether.transpile code selfValue = {getItems: -> [3, 3, 4, 3, 5, 6, 3]} method = aether.createMethod selfValue expect(aether.run(method)).toEqual(4) it "Protected API returns Python dict", -> code =""" items = self.getItems() if items._isPython: return items.length return 'not a Python object' """ aether = new Aether language: "python", protectAPI: true aether.transpile code selfValue = {getItems: -> {'name': '<NAME>', 'shortName': true}} method = aether.createMethod selfValue expect(aether.run(method)).toEqual(2) it "Pass Python arguments to inner functions", -> code =""" def f(d, l): return d._isPython and l._isPython return f({'p1': '<NAME>'}, ['Python', 'is', 'fun.', True]) """ aether = new Aether language: "python", protectAPI: true aether.transpile code expect(aether.run()).toEqual(true) describe "Conflicts", -> it "doesn't interfere with type property", -> code = """ d = {'type': 'merino wool'} return d['type'] """ aether = new Aether language: "python", protectAPI: true aether.transpile(code) expect(aether.run()).toBe('merino wool') describe "Usage", -> it "self.doStuff via thisValue param", -> history = [] log = (s) -> history.push s moveDown = -> history.push 'moveDown' thisValue = {say: log, moveDown: moveDown} aetherOptions = { language: 'python' } aether = new Aether aetherOptions code = """ self.moveDown() self.say('hello') """ aether.transpile code method = aether.createMethod thisValue aether.run method expect(history).toEqual(['moveDown', 'hello']) it "Math is fun?", -> thisValue = {} aetherOptions = { language: 'python' } aether = new Aether aetherOptions code = """ return Math.abs(-3) == abs(-3) """ aether.transpile code method = aether.createMethod thisValue expect(aether.run(method)).toEqual(true) it "self.getItems()", -> history = [] getItems = -> [{'pos':1}, {'pos':4}, {'pos':3}, {'pos':5}] move = (i) -> history.push i thisValue = {getItems: getItems, move: move} aetherOptions = { language: 'python' } code = """ items = self.getItems() for item in items: self.move(item['pos']) """ aether = new Aether aetherOptions aether.transpile code method = aether.createMethod thisValue aether.run method expect(history).toEqual([1, 4, 3, 5]) describe "parseDammit! & Ranges", -> aether = new Aether language: "python" it "Bad indent", -> code = """ def fn(): x = 45 x += 5 return x return fn() """ aether.transpile(code) result = aether.run() expect(aether.problems.errors.length).toEqual(1) expect(/Unexpected indent/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 21, row : 2, col : 2 }, { ofs : 23, row : 2, col : 4 } ]) expect(result).toEqual(50) xit "Bad indent after comment", -> # https://github.com/codecombat/aether/issues/116 code = """ def fn(): x = 45 # Bummer x += 5 return x return fn() """ aether.transpile(code) result = aether.run() expect(aether.problems.errors.length).toEqual(1) expect(/Unexpected indent/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 32, row : 3, col : 2 }, { ofs : 34, row : 3, col : 4 } ]) expect(result).toEqual(50) it "Transpile error, missing )", -> code = """ def fn(): return 45 x = fn( return x """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(/Unexpected token/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 29, row : 2, col : 7 }, { ofs : 30, row : 2, col : 8 } ]) result = aether.run() expect(result).toEqual(45) it "Missing self: x() row 0", -> code = """x()""" aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.x`.") expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 3, row: 0, col: 3 } ]) it "Missing self: x() row 1", -> code = """ y = 5 x() """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.x`.") expect(aether.problems.errors[0].range).toEqual([ { ofs: 6, row: 1, col: 0 }, { ofs: 9, row: 1, col: 3 } ]) it "Missing self: x() row 3", -> code = """ y = 5 s = 'some other stuff' if y is 5: x() """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.x`.") expect(aether.problems.errors[0].range).toEqual([ { ofs: 42, row: 3, col: 2 }, { ofs: 45, row: 3, col: 5 } ]) it "self.getItems missing parentheses", -> code = """ self.getItems """ aether = new Aether language: 'python', problemContext: thisMethods: ['getItems'] aether.transpile code aether.run() expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual('self.getItems has no effect. It needs parentheses: self.getItems()') expect(aether.problems.errors[0].range).toEqual([ { ofs : 0, row : 0, col : 0 }, { ofs : 13, row : 0, col : 13 } ]) it "self.getItems missing parentheses row 1", -> code = """ x = 5 self.getItems """ aether = new Aether language: 'python', problemContext: thisMethods: ['getItems'] aether.transpile code aether.run() expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual('self.getItems has no effect. It needs parentheses: self.getItems()') expect(aether.problems.errors[0].range).toEqual([ { ofs : 6, row : 1, col : 0 }, { ofs : 19, row : 1, col : 13 } ]) it "Incomplete string", -> code = """ s = 'hi return s """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(/Unterminated string constant/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 4, row : 0, col : 4 }, { ofs : 7, row : 0, col : 7 } ]) result = aether.run() expect(result).toEqual('hi') it "Runtime ReferenceError", -> code = """ x = 5 y = x + z """ aether.transpile(code) aether.run() expect(aether.problems.errors.length).toEqual(1) expect(/ReferenceError/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 14, row : 1, col : 8 }, { ofs : 15, row : 1, col : 9 } ]) describe "Simple loop", -> it "loop:", -> code = """ total = 0 loop: total += 1 if total is 10: break; return total """ aether = new Aether language: "python", simpleLoops: true aether.transpile(code) expect(aether.run()).toEqual(10) xit "one line", -> # Blocked by https://github.com/differentmatt/filbert/issues/41 code = """ total = 0 loop: total += 12; break; return total """ aether = new Aether language: "python", simpleLoops: true aether.transpile(code) expect(aether.run()).toEqual(12) xit "loop :", -> # Blocked by https://github.com/codecombat/aether/issues/108 code = """ total = 0 loop : total += 23; break; return total """ aether = new Aether language: "python", simpleLoops: true aether.transpile(code) expect(aether.run()).toEqual(23) it "Conditional yielding", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ while True: self.slay(); break; loop: self.slay(); if self.getKillCount() >= 5: break; while True: self.slay(); break; """ aether.transpile code f = aether.createFunction() gen = f.apply dude for i in [1..6] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i expect(gen.next().done).toEqual true expect(dude.killCount).toEqual 6 it "Conditional yielding empty loop", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ x = 0 loop: x += 1 if x >= 3: break """ aether.transpile code f = aether.createFunction() gen = f.apply dude expect(gen.next().done).toEqual false expect(gen.next().done).toEqual false expect(gen.next().done).toEqual true it "Conditional yielding mixed loops", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ loop: self.slay() if self.getKillCount() >= 5: break x = 0 loop: x += 1 if x > 10: break loop: self.slay() if self.getKillCount() >= 15: break while True: self.slay() break """ aether.transpile code f = aether.createFunction() gen = f.apply dude for i in [1..5] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i for i in [1..10] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual 5 for i in [6..15] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i expect(gen.next().done).toEqual false expect(dude.killCount).toEqual 16 expect(gen.next().done).toEqual true expect(dude.killCount).toEqual 16 it "Conditional yielding nested loops", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ # outer auto yield, inner yield x = 0 loop: y = 0 loop: self.slay() y += 1 if y >= 2: break x += 1 if x >= 3: break # outer yield, inner auto yield x = 0 loop: self.slay() y = 0 loop: y += 1 if y >= 4: break x += 1 if x >= 5: break # outer and inner auto yield x = 0 loop: y = 0 loop: y += 1 if y >= 6: break x += 1 if x >= 7: break # outer and inner yields x = 0 loop: self.slay() y = 0 loop: self.slay() y += 1 if y >= 9: break x += 1 if x >= 8: break """ aether.transpile code f = aether.createFunction() gen = f.apply dude # NOTE: auto yield loops break before invisible automatic yield # outer auto yield, inner yield for i in [1..3] for j in [1..2] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual (i - 1) * 2 + j expect(gen.next().done).toEqual false if i < 3 expect(dude.killCount).toEqual 6 # outer yield, inner auto yield killOffset = dude.killCount for i in [1..5] for j in [1..3] expect(gen.next().done).toEqual false expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i + killOffset expect(dude.killCount).toEqual 6 + 5 # outer and inner auto yield killOffset = dude.killCount for i in [1..7] for j in [1..5] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual killOffset expect(gen.next().done).toEqual false if i < 7 expect(dude.killCount).toEqual 6 + 5 + 0 # outer and inner yields killOffset = dude.killCount for i in [1..8] expect(gen.next().done).toEqual false for j in [1..9] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual (i - 1) * 9 + i + j + killOffset expect(dude.killCount).toEqual 6 + 5 + 0 + 80 expect(gen.next().done).toEqual true expect(dude.killCount).toEqual 91 it "Empty loop", -> code = """ loop: x = 5 """ aether = new Aether language: "python", simpleLoops: true aether.transpile code expect(aether.problems.warnings.length).toEqual(1) expect(aether.problems.warnings[0].type).toEqual('transpile') expect(aether.problems.warnings[0].message).toEqual("Empty loop. Put 4 spaces in front of statements inside loops.") it "Empty if", -> code = """ if True: x = 5 """ aether = new Aether language: "python", simpleLoops: true aether.transpile code expect(aether.problems.warnings.length).toEqual(1) expect(aether.problems.warnings[0].type).toEqual('transpile') expect(aether.problems.warnings[0].message).toEqual("Empty if statement. Put 4 spaces in front of statements inside the if statement.") it "convertToNativeType", -> globals = foo: -> o = p1: 34, p2: '<NAME>' Object.defineProperty o, 'health', value: 42 code = """ myObj = self.foo() return myObj.health """ aether = new Aether language: "python", simpleLoops: true, yieldConditionally: true aether.transpile code f = aether.createFunction() gen = f.apply globals result = gen.next() expect(aether.problems.errors.length).toEqual(0) expect(result.value).toEqual(42) # TODO: simple loop in a function # TODO: blocked by https://github.com/codecombat/aether/issues/48
true
Aether = require '../aether' describe "Python test suite", -> describe "Basics", -> aether = new Aether language: "python" it "return 1000", -> code = """ return 1000 """ aether.transpile(code) expect(aether.run()).toEqual 1000 it "simple if", -> code = """ if False: return 2000 return 1000 """ aether.transpile(code) expect(aether.run()).toBe(1000) it "multiple elif", -> code = """ x = 4 if x == 2: x += 1 return '2' elif x == 44564: x += 1 return '44564' elif x == 4: x += 1 return '4' """ aether.transpile(code) expect(aether.run()).toBe('4') it "mathmetics order", -> code = """ return (2*2 + 2/2 - 2*2/2) """ aether.transpile(code) expect(aether.run()).toBe(3) it "fibonacci function", -> code = """ def fib(n): if n < 2: return n else: return fib(n - 1) + fib(n - 2) chupacabra = fib(6) return chupacabra """ aether.transpile(code) expect(aether.run()).toBe(8) it "for loop", -> code = """ data = [4, 2, 65, 7] total = 0 for d in data: total += d return total """ aether.transpile(code) expect(aether.run()).toBe(78) it "bubble sort", -> code = """ import random def createShuffled(n): r = n * 10 + 1 shuffle = [] for i in range(n): item = int(r * random.random()) shuffle.append(item) return shuffle def bubbleSort(data): sorted = False while not sorted: sorted = True for i in range(len(data) - 1): if data[i] > data[i + 1]: t = data[i] data[i] = data[i + 1] data[i + 1] = t sorted = False return data def isSorted(data): for i in range(len(data) - 1): if data[i] > data[i + 1]: return False return True data = createShuffled(10) bubbleSort(data) return isSorted(data) """ aether.transpile(code) expect(aether.run()).toBe(true) it "dictionary", -> code = """ d = {'p1': 'prop1'} return d['p1'] """ aether.transpile(code) expect(aether.run()).toBe('prop1') it "class", -> code = """ class MyClass: i = 123 def __init__(self, i): self.i = i def f(self): return self.i x = MyClass(456) return x.f() """ aether.transpile(code) expect(aether.run()).toEqual(456) it "L[0:2]", -> code = """ L = [1, 45, 6, -9] return L[0:2] """ aether.transpile(code) expect(aether.run()).toEqual([1, 45]) it "L[f(2)::9 - (2 * 5)]", -> code = """ def f(x): return x L = [0, 1, 2, 3, 4] return L[f(2)::9 - (2 * 5)] """ aether.transpile(code) expect(aether.run()).toEqual([2, 1, 0]) it "T[-1:-3:-1]", -> code = """ T = (0, 1, 2, 3, 4) return T[-1:-3:-1] """ aether.transpile(code) expect(aether.run()).toEqual([4, 3]) it "[str(round(pi, i)) for i in range(1, 6)]", -> code = """ pi = 3.1415926 L = [str(round(pi, i)) for i in range(1, 6)] return L """ aether.transpile(code) expect(aether.run()).toEqual(['3.1', '3.14', '3.142', '3.1416', '3.14159']) it "[(x*2, y) for x in range(4) if x > 1 for y in range(2)]", -> code = """ L = [(x*2, y) for x in range(4) if x > 1 for y in range(2)] return L[1] """ aether.transpile(code) expect(aether.run()).toEqual([4, 1]) it "range(0, 10, 4)", -> code = """ return range(0, 10, 4) """ aether.transpile(code) expect(aether.run()).toEqual([0, 4, 8]) it "sequence operations", -> code = """ a = [1] b = a + [2] b *= 2 return b """ aether.transpile(code) expect(aether.run()).toEqual([1, 2, 1, 2]) it "default and keyword fn arguments", -> code = """ def f(a=4, b=7, c=10): return a + b + c return f(4, c=2, b=1) """ aether.transpile(code) expect(aether.run()).toEqual(7) it "*args and **kwargs", -> code = """ def f(x, y=5, z=8, *a, **b): return x + y + z + sum(a) + sum([b[k] for k in b]) return f(1, 2, 3, 4, 5, a=10, b=100) """ aether.transpile(code) expect(aether.run()).toEqual(125) it "Protected API returns Python list", -> code =""" items = self.getItems() if items._isPython: return items.count(3) return 'not a Python object' """ aether = new Aether language: "python", protectAPI: true aether.transpile code selfValue = {getItems: -> [3, 3, 4, 3, 5, 6, 3]} method = aether.createMethod selfValue expect(aether.run(method)).toEqual(4) it "Protected API returns Python dict", -> code =""" items = self.getItems() if items._isPython: return items.length return 'not a Python object' """ aether = new Aether language: "python", protectAPI: true aether.transpile code selfValue = {getItems: -> {'name': 'PI:NAME:<NAME>END_PI', 'shortName': true}} method = aether.createMethod selfValue expect(aether.run(method)).toEqual(2) it "Pass Python arguments to inner functions", -> code =""" def f(d, l): return d._isPython and l._isPython return f({'p1': 'PI:NAME:<NAME>END_PI'}, ['Python', 'is', 'fun.', True]) """ aether = new Aether language: "python", protectAPI: true aether.transpile code expect(aether.run()).toEqual(true) describe "Conflicts", -> it "doesn't interfere with type property", -> code = """ d = {'type': 'merino wool'} return d['type'] """ aether = new Aether language: "python", protectAPI: true aether.transpile(code) expect(aether.run()).toBe('merino wool') describe "Usage", -> it "self.doStuff via thisValue param", -> history = [] log = (s) -> history.push s moveDown = -> history.push 'moveDown' thisValue = {say: log, moveDown: moveDown} aetherOptions = { language: 'python' } aether = new Aether aetherOptions code = """ self.moveDown() self.say('hello') """ aether.transpile code method = aether.createMethod thisValue aether.run method expect(history).toEqual(['moveDown', 'hello']) it "Math is fun?", -> thisValue = {} aetherOptions = { language: 'python' } aether = new Aether aetherOptions code = """ return Math.abs(-3) == abs(-3) """ aether.transpile code method = aether.createMethod thisValue expect(aether.run(method)).toEqual(true) it "self.getItems()", -> history = [] getItems = -> [{'pos':1}, {'pos':4}, {'pos':3}, {'pos':5}] move = (i) -> history.push i thisValue = {getItems: getItems, move: move} aetherOptions = { language: 'python' } code = """ items = self.getItems() for item in items: self.move(item['pos']) """ aether = new Aether aetherOptions aether.transpile code method = aether.createMethod thisValue aether.run method expect(history).toEqual([1, 4, 3, 5]) describe "parseDammit! & Ranges", -> aether = new Aether language: "python" it "Bad indent", -> code = """ def fn(): x = 45 x += 5 return x return fn() """ aether.transpile(code) result = aether.run() expect(aether.problems.errors.length).toEqual(1) expect(/Unexpected indent/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 21, row : 2, col : 2 }, { ofs : 23, row : 2, col : 4 } ]) expect(result).toEqual(50) xit "Bad indent after comment", -> # https://github.com/codecombat/aether/issues/116 code = """ def fn(): x = 45 # Bummer x += 5 return x return fn() """ aether.transpile(code) result = aether.run() expect(aether.problems.errors.length).toEqual(1) expect(/Unexpected indent/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 32, row : 3, col : 2 }, { ofs : 34, row : 3, col : 4 } ]) expect(result).toEqual(50) it "Transpile error, missing )", -> code = """ def fn(): return 45 x = fn( return x """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(/Unexpected token/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 29, row : 2, col : 7 }, { ofs : 30, row : 2, col : 8 } ]) result = aether.run() expect(result).toEqual(45) it "Missing self: x() row 0", -> code = """x()""" aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.x`.") expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 3, row: 0, col: 3 } ]) it "Missing self: x() row 1", -> code = """ y = 5 x() """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.x`.") expect(aether.problems.errors[0].range).toEqual([ { ofs: 6, row: 1, col: 0 }, { ofs: 9, row: 1, col: 3 } ]) it "Missing self: x() row 3", -> code = """ y = 5 s = 'some other stuff' if y is 5: x() """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.x`.") expect(aether.problems.errors[0].range).toEqual([ { ofs: 42, row: 3, col: 2 }, { ofs: 45, row: 3, col: 5 } ]) it "self.getItems missing parentheses", -> code = """ self.getItems """ aether = new Aether language: 'python', problemContext: thisMethods: ['getItems'] aether.transpile code aether.run() expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual('self.getItems has no effect. It needs parentheses: self.getItems()') expect(aether.problems.errors[0].range).toEqual([ { ofs : 0, row : 0, col : 0 }, { ofs : 13, row : 0, col : 13 } ]) it "self.getItems missing parentheses row 1", -> code = """ x = 5 self.getItems """ aether = new Aether language: 'python', problemContext: thisMethods: ['getItems'] aether.transpile code aether.run() expect(aether.problems.errors.length).toEqual(1) expect(aether.problems.errors[0].message).toEqual('self.getItems has no effect. It needs parentheses: self.getItems()') expect(aether.problems.errors[0].range).toEqual([ { ofs : 6, row : 1, col : 0 }, { ofs : 19, row : 1, col : 13 } ]) it "Incomplete string", -> code = """ s = 'hi return s """ aether.transpile(code) expect(aether.problems.errors.length).toEqual(1) expect(/Unterminated string constant/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 4, row : 0, col : 4 }, { ofs : 7, row : 0, col : 7 } ]) result = aether.run() expect(result).toEqual('hi') it "Runtime ReferenceError", -> code = """ x = 5 y = x + z """ aether.transpile(code) aether.run() expect(aether.problems.errors.length).toEqual(1) expect(/ReferenceError/.test(aether.problems.errors[0].message)).toBe(true) expect(aether.problems.errors[0].range).toEqual([ { ofs : 14, row : 1, col : 8 }, { ofs : 15, row : 1, col : 9 } ]) describe "Simple loop", -> it "loop:", -> code = """ total = 0 loop: total += 1 if total is 10: break; return total """ aether = new Aether language: "python", simpleLoops: true aether.transpile(code) expect(aether.run()).toEqual(10) xit "one line", -> # Blocked by https://github.com/differentmatt/filbert/issues/41 code = """ total = 0 loop: total += 12; break; return total """ aether = new Aether language: "python", simpleLoops: true aether.transpile(code) expect(aether.run()).toEqual(12) xit "loop :", -> # Blocked by https://github.com/codecombat/aether/issues/108 code = """ total = 0 loop : total += 23; break; return total """ aether = new Aether language: "python", simpleLoops: true aether.transpile(code) expect(aether.run()).toEqual(23) it "Conditional yielding", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ while True: self.slay(); break; loop: self.slay(); if self.getKillCount() >= 5: break; while True: self.slay(); break; """ aether.transpile code f = aether.createFunction() gen = f.apply dude for i in [1..6] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i expect(gen.next().done).toEqual true expect(dude.killCount).toEqual 6 it "Conditional yielding empty loop", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ x = 0 loop: x += 1 if x >= 3: break """ aether.transpile code f = aether.createFunction() gen = f.apply dude expect(gen.next().done).toEqual false expect(gen.next().done).toEqual false expect(gen.next().done).toEqual true it "Conditional yielding mixed loops", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ loop: self.slay() if self.getKillCount() >= 5: break x = 0 loop: x += 1 if x > 10: break loop: self.slay() if self.getKillCount() >= 15: break while True: self.slay() break """ aether.transpile code f = aether.createFunction() gen = f.apply dude for i in [1..5] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i for i in [1..10] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual 5 for i in [6..15] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i expect(gen.next().done).toEqual false expect(dude.killCount).toEqual 16 expect(gen.next().done).toEqual true expect(dude.killCount).toEqual 16 it "Conditional yielding nested loops", -> aether = new Aether language: "python", yieldConditionally: true, simpleLoops: true dude = killCount: 0 slay: -> @killCount += 1 aether._shouldYield = true getKillCount: -> return @killCount code = """ # outer auto yield, inner yield x = 0 loop: y = 0 loop: self.slay() y += 1 if y >= 2: break x += 1 if x >= 3: break # outer yield, inner auto yield x = 0 loop: self.slay() y = 0 loop: y += 1 if y >= 4: break x += 1 if x >= 5: break # outer and inner auto yield x = 0 loop: y = 0 loop: y += 1 if y >= 6: break x += 1 if x >= 7: break # outer and inner yields x = 0 loop: self.slay() y = 0 loop: self.slay() y += 1 if y >= 9: break x += 1 if x >= 8: break """ aether.transpile code f = aether.createFunction() gen = f.apply dude # NOTE: auto yield loops break before invisible automatic yield # outer auto yield, inner yield for i in [1..3] for j in [1..2] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual (i - 1) * 2 + j expect(gen.next().done).toEqual false if i < 3 expect(dude.killCount).toEqual 6 # outer yield, inner auto yield killOffset = dude.killCount for i in [1..5] for j in [1..3] expect(gen.next().done).toEqual false expect(gen.next().done).toEqual false expect(dude.killCount).toEqual i + killOffset expect(dude.killCount).toEqual 6 + 5 # outer and inner auto yield killOffset = dude.killCount for i in [1..7] for j in [1..5] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual killOffset expect(gen.next().done).toEqual false if i < 7 expect(dude.killCount).toEqual 6 + 5 + 0 # outer and inner yields killOffset = dude.killCount for i in [1..8] expect(gen.next().done).toEqual false for j in [1..9] expect(gen.next().done).toEqual false expect(dude.killCount).toEqual (i - 1) * 9 + i + j + killOffset expect(dude.killCount).toEqual 6 + 5 + 0 + 80 expect(gen.next().done).toEqual true expect(dude.killCount).toEqual 91 it "Empty loop", -> code = """ loop: x = 5 """ aether = new Aether language: "python", simpleLoops: true aether.transpile code expect(aether.problems.warnings.length).toEqual(1) expect(aether.problems.warnings[0].type).toEqual('transpile') expect(aether.problems.warnings[0].message).toEqual("Empty loop. Put 4 spaces in front of statements inside loops.") it "Empty if", -> code = """ if True: x = 5 """ aether = new Aether language: "python", simpleLoops: true aether.transpile code expect(aether.problems.warnings.length).toEqual(1) expect(aether.problems.warnings[0].type).toEqual('transpile') expect(aether.problems.warnings[0].message).toEqual("Empty if statement. Put 4 spaces in front of statements inside the if statement.") it "convertToNativeType", -> globals = foo: -> o = p1: 34, p2: 'PI:NAME:<NAME>END_PI' Object.defineProperty o, 'health', value: 42 code = """ myObj = self.foo() return myObj.health """ aether = new Aether language: "python", simpleLoops: true, yieldConditionally: true aether.transpile code f = aether.createFunction() gen = f.apply globals result = gen.next() expect(aether.problems.errors.length).toEqual(0) expect(result.value).toEqual(42) # TODO: simple loop in a function # TODO: blocked by https://github.com/codecombat/aether/issues/48
[ { "context": "-> 'com.example.bank'\n creds = m -> username: 'myname123', password: 'smurf32'\n options = m -> {}\n\n de", "end": 355, "score": 0.9994099736213684, "start": 346, "tag": "USERNAME", "value": "myname123" }, { "context": " creds = m -> username: 'myname123', pas...
spec/wesabe/download/Job_spec.coffee
wesabe/ssu
28
Job = require 'download/Job' # small utility to memoize a function m = (generator) -> result = null -> result ||= generator() describe 'Job', -> job = id = fid = creds = options = null beforeEach -> job = m -> new Job id(), fid(), creds(), options() id = m -> null fid = m -> 'com.example.bank' creds = m -> username: 'myname123', password: 'smurf32' options = m -> {} describe 'defaults', -> it 'has status=202', -> expect(job().status).toEqual(202) it 'is not done', -> expect(job().done).toBeFalsy() it 'is at version=0', -> expect(job().version).toEqual(0) it 'has a single goal: "statements"', -> expect(job().options.goals).toEqual(['statements']) it 'does not set the "since" option', -> expect(job().since?).toBeFalsy() it 'generates a UUID as its id', -> expect(job().id).toMatch(/[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}/) describe '#done', -> it 'is true when status is not 202', -> job().status = 200 expect(job().done).toBeTruthy() describe 'given a specific id', -> beforeEach -> id = m -> '1D99213B-BD5E-0001-FFFF-1FFF1FFF1FFF' it 'uses that id instead of generating its own', -> expect(job().id).toEqual(id())
7143
Job = require 'download/Job' # small utility to memoize a function m = (generator) -> result = null -> result ||= generator() describe 'Job', -> job = id = fid = creds = options = null beforeEach -> job = m -> new Job id(), fid(), creds(), options() id = m -> null fid = m -> 'com.example.bank' creds = m -> username: 'myname123', password: '<PASSWORD>' options = m -> {} describe 'defaults', -> it 'has status=202', -> expect(job().status).toEqual(202) it 'is not done', -> expect(job().done).toBeFalsy() it 'is at version=0', -> expect(job().version).toEqual(0) it 'has a single goal: "statements"', -> expect(job().options.goals).toEqual(['statements']) it 'does not set the "since" option', -> expect(job().since?).toBeFalsy() it 'generates a UUID as its id', -> expect(job().id).toMatch(/[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}/) describe '#done', -> it 'is true when status is not 202', -> job().status = 200 expect(job().done).toBeTruthy() describe 'given a specific id', -> beforeEach -> id = m -> '1D99213B-BD5E-0001-FFFF-1FFF1FFF1FFF' it 'uses that id instead of generating its own', -> expect(job().id).toEqual(id())
true
Job = require 'download/Job' # small utility to memoize a function m = (generator) -> result = null -> result ||= generator() describe 'Job', -> job = id = fid = creds = options = null beforeEach -> job = m -> new Job id(), fid(), creds(), options() id = m -> null fid = m -> 'com.example.bank' creds = m -> username: 'myname123', password: 'PI:PASSWORD:<PASSWORD>END_PI' options = m -> {} describe 'defaults', -> it 'has status=202', -> expect(job().status).toEqual(202) it 'is not done', -> expect(job().done).toBeFalsy() it 'is at version=0', -> expect(job().version).toEqual(0) it 'has a single goal: "statements"', -> expect(job().options.goals).toEqual(['statements']) it 'does not set the "since" option', -> expect(job().since?).toBeFalsy() it 'generates a UUID as its id', -> expect(job().id).toMatch(/[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}/) describe '#done', -> it 'is true when status is not 202', -> job().status = 200 expect(job().done).toBeTruthy() describe 'given a specific id', -> beforeEach -> id = m -> '1D99213B-BD5E-0001-FFFF-1FFF1FFF1FFF' it 'uses that id instead of generating its own', -> expect(job().id).toEqual(id())
[ { "context": "##########\n\n # See:\n # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/lib/sche", "end": 1701, "score": 0.9996687769889832, "start": 1692, "tag": "USERNAME", "value": "jrwdunham" }, { "context": "/schemata.py#L846-L854\n # - https://g...
app/scripts/models/search.coffee
OpenSourceFieldlinguistics/dative
7
define [ './resource' './form' ], (ResourceModel, FormModel) -> # Search Model # --------------- # # A Backbone model for Dative searches. class SearchModel extends ResourceModel resourceName: 'search' # Change some or all of the following four attributes if this search model # is being used to search over a resource other than forms, e.g., over file # resources. targetResourceName: 'form' targetResourcePrimaryAttribute: 'transcription' targetModelClass: FormModel # This may need to be overridden when this SearchModel is used to search # over models that don't have "id" as their primary key, e.g., OLD # languages which have the ISO 639-3 "Id" as their primary key. targetResourcePrimaryKey: 'id' getTargetResourceNameCapitalized: -> @utils.capitalize @targetResourceName serverSideResourceName: 'formsearches' initialize: (attributes, options) -> super attributes, options @targetResourceNameCapitalized = @getTargetResourceNameCapitalized() @targetResourceNamePlural = @utils.pluralize @targetResourceName @targetResourceNamePluralCapitalized = @utils.capitalize @targetResourceNamePlural editableAttributes: [ 'name' 'description' 'search' ] manyToOneAttributes: [] manyToManyAttributes: [] getValidator: (attribute) -> switch attribute when 'name' then @requiredString else null ############################################################################ # Search Schema ############################################################################ # See: # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/lib/schemata.py#L846-L854 # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/model/formsearch.py # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/model/model.py defaults: -> name: '' # required, unique among search names, max 255 chars description: '' # string description search: filter: [ @getTargetResourceNameCapitalized() @targetResourcePrimaryAttribute 'regex' '' ] order_by: [ @getTargetResourceNameCapitalized() @targetResourcePrimaryKey 'asc' ] # Attributes that the OLD sends to us, but which the OLD will ignore if # we try to send them back. id: null # An integer relational id enterer: null # an object (attributes: `id`, `first_name`, # `last_name`, `role`) datetime_modified: "" # <string> (datetime search was last modified, # format and construction same as # `datetime_entered`.) # We listen to this once so that we can add the result of calling GET # /<target_resource_plural>/new_search to the result of calling GET # /formsearches/new. getNewTargetResourceSearchDataSuccess: (newSearchData) -> key = "#{@targetResourceName}_search_parameters" @searchNewData[key] = newSearchData.search_parameters @trigger "getNew#{@resourceNameCapitalized}DataSuccess", @searchNewData # We listen to this once so that we can tell the user that the request to # GET /<target_resource_plural>/new_search failed. getNewTargetResourceSearchDataFail: -> @trigger "getNew#{@resourceNameCapitalized}DataFail", "Error in GET request to OLD server for /#{@targetResourceNamePlural}/new_search" # Get the data necessary to create a new search over <target_resource> # objects. Note: this is an override of the base `ResourceModel`'s # implementation of this method since here we need to also request GET # /<target_resource_plural>/new_search. We do this by first requesting GET # /formsearches/new and then, if that's successful, requesting GET # /<target_resource_plural>/new_search. If that's successful, we trigger # the standard Backbone-wide success event for this method, passing in an # integrated/extended object. getNewResourceData: -> @trigger "getNew#{@resourceNameCapitalized}DataStart" @constructor.cors.request( method: 'GET' url: "#{@getOLDURL()}/#{@getServerSideResourceName()}/new" onload: (responseJSON, xhr) => @trigger "getNew#{@resourceNameCapitalized}DataEnd" if xhr.status is 200 @searchNewData = responseJSON ourTargetModel = new @targetModelClass() @listenToOnce(ourTargetModel, "getNew#{@targetResourceNameCapitalized}SearchDataSuccess", @getNewTargetResourceSearchDataSuccess) @listenToOnce(ourTargetModel, "getNew#{@targetResourceNameCapitalized}SearchDataFail", @getNewTargetResourceSearchDataFail) ourTargetModel.getNewSearchData() else @trigger "getNew#{@resourceNameCapitalized}DataFail", "Failed in fetching the data required to create new #{@getServerSideResourceName()}." onerror: (responseJSON) => @trigger "getNew#{@resourceNameCapitalized}DataEnd" @trigger "getNew#{@resourceNameCapitalized}DataFail", "Error in GET request to OLD server for /#{@getServerSideResourceName()}/new" console.log "Error in GET request to OLD server for /#{@getServerSideResourceName()}/new" ) ############################################################################ # Logic for returning a "patterns object" for the search model. ############################################################################ # A patterns object is an object that maps attributes to regular # expressions that can be used to highlight the attribute's value in order # to better indicate why a given resource matches the search model. getPatternsObject: -> patterns = @getPatterns @get('search').filter @_getPatternsObject patterns # Return a "patterns" array with all of the "positive" filter # expressions (i.e., patterns) in the (OLD-style) filter expression, i.e., # all of the non-negated filter expressions. getPatterns: (filter) -> patterns = [] if filter.length in [4, 5] patterns.push filter else if filter[0] in ['and', 'or'] for junct in filter[1] patterns = patterns.concat @getPatterns(junct) patterns # Return an object with resource attributes as attributes and regular # expressions for matching search pattern matches as values. Setting the # `flatten` param to `true` will treat all attribute-values as scalars # (i.e., strings or numbers). # The `patterns` param is an array of subarrays, where each subarray is a # "positive" OLD-style filter expression (positive, meaning that it asserts # something content-ful/non-negative of the match). The `patternsObject` # returned maps attributes (and `[attribute, subattribute]` duples) to # `RegExp` instances. _getPatternsObject: (patterns, flatten=false) -> patternsObject = {} for pattern in patterns attribute = pattern[1] if pattern.length is 4 relation = pattern[2] term = pattern[3] else subattribute = pattern[2] relation = pattern[3] term = pattern[4] regex = @getRegex relation, term if not regex then continue if attribute of patternsObject if (not flatten) and pattern.length is 5 if subattribute of patternsObject[attribute] patternsObject[attribute][subattribute].push regex else patternsObject[attribute][subattribute] = [regex] else patternsObject[attribute].push regex else if (not flatten) and pattern.length is 5 patternsObject[attribute] = {} patternsObject[attribute][subattribute] = [regex] else patternsObject[attribute] = [regex] for k, v of patternsObject if @utils.type(v) is 'object' for kk, vv of v patternsObject[k][kk] = new RegExp("((?:#{vv.join ')|(?:'}))", 'g') else patternsObject[k] = new RegExp("((?:#{v.join ')|(?:'}))", 'g') patternsObject # Take `relation` and `term` and return an appropriate regular expression # string. Relations currently accounted for: 'regex', 'like', '=', and # 'in'. TODO: relations still needing work: <=, >=, <, and >. getRegex: (relation, term) -> if relation is 'regex' regex = term else if relation is 'like' # Clip off '%' on the edges so that the later `.replace` call # highlights only the pattern and not the entire value. if term.length > 1 and term[0] is '%' term = term[1...] if term.length > 1 and term[term.length - 1] is '%' term = term[...-1] regex = @utils.escapeRegexChars(term).replace(/_/g, '.').replace(/%/g, '.*') else if relation is '=' regex = "^#{@utils.escapeRegexChars term}$" else if relation is 'in' regex = "(?:^#{term.join ')$|(?:^'})$" else regex = null # The OLD NFD-Unicode normalizes all data. So we need to normalize our # regex string in order for all matches to work out correctly. try regex.normalize 'NFD' catch regex
195919
define [ './resource' './form' ], (ResourceModel, FormModel) -> # Search Model # --------------- # # A Backbone model for Dative searches. class SearchModel extends ResourceModel resourceName: 'search' # Change some or all of the following four attributes if this search model # is being used to search over a resource other than forms, e.g., over file # resources. targetResourceName: 'form' targetResourcePrimaryAttribute: 'transcription' targetModelClass: FormModel # This may need to be overridden when this SearchModel is used to search # over models that don't have "id" as their primary key, e.g., OLD # languages which have the ISO 639-3 "Id" as their primary key. targetResourcePrimaryKey: 'id' getTargetResourceNameCapitalized: -> @utils.capitalize @targetResourceName serverSideResourceName: 'formsearches' initialize: (attributes, options) -> super attributes, options @targetResourceNameCapitalized = @getTargetResourceNameCapitalized() @targetResourceNamePlural = @utils.pluralize @targetResourceName @targetResourceNamePluralCapitalized = @utils.capitalize @targetResourceNamePlural editableAttributes: [ 'name' 'description' 'search' ] manyToOneAttributes: [] manyToManyAttributes: [] getValidator: (attribute) -> switch attribute when 'name' then @requiredString else null ############################################################################ # Search Schema ############################################################################ # See: # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/lib/schemata.py#L846-L854 # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/model/formsearch.py # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/model/model.py defaults: -> name: '' # required, unique among search names, max 255 chars description: '' # string description search: filter: [ @getTargetResourceNameCapitalized() @targetResourcePrimaryAttribute 'regex' '' ] order_by: [ @getTargetResourceNameCapitalized() @targetResourcePrimaryKey 'asc' ] # Attributes that the OLD sends to us, but which the OLD will ignore if # we try to send them back. id: null # An integer relational id enterer: null # an object (attributes: `id`, `first_name`, # `last_name`, `role`) datetime_modified: "" # <string> (datetime search was last modified, # format and construction same as # `datetime_entered`.) # We listen to this once so that we can add the result of calling GET # /<target_resource_plural>/new_search to the result of calling GET # /formsearches/new. getNewTargetResourceSearchDataSuccess: (newSearchData) -> key = <KEY>@target<KEY>" @searchNewData[key] = newSearchData.search_parameters @trigger "getNew#{@resourceNameCapitalized}DataSuccess", @searchNewData # We listen to this once so that we can tell the user that the request to # GET /<target_resource_plural>/new_search failed. getNewTargetResourceSearchDataFail: -> @trigger "getNew#{@resourceNameCapitalized}DataFail", "Error in GET request to OLD server for /#{@targetResourceNamePlural}/new_search" # Get the data necessary to create a new search over <target_resource> # objects. Note: this is an override of the base `ResourceModel`'s # implementation of this method since here we need to also request GET # /<target_resource_plural>/new_search. We do this by first requesting GET # /formsearches/new and then, if that's successful, requesting GET # /<target_resource_plural>/new_search. If that's successful, we trigger # the standard Backbone-wide success event for this method, passing in an # integrated/extended object. getNewResourceData: -> @trigger "getNew#{@resourceNameCapitalized}DataStart" @constructor.cors.request( method: 'GET' url: "#{@getOLDURL()}/#{@getServerSideResourceName()}/new" onload: (responseJSON, xhr) => @trigger "getNew#{@resourceNameCapitalized}DataEnd" if xhr.status is 200 @searchNewData = responseJSON ourTargetModel = new @targetModelClass() @listenToOnce(ourTargetModel, "getNew#{@targetResourceNameCapitalized}SearchDataSuccess", @getNewTargetResourceSearchDataSuccess) @listenToOnce(ourTargetModel, "getNew#{@targetResourceNameCapitalized}SearchDataFail", @getNewTargetResourceSearchDataFail) ourTargetModel.getNewSearchData() else @trigger "getNew#{@resourceNameCapitalized}DataFail", "Failed in fetching the data required to create new #{@getServerSideResourceName()}." onerror: (responseJSON) => @trigger "getNew#{@resourceNameCapitalized}DataEnd" @trigger "getNew#{@resourceNameCapitalized}DataFail", "Error in GET request to OLD server for /#{@getServerSideResourceName()}/new" console.log "Error in GET request to OLD server for /#{@getServerSideResourceName()}/new" ) ############################################################################ # Logic for returning a "patterns object" for the search model. ############################################################################ # A patterns object is an object that maps attributes to regular # expressions that can be used to highlight the attribute's value in order # to better indicate why a given resource matches the search model. getPatternsObject: -> patterns = @getPatterns @get('search').filter @_getPatternsObject patterns # Return a "patterns" array with all of the "positive" filter # expressions (i.e., patterns) in the (OLD-style) filter expression, i.e., # all of the non-negated filter expressions. getPatterns: (filter) -> patterns = [] if filter.length in [4, 5] patterns.push filter else if filter[0] in ['and', 'or'] for junct in filter[1] patterns = patterns.concat @getPatterns(junct) patterns # Return an object with resource attributes as attributes and regular # expressions for matching search pattern matches as values. Setting the # `flatten` param to `true` will treat all attribute-values as scalars # (i.e., strings or numbers). # The `patterns` param is an array of subarrays, where each subarray is a # "positive" OLD-style filter expression (positive, meaning that it asserts # something content-ful/non-negative of the match). The `patternsObject` # returned maps attributes (and `[attribute, subattribute]` duples) to # `RegExp` instances. _getPatternsObject: (patterns, flatten=false) -> patternsObject = {} for pattern in patterns attribute = pattern[1] if pattern.length is 4 relation = pattern[2] term = pattern[3] else subattribute = pattern[2] relation = pattern[3] term = pattern[4] regex = @getRegex relation, term if not regex then continue if attribute of patternsObject if (not flatten) and pattern.length is 5 if subattribute of patternsObject[attribute] patternsObject[attribute][subattribute].push regex else patternsObject[attribute][subattribute] = [regex] else patternsObject[attribute].push regex else if (not flatten) and pattern.length is 5 patternsObject[attribute] = {} patternsObject[attribute][subattribute] = [regex] else patternsObject[attribute] = [regex] for k, v of patternsObject if @utils.type(v) is 'object' for kk, vv of v patternsObject[k][kk] = new RegExp("((?:#{vv.join ')|(?:'}))", 'g') else patternsObject[k] = new RegExp("((?:#{v.join ')|(?:'}))", 'g') patternsObject # Take `relation` and `term` and return an appropriate regular expression # string. Relations currently accounted for: 'regex', 'like', '=', and # 'in'. TODO: relations still needing work: <=, >=, <, and >. getRegex: (relation, term) -> if relation is 'regex' regex = term else if relation is 'like' # Clip off '%' on the edges so that the later `.replace` call # highlights only the pattern and not the entire value. if term.length > 1 and term[0] is '%' term = term[1...] if term.length > 1 and term[term.length - 1] is '%' term = term[...-1] regex = @utils.escapeRegexChars(term).replace(/_/g, '.').replace(/%/g, '.*') else if relation is '=' regex = "^#{@utils.escapeRegexChars term}$" else if relation is 'in' regex = "(?:^#{term.join ')$|(?:^'})$" else regex = null # The OLD NFD-Unicode normalizes all data. So we need to normalize our # regex string in order for all matches to work out correctly. try regex.normalize 'NFD' catch regex
true
define [ './resource' './form' ], (ResourceModel, FormModel) -> # Search Model # --------------- # # A Backbone model for Dative searches. class SearchModel extends ResourceModel resourceName: 'search' # Change some or all of the following four attributes if this search model # is being used to search over a resource other than forms, e.g., over file # resources. targetResourceName: 'form' targetResourcePrimaryAttribute: 'transcription' targetModelClass: FormModel # This may need to be overridden when this SearchModel is used to search # over models that don't have "id" as their primary key, e.g., OLD # languages which have the ISO 639-3 "Id" as their primary key. targetResourcePrimaryKey: 'id' getTargetResourceNameCapitalized: -> @utils.capitalize @targetResourceName serverSideResourceName: 'formsearches' initialize: (attributes, options) -> super attributes, options @targetResourceNameCapitalized = @getTargetResourceNameCapitalized() @targetResourceNamePlural = @utils.pluralize @targetResourceName @targetResourceNamePluralCapitalized = @utils.capitalize @targetResourceNamePlural editableAttributes: [ 'name' 'description' 'search' ] manyToOneAttributes: [] manyToManyAttributes: [] getValidator: (attribute) -> switch attribute when 'name' then @requiredString else null ############################################################################ # Search Schema ############################################################################ # See: # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/lib/schemata.py#L846-L854 # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/model/formsearch.py # - https://github.com/jrwdunham/old/blob/master/onlinelinguisticdatabase/model/model.py defaults: -> name: '' # required, unique among search names, max 255 chars description: '' # string description search: filter: [ @getTargetResourceNameCapitalized() @targetResourcePrimaryAttribute 'regex' '' ] order_by: [ @getTargetResourceNameCapitalized() @targetResourcePrimaryKey 'asc' ] # Attributes that the OLD sends to us, but which the OLD will ignore if # we try to send them back. id: null # An integer relational id enterer: null # an object (attributes: `id`, `first_name`, # `last_name`, `role`) datetime_modified: "" # <string> (datetime search was last modified, # format and construction same as # `datetime_entered`.) # We listen to this once so that we can add the result of calling GET # /<target_resource_plural>/new_search to the result of calling GET # /formsearches/new. getNewTargetResourceSearchDataSuccess: (newSearchData) -> key = PI:KEY:<KEY>END_PI@targetPI:KEY:<KEY>END_PI" @searchNewData[key] = newSearchData.search_parameters @trigger "getNew#{@resourceNameCapitalized}DataSuccess", @searchNewData # We listen to this once so that we can tell the user that the request to # GET /<target_resource_plural>/new_search failed. getNewTargetResourceSearchDataFail: -> @trigger "getNew#{@resourceNameCapitalized}DataFail", "Error in GET request to OLD server for /#{@targetResourceNamePlural}/new_search" # Get the data necessary to create a new search over <target_resource> # objects. Note: this is an override of the base `ResourceModel`'s # implementation of this method since here we need to also request GET # /<target_resource_plural>/new_search. We do this by first requesting GET # /formsearches/new and then, if that's successful, requesting GET # /<target_resource_plural>/new_search. If that's successful, we trigger # the standard Backbone-wide success event for this method, passing in an # integrated/extended object. getNewResourceData: -> @trigger "getNew#{@resourceNameCapitalized}DataStart" @constructor.cors.request( method: 'GET' url: "#{@getOLDURL()}/#{@getServerSideResourceName()}/new" onload: (responseJSON, xhr) => @trigger "getNew#{@resourceNameCapitalized}DataEnd" if xhr.status is 200 @searchNewData = responseJSON ourTargetModel = new @targetModelClass() @listenToOnce(ourTargetModel, "getNew#{@targetResourceNameCapitalized}SearchDataSuccess", @getNewTargetResourceSearchDataSuccess) @listenToOnce(ourTargetModel, "getNew#{@targetResourceNameCapitalized}SearchDataFail", @getNewTargetResourceSearchDataFail) ourTargetModel.getNewSearchData() else @trigger "getNew#{@resourceNameCapitalized}DataFail", "Failed in fetching the data required to create new #{@getServerSideResourceName()}." onerror: (responseJSON) => @trigger "getNew#{@resourceNameCapitalized}DataEnd" @trigger "getNew#{@resourceNameCapitalized}DataFail", "Error in GET request to OLD server for /#{@getServerSideResourceName()}/new" console.log "Error in GET request to OLD server for /#{@getServerSideResourceName()}/new" ) ############################################################################ # Logic for returning a "patterns object" for the search model. ############################################################################ # A patterns object is an object that maps attributes to regular # expressions that can be used to highlight the attribute's value in order # to better indicate why a given resource matches the search model. getPatternsObject: -> patterns = @getPatterns @get('search').filter @_getPatternsObject patterns # Return a "patterns" array with all of the "positive" filter # expressions (i.e., patterns) in the (OLD-style) filter expression, i.e., # all of the non-negated filter expressions. getPatterns: (filter) -> patterns = [] if filter.length in [4, 5] patterns.push filter else if filter[0] in ['and', 'or'] for junct in filter[1] patterns = patterns.concat @getPatterns(junct) patterns # Return an object with resource attributes as attributes and regular # expressions for matching search pattern matches as values. Setting the # `flatten` param to `true` will treat all attribute-values as scalars # (i.e., strings or numbers). # The `patterns` param is an array of subarrays, where each subarray is a # "positive" OLD-style filter expression (positive, meaning that it asserts # something content-ful/non-negative of the match). The `patternsObject` # returned maps attributes (and `[attribute, subattribute]` duples) to # `RegExp` instances. _getPatternsObject: (patterns, flatten=false) -> patternsObject = {} for pattern in patterns attribute = pattern[1] if pattern.length is 4 relation = pattern[2] term = pattern[3] else subattribute = pattern[2] relation = pattern[3] term = pattern[4] regex = @getRegex relation, term if not regex then continue if attribute of patternsObject if (not flatten) and pattern.length is 5 if subattribute of patternsObject[attribute] patternsObject[attribute][subattribute].push regex else patternsObject[attribute][subattribute] = [regex] else patternsObject[attribute].push regex else if (not flatten) and pattern.length is 5 patternsObject[attribute] = {} patternsObject[attribute][subattribute] = [regex] else patternsObject[attribute] = [regex] for k, v of patternsObject if @utils.type(v) is 'object' for kk, vv of v patternsObject[k][kk] = new RegExp("((?:#{vv.join ')|(?:'}))", 'g') else patternsObject[k] = new RegExp("((?:#{v.join ')|(?:'}))", 'g') patternsObject # Take `relation` and `term` and return an appropriate regular expression # string. Relations currently accounted for: 'regex', 'like', '=', and # 'in'. TODO: relations still needing work: <=, >=, <, and >. getRegex: (relation, term) -> if relation is 'regex' regex = term else if relation is 'like' # Clip off '%' on the edges so that the later `.replace` call # highlights only the pattern and not the entire value. if term.length > 1 and term[0] is '%' term = term[1...] if term.length > 1 and term[term.length - 1] is '%' term = term[...-1] regex = @utils.escapeRegexChars(term).replace(/_/g, '.').replace(/%/g, '.*') else if relation is '=' regex = "^#{@utils.escapeRegexChars term}$" else if relation is 'in' regex = "(?:^#{term.join ')$|(?:^'})$" else regex = null # The OLD NFD-Unicode normalizes all data. So we need to normalize our # regex string in order for all matches to work out correctly. try regex.normalize 'NFD' catch regex
[ { "context": "ire './views/' + name\n key = className.charAt(0).toLowerCase() + className.slice(1)\n @[key] ?= new @[classNam", "end": 5677, "score": 0.6902965903282166, "start": 5664, "tag": "KEY", "value": "toLowerCase()" } ]
lib/spark-dev.coffee
lukehoban/spark-dev
1
fs = null settings = null utilities = null path = null _s = null url = null module.exports = # Local modules for JIT require SettingsHelper: null MenuManager: null SerialHelper: null PathWatcher: null StatusView: null LoginView: null SelectCoreView: null RenameCoreView: null ClaimCoreView: null IdentifyCoreView: null ListeningModeView: null SelectPortView: null CompileErrorsView: null SelectFirmwareView: null statusView: null loginView: null selectCoreView: null renameCoreView: null claimCoreView: null identifyCoreView: null listeningModeView: null selectPortView: null compileErrorsView: null selectFirmwareView: null spark: null toolbar: null watchSubscription: null removePromise: null listPortsPromise: null compileCloudPromise: null flashCorePromise: null activate: (state) -> # Require modules on activation @StatusView ?= require './views/status-bar-view' @SettingsHelper ?= require './utils/settings-helper' @MenuManager ?= require './utils/menu-manager' @PathWatcher ?= require 'pathwatcher' # Initialize status bar view @statusView = new @StatusView() # Hook up commands atom.workspaceView.command 'spark-dev:login', => @login() atom.workspaceView.command 'spark-dev:logout', => @logout() atom.workspaceView.command 'spark-dev:select-device', => @selectCore() atom.workspaceView.command 'spark-dev:rename-device', => @renameCore() atom.workspaceView.command 'spark-dev:remove-device', => @removeCore() atom.workspaceView.command 'spark-dev:claim-device', => @claimCore() atom.workspaceView.command 'spark-dev:identify-device', (event, port) => @identifyCore(port) atom.workspaceView.command 'spark-dev:compile-cloud', (event, thenFlash) => @compileCloud(thenFlash) atom.workspaceView.command 'spark-dev:show-compile-errors', => @showCompileErrors() atom.workspaceView.command 'spark-dev:flash-cloud', (event, firmware) => @flashCloud(firmware) atom.workspaceView.command 'spark-dev:show-serial-monitor', => @showSerialMonitor() atom.workspaceView.command 'spark-dev:setup-wifi', (event, port) => @setupWifi(port) atom.workspaceView.command 'spark-dev:enter-wifi-credentials', (event, port, ssid, security) => @enterWifiCredentials(port, ssid, security) atom.workspaceView.command 'spark-dev:try-flash-usb', => @tryFlashUsb() atom.workspaceView.command 'spark-dev:update-menu', => @MenuManager.update() # Update menu (default one in CSON file is empty) @MenuManager.update() url = require 'url' atom.workspace.addOpener (uriToOpen) => try {protocol, host, pathname} = url.parse(uriToOpen) catch error return return unless protocol is 'spark-dev:' try @initView pathname.substr(1) catch return # Updating toolbar try atom.packages.activatePackage('toolbar') .then (pkg) => @toolbar = pkg.mainModule @toolbar.appendSpacer() @flashButton = @toolbar.appendButton 'flash', 'spark-dev:flash-cloud', 'Compile and upload code using cloud', 'ion' @compileButton = @toolbar.appendButton 'checkmark-circled', 'spark-dev:compile-cloud', 'Compile and show errors if any', 'ion' @toolbar.appendSpacer() @toolbar.appendButton 'document-text', -> require('shell').openExternal('http://docs.spark.io/') , 'Opens reference at docs.spark.io', 'ion' @coreButton = @toolbar.appendButton 'pinpoint', 'spark-dev:select-device', 'Select which device you want to work on', 'ion' @wifiButton = @toolbar.appendButton 'wifi', 'spark-dev:setup-wifi', 'Setup device\'s WiFi credentials', 'ion' @toolbar.appendButton 'usb', 'spark-dev:show-serial-monitor', 'Show serial monitor', 'ion' @updateToolbarButtons() atom.workspaceView.command 'spark-dev:update-login-status', => @updateToolbarButtons() atom.workspaceView.command 'spark-dev:update-core-status', => @updateToolbarButtons() catch # Monitoring changes in settings settings ?= require './vendor/settings' fs ?= require 'fs-plus' path ?= require 'path' proFile = path.join settings.ensureFolder(), 'profile.json' if !fs.existsSync(proFile) fs.writeFileSync proFile, '{}' console.log '!Created profile ' + proFile if typeof(jasmine) == 'undefined' # Don't watch settings during tests @profileSubscription ?= @PathWatcher.watch proFile, (eventType) => if eventType is 'change' and @profileSubscription? @configSubscription?.close() @configSubscription = null @watchConfig() @updateToolbarButtons() @MenuManager.update() atom.workspaceView.trigger 'spark-dev:update-login-status' @watchConfig() deactivate: -> @statusView?.destroy() serialize: -> config: # Delete .bin file after flash deleteFirmwareAfterFlash: type: 'boolean' default: true # Delete old .bin files on successful compile deleteOldFirmwareAfterCompile: type: 'boolean' default: true # Files ignored when compiling filesExcludedFromCompile: type: 'string' default: '.ds_store, .jpg, .gif, .png, .include, .ignore, Thumbs.db, .git, .bin' # Require view's module and initialize it initView: (name) -> _s ?= require 'underscore.string' name += '-view' className = '' for part in name.split '-' className += _s.capitalize part @[className] ?= require './views/' + name key = className.charAt(0).toLowerCase() + className.slice(1) @[key] ?= new @[className]() @[key] # "Decorator" which runs callback only when user is logged in loginRequired: (callback) -> if !@SettingsHelper.isLoggedIn() return @spark ?= require 'spark' @spark.login { accessToken: @SettingsHelper.get('access_token') } callback() # "Decorator" which runs callback only when user is logged in and has core selected coreRequired: (callback) -> @loginRequired => if !@SettingsHelper.hasCurrentCore() return callback() # "Decorator" which runs callback only when there's project set projectRequired: (callback) -> if atom.project.getPaths().length == 0 return callback() # Open view in bottom panel openPane: (uri) -> uri = 'spark-dev://editor/' + uri pane = atom.workspace.paneForUri uri if pane? pane.activateItemForUri uri else if atom.workspaceView.getPaneViews().length == 1 pane = atom.workspaceView.getActivePaneView().splitDown() else paneViews = atom.workspaceView.getPaneViews() pane = paneViews[paneViews.length - 1] pane = pane.splitRight() pane.activate() atom.workspace.open uri, searchAllPanes: true # Enables/disables toolbar buttons based on log in state updateToolbarButtons: -> if @SettingsHelper.isLoggedIn() @compileButton.setEnabled true @coreButton.setEnabled true @wifiButton.setEnabled true if @SettingsHelper.hasCurrentCore() @flashButton.setEnabled true else @flashButton.setEnabled false else @flashButton.setEnabled false @compileButton.setEnabled false @coreButton.setEnabled false @wifiButton.setEnabled false # Watch config file for changes watchConfig: -> settings.whichProfile() settingsFile = settings.findOverridesFile() if !fs.existsSync(settingsFile) console.log '!Created ' + settingsFile fs.writeFileSync settingsFile, '{}' @configSubscription ?= @PathWatcher.watch settingsFile, (eventType) => if eventType is 'change' and @configSubscription? and @accessToken != @SettingsHelper.get('access_token') @accessToken = @SettingsHelper.get 'access_token' @updateToolbarButtons() @MenuManager.update() atom.workspaceView.trigger 'spark-dev:update-login-status' processDirIncludes: (dirname) -> settings ?= require './vendor/settings' utilities ?= require './vendor/utilities' dirname = path.resolve dirname includesFile = path.join dirname, settings.dirIncludeFilename ignoreFile = path.join dirname, settings.dirExcludeFilename ignores = [] includes = [ "**/*.h", "**/*.ino", "**/*.cpp", "**/*.c" ] if fs.existsSync(includesFile) # Grab and process all the files in the include file. # cleanIncludes = utilities.trimBlankLinesAndComments(utilities.readAndTrimLines(includesFile)) # includes = utilities.fixRelativePaths dirname, cleanIncludes null files = utilities.globList dirname, includes notSourceExtensions = atom.config.get('spark-dev.filesExcludedFromCompile').split ',' ignores = ('**/*' + _s.trim(extension).toLowerCase() for extension in notSourceExtensions) if fs.existsSync(ignoreFile) cleanIgnores = utilities.readAndTrimLines ignoreFile ignores = ignores.concat utilities.trimBlankLinesAndComments cleanIgnores ignoredFiles = utilities.globList dirname, ignores utilities.compliment files, ignoredFiles # Function for selecting port or showing Listen dialog choosePort: (delegate) -> @ListeningModeView ?= require './views/listening-mode-view' @SerialHelper ?= require './utils/serial-helper' @listPortsPromise = @SerialHelper.listPorts() @listPortsPromise.done (ports) => @listPortsPromise = null if ports.length == 0 # If there are no ports, show dialog with animation how to enter listening mode @listeningModeView = new @ListeningModeView(delegate) @listeningModeView.show() else if ports.length == 1 atom.workspaceView.trigger delegate, [ports[0].comName] else # There are at least two ports so show them and ask user to choose @SelectPortView ?= require './views/select-port-view' @selectPortView = new @SelectPortView(delegate) @selectPortView.show() , (e) => console.error e # Show login dialog login: -> @initView 'login' # You may ask why commands aren't registered in LoginView? # This way, we don't need to require/initialize login view until it's needed. atom.workspaceView.command 'spark-dev:cancel-login', => @loginView.cancelCommand() @loginView.show() # Log out current user logout: -> @loginRequired => @initView 'login' @loginView.logout() # Show user's cores list selectCore: -> @loginRequired => @initView 'select-core' @selectCoreView.show() # Show rename core dialog renameCore: -> @coreRequired => @RenameCoreView ?= require './views/rename-core-view' @renameCoreView = new @RenameCoreView(@SettingsHelper.getLocal 'current_core_name') @renameCoreView.attach() # Remove current core from user's account removeCore: -> @coreRequired => removeButton = 'Remove ' + @SettingsHelper.getLocal('current_core_name') buttons = {} buttons['Cancel'] = -> buttons['Remove ' + @SettingsHelper.getLocal('current_core_name')] = => workspace = atom.workspaceView @removePromise = @spark.removeCore @SettingsHelper.getLocal('current_core') @removePromise.done (e) => if !@removePromise return atom.workspaceView = workspace @SettingsHelper.clearCurrentCore() atom.workspaceView.trigger 'spark-dev:update-core-status' atom.workspaceView.trigger 'spark-dev:update-menu' @removePromise = null , (e) => @removePromise = null if e.code == 'ENOTFOUND' message = 'Error while connecting to ' + e.hostname else message = e.info atom.confirm message: 'Error' detailedMessage: message atom.confirm message: 'Removal confirmation' detailedMessage: 'Do you really want to remove ' + @SettingsHelper.getLocal('current_core_name') + '?' buttons: buttons # Show core claiming dialog claimCore: -> @loginRequired => @claimCoreView = null @initView 'claim-core' @claimCoreView.attach() # Identify core via serial identifyCore: (port=null) -> @loginRequired => if !port @choosePort('spark-dev:identify-device') else @SerialHelper ?= require './utils/serial-helper' promise = @SerialHelper.askForCoreID port promise.done (coreID) => @IdentifyCoreView ?= require './views/identify-core-view' @identifyCoreView = new @IdentifyCoreView coreID @identifyCoreView.attach() , (e) => @statusView.setStatus e, 'error' @statusView.clearAfter 5000 # Compile current project in the cloud compileCloud: (thenFlash=null) -> @loginRequired => @projectRequired => if !!@compileCloudPromise return @SettingsHelper.setLocal 'compile-status', {working: true} atom.workspaceView.trigger 'spark-dev:update-compile-status' # Including files fs ?= require 'fs-plus' path ?= require 'path' settings ?= require './vendor/settings' utilities ?= require './vendor/utilities' _s ?= require 'underscore.string' rootPath = atom.project.getPaths()[0] files = @processDirIncludes rootPath process.chdir rootPath files = (path.relative(rootPath, file) for file in files) invalidFiles = files.filter (file) -> path.basename(file).indexOf(' ') > -1 if invalidFiles.length errors = [] for file in invalidFiles errors.push file: file, message: 'File contains space in its name' row: 0, col: 0 @CompileErrorsView ?= require './views/compile-errors-view' @SettingsHelper.setLocal 'compile-status', {errors: errors} atom.workspaceView.trigger 'spark-dev:show-compile-errors' atom.workspaceView.trigger 'spark-dev:update-compile-status' return workspace = atom.workspaceView @compileCloudPromise = @spark.compileCode files @compileCloudPromise.done (e) => if !e return if e.ok # Download binary @compileCloudPromise = null if atom.config.get('spark-dev.deleteOldFirmwareAfterCompile') # Remove old firmwares files = fs.listSync rootPath for file in files if _s.startsWith(path.basename(file), 'firmware') and _s.endsWith(file, '.bin') fs.unlinkSync file filename = 'firmware_' + (new Date()).getTime() + '.bin'; @downloadBinaryPromise = @spark.downloadBinary e.binary_url, rootPath + '/' + filename @downloadBinaryPromise.done (e) => atom.workspaceView = workspace @SettingsHelper.setLocal 'compile-status', {filename: filename} atom.workspaceView.trigger 'spark-dev:update-compile-status' if !!thenFlash setTimeout -> atom.workspaceView.trigger 'spark-dev:flash-cloud' , 500 @downloadBinaryPromise = null , (e) => console.error e else # Handle errors @CompileErrorsView ?= require './views/compile-errors-view' errors = @CompileErrorsView.parseErrors(e.errors[0]) if errors.length == 0 @SettingsHelper.setLocal 'compile-status', {error: e.output} else @SettingsHelper.setLocal 'compile-status', {errors: errors} atom.workspaceView.trigger 'spark-dev:show-compile-errors' atom.workspaceView.trigger 'spark-dev:update-compile-status' @compileCloudPromise = null , (e) => console.error e @SettingsHelper.setLocal 'compile-status', null atom.workspaceView.trigger 'spark-dev:update-compile-status' # Show compile errors list showCompileErrors: -> @initView 'compile-errors' @compileErrorsView.show() # Flash core via the cloud flashCloud: (firmware=null) -> @coreRequired => @projectRequired => fs ?= require 'fs-plus' path ?= require 'path' utilities ?= require './vendor/utilities' rootPath = atom.project.getPaths()[0] files = fs.listSync(rootPath) files = files.filter (file) -> return (utilities.getFilenameExt(file).toLowerCase() == '.bin') if files.length == 0 # If no firmware file, compile atom.workspaceView.trigger 'spark-dev:compile-cloud', [true] else if (files.length == 1) || (!!firmware) # If one firmware file, flash if !firmware firmware = files[0] process.chdir rootPath firmware = path.relative rootPath, firmware @statusView.setStatus 'Flashing via the cloud...' @flashCorePromise = @spark.flashCore @SettingsHelper.getLocal('current_core'), [firmware] @flashCorePromise.done (e) => @statusView.setStatus e.status + '...' @statusView.clearAfter 5000 if atom.config.get 'spark-dev.deleteFirmwareAfterFlash' fs.unlink firmware @flashCorePromise = null , (e) => if e.code == 'ECONNRESET' @statusView.setStatus 'Device seems to be offline', 'error' else @statusView.setStatus e.message, 'error' @statusView.clearAfter 5000 @flashCorePromise = null else # If multiple firmware files, show select @initView 'select-firmware' files.reverse() @selectFirmwareView.setItems files @selectFirmwareView.show() # Show serial monitor panel showSerialMonitor: -> @serialMonitorView = null @openPane 'serial-monitor' # Set up core's WiFi setupWifi: (port=null) -> @loginRequired => if !port @choosePort 'spark-dev:setup-wifi' else @initView 'select-wifi' @selectWifiView.port = port @selectWifiView.show() enterWifiCredentials: (port, ssid=null, security=null) -> @loginRequired => if !port return @wifiCredentialsView = null @initView 'wifi-credentials' @wifiCredentialsView.port = port @wifiCredentialsView.show(ssid, security) tryFlashUsb: -> @projectRequired => if !atom.commands.registeredCommands['spark-dev-dfu-util:flash-usb'] # TODO: Ask for installation else atom.workspaceView.trigger 'spark-dev-dfu-util:flash-usb'
207269
fs = null settings = null utilities = null path = null _s = null url = null module.exports = # Local modules for JIT require SettingsHelper: null MenuManager: null SerialHelper: null PathWatcher: null StatusView: null LoginView: null SelectCoreView: null RenameCoreView: null ClaimCoreView: null IdentifyCoreView: null ListeningModeView: null SelectPortView: null CompileErrorsView: null SelectFirmwareView: null statusView: null loginView: null selectCoreView: null renameCoreView: null claimCoreView: null identifyCoreView: null listeningModeView: null selectPortView: null compileErrorsView: null selectFirmwareView: null spark: null toolbar: null watchSubscription: null removePromise: null listPortsPromise: null compileCloudPromise: null flashCorePromise: null activate: (state) -> # Require modules on activation @StatusView ?= require './views/status-bar-view' @SettingsHelper ?= require './utils/settings-helper' @MenuManager ?= require './utils/menu-manager' @PathWatcher ?= require 'pathwatcher' # Initialize status bar view @statusView = new @StatusView() # Hook up commands atom.workspaceView.command 'spark-dev:login', => @login() atom.workspaceView.command 'spark-dev:logout', => @logout() atom.workspaceView.command 'spark-dev:select-device', => @selectCore() atom.workspaceView.command 'spark-dev:rename-device', => @renameCore() atom.workspaceView.command 'spark-dev:remove-device', => @removeCore() atom.workspaceView.command 'spark-dev:claim-device', => @claimCore() atom.workspaceView.command 'spark-dev:identify-device', (event, port) => @identifyCore(port) atom.workspaceView.command 'spark-dev:compile-cloud', (event, thenFlash) => @compileCloud(thenFlash) atom.workspaceView.command 'spark-dev:show-compile-errors', => @showCompileErrors() atom.workspaceView.command 'spark-dev:flash-cloud', (event, firmware) => @flashCloud(firmware) atom.workspaceView.command 'spark-dev:show-serial-monitor', => @showSerialMonitor() atom.workspaceView.command 'spark-dev:setup-wifi', (event, port) => @setupWifi(port) atom.workspaceView.command 'spark-dev:enter-wifi-credentials', (event, port, ssid, security) => @enterWifiCredentials(port, ssid, security) atom.workspaceView.command 'spark-dev:try-flash-usb', => @tryFlashUsb() atom.workspaceView.command 'spark-dev:update-menu', => @MenuManager.update() # Update menu (default one in CSON file is empty) @MenuManager.update() url = require 'url' atom.workspace.addOpener (uriToOpen) => try {protocol, host, pathname} = url.parse(uriToOpen) catch error return return unless protocol is 'spark-dev:' try @initView pathname.substr(1) catch return # Updating toolbar try atom.packages.activatePackage('toolbar') .then (pkg) => @toolbar = pkg.mainModule @toolbar.appendSpacer() @flashButton = @toolbar.appendButton 'flash', 'spark-dev:flash-cloud', 'Compile and upload code using cloud', 'ion' @compileButton = @toolbar.appendButton 'checkmark-circled', 'spark-dev:compile-cloud', 'Compile and show errors if any', 'ion' @toolbar.appendSpacer() @toolbar.appendButton 'document-text', -> require('shell').openExternal('http://docs.spark.io/') , 'Opens reference at docs.spark.io', 'ion' @coreButton = @toolbar.appendButton 'pinpoint', 'spark-dev:select-device', 'Select which device you want to work on', 'ion' @wifiButton = @toolbar.appendButton 'wifi', 'spark-dev:setup-wifi', 'Setup device\'s WiFi credentials', 'ion' @toolbar.appendButton 'usb', 'spark-dev:show-serial-monitor', 'Show serial monitor', 'ion' @updateToolbarButtons() atom.workspaceView.command 'spark-dev:update-login-status', => @updateToolbarButtons() atom.workspaceView.command 'spark-dev:update-core-status', => @updateToolbarButtons() catch # Monitoring changes in settings settings ?= require './vendor/settings' fs ?= require 'fs-plus' path ?= require 'path' proFile = path.join settings.ensureFolder(), 'profile.json' if !fs.existsSync(proFile) fs.writeFileSync proFile, '{}' console.log '!Created profile ' + proFile if typeof(jasmine) == 'undefined' # Don't watch settings during tests @profileSubscription ?= @PathWatcher.watch proFile, (eventType) => if eventType is 'change' and @profileSubscription? @configSubscription?.close() @configSubscription = null @watchConfig() @updateToolbarButtons() @MenuManager.update() atom.workspaceView.trigger 'spark-dev:update-login-status' @watchConfig() deactivate: -> @statusView?.destroy() serialize: -> config: # Delete .bin file after flash deleteFirmwareAfterFlash: type: 'boolean' default: true # Delete old .bin files on successful compile deleteOldFirmwareAfterCompile: type: 'boolean' default: true # Files ignored when compiling filesExcludedFromCompile: type: 'string' default: '.ds_store, .jpg, .gif, .png, .include, .ignore, Thumbs.db, .git, .bin' # Require view's module and initialize it initView: (name) -> _s ?= require 'underscore.string' name += '-view' className = '' for part in name.split '-' className += _s.capitalize part @[className] ?= require './views/' + name key = className.charAt(0).<KEY> + className.slice(1) @[key] ?= new @[className]() @[key] # "Decorator" which runs callback only when user is logged in loginRequired: (callback) -> if !@SettingsHelper.isLoggedIn() return @spark ?= require 'spark' @spark.login { accessToken: @SettingsHelper.get('access_token') } callback() # "Decorator" which runs callback only when user is logged in and has core selected coreRequired: (callback) -> @loginRequired => if !@SettingsHelper.hasCurrentCore() return callback() # "Decorator" which runs callback only when there's project set projectRequired: (callback) -> if atom.project.getPaths().length == 0 return callback() # Open view in bottom panel openPane: (uri) -> uri = 'spark-dev://editor/' + uri pane = atom.workspace.paneForUri uri if pane? pane.activateItemForUri uri else if atom.workspaceView.getPaneViews().length == 1 pane = atom.workspaceView.getActivePaneView().splitDown() else paneViews = atom.workspaceView.getPaneViews() pane = paneViews[paneViews.length - 1] pane = pane.splitRight() pane.activate() atom.workspace.open uri, searchAllPanes: true # Enables/disables toolbar buttons based on log in state updateToolbarButtons: -> if @SettingsHelper.isLoggedIn() @compileButton.setEnabled true @coreButton.setEnabled true @wifiButton.setEnabled true if @SettingsHelper.hasCurrentCore() @flashButton.setEnabled true else @flashButton.setEnabled false else @flashButton.setEnabled false @compileButton.setEnabled false @coreButton.setEnabled false @wifiButton.setEnabled false # Watch config file for changes watchConfig: -> settings.whichProfile() settingsFile = settings.findOverridesFile() if !fs.existsSync(settingsFile) console.log '!Created ' + settingsFile fs.writeFileSync settingsFile, '{}' @configSubscription ?= @PathWatcher.watch settingsFile, (eventType) => if eventType is 'change' and @configSubscription? and @accessToken != @SettingsHelper.get('access_token') @accessToken = @SettingsHelper.get 'access_token' @updateToolbarButtons() @MenuManager.update() atom.workspaceView.trigger 'spark-dev:update-login-status' processDirIncludes: (dirname) -> settings ?= require './vendor/settings' utilities ?= require './vendor/utilities' dirname = path.resolve dirname includesFile = path.join dirname, settings.dirIncludeFilename ignoreFile = path.join dirname, settings.dirExcludeFilename ignores = [] includes = [ "**/*.h", "**/*.ino", "**/*.cpp", "**/*.c" ] if fs.existsSync(includesFile) # Grab and process all the files in the include file. # cleanIncludes = utilities.trimBlankLinesAndComments(utilities.readAndTrimLines(includesFile)) # includes = utilities.fixRelativePaths dirname, cleanIncludes null files = utilities.globList dirname, includes notSourceExtensions = atom.config.get('spark-dev.filesExcludedFromCompile').split ',' ignores = ('**/*' + _s.trim(extension).toLowerCase() for extension in notSourceExtensions) if fs.existsSync(ignoreFile) cleanIgnores = utilities.readAndTrimLines ignoreFile ignores = ignores.concat utilities.trimBlankLinesAndComments cleanIgnores ignoredFiles = utilities.globList dirname, ignores utilities.compliment files, ignoredFiles # Function for selecting port or showing Listen dialog choosePort: (delegate) -> @ListeningModeView ?= require './views/listening-mode-view' @SerialHelper ?= require './utils/serial-helper' @listPortsPromise = @SerialHelper.listPorts() @listPortsPromise.done (ports) => @listPortsPromise = null if ports.length == 0 # If there are no ports, show dialog with animation how to enter listening mode @listeningModeView = new @ListeningModeView(delegate) @listeningModeView.show() else if ports.length == 1 atom.workspaceView.trigger delegate, [ports[0].comName] else # There are at least two ports so show them and ask user to choose @SelectPortView ?= require './views/select-port-view' @selectPortView = new @SelectPortView(delegate) @selectPortView.show() , (e) => console.error e # Show login dialog login: -> @initView 'login' # You may ask why commands aren't registered in LoginView? # This way, we don't need to require/initialize login view until it's needed. atom.workspaceView.command 'spark-dev:cancel-login', => @loginView.cancelCommand() @loginView.show() # Log out current user logout: -> @loginRequired => @initView 'login' @loginView.logout() # Show user's cores list selectCore: -> @loginRequired => @initView 'select-core' @selectCoreView.show() # Show rename core dialog renameCore: -> @coreRequired => @RenameCoreView ?= require './views/rename-core-view' @renameCoreView = new @RenameCoreView(@SettingsHelper.getLocal 'current_core_name') @renameCoreView.attach() # Remove current core from user's account removeCore: -> @coreRequired => removeButton = 'Remove ' + @SettingsHelper.getLocal('current_core_name') buttons = {} buttons['Cancel'] = -> buttons['Remove ' + @SettingsHelper.getLocal('current_core_name')] = => workspace = atom.workspaceView @removePromise = @spark.removeCore @SettingsHelper.getLocal('current_core') @removePromise.done (e) => if !@removePromise return atom.workspaceView = workspace @SettingsHelper.clearCurrentCore() atom.workspaceView.trigger 'spark-dev:update-core-status' atom.workspaceView.trigger 'spark-dev:update-menu' @removePromise = null , (e) => @removePromise = null if e.code == 'ENOTFOUND' message = 'Error while connecting to ' + e.hostname else message = e.info atom.confirm message: 'Error' detailedMessage: message atom.confirm message: 'Removal confirmation' detailedMessage: 'Do you really want to remove ' + @SettingsHelper.getLocal('current_core_name') + '?' buttons: buttons # Show core claiming dialog claimCore: -> @loginRequired => @claimCoreView = null @initView 'claim-core' @claimCoreView.attach() # Identify core via serial identifyCore: (port=null) -> @loginRequired => if !port @choosePort('spark-dev:identify-device') else @SerialHelper ?= require './utils/serial-helper' promise = @SerialHelper.askForCoreID port promise.done (coreID) => @IdentifyCoreView ?= require './views/identify-core-view' @identifyCoreView = new @IdentifyCoreView coreID @identifyCoreView.attach() , (e) => @statusView.setStatus e, 'error' @statusView.clearAfter 5000 # Compile current project in the cloud compileCloud: (thenFlash=null) -> @loginRequired => @projectRequired => if !!@compileCloudPromise return @SettingsHelper.setLocal 'compile-status', {working: true} atom.workspaceView.trigger 'spark-dev:update-compile-status' # Including files fs ?= require 'fs-plus' path ?= require 'path' settings ?= require './vendor/settings' utilities ?= require './vendor/utilities' _s ?= require 'underscore.string' rootPath = atom.project.getPaths()[0] files = @processDirIncludes rootPath process.chdir rootPath files = (path.relative(rootPath, file) for file in files) invalidFiles = files.filter (file) -> path.basename(file).indexOf(' ') > -1 if invalidFiles.length errors = [] for file in invalidFiles errors.push file: file, message: 'File contains space in its name' row: 0, col: 0 @CompileErrorsView ?= require './views/compile-errors-view' @SettingsHelper.setLocal 'compile-status', {errors: errors} atom.workspaceView.trigger 'spark-dev:show-compile-errors' atom.workspaceView.trigger 'spark-dev:update-compile-status' return workspace = atom.workspaceView @compileCloudPromise = @spark.compileCode files @compileCloudPromise.done (e) => if !e return if e.ok # Download binary @compileCloudPromise = null if atom.config.get('spark-dev.deleteOldFirmwareAfterCompile') # Remove old firmwares files = fs.listSync rootPath for file in files if _s.startsWith(path.basename(file), 'firmware') and _s.endsWith(file, '.bin') fs.unlinkSync file filename = 'firmware_' + (new Date()).getTime() + '.bin'; @downloadBinaryPromise = @spark.downloadBinary e.binary_url, rootPath + '/' + filename @downloadBinaryPromise.done (e) => atom.workspaceView = workspace @SettingsHelper.setLocal 'compile-status', {filename: filename} atom.workspaceView.trigger 'spark-dev:update-compile-status' if !!thenFlash setTimeout -> atom.workspaceView.trigger 'spark-dev:flash-cloud' , 500 @downloadBinaryPromise = null , (e) => console.error e else # Handle errors @CompileErrorsView ?= require './views/compile-errors-view' errors = @CompileErrorsView.parseErrors(e.errors[0]) if errors.length == 0 @SettingsHelper.setLocal 'compile-status', {error: e.output} else @SettingsHelper.setLocal 'compile-status', {errors: errors} atom.workspaceView.trigger 'spark-dev:show-compile-errors' atom.workspaceView.trigger 'spark-dev:update-compile-status' @compileCloudPromise = null , (e) => console.error e @SettingsHelper.setLocal 'compile-status', null atom.workspaceView.trigger 'spark-dev:update-compile-status' # Show compile errors list showCompileErrors: -> @initView 'compile-errors' @compileErrorsView.show() # Flash core via the cloud flashCloud: (firmware=null) -> @coreRequired => @projectRequired => fs ?= require 'fs-plus' path ?= require 'path' utilities ?= require './vendor/utilities' rootPath = atom.project.getPaths()[0] files = fs.listSync(rootPath) files = files.filter (file) -> return (utilities.getFilenameExt(file).toLowerCase() == '.bin') if files.length == 0 # If no firmware file, compile atom.workspaceView.trigger 'spark-dev:compile-cloud', [true] else if (files.length == 1) || (!!firmware) # If one firmware file, flash if !firmware firmware = files[0] process.chdir rootPath firmware = path.relative rootPath, firmware @statusView.setStatus 'Flashing via the cloud...' @flashCorePromise = @spark.flashCore @SettingsHelper.getLocal('current_core'), [firmware] @flashCorePromise.done (e) => @statusView.setStatus e.status + '...' @statusView.clearAfter 5000 if atom.config.get 'spark-dev.deleteFirmwareAfterFlash' fs.unlink firmware @flashCorePromise = null , (e) => if e.code == 'ECONNRESET' @statusView.setStatus 'Device seems to be offline', 'error' else @statusView.setStatus e.message, 'error' @statusView.clearAfter 5000 @flashCorePromise = null else # If multiple firmware files, show select @initView 'select-firmware' files.reverse() @selectFirmwareView.setItems files @selectFirmwareView.show() # Show serial monitor panel showSerialMonitor: -> @serialMonitorView = null @openPane 'serial-monitor' # Set up core's WiFi setupWifi: (port=null) -> @loginRequired => if !port @choosePort 'spark-dev:setup-wifi' else @initView 'select-wifi' @selectWifiView.port = port @selectWifiView.show() enterWifiCredentials: (port, ssid=null, security=null) -> @loginRequired => if !port return @wifiCredentialsView = null @initView 'wifi-credentials' @wifiCredentialsView.port = port @wifiCredentialsView.show(ssid, security) tryFlashUsb: -> @projectRequired => if !atom.commands.registeredCommands['spark-dev-dfu-util:flash-usb'] # TODO: Ask for installation else atom.workspaceView.trigger 'spark-dev-dfu-util:flash-usb'
true
fs = null settings = null utilities = null path = null _s = null url = null module.exports = # Local modules for JIT require SettingsHelper: null MenuManager: null SerialHelper: null PathWatcher: null StatusView: null LoginView: null SelectCoreView: null RenameCoreView: null ClaimCoreView: null IdentifyCoreView: null ListeningModeView: null SelectPortView: null CompileErrorsView: null SelectFirmwareView: null statusView: null loginView: null selectCoreView: null renameCoreView: null claimCoreView: null identifyCoreView: null listeningModeView: null selectPortView: null compileErrorsView: null selectFirmwareView: null spark: null toolbar: null watchSubscription: null removePromise: null listPortsPromise: null compileCloudPromise: null flashCorePromise: null activate: (state) -> # Require modules on activation @StatusView ?= require './views/status-bar-view' @SettingsHelper ?= require './utils/settings-helper' @MenuManager ?= require './utils/menu-manager' @PathWatcher ?= require 'pathwatcher' # Initialize status bar view @statusView = new @StatusView() # Hook up commands atom.workspaceView.command 'spark-dev:login', => @login() atom.workspaceView.command 'spark-dev:logout', => @logout() atom.workspaceView.command 'spark-dev:select-device', => @selectCore() atom.workspaceView.command 'spark-dev:rename-device', => @renameCore() atom.workspaceView.command 'spark-dev:remove-device', => @removeCore() atom.workspaceView.command 'spark-dev:claim-device', => @claimCore() atom.workspaceView.command 'spark-dev:identify-device', (event, port) => @identifyCore(port) atom.workspaceView.command 'spark-dev:compile-cloud', (event, thenFlash) => @compileCloud(thenFlash) atom.workspaceView.command 'spark-dev:show-compile-errors', => @showCompileErrors() atom.workspaceView.command 'spark-dev:flash-cloud', (event, firmware) => @flashCloud(firmware) atom.workspaceView.command 'spark-dev:show-serial-monitor', => @showSerialMonitor() atom.workspaceView.command 'spark-dev:setup-wifi', (event, port) => @setupWifi(port) atom.workspaceView.command 'spark-dev:enter-wifi-credentials', (event, port, ssid, security) => @enterWifiCredentials(port, ssid, security) atom.workspaceView.command 'spark-dev:try-flash-usb', => @tryFlashUsb() atom.workspaceView.command 'spark-dev:update-menu', => @MenuManager.update() # Update menu (default one in CSON file is empty) @MenuManager.update() url = require 'url' atom.workspace.addOpener (uriToOpen) => try {protocol, host, pathname} = url.parse(uriToOpen) catch error return return unless protocol is 'spark-dev:' try @initView pathname.substr(1) catch return # Updating toolbar try atom.packages.activatePackage('toolbar') .then (pkg) => @toolbar = pkg.mainModule @toolbar.appendSpacer() @flashButton = @toolbar.appendButton 'flash', 'spark-dev:flash-cloud', 'Compile and upload code using cloud', 'ion' @compileButton = @toolbar.appendButton 'checkmark-circled', 'spark-dev:compile-cloud', 'Compile and show errors if any', 'ion' @toolbar.appendSpacer() @toolbar.appendButton 'document-text', -> require('shell').openExternal('http://docs.spark.io/') , 'Opens reference at docs.spark.io', 'ion' @coreButton = @toolbar.appendButton 'pinpoint', 'spark-dev:select-device', 'Select which device you want to work on', 'ion' @wifiButton = @toolbar.appendButton 'wifi', 'spark-dev:setup-wifi', 'Setup device\'s WiFi credentials', 'ion' @toolbar.appendButton 'usb', 'spark-dev:show-serial-monitor', 'Show serial monitor', 'ion' @updateToolbarButtons() atom.workspaceView.command 'spark-dev:update-login-status', => @updateToolbarButtons() atom.workspaceView.command 'spark-dev:update-core-status', => @updateToolbarButtons() catch # Monitoring changes in settings settings ?= require './vendor/settings' fs ?= require 'fs-plus' path ?= require 'path' proFile = path.join settings.ensureFolder(), 'profile.json' if !fs.existsSync(proFile) fs.writeFileSync proFile, '{}' console.log '!Created profile ' + proFile if typeof(jasmine) == 'undefined' # Don't watch settings during tests @profileSubscription ?= @PathWatcher.watch proFile, (eventType) => if eventType is 'change' and @profileSubscription? @configSubscription?.close() @configSubscription = null @watchConfig() @updateToolbarButtons() @MenuManager.update() atom.workspaceView.trigger 'spark-dev:update-login-status' @watchConfig() deactivate: -> @statusView?.destroy() serialize: -> config: # Delete .bin file after flash deleteFirmwareAfterFlash: type: 'boolean' default: true # Delete old .bin files on successful compile deleteOldFirmwareAfterCompile: type: 'boolean' default: true # Files ignored when compiling filesExcludedFromCompile: type: 'string' default: '.ds_store, .jpg, .gif, .png, .include, .ignore, Thumbs.db, .git, .bin' # Require view's module and initialize it initView: (name) -> _s ?= require 'underscore.string' name += '-view' className = '' for part in name.split '-' className += _s.capitalize part @[className] ?= require './views/' + name key = className.charAt(0).PI:KEY:<KEY>END_PI + className.slice(1) @[key] ?= new @[className]() @[key] # "Decorator" which runs callback only when user is logged in loginRequired: (callback) -> if !@SettingsHelper.isLoggedIn() return @spark ?= require 'spark' @spark.login { accessToken: @SettingsHelper.get('access_token') } callback() # "Decorator" which runs callback only when user is logged in and has core selected coreRequired: (callback) -> @loginRequired => if !@SettingsHelper.hasCurrentCore() return callback() # "Decorator" which runs callback only when there's project set projectRequired: (callback) -> if atom.project.getPaths().length == 0 return callback() # Open view in bottom panel openPane: (uri) -> uri = 'spark-dev://editor/' + uri pane = atom.workspace.paneForUri uri if pane? pane.activateItemForUri uri else if atom.workspaceView.getPaneViews().length == 1 pane = atom.workspaceView.getActivePaneView().splitDown() else paneViews = atom.workspaceView.getPaneViews() pane = paneViews[paneViews.length - 1] pane = pane.splitRight() pane.activate() atom.workspace.open uri, searchAllPanes: true # Enables/disables toolbar buttons based on log in state updateToolbarButtons: -> if @SettingsHelper.isLoggedIn() @compileButton.setEnabled true @coreButton.setEnabled true @wifiButton.setEnabled true if @SettingsHelper.hasCurrentCore() @flashButton.setEnabled true else @flashButton.setEnabled false else @flashButton.setEnabled false @compileButton.setEnabled false @coreButton.setEnabled false @wifiButton.setEnabled false # Watch config file for changes watchConfig: -> settings.whichProfile() settingsFile = settings.findOverridesFile() if !fs.existsSync(settingsFile) console.log '!Created ' + settingsFile fs.writeFileSync settingsFile, '{}' @configSubscription ?= @PathWatcher.watch settingsFile, (eventType) => if eventType is 'change' and @configSubscription? and @accessToken != @SettingsHelper.get('access_token') @accessToken = @SettingsHelper.get 'access_token' @updateToolbarButtons() @MenuManager.update() atom.workspaceView.trigger 'spark-dev:update-login-status' processDirIncludes: (dirname) -> settings ?= require './vendor/settings' utilities ?= require './vendor/utilities' dirname = path.resolve dirname includesFile = path.join dirname, settings.dirIncludeFilename ignoreFile = path.join dirname, settings.dirExcludeFilename ignores = [] includes = [ "**/*.h", "**/*.ino", "**/*.cpp", "**/*.c" ] if fs.existsSync(includesFile) # Grab and process all the files in the include file. # cleanIncludes = utilities.trimBlankLinesAndComments(utilities.readAndTrimLines(includesFile)) # includes = utilities.fixRelativePaths dirname, cleanIncludes null files = utilities.globList dirname, includes notSourceExtensions = atom.config.get('spark-dev.filesExcludedFromCompile').split ',' ignores = ('**/*' + _s.trim(extension).toLowerCase() for extension in notSourceExtensions) if fs.existsSync(ignoreFile) cleanIgnores = utilities.readAndTrimLines ignoreFile ignores = ignores.concat utilities.trimBlankLinesAndComments cleanIgnores ignoredFiles = utilities.globList dirname, ignores utilities.compliment files, ignoredFiles # Function for selecting port or showing Listen dialog choosePort: (delegate) -> @ListeningModeView ?= require './views/listening-mode-view' @SerialHelper ?= require './utils/serial-helper' @listPortsPromise = @SerialHelper.listPorts() @listPortsPromise.done (ports) => @listPortsPromise = null if ports.length == 0 # If there are no ports, show dialog with animation how to enter listening mode @listeningModeView = new @ListeningModeView(delegate) @listeningModeView.show() else if ports.length == 1 atom.workspaceView.trigger delegate, [ports[0].comName] else # There are at least two ports so show them and ask user to choose @SelectPortView ?= require './views/select-port-view' @selectPortView = new @SelectPortView(delegate) @selectPortView.show() , (e) => console.error e # Show login dialog login: -> @initView 'login' # You may ask why commands aren't registered in LoginView? # This way, we don't need to require/initialize login view until it's needed. atom.workspaceView.command 'spark-dev:cancel-login', => @loginView.cancelCommand() @loginView.show() # Log out current user logout: -> @loginRequired => @initView 'login' @loginView.logout() # Show user's cores list selectCore: -> @loginRequired => @initView 'select-core' @selectCoreView.show() # Show rename core dialog renameCore: -> @coreRequired => @RenameCoreView ?= require './views/rename-core-view' @renameCoreView = new @RenameCoreView(@SettingsHelper.getLocal 'current_core_name') @renameCoreView.attach() # Remove current core from user's account removeCore: -> @coreRequired => removeButton = 'Remove ' + @SettingsHelper.getLocal('current_core_name') buttons = {} buttons['Cancel'] = -> buttons['Remove ' + @SettingsHelper.getLocal('current_core_name')] = => workspace = atom.workspaceView @removePromise = @spark.removeCore @SettingsHelper.getLocal('current_core') @removePromise.done (e) => if !@removePromise return atom.workspaceView = workspace @SettingsHelper.clearCurrentCore() atom.workspaceView.trigger 'spark-dev:update-core-status' atom.workspaceView.trigger 'spark-dev:update-menu' @removePromise = null , (e) => @removePromise = null if e.code == 'ENOTFOUND' message = 'Error while connecting to ' + e.hostname else message = e.info atom.confirm message: 'Error' detailedMessage: message atom.confirm message: 'Removal confirmation' detailedMessage: 'Do you really want to remove ' + @SettingsHelper.getLocal('current_core_name') + '?' buttons: buttons # Show core claiming dialog claimCore: -> @loginRequired => @claimCoreView = null @initView 'claim-core' @claimCoreView.attach() # Identify core via serial identifyCore: (port=null) -> @loginRequired => if !port @choosePort('spark-dev:identify-device') else @SerialHelper ?= require './utils/serial-helper' promise = @SerialHelper.askForCoreID port promise.done (coreID) => @IdentifyCoreView ?= require './views/identify-core-view' @identifyCoreView = new @IdentifyCoreView coreID @identifyCoreView.attach() , (e) => @statusView.setStatus e, 'error' @statusView.clearAfter 5000 # Compile current project in the cloud compileCloud: (thenFlash=null) -> @loginRequired => @projectRequired => if !!@compileCloudPromise return @SettingsHelper.setLocal 'compile-status', {working: true} atom.workspaceView.trigger 'spark-dev:update-compile-status' # Including files fs ?= require 'fs-plus' path ?= require 'path' settings ?= require './vendor/settings' utilities ?= require './vendor/utilities' _s ?= require 'underscore.string' rootPath = atom.project.getPaths()[0] files = @processDirIncludes rootPath process.chdir rootPath files = (path.relative(rootPath, file) for file in files) invalidFiles = files.filter (file) -> path.basename(file).indexOf(' ') > -1 if invalidFiles.length errors = [] for file in invalidFiles errors.push file: file, message: 'File contains space in its name' row: 0, col: 0 @CompileErrorsView ?= require './views/compile-errors-view' @SettingsHelper.setLocal 'compile-status', {errors: errors} atom.workspaceView.trigger 'spark-dev:show-compile-errors' atom.workspaceView.trigger 'spark-dev:update-compile-status' return workspace = atom.workspaceView @compileCloudPromise = @spark.compileCode files @compileCloudPromise.done (e) => if !e return if e.ok # Download binary @compileCloudPromise = null if atom.config.get('spark-dev.deleteOldFirmwareAfterCompile') # Remove old firmwares files = fs.listSync rootPath for file in files if _s.startsWith(path.basename(file), 'firmware') and _s.endsWith(file, '.bin') fs.unlinkSync file filename = 'firmware_' + (new Date()).getTime() + '.bin'; @downloadBinaryPromise = @spark.downloadBinary e.binary_url, rootPath + '/' + filename @downloadBinaryPromise.done (e) => atom.workspaceView = workspace @SettingsHelper.setLocal 'compile-status', {filename: filename} atom.workspaceView.trigger 'spark-dev:update-compile-status' if !!thenFlash setTimeout -> atom.workspaceView.trigger 'spark-dev:flash-cloud' , 500 @downloadBinaryPromise = null , (e) => console.error e else # Handle errors @CompileErrorsView ?= require './views/compile-errors-view' errors = @CompileErrorsView.parseErrors(e.errors[0]) if errors.length == 0 @SettingsHelper.setLocal 'compile-status', {error: e.output} else @SettingsHelper.setLocal 'compile-status', {errors: errors} atom.workspaceView.trigger 'spark-dev:show-compile-errors' atom.workspaceView.trigger 'spark-dev:update-compile-status' @compileCloudPromise = null , (e) => console.error e @SettingsHelper.setLocal 'compile-status', null atom.workspaceView.trigger 'spark-dev:update-compile-status' # Show compile errors list showCompileErrors: -> @initView 'compile-errors' @compileErrorsView.show() # Flash core via the cloud flashCloud: (firmware=null) -> @coreRequired => @projectRequired => fs ?= require 'fs-plus' path ?= require 'path' utilities ?= require './vendor/utilities' rootPath = atom.project.getPaths()[0] files = fs.listSync(rootPath) files = files.filter (file) -> return (utilities.getFilenameExt(file).toLowerCase() == '.bin') if files.length == 0 # If no firmware file, compile atom.workspaceView.trigger 'spark-dev:compile-cloud', [true] else if (files.length == 1) || (!!firmware) # If one firmware file, flash if !firmware firmware = files[0] process.chdir rootPath firmware = path.relative rootPath, firmware @statusView.setStatus 'Flashing via the cloud...' @flashCorePromise = @spark.flashCore @SettingsHelper.getLocal('current_core'), [firmware] @flashCorePromise.done (e) => @statusView.setStatus e.status + '...' @statusView.clearAfter 5000 if atom.config.get 'spark-dev.deleteFirmwareAfterFlash' fs.unlink firmware @flashCorePromise = null , (e) => if e.code == 'ECONNRESET' @statusView.setStatus 'Device seems to be offline', 'error' else @statusView.setStatus e.message, 'error' @statusView.clearAfter 5000 @flashCorePromise = null else # If multiple firmware files, show select @initView 'select-firmware' files.reverse() @selectFirmwareView.setItems files @selectFirmwareView.show() # Show serial monitor panel showSerialMonitor: -> @serialMonitorView = null @openPane 'serial-monitor' # Set up core's WiFi setupWifi: (port=null) -> @loginRequired => if !port @choosePort 'spark-dev:setup-wifi' else @initView 'select-wifi' @selectWifiView.port = port @selectWifiView.show() enterWifiCredentials: (port, ssid=null, security=null) -> @loginRequired => if !port return @wifiCredentialsView = null @initView 'wifi-credentials' @wifiCredentialsView.port = port @wifiCredentialsView.show(ssid, security) tryFlashUsb: -> @projectRequired => if !atom.commands.registeredCommands['spark-dev-dfu-util:flash-usb'] # TODO: Ask for installation else atom.workspaceView.trigger 'spark-dev-dfu-util:flash-usb'
[ { "context": "# MaryJane: a mock object library supporting Arrange Act Ass", "end": 10, "score": 0.9998558759689331, "start": 2, "tag": "NAME", "value": "MaryJane" }, { "context": "p = @_ops[@_ops.length - 1]\n\t\telse\n\t\t\top = @_ops[@_count]\n\t\t@_count++\n\t\top.execute @_mock,...
lib/maryjane.coffee
dhasenan/maryjane
5
# MaryJane: a mock object library supporting Arrange Act Assert syntax. # Standard mock methods # Create a new mock based on: # - a prototype of an existing object # - an existing object # - a constructor exports.mock = (type) -> if !type? throw new Error 'You must provide a type' if typeof type == 'function' new Mock type.prototype else new Mock type exports.when = (mock) -> onMock mock, (m) -> m._mockInternals.newExpectation() exports.verify = (mock, times) -> if !times? times = new Range(1, Infinity) onMock mock, (m) -> m._mockInternals.verify(times) class Range constructor: (@min, @max) -> if !@max? @max = @min toString: -> if @min == @max return 'exactly ' + @min + ' times' if @min <= 0 if @max == Infinity return 'any number of times' else return 'at most ' + @max + ' times' else if @max == Infinity return 'at least ' + @min + ' times' else return 'between ' + @min + ' and ' + @max + ' times' match: (point) -> point <= @max and point >= @min # There's a rather interesting situation here worth mentioning. # The user might have set up some calls before this: # when(mock).blah().thenDo blah # verifyZeroInteractions(mock) # # This is perfectly sensible. They might have some outrageously # horrible or stupid test, maybe with a random element, and # the interactions should be all-or-nothing. # # It's a pretty stupid use case, but we support it! exports.verifyZeroInteractions = (mocks...) -> for mock in mocks onMock mock, (m) -> m._mockInternals.verifyZeroInteractions() exports.verifyNoMoreInteractions = (mocks...) -> for mock in mocks onMock mock, (m) -> m._mockInternals.verifyNoMoreInteractions() # Repeat functions exports.times = (min, max) -> new Range(min, max) exports.never = new Range(0, 0) exports.once = new Range(1, 1) exports.twice = new Range(2, 2) exports.thrice = new Range(3, 3) exports.atLeast = (min) -> new Range(min, Infinity) exports.atMost = (max) -> new Range(0, max) exports.range = (min, max) -> new Range(min, max) class Matcher constructor: (@matcher) -> exports.match = (fn) -> new Matcher fn onMock = (mock, cb) -> if !(mock instanceof Mock) throw new Error 'You can only use this with mock objects' if mock._mockInternals? return cb mock else throw new Error 'Malformed mock object' getName = (type) -> f = type.constructor.toString() f = f.split(' ', 2)[1] f = f.split('(', 2)[0] f.replace ' ', '' formatMethodCall = (typeName, method, args) -> argString = '(' first = true for arg in args if first first = false else argString += ', ' argString += arg argString += ')' return typeName + '.' + method + argString class MockInternals constructor: (@type, @mock) -> if @type == null or @type == undefined throw new Error 'You must provide a type' for key, value of @type addFieldOrMethod(@mock, @type, key) @preparedMethodCalls = [] @unpreparedMethodCalls = [] @recording = false @checking = false @typeName = getName(@type) checkExpectedCall: (field, args) -> if @recording return @record field, args if @checking return @check field, args m = @findCall @preparedMethodCalls, field, args if m? return m.execute args m = @findCall @unpreparedMethodCalls, field, args if !m? m = new MockOptions(@mock, field, args) @unpreparedMethodCalls.push m m.alreadyRan() null check: (field, args) -> @checking = false m = @findCall @preparedMethodCalls, field, args if m? if ! (m instanceof MockOptions) throw new Error 'malformed recorded expectation' if !@range.match m.count() @failCheck field, args, m m.checkedRange @range else m = @findCall @unpreparedMethodCalls, field, args count = if !m? then 0 else m.count() if !@range.match count @failCheck field, args, m if m? m.checkedRange @range null record: (field, args) -> @recording = false m = new MockOptions(@mock, field, args) @preparedMethodCalls.push m m findCall: (list, field, args) -> for call in list if call.matches field, args return call return null failCheck: (field, args, match) -> count = if match? then match.count() else 0 method = formatMethodCall @typeName, field, args throw new Error 'Expected ' + method + ' to be called ' + @range.toString() + ', but it was called ' + count + ' times' newExpectation: -> @recording = true @mock verify: (times) -> @checking = true @range = times @mock verifyNoMoreInteractions: -> # First let's run through and see if we have any excessive calls excessive = [] for call in @unpreparedMethodCalls if call.verified() and call.inExpectedRange() continue excessive.push call for call in @preparedMethodCalls if call.verified() and call.inExpectedRange() continue excessive.push call if excessive.length == 0 return expected = 'Expected:' actual = 'Actual:' for call in excessive expected += '\n\t' expected += call.expectationDescription() actual += '\n\t' actual += call.callDescription() throw new Error expected + '\n' + actual verifyZeroInteractions: -> if @unpreparedMethodCalls.length == 0 && @preparedMethodCalls.length == 0 return first = true result = 'Expected no interactions with ' + @typeName + ', but ' found = false for a in @unpreparedMethodCalls found = true if !first result += '\n\t' result += a.callDescription() first = false for a in @preparedMethodCalls if a.count() > 0 found = true if !first result += '\n\t' result += a.callDescription() first = false if found throw new Error result class Mock constructor: (type) -> if type == null or type == undefined throw new Error 'You must provide a type' @_mockInternals = new MockInternals(type, @) addFieldOrMethod = (mock, type, field) -> f = type[field] if typeof f == 'function' mock[field] = () -> t = mock._mockInternals.checkExpectedCall field, arguments return t else if type.hasOwnProperty field mock[field] = type[field] class MockOperation constructor: (@retval, @exception, @cb) -> execute: (mock, args) -> if @cb? return @cb.apply mock, args else if @exception? throw @exception else return @retval expectation_count = 0 class MockOptions constructor: (@_mock, @_name, @_args) -> # Use constructor assignment; otherwise the prototype fields # leak and you end up setting all mocks ever to strict rather # than just this one @_strict = true @_ops = [] @_count = 0 @_id = expectation_count++ @_matchers = [] lax: -> @_strict = false return @ thenThrow: (ex) -> @_ops.push new MockOperation(null, ex) return @ thenReturn: (value) -> @_ops.push new MockOperation(value) return @ thenDo: (fn) -> @_ops.push new MockOperation(null, null, fn) return @ execute: (args) -> op = null if @_ops.length == 0 @_count++ return null if @_count > @_ops.length op = @_ops[@_ops.length - 1] else op = @_ops[@_count] @_count++ op.execute @_mock, args matches: (name, args) -> if (@_args != null) if (@_strict and @_args.length != args.length) return false if @_args.length > args.length return false for i in [0 ... @_args.length] if args[i] instanceof Matcher if !args[i].matcher(@_args[i]) return false else if @_args[i] instanceof Matcher if !@_args[i].matcher(args[i]) return false else if args[i] != @_args[i] return false return true where: (matchers...) -> if typeof matchers[0] == 'number' or matchers[0] instanceof Number if matchers.length != 2 throw new Error 'When supplying matchers by index, you must give exactly two arguments, the first of which should be a numeric index, the second of which should be a function' if @_matchers[matchers[0]]? throw new Error 'Matcher for argument ' + matchers[0] + ' specified more than once' @_matchers[matchers[0]] = matchers[1] else for m, i in matchers if typeof m != 'function' throw new Error 'MockOptions.where: parameter ' + i + ' is of type ' + (typeof m) + ', but it should be a function' @_matchers.push m @ alreadyRan: -> @_count++ count: -> @_count verified: -> @_verified checkedRange: (range) -> @_checkedRange = range inExpectedRange: -> @_checkedRange.match @_count expectationDescription: -> if @_checkedRange? return @method() + ' should be called ' + @_checkedRange.toString() else return @method() + ' should not be called' method: -> formatMethodCall(@_mock._mockInternals.typeName, @_name, @_args) callDescription: -> @method() + ' was called ' + @_count + ' times'
189340
# <NAME>: a mock object library supporting Arrange Act Assert syntax. # Standard mock methods # Create a new mock based on: # - a prototype of an existing object # - an existing object # - a constructor exports.mock = (type) -> if !type? throw new Error 'You must provide a type' if typeof type == 'function' new Mock type.prototype else new Mock type exports.when = (mock) -> onMock mock, (m) -> m._mockInternals.newExpectation() exports.verify = (mock, times) -> if !times? times = new Range(1, Infinity) onMock mock, (m) -> m._mockInternals.verify(times) class Range constructor: (@min, @max) -> if !@max? @max = @min toString: -> if @min == @max return 'exactly ' + @min + ' times' if @min <= 0 if @max == Infinity return 'any number of times' else return 'at most ' + @max + ' times' else if @max == Infinity return 'at least ' + @min + ' times' else return 'between ' + @min + ' and ' + @max + ' times' match: (point) -> point <= @max and point >= @min # There's a rather interesting situation here worth mentioning. # The user might have set up some calls before this: # when(mock).blah().thenDo blah # verifyZeroInteractions(mock) # # This is perfectly sensible. They might have some outrageously # horrible or stupid test, maybe with a random element, and # the interactions should be all-or-nothing. # # It's a pretty stupid use case, but we support it! exports.verifyZeroInteractions = (mocks...) -> for mock in mocks onMock mock, (m) -> m._mockInternals.verifyZeroInteractions() exports.verifyNoMoreInteractions = (mocks...) -> for mock in mocks onMock mock, (m) -> m._mockInternals.verifyNoMoreInteractions() # Repeat functions exports.times = (min, max) -> new Range(min, max) exports.never = new Range(0, 0) exports.once = new Range(1, 1) exports.twice = new Range(2, 2) exports.thrice = new Range(3, 3) exports.atLeast = (min) -> new Range(min, Infinity) exports.atMost = (max) -> new Range(0, max) exports.range = (min, max) -> new Range(min, max) class Matcher constructor: (@matcher) -> exports.match = (fn) -> new Matcher fn onMock = (mock, cb) -> if !(mock instanceof Mock) throw new Error 'You can only use this with mock objects' if mock._mockInternals? return cb mock else throw new Error 'Malformed mock object' getName = (type) -> f = type.constructor.toString() f = f.split(' ', 2)[1] f = f.split('(', 2)[0] f.replace ' ', '' formatMethodCall = (typeName, method, args) -> argString = '(' first = true for arg in args if first first = false else argString += ', ' argString += arg argString += ')' return typeName + '.' + method + argString class MockInternals constructor: (@type, @mock) -> if @type == null or @type == undefined throw new Error 'You must provide a type' for key, value of @type addFieldOrMethod(@mock, @type, key) @preparedMethodCalls = [] @unpreparedMethodCalls = [] @recording = false @checking = false @typeName = getName(@type) checkExpectedCall: (field, args) -> if @recording return @record field, args if @checking return @check field, args m = @findCall @preparedMethodCalls, field, args if m? return m.execute args m = @findCall @unpreparedMethodCalls, field, args if !m? m = new MockOptions(@mock, field, args) @unpreparedMethodCalls.push m m.alreadyRan() null check: (field, args) -> @checking = false m = @findCall @preparedMethodCalls, field, args if m? if ! (m instanceof MockOptions) throw new Error 'malformed recorded expectation' if !@range.match m.count() @failCheck field, args, m m.checkedRange @range else m = @findCall @unpreparedMethodCalls, field, args count = if !m? then 0 else m.count() if !@range.match count @failCheck field, args, m if m? m.checkedRange @range null record: (field, args) -> @recording = false m = new MockOptions(@mock, field, args) @preparedMethodCalls.push m m findCall: (list, field, args) -> for call in list if call.matches field, args return call return null failCheck: (field, args, match) -> count = if match? then match.count() else 0 method = formatMethodCall @typeName, field, args throw new Error 'Expected ' + method + ' to be called ' + @range.toString() + ', but it was called ' + count + ' times' newExpectation: -> @recording = true @mock verify: (times) -> @checking = true @range = times @mock verifyNoMoreInteractions: -> # First let's run through and see if we have any excessive calls excessive = [] for call in @unpreparedMethodCalls if call.verified() and call.inExpectedRange() continue excessive.push call for call in @preparedMethodCalls if call.verified() and call.inExpectedRange() continue excessive.push call if excessive.length == 0 return expected = 'Expected:' actual = 'Actual:' for call in excessive expected += '\n\t' expected += call.expectationDescription() actual += '\n\t' actual += call.callDescription() throw new Error expected + '\n' + actual verifyZeroInteractions: -> if @unpreparedMethodCalls.length == 0 && @preparedMethodCalls.length == 0 return first = true result = 'Expected no interactions with ' + @typeName + ', but ' found = false for a in @unpreparedMethodCalls found = true if !first result += '\n\t' result += a.callDescription() first = false for a in @preparedMethodCalls if a.count() > 0 found = true if !first result += '\n\t' result += a.callDescription() first = false if found throw new Error result class Mock constructor: (type) -> if type == null or type == undefined throw new Error 'You must provide a type' @_mockInternals = new MockInternals(type, @) addFieldOrMethod = (mock, type, field) -> f = type[field] if typeof f == 'function' mock[field] = () -> t = mock._mockInternals.checkExpectedCall field, arguments return t else if type.hasOwnProperty field mock[field] = type[field] class MockOperation constructor: (@retval, @exception, @cb) -> execute: (mock, args) -> if @cb? return @cb.apply mock, args else if @exception? throw @exception else return @retval expectation_count = 0 class MockOptions constructor: (@_mock, @_name, @_args) -> # Use constructor assignment; otherwise the prototype fields # leak and you end up setting all mocks ever to strict rather # than just this one @_strict = true @_ops = [] @_count = 0 @_id = expectation_count++ @_matchers = [] lax: -> @_strict = false return @ thenThrow: (ex) -> @_ops.push new MockOperation(null, ex) return @ thenReturn: (value) -> @_ops.push new MockOperation(value) return @ thenDo: (fn) -> @_ops.push new MockOperation(null, null, fn) return @ execute: (args) -> op = null if @_ops.length == 0 @_count++ return null if @_count > @_ops.length op = @_ops[@_ops.length - 1] else op = @_ops[@_count] @_count++ op.execute @_mock, args matches: (name, args) -> if (@_args != null) if (@_strict and @_args.length != args.length) return false if @_args.length > args.length return false for i in [0 ... @_args.length] if args[i] instanceof Matcher if !args[i].matcher(@_args[i]) return false else if @_args[i] instanceof Matcher if !@_args[i].matcher(args[i]) return false else if args[i] != @_args[i] return false return true where: (matchers...) -> if typeof matchers[0] == 'number' or matchers[0] instanceof Number if matchers.length != 2 throw new Error 'When supplying matchers by index, you must give exactly two arguments, the first of which should be a numeric index, the second of which should be a function' if @_matchers[matchers[0]]? throw new Error 'Matcher for argument ' + matchers[0] + ' specified more than once' @_matchers[matchers[0]] = matchers[1] else for m, i in matchers if typeof m != 'function' throw new Error 'MockOptions.where: parameter ' + i + ' is of type ' + (typeof m) + ', but it should be a function' @_matchers.push m @ alreadyRan: -> @_count++ count: -> @_count verified: -> @_verified checkedRange: (range) -> @_checkedRange = range inExpectedRange: -> @_checkedRange.match @_count expectationDescription: -> if @_checkedRange? return @method() + ' should be called ' + @_checkedRange.toString() else return @method() + ' should not be called' method: -> formatMethodCall(@_mock._mockInternals.typeName, @_name, @_args) callDescription: -> @method() + ' was called ' + @_count + ' times'
true
# PI:NAME:<NAME>END_PI: a mock object library supporting Arrange Act Assert syntax. # Standard mock methods # Create a new mock based on: # - a prototype of an existing object # - an existing object # - a constructor exports.mock = (type) -> if !type? throw new Error 'You must provide a type' if typeof type == 'function' new Mock type.prototype else new Mock type exports.when = (mock) -> onMock mock, (m) -> m._mockInternals.newExpectation() exports.verify = (mock, times) -> if !times? times = new Range(1, Infinity) onMock mock, (m) -> m._mockInternals.verify(times) class Range constructor: (@min, @max) -> if !@max? @max = @min toString: -> if @min == @max return 'exactly ' + @min + ' times' if @min <= 0 if @max == Infinity return 'any number of times' else return 'at most ' + @max + ' times' else if @max == Infinity return 'at least ' + @min + ' times' else return 'between ' + @min + ' and ' + @max + ' times' match: (point) -> point <= @max and point >= @min # There's a rather interesting situation here worth mentioning. # The user might have set up some calls before this: # when(mock).blah().thenDo blah # verifyZeroInteractions(mock) # # This is perfectly sensible. They might have some outrageously # horrible or stupid test, maybe with a random element, and # the interactions should be all-or-nothing. # # It's a pretty stupid use case, but we support it! exports.verifyZeroInteractions = (mocks...) -> for mock in mocks onMock mock, (m) -> m._mockInternals.verifyZeroInteractions() exports.verifyNoMoreInteractions = (mocks...) -> for mock in mocks onMock mock, (m) -> m._mockInternals.verifyNoMoreInteractions() # Repeat functions exports.times = (min, max) -> new Range(min, max) exports.never = new Range(0, 0) exports.once = new Range(1, 1) exports.twice = new Range(2, 2) exports.thrice = new Range(3, 3) exports.atLeast = (min) -> new Range(min, Infinity) exports.atMost = (max) -> new Range(0, max) exports.range = (min, max) -> new Range(min, max) class Matcher constructor: (@matcher) -> exports.match = (fn) -> new Matcher fn onMock = (mock, cb) -> if !(mock instanceof Mock) throw new Error 'You can only use this with mock objects' if mock._mockInternals? return cb mock else throw new Error 'Malformed mock object' getName = (type) -> f = type.constructor.toString() f = f.split(' ', 2)[1] f = f.split('(', 2)[0] f.replace ' ', '' formatMethodCall = (typeName, method, args) -> argString = '(' first = true for arg in args if first first = false else argString += ', ' argString += arg argString += ')' return typeName + '.' + method + argString class MockInternals constructor: (@type, @mock) -> if @type == null or @type == undefined throw new Error 'You must provide a type' for key, value of @type addFieldOrMethod(@mock, @type, key) @preparedMethodCalls = [] @unpreparedMethodCalls = [] @recording = false @checking = false @typeName = getName(@type) checkExpectedCall: (field, args) -> if @recording return @record field, args if @checking return @check field, args m = @findCall @preparedMethodCalls, field, args if m? return m.execute args m = @findCall @unpreparedMethodCalls, field, args if !m? m = new MockOptions(@mock, field, args) @unpreparedMethodCalls.push m m.alreadyRan() null check: (field, args) -> @checking = false m = @findCall @preparedMethodCalls, field, args if m? if ! (m instanceof MockOptions) throw new Error 'malformed recorded expectation' if !@range.match m.count() @failCheck field, args, m m.checkedRange @range else m = @findCall @unpreparedMethodCalls, field, args count = if !m? then 0 else m.count() if !@range.match count @failCheck field, args, m if m? m.checkedRange @range null record: (field, args) -> @recording = false m = new MockOptions(@mock, field, args) @preparedMethodCalls.push m m findCall: (list, field, args) -> for call in list if call.matches field, args return call return null failCheck: (field, args, match) -> count = if match? then match.count() else 0 method = formatMethodCall @typeName, field, args throw new Error 'Expected ' + method + ' to be called ' + @range.toString() + ', but it was called ' + count + ' times' newExpectation: -> @recording = true @mock verify: (times) -> @checking = true @range = times @mock verifyNoMoreInteractions: -> # First let's run through and see if we have any excessive calls excessive = [] for call in @unpreparedMethodCalls if call.verified() and call.inExpectedRange() continue excessive.push call for call in @preparedMethodCalls if call.verified() and call.inExpectedRange() continue excessive.push call if excessive.length == 0 return expected = 'Expected:' actual = 'Actual:' for call in excessive expected += '\n\t' expected += call.expectationDescription() actual += '\n\t' actual += call.callDescription() throw new Error expected + '\n' + actual verifyZeroInteractions: -> if @unpreparedMethodCalls.length == 0 && @preparedMethodCalls.length == 0 return first = true result = 'Expected no interactions with ' + @typeName + ', but ' found = false for a in @unpreparedMethodCalls found = true if !first result += '\n\t' result += a.callDescription() first = false for a in @preparedMethodCalls if a.count() > 0 found = true if !first result += '\n\t' result += a.callDescription() first = false if found throw new Error result class Mock constructor: (type) -> if type == null or type == undefined throw new Error 'You must provide a type' @_mockInternals = new MockInternals(type, @) addFieldOrMethod = (mock, type, field) -> f = type[field] if typeof f == 'function' mock[field] = () -> t = mock._mockInternals.checkExpectedCall field, arguments return t else if type.hasOwnProperty field mock[field] = type[field] class MockOperation constructor: (@retval, @exception, @cb) -> execute: (mock, args) -> if @cb? return @cb.apply mock, args else if @exception? throw @exception else return @retval expectation_count = 0 class MockOptions constructor: (@_mock, @_name, @_args) -> # Use constructor assignment; otherwise the prototype fields # leak and you end up setting all mocks ever to strict rather # than just this one @_strict = true @_ops = [] @_count = 0 @_id = expectation_count++ @_matchers = [] lax: -> @_strict = false return @ thenThrow: (ex) -> @_ops.push new MockOperation(null, ex) return @ thenReturn: (value) -> @_ops.push new MockOperation(value) return @ thenDo: (fn) -> @_ops.push new MockOperation(null, null, fn) return @ execute: (args) -> op = null if @_ops.length == 0 @_count++ return null if @_count > @_ops.length op = @_ops[@_ops.length - 1] else op = @_ops[@_count] @_count++ op.execute @_mock, args matches: (name, args) -> if (@_args != null) if (@_strict and @_args.length != args.length) return false if @_args.length > args.length return false for i in [0 ... @_args.length] if args[i] instanceof Matcher if !args[i].matcher(@_args[i]) return false else if @_args[i] instanceof Matcher if !@_args[i].matcher(args[i]) return false else if args[i] != @_args[i] return false return true where: (matchers...) -> if typeof matchers[0] == 'number' or matchers[0] instanceof Number if matchers.length != 2 throw new Error 'When supplying matchers by index, you must give exactly two arguments, the first of which should be a numeric index, the second of which should be a function' if @_matchers[matchers[0]]? throw new Error 'Matcher for argument ' + matchers[0] + ' specified more than once' @_matchers[matchers[0]] = matchers[1] else for m, i in matchers if typeof m != 'function' throw new Error 'MockOptions.where: parameter ' + i + ' is of type ' + (typeof m) + ', but it should be a function' @_matchers.push m @ alreadyRan: -> @_count++ count: -> @_count verified: -> @_verified checkedRange: (range) -> @_checkedRange = range inExpectedRange: -> @_checkedRange.match @_count expectationDescription: -> if @_checkedRange? return @method() + ' should be called ' + @_checkedRange.toString() else return @method() + ' should not be called' method: -> formatMethodCall(@_mock._mockInternals.typeName, @_name, @_args) callDescription: -> @method() + ' was called ' + @_count + ' times'
[ { "context": "/postLogin\", {\n\t\t\t\tname: v_this.name\n\t\t\t\tpassword: v_this.password\n\t\t\t}, (msg)->\n\t\t\t\tconsole.log msg\n\t\t\t\tv_this.sub_", "end": 544, "score": 0.9990624189376831, "start": 529, "tag": "PASSWORD", "value": "v_this.password" } ]
public/src/pages/login.coffee
Jv-Juven/usedmk
0
# Vue = require "../../lib/vue/vue.js" form = new Vue { el: "#login" data: { name: "", password: "", sub_tips: "",# “提交”按钮提示信息 tips_type: -1 } methods: submit: ()-> if ( this.name.length < 1 || this.name.length > 20 ) this.sub_tips = "请输入1-20位的用户名" this.tips_type = 1 return if ( this.password.length < 6 || this.password.length > 20 ) this.sub_tips = "请输入6-20位的密码" this.tips_type = 1 return v_this = this $.post "/postLogin", { name: v_this.name password: v_this.password }, (msg)-> console.log msg v_this.sub_tips = msg.message v_this.tips_type = msg.errCode nowarn: ()-> this.sub_tips = "" this.tips_type = -1 }
106834
# Vue = require "../../lib/vue/vue.js" form = new Vue { el: "#login" data: { name: "", password: "", sub_tips: "",# “提交”按钮提示信息 tips_type: -1 } methods: submit: ()-> if ( this.name.length < 1 || this.name.length > 20 ) this.sub_tips = "请输入1-20位的用户名" this.tips_type = 1 return if ( this.password.length < 6 || this.password.length > 20 ) this.sub_tips = "请输入6-20位的密码" this.tips_type = 1 return v_this = this $.post "/postLogin", { name: v_this.name password: <PASSWORD> }, (msg)-> console.log msg v_this.sub_tips = msg.message v_this.tips_type = msg.errCode nowarn: ()-> this.sub_tips = "" this.tips_type = -1 }
true
# Vue = require "../../lib/vue/vue.js" form = new Vue { el: "#login" data: { name: "", password: "", sub_tips: "",# “提交”按钮提示信息 tips_type: -1 } methods: submit: ()-> if ( this.name.length < 1 || this.name.length > 20 ) this.sub_tips = "请输入1-20位的用户名" this.tips_type = 1 return if ( this.password.length < 6 || this.password.length > 20 ) this.sub_tips = "请输入6-20位的密码" this.tips_type = 1 return v_this = this $.post "/postLogin", { name: v_this.name password: PI:PASSWORD:<PASSWORD>END_PI }, (msg)-> console.log msg v_this.sub_tips = msg.message v_this.tips_type = msg.errCode nowarn: ()-> this.sub_tips = "" this.tips_type = -1 }
[ { "context": "ser', ->\n @timeout 500000\n\t\n user = \n name: 'user'\n email: 'user@abc.com'\n files = [\n '/usr/", "end": 109, "score": 0.9980341792106628, "start": 105, "tag": "USERNAME", "value": "user" }, { "context": "t 500000\n\t\n user = \n name: 'user'\n e...
test/unit/0-model/0-User.coffee
twhtanghk/restfile
0
_ = require 'lodash' path = require 'path' describe 'User', -> @timeout 500000 user = name: 'user' email: 'user@abc.com' files = [ '/usr/src/app/LICENSE' '/usr/src/app/README.md' '/usr/src/app/Dockerfile' '/usr/src/app/package.json' '/usr/src/app/app.js' ] it "create user #{user.email}", (done) -> sails.models.user .create user .then -> done() .catch done
6358
_ = require 'lodash' path = require 'path' describe 'User', -> @timeout 500000 user = name: 'user' email: '<EMAIL>' files = [ '/usr/src/app/LICENSE' '/usr/src/app/README.md' '/usr/src/app/Dockerfile' '/usr/src/app/package.json' '/usr/src/app/app.js' ] it "create user #{user.email}", (done) -> sails.models.user .create user .then -> done() .catch done
true
_ = require 'lodash' path = require 'path' describe 'User', -> @timeout 500000 user = name: 'user' email: 'PI:EMAIL:<EMAIL>END_PI' files = [ '/usr/src/app/LICENSE' '/usr/src/app/README.md' '/usr/src/app/Dockerfile' '/usr/src/app/package.json' '/usr/src/app/app.js' ] it "create user #{user.email}", (done) -> sails.models.user .create user .then -> done() .catch done
[ { "context": "orm Javascript Library\n\n URL: https://github.com/jondavidjohn/payform\n Author: Jonathan D. Johnson <me@jondavi", "end": 72, "score": 0.813970148563385, "start": 60, "tag": "USERNAME", "value": "jondavidjohn" }, { "context": " https://github.com/jondavidjohn/payform...
src/payform.coffee
sergiocruz/payform
0
### Payform Javascript Library URL: https://github.com/jondavidjohn/payform Author: Jonathan D. Johnson <me@jondavidjohn.com> License: MIT Version: 1.3.0 ### ((name, definition) -> if module? module.exports = definition() else if typeof define is 'function' and typeof define.amd is 'object' define(name, definition) else this[name] = definition() )('payform', -> _getCaretPos = (ele) -> if ele.selectionStart? return ele.selectionStart else if document.selection? ele.focus() r = document.selection.createRange() re = ele.createTextRange() rc = re.duplicate() re.moveToBookmark(r.getBookmark()) rc.setEndPoint('EndToStart', re) return rc.text.length _eventNormalize = (listener) -> return (e = window.event) -> if e.inputType == 'insertCompositionText' and !e.isComposing return newEvt = target: e.target or e.srcElement which: e.which or e.keyCode type: e.type metaKey: e.metaKey ctrlKey: e.ctrlKey preventDefault: -> if e.preventDefault e.preventDefault() else e.returnValue = false return listener(newEvt) _on = (ele, event, listener) -> listener = _eventNormalize(listener) if ele.addEventListener? ele.addEventListener(event, listener, false) else ele.attachEvent("on#{event}", listener) payform = {} # Key Codes keyCodes = { UNKNOWN : 0, BACKSPACE : 8, PAGE_UP : 33, ARROW_LEFT : 37, ARROW_RIGHT : 39, } # Utils defaultFormat = /(\d{1,4})/g payform.cards = [ # Debit cards must come first, since they have more # specific patterns than their credit-card equivalents. { type: 'elo' pattern: /^(4011(78|79)|43(1274|8935)|45(1416|7393|763(1|2))|50(4175|6699|67[0-7][0-9]|9000)|627780|63(6297|6368)|650(03([^4])|04([0-9])|05(0|1)|4(0[5-9]|3[0-9]|8[5-9]|9[0-9])|5([0-2][0-9]|3[0-8])|9([2-6][0-9]|7[0-8])|541|700|720|901)|651652|655000|655021)/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'visaelectron' pattern: /^4(026|17500|405|508|844|91[37])/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'maestro' pattern: /^(5018|5020|5038|6304|6703|6708|6759|676[1-3])/ format: defaultFormat length: [12..19] cvcLength: [3] luhn: true } { type: 'forbrugsforeningen' pattern: /^600/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'dankort' pattern: /^5019/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } # Credit cards { type: 'visa' pattern: /^4/ format: defaultFormat length: [13, 16, 19] cvcLength: [3] luhn: true } { type: 'mastercard' pattern: /^(5[1-5]|677189)|^(222[1-9]|2[3-6]\d{2}|27[0-1]\d|2720)/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'amex' pattern: /^3[47]/ format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/ length: [15] cvcLength: [4] luhn: true } # Must be above dinersclub. { type: 'hipercard' pattern: /^(384100|384140|384160|606282|637095|637568|60(?!11))/ format: defaultFormat length: [14..19] cvcLength: [3] luhn: true } { type: 'dinersclub' pattern: /^(36|38|30[0-5])/ format: /(\d{1,4})(\d{1,6})?(\d{1,4})?/ length: [14] cvcLength: [3] luhn: true } { type: 'discover' pattern: /^(6011|65|64[4-9]|622)/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'unionpay' pattern: /^62/ format: defaultFormat length: [16..19] cvcLength: [3] luhn: false } { type: 'jcb' pattern: /^35/ format: defaultFormat length: [16..19] cvcLength: [3] luhn: true } { type: 'laser' pattern: /^(6706|6771|6709)/ format: defaultFormat length: [16..19] cvcLength: [3] luhn: true } ] cardFromNumber = (num) -> num = (num + '').replace(/\D/g, '') return card for card in payform.cards when card.pattern.test(num) cardFromType = (type) -> return card for card in payform.cards when card.type is type getDirectionality = (target) -> # Work around Firefox not returning the styles in some edge cases. # In Firefox < 62, style can be `null`. # In Firefox 62+, `style['direction']` can be an empty string. # See https://bugzilla.mozilla.org/show_bug.cgi?id=1467722. style = getComputedStyle(target) style and style['direction'] or document.dir luhnCheck = (num) -> odd = true sum = 0 digits = (num + '').split('').reverse() for digit in digits digit = parseInt(digit, 10) digit *= 2 if (odd = !odd) digit -= 9 if digit > 9 sum += digit sum % 10 == 0 hasTextSelected = (target) -> # If some text is selected in IE if document?.selection?.createRange? return true if document.selection.createRange().text target.selectionStart? and target.selectionStart isnt target.selectionEnd # Private # Replace Full-Width Chars replaceFullWidthChars = (str = '') -> fullWidth = '\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19' halfWidth = '0123456789' value = '' chars = str.split('') for char in chars idx = fullWidth.indexOf(char) char = halfWidth[idx] if idx > -1 value += char value # Format Card Number reFormatCardNumber = (e) -> cursor = _getCaretPos(e.target) return if e.target.value is "" if getDirectionality(e.target) == 'ltr' cursor = _getCaretPos(e.target) e.target.value = payform.formatCardNumber(e.target.value) if getDirectionality(e.target) == 'ltr' and cursor isnt e.target.selectionStart cursor = _getCaretPos(e.target) if getDirectionality(e.target) == 'rtl' and e.target.value.indexOf('‎\u200e') == -1 e.target.value = '‎\u200e'.concat(e.target.value) cursor = _getCaretPos(e.target) if cursor? and cursor isnt 0 and e.type isnt 'change' e.target.setSelectionRange(cursor, cursor) formatCardNumber = (e) -> # Only format if input is a number digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) value = e.target.value card = cardFromNumber(value + digit) length = (value.replace(/\D/g, '') + digit).length upperLength = 16 upperLength = card.length[card.length.length - 1] if card return if length >= upperLength # Return if focus isn't at the end of the text cursor = _getCaretPos(e.target) return if cursor and cursor isnt value.length if card && card.type is 'amex' # AMEX cards are formatted differently re = /^(\d{4}|\d{4}\s\d{6})$/ else re = /(?:^|\s)(\d{4})$/ # If '4242' + 4 if re.test(value) e.preventDefault() setTimeout -> e.target.value = "#{value} #{digit}" # If '424' + 2 else if re.test(value + digit) e.preventDefault() setTimeout -> e.target.value = "#{value + digit} " formatBackCardNumber = (e) -> value = e.target.value # Return unless backspacing return unless e.which is keyCodes.BACKSPACE # Return if focus isn't at the end of the text cursor = _getCaretPos(e.target) return if cursor and cursor isnt value.length return if (e.target.selectionEnd - e.target.selectionStart) > 1 # Remove the digit + trailing space if /\d\s$/.test(value) e.preventDefault() setTimeout -> e.target.value = value.replace /\d\s$/, '' # Remove digit if ends in space + digit else if /\s\d?$/.test(value) e.preventDefault() setTimeout -> e.target.value = value.replace /\d$/, '' # Format Expiry reFormatExpiry = (e) -> return if e.target.value is "" e.target.value = payform.formatCardExpiry(e.target.value) if getDirectionality(e.target) == 'rtl' and e.target.value.indexOf('‎\u200e') == -1 e.target.value = '‎\u200e'.concat(e.target.value) cursor = _getCaretPos(e.target) if cursor? and e.type isnt 'change' e.target.setSelectionRange(cursor, cursor) formatCardExpiry = (e) -> # Only format if input is a number digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) val = e.target.value + digit if /^\d$/.test(val) and val not in ['0', '1'] e.preventDefault() setTimeout -> e.target.value = "0#{val} / " else if /^\d\d$/.test(val) e.preventDefault() setTimeout -> e.target.value = "#{val} / " formatForwardExpiry = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) val = e.target.value if /^\d\d$/.test(val) e.target.value = "#{val} / " formatForwardSlashAndSpace = (e) -> which = String.fromCharCode(e.which) return unless which is '/' or which is ' ' val = e.target.value if /^\d$/.test(val) and val isnt '0' e.target.value = "0#{val} / " formatBackExpiry = (e) -> value = e.target.value # Return unless backspacing return unless e.which is keyCodes.BACKSPACE # Return if focus isn't at the end of the text cursor = _getCaretPos(e.target) return if cursor and cursor isnt value.length # Remove the trailing space + last digit if /\d\s\/\s$/.test(value) e.preventDefault() setTimeout -> e.target.value = value.replace(/\d\s\/\s$/, '') # Format CVC reFormatCVC = (e) -> return if e.target.value is "" cursor = _getCaretPos(e.target) e.target.value = replaceFullWidthChars(e.target.value).replace(/\D/g, '')[0...4] if cursor? and e.type isnt 'change' e.target.setSelectionRange(cursor, cursor) # Restrictions restrictNumeric = (e) -> # Key event is for a browser shortcut return if e.metaKey or e.ctrlKey # If keycode is a special char (WebKit) return if [keyCodes.UNKNOWN, keyCodes.ARROW_LEFT, keyCodes.ARROW_RIGHT].indexOf(e.which) > -1 # If char is a special char (Firefox) return if e.which < keyCodes.PAGE_UP input = String.fromCharCode(e.which) # Char is a number unless /^\d+$/.test(input) e.preventDefault() restrictCardNumber = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) return if hasTextSelected(e.target) # Restrict number of digits value = (e.target.value + digit).replace(/\D/g, '') card = cardFromNumber(value) maxLength = if card then card.length[card.length.length - 1] else 16 if value.length > maxLength e.preventDefault() restrictExpiry = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) return if hasTextSelected(e.target) value = e.target.value + digit value = value.replace(/\D/g, '') if value.length > 6 e.preventDefault() restrictCVC = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) return if hasTextSelected(e.target) val = e.target.value + digit if val.length > 4 e.preventDefault() # Public # Formatting payform.cvcInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'keypress', restrictCVC) _on(input, 'paste', reFormatCVC) _on(input, 'change', reFormatCVC) _on(input, 'input', reFormatCVC) payform.expiryInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'keypress', restrictExpiry) _on(input, 'keypress', formatCardExpiry) _on(input, 'keypress', formatForwardSlashAndSpace) _on(input, 'keypress', formatForwardExpiry) _on(input, 'keydown', formatBackExpiry) _on(input, 'change', reFormatExpiry) _on(input, 'input', reFormatExpiry) payform.cardNumberInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'keypress', restrictCardNumber) _on(input, 'keypress', formatCardNumber) _on(input, 'keydown', formatBackCardNumber) _on(input, 'paste', reFormatCardNumber) _on(input, 'change', reFormatCardNumber) _on(input, 'input', reFormatCardNumber) payform.numericInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'paste', restrictNumeric) _on(input, 'change', restrictNumeric) _on(input, 'input', restrictNumeric) # Validations payform.parseCardExpiry = (value) -> value = value.replace(/\s/g, '') [month, year] = value.split('/', 2) # Allow for year shortcut if year?.length is 2 and /^\d+$/.test(year) prefix = (new Date).getFullYear() prefix = prefix.toString()[0..1] year = prefix + year # Remove left-to-right mark LTR invisible unicode control character used in right-to-left contexts month = parseInt(month.replace(/[\u200e]/g, ""), 10); year = parseInt(year, 10) month: month, year: year payform.validateCardNumber = (num) -> num = (num + '').replace(/\s+|-/g, '') return false unless /^\d+$/.test(num) card = cardFromNumber(num) return false unless card num.length in card.length and (card.luhn is false or luhnCheck(num)) payform.validateCardExpiry = (month, year) -> # Allow passing an object if typeof month is 'object' and 'month' of month {month, year} = month return false unless month and year month = String(month).trim() year = String(year).trim() return false unless /^\d+$/.test(month) return false unless /^\d+$/.test(year) return false unless 1 <= month <= 12 if year.length == 2 if year < 70 year = "20#{year}" else year = "19#{year}" return false unless year.length == 4 expiry = new Date(year, month) currentTime = new Date # Months start from 0 in JavaScript expiry.setMonth(expiry.getMonth() - 1) # The cc expires at the end of the month, # so we need to make the expiry the first day # of the month after expiry.setMonth(expiry.getMonth() + 1, 1) expiry > currentTime payform.validateCardCVC = (cvc, type) -> cvc = String(cvc).trim() return false unless /^\d+$/.test(cvc) card = cardFromType(type) if card? # Check against a explicit card type cvc.length in card.cvcLength else # Check against all types cvc.length >= 3 and cvc.length <= 4 payform.parseCardType = (num) -> return null unless num cardFromNumber(num)?.type or null payform.formatCardNumber = (num) -> num = replaceFullWidthChars(num) num = num.replace(/\D/g, '') card = cardFromNumber(num) return num unless card upperLength = card.length[card.length.length - 1] num = num[0...upperLength] if card.format.global num.match(card.format)?.join(' ') else groups = card.format.exec(num) return unless groups? groups.shift() groups = groups.filter(Boolean) groups.join(' ') payform.formatCardExpiry = (expiry) -> expiry = replaceFullWidthChars(expiry) parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/) return '' unless parts mon = parts[1] || '' sep = parts[2] || '' year = parts[3] || '' if year.length > 0 sep = ' / ' else if sep is ' /' mon = mon.substring(0, 1) sep = '' else if mon.length == 2 or sep.length > 0 sep = ' / ' else if mon.length == 1 and mon not in ['0', '1'] mon = "0#{mon}" sep = ' / ' return mon + sep + year payform )
11452
### Payform Javascript Library URL: https://github.com/jondavidjohn/payform Author: <NAME> <<EMAIL>> License: MIT Version: 1.3.0 ### ((name, definition) -> if module? module.exports = definition() else if typeof define is 'function' and typeof define.amd is 'object' define(name, definition) else this[name] = definition() )('payform', -> _getCaretPos = (ele) -> if ele.selectionStart? return ele.selectionStart else if document.selection? ele.focus() r = document.selection.createRange() re = ele.createTextRange() rc = re.duplicate() re.moveToBookmark(r.getBookmark()) rc.setEndPoint('EndToStart', re) return rc.text.length _eventNormalize = (listener) -> return (e = window.event) -> if e.inputType == 'insertCompositionText' and !e.isComposing return newEvt = target: e.target or e.srcElement which: e.which or e.keyCode type: e.type metaKey: e.metaKey ctrlKey: e.ctrlKey preventDefault: -> if e.preventDefault e.preventDefault() else e.returnValue = false return listener(newEvt) _on = (ele, event, listener) -> listener = _eventNormalize(listener) if ele.addEventListener? ele.addEventListener(event, listener, false) else ele.attachEvent("on#{event}", listener) payform = {} # Key Codes keyCodes = { UNKNOWN : 0, BACKSPACE : 8, PAGE_UP : 33, ARROW_LEFT : 37, ARROW_RIGHT : 39, } # Utils defaultFormat = /(\d{1,4})/g payform.cards = [ # Debit cards must come first, since they have more # specific patterns than their credit-card equivalents. { type: 'elo' pattern: /^(4011(78|79)|43(1274|8935)|45(1416|7393|763(1|2))|50(4175|6699|67[0-7][0-9]|9000)|627780|63(6297|6368)|650(03([^4])|04([0-9])|05(0|1)|4(0[5-9]|3[0-9]|8[5-9]|9[0-9])|5([0-2][0-9]|3[0-8])|9([2-6][0-9]|7[0-8])|541|700|720|901)|651652|655000|655021)/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'visaelectron' pattern: /^4(026|17500|405|508|844|91[37])/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'maestro' pattern: /^(5018|5020|5038|6304|6703|6708|6759|676[1-3])/ format: defaultFormat length: [12..19] cvcLength: [3] luhn: true } { type: 'forbrugsforeningen' pattern: /^600/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'dankort' pattern: /^5019/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } # Credit cards { type: 'visa' pattern: /^4/ format: defaultFormat length: [13, 16, 19] cvcLength: [3] luhn: true } { type: 'mastercard' pattern: /^(5[1-5]|677189)|^(222[1-9]|2[3-6]\d{2}|27[0-1]\d|2720)/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'amex' pattern: /^3[47]/ format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/ length: [15] cvcLength: [4] luhn: true } # Must be above dinersclub. { type: 'hipercard' pattern: /^(384100|384140|384160|606282|637095|637568|60(?!11))/ format: defaultFormat length: [14..19] cvcLength: [3] luhn: true } { type: 'dinersclub' pattern: /^(36|38|30[0-5])/ format: /(\d{1,4})(\d{1,6})?(\d{1,4})?/ length: [14] cvcLength: [3] luhn: true } { type: 'discover' pattern: /^(6011|65|64[4-9]|622)/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'unionpay' pattern: /^62/ format: defaultFormat length: [16..19] cvcLength: [3] luhn: false } { type: 'jcb' pattern: /^35/ format: defaultFormat length: [16..19] cvcLength: [3] luhn: true } { type: 'laser' pattern: /^(6706|6771|6709)/ format: defaultFormat length: [16..19] cvcLength: [3] luhn: true } ] cardFromNumber = (num) -> num = (num + '').replace(/\D/g, '') return card for card in payform.cards when card.pattern.test(num) cardFromType = (type) -> return card for card in payform.cards when card.type is type getDirectionality = (target) -> # Work around Firefox not returning the styles in some edge cases. # In Firefox < 62, style can be `null`. # In Firefox 62+, `style['direction']` can be an empty string. # See https://bugzilla.mozilla.org/show_bug.cgi?id=1467722. style = getComputedStyle(target) style and style['direction'] or document.dir luhnCheck = (num) -> odd = true sum = 0 digits = (num + '').split('').reverse() for digit in digits digit = parseInt(digit, 10) digit *= 2 if (odd = !odd) digit -= 9 if digit > 9 sum += digit sum % 10 == 0 hasTextSelected = (target) -> # If some text is selected in IE if document?.selection?.createRange? return true if document.selection.createRange().text target.selectionStart? and target.selectionStart isnt target.selectionEnd # Private # Replace Full-Width Chars replaceFullWidthChars = (str = '') -> fullWidth = '\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19' halfWidth = '0123456789' value = '' chars = str.split('') for char in chars idx = fullWidth.indexOf(char) char = halfWidth[idx] if idx > -1 value += char value # Format Card Number reFormatCardNumber = (e) -> cursor = _getCaretPos(e.target) return if e.target.value is "" if getDirectionality(e.target) == 'ltr' cursor = _getCaretPos(e.target) e.target.value = payform.formatCardNumber(e.target.value) if getDirectionality(e.target) == 'ltr' and cursor isnt e.target.selectionStart cursor = _getCaretPos(e.target) if getDirectionality(e.target) == 'rtl' and e.target.value.indexOf('‎\u200e') == -1 e.target.value = '‎\u200e'.concat(e.target.value) cursor = _getCaretPos(e.target) if cursor? and cursor isnt 0 and e.type isnt 'change' e.target.setSelectionRange(cursor, cursor) formatCardNumber = (e) -> # Only format if input is a number digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) value = e.target.value card = cardFromNumber(value + digit) length = (value.replace(/\D/g, '') + digit).length upperLength = 16 upperLength = card.length[card.length.length - 1] if card return if length >= upperLength # Return if focus isn't at the end of the text cursor = _getCaretPos(e.target) return if cursor and cursor isnt value.length if card && card.type is 'amex' # AMEX cards are formatted differently re = /^(\d{4}|\d{4}\s\d{6})$/ else re = /(?:^|\s)(\d{4})$/ # If '4242' + 4 if re.test(value) e.preventDefault() setTimeout -> e.target.value = "#{value} #{digit}" # If '424' + 2 else if re.test(value + digit) e.preventDefault() setTimeout -> e.target.value = "#{value + digit} " formatBackCardNumber = (e) -> value = e.target.value # Return unless backspacing return unless e.which is keyCodes.BACKSPACE # Return if focus isn't at the end of the text cursor = _getCaretPos(e.target) return if cursor and cursor isnt value.length return if (e.target.selectionEnd - e.target.selectionStart) > 1 # Remove the digit + trailing space if /\d\s$/.test(value) e.preventDefault() setTimeout -> e.target.value = value.replace /\d\s$/, '' # Remove digit if ends in space + digit else if /\s\d?$/.test(value) e.preventDefault() setTimeout -> e.target.value = value.replace /\d$/, '' # Format Expiry reFormatExpiry = (e) -> return if e.target.value is "" e.target.value = payform.formatCardExpiry(e.target.value) if getDirectionality(e.target) == 'rtl' and e.target.value.indexOf('‎\u200e') == -1 e.target.value = '‎\u200e'.concat(e.target.value) cursor = _getCaretPos(e.target) if cursor? and e.type isnt 'change' e.target.setSelectionRange(cursor, cursor) formatCardExpiry = (e) -> # Only format if input is a number digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) val = e.target.value + digit if /^\d$/.test(val) and val not in ['0', '1'] e.preventDefault() setTimeout -> e.target.value = "0#{val} / " else if /^\d\d$/.test(val) e.preventDefault() setTimeout -> e.target.value = "#{val} / " formatForwardExpiry = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) val = e.target.value if /^\d\d$/.test(val) e.target.value = "#{val} / " formatForwardSlashAndSpace = (e) -> which = String.fromCharCode(e.which) return unless which is '/' or which is ' ' val = e.target.value if /^\d$/.test(val) and val isnt '0' e.target.value = "0#{val} / " formatBackExpiry = (e) -> value = e.target.value # Return unless backspacing return unless e.which is keyCodes.BACKSPACE # Return if focus isn't at the end of the text cursor = _getCaretPos(e.target) return if cursor and cursor isnt value.length # Remove the trailing space + last digit if /\d\s\/\s$/.test(value) e.preventDefault() setTimeout -> e.target.value = value.replace(/\d\s\/\s$/, '') # Format CVC reFormatCVC = (e) -> return if e.target.value is "" cursor = _getCaretPos(e.target) e.target.value = replaceFullWidthChars(e.target.value).replace(/\D/g, '')[0...4] if cursor? and e.type isnt 'change' e.target.setSelectionRange(cursor, cursor) # Restrictions restrictNumeric = (e) -> # Key event is for a browser shortcut return if e.metaKey or e.ctrlKey # If keycode is a special char (WebKit) return if [keyCodes.UNKNOWN, keyCodes.ARROW_LEFT, keyCodes.ARROW_RIGHT].indexOf(e.which) > -1 # If char is a special char (Firefox) return if e.which < keyCodes.PAGE_UP input = String.fromCharCode(e.which) # Char is a number unless /^\d+$/.test(input) e.preventDefault() restrictCardNumber = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) return if hasTextSelected(e.target) # Restrict number of digits value = (e.target.value + digit).replace(/\D/g, '') card = cardFromNumber(value) maxLength = if card then card.length[card.length.length - 1] else 16 if value.length > maxLength e.preventDefault() restrictExpiry = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) return if hasTextSelected(e.target) value = e.target.value + digit value = value.replace(/\D/g, '') if value.length > 6 e.preventDefault() restrictCVC = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) return if hasTextSelected(e.target) val = e.target.value + digit if val.length > 4 e.preventDefault() # Public # Formatting payform.cvcInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'keypress', restrictCVC) _on(input, 'paste', reFormatCVC) _on(input, 'change', reFormatCVC) _on(input, 'input', reFormatCVC) payform.expiryInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'keypress', restrictExpiry) _on(input, 'keypress', formatCardExpiry) _on(input, 'keypress', formatForwardSlashAndSpace) _on(input, 'keypress', formatForwardExpiry) _on(input, 'keydown', formatBackExpiry) _on(input, 'change', reFormatExpiry) _on(input, 'input', reFormatExpiry) payform.cardNumberInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'keypress', restrictCardNumber) _on(input, 'keypress', formatCardNumber) _on(input, 'keydown', formatBackCardNumber) _on(input, 'paste', reFormatCardNumber) _on(input, 'change', reFormatCardNumber) _on(input, 'input', reFormatCardNumber) payform.numericInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'paste', restrictNumeric) _on(input, 'change', restrictNumeric) _on(input, 'input', restrictNumeric) # Validations payform.parseCardExpiry = (value) -> value = value.replace(/\s/g, '') [month, year] = value.split('/', 2) # Allow for year shortcut if year?.length is 2 and /^\d+$/.test(year) prefix = (new Date).getFullYear() prefix = prefix.toString()[0..1] year = prefix + year # Remove left-to-right mark LTR invisible unicode control character used in right-to-left contexts month = parseInt(month.replace(/[\u200e]/g, ""), 10); year = parseInt(year, 10) month: month, year: year payform.validateCardNumber = (num) -> num = (num + '').replace(/\s+|-/g, '') return false unless /^\d+$/.test(num) card = cardFromNumber(num) return false unless card num.length in card.length and (card.luhn is false or luhnCheck(num)) payform.validateCardExpiry = (month, year) -> # Allow passing an object if typeof month is 'object' and 'month' of month {month, year} = month return false unless month and year month = String(month).trim() year = String(year).trim() return false unless /^\d+$/.test(month) return false unless /^\d+$/.test(year) return false unless 1 <= month <= 12 if year.length == 2 if year < 70 year = "20#{year}" else year = "19#{year}" return false unless year.length == 4 expiry = new Date(year, month) currentTime = new Date # Months start from 0 in JavaScript expiry.setMonth(expiry.getMonth() - 1) # The cc expires at the end of the month, # so we need to make the expiry the first day # of the month after expiry.setMonth(expiry.getMonth() + 1, 1) expiry > currentTime payform.validateCardCVC = (cvc, type) -> cvc = String(cvc).trim() return false unless /^\d+$/.test(cvc) card = cardFromType(type) if card? # Check against a explicit card type cvc.length in card.cvcLength else # Check against all types cvc.length >= 3 and cvc.length <= 4 payform.parseCardType = (num) -> return null unless num cardFromNumber(num)?.type or null payform.formatCardNumber = (num) -> num = replaceFullWidthChars(num) num = num.replace(/\D/g, '') card = cardFromNumber(num) return num unless card upperLength = card.length[card.length.length - 1] num = num[0...upperLength] if card.format.global num.match(card.format)?.join(' ') else groups = card.format.exec(num) return unless groups? groups.shift() groups = groups.filter(Boolean) groups.join(' ') payform.formatCardExpiry = (expiry) -> expiry = replaceFullWidthChars(expiry) parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/) return '' unless parts mon = parts[1] || '' sep = parts[2] || '' year = parts[3] || '' if year.length > 0 sep = ' / ' else if sep is ' /' mon = mon.substring(0, 1) sep = '' else if mon.length == 2 or sep.length > 0 sep = ' / ' else if mon.length == 1 and mon not in ['0', '1'] mon = "0#{mon}" sep = ' / ' return mon + sep + year payform )
true
### Payform Javascript Library URL: https://github.com/jondavidjohn/payform Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> License: MIT Version: 1.3.0 ### ((name, definition) -> if module? module.exports = definition() else if typeof define is 'function' and typeof define.amd is 'object' define(name, definition) else this[name] = definition() )('payform', -> _getCaretPos = (ele) -> if ele.selectionStart? return ele.selectionStart else if document.selection? ele.focus() r = document.selection.createRange() re = ele.createTextRange() rc = re.duplicate() re.moveToBookmark(r.getBookmark()) rc.setEndPoint('EndToStart', re) return rc.text.length _eventNormalize = (listener) -> return (e = window.event) -> if e.inputType == 'insertCompositionText' and !e.isComposing return newEvt = target: e.target or e.srcElement which: e.which or e.keyCode type: e.type metaKey: e.metaKey ctrlKey: e.ctrlKey preventDefault: -> if e.preventDefault e.preventDefault() else e.returnValue = false return listener(newEvt) _on = (ele, event, listener) -> listener = _eventNormalize(listener) if ele.addEventListener? ele.addEventListener(event, listener, false) else ele.attachEvent("on#{event}", listener) payform = {} # Key Codes keyCodes = { UNKNOWN : 0, BACKSPACE : 8, PAGE_UP : 33, ARROW_LEFT : 37, ARROW_RIGHT : 39, } # Utils defaultFormat = /(\d{1,4})/g payform.cards = [ # Debit cards must come first, since they have more # specific patterns than their credit-card equivalents. { type: 'elo' pattern: /^(4011(78|79)|43(1274|8935)|45(1416|7393|763(1|2))|50(4175|6699|67[0-7][0-9]|9000)|627780|63(6297|6368)|650(03([^4])|04([0-9])|05(0|1)|4(0[5-9]|3[0-9]|8[5-9]|9[0-9])|5([0-2][0-9]|3[0-8])|9([2-6][0-9]|7[0-8])|541|700|720|901)|651652|655000|655021)/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'visaelectron' pattern: /^4(026|17500|405|508|844|91[37])/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'maestro' pattern: /^(5018|5020|5038|6304|6703|6708|6759|676[1-3])/ format: defaultFormat length: [12..19] cvcLength: [3] luhn: true } { type: 'forbrugsforeningen' pattern: /^600/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'dankort' pattern: /^5019/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } # Credit cards { type: 'visa' pattern: /^4/ format: defaultFormat length: [13, 16, 19] cvcLength: [3] luhn: true } { type: 'mastercard' pattern: /^(5[1-5]|677189)|^(222[1-9]|2[3-6]\d{2}|27[0-1]\d|2720)/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'amex' pattern: /^3[47]/ format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/ length: [15] cvcLength: [4] luhn: true } # Must be above dinersclub. { type: 'hipercard' pattern: /^(384100|384140|384160|606282|637095|637568|60(?!11))/ format: defaultFormat length: [14..19] cvcLength: [3] luhn: true } { type: 'dinersclub' pattern: /^(36|38|30[0-5])/ format: /(\d{1,4})(\d{1,6})?(\d{1,4})?/ length: [14] cvcLength: [3] luhn: true } { type: 'discover' pattern: /^(6011|65|64[4-9]|622)/ format: defaultFormat length: [16] cvcLength: [3] luhn: true } { type: 'unionpay' pattern: /^62/ format: defaultFormat length: [16..19] cvcLength: [3] luhn: false } { type: 'jcb' pattern: /^35/ format: defaultFormat length: [16..19] cvcLength: [3] luhn: true } { type: 'laser' pattern: /^(6706|6771|6709)/ format: defaultFormat length: [16..19] cvcLength: [3] luhn: true } ] cardFromNumber = (num) -> num = (num + '').replace(/\D/g, '') return card for card in payform.cards when card.pattern.test(num) cardFromType = (type) -> return card for card in payform.cards when card.type is type getDirectionality = (target) -> # Work around Firefox not returning the styles in some edge cases. # In Firefox < 62, style can be `null`. # In Firefox 62+, `style['direction']` can be an empty string. # See https://bugzilla.mozilla.org/show_bug.cgi?id=1467722. style = getComputedStyle(target) style and style['direction'] or document.dir luhnCheck = (num) -> odd = true sum = 0 digits = (num + '').split('').reverse() for digit in digits digit = parseInt(digit, 10) digit *= 2 if (odd = !odd) digit -= 9 if digit > 9 sum += digit sum % 10 == 0 hasTextSelected = (target) -> # If some text is selected in IE if document?.selection?.createRange? return true if document.selection.createRange().text target.selectionStart? and target.selectionStart isnt target.selectionEnd # Private # Replace Full-Width Chars replaceFullWidthChars = (str = '') -> fullWidth = '\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19' halfWidth = '0123456789' value = '' chars = str.split('') for char in chars idx = fullWidth.indexOf(char) char = halfWidth[idx] if idx > -1 value += char value # Format Card Number reFormatCardNumber = (e) -> cursor = _getCaretPos(e.target) return if e.target.value is "" if getDirectionality(e.target) == 'ltr' cursor = _getCaretPos(e.target) e.target.value = payform.formatCardNumber(e.target.value) if getDirectionality(e.target) == 'ltr' and cursor isnt e.target.selectionStart cursor = _getCaretPos(e.target) if getDirectionality(e.target) == 'rtl' and e.target.value.indexOf('‎\u200e') == -1 e.target.value = '‎\u200e'.concat(e.target.value) cursor = _getCaretPos(e.target) if cursor? and cursor isnt 0 and e.type isnt 'change' e.target.setSelectionRange(cursor, cursor) formatCardNumber = (e) -> # Only format if input is a number digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) value = e.target.value card = cardFromNumber(value + digit) length = (value.replace(/\D/g, '') + digit).length upperLength = 16 upperLength = card.length[card.length.length - 1] if card return if length >= upperLength # Return if focus isn't at the end of the text cursor = _getCaretPos(e.target) return if cursor and cursor isnt value.length if card && card.type is 'amex' # AMEX cards are formatted differently re = /^(\d{4}|\d{4}\s\d{6})$/ else re = /(?:^|\s)(\d{4})$/ # If '4242' + 4 if re.test(value) e.preventDefault() setTimeout -> e.target.value = "#{value} #{digit}" # If '424' + 2 else if re.test(value + digit) e.preventDefault() setTimeout -> e.target.value = "#{value + digit} " formatBackCardNumber = (e) -> value = e.target.value # Return unless backspacing return unless e.which is keyCodes.BACKSPACE # Return if focus isn't at the end of the text cursor = _getCaretPos(e.target) return if cursor and cursor isnt value.length return if (e.target.selectionEnd - e.target.selectionStart) > 1 # Remove the digit + trailing space if /\d\s$/.test(value) e.preventDefault() setTimeout -> e.target.value = value.replace /\d\s$/, '' # Remove digit if ends in space + digit else if /\s\d?$/.test(value) e.preventDefault() setTimeout -> e.target.value = value.replace /\d$/, '' # Format Expiry reFormatExpiry = (e) -> return if e.target.value is "" e.target.value = payform.formatCardExpiry(e.target.value) if getDirectionality(e.target) == 'rtl' and e.target.value.indexOf('‎\u200e') == -1 e.target.value = '‎\u200e'.concat(e.target.value) cursor = _getCaretPos(e.target) if cursor? and e.type isnt 'change' e.target.setSelectionRange(cursor, cursor) formatCardExpiry = (e) -> # Only format if input is a number digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) val = e.target.value + digit if /^\d$/.test(val) and val not in ['0', '1'] e.preventDefault() setTimeout -> e.target.value = "0#{val} / " else if /^\d\d$/.test(val) e.preventDefault() setTimeout -> e.target.value = "#{val} / " formatForwardExpiry = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) val = e.target.value if /^\d\d$/.test(val) e.target.value = "#{val} / " formatForwardSlashAndSpace = (e) -> which = String.fromCharCode(e.which) return unless which is '/' or which is ' ' val = e.target.value if /^\d$/.test(val) and val isnt '0' e.target.value = "0#{val} / " formatBackExpiry = (e) -> value = e.target.value # Return unless backspacing return unless e.which is keyCodes.BACKSPACE # Return if focus isn't at the end of the text cursor = _getCaretPos(e.target) return if cursor and cursor isnt value.length # Remove the trailing space + last digit if /\d\s\/\s$/.test(value) e.preventDefault() setTimeout -> e.target.value = value.replace(/\d\s\/\s$/, '') # Format CVC reFormatCVC = (e) -> return if e.target.value is "" cursor = _getCaretPos(e.target) e.target.value = replaceFullWidthChars(e.target.value).replace(/\D/g, '')[0...4] if cursor? and e.type isnt 'change' e.target.setSelectionRange(cursor, cursor) # Restrictions restrictNumeric = (e) -> # Key event is for a browser shortcut return if e.metaKey or e.ctrlKey # If keycode is a special char (WebKit) return if [keyCodes.UNKNOWN, keyCodes.ARROW_LEFT, keyCodes.ARROW_RIGHT].indexOf(e.which) > -1 # If char is a special char (Firefox) return if e.which < keyCodes.PAGE_UP input = String.fromCharCode(e.which) # Char is a number unless /^\d+$/.test(input) e.preventDefault() restrictCardNumber = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) return if hasTextSelected(e.target) # Restrict number of digits value = (e.target.value + digit).replace(/\D/g, '') card = cardFromNumber(value) maxLength = if card then card.length[card.length.length - 1] else 16 if value.length > maxLength e.preventDefault() restrictExpiry = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) return if hasTextSelected(e.target) value = e.target.value + digit value = value.replace(/\D/g, '') if value.length > 6 e.preventDefault() restrictCVC = (e) -> digit = String.fromCharCode(e.which) return unless /^\d+$/.test(digit) return if hasTextSelected(e.target) val = e.target.value + digit if val.length > 4 e.preventDefault() # Public # Formatting payform.cvcInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'keypress', restrictCVC) _on(input, 'paste', reFormatCVC) _on(input, 'change', reFormatCVC) _on(input, 'input', reFormatCVC) payform.expiryInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'keypress', restrictExpiry) _on(input, 'keypress', formatCardExpiry) _on(input, 'keypress', formatForwardSlashAndSpace) _on(input, 'keypress', formatForwardExpiry) _on(input, 'keydown', formatBackExpiry) _on(input, 'change', reFormatExpiry) _on(input, 'input', reFormatExpiry) payform.cardNumberInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'keypress', restrictCardNumber) _on(input, 'keypress', formatCardNumber) _on(input, 'keydown', formatBackCardNumber) _on(input, 'paste', reFormatCardNumber) _on(input, 'change', reFormatCardNumber) _on(input, 'input', reFormatCardNumber) payform.numericInput = (input) -> _on(input, 'keypress', restrictNumeric) _on(input, 'paste', restrictNumeric) _on(input, 'change', restrictNumeric) _on(input, 'input', restrictNumeric) # Validations payform.parseCardExpiry = (value) -> value = value.replace(/\s/g, '') [month, year] = value.split('/', 2) # Allow for year shortcut if year?.length is 2 and /^\d+$/.test(year) prefix = (new Date).getFullYear() prefix = prefix.toString()[0..1] year = prefix + year # Remove left-to-right mark LTR invisible unicode control character used in right-to-left contexts month = parseInt(month.replace(/[\u200e]/g, ""), 10); year = parseInt(year, 10) month: month, year: year payform.validateCardNumber = (num) -> num = (num + '').replace(/\s+|-/g, '') return false unless /^\d+$/.test(num) card = cardFromNumber(num) return false unless card num.length in card.length and (card.luhn is false or luhnCheck(num)) payform.validateCardExpiry = (month, year) -> # Allow passing an object if typeof month is 'object' and 'month' of month {month, year} = month return false unless month and year month = String(month).trim() year = String(year).trim() return false unless /^\d+$/.test(month) return false unless /^\d+$/.test(year) return false unless 1 <= month <= 12 if year.length == 2 if year < 70 year = "20#{year}" else year = "19#{year}" return false unless year.length == 4 expiry = new Date(year, month) currentTime = new Date # Months start from 0 in JavaScript expiry.setMonth(expiry.getMonth() - 1) # The cc expires at the end of the month, # so we need to make the expiry the first day # of the month after expiry.setMonth(expiry.getMonth() + 1, 1) expiry > currentTime payform.validateCardCVC = (cvc, type) -> cvc = String(cvc).trim() return false unless /^\d+$/.test(cvc) card = cardFromType(type) if card? # Check against a explicit card type cvc.length in card.cvcLength else # Check against all types cvc.length >= 3 and cvc.length <= 4 payform.parseCardType = (num) -> return null unless num cardFromNumber(num)?.type or null payform.formatCardNumber = (num) -> num = replaceFullWidthChars(num) num = num.replace(/\D/g, '') card = cardFromNumber(num) return num unless card upperLength = card.length[card.length.length - 1] num = num[0...upperLength] if card.format.global num.match(card.format)?.join(' ') else groups = card.format.exec(num) return unless groups? groups.shift() groups = groups.filter(Boolean) groups.join(' ') payform.formatCardExpiry = (expiry) -> expiry = replaceFullWidthChars(expiry) parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/) return '' unless parts mon = parts[1] || '' sep = parts[2] || '' year = parts[3] || '' if year.length > 0 sep = ' / ' else if sep is ' /' mon = mon.substring(0, 1) sep = '' else if mon.length == 2 or sep.length > 0 sep = ' / ' else if mon.length == 1 and mon not in ['0', '1'] mon = "0#{mon}" sep = ' / ' return mon + sep + year payform )
[ { "context": " visibility_level: 0\n ssh_url_to_repo: 'git@demo.gitlab.com:sandbox/afro.git'\n http_url_to_repo: 'http:/", "end": 232, "score": 0.958211362361908, "start": 213, "tag": "EMAIL", "value": "git@demo.gitlab.com" } ]
tests/mock.coffee
lengyuedaidai/node-gitlab
143
class Mock constructor: -> @path = '' @projects = [] project = id: 13 description: '' default_branch: 'master' public: false visibility_level: 0 ssh_url_to_repo: 'git@demo.gitlab.com:sandbox/afro.git' http_url_to_repo: 'http://demo.gitlab.com/sandbox/afro.git' web_url: 'http://demo.gitlab.com/sandbox/afro' owner: id: 8 name: 'Sandbox' created_at: '2013-08-01T16:44:17.000Z' name: 'Afro' name_with_namespace: 'Sandbox / Afro' path: 'afro' path_with_namespace: 'sandbox/afro' issues_enabled: true merge_requests_enabled: true wall_enabled: false wiki_enabled: true snippets_enabled: false created_at: '2013-11-14T17:45:19.000Z' last_activity_at: '2014-01-16T15:32:07.000Z' namespace: id: 8 name: 'Sandbox' path: 'sandbox' owner_id: 1 created_at: '2013-08-01T16:44:17.000Z' updated_at: '2013-08-01T16:44:17.000Z' description: '' @projects.push project setup: (gitlab) => before => gitlab.slumber = (path) => @update_path(path) beforeEach => do @beforeEach update_path: (@path) => return @ defaults: get: (opts, cb) -> cb(null, {}, [{}]) if cb delete: (opts, cb) -> cb(null, {}, [{}]) if cb post: (opts, cb) -> cb(null, {}, [{}]) if cb put: (opts, cb) -> cb(null, {}, [{}]) if cb patch: (opts, cb) -> cb(null, {}, [{}]) if cb beforeEach: => for method in ['get', 'delete', 'post', 'put', 'patch'] @[method] = @defaults[method] module.exports = new Mock()
202634
class Mock constructor: -> @path = '' @projects = [] project = id: 13 description: '' default_branch: 'master' public: false visibility_level: 0 ssh_url_to_repo: '<EMAIL>:sandbox/afro.git' http_url_to_repo: 'http://demo.gitlab.com/sandbox/afro.git' web_url: 'http://demo.gitlab.com/sandbox/afro' owner: id: 8 name: 'Sandbox' created_at: '2013-08-01T16:44:17.000Z' name: 'Afro' name_with_namespace: 'Sandbox / Afro' path: 'afro' path_with_namespace: 'sandbox/afro' issues_enabled: true merge_requests_enabled: true wall_enabled: false wiki_enabled: true snippets_enabled: false created_at: '2013-11-14T17:45:19.000Z' last_activity_at: '2014-01-16T15:32:07.000Z' namespace: id: 8 name: 'Sandbox' path: 'sandbox' owner_id: 1 created_at: '2013-08-01T16:44:17.000Z' updated_at: '2013-08-01T16:44:17.000Z' description: '' @projects.push project setup: (gitlab) => before => gitlab.slumber = (path) => @update_path(path) beforeEach => do @beforeEach update_path: (@path) => return @ defaults: get: (opts, cb) -> cb(null, {}, [{}]) if cb delete: (opts, cb) -> cb(null, {}, [{}]) if cb post: (opts, cb) -> cb(null, {}, [{}]) if cb put: (opts, cb) -> cb(null, {}, [{}]) if cb patch: (opts, cb) -> cb(null, {}, [{}]) if cb beforeEach: => for method in ['get', 'delete', 'post', 'put', 'patch'] @[method] = @defaults[method] module.exports = new Mock()
true
class Mock constructor: -> @path = '' @projects = [] project = id: 13 description: '' default_branch: 'master' public: false visibility_level: 0 ssh_url_to_repo: 'PI:EMAIL:<EMAIL>END_PI:sandbox/afro.git' http_url_to_repo: 'http://demo.gitlab.com/sandbox/afro.git' web_url: 'http://demo.gitlab.com/sandbox/afro' owner: id: 8 name: 'Sandbox' created_at: '2013-08-01T16:44:17.000Z' name: 'Afro' name_with_namespace: 'Sandbox / Afro' path: 'afro' path_with_namespace: 'sandbox/afro' issues_enabled: true merge_requests_enabled: true wall_enabled: false wiki_enabled: true snippets_enabled: false created_at: '2013-11-14T17:45:19.000Z' last_activity_at: '2014-01-16T15:32:07.000Z' namespace: id: 8 name: 'Sandbox' path: 'sandbox' owner_id: 1 created_at: '2013-08-01T16:44:17.000Z' updated_at: '2013-08-01T16:44:17.000Z' description: '' @projects.push project setup: (gitlab) => before => gitlab.slumber = (path) => @update_path(path) beforeEach => do @beforeEach update_path: (@path) => return @ defaults: get: (opts, cb) -> cb(null, {}, [{}]) if cb delete: (opts, cb) -> cb(null, {}, [{}]) if cb post: (opts, cb) -> cb(null, {}, [{}]) if cb put: (opts, cb) -> cb(null, {}, [{}]) if cb patch: (opts, cb) -> cb(null, {}, [{}]) if cb beforeEach: => for method in ['get', 'delete', 'post', 'put', 'patch'] @[method] = @defaults[method] module.exports = new Mock()
[ { "context": " @user.errors = {password: [t('passport.failure.invalid_password_format')]}\n\n rende", "end": 665, "score": 0.5454352498054504, "start": 665, "tag": "PASSWORD", "value": "" }, { "context": " @user = user\n @user.password = body.User...
app/controllers/registrations_controller.coffee
scottbarstow/sample-node-web
0
load 'application' action 'new', -> @title = 'Sign Up' @user = User(email: req.body.email) render() action 'welcome', -> @title = 'Welcome' render() action 'create', -> @title = 'Welcome' @user = User(email: req.body.email) @user.password = req.body.password.trim() if req.body.password != req.body.password_confirmation flash 'error', t('passport.failure.password_neq_confirmation') render 'new' else if @user.password.length < 6 if @user.errors @user.errors.add 'password', t('passport.failure.invalid_password_format') else @user.errors = {password: [t('passport.failure.invalid_password_format')]} render 'new' else @user.save (err) => if err render 'new' else log = compound.logger # send confirmation token sendEmail 'emails/registrations/confirmation', { confirmation_link: pathTo.users_confirmation(confirmation_token: @user.confirmation_token) }, { subject: 'Thank You For Using DIDify!', email: @user.email }, (err, success) => if success @user.confirmation_sent_at = Date.now() @user.save => log.write('=== Email was sent to: ' + @user.email); else log.write('Nodemailer error: ' + err) redirect pathTo.welcome action 'reset_password_email_show', -> @title = 'Forgot your password?' render() action 'reset_password_email', -> @title = 'Forgot your password?' log = compound.logger User.findOne where: {email: body.email}, (err, user) -> if err || !user flash 'error', body.email + " " + t('failure.email.not_found') redirect pathTo.reset_password_email else if user.confirmation_token flash 'error', body.email + " " + t('passport.failure.unconfirmed') redirect pathTo.users_confirmation_resend else user.initResetPasswordToken (err) -> if err log.write('initResetPasswordToken error: ' + err) flash 'error', t('failure.application') redirect pathTo.reset_password_email else # send confirmation token sendEmail 'emails/registrations/reset_password', email: user.email reset_password_link: pathTo.reset_password(reset_password_token: user.reset_password_token) , subject: 'Reset Password Request' email: user.email , (err, success) => if success user.reset_password_sent_at = Date.now() user.save (err) => log.write("Error after reset password email: " + err) if err log.write('=== Email was sent to: ' + user.email); else log.write('Reset password nodemailer error: ' + err) flash 'info', t('passport.passwords.send_instructions') redirect pathTo.signin action 'reset_password_show', -> @title = 'Set new password' @reset_password_token = req.query.reset_password_token unless @reset_password_token flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else User.findOne where: {reset_password_token: @reset_password_token}, (err, user) -> if err or !user flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else @user = user render() action 'reset_password', -> @title = 'Set new password' @reset_password_token = body.reset_password_token log = compound.logger unless @reset_password_token flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else User.findOne where: {reset_password_token: @reset_password_token}, (err, user) -> if err or !user flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else @user = user @user.password = body.User.password if body.User.password != body.User.password_confirmation flash 'error', t('passport.failure.password_neq_confirmation') render 'reset_password_show' else if @user.password.length < 6 if @user.errors @user.errors.add 'password', t('passport.failure.invalid_password_format') else @user.errors = {password: [t('passport.failure.invalid_password_format')]} render 'reset_password_show' else user.reset_password_token = null user.reset_password_sent_at = null user.save (err) -> if err log.write('Save user(clean reset_password_token) error: ' + err) flash 'error', t('failure.application') render 'reset_password_show' else req.login user, (err) => if err log.write "Error during passport login: #{err}" flash 'error', t('failure.application') redirect pathTo.reset_password_email else flash 'info', t('passport.passwords.updated') redirect pathTo.home
147970
load 'application' action 'new', -> @title = 'Sign Up' @user = User(email: req.body.email) render() action 'welcome', -> @title = 'Welcome' render() action 'create', -> @title = 'Welcome' @user = User(email: req.body.email) @user.password = req.body.password.trim() if req.body.password != req.body.password_confirmation flash 'error', t('passport.failure.password_neq_confirmation') render 'new' else if @user.password.length < 6 if @user.errors @user.errors.add 'password', t('passport.failure.invalid_password_format') else @user.errors = {password: [t('passport<PASSWORD>.failure.invalid_password_format')]} render 'new' else @user.save (err) => if err render 'new' else log = compound.logger # send confirmation token sendEmail 'emails/registrations/confirmation', { confirmation_link: pathTo.users_confirmation(confirmation_token: @user.confirmation_token) }, { subject: 'Thank You For Using DIDify!', email: @user.email }, (err, success) => if success @user.confirmation_sent_at = Date.now() @user.save => log.write('=== Email was sent to: ' + @user.email); else log.write('Nodemailer error: ' + err) redirect pathTo.welcome action 'reset_password_email_show', -> @title = 'Forgot your password?' render() action 'reset_password_email', -> @title = 'Forgot your password?' log = compound.logger User.findOne where: {email: body.email}, (err, user) -> if err || !user flash 'error', body.email + " " + t('failure.email.not_found') redirect pathTo.reset_password_email else if user.confirmation_token flash 'error', body.email + " " + t('passport.failure.unconfirmed') redirect pathTo.users_confirmation_resend else user.initResetPasswordToken (err) -> if err log.write('initResetPasswordToken error: ' + err) flash 'error', t('failure.application') redirect pathTo.reset_password_email else # send confirmation token sendEmail 'emails/registrations/reset_password', email: user.email reset_password_link: pathTo.reset_password(reset_password_token: user.reset_password_token) , subject: 'Reset Password Request' email: user.email , (err, success) => if success user.reset_password_sent_at = Date.now() user.save (err) => log.write("Error after reset password email: " + err) if err log.write('=== Email was sent to: ' + user.email); else log.write('Reset password nodemailer error: ' + err) flash 'info', t('passport.passwords.send_instructions') redirect pathTo.signin action 'reset_password_show', -> @title = 'Set new password' @reset_password_token = req.query.reset_password_token unless @reset_password_token flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else User.findOne where: {reset_password_token: @reset_password_token}, (err, user) -> if err or !user flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else @user = user render() action 'reset_password', -> @title = 'Set new password' @reset_password_token = body.reset_password_token log = compound.logger unless @reset_password_token flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else User.findOne where: {reset_password_token: @reset_password_token}, (err, user) -> if err or !user flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else @user = user @user.password = <PASSWORD>.User.password if body.User.password != body.User.password_confirmation flash 'error', t('passport.failure.password_neq_confirmation') render 'reset_password_show' else if @user.password.length < 6 if @user.errors @user.errors.add 'password', t('passport.failure.invalid_password_format') else @user.errors = {password: [t('passport.failure.invalid_password_format')]} render 'reset_password_show' else user.reset_password_token = null user.reset_password_sent_at = null user.save (err) -> if err log.write('Save user(clean reset_password_token) error: ' + err) flash 'error', t('failure.application') render 'reset_password_show' else req.login user, (err) => if err log.write "Error during passport login: #{err}" flash 'error', t('failure.application') redirect pathTo.reset_password_email else flash 'info', t('passport.passwords.updated') redirect pathTo.home
true
load 'application' action 'new', -> @title = 'Sign Up' @user = User(email: req.body.email) render() action 'welcome', -> @title = 'Welcome' render() action 'create', -> @title = 'Welcome' @user = User(email: req.body.email) @user.password = req.body.password.trim() if req.body.password != req.body.password_confirmation flash 'error', t('passport.failure.password_neq_confirmation') render 'new' else if @user.password.length < 6 if @user.errors @user.errors.add 'password', t('passport.failure.invalid_password_format') else @user.errors = {password: [t('passportPI:PASSWORD:<PASSWORD>END_PI.failure.invalid_password_format')]} render 'new' else @user.save (err) => if err render 'new' else log = compound.logger # send confirmation token sendEmail 'emails/registrations/confirmation', { confirmation_link: pathTo.users_confirmation(confirmation_token: @user.confirmation_token) }, { subject: 'Thank You For Using DIDify!', email: @user.email }, (err, success) => if success @user.confirmation_sent_at = Date.now() @user.save => log.write('=== Email was sent to: ' + @user.email); else log.write('Nodemailer error: ' + err) redirect pathTo.welcome action 'reset_password_email_show', -> @title = 'Forgot your password?' render() action 'reset_password_email', -> @title = 'Forgot your password?' log = compound.logger User.findOne where: {email: body.email}, (err, user) -> if err || !user flash 'error', body.email + " " + t('failure.email.not_found') redirect pathTo.reset_password_email else if user.confirmation_token flash 'error', body.email + " " + t('passport.failure.unconfirmed') redirect pathTo.users_confirmation_resend else user.initResetPasswordToken (err) -> if err log.write('initResetPasswordToken error: ' + err) flash 'error', t('failure.application') redirect pathTo.reset_password_email else # send confirmation token sendEmail 'emails/registrations/reset_password', email: user.email reset_password_link: pathTo.reset_password(reset_password_token: user.reset_password_token) , subject: 'Reset Password Request' email: user.email , (err, success) => if success user.reset_password_sent_at = Date.now() user.save (err) => log.write("Error after reset password email: " + err) if err log.write('=== Email was sent to: ' + user.email); else log.write('Reset password nodemailer error: ' + err) flash 'info', t('passport.passwords.send_instructions') redirect pathTo.signin action 'reset_password_show', -> @title = 'Set new password' @reset_password_token = req.query.reset_password_token unless @reset_password_token flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else User.findOne where: {reset_password_token: @reset_password_token}, (err, user) -> if err or !user flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else @user = user render() action 'reset_password', -> @title = 'Set new password' @reset_password_token = body.reset_password_token log = compound.logger unless @reset_password_token flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else User.findOne where: {reset_password_token: @reset_password_token}, (err, user) -> if err or !user flash 'error', t('passport.failure.invalid_token') redirect pathTo.reset_password_email else @user = user @user.password = PI:PASSWORD:<PASSWORD>END_PI.User.password if body.User.password != body.User.password_confirmation flash 'error', t('passport.failure.password_neq_confirmation') render 'reset_password_show' else if @user.password.length < 6 if @user.errors @user.errors.add 'password', t('passport.failure.invalid_password_format') else @user.errors = {password: [t('passport.failure.invalid_password_format')]} render 'reset_password_show' else user.reset_password_token = null user.reset_password_sent_at = null user.save (err) -> if err log.write('Save user(clean reset_password_token) error: ' + err) flash 'error', t('failure.application') render 'reset_password_show' else req.login user, (err) => if err log.write "Error during passport login: #{err}" flash 'error', t('failure.application') redirect pathTo.reset_password_email else flash 'info', t('passport.passwords.updated') redirect pathTo.home
[ { "context": ".String\n expect(form.get 'username').to.equal 'test'\n\n form.set\n username:\n ' test2", "end": 1508, "score": 0.9931105971336365, "start": 1504, "tag": "USERNAME", "value": "test" }, { "context": " 'test'\n\n form.set\n username:\n ...
test/form._.spec.coffee
nrako/formal-mongoose
5
### global describe, it, beforeEach ### chai = require 'chai' expect = chai.expect Form = require '../lib/form' mongoose = require 'mongoose' Schema = mongoose.Schema Formal = require 'formal' FieldTypes = Formal.FieldTypes moment = require 'moment' validate = require('mongoose-validator').validate describe 'Formal-mongoose', -> subSchema = new Schema name: String schema = new Schema email: type: String trim: true validate: validate message: 'Invalid email' ,'isEmail' username: type: String trim: true default: 'test' birthdate: Date name: family: String first: String mix: {} buf: Buffer sub: type: Schema.Types.ObjectId ref: 'SubSchema' subs: [subSchema] schema.virtual('fullname').get -> return this.name.first + ' ' + this.name.family schema.virtual('age').get -> return moment(new Date).diff this.birthdate, 'years' schema.virtual('age').set (val) -> if isNaN val throw new TypeError 'invalid number for age' this.birthdate = moment(new Date).subtract('years', val).toDate() model = mongoose.model 'TestModel', schema it 'works with schema as argument', -> form = new Form schema, ['email', 'username', 'name.family'] expect(form).to.be.an.instanceof Formal expect(Object.keys(form.paths).length).to.equal 3 expect(form.path 'name.family').to.be.an.instanceof FieldTypes.String expect(form.get 'username').to.equal 'test' form.set username: ' test2 ' expect(form.get 'username').to.equal 'test2' it 'supports model as schema argument', -> form = new Form model, ['email', 'username'] expect(Object.keys(form.paths).length).to.equal 2 it 'supports wildcard shortcut in path name', -> form = new Form schema, ['name.*'] expect(Object.keys(form.paths).length).to.equal 2 it 'supports validators from mongoose', (done) -> form = new Form schema, ['email'] form.set email: 'dsjlkfaj' form.validate (err) -> expect(err.errors.email.type).to.equal 'Invalid email' done() it 'supports virtuals from mongoose', -> form = new Form schema, ['name.*', 'fullname', 'birthdate', 'age'] age = 28 form.set name: first: 'Marvin' family: 'Hagler' birthdate: moment().subtract('years', age).toDate() expect(form.get 'fullname').to.equal 'Marvin Hagler' expect(form.get 'age').to.equal age form.set age: 18 expect(form.get 'age').to.equal 18 it 'supports form() shorthand ', (done) -> middleware = Form schema, ['name.*', 'email'] request = body: name: first: 'Marvin' family: 'Hagler' email: 'wrong email' response = locals: {} cb = -> form = request.form expect(form.get 'name.first').to.equal 'Marvin' expect(response.locals.form.email.error).to.be.a 'string' done() # app.post('/url', form.express, function (req, res) {...}) middleware request, response, cb # Hopefuly this will disappear soon it 'should throw errors on unsuported SchemaTypes', -> fn = -> form = new Form schema, ['mix'] expect(fn).to.throw Error fn = -> form = new Form schema, ['buf'] expect(fn).to.throw Error fn = -> form = new Form schema, ['sub'] expect(fn).to.throw Error fn = -> form = new Form schema, ['subs'] expect(fn).to.throw Error it 'can have 100% test coverage', -> fn = -> form = new Form null expect(fn).to.throw TypeError fn = -> form = new Form {} expect(fn).to.throw TypeError fn = -> form = new Form tree: {} expect(fn).to.throw TypeError
176678
### global describe, it, beforeEach ### chai = require 'chai' expect = chai.expect Form = require '../lib/form' mongoose = require 'mongoose' Schema = mongoose.Schema Formal = require 'formal' FieldTypes = Formal.FieldTypes moment = require 'moment' validate = require('mongoose-validator').validate describe 'Formal-mongoose', -> subSchema = new Schema name: String schema = new Schema email: type: String trim: true validate: validate message: 'Invalid email' ,'isEmail' username: type: String trim: true default: 'test' birthdate: Date name: family: String first: String mix: {} buf: Buffer sub: type: Schema.Types.ObjectId ref: 'SubSchema' subs: [subSchema] schema.virtual('fullname').get -> return this.name.first + ' ' + this.name.family schema.virtual('age').get -> return moment(new Date).diff this.birthdate, 'years' schema.virtual('age').set (val) -> if isNaN val throw new TypeError 'invalid number for age' this.birthdate = moment(new Date).subtract('years', val).toDate() model = mongoose.model 'TestModel', schema it 'works with schema as argument', -> form = new Form schema, ['email', 'username', 'name.family'] expect(form).to.be.an.instanceof Formal expect(Object.keys(form.paths).length).to.equal 3 expect(form.path 'name.family').to.be.an.instanceof FieldTypes.String expect(form.get 'username').to.equal 'test' form.set username: ' test2 ' expect(form.get 'username').to.equal 'test2' it 'supports model as schema argument', -> form = new Form model, ['email', 'username'] expect(Object.keys(form.paths).length).to.equal 2 it 'supports wildcard shortcut in path name', -> form = new Form schema, ['name.*'] expect(Object.keys(form.paths).length).to.equal 2 it 'supports validators from mongoose', (done) -> form = new Form schema, ['email'] form.set email: 'dsjlkfaj' form.validate (err) -> expect(err.errors.email.type).to.equal 'Invalid email' done() it 'supports virtuals from mongoose', -> form = new Form schema, ['name.*', 'fullname', 'birthdate', 'age'] age = 28 form.set name: first: '<NAME>' family: '<NAME>' birthdate: moment().subtract('years', age).toDate() expect(form.get 'fullname').to.equal '<NAME>' expect(form.get 'age').to.equal age form.set age: 18 expect(form.get 'age').to.equal 18 it 'supports form() shorthand ', (done) -> middleware = Form schema, ['name.*', 'email'] request = body: name: first: '<NAME>' family: 'H<NAME>ler' email: 'wrong email' response = locals: {} cb = -> form = request.form expect(form.get 'name.first').to.equal '<NAME>' expect(response.locals.form.email.error).to.be.a 'string' done() # app.post('/url', form.express, function (req, res) {...}) middleware request, response, cb # Hopefuly this will disappear soon it 'should throw errors on unsuported SchemaTypes', -> fn = -> form = new Form schema, ['mix'] expect(fn).to.throw Error fn = -> form = new Form schema, ['buf'] expect(fn).to.throw Error fn = -> form = new Form schema, ['sub'] expect(fn).to.throw Error fn = -> form = new Form schema, ['subs'] expect(fn).to.throw Error it 'can have 100% test coverage', -> fn = -> form = new Form null expect(fn).to.throw TypeError fn = -> form = new Form {} expect(fn).to.throw TypeError fn = -> form = new Form tree: {} expect(fn).to.throw TypeError
true
### global describe, it, beforeEach ### chai = require 'chai' expect = chai.expect Form = require '../lib/form' mongoose = require 'mongoose' Schema = mongoose.Schema Formal = require 'formal' FieldTypes = Formal.FieldTypes moment = require 'moment' validate = require('mongoose-validator').validate describe 'Formal-mongoose', -> subSchema = new Schema name: String schema = new Schema email: type: String trim: true validate: validate message: 'Invalid email' ,'isEmail' username: type: String trim: true default: 'test' birthdate: Date name: family: String first: String mix: {} buf: Buffer sub: type: Schema.Types.ObjectId ref: 'SubSchema' subs: [subSchema] schema.virtual('fullname').get -> return this.name.first + ' ' + this.name.family schema.virtual('age').get -> return moment(new Date).diff this.birthdate, 'years' schema.virtual('age').set (val) -> if isNaN val throw new TypeError 'invalid number for age' this.birthdate = moment(new Date).subtract('years', val).toDate() model = mongoose.model 'TestModel', schema it 'works with schema as argument', -> form = new Form schema, ['email', 'username', 'name.family'] expect(form).to.be.an.instanceof Formal expect(Object.keys(form.paths).length).to.equal 3 expect(form.path 'name.family').to.be.an.instanceof FieldTypes.String expect(form.get 'username').to.equal 'test' form.set username: ' test2 ' expect(form.get 'username').to.equal 'test2' it 'supports model as schema argument', -> form = new Form model, ['email', 'username'] expect(Object.keys(form.paths).length).to.equal 2 it 'supports wildcard shortcut in path name', -> form = new Form schema, ['name.*'] expect(Object.keys(form.paths).length).to.equal 2 it 'supports validators from mongoose', (done) -> form = new Form schema, ['email'] form.set email: 'dsjlkfaj' form.validate (err) -> expect(err.errors.email.type).to.equal 'Invalid email' done() it 'supports virtuals from mongoose', -> form = new Form schema, ['name.*', 'fullname', 'birthdate', 'age'] age = 28 form.set name: first: 'PI:NAME:<NAME>END_PI' family: 'PI:NAME:<NAME>END_PI' birthdate: moment().subtract('years', age).toDate() expect(form.get 'fullname').to.equal 'PI:NAME:<NAME>END_PI' expect(form.get 'age').to.equal age form.set age: 18 expect(form.get 'age').to.equal 18 it 'supports form() shorthand ', (done) -> middleware = Form schema, ['name.*', 'email'] request = body: name: first: 'PI:NAME:<NAME>END_PI' family: 'HPI:NAME:<NAME>END_PIler' email: 'wrong email' response = locals: {} cb = -> form = request.form expect(form.get 'name.first').to.equal 'PI:NAME:<NAME>END_PI' expect(response.locals.form.email.error).to.be.a 'string' done() # app.post('/url', form.express, function (req, res) {...}) middleware request, response, cb # Hopefuly this will disappear soon it 'should throw errors on unsuported SchemaTypes', -> fn = -> form = new Form schema, ['mix'] expect(fn).to.throw Error fn = -> form = new Form schema, ['buf'] expect(fn).to.throw Error fn = -> form = new Form schema, ['sub'] expect(fn).to.throw Error fn = -> form = new Form schema, ['subs'] expect(fn).to.throw Error it 'can have 100% test coverage', -> fn = -> form = new Form null expect(fn).to.throw TypeError fn = -> form = new Form {} expect(fn).to.throw TypeError fn = -> form = new Form tree: {} expect(fn).to.throw TypeError
[ { "context": "#\n# node-sendgird\n# Copyright(c) 2011 Scopely <dev@scopely.com>\n# MIT Licensed\n#\n\nmodule.expor", "end": 47, "score": 0.999492347240448, "start": 40, "tag": "USERNAME", "value": "Scopely" }, { "context": "#\n# node-sendgird\n# Copyright(c) 2011 Scopely <dev@sc...
coffee/index.coffee
scopely/node-awesm
1
# # node-sendgird # Copyright(c) 2011 Scopely <dev@scopely.com> # MIT Licensed # module.exports = require('./lib/awesm')
21236
# # node-sendgird # Copyright(c) 2011 Scopely <<EMAIL>> # MIT Licensed # module.exports = require('./lib/awesm')
true
# # node-sendgird # Copyright(c) 2011 Scopely <PI:EMAIL:<EMAIL>END_PI> # MIT Licensed # module.exports = require('./lib/awesm')
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.999444305896759, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-event-emitter-check-listener-leaks.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") events = require("events") e = new events.EventEmitter() # default i = 0 while i < 10 e.on "default", -> i++ assert.ok not e._events["default"].hasOwnProperty("warned") e.on "default", -> assert.ok e._events["default"].warned # specific e.setMaxListeners 5 i = 0 while i < 5 e.on "specific", -> i++ assert.ok not e._events["specific"].hasOwnProperty("warned") e.on "specific", -> assert.ok e._events["specific"].warned # only one e.setMaxListeners 1 e.on "only one", -> assert.ok not e._events["only one"].hasOwnProperty("warned") e.on "only one", -> assert.ok e._events["only one"].hasOwnProperty("warned") # unlimited e.setMaxListeners 0 i = 0 while i < 1000 e.on "unlimited", -> i++ assert.ok not e._events["unlimited"].hasOwnProperty("warned") # process-wide events.EventEmitter.defaultMaxListeners = 42 e = new events.EventEmitter() i = 0 while i < 42 e.on "fortytwo", -> ++i assert.ok not e._events["fortytwo"].hasOwnProperty("warned") e.on "fortytwo", -> assert.ok e._events["fortytwo"].hasOwnProperty("warned") delete e._events["fortytwo"].warned events.EventEmitter.defaultMaxListeners = 44 e.on "fortytwo", -> assert.ok not e._events["fortytwo"].hasOwnProperty("warned") e.on "fortytwo", -> assert.ok e._events["fortytwo"].hasOwnProperty("warned") # but _maxListeners still has precedence over defaultMaxListeners events.EventEmitter.defaultMaxListeners = 42 e = new events.EventEmitter() e.setMaxListeners 1 e.on "uno", -> assert.ok not e._events["uno"].hasOwnProperty("warned") e.on "uno", -> assert.ok e._events["uno"].hasOwnProperty("warned") # chainable assert.strictEqual e, e.setMaxListeners(1)
41038
# 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") events = require("events") e = new events.EventEmitter() # default i = 0 while i < 10 e.on "default", -> i++ assert.ok not e._events["default"].hasOwnProperty("warned") e.on "default", -> assert.ok e._events["default"].warned # specific e.setMaxListeners 5 i = 0 while i < 5 e.on "specific", -> i++ assert.ok not e._events["specific"].hasOwnProperty("warned") e.on "specific", -> assert.ok e._events["specific"].warned # only one e.setMaxListeners 1 e.on "only one", -> assert.ok not e._events["only one"].hasOwnProperty("warned") e.on "only one", -> assert.ok e._events["only one"].hasOwnProperty("warned") # unlimited e.setMaxListeners 0 i = 0 while i < 1000 e.on "unlimited", -> i++ assert.ok not e._events["unlimited"].hasOwnProperty("warned") # process-wide events.EventEmitter.defaultMaxListeners = 42 e = new events.EventEmitter() i = 0 while i < 42 e.on "fortytwo", -> ++i assert.ok not e._events["fortytwo"].hasOwnProperty("warned") e.on "fortytwo", -> assert.ok e._events["fortytwo"].hasOwnProperty("warned") delete e._events["fortytwo"].warned events.EventEmitter.defaultMaxListeners = 44 e.on "fortytwo", -> assert.ok not e._events["fortytwo"].hasOwnProperty("warned") e.on "fortytwo", -> assert.ok e._events["fortytwo"].hasOwnProperty("warned") # but _maxListeners still has precedence over defaultMaxListeners events.EventEmitter.defaultMaxListeners = 42 e = new events.EventEmitter() e.setMaxListeners 1 e.on "uno", -> assert.ok not e._events["uno"].hasOwnProperty("warned") e.on "uno", -> assert.ok e._events["uno"].hasOwnProperty("warned") # chainable assert.strictEqual e, e.setMaxListeners(1)
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") events = require("events") e = new events.EventEmitter() # default i = 0 while i < 10 e.on "default", -> i++ assert.ok not e._events["default"].hasOwnProperty("warned") e.on "default", -> assert.ok e._events["default"].warned # specific e.setMaxListeners 5 i = 0 while i < 5 e.on "specific", -> i++ assert.ok not e._events["specific"].hasOwnProperty("warned") e.on "specific", -> assert.ok e._events["specific"].warned # only one e.setMaxListeners 1 e.on "only one", -> assert.ok not e._events["only one"].hasOwnProperty("warned") e.on "only one", -> assert.ok e._events["only one"].hasOwnProperty("warned") # unlimited e.setMaxListeners 0 i = 0 while i < 1000 e.on "unlimited", -> i++ assert.ok not e._events["unlimited"].hasOwnProperty("warned") # process-wide events.EventEmitter.defaultMaxListeners = 42 e = new events.EventEmitter() i = 0 while i < 42 e.on "fortytwo", -> ++i assert.ok not e._events["fortytwo"].hasOwnProperty("warned") e.on "fortytwo", -> assert.ok e._events["fortytwo"].hasOwnProperty("warned") delete e._events["fortytwo"].warned events.EventEmitter.defaultMaxListeners = 44 e.on "fortytwo", -> assert.ok not e._events["fortytwo"].hasOwnProperty("warned") e.on "fortytwo", -> assert.ok e._events["fortytwo"].hasOwnProperty("warned") # but _maxListeners still has precedence over defaultMaxListeners events.EventEmitter.defaultMaxListeners = 42 e = new events.EventEmitter() e.setMaxListeners 1 e.on "uno", -> assert.ok not e._events["uno"].hasOwnProperty("warned") e.on "uno", -> assert.ok e._events["uno"].hasOwnProperty("warned") # chainable assert.strictEqual e, e.setMaxListeners(1)
[ { "context": "render\n @_Halvalla =\n birthName: 'Bishop '+nameMine.getName()\n propertyName:prope", "end": 2472, "score": 0.9239247441291809, "start": 2466, "tag": "NAME", "value": "Bishop" }, { "context": "d!\",@\n\n @_Halvalla =\n birthName...
src/halvalla.coffee
jahbini/halvalla
2
### # Halvalla -- bindings for element creation and expression via teact and teacup ### nameMine = require '../lib/name-mine' ### # The oracle, a globally supplied object to this module has this signature Examples of oracle -- the default is to do Teacup to HTML ReactDom = require 'react-dom' Oracle = summoner: React name: 'React' isValidElement: React.isValidElement Component: React.Component createElement: React.createElement conjurer: ReactDom.renderToString Mithril = require 'mithril' Oracle = name: 'Mithril' isValidElement: (c)->c.view? createElement: Mithril Component: {} ### {doctypes,elements,normalizeArray,mergeElements,allTags,escape,quote,BagMan} = require '../lib/html-tags' teacup = require '../lib/teacup' #if we are using React as the master, it supplies a class, otherwise an empty class with an empty view propertyName = 'props' GreatEmptiness = null dummyComponent = null dummyElement = null class Halvalla oracle=null # constructor: (Oracle=null)-> @bagMan = new BagMan GreatEmptiness = class GreatEmptiness constructor: (instantiator,Oracle={})-> defaultObject = isValidElement: (c)->c.view? name: Oracle.name || 'great-emptiness' Component: Oracle.Component || class Component Element: Oracle.Element || class Element createElement: (args...)-> new dummyElement args... summoner: null getChildren: (element)->element.children getProp: (element)->element.attrs getName: (element)->element.type||element._Halvalla?.tagName|| element.tagName propertyName: 'attrs' preInstantiate: true #needed for mithril, maybe for teacup, react??? conjurer: null # decorate this singleton with for key,value of Object.assign defaultObject, Oracle GreatEmptiness::[key] = value @teacup=new teacup instantiator,defaultObject @conjurer= @teacup.render.bind @teacup unless @conjurer @ # oracle = new GreatEmptiness ((component)=>@create component),Oracle propertyName = oracle.propertyName dummyComponent = class Component extends oracle.Component constructor:(tagName,properties,children...)-> super properties,children... @tagName=tagName @[propertyName] = properties unless @[propertyName] @children = @render @_Halvalla = birthName: 'Bishop '+nameMine.getName() propertyName:propertyName children:@render tagname: tagName[0].toLowerCase()+tagName.slice 1 #console.log "Component construct",@ #console.log "Component arguments",arguments return render: -> dummyElement = class Element extends oracle.Component constructor:(tagName,properties={},@children...)-> super properties,@children... @tagName=tagName @tag = tagName @[propertyName]=properties if propertyName == 'attr' @props = properties @children = @children[0] if @children.length ==1 if typeof tagName == 'object' name = tagName.name || tagName.constructor.name else name = tagName try name = name[0].toLowerCase()+name.slice 1 catch name = "badSeed" #console.log "Bad Seed!",@ @_Halvalla = birthName: 'Acolyte '+nameMine.getName() tagName: name[0].toLowerCase()+name.slice 1 propertyName:propertyName children:@[propertyName].children #console.log "Element construct",@ #console.log "Element attrs should be object, typeof this.attrs = ",typeof @.attrs #console.log "Element arguments",arguments return view: -> mutator: (tagName,destination,withThis=null)-> do (tagName)=> Halvalla::[tagName] = (args...) => destination.apply @, [tagName].concat args thing= Halvalla::[tagName] thing.Halvalla={tagName:tagName,boss:oracle.name} allTags[tagName] = thing return thing # global Oracle # # bring in some pure utility text functions escape:escape quote:quote pureComponent: (contents) -> return => @bagMan.context [] @bagMan.shipOut contents.apply @, arguments stackHad=@bagMan.harvest() #console.log "Pure ", st #console.log "WAS ",previous return stackHad coffeescript: (fn)-> @raw """<script type="text/javascript">(function() { var slice = [].slice, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; (#{fn.toString().replace /<\//g,"<\\/"})(); })();</script>""" comment: (text)-> unless text.toString throw new Error "comment tag allows text only: expected a string" return @raw "<!--#{escape text}-->" raw: (text="")-> #allow empty or null parmameter unless text.toString throw new Error "raw allows text only: expected a string" if oracle.trust el = oracle.trust text else el = oracle.createElement 'text', dangerouslySetInnerHTML: __html: text.toString() return @bagMan.shipOut el doctype: (type=5) -> #console.log "doctype request #{type}" #console.log "and it is... ",doctypes @raw doctypes[type] ie: (condition,contents)-> @crel 'ie',condition:condition,contents tag: (tagName,args...) -> unless tagName? && 'string'== typeof tagName throw new Error "HTML tag type is invalid: expected a string but got #{typeof tagName?}" return @crel tagName,args... bless: (component,itsName=null)-> component = component.default if component.__esModule && component.default name = itsName || component.name allTags[name]= Halvalla::[name] = (args...) => @crel component, args... renderContents: (contents, rest...) -> #for Teacup style signatures, we expect a single parameter-less function # we call it and it wil leave stuff on the 'stack' if not contents? return if typeof contents is 'function' contents = contents.apply @, rest if typeof contents is 'number' return @bagMan.shipOut new Number contents if typeof contents is 'string' return @bagMan.shipOut new String contents if contents.length >0 return @bagMan.shipOut contents... return [] component: (func) -> (args...) => {selector, attrs, contents} = @normalizeArgs(args) child = (args...) => # in theory, their might be many elements in contents # the most common use case is a singleton array # which needs to be promoted as the 'child' of this activation # this twerk allows the test to pass, but the larger situation??? args.unshift contents[0] @renderContents.apply @, args func.apply @, [selector, attrs, child] crelVoid: (tagName, args...) -> {attrs, contents} = @normalizeArgs args if contents.length > 0 throw new Error "Element type is invalid: must not have content: #{tagName}" return @crel tagName, args... crel: (tagName, args...) -> unless tagName? throw new Error "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: #{tagName}" {attrs, contents} = @normalizeArgs args children = if contents.length > 0 oldBagger = @bagMan @bagMan = new BagMan @bagMan.context contents @march @bagMan contents = @bagMan.harvest() @bagMan = oldBagger #console.log "Children",contents contents else [] if typeof tagName != 'function' name = tagName el = oracle.createElement tagName, attrs, children... else tagConstructor=tagName name = tagName.name tagName= name[0].toLowerCase()+name.slice 1 #console.log "Activvating NEW" unless Halvalla::[tagName] #generate alias for stack dumps Halvalla::[tagName]= (component, args...) -> @crel tagName,component,args... if oracle.preInstantiate # mithril specific Component instantiation done here el1 = new tagConstructor tagName #attrs._Halvalla= el1._Halvalla ## promote for mithril el = oracle.createElement el1,attrs,null # no children until 'view'ed else name = tagName el = oracle.createElement tagName, attrs, children... el._Halvalla= { birthName: 'Supplicant '+nameMine.getName() tagName: tagName propertyName: oracle.propertyName, children: oracle.getChildren el } unless el._Halvalla @bagMan.shipOut el return el text: (s) -> return s unless s?.toString return @bagMan.shipOut s.toString() isSelector: (string) -> string.length > 1 and string.charAt(0) in ['#', '.'] parseSelector: (selector) -> id = null classes = [] for token in selector.split '.' token = token.trim() if id classes.push token else [klass, id] = token.split '#' classes.push token unless klass is '' return {id, classes} normalizeArgs: (args) -> args = [args] unless args.length? attrs = {} selector = null contents = null for arg, index in args when arg? switch typeof arg when 'string' if index is 0 and @isSelector(arg) selector = arg parsedSelector = @parseSelector(arg) else contents= new String arg when 'number', 'boolean' contents= new String arg when 'function' contents = arg when 'object' if arg.constructor == Object attrs = arg arg = arg.default if arg.default && arg.__esModule if arg.constructor == Object and not oracle.isValidElement arg attrs = Object.keys(arg).reduce( (clone, key) -> clone[key] = arg[key]; clone {} ) if arg.toString?() != '[object Object]' contents = arg.toString() else if arg.length? contents= arg else contents = arg if parsedSelector? {id, classes} = parsedSelector attrs.id = id if id? if classes?.length if attrs.class classes.push attrs.class attrs.class = classes.join(' ') if attrs.className classes.push attrs.className attrs.className = classes.join(' ') # Expand data attributes dataAttrs = attrs.data if typeof dataAttrs is 'object' delete attrs.data for k, v of dataAttrs attrs["data-#{k}"] = v contents = normalizeArray contents return {attrs, contents, selector} # # Plugins # use: (plugin) -> plugin @ renderable: (stuff)-> return (args...) => #console.log "RENDERABLE Called ", args... @create stuff args... # # rendering cede: (args...)-> @render args... #liftedd from teacup renderer. This side only does the instantiation march: (bag)-> while component = bag.inspect() #console.log "March Halvalla - to component",component #console.log "Constructor name",component.constructor.name switch n=component.constructor.name when 'Function' y=bag.harvest() x = component() # evaluate and push back if 'function' == typeof x w = x() x=w z=bag.harvest() ### we shold not reinspect more than just the single return from x() Why did the entire z need to be put in? bag.reinspect if z.length>0 then z else x ### bag.reinspect x break when 'String','Number' then bag.shipOut component when n[0].toLowerCase()+n.slice 1 then bag.shipOut component else tagName = oracle.getName component #console.log 'Tagname of March component type object',tagName if 'string'== typeof tagName bag.shipOut component break if 'function' == typeof tagName #this component has not been instantiated yet tagConstructor = tagName tagName = tagConstructor.name tagNameLC = tagName[0].toLowerCase()+tagName.slice 1 if component.attrs attrs = component.attrs else attrs = component.props if tagName[0] != tagNameLC[0] #console.log "Activvating NEW" unless Halvalla::[tagNameLC] #generate alias for stack dumps Halvalla::[tagNameLC]= (component, args...) -> @crel tagNameLC,component,args... #crell = new tagConstructor tagNameLC,attrs,component.children #console.log "calling crel A", crell crellB = @[tagNameLC] attrs,oracle.getChildren component #console.log "calling crel B", crellB bag.shipOut crellB break else #render the node and append it to the htmlOout string bag.shipOut @[tagNameLC] '.selectorCase',attrs,oracle.getChildren component return null create: (node,rest...)-> if 'function' == typeof node oldBagger = @bagMan @bagMan = new BagMan @bagMan.context ()=>node rest... @march @bagMan structure= @bagMan.harvest() @bagMan = oldBagger else if 'object' == typeof node structure = node else structure = new String node return structure render: (funct,rest...)-> structure = @create funct,rest... structure = [structure ] unless structure.length result = for element in structure #console.log "Render element sent to oracle.conjurer",element oracle.conjurer element #console.log "And it ends with a caboom",result return result.join '' # # Binding # tags: -> bound = {} bound.Oracle = oracle bound.Component = dummyComponent bound.Element = dummyElement boundMethodNames = [].concat( 'create bless cede component doctype escape ie normalizeArgs pureComponent raw render renderable tag text use'.split(' ') mergeElements 'regular', 'obsolete', 'raw', 'void', 'obsolete_void', 'script','coffeescript','comment' ) for method in boundMethodNames do (method) => allTags[method]= bound[method] = (args...) => if !@[method] throw "no method named #{method} in Halvalla" @[method].apply @, args # Define tag functions on the prototype for pretty stack traces for tagName in mergeElements 'regular', 'obsolete' do (tagName) => @mutator tagName,@crel for tagName in mergeElements 'raw' do (tagName) => @mutator tagName,@crel for tagName in mergeElements 'script' do (tagName) => @mutator tagName,@crel #allTags['ie']= Halvalla::['ie'] = (args...) -> @ie args... for tagName in mergeElements 'void', 'obsolete_void' do (tagName) => @mutator tagName,@crelVoid return bound if module?.exports module.exports = new Halvalla().tags() module.exports.Halvalla = Halvalla else window.Halvalla = new Halvalla().tags() window.Halvalla.Halvalla = Halvalla
67208
### # Halvalla -- bindings for element creation and expression via teact and teacup ### nameMine = require '../lib/name-mine' ### # The oracle, a globally supplied object to this module has this signature Examples of oracle -- the default is to do Teacup to HTML ReactDom = require 'react-dom' Oracle = summoner: React name: 'React' isValidElement: React.isValidElement Component: React.Component createElement: React.createElement conjurer: ReactDom.renderToString Mithril = require 'mithril' Oracle = name: 'Mithril' isValidElement: (c)->c.view? createElement: Mithril Component: {} ### {doctypes,elements,normalizeArray,mergeElements,allTags,escape,quote,BagMan} = require '../lib/html-tags' teacup = require '../lib/teacup' #if we are using React as the master, it supplies a class, otherwise an empty class with an empty view propertyName = 'props' GreatEmptiness = null dummyComponent = null dummyElement = null class Halvalla oracle=null # constructor: (Oracle=null)-> @bagMan = new BagMan GreatEmptiness = class GreatEmptiness constructor: (instantiator,Oracle={})-> defaultObject = isValidElement: (c)->c.view? name: Oracle.name || 'great-emptiness' Component: Oracle.Component || class Component Element: Oracle.Element || class Element createElement: (args...)-> new dummyElement args... summoner: null getChildren: (element)->element.children getProp: (element)->element.attrs getName: (element)->element.type||element._Halvalla?.tagName|| element.tagName propertyName: 'attrs' preInstantiate: true #needed for mithril, maybe for teacup, react??? conjurer: null # decorate this singleton with for key,value of Object.assign defaultObject, Oracle GreatEmptiness::[key] = value @teacup=new teacup instantiator,defaultObject @conjurer= @teacup.render.bind @teacup unless @conjurer @ # oracle = new GreatEmptiness ((component)=>@create component),Oracle propertyName = oracle.propertyName dummyComponent = class Component extends oracle.Component constructor:(tagName,properties,children...)-> super properties,children... @tagName=tagName @[propertyName] = properties unless @[propertyName] @children = @render @_Halvalla = birthName: '<NAME> '+nameMine.getName() propertyName:propertyName children:@render tagname: tagName[0].toLowerCase()+tagName.slice 1 #console.log "Component construct",@ #console.log "Component arguments",arguments return render: -> dummyElement = class Element extends oracle.Component constructor:(tagName,properties={},@children...)-> super properties,@children... @tagName=tagName @tag = tagName @[propertyName]=properties if propertyName == 'attr' @props = properties @children = @children[0] if @children.length ==1 if typeof tagName == 'object' name = tagName.name || tagName.constructor.name else name = tagName try name = name[0].toLowerCase()+name.slice 1 catch name = "badSeed" #console.log "Bad Seed!",@ @_Halvalla = birthName: '<NAME> '+nameMine.getName() tagName: name[0].toLowerCase()+name.slice 1 propertyName:propertyName children:@[propertyName].children #console.log "Element construct",@ #console.log "Element attrs should be object, typeof this.attrs = ",typeof @.attrs #console.log "Element arguments",arguments return view: -> mutator: (tagName,destination,withThis=null)-> do (tagName)=> Halvalla::[tagName] = (args...) => destination.apply @, [tagName].concat args thing= Halvalla::[tagName] thing.Halvalla={tagName:tagName,boss:oracle.name} allTags[tagName] = thing return thing # global Oracle # # bring in some pure utility text functions escape:escape quote:quote pureComponent: (contents) -> return => @bagMan.context [] @bagMan.shipOut contents.apply @, arguments stackHad=@bagMan.harvest() #console.log "Pure ", st #console.log "WAS ",previous return stackHad coffeescript: (fn)-> @raw """<script type="text/javascript">(function() { var slice = [].slice, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; (#{fn.toString().replace /<\//g,"<\\/"})(); })();</script>""" comment: (text)-> unless text.toString throw new Error "comment tag allows text only: expected a string" return @raw "<!--#{escape text}-->" raw: (text="")-> #allow empty or null parmameter unless text.toString throw new Error "raw allows text only: expected a string" if oracle.trust el = oracle.trust text else el = oracle.createElement 'text', dangerouslySetInnerHTML: __html: text.toString() return @bagMan.shipOut el doctype: (type=5) -> #console.log "doctype request #{type}" #console.log "and it is... ",doctypes @raw doctypes[type] ie: (condition,contents)-> @crel 'ie',condition:condition,contents tag: (tagName,args...) -> unless tagName? && 'string'== typeof tagName throw new Error "HTML tag type is invalid: expected a string but got #{typeof tagName?}" return @crel tagName,args... bless: (component,itsName=null)-> component = component.default if component.__esModule && component.default name = itsName || component.name allTags[name]= Halvalla::[name] = (args...) => @crel component, args... renderContents: (contents, rest...) -> #for Teacup style signatures, we expect a single parameter-less function # we call it and it wil leave stuff on the 'stack' if not contents? return if typeof contents is 'function' contents = contents.apply @, rest if typeof contents is 'number' return @bagMan.shipOut new Number contents if typeof contents is 'string' return @bagMan.shipOut new String contents if contents.length >0 return @bagMan.shipOut contents... return [] component: (func) -> (args...) => {selector, attrs, contents} = @normalizeArgs(args) child = (args...) => # in theory, their might be many elements in contents # the most common use case is a singleton array # which needs to be promoted as the 'child' of this activation # this twerk allows the test to pass, but the larger situation??? args.unshift contents[0] @renderContents.apply @, args func.apply @, [selector, attrs, child] crelVoid: (tagName, args...) -> {attrs, contents} = @normalizeArgs args if contents.length > 0 throw new Error "Element type is invalid: must not have content: #{tagName}" return @crel tagName, args... crel: (tagName, args...) -> unless tagName? throw new Error "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: #{tagName}" {attrs, contents} = @normalizeArgs args children = if contents.length > 0 oldBagger = @bagMan @bagMan = new BagMan @bagMan.context contents @march @bagMan contents = @bagMan.harvest() @bagMan = oldBagger #console.log "Children",contents contents else [] if typeof tagName != 'function' name = tagName el = oracle.createElement tagName, attrs, children... else tagConstructor=tagName name = tagName.name tagName= name[0].toLowerCase()+name.slice 1 #console.log "Activvating NEW" unless Halvalla::[tagName] #generate alias for stack dumps Halvalla::[tagName]= (component, args...) -> @crel tagName,component,args... if oracle.preInstantiate # mithril specific Component instantiation done here el1 = new tagConstructor tagName #attrs._Halvalla= el1._Halvalla ## promote for mithril el = oracle.createElement el1,attrs,null # no children until 'view'ed else name = tagName el = oracle.createElement tagName, attrs, children... el._Halvalla= { birthName: 'Supplicant '+nameMine.getName() tagName: tagName propertyName: oracle.propertyName, children: oracle.getChildren el } unless el._Halvalla @bagMan.shipOut el return el text: (s) -> return s unless s?.toString return @bagMan.shipOut s.toString() isSelector: (string) -> string.length > 1 and string.charAt(0) in ['#', '.'] parseSelector: (selector) -> id = null classes = [] for token in selector.split '.' token = token.trim() if id classes.push token else [klass, id] = token.split '#' classes.push token unless klass is '' return {id, classes} normalizeArgs: (args) -> args = [args] unless args.length? attrs = {} selector = null contents = null for arg, index in args when arg? switch typeof arg when 'string' if index is 0 and @isSelector(arg) selector = arg parsedSelector = @parseSelector(arg) else contents= new String arg when 'number', 'boolean' contents= new String arg when 'function' contents = arg when 'object' if arg.constructor == Object attrs = arg arg = arg.default if arg.default && arg.__esModule if arg.constructor == Object and not oracle.isValidElement arg attrs = Object.keys(arg).reduce( (clone, key) -> clone[key] = arg[key]; clone {} ) if arg.toString?() != '[object Object]' contents = arg.toString() else if arg.length? contents= arg else contents = arg if parsedSelector? {id, classes} = parsedSelector attrs.id = id if id? if classes?.length if attrs.class classes.push attrs.class attrs.class = classes.join(' ') if attrs.className classes.push attrs.className attrs.className = classes.join(' ') # Expand data attributes dataAttrs = attrs.data if typeof dataAttrs is 'object' delete attrs.data for k, v of dataAttrs attrs["data-#{k}"] = v contents = normalizeArray contents return {attrs, contents, selector} # # Plugins # use: (plugin) -> plugin @ renderable: (stuff)-> return (args...) => #console.log "RENDERABLE Called ", args... @create stuff args... # # rendering cede: (args...)-> @render args... #liftedd from teacup renderer. This side only does the instantiation march: (bag)-> while component = bag.inspect() #console.log "March Halvalla - to component",component #console.log "Constructor name",component.constructor.name switch n=component.constructor.name when 'Function' y=bag.harvest() x = component() # evaluate and push back if 'function' == typeof x w = x() x=w z=bag.harvest() ### we shold not reinspect more than just the single return from x() Why did the entire z need to be put in? bag.reinspect if z.length>0 then z else x ### bag.reinspect x break when 'String','Number' then bag.shipOut component when n[0].toLowerCase()+n.slice 1 then bag.shipOut component else tagName = oracle.getName component #console.log 'Tagname of March component type object',tagName if 'string'== typeof tagName bag.shipOut component break if 'function' == typeof tagName #this component has not been instantiated yet tagConstructor = tagName tagName = tagConstructor.name tagNameLC = tagName[0].toLowerCase()+tagName.slice 1 if component.attrs attrs = component.attrs else attrs = component.props if tagName[0] != tagNameLC[0] #console.log "Activvating NEW" unless Halvalla::[tagNameLC] #generate alias for stack dumps Halvalla::[tagNameLC]= (component, args...) -> @crel tagNameLC,component,args... #crell = new tagConstructor tagNameLC,attrs,component.children #console.log "calling crel A", crell crellB = @[tagNameLC] attrs,oracle.getChildren component #console.log "calling crel B", crellB bag.shipOut crellB break else #render the node and append it to the htmlOout string bag.shipOut @[tagNameLC] '.selectorCase',attrs,oracle.getChildren component return null create: (node,rest...)-> if 'function' == typeof node oldBagger = @bagMan @bagMan = new BagMan @bagMan.context ()=>node rest... @march @bagMan structure= @bagMan.harvest() @bagMan = oldBagger else if 'object' == typeof node structure = node else structure = new String node return structure render: (funct,rest...)-> structure = @create funct,rest... structure = [structure ] unless structure.length result = for element in structure #console.log "Render element sent to oracle.conjurer",element oracle.conjurer element #console.log "And it ends with a caboom",result return result.join '' # # Binding # tags: -> bound = {} bound.Oracle = oracle bound.Component = dummyComponent bound.Element = dummyElement boundMethodNames = [].concat( 'create bless cede component doctype escape ie normalizeArgs pureComponent raw render renderable tag text use'.split(' ') mergeElements 'regular', 'obsolete', 'raw', 'void', 'obsolete_void', 'script','coffeescript','comment' ) for method in boundMethodNames do (method) => allTags[method]= bound[method] = (args...) => if !@[method] throw "no method named #{method} in Halvalla" @[method].apply @, args # Define tag functions on the prototype for pretty stack traces for tagName in mergeElements 'regular', 'obsolete' do (tagName) => @mutator tagName,@crel for tagName in mergeElements 'raw' do (tagName) => @mutator tagName,@crel for tagName in mergeElements 'script' do (tagName) => @mutator tagName,@crel #allTags['ie']= Halvalla::['ie'] = (args...) -> @ie args... for tagName in mergeElements 'void', 'obsolete_void' do (tagName) => @mutator tagName,@crelVoid return bound if module?.exports module.exports = new Halvalla().tags() module.exports.Halvalla = Halvalla else window.Halvalla = new Halvalla().tags() window.Halvalla.Halvalla = Halvalla
true
### # Halvalla -- bindings for element creation and expression via teact and teacup ### nameMine = require '../lib/name-mine' ### # The oracle, a globally supplied object to this module has this signature Examples of oracle -- the default is to do Teacup to HTML ReactDom = require 'react-dom' Oracle = summoner: React name: 'React' isValidElement: React.isValidElement Component: React.Component createElement: React.createElement conjurer: ReactDom.renderToString Mithril = require 'mithril' Oracle = name: 'Mithril' isValidElement: (c)->c.view? createElement: Mithril Component: {} ### {doctypes,elements,normalizeArray,mergeElements,allTags,escape,quote,BagMan} = require '../lib/html-tags' teacup = require '../lib/teacup' #if we are using React as the master, it supplies a class, otherwise an empty class with an empty view propertyName = 'props' GreatEmptiness = null dummyComponent = null dummyElement = null class Halvalla oracle=null # constructor: (Oracle=null)-> @bagMan = new BagMan GreatEmptiness = class GreatEmptiness constructor: (instantiator,Oracle={})-> defaultObject = isValidElement: (c)->c.view? name: Oracle.name || 'great-emptiness' Component: Oracle.Component || class Component Element: Oracle.Element || class Element createElement: (args...)-> new dummyElement args... summoner: null getChildren: (element)->element.children getProp: (element)->element.attrs getName: (element)->element.type||element._Halvalla?.tagName|| element.tagName propertyName: 'attrs' preInstantiate: true #needed for mithril, maybe for teacup, react??? conjurer: null # decorate this singleton with for key,value of Object.assign defaultObject, Oracle GreatEmptiness::[key] = value @teacup=new teacup instantiator,defaultObject @conjurer= @teacup.render.bind @teacup unless @conjurer @ # oracle = new GreatEmptiness ((component)=>@create component),Oracle propertyName = oracle.propertyName dummyComponent = class Component extends oracle.Component constructor:(tagName,properties,children...)-> super properties,children... @tagName=tagName @[propertyName] = properties unless @[propertyName] @children = @render @_Halvalla = birthName: 'PI:NAME:<NAME>END_PI '+nameMine.getName() propertyName:propertyName children:@render tagname: tagName[0].toLowerCase()+tagName.slice 1 #console.log "Component construct",@ #console.log "Component arguments",arguments return render: -> dummyElement = class Element extends oracle.Component constructor:(tagName,properties={},@children...)-> super properties,@children... @tagName=tagName @tag = tagName @[propertyName]=properties if propertyName == 'attr' @props = properties @children = @children[0] if @children.length ==1 if typeof tagName == 'object' name = tagName.name || tagName.constructor.name else name = tagName try name = name[0].toLowerCase()+name.slice 1 catch name = "badSeed" #console.log "Bad Seed!",@ @_Halvalla = birthName: 'PI:NAME:<NAME>END_PI '+nameMine.getName() tagName: name[0].toLowerCase()+name.slice 1 propertyName:propertyName children:@[propertyName].children #console.log "Element construct",@ #console.log "Element attrs should be object, typeof this.attrs = ",typeof @.attrs #console.log "Element arguments",arguments return view: -> mutator: (tagName,destination,withThis=null)-> do (tagName)=> Halvalla::[tagName] = (args...) => destination.apply @, [tagName].concat args thing= Halvalla::[tagName] thing.Halvalla={tagName:tagName,boss:oracle.name} allTags[tagName] = thing return thing # global Oracle # # bring in some pure utility text functions escape:escape quote:quote pureComponent: (contents) -> return => @bagMan.context [] @bagMan.shipOut contents.apply @, arguments stackHad=@bagMan.harvest() #console.log "Pure ", st #console.log "WAS ",previous return stackHad coffeescript: (fn)-> @raw """<script type="text/javascript">(function() { var slice = [].slice, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; (#{fn.toString().replace /<\//g,"<\\/"})(); })();</script>""" comment: (text)-> unless text.toString throw new Error "comment tag allows text only: expected a string" return @raw "<!--#{escape text}-->" raw: (text="")-> #allow empty or null parmameter unless text.toString throw new Error "raw allows text only: expected a string" if oracle.trust el = oracle.trust text else el = oracle.createElement 'text', dangerouslySetInnerHTML: __html: text.toString() return @bagMan.shipOut el doctype: (type=5) -> #console.log "doctype request #{type}" #console.log "and it is... ",doctypes @raw doctypes[type] ie: (condition,contents)-> @crel 'ie',condition:condition,contents tag: (tagName,args...) -> unless tagName? && 'string'== typeof tagName throw new Error "HTML tag type is invalid: expected a string but got #{typeof tagName?}" return @crel tagName,args... bless: (component,itsName=null)-> component = component.default if component.__esModule && component.default name = itsName || component.name allTags[name]= Halvalla::[name] = (args...) => @crel component, args... renderContents: (contents, rest...) -> #for Teacup style signatures, we expect a single parameter-less function # we call it and it wil leave stuff on the 'stack' if not contents? return if typeof contents is 'function' contents = contents.apply @, rest if typeof contents is 'number' return @bagMan.shipOut new Number contents if typeof contents is 'string' return @bagMan.shipOut new String contents if contents.length >0 return @bagMan.shipOut contents... return [] component: (func) -> (args...) => {selector, attrs, contents} = @normalizeArgs(args) child = (args...) => # in theory, their might be many elements in contents # the most common use case is a singleton array # which needs to be promoted as the 'child' of this activation # this twerk allows the test to pass, but the larger situation??? args.unshift contents[0] @renderContents.apply @, args func.apply @, [selector, attrs, child] crelVoid: (tagName, args...) -> {attrs, contents} = @normalizeArgs args if contents.length > 0 throw new Error "Element type is invalid: must not have content: #{tagName}" return @crel tagName, args... crel: (tagName, args...) -> unless tagName? throw new Error "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: #{tagName}" {attrs, contents} = @normalizeArgs args children = if contents.length > 0 oldBagger = @bagMan @bagMan = new BagMan @bagMan.context contents @march @bagMan contents = @bagMan.harvest() @bagMan = oldBagger #console.log "Children",contents contents else [] if typeof tagName != 'function' name = tagName el = oracle.createElement tagName, attrs, children... else tagConstructor=tagName name = tagName.name tagName= name[0].toLowerCase()+name.slice 1 #console.log "Activvating NEW" unless Halvalla::[tagName] #generate alias for stack dumps Halvalla::[tagName]= (component, args...) -> @crel tagName,component,args... if oracle.preInstantiate # mithril specific Component instantiation done here el1 = new tagConstructor tagName #attrs._Halvalla= el1._Halvalla ## promote for mithril el = oracle.createElement el1,attrs,null # no children until 'view'ed else name = tagName el = oracle.createElement tagName, attrs, children... el._Halvalla= { birthName: 'Supplicant '+nameMine.getName() tagName: tagName propertyName: oracle.propertyName, children: oracle.getChildren el } unless el._Halvalla @bagMan.shipOut el return el text: (s) -> return s unless s?.toString return @bagMan.shipOut s.toString() isSelector: (string) -> string.length > 1 and string.charAt(0) in ['#', '.'] parseSelector: (selector) -> id = null classes = [] for token in selector.split '.' token = token.trim() if id classes.push token else [klass, id] = token.split '#' classes.push token unless klass is '' return {id, classes} normalizeArgs: (args) -> args = [args] unless args.length? attrs = {} selector = null contents = null for arg, index in args when arg? switch typeof arg when 'string' if index is 0 and @isSelector(arg) selector = arg parsedSelector = @parseSelector(arg) else contents= new String arg when 'number', 'boolean' contents= new String arg when 'function' contents = arg when 'object' if arg.constructor == Object attrs = arg arg = arg.default if arg.default && arg.__esModule if arg.constructor == Object and not oracle.isValidElement arg attrs = Object.keys(arg).reduce( (clone, key) -> clone[key] = arg[key]; clone {} ) if arg.toString?() != '[object Object]' contents = arg.toString() else if arg.length? contents= arg else contents = arg if parsedSelector? {id, classes} = parsedSelector attrs.id = id if id? if classes?.length if attrs.class classes.push attrs.class attrs.class = classes.join(' ') if attrs.className classes.push attrs.className attrs.className = classes.join(' ') # Expand data attributes dataAttrs = attrs.data if typeof dataAttrs is 'object' delete attrs.data for k, v of dataAttrs attrs["data-#{k}"] = v contents = normalizeArray contents return {attrs, contents, selector} # # Plugins # use: (plugin) -> plugin @ renderable: (stuff)-> return (args...) => #console.log "RENDERABLE Called ", args... @create stuff args... # # rendering cede: (args...)-> @render args... #liftedd from teacup renderer. This side only does the instantiation march: (bag)-> while component = bag.inspect() #console.log "March Halvalla - to component",component #console.log "Constructor name",component.constructor.name switch n=component.constructor.name when 'Function' y=bag.harvest() x = component() # evaluate and push back if 'function' == typeof x w = x() x=w z=bag.harvest() ### we shold not reinspect more than just the single return from x() Why did the entire z need to be put in? bag.reinspect if z.length>0 then z else x ### bag.reinspect x break when 'String','Number' then bag.shipOut component when n[0].toLowerCase()+n.slice 1 then bag.shipOut component else tagName = oracle.getName component #console.log 'Tagname of March component type object',tagName if 'string'== typeof tagName bag.shipOut component break if 'function' == typeof tagName #this component has not been instantiated yet tagConstructor = tagName tagName = tagConstructor.name tagNameLC = tagName[0].toLowerCase()+tagName.slice 1 if component.attrs attrs = component.attrs else attrs = component.props if tagName[0] != tagNameLC[0] #console.log "Activvating NEW" unless Halvalla::[tagNameLC] #generate alias for stack dumps Halvalla::[tagNameLC]= (component, args...) -> @crel tagNameLC,component,args... #crell = new tagConstructor tagNameLC,attrs,component.children #console.log "calling crel A", crell crellB = @[tagNameLC] attrs,oracle.getChildren component #console.log "calling crel B", crellB bag.shipOut crellB break else #render the node and append it to the htmlOout string bag.shipOut @[tagNameLC] '.selectorCase',attrs,oracle.getChildren component return null create: (node,rest...)-> if 'function' == typeof node oldBagger = @bagMan @bagMan = new BagMan @bagMan.context ()=>node rest... @march @bagMan structure= @bagMan.harvest() @bagMan = oldBagger else if 'object' == typeof node structure = node else structure = new String node return structure render: (funct,rest...)-> structure = @create funct,rest... structure = [structure ] unless structure.length result = for element in structure #console.log "Render element sent to oracle.conjurer",element oracle.conjurer element #console.log "And it ends with a caboom",result return result.join '' # # Binding # tags: -> bound = {} bound.Oracle = oracle bound.Component = dummyComponent bound.Element = dummyElement boundMethodNames = [].concat( 'create bless cede component doctype escape ie normalizeArgs pureComponent raw render renderable tag text use'.split(' ') mergeElements 'regular', 'obsolete', 'raw', 'void', 'obsolete_void', 'script','coffeescript','comment' ) for method in boundMethodNames do (method) => allTags[method]= bound[method] = (args...) => if !@[method] throw "no method named #{method} in Halvalla" @[method].apply @, args # Define tag functions on the prototype for pretty stack traces for tagName in mergeElements 'regular', 'obsolete' do (tagName) => @mutator tagName,@crel for tagName in mergeElements 'raw' do (tagName) => @mutator tagName,@crel for tagName in mergeElements 'script' do (tagName) => @mutator tagName,@crel #allTags['ie']= Halvalla::['ie'] = (args...) -> @ie args... for tagName in mergeElements 'void', 'obsolete_void' do (tagName) => @mutator tagName,@crelVoid return bound if module?.exports module.exports = new Halvalla().tags() module.exports.Halvalla = Halvalla else window.Halvalla = new Halvalla().tags() window.Halvalla.Halvalla = Halvalla
[ { "context": "te a model\", ->\n rawListing = {id: 9, name: 'Sunny'}\n results =\n listing: new Listing(ra", "end": 1680, "score": 0.9482371807098389, "start": 1675, "tag": "NAME", "value": "Sunny" }, { "context": "llection\", ->\n rawListings = [{id: 1, name: '...
test/shared/fetcher.test.coffee
redbadger/rendr
0
require('../../shared/globals') fetcher = require('../../shared/fetcher') should = require('should') modelUtils = require('../../shared/modelUtils') BaseModel = require('../../shared/base/model') BaseCollection = require('../../shared/base/collection') listingResponses = basic: name: 'Fetching!' full: name: 'Fetching!' city: 'San Francisco' class Listing extends BaseModel jsonKey: 'listing' fetch: (options) -> resp = getModelResponse('full', options.data.id, true) setTimeout => parsed = @parse(resp) @set(parsed) options.success(this, parsed) , 1 class Listings extends BaseCollection model: Listing jsonKey: 'listings' fetch: (options) -> resp = buildCollectionResponse(true) if options.data? resp.meta = options.data setTimeout => parsed = @parse(resp) @reset(parsed.map (attrs) => new @model(attrs, parse: true)) options.success(this, parsed) , 1 getModelResponse = (version, id, addJsonKey = false) -> resp = _.extend({}, listingResponses[version], {id}) if addJsonKey _.tap {}, (obj) -> obj.listing = resp else resp buildCollectionResponse = (addJsonKey = false) -> resp = [1..5].map (id) -> getModelResponse('basic', id, addJsonKey) if addJsonKey _.tap {}, (obj) -> obj.listings = resp else resp modelUtils.addClassMapping 'Listing', Listing modelUtils.addClassMapping 'Listings', Listings describe 'fetcher', -> describe 'hydrate', -> beforeEach -> fetcher.modelStore.clear() fetcher.collectionStore.clear() it "should be able store and hydrate a model", -> rawListing = {id: 9, name: 'Sunny'} results = listing: new Listing(rawListing) fetchSummary = listing: { model: 'listing', id: 9 } fetcher.storeResults results hydrated = fetcher.hydrate fetchSummary listing = hydrated.listing listing.should.be.an.instanceOf Listing listing.toJSON().should.eql rawListing it "should be able to store and hydrate a collection", -> rawListings = [{id: 1, name: 'Sunny'}, {id: 3, name: 'Cloudy'}, {id: 99, name: 'Tall'}] params = items_per_page: 99 results = listings: new Listings(rawListings, params: params) fetchSummary = listings: { collection: 'listings', ids: _.pluck(rawListings, 'id'), params: params } fetcher.storeResults results hydrated = fetcher.hydrate fetchSummary listings = hydrated.listings listings.should.be.an.instanceOf Listings listings.toJSON().should.eql rawListings listings.params.should.eql params should.not.exist fetcher.collectionStore.get('Listings', {}) fetcher.collectionStore.get('Listings', params).should.eql ids: listings.pluck('id') meta: {} it "should be able to hydrate multiple objects at once", -> rawListing = {id: 9, name: 'Sunny'} rawListings = [{id: 1, name: 'Sunny'}, {id: 3, name: 'Cloudy'}, {id: 99, name: 'Tall'}] results = listing: new Listing(rawListing) listings: new Listings(rawListings) fetchSummary = listing: { model: 'listing', id: 9 } listings: { collection: 'listings', ids: [1,3,99] } fetcher.storeResults results hydrated = fetcher.hydrate fetchSummary listing = hydrated.listing listing.should.be.an.instanceOf Listing should.deepEqual listing.toJSON(), rawListing listings = hydrated.listings listings.should.be.an.instanceOf Listings should.deepEqual listings.toJSON(), rawListings it "should inject the app instance", -> listing1 = new Listing(id: 1) fetcher.modelStore.set(listing1) summaries = model: id: 1 model: 'Listing' app = fake: 'app' results = fetcher.hydrate(summaries, app: app) model = results.model model.app.should.eql(app) describe 'fetch', -> beforeEach -> fetcher.modelStore.clear() fetcher.collectionStore.clear() fetcher.off(null, null) it "should be able to fetch a model", (done) -> fetchSpec = model: { model: 'Listing', params: { id: 1 } } fetcher.pendingFetches.should.eql 0 fetcher.fetch fetchSpec, (err, results) -> fetcher.pendingFetches.should.eql 0 return done(err) if err results.model.should.be.an.instanceOf(Listing) results.model.toJSON().should.eql(getModelResponse('full', 1)) done() fetcher.pendingFetches.should.eql 1 it "should be able to fetch a collection", (done) -> fetchSpec = collection: { collection: 'Listings' } fetcher.pendingFetches.should.eql 0 fetcher.fetch fetchSpec, (err, results) -> fetcher.pendingFetches.should.eql 0 return done(err) if err results.collection.should.be.an.instanceOf(Listings) results.collection.toJSON().should.eql(buildCollectionResponse()) done() fetcher.pendingFetches.should.eql 1 it "should be able to fetch both a model and a collection at the same time", (done) -> fetchSpec = model: { model: 'Listing', params: { id: 1 } } collection: { collection: 'Listings' } fetcher.pendingFetches.should.eql 0 fetcher.fetch fetchSpec, (err, results) -> fetcher.pendingFetches.should.eql 0 return done(err) if err results.model.should.be.an.instanceOf(Listing) results.model.toJSON().should.eql(getModelResponse('full', 1)) results.collection.should.be.an.instanceOf(Listings) results.collection.toJSON().should.eql(buildCollectionResponse()) done() fetcher.pendingFetches.should.eql 1 it "should be able to fetch models from cache with custom idAttribute", (done) -> class User extends BaseModel idAttribute: 'login' userAttrs = login: 'someperson' name: 'Some Person' someperson = new User(userAttrs) modelUtils.addClassMapping 'user', User fetcher.modelStore.set(someperson) fetchSpec = model: { model: 'user', params: { login: 'someperson' } } fetcher.fetch fetchSpec, {readFromCache: true}, (err, results) -> return done(err) if err results.model.should.be.an.instanceOf(User) results.model.toJSON().should.eql(userAttrs) done() it "should be able to re-fetch if already exists but is missing key", (done) -> # First, fetch the collection, which has smaller versions of the models. fetchSpec = collection: { collection: 'Listings' } fetcher.fetch fetchSpec, {writeToCache: true}, (err, results) -> return done(err) if err results.collection.toJSON().should.eql(buildCollectionResponse()) # Make sure that the basic version is stored in modelStore. fetcher.modelStore.get('Listing', 1).should.eql getModelResponse('basic', 1) # Then, fetch the single model, which should be cached. fetchSpec = model: { model: 'Listing', params: { id: 1 } } fetcher.fetch fetchSpec, {readFromCache: true}, (err, results) -> return done(err) if err results.model.toJSON().should.eql(getModelResponse('basic', 1)) # Finally, fetch the single model, but specifiy that certain key must be present. fetchSpec = model: { model: 'Listing', params: { id: 1 }, ensureKeys: ['city'] } fetcher.fetch fetchSpec, {readFromCache: true}, (err, results) -> return done(err) if err results.model.toJSON().should.eql(getModelResponse('full', 1)) done() it "should emit events", (done) -> startEmitted = false endEmitted = false fetcher.on 'fetch:start', (eventFetchSpec) -> startEmitted = true eventFetchSpec.should.eql fetchSpec fetcher.on 'fetch:end', (eventFetchSpec) -> endEmitted = true eventFetchSpec.should.eql fetchSpec fetchSpec = model: { model: 'Listing', params: { id: 1 } } fetcher.fetch fetchSpec, (err, results) -> startEmitted.should.be.true endEmitted.should.be.true done(err) if err results.model.should.be.an.instanceOf(Listing) results.model.toJSON().should.eql(getModelResponse('full', 1)) done() startEmitted.should.be.true endEmitted.should.be.false describe 'isMissingKeys', -> before -> @modelData = id: 1 name: 'foobar' it "should be false if keys not passed in", -> fetcher.isMissingKeys(@modelData, undefined).should.be.false fetcher.isMissingKeys(@modelData, []).should.be.false it "should be false if keys passed in but are present", -> fetcher.isMissingKeys(@modelData, 'name').should.be.false fetcher.isMissingKeys(@modelData, ['name']).should.be.false fetcher.isMissingKeys(@modelData, ['id', 'name']).should.be.false it "should be true if keys passed in are not present", -> fetcher.isMissingKeys(@modelData, 'city').should.be.true fetcher.isMissingKeys(@modelData, ['city']).should.be.true fetcher.isMissingKeys(@modelData, ['id', 'city']).should.be.true describe 'summarize', -> it "should summarize a model", -> attrs = id: 1234 blahblah: 'boomtown' model = new Listing(attrs) summary = fetcher.summarize(model) summary.model.should.eql 'listing' summary.id.should.eql attrs.id it "should support custom idAttribute", -> attrs = login: 'joeschmo' blahblah: 'boomtown' class CustomListing extends Listing idAttribute: 'login' model = new CustomListing(attrs) summary = fetcher.summarize(model) summary.model.should.eql 'custom_listing' summary.id.should.eql attrs.login it "should summarize a collection", -> models = [{ id: 1 name: 'foo' }, { id: 2 name: 'bar' }] params = some: 'key' other: 'value' meta = the: 'one' foo: 'butt' collection = new Listings(models, {params, meta}) summary = fetcher.summarize(collection) summary.collection.should.eql 'listings' summary.ids.should.eql [1,2] summary.params.should.eql params summary.meta.should.eql meta describe 'checkFresh', -> describe 'didCheckFresh', -> beforeEach -> fetcher.checkedFreshTimestamps = {} @spec = model: 'foobutt' params: {} it "should store it properly", -> fetcher.didCheckFresh(@spec) key = fetcher.checkedFreshKey(@spec) fetcher.checkedFreshTimestamps[key].should.be.ok describe 'shouldCheckFresh', -> beforeEach -> fetcher.checkedFreshTimestamps = {} @spec = model: 'foobutt' params: {} it "should return true if timestamp doesn't exist", -> fetcher.shouldCheckFresh(@spec).should.be.true it "should return true if timestamp exists and is greater than 'checkedFreshRate' ago", -> key = fetcher.checkedFreshKey(@spec) now = new Date().getTime() fetcher.checkedFreshTimestamps[key] = now - fetcher.checkedFreshRate - 1000 fetcher.shouldCheckFresh(@spec).should.be.true it "should return false if timestamp exists and is less than 'checkedFreshRate' ago", -> key = fetcher.checkedFreshKey(@spec) now = new Date().getTime() fetcher.checkedFreshTimestamps[key] = now - 1 fetcher.shouldCheckFresh(@spec).should.be.false
113373
require('../../shared/globals') fetcher = require('../../shared/fetcher') should = require('should') modelUtils = require('../../shared/modelUtils') BaseModel = require('../../shared/base/model') BaseCollection = require('../../shared/base/collection') listingResponses = basic: name: 'Fetching!' full: name: 'Fetching!' city: 'San Francisco' class Listing extends BaseModel jsonKey: 'listing' fetch: (options) -> resp = getModelResponse('full', options.data.id, true) setTimeout => parsed = @parse(resp) @set(parsed) options.success(this, parsed) , 1 class Listings extends BaseCollection model: Listing jsonKey: 'listings' fetch: (options) -> resp = buildCollectionResponse(true) if options.data? resp.meta = options.data setTimeout => parsed = @parse(resp) @reset(parsed.map (attrs) => new @model(attrs, parse: true)) options.success(this, parsed) , 1 getModelResponse = (version, id, addJsonKey = false) -> resp = _.extend({}, listingResponses[version], {id}) if addJsonKey _.tap {}, (obj) -> obj.listing = resp else resp buildCollectionResponse = (addJsonKey = false) -> resp = [1..5].map (id) -> getModelResponse('basic', id, addJsonKey) if addJsonKey _.tap {}, (obj) -> obj.listings = resp else resp modelUtils.addClassMapping 'Listing', Listing modelUtils.addClassMapping 'Listings', Listings describe 'fetcher', -> describe 'hydrate', -> beforeEach -> fetcher.modelStore.clear() fetcher.collectionStore.clear() it "should be able store and hydrate a model", -> rawListing = {id: 9, name: '<NAME>'} results = listing: new Listing(rawListing) fetchSummary = listing: { model: 'listing', id: 9 } fetcher.storeResults results hydrated = fetcher.hydrate fetchSummary listing = hydrated.listing listing.should.be.an.instanceOf Listing listing.toJSON().should.eql rawListing it "should be able to store and hydrate a collection", -> rawListings = [{id: 1, name: '<NAME>'}, {id: 3, name: 'Cloudy'}, {id: 99, name: 'Tall'}] params = items_per_page: 99 results = listings: new Listings(rawListings, params: params) fetchSummary = listings: { collection: 'listings', ids: _.pluck(rawListings, 'id'), params: params } fetcher.storeResults results hydrated = fetcher.hydrate fetchSummary listings = hydrated.listings listings.should.be.an.instanceOf Listings listings.toJSON().should.eql rawListings listings.params.should.eql params should.not.exist fetcher.collectionStore.get('Listings', {}) fetcher.collectionStore.get('Listings', params).should.eql ids: listings.pluck('id') meta: {} it "should be able to hydrate multiple objects at once", -> rawListing = {id: 9, name: '<NAME>'} rawListings = [{id: 1, name: '<NAME>'}, {id: 3, name: 'Cloudy'}, {id: 99, name: 'Tall'}] results = listing: new Listing(rawListing) listings: new Listings(rawListings) fetchSummary = listing: { model: 'listing', id: 9 } listings: { collection: 'listings', ids: [1,3,99] } fetcher.storeResults results hydrated = fetcher.hydrate fetchSummary listing = hydrated.listing listing.should.be.an.instanceOf Listing should.deepEqual listing.toJSON(), rawListing listings = hydrated.listings listings.should.be.an.instanceOf Listings should.deepEqual listings.toJSON(), rawListings it "should inject the app instance", -> listing1 = new Listing(id: 1) fetcher.modelStore.set(listing1) summaries = model: id: 1 model: 'Listing' app = fake: 'app' results = fetcher.hydrate(summaries, app: app) model = results.model model.app.should.eql(app) describe 'fetch', -> beforeEach -> fetcher.modelStore.clear() fetcher.collectionStore.clear() fetcher.off(null, null) it "should be able to fetch a model", (done) -> fetchSpec = model: { model: 'Listing', params: { id: 1 } } fetcher.pendingFetches.should.eql 0 fetcher.fetch fetchSpec, (err, results) -> fetcher.pendingFetches.should.eql 0 return done(err) if err results.model.should.be.an.instanceOf(Listing) results.model.toJSON().should.eql(getModelResponse('full', 1)) done() fetcher.pendingFetches.should.eql 1 it "should be able to fetch a collection", (done) -> fetchSpec = collection: { collection: 'Listings' } fetcher.pendingFetches.should.eql 0 fetcher.fetch fetchSpec, (err, results) -> fetcher.pendingFetches.should.eql 0 return done(err) if err results.collection.should.be.an.instanceOf(Listings) results.collection.toJSON().should.eql(buildCollectionResponse()) done() fetcher.pendingFetches.should.eql 1 it "should be able to fetch both a model and a collection at the same time", (done) -> fetchSpec = model: { model: 'Listing', params: { id: 1 } } collection: { collection: 'Listings' } fetcher.pendingFetches.should.eql 0 fetcher.fetch fetchSpec, (err, results) -> fetcher.pendingFetches.should.eql 0 return done(err) if err results.model.should.be.an.instanceOf(Listing) results.model.toJSON().should.eql(getModelResponse('full', 1)) results.collection.should.be.an.instanceOf(Listings) results.collection.toJSON().should.eql(buildCollectionResponse()) done() fetcher.pendingFetches.should.eql 1 it "should be able to fetch models from cache with custom idAttribute", (done) -> class User extends BaseModel idAttribute: 'login' userAttrs = login: 'someperson' name: '<NAME>' someperson = new User(userAttrs) modelUtils.addClassMapping 'user', User fetcher.modelStore.set(someperson) fetchSpec = model: { model: 'user', params: { login: 'someperson' } } fetcher.fetch fetchSpec, {readFromCache: true}, (err, results) -> return done(err) if err results.model.should.be.an.instanceOf(User) results.model.toJSON().should.eql(userAttrs) done() it "should be able to re-fetch if already exists but is missing key", (done) -> # First, fetch the collection, which has smaller versions of the models. fetchSpec = collection: { collection: 'Listings' } fetcher.fetch fetchSpec, {writeToCache: true}, (err, results) -> return done(err) if err results.collection.toJSON().should.eql(buildCollectionResponse()) # Make sure that the basic version is stored in modelStore. fetcher.modelStore.get('Listing', 1).should.eql getModelResponse('basic', 1) # Then, fetch the single model, which should be cached. fetchSpec = model: { model: 'Listing', params: { id: 1 } } fetcher.fetch fetchSpec, {readFromCache: true}, (err, results) -> return done(err) if err results.model.toJSON().should.eql(getModelResponse('basic', 1)) # Finally, fetch the single model, but specifiy that certain key must be present. fetchSpec = model: { model: 'Listing', params: { id: 1 }, ensureKeys: ['city'] } fetcher.fetch fetchSpec, {readFromCache: true}, (err, results) -> return done(err) if err results.model.toJSON().should.eql(getModelResponse('full', 1)) done() it "should emit events", (done) -> startEmitted = false endEmitted = false fetcher.on 'fetch:start', (eventFetchSpec) -> startEmitted = true eventFetchSpec.should.eql fetchSpec fetcher.on 'fetch:end', (eventFetchSpec) -> endEmitted = true eventFetchSpec.should.eql fetchSpec fetchSpec = model: { model: 'Listing', params: { id: 1 } } fetcher.fetch fetchSpec, (err, results) -> startEmitted.should.be.true endEmitted.should.be.true done(err) if err results.model.should.be.an.instanceOf(Listing) results.model.toJSON().should.eql(getModelResponse('full', 1)) done() startEmitted.should.be.true endEmitted.should.be.false describe 'isMissingKeys', -> before -> @modelData = id: 1 name: '<NAME>' it "should be false if keys not passed in", -> fetcher.isMissingKeys(@modelData, undefined).should.be.false fetcher.isMissingKeys(@modelData, []).should.be.false it "should be false if keys passed in but are present", -> fetcher.isMissingKeys(@modelData, 'name').should.be.false fetcher.isMissingKeys(@modelData, ['name']).should.be.false fetcher.isMissingKeys(@modelData, ['id', 'name']).should.be.false it "should be true if keys passed in are not present", -> fetcher.isMissingKeys(@modelData, 'city').should.be.true fetcher.isMissingKeys(@modelData, ['city']).should.be.true fetcher.isMissingKeys(@modelData, ['id', 'city']).should.be.true describe 'summarize', -> it "should summarize a model", -> attrs = id: 1234 blahblah: 'boomtown' model = new Listing(attrs) summary = fetcher.summarize(model) summary.model.should.eql 'listing' summary.id.should.eql attrs.id it "should support custom idAttribute", -> attrs = login: 'joeschmo' blahblah: 'boomtown' class CustomListing extends Listing idAttribute: 'login' model = new CustomListing(attrs) summary = fetcher.summarize(model) summary.model.should.eql 'custom_listing' summary.id.should.eql attrs.login it "should summarize a collection", -> models = [{ id: 1 name: 'foo' }, { id: 2 name: 'bar' }] params = some: 'key' other: 'value' meta = the: 'one' foo: 'butt' collection = new Listings(models, {params, meta}) summary = fetcher.summarize(collection) summary.collection.should.eql 'listings' summary.ids.should.eql [1,2] summary.params.should.eql params summary.meta.should.eql meta describe 'checkFresh', -> describe 'didCheckFresh', -> beforeEach -> fetcher.checkedFreshTimestamps = {} @spec = model: 'foobutt' params: {} it "should store it properly", -> fetcher.didCheckFresh(@spec) key = fetcher.checkedFreshKey(@spec) fetcher.checkedFreshTimestamps[key].should.be.ok describe 'shouldCheckFresh', -> beforeEach -> fetcher.checkedFreshTimestamps = {} @spec = model: 'foobutt' params: {} it "should return true if timestamp doesn't exist", -> fetcher.shouldCheckFresh(@spec).should.be.true it "should return true if timestamp exists and is greater than 'checkedFreshRate' ago", -> key = fetcher.checkedFreshKey(@spec) now = new Date().getTime() fetcher.checkedFreshTimestamps[key] = now - fetcher.checkedFreshRate - 1000 fetcher.shouldCheckFresh(@spec).should.be.true it "should return false if timestamp exists and is less than 'checkedFreshRate' ago", -> key = fetcher.checkedFreshKey(@spec) now = new Date().getTime() fetcher.checkedFreshTimestamps[key] = now - 1 fetcher.shouldCheckFresh(@spec).should.be.false
true
require('../../shared/globals') fetcher = require('../../shared/fetcher') should = require('should') modelUtils = require('../../shared/modelUtils') BaseModel = require('../../shared/base/model') BaseCollection = require('../../shared/base/collection') listingResponses = basic: name: 'Fetching!' full: name: 'Fetching!' city: 'San Francisco' class Listing extends BaseModel jsonKey: 'listing' fetch: (options) -> resp = getModelResponse('full', options.data.id, true) setTimeout => parsed = @parse(resp) @set(parsed) options.success(this, parsed) , 1 class Listings extends BaseCollection model: Listing jsonKey: 'listings' fetch: (options) -> resp = buildCollectionResponse(true) if options.data? resp.meta = options.data setTimeout => parsed = @parse(resp) @reset(parsed.map (attrs) => new @model(attrs, parse: true)) options.success(this, parsed) , 1 getModelResponse = (version, id, addJsonKey = false) -> resp = _.extend({}, listingResponses[version], {id}) if addJsonKey _.tap {}, (obj) -> obj.listing = resp else resp buildCollectionResponse = (addJsonKey = false) -> resp = [1..5].map (id) -> getModelResponse('basic', id, addJsonKey) if addJsonKey _.tap {}, (obj) -> obj.listings = resp else resp modelUtils.addClassMapping 'Listing', Listing modelUtils.addClassMapping 'Listings', Listings describe 'fetcher', -> describe 'hydrate', -> beforeEach -> fetcher.modelStore.clear() fetcher.collectionStore.clear() it "should be able store and hydrate a model", -> rawListing = {id: 9, name: 'PI:NAME:<NAME>END_PI'} results = listing: new Listing(rawListing) fetchSummary = listing: { model: 'listing', id: 9 } fetcher.storeResults results hydrated = fetcher.hydrate fetchSummary listing = hydrated.listing listing.should.be.an.instanceOf Listing listing.toJSON().should.eql rawListing it "should be able to store and hydrate a collection", -> rawListings = [{id: 1, name: 'PI:NAME:<NAME>END_PI'}, {id: 3, name: 'Cloudy'}, {id: 99, name: 'Tall'}] params = items_per_page: 99 results = listings: new Listings(rawListings, params: params) fetchSummary = listings: { collection: 'listings', ids: _.pluck(rawListings, 'id'), params: params } fetcher.storeResults results hydrated = fetcher.hydrate fetchSummary listings = hydrated.listings listings.should.be.an.instanceOf Listings listings.toJSON().should.eql rawListings listings.params.should.eql params should.not.exist fetcher.collectionStore.get('Listings', {}) fetcher.collectionStore.get('Listings', params).should.eql ids: listings.pluck('id') meta: {} it "should be able to hydrate multiple objects at once", -> rawListing = {id: 9, name: 'PI:NAME:<NAME>END_PI'} rawListings = [{id: 1, name: 'PI:NAME:<NAME>END_PI'}, {id: 3, name: 'Cloudy'}, {id: 99, name: 'Tall'}] results = listing: new Listing(rawListing) listings: new Listings(rawListings) fetchSummary = listing: { model: 'listing', id: 9 } listings: { collection: 'listings', ids: [1,3,99] } fetcher.storeResults results hydrated = fetcher.hydrate fetchSummary listing = hydrated.listing listing.should.be.an.instanceOf Listing should.deepEqual listing.toJSON(), rawListing listings = hydrated.listings listings.should.be.an.instanceOf Listings should.deepEqual listings.toJSON(), rawListings it "should inject the app instance", -> listing1 = new Listing(id: 1) fetcher.modelStore.set(listing1) summaries = model: id: 1 model: 'Listing' app = fake: 'app' results = fetcher.hydrate(summaries, app: app) model = results.model model.app.should.eql(app) describe 'fetch', -> beforeEach -> fetcher.modelStore.clear() fetcher.collectionStore.clear() fetcher.off(null, null) it "should be able to fetch a model", (done) -> fetchSpec = model: { model: 'Listing', params: { id: 1 } } fetcher.pendingFetches.should.eql 0 fetcher.fetch fetchSpec, (err, results) -> fetcher.pendingFetches.should.eql 0 return done(err) if err results.model.should.be.an.instanceOf(Listing) results.model.toJSON().should.eql(getModelResponse('full', 1)) done() fetcher.pendingFetches.should.eql 1 it "should be able to fetch a collection", (done) -> fetchSpec = collection: { collection: 'Listings' } fetcher.pendingFetches.should.eql 0 fetcher.fetch fetchSpec, (err, results) -> fetcher.pendingFetches.should.eql 0 return done(err) if err results.collection.should.be.an.instanceOf(Listings) results.collection.toJSON().should.eql(buildCollectionResponse()) done() fetcher.pendingFetches.should.eql 1 it "should be able to fetch both a model and a collection at the same time", (done) -> fetchSpec = model: { model: 'Listing', params: { id: 1 } } collection: { collection: 'Listings' } fetcher.pendingFetches.should.eql 0 fetcher.fetch fetchSpec, (err, results) -> fetcher.pendingFetches.should.eql 0 return done(err) if err results.model.should.be.an.instanceOf(Listing) results.model.toJSON().should.eql(getModelResponse('full', 1)) results.collection.should.be.an.instanceOf(Listings) results.collection.toJSON().should.eql(buildCollectionResponse()) done() fetcher.pendingFetches.should.eql 1 it "should be able to fetch models from cache with custom idAttribute", (done) -> class User extends BaseModel idAttribute: 'login' userAttrs = login: 'someperson' name: 'PI:NAME:<NAME>END_PI' someperson = new User(userAttrs) modelUtils.addClassMapping 'user', User fetcher.modelStore.set(someperson) fetchSpec = model: { model: 'user', params: { login: 'someperson' } } fetcher.fetch fetchSpec, {readFromCache: true}, (err, results) -> return done(err) if err results.model.should.be.an.instanceOf(User) results.model.toJSON().should.eql(userAttrs) done() it "should be able to re-fetch if already exists but is missing key", (done) -> # First, fetch the collection, which has smaller versions of the models. fetchSpec = collection: { collection: 'Listings' } fetcher.fetch fetchSpec, {writeToCache: true}, (err, results) -> return done(err) if err results.collection.toJSON().should.eql(buildCollectionResponse()) # Make sure that the basic version is stored in modelStore. fetcher.modelStore.get('Listing', 1).should.eql getModelResponse('basic', 1) # Then, fetch the single model, which should be cached. fetchSpec = model: { model: 'Listing', params: { id: 1 } } fetcher.fetch fetchSpec, {readFromCache: true}, (err, results) -> return done(err) if err results.model.toJSON().should.eql(getModelResponse('basic', 1)) # Finally, fetch the single model, but specifiy that certain key must be present. fetchSpec = model: { model: 'Listing', params: { id: 1 }, ensureKeys: ['city'] } fetcher.fetch fetchSpec, {readFromCache: true}, (err, results) -> return done(err) if err results.model.toJSON().should.eql(getModelResponse('full', 1)) done() it "should emit events", (done) -> startEmitted = false endEmitted = false fetcher.on 'fetch:start', (eventFetchSpec) -> startEmitted = true eventFetchSpec.should.eql fetchSpec fetcher.on 'fetch:end', (eventFetchSpec) -> endEmitted = true eventFetchSpec.should.eql fetchSpec fetchSpec = model: { model: 'Listing', params: { id: 1 } } fetcher.fetch fetchSpec, (err, results) -> startEmitted.should.be.true endEmitted.should.be.true done(err) if err results.model.should.be.an.instanceOf(Listing) results.model.toJSON().should.eql(getModelResponse('full', 1)) done() startEmitted.should.be.true endEmitted.should.be.false describe 'isMissingKeys', -> before -> @modelData = id: 1 name: 'PI:NAME:<NAME>END_PI' it "should be false if keys not passed in", -> fetcher.isMissingKeys(@modelData, undefined).should.be.false fetcher.isMissingKeys(@modelData, []).should.be.false it "should be false if keys passed in but are present", -> fetcher.isMissingKeys(@modelData, 'name').should.be.false fetcher.isMissingKeys(@modelData, ['name']).should.be.false fetcher.isMissingKeys(@modelData, ['id', 'name']).should.be.false it "should be true if keys passed in are not present", -> fetcher.isMissingKeys(@modelData, 'city').should.be.true fetcher.isMissingKeys(@modelData, ['city']).should.be.true fetcher.isMissingKeys(@modelData, ['id', 'city']).should.be.true describe 'summarize', -> it "should summarize a model", -> attrs = id: 1234 blahblah: 'boomtown' model = new Listing(attrs) summary = fetcher.summarize(model) summary.model.should.eql 'listing' summary.id.should.eql attrs.id it "should support custom idAttribute", -> attrs = login: 'joeschmo' blahblah: 'boomtown' class CustomListing extends Listing idAttribute: 'login' model = new CustomListing(attrs) summary = fetcher.summarize(model) summary.model.should.eql 'custom_listing' summary.id.should.eql attrs.login it "should summarize a collection", -> models = [{ id: 1 name: 'foo' }, { id: 2 name: 'bar' }] params = some: 'key' other: 'value' meta = the: 'one' foo: 'butt' collection = new Listings(models, {params, meta}) summary = fetcher.summarize(collection) summary.collection.should.eql 'listings' summary.ids.should.eql [1,2] summary.params.should.eql params summary.meta.should.eql meta describe 'checkFresh', -> describe 'didCheckFresh', -> beforeEach -> fetcher.checkedFreshTimestamps = {} @spec = model: 'foobutt' params: {} it "should store it properly", -> fetcher.didCheckFresh(@spec) key = fetcher.checkedFreshKey(@spec) fetcher.checkedFreshTimestamps[key].should.be.ok describe 'shouldCheckFresh', -> beforeEach -> fetcher.checkedFreshTimestamps = {} @spec = model: 'foobutt' params: {} it "should return true if timestamp doesn't exist", -> fetcher.shouldCheckFresh(@spec).should.be.true it "should return true if timestamp exists and is greater than 'checkedFreshRate' ago", -> key = fetcher.checkedFreshKey(@spec) now = new Date().getTime() fetcher.checkedFreshTimestamps[key] = now - fetcher.checkedFreshRate - 1000 fetcher.shouldCheckFresh(@spec).should.be.true it "should return false if timestamp exists and is less than 'checkedFreshRate' ago", -> key = fetcher.checkedFreshKey(@spec) now = new Date().getTime() fetcher.checkedFreshTimestamps[key] = now - 1 fetcher.shouldCheckFresh(@spec).should.be.false
[ { "context": "\"无损压缩\"\n\n\t# 存储位置\n\tformData.current_location = \"\\\\\\\\192.168.0.151\\\\beta\\\\data\\\\oafile\"\n\t\n\t# 机构人员类型\n\tformData.agent_", "end": 2405, "score": 0.9997069835662842, "start": 2392, "tag": "IP_ADDRESS", "value": "192.168.0.151" }, { "context": "nstance?....
packages/steedos-qhd-archive-sync/server/lib/instances_to_archive.coffee
zonglu233/fuel-car
0
request = Npm.require('request') path = Npm.require('path') fs = Npm.require('fs') logger = new Logger 'Records_QHD -> InstancesToArchive' setFileName = (record_id, file_prefix) -> file_name = "未命名" collection = Creator.Collections["cms_files"] count = collection.find({"parent.ids": record_id}).count() count = count + 1 strcount = "00" + count count_code = strcount.substr(strcount.length-2) file_name = file_prefix + "-" + count_code return file_name # 校验必填 _checkParameter = (formData) -> if !formData.fonds_name return false return true # 整理档案表数据 _minxiInstanceData = (formData, instance) -> if !instance return dateFormat = "YYYY-MM-DD HH:mm:ss" formData.space = instance.space formData.owner = instance.submitter formData.created_by = instance.created_by formData.created = new Date() # 字段映射:表单字段对应到formData field_values = InstanceManager.handlerInstanceByFieldMap(instance) formData.applicant_name = field_values?.nigaorens formData.archive_dept = field_values?.guidangbumen formData.applicant_organization_name = field_values?.nigaodanwei || field_values?.FILE_CODE_fzr formData.security_classification = field_values?.miji formData.document_type = field_values?.wenjianleixing formData.document_date = field_values?.wenjianriqi formData.document_number = field_values?.wenjianzihao formData.author = field_values?.FILE_CODE_fzr formData.title = instance.name formData.prinpipal_receiver = field_values?.zhusong formData.year = field_values?.suoshuniandu # 设置页数 if field_values?.PAGE_COUNT old_page = field_values?.PAGE_COUNT.toString() || "00" # console.log "old_page: ",old_page; # console.log "instance._id: ",instance._id; str_page_count = old_page.substr(0,old_page.length-1); if str_page_count formData.total_number_of_pages = parseInt(str_page_count) + 1 else formData.total_number_of_pages = "1" # 默认值 formData.fonds_constituting_unit_name = "河北港口集团有限公司" formData.archival_category_code = "WS" formData.aggregation_level = "文件" formData.document_aggregation = "单件" formData.language = "汉语" formData.orignal_document_creation_way = "原生" formData.document_status = "电子归档" # 数字化属性 formData.physical_record_characteristics = "PDF" formData.scanning_resolution = "220dpi" formData.scanning_color_model = "彩色" formData.image_compression_scheme = "无损压缩" # 存储位置 formData.current_location = "\\\\192.168.0.151\\beta\\data\\oafile" # 机构人员类型 formData.agent_type = "部门" # 机构:FILING_DEPT字段(发文是拟稿单位,收文是所属部门) if field_values?.FILING_DEPT orgObj = Creator.Collections["archive_organization"].findOne({'name':field_values?.FILING_DEPT}) if orgObj formData.organizational_structure = orgObj._id formData.organizational_structure_code = orgObj.code # 根据FONDSID查找全宗号和全总名称 fondObj = Creator.Collections["archive_fonds"].findOne({'name':field_values?.FONDSID}) if fondObj formData.fonds_name = fondObj?._id formData.company = fondObj?.company formData.fonds_code = fondObj?.code # 保管期限代码查找 retentionObj = Creator.Collections["archive_retention"].findOne({'name':field_values?.baocunqixian}) if retentionObj formData.retention_peroid = retentionObj?._id formData.retention_peroid_code = retentionObj?.code # 根据保管期限,处理标志 if retentionObj?.years >= 10 formData.produce_flag = "在档" else formData.produce_flag = "暂存" # 归档日期 formData.archive_date = moment(new Date()).format(dateFormat) # OA表单的ID,作为判断OA归档的标志 formData.external_id = instance._id fieldNames = _.keys(formData) fieldNames.forEach (key)-> fieldValue = formData[key] if _.isDate(fieldValue) fieldValue = moment(fieldValue).format(dateFormat) if _.isObject(fieldValue) fieldValue = fieldValue?.name if _.isArray(fieldValue) && fieldValue.length > 0 && _.isObject(fieldValue) fieldValue = fieldValue?.getProperty("name")?.join(",") if _.isArray(fieldValue) fieldValue = fieldValue?.join(",") if !fieldValue fieldValue = '' return formData # 整理关联档案 _minxiRelatedArchives = (instance, record_id) -> # 当前归档的文件有关联的文件 if instance?.related_instances related_archives = [] instance.related_instances.forEach (related_instance) -> relatedObj = Creator.Collections["archive_wenshu"].findOne({'external_id':related_instance},{fields:{_id:1}}) if relatedObj related_archives.push relatedObj?._id Creator.Collections["archive_wenshu"].update( {_id:record_id}, { $set:{ related_archives:related_archives } }) # 查找当前 instance 是否被其他的 主instance 关联 mainRelatedObjs = Creator.Collections["instances"].find( {'related_instances':instance._id}, {fields: {_id: 1}}).fetch() # 如果被其他的主instance关联该文件,则更新主instance的related_archives字段 if mainRelatedObjs.length > 0 mainRelatedObjs.forEach (mainRelatedObj) -> # 查找该主 instance对应的主关联档案 mainRelatedObj = Creator.Collections["archive_wenshu"].findOne({'external_id':mainRelatedObj._id}) if mainRelatedObj related_archives = mainRelatedObj?.related_archives || [] related_archives.push record_id Creator.Collections["archive_wenshu"].update( {_id:mainRelatedObj._id}, { $set:{ related_archives:related_archives } }) # 整理文件数据 _minxiAttachmentInfo = (instance, record_id, file_prefix) -> # 对象名 object_name = RecordsQHD?.settings_records_qhd?.to_archive?.object_name parents = [] spaceId = instance?.space # 查找最新版本的文件(包括正文附件) currentFiles = cfs.instances.find({ 'metadata.instance': instance._id, 'metadata.current': true }).fetch() collection = Creator.Collections["cms_files"] currentFiles.forEach (cf, index)-> try instance_file_path = RecordsQHD?.settings_records_qhd?.instance_file_path versions = [] # 根据当前的文件,生成一个cms_files记录 cmsFileId = collection._makeNewID() file_name = setFileName(record_id, file_prefix) + "." + cf.extension() collection.insert({ _id: cmsFileId, versions: [], created_by: cf.metadata.owner, size: cf.size(), owner: cf?.metadata?.owner, modified: cf?.metadata?.modified, main: cf?.metadata?.main, parent: { o: object_name, ids: [record_id] }, modified_by: cf?.metadata?.modified_by, created: cf?.metadata?.created, name: file_name, space: spaceId, extention: cf.extension() }) # 查找每个文件的历史版本 historyFiles = cfs.instances.find({ 'metadata.instance': cf.metadata.instance, 'metadata.current': {$ne: true}, "metadata.parent": cf.metadata.parent }, {sort: {uploadedAt: -1}}).fetch() # 把当前文件放在历史版本文件的最后 historyFiles.push(cf) # 历史版本文件+当前文件 上传到creator historyFiles.forEach (hf) -> instance_file_key = path.join(instance_file_path, hf?.copies?.instances?.key) if fs.existsSync(instance_file_key) # console.log "createReadStream: ",hf?.copies?.instances?.key newFile = new FS.File() newFile.attachData( fs.createReadStream(instance_file_key), {type: hf.original.type}, (err)-> if err throw new Meteor.Error(err.error, err.reason) newFile.name hf.name() newFile.size hf.size() metadata = { owner: hf.metadata.owner, owner_name: hf.metadata?.owner_name, space: spaceId, record_id: record_id, object_name: object_name, parent: cmsFileId, current: hf.metadata?.current, main: hf.metadata?.main } newFile.metadata = metadata fileObj = cfs.files.insert(newFile) if fileObj versions.push(fileObj._id) ) # 把 cms_files 记录的 versions 更新 collection.update(cmsFileId, {$set: {versions: versions}}) catch e logger.error "正文附件下载失败:#{cf._id}. error: " + e # 整理表单html _minxiInstanceHtml = (instance, record_id, file_prefix) -> admin = RecordsQHD?.settings_records_qhd?.to_archive?.admin apps_url = RecordsQHD?.settings_records_qhd?.to_archive?.apps_url space_id = instance?.space ins_id = instance?._id user_id = admin?.userid username = admin?.username password = admin?.password instance_html_url = apps_url + '/workflow/space/' + space_id + '/view/readonly/' + ins_id + '?username=' + username + '&password=' + password + '&hide_traces=1' # console.log "instance_html_url",instance_html_url result_html = HTTP.call('GET',instance_html_url)?.content if result_html try object_name = RecordsQHD?.settings_records_qhd?.to_archive?.object_name collection = Creator.Collections["cms_files"] cmsFileId = collection._makeNewID() date_now = new Date() data_buffer = new Buffer(result_html.toString()) file_name = setFileName(record_id, file_prefix) + '.html' file_size = data_buffer?.length collection.insert({ _id: cmsFileId, versions: [], size: file_size, owner: user_id, instance_html: true, parent: { o: object_name, ids: [record_id] }, modified: date_now, modified_by: user_id, created: date_now, created_by: user_id, name: file_name, space: space_id, extention: 'html' }, (error,result)-> if error throw new Meteor.Error(error) ) newFile = new FS.File() newFile.attachData( data_buffer, {type: 'text/html'}, (err)-> if err throw new Meteor.Error(err.error, err.reason) newFile.name file_name newFile.size file_size metadata = { owner: user_id, owner_name: "系统生成", space: space_id, record_id: record_id, object_name: object_name, parent: cmsFileId, instance_html: true } newFile.metadata = metadata fileObj = cfs.files.insert(newFile) if fileObj versions = [] versions.push fileObj?._id collection.update(cmsFileId, {$set: {versions: versions}}) ) catch e logger.error "存储HTML失败:#{ins_id}. error: " + e else logger.error "表单生成HTML失败:#{ins_id}. error: " + e # 整理档案审计数据 _minxiInstanceTraces = (auditList, instance, record_id) -> collection = Creator.Collections["archive_audit"] # 获取步骤状态文本 getApproveStatusText = (approveJudge) -> locale = "zh-CN" #已结束的显示为核准/驳回/取消申请,并显示处理状态图标 approveStatusText = undefined switch approveJudge when 'approved' # 已核准 approveStatusText = "已核准" when 'rejected' # 已驳回 approveStatusText = "已驳回" when 'terminated' # 已取消 approveStatusText = "已取消" when 'reassigned' # 转签核 approveStatusText = "转签核" when 'relocated' # 重定位 approveStatusText = "重定位" when 'retrieved' # 已取回 approveStatusText = "已取回" when 'returned' # 已退回 approveStatusText = "已退回" when 'readed' # 已阅 approveStatusText = "已阅" else approveStatusText = '' break return approveStatusText traces = instance?.traces traces.forEach (trace)-> approves = trace?.approves || [] approves.forEach (approve)-> auditObj = {} auditObj.business_status = "计划任务" auditObj.business_activity = trace?.name auditObj.action_time = approve?.start_date auditObj.action_user = approve?.user auditObj.action_description = getApproveStatusText approve?.judge auditObj.action_administrative_records_id = record_id auditObj.instace_id = instance._id auditObj.space = instance.space auditObj.owner = approve?.user collection.direct.insert auditObj autoAudit = { business_status: "计划任务", business_activity: "自动归档", action_time: new Date, action_user: "OA", action_description: "", action_administrative_records_id: record_id, instace_id: instance._id, space: instance.space, owner: "" } collection.direct.insert autoAudit return # ============================================= # spaces: Array 工作区ID # contract_flows: Array 合同类流程 InstancesToArchive = (spaces, contract_flows, ins_ids) -> @spaces = spaces @contract_flows = contract_flows @ins_ids = ins_ids return InstancesToArchive.success = (instance)-> Creator.Collections["instances"].update({_id: instance._id}, {$set: {is_recorded: true}}) InstancesToArchive.failed = (instance, error)-> logger.error "failed, name is #{instance.name}, id is #{instance._id}. error: ", error # 获取非合同类的申请单:正常结束的(不包括取消申请、被驳回的申请单) InstancesToArchive::getNonContractInstances = ()-> query = { space: {$in: @spaces}, flow: {$nin: @contract_flows}, # is_archived 字段被老归档接口占用,所以使用 is_recorded 字段判断是否归档 # 正常情况下,未归档的表单无 is_recorded 字段 $or: [ {is_recorded: false}, {is_recorded: {$exists: false}} ], is_deleted: false, state: "completed", "values.record_need": "true" # 重定位到结束的表单该值为 terminated,故取消此判断 # $or: [ # {final_decision: "approved"}, # {final_decision: {$exists: false}}, # {final_decision: ""} # ] } if @ins_ids query._id = {$in: @ins_ids} return Creator.Collections["instances"].find(query, {fields: {_id: 1}}).fetch() InstancesToArchive.syncNonContractInstance = (instance, callback) -> # 表单数据 formData = {} # 审计记录 auditList = [] _minxiInstanceData(formData, instance) # console.log "formData", formData if _checkParameter(formData) logger.debug("_sendContractInstance: #{instance._id}") try file_prefix = formData?.fonds_code + "-" + formData?.archival_category_code + "·" + formData?.year + "-" + formData?.retention_peroid_code + "-" + formData?.organizational_structure_code # 如果原来已经归档,则删除原来归档的记录 collection = Creator.Collections["archive_wenshu"] collection.remove({'external_id':instance._id}) # console.log "插入档案" record_id = collection.insert formData # 整理表单html # console.log "整理表单html" # console.log "file_prefix",file_prefix _minxiInstanceHtml(instance, record_id, file_prefix) # 整理文件 # console.log "整理文件" _minxiAttachmentInfo(instance, record_id, file_prefix) # 整理关联档案 _minxiRelatedArchives(instance, record_id) # 处理审计记录 _minxiInstanceTraces(auditList, instance, record_id) InstancesToArchive.success instance catch e logger.error e console.log "#{instance._id}表单归档失败,", e else InstancesToArchive.failed instance, "立档单位未找到" @Test = {} # Test.run('iTRRqEfHYGhDeWwaC') Test.run = (ins_id)-> instance = Creator.Collections["instances"].findOne({_id: ins_id}) if instance InstancesToArchive.syncNonContractInstance instance InstancesToArchive::syncNonContractInstances = () -> console.time("syncNonContractInstances") instances = @getNonContractInstances() that = @ instances.forEach (mini_ins)-> instance = Creator.Collections["instances"].findOne({_id: mini_ins._id}) if instance try InstancesToArchive.syncNonContractInstance instance catch e logger.error e console.log e console.timeEnd("syncNonContractInstances")
211664
request = Npm.require('request') path = Npm.require('path') fs = Npm.require('fs') logger = new Logger 'Records_QHD -> InstancesToArchive' setFileName = (record_id, file_prefix) -> file_name = "未命名" collection = Creator.Collections["cms_files"] count = collection.find({"parent.ids": record_id}).count() count = count + 1 strcount = "00" + count count_code = strcount.substr(strcount.length-2) file_name = file_prefix + "-" + count_code return file_name # 校验必填 _checkParameter = (formData) -> if !formData.fonds_name return false return true # 整理档案表数据 _minxiInstanceData = (formData, instance) -> if !instance return dateFormat = "YYYY-MM-DD HH:mm:ss" formData.space = instance.space formData.owner = instance.submitter formData.created_by = instance.created_by formData.created = new Date() # 字段映射:表单字段对应到formData field_values = InstanceManager.handlerInstanceByFieldMap(instance) formData.applicant_name = field_values?.nigaorens formData.archive_dept = field_values?.guidangbumen formData.applicant_organization_name = field_values?.nigaodanwei || field_values?.FILE_CODE_fzr formData.security_classification = field_values?.miji formData.document_type = field_values?.wenjianleixing formData.document_date = field_values?.wenjianriqi formData.document_number = field_values?.wenjianzihao formData.author = field_values?.FILE_CODE_fzr formData.title = instance.name formData.prinpipal_receiver = field_values?.zhusong formData.year = field_values?.suoshuniandu # 设置页数 if field_values?.PAGE_COUNT old_page = field_values?.PAGE_COUNT.toString() || "00" # console.log "old_page: ",old_page; # console.log "instance._id: ",instance._id; str_page_count = old_page.substr(0,old_page.length-1); if str_page_count formData.total_number_of_pages = parseInt(str_page_count) + 1 else formData.total_number_of_pages = "1" # 默认值 formData.fonds_constituting_unit_name = "河北港口集团有限公司" formData.archival_category_code = "WS" formData.aggregation_level = "文件" formData.document_aggregation = "单件" formData.language = "汉语" formData.orignal_document_creation_way = "原生" formData.document_status = "电子归档" # 数字化属性 formData.physical_record_characteristics = "PDF" formData.scanning_resolution = "220dpi" formData.scanning_color_model = "彩色" formData.image_compression_scheme = "无损压缩" # 存储位置 formData.current_location = "\\\\192.168.0.151\\beta\\data\\oafile" # 机构人员类型 formData.agent_type = "部门" # 机构:FILING_DEPT字段(发文是拟稿单位,收文是所属部门) if field_values?.FILING_DEPT orgObj = Creator.Collections["archive_organization"].findOne({'name':field_values?.FILING_DEPT}) if orgObj formData.organizational_structure = orgObj._id formData.organizational_structure_code = orgObj.code # 根据FONDSID查找全宗号和全总名称 fondObj = Creator.Collections["archive_fonds"].findOne({'name':field_values?.FONDSID}) if fondObj formData.fonds_name = fondObj?._id formData.company = fondObj?.company formData.fonds_code = fondObj?.code # 保管期限代码查找 retentionObj = Creator.Collections["archive_retention"].findOne({'name':field_values?.baocunqixian}) if retentionObj formData.retention_peroid = retentionObj?._id formData.retention_peroid_code = retentionObj?.code # 根据保管期限,处理标志 if retentionObj?.years >= 10 formData.produce_flag = "在档" else formData.produce_flag = "暂存" # 归档日期 formData.archive_date = moment(new Date()).format(dateFormat) # OA表单的ID,作为判断OA归档的标志 formData.external_id = instance._id fieldNames = _.keys(formData) fieldNames.forEach (key)-> fieldValue = formData[key] if _.isDate(fieldValue) fieldValue = moment(fieldValue).format(dateFormat) if _.isObject(fieldValue) fieldValue = fieldValue?.name if _.isArray(fieldValue) && fieldValue.length > 0 && _.isObject(fieldValue) fieldValue = fieldValue?.getProperty("name")?.join(",") if _.isArray(fieldValue) fieldValue = fieldValue?.join(",") if !fieldValue fieldValue = '' return formData # 整理关联档案 _minxiRelatedArchives = (instance, record_id) -> # 当前归档的文件有关联的文件 if instance?.related_instances related_archives = [] instance.related_instances.forEach (related_instance) -> relatedObj = Creator.Collections["archive_wenshu"].findOne({'external_id':related_instance},{fields:{_id:1}}) if relatedObj related_archives.push relatedObj?._id Creator.Collections["archive_wenshu"].update( {_id:record_id}, { $set:{ related_archives:related_archives } }) # 查找当前 instance 是否被其他的 主instance 关联 mainRelatedObjs = Creator.Collections["instances"].find( {'related_instances':instance._id}, {fields: {_id: 1}}).fetch() # 如果被其他的主instance关联该文件,则更新主instance的related_archives字段 if mainRelatedObjs.length > 0 mainRelatedObjs.forEach (mainRelatedObj) -> # 查找该主 instance对应的主关联档案 mainRelatedObj = Creator.Collections["archive_wenshu"].findOne({'external_id':mainRelatedObj._id}) if mainRelatedObj related_archives = mainRelatedObj?.related_archives || [] related_archives.push record_id Creator.Collections["archive_wenshu"].update( {_id:mainRelatedObj._id}, { $set:{ related_archives:related_archives } }) # 整理文件数据 _minxiAttachmentInfo = (instance, record_id, file_prefix) -> # 对象名 object_name = RecordsQHD?.settings_records_qhd?.to_archive?.object_name parents = [] spaceId = instance?.space # 查找最新版本的文件(包括正文附件) currentFiles = cfs.instances.find({ 'metadata.instance': instance._id, 'metadata.current': true }).fetch() collection = Creator.Collections["cms_files"] currentFiles.forEach (cf, index)-> try instance_file_path = RecordsQHD?.settings_records_qhd?.instance_file_path versions = [] # 根据当前的文件,生成一个cms_files记录 cmsFileId = collection._makeNewID() file_name = setFileName(record_id, file_prefix) + "." + cf.extension() collection.insert({ _id: cmsFileId, versions: [], created_by: cf.metadata.owner, size: cf.size(), owner: cf?.metadata?.owner, modified: cf?.metadata?.modified, main: cf?.metadata?.main, parent: { o: object_name, ids: [record_id] }, modified_by: cf?.metadata?.modified_by, created: cf?.metadata?.created, name: file_name, space: spaceId, extention: cf.extension() }) # 查找每个文件的历史版本 historyFiles = cfs.instances.find({ 'metadata.instance': cf.metadata.instance, 'metadata.current': {$ne: true}, "metadata.parent": cf.metadata.parent }, {sort: {uploadedAt: -1}}).fetch() # 把当前文件放在历史版本文件的最后 historyFiles.push(cf) # 历史版本文件+当前文件 上传到creator historyFiles.forEach (hf) -> instance_file_key = path.join(instance_file_path, hf?.copies?.instances?.key) if fs.existsSync(instance_file_key) # console.log "createReadStream: ",hf?.copies?.instances?.key newFile = new FS.File() newFile.attachData( fs.createReadStream(instance_file_key), {type: hf.original.type}, (err)-> if err throw new Meteor.Error(err.error, err.reason) newFile.name hf.name() newFile.size hf.size() metadata = { owner: hf.metadata.owner, owner_name: hf.metadata?.owner_name, space: spaceId, record_id: record_id, object_name: object_name, parent: cmsFileId, current: hf.metadata?.current, main: hf.metadata?.main } newFile.metadata = metadata fileObj = cfs.files.insert(newFile) if fileObj versions.push(fileObj._id) ) # 把 cms_files 记录的 versions 更新 collection.update(cmsFileId, {$set: {versions: versions}}) catch e logger.error "正文附件下载失败:#{cf._id}. error: " + e # 整理表单html _minxiInstanceHtml = (instance, record_id, file_prefix) -> admin = RecordsQHD?.settings_records_qhd?.to_archive?.admin apps_url = RecordsQHD?.settings_records_qhd?.to_archive?.apps_url space_id = instance?.space ins_id = instance?._id user_id = admin?.userid username = admin?.username password = <PASSWORD> instance_html_url = apps_url + '/workflow/space/' + space_id + '/view/readonly/' + ins_id + '?username=' + username + '&password=' + <PASSWORD> + '&hide_traces=1' # console.log "instance_html_url",instance_html_url result_html = HTTP.call('GET',instance_html_url)?.content if result_html try object_name = RecordsQHD?.settings_records_qhd?.to_archive?.object_name collection = Creator.Collections["cms_files"] cmsFileId = collection._makeNewID() date_now = new Date() data_buffer = new Buffer(result_html.toString()) file_name = setFileName(record_id, file_prefix) + '.html' file_size = data_buffer?.length collection.insert({ _id: cmsFileId, versions: [], size: file_size, owner: user_id, instance_html: true, parent: { o: object_name, ids: [record_id] }, modified: date_now, modified_by: user_id, created: date_now, created_by: user_id, name: file_name, space: space_id, extention: 'html' }, (error,result)-> if error throw new Meteor.Error(error) ) newFile = new FS.File() newFile.attachData( data_buffer, {type: 'text/html'}, (err)-> if err throw new Meteor.Error(err.error, err.reason) newFile.name file_name newFile.size file_size metadata = { owner: user_id, owner_name: "系统生成", space: space_id, record_id: record_id, object_name: object_name, parent: cmsFileId, instance_html: true } newFile.metadata = metadata fileObj = cfs.files.insert(newFile) if fileObj versions = [] versions.push fileObj?._id collection.update(cmsFileId, {$set: {versions: versions}}) ) catch e logger.error "存储HTML失败:#{ins_id}. error: " + e else logger.error "表单生成HTML失败:#{ins_id}. error: " + e # 整理档案审计数据 _minxiInstanceTraces = (auditList, instance, record_id) -> collection = Creator.Collections["archive_audit"] # 获取步骤状态文本 getApproveStatusText = (approveJudge) -> locale = "zh-CN" #已结束的显示为核准/驳回/取消申请,并显示处理状态图标 approveStatusText = undefined switch approveJudge when 'approved' # 已核准 approveStatusText = "已核准" when 'rejected' # 已驳回 approveStatusText = "已驳回" when 'terminated' # 已取消 approveStatusText = "已取消" when 'reassigned' # 转签核 approveStatusText = "转签核" when 'relocated' # 重定位 approveStatusText = "重定位" when 'retrieved' # 已取回 approveStatusText = "已取回" when 'returned' # 已退回 approveStatusText = "已退回" when 'readed' # 已阅 approveStatusText = "已阅" else approveStatusText = '' break return approveStatusText traces = instance?.traces traces.forEach (trace)-> approves = trace?.approves || [] approves.forEach (approve)-> auditObj = {} auditObj.business_status = "计划任务" auditObj.business_activity = trace?.name auditObj.action_time = approve?.start_date auditObj.action_user = approve?.user auditObj.action_description = getApproveStatusText approve?.judge auditObj.action_administrative_records_id = record_id auditObj.instace_id = instance._id auditObj.space = instance.space auditObj.owner = approve?.user collection.direct.insert auditObj autoAudit = { business_status: "计划任务", business_activity: "自动归档", action_time: new Date, action_user: "OA", action_description: "", action_administrative_records_id: record_id, instace_id: instance._id, space: instance.space, owner: "" } collection.direct.insert autoAudit return # ============================================= # spaces: Array 工作区ID # contract_flows: Array 合同类流程 InstancesToArchive = (spaces, contract_flows, ins_ids) -> @spaces = spaces @contract_flows = contract_flows @ins_ids = ins_ids return InstancesToArchive.success = (instance)-> Creator.Collections["instances"].update({_id: instance._id}, {$set: {is_recorded: true}}) InstancesToArchive.failed = (instance, error)-> logger.error "failed, name is #{instance.name}, id is #{instance._id}. error: ", error # 获取非合同类的申请单:正常结束的(不包括取消申请、被驳回的申请单) InstancesToArchive::getNonContractInstances = ()-> query = { space: {$in: @spaces}, flow: {$nin: @contract_flows}, # is_archived 字段被老归档接口占用,所以使用 is_recorded 字段判断是否归档 # 正常情况下,未归档的表单无 is_recorded 字段 $or: [ {is_recorded: false}, {is_recorded: {$exists: false}} ], is_deleted: false, state: "completed", "values.record_need": "true" # 重定位到结束的表单该值为 terminated,故取消此判断 # $or: [ # {final_decision: "approved"}, # {final_decision: {$exists: false}}, # {final_decision: ""} # ] } if @ins_ids query._id = {$in: @ins_ids} return Creator.Collections["instances"].find(query, {fields: {_id: 1}}).fetch() InstancesToArchive.syncNonContractInstance = (instance, callback) -> # 表单数据 formData = {} # 审计记录 auditList = [] _minxiInstanceData(formData, instance) # console.log "formData", formData if _checkParameter(formData) logger.debug("_sendContractInstance: #{instance._id}") try file_prefix = formData?.fonds_code + "-" + formData?.archival_category_code + "·" + formData?.year + "-" + formData?.retention_peroid_code + "-" + formData?.organizational_structure_code # 如果原来已经归档,则删除原来归档的记录 collection = Creator.Collections["archive_wenshu"] collection.remove({'external_id':instance._id}) # console.log "插入档案" record_id = collection.insert formData # 整理表单html # console.log "整理表单html" # console.log "file_prefix",file_prefix _minxiInstanceHtml(instance, record_id, file_prefix) # 整理文件 # console.log "整理文件" _minxiAttachmentInfo(instance, record_id, file_prefix) # 整理关联档案 _minxiRelatedArchives(instance, record_id) # 处理审计记录 _minxiInstanceTraces(auditList, instance, record_id) InstancesToArchive.success instance catch e logger.error e console.log "#{instance._id}表单归档失败,", e else InstancesToArchive.failed instance, "立档单位未找到" @Test = {} # Test.run('iTRRqEfHYGhDeWwaC') Test.run = (ins_id)-> instance = Creator.Collections["instances"].findOne({_id: ins_id}) if instance InstancesToArchive.syncNonContractInstance instance InstancesToArchive::syncNonContractInstances = () -> console.time("syncNonContractInstances") instances = @getNonContractInstances() that = @ instances.forEach (mini_ins)-> instance = Creator.Collections["instances"].findOne({_id: mini_ins._id}) if instance try InstancesToArchive.syncNonContractInstance instance catch e logger.error e console.log e console.timeEnd("syncNonContractInstances")
true
request = Npm.require('request') path = Npm.require('path') fs = Npm.require('fs') logger = new Logger 'Records_QHD -> InstancesToArchive' setFileName = (record_id, file_prefix) -> file_name = "未命名" collection = Creator.Collections["cms_files"] count = collection.find({"parent.ids": record_id}).count() count = count + 1 strcount = "00" + count count_code = strcount.substr(strcount.length-2) file_name = file_prefix + "-" + count_code return file_name # 校验必填 _checkParameter = (formData) -> if !formData.fonds_name return false return true # 整理档案表数据 _minxiInstanceData = (formData, instance) -> if !instance return dateFormat = "YYYY-MM-DD HH:mm:ss" formData.space = instance.space formData.owner = instance.submitter formData.created_by = instance.created_by formData.created = new Date() # 字段映射:表单字段对应到formData field_values = InstanceManager.handlerInstanceByFieldMap(instance) formData.applicant_name = field_values?.nigaorens formData.archive_dept = field_values?.guidangbumen formData.applicant_organization_name = field_values?.nigaodanwei || field_values?.FILE_CODE_fzr formData.security_classification = field_values?.miji formData.document_type = field_values?.wenjianleixing formData.document_date = field_values?.wenjianriqi formData.document_number = field_values?.wenjianzihao formData.author = field_values?.FILE_CODE_fzr formData.title = instance.name formData.prinpipal_receiver = field_values?.zhusong formData.year = field_values?.suoshuniandu # 设置页数 if field_values?.PAGE_COUNT old_page = field_values?.PAGE_COUNT.toString() || "00" # console.log "old_page: ",old_page; # console.log "instance._id: ",instance._id; str_page_count = old_page.substr(0,old_page.length-1); if str_page_count formData.total_number_of_pages = parseInt(str_page_count) + 1 else formData.total_number_of_pages = "1" # 默认值 formData.fonds_constituting_unit_name = "河北港口集团有限公司" formData.archival_category_code = "WS" formData.aggregation_level = "文件" formData.document_aggregation = "单件" formData.language = "汉语" formData.orignal_document_creation_way = "原生" formData.document_status = "电子归档" # 数字化属性 formData.physical_record_characteristics = "PDF" formData.scanning_resolution = "220dpi" formData.scanning_color_model = "彩色" formData.image_compression_scheme = "无损压缩" # 存储位置 formData.current_location = "\\\\192.168.0.151\\beta\\data\\oafile" # 机构人员类型 formData.agent_type = "部门" # 机构:FILING_DEPT字段(发文是拟稿单位,收文是所属部门) if field_values?.FILING_DEPT orgObj = Creator.Collections["archive_organization"].findOne({'name':field_values?.FILING_DEPT}) if orgObj formData.organizational_structure = orgObj._id formData.organizational_structure_code = orgObj.code # 根据FONDSID查找全宗号和全总名称 fondObj = Creator.Collections["archive_fonds"].findOne({'name':field_values?.FONDSID}) if fondObj formData.fonds_name = fondObj?._id formData.company = fondObj?.company formData.fonds_code = fondObj?.code # 保管期限代码查找 retentionObj = Creator.Collections["archive_retention"].findOne({'name':field_values?.baocunqixian}) if retentionObj formData.retention_peroid = retentionObj?._id formData.retention_peroid_code = retentionObj?.code # 根据保管期限,处理标志 if retentionObj?.years >= 10 formData.produce_flag = "在档" else formData.produce_flag = "暂存" # 归档日期 formData.archive_date = moment(new Date()).format(dateFormat) # OA表单的ID,作为判断OA归档的标志 formData.external_id = instance._id fieldNames = _.keys(formData) fieldNames.forEach (key)-> fieldValue = formData[key] if _.isDate(fieldValue) fieldValue = moment(fieldValue).format(dateFormat) if _.isObject(fieldValue) fieldValue = fieldValue?.name if _.isArray(fieldValue) && fieldValue.length > 0 && _.isObject(fieldValue) fieldValue = fieldValue?.getProperty("name")?.join(",") if _.isArray(fieldValue) fieldValue = fieldValue?.join(",") if !fieldValue fieldValue = '' return formData # 整理关联档案 _minxiRelatedArchives = (instance, record_id) -> # 当前归档的文件有关联的文件 if instance?.related_instances related_archives = [] instance.related_instances.forEach (related_instance) -> relatedObj = Creator.Collections["archive_wenshu"].findOne({'external_id':related_instance},{fields:{_id:1}}) if relatedObj related_archives.push relatedObj?._id Creator.Collections["archive_wenshu"].update( {_id:record_id}, { $set:{ related_archives:related_archives } }) # 查找当前 instance 是否被其他的 主instance 关联 mainRelatedObjs = Creator.Collections["instances"].find( {'related_instances':instance._id}, {fields: {_id: 1}}).fetch() # 如果被其他的主instance关联该文件,则更新主instance的related_archives字段 if mainRelatedObjs.length > 0 mainRelatedObjs.forEach (mainRelatedObj) -> # 查找该主 instance对应的主关联档案 mainRelatedObj = Creator.Collections["archive_wenshu"].findOne({'external_id':mainRelatedObj._id}) if mainRelatedObj related_archives = mainRelatedObj?.related_archives || [] related_archives.push record_id Creator.Collections["archive_wenshu"].update( {_id:mainRelatedObj._id}, { $set:{ related_archives:related_archives } }) # 整理文件数据 _minxiAttachmentInfo = (instance, record_id, file_prefix) -> # 对象名 object_name = RecordsQHD?.settings_records_qhd?.to_archive?.object_name parents = [] spaceId = instance?.space # 查找最新版本的文件(包括正文附件) currentFiles = cfs.instances.find({ 'metadata.instance': instance._id, 'metadata.current': true }).fetch() collection = Creator.Collections["cms_files"] currentFiles.forEach (cf, index)-> try instance_file_path = RecordsQHD?.settings_records_qhd?.instance_file_path versions = [] # 根据当前的文件,生成一个cms_files记录 cmsFileId = collection._makeNewID() file_name = setFileName(record_id, file_prefix) + "." + cf.extension() collection.insert({ _id: cmsFileId, versions: [], created_by: cf.metadata.owner, size: cf.size(), owner: cf?.metadata?.owner, modified: cf?.metadata?.modified, main: cf?.metadata?.main, parent: { o: object_name, ids: [record_id] }, modified_by: cf?.metadata?.modified_by, created: cf?.metadata?.created, name: file_name, space: spaceId, extention: cf.extension() }) # 查找每个文件的历史版本 historyFiles = cfs.instances.find({ 'metadata.instance': cf.metadata.instance, 'metadata.current': {$ne: true}, "metadata.parent": cf.metadata.parent }, {sort: {uploadedAt: -1}}).fetch() # 把当前文件放在历史版本文件的最后 historyFiles.push(cf) # 历史版本文件+当前文件 上传到creator historyFiles.forEach (hf) -> instance_file_key = path.join(instance_file_path, hf?.copies?.instances?.key) if fs.existsSync(instance_file_key) # console.log "createReadStream: ",hf?.copies?.instances?.key newFile = new FS.File() newFile.attachData( fs.createReadStream(instance_file_key), {type: hf.original.type}, (err)-> if err throw new Meteor.Error(err.error, err.reason) newFile.name hf.name() newFile.size hf.size() metadata = { owner: hf.metadata.owner, owner_name: hf.metadata?.owner_name, space: spaceId, record_id: record_id, object_name: object_name, parent: cmsFileId, current: hf.metadata?.current, main: hf.metadata?.main } newFile.metadata = metadata fileObj = cfs.files.insert(newFile) if fileObj versions.push(fileObj._id) ) # 把 cms_files 记录的 versions 更新 collection.update(cmsFileId, {$set: {versions: versions}}) catch e logger.error "正文附件下载失败:#{cf._id}. error: " + e # 整理表单html _minxiInstanceHtml = (instance, record_id, file_prefix) -> admin = RecordsQHD?.settings_records_qhd?.to_archive?.admin apps_url = RecordsQHD?.settings_records_qhd?.to_archive?.apps_url space_id = instance?.space ins_id = instance?._id user_id = admin?.userid username = admin?.username password = PI:PASSWORD:<PASSWORD>END_PI instance_html_url = apps_url + '/workflow/space/' + space_id + '/view/readonly/' + ins_id + '?username=' + username + '&password=' + PI:PASSWORD:<PASSWORD>END_PI + '&hide_traces=1' # console.log "instance_html_url",instance_html_url result_html = HTTP.call('GET',instance_html_url)?.content if result_html try object_name = RecordsQHD?.settings_records_qhd?.to_archive?.object_name collection = Creator.Collections["cms_files"] cmsFileId = collection._makeNewID() date_now = new Date() data_buffer = new Buffer(result_html.toString()) file_name = setFileName(record_id, file_prefix) + '.html' file_size = data_buffer?.length collection.insert({ _id: cmsFileId, versions: [], size: file_size, owner: user_id, instance_html: true, parent: { o: object_name, ids: [record_id] }, modified: date_now, modified_by: user_id, created: date_now, created_by: user_id, name: file_name, space: space_id, extention: 'html' }, (error,result)-> if error throw new Meteor.Error(error) ) newFile = new FS.File() newFile.attachData( data_buffer, {type: 'text/html'}, (err)-> if err throw new Meteor.Error(err.error, err.reason) newFile.name file_name newFile.size file_size metadata = { owner: user_id, owner_name: "系统生成", space: space_id, record_id: record_id, object_name: object_name, parent: cmsFileId, instance_html: true } newFile.metadata = metadata fileObj = cfs.files.insert(newFile) if fileObj versions = [] versions.push fileObj?._id collection.update(cmsFileId, {$set: {versions: versions}}) ) catch e logger.error "存储HTML失败:#{ins_id}. error: " + e else logger.error "表单生成HTML失败:#{ins_id}. error: " + e # 整理档案审计数据 _minxiInstanceTraces = (auditList, instance, record_id) -> collection = Creator.Collections["archive_audit"] # 获取步骤状态文本 getApproveStatusText = (approveJudge) -> locale = "zh-CN" #已结束的显示为核准/驳回/取消申请,并显示处理状态图标 approveStatusText = undefined switch approveJudge when 'approved' # 已核准 approveStatusText = "已核准" when 'rejected' # 已驳回 approveStatusText = "已驳回" when 'terminated' # 已取消 approveStatusText = "已取消" when 'reassigned' # 转签核 approveStatusText = "转签核" when 'relocated' # 重定位 approveStatusText = "重定位" when 'retrieved' # 已取回 approveStatusText = "已取回" when 'returned' # 已退回 approveStatusText = "已退回" when 'readed' # 已阅 approveStatusText = "已阅" else approveStatusText = '' break return approveStatusText traces = instance?.traces traces.forEach (trace)-> approves = trace?.approves || [] approves.forEach (approve)-> auditObj = {} auditObj.business_status = "计划任务" auditObj.business_activity = trace?.name auditObj.action_time = approve?.start_date auditObj.action_user = approve?.user auditObj.action_description = getApproveStatusText approve?.judge auditObj.action_administrative_records_id = record_id auditObj.instace_id = instance._id auditObj.space = instance.space auditObj.owner = approve?.user collection.direct.insert auditObj autoAudit = { business_status: "计划任务", business_activity: "自动归档", action_time: new Date, action_user: "OA", action_description: "", action_administrative_records_id: record_id, instace_id: instance._id, space: instance.space, owner: "" } collection.direct.insert autoAudit return # ============================================= # spaces: Array 工作区ID # contract_flows: Array 合同类流程 InstancesToArchive = (spaces, contract_flows, ins_ids) -> @spaces = spaces @contract_flows = contract_flows @ins_ids = ins_ids return InstancesToArchive.success = (instance)-> Creator.Collections["instances"].update({_id: instance._id}, {$set: {is_recorded: true}}) InstancesToArchive.failed = (instance, error)-> logger.error "failed, name is #{instance.name}, id is #{instance._id}. error: ", error # 获取非合同类的申请单:正常结束的(不包括取消申请、被驳回的申请单) InstancesToArchive::getNonContractInstances = ()-> query = { space: {$in: @spaces}, flow: {$nin: @contract_flows}, # is_archived 字段被老归档接口占用,所以使用 is_recorded 字段判断是否归档 # 正常情况下,未归档的表单无 is_recorded 字段 $or: [ {is_recorded: false}, {is_recorded: {$exists: false}} ], is_deleted: false, state: "completed", "values.record_need": "true" # 重定位到结束的表单该值为 terminated,故取消此判断 # $or: [ # {final_decision: "approved"}, # {final_decision: {$exists: false}}, # {final_decision: ""} # ] } if @ins_ids query._id = {$in: @ins_ids} return Creator.Collections["instances"].find(query, {fields: {_id: 1}}).fetch() InstancesToArchive.syncNonContractInstance = (instance, callback) -> # 表单数据 formData = {} # 审计记录 auditList = [] _minxiInstanceData(formData, instance) # console.log "formData", formData if _checkParameter(formData) logger.debug("_sendContractInstance: #{instance._id}") try file_prefix = formData?.fonds_code + "-" + formData?.archival_category_code + "·" + formData?.year + "-" + formData?.retention_peroid_code + "-" + formData?.organizational_structure_code # 如果原来已经归档,则删除原来归档的记录 collection = Creator.Collections["archive_wenshu"] collection.remove({'external_id':instance._id}) # console.log "插入档案" record_id = collection.insert formData # 整理表单html # console.log "整理表单html" # console.log "file_prefix",file_prefix _minxiInstanceHtml(instance, record_id, file_prefix) # 整理文件 # console.log "整理文件" _minxiAttachmentInfo(instance, record_id, file_prefix) # 整理关联档案 _minxiRelatedArchives(instance, record_id) # 处理审计记录 _minxiInstanceTraces(auditList, instance, record_id) InstancesToArchive.success instance catch e logger.error e console.log "#{instance._id}表单归档失败,", e else InstancesToArchive.failed instance, "立档单位未找到" @Test = {} # Test.run('iTRRqEfHYGhDeWwaC') Test.run = (ins_id)-> instance = Creator.Collections["instances"].findOne({_id: ins_id}) if instance InstancesToArchive.syncNonContractInstance instance InstancesToArchive::syncNonContractInstances = () -> console.time("syncNonContractInstances") instances = @getNonContractInstances() that = @ instances.forEach (mini_ins)-> instance = Creator.Collections["instances"].findOne({_id: mini_ins._id}) if instance try InstancesToArchive.syncNonContractInstance instance catch e logger.error e console.log e console.timeEnd("syncNonContractInstances")
[ { "context": "vitation: 'common'\n # password_reset: 'common'\n\n\n # thinkspace/markup\n # comment: ", "end": 3515, "score": 0.9258584976196289, "start": 3509, "tag": "PASSWORD", "value": "common" } ]
src/thinkspace/client/thinkspace-model/app/_config/thinkspace/models/_config.coffee
sixthedge/cellar
6
export default { env: {modulePrefix: 'thinkspace-models'} ns: # Namespace keys to resolve the full path for a key in the 'type_to_namespace'. # The keys values can be any value that matches a 'type_to_namespace' key's value # (or a unique key for using just the namespace). # # If want to use a 'namespaces' key in a 'ns.to_' function and resolve to the namespace path, # (e.g. without adding the type) it cannot match a key in 'type_to_namespace'. # e.g. no 'casespace' key in 'type_to_namespace': to_p('casespace') -> 'thinkspace/casespace' # e.g. casespace: 'casespace' in 'type_to_namespace': to_p('casespace') -> 'thinkspace/casespace/casespace' namespaces: authorization: 'thinkspace/authorization' # toolbar: 'thinkspace/casespace/toolbar' # right_pocket: 'thinkspace/casespace/right_pocket' # crumbs: 'thinkspace/casespace/toolbar/crumbs' # dock: 'thinkspace/dock' # common: 'thinkspace/common' # casespace: 'thinkspace/casespace' # artifact: 'thinkspace/artifact' diagnostic_path: 'thinkspace/diagnostic_path' diagnostic_path_viewer: 'thinkspace/diagnostic_path_viewer' # html: 'thinkspace/html' # input_element: 'thinkspace/input_element' # lab: 'thinkspace/lab' # markup: 'thinkspace/markup' # observation_list: 'thinkspace/observation_list' # resource: 'thinkspace/resource' team: 'thinkspace/team' peer_assessment: 'thinkspace/peer_assessment' # weather_forecaster: 'thinkspace/weather_forecaster' simulation: 'thinkspace/simulation' builder: 'thinkspace/builder' # indented_list: 'thinkspace/indented_list' stripe: 'thinkspace/stripe' # Convert commonly used key values to a full namespace path. # When using a 'ns.to_' function, the type key will be converted to a namespaced path. # # The 'type' must be the first argument and match either a key in 'type_to_namespace' # or the 'namespaces'. Any remaining arguments are added to the path. # The 'ns.to_' functions return the same value only with a different seperator. # e.g. ns.to_p('team', 'arg1', 'arg2') -> 'thinkspace/team/team/arg1/arg2' # e.g. ns.to_r('team', 'arg1', 'arg2') -> 'thinkspace/team/team.arg1.arg2' # # Keys must be unique and can be made unique by using 'unique-prefix:duplicate-type'. # e.g. 'phase_template_section:parent': 'casespace' -> thinkspace/casespace/parent # e.g. 'user:parent': 'common' -> thinkspace/common/parent # # CAUTION: The 'key' must be the singular value for lookup, but the original type value # (whether singular or plural) is added to the path. type_to_namespace: # thinkspace/authorization ability: 'authorization' metadata: 'authorization' # thinkspace/common # user: 'common' # owner: 'common' # space: 'common' # space_type: 'common' # space_user: 'common' # configuration: 'common' # configurable: 'common' # component: 'common' # invitation: 'common' # password_reset: 'common' # thinkspace/markup # comment: 'markup' # library: 'markup' # library_comment: 'markup' # discussion: 'markup' # 'comment:parent': 'markup' # # thinkspace/resource # resourceable: 'resource' # file: 'resource' # link: 'resource' # tag: 'resource' # thinkspace/stripe customer: 'stripe' # thinkspace/team team: 'team' team_category: 'team' team_user: 'team' team_teamable: 'team' team_viewer: 'team' team_set: 'team' # thinkspace/casespace # assignment: 'casespace' # phase: 'casespace' # phase_template: 'casespace' # phase_component: 'casespace' # phase_state: 'casespace' # phase_score: 'casespace' # gradebook: 'casespace' peer_review: 'casespace' # case_manager: 'casespace' # case_manager_template: 'casespace' # content: 'html' path: 'diagnostic_path' path_item: 'diagnostic_path' path_itemable: 'diagnostic_path' viewer: 'diagnostic_path_viewer' 'path_item:parent': 'diagnostic_path' # bucket: 'artifact' # 'artifact:file': 'artifact' # 'lab:chart': 'lab' # 'lab:category': 'lab' # 'lab:result': 'lab' # 'lab:observation': 'lab' # 'wf:assessment': 'weather_forecaster' # 'wf:assessment_item': 'weather_forecaster' # 'wf:forecast': 'weather_forecaster' # 'wf:forecast_day': 'weather_forecaster' # 'wf:item': 'weather_forecaster' # 'wf:response': 'weather_forecaster' # 'wf:response_score': 'weather_forecaster' # 'wf:station': 'weather_forecaster' # list: 'observation_list' # observation: 'observation_list' # observation_note: 'observation_list' # 'observation_list:group': 'observation_list' # element: 'input_element' # response: 'input_element' 'tbl:assessment': 'peer_assessment' 'tbl:review': 'peer_assessment' 'tbl:review_set': 'peer_assessment' 'tbl:team_set': 'peer_assessment' 'tbl:overview': 'peer_assessment' 'sim:simulation': 'simulation' 'builder:template': 'builder' # 'indented:list': 'indented_list' # 'indented:response': 'indented_list' # 'indented:expert_response': 'indented_list' # query_params: # # phase: ownerable: true, authable: false # # phase_score: ownerable: true, authable: true # # phase_state: ownerable: true, authable: true # # content: ownerable: true, authable: true # # list: ownerable: true, authable: false # # response: ownerable: true, authable: true # # observation: ownerable: true, authable: true # # team_category: ownerable: true, authable: true # # path: ownerable: true, authable: false # # bucket: ownerable: true, authable: false # # comment: ownerable: true, authable: false # # discussion: ownerable: true, authable: true # # viewer: ownerable: true, authable: false # # # 'lab:chart': ownerable: true, authable: false # # 'lab:observation': ownerable: true, authable: true # # 'tbl:assessment': ownerable: true, authable: true # # 'tbl:review': ownerable: true, authable: true # # 'tbl:overview': ownerable: true, authable: true # # 'wf:assessment': ownerable: true, authable: false # # 'wf:forecast': ownerable: true, authable: false # # 'wf:response': ownerable: true, authable: true # # 'sim:simulation': ownerable: true, authable: true # # # 'indented:list': ownerable: true, authable: true # # 'indented:response': ownerable: true, authable: true # # 'indented:expert_response': ownerable: true, authable: true }
91043
export default { env: {modulePrefix: 'thinkspace-models'} ns: # Namespace keys to resolve the full path for a key in the 'type_to_namespace'. # The keys values can be any value that matches a 'type_to_namespace' key's value # (or a unique key for using just the namespace). # # If want to use a 'namespaces' key in a 'ns.to_' function and resolve to the namespace path, # (e.g. without adding the type) it cannot match a key in 'type_to_namespace'. # e.g. no 'casespace' key in 'type_to_namespace': to_p('casespace') -> 'thinkspace/casespace' # e.g. casespace: 'casespace' in 'type_to_namespace': to_p('casespace') -> 'thinkspace/casespace/casespace' namespaces: authorization: 'thinkspace/authorization' # toolbar: 'thinkspace/casespace/toolbar' # right_pocket: 'thinkspace/casespace/right_pocket' # crumbs: 'thinkspace/casespace/toolbar/crumbs' # dock: 'thinkspace/dock' # common: 'thinkspace/common' # casespace: 'thinkspace/casespace' # artifact: 'thinkspace/artifact' diagnostic_path: 'thinkspace/diagnostic_path' diagnostic_path_viewer: 'thinkspace/diagnostic_path_viewer' # html: 'thinkspace/html' # input_element: 'thinkspace/input_element' # lab: 'thinkspace/lab' # markup: 'thinkspace/markup' # observation_list: 'thinkspace/observation_list' # resource: 'thinkspace/resource' team: 'thinkspace/team' peer_assessment: 'thinkspace/peer_assessment' # weather_forecaster: 'thinkspace/weather_forecaster' simulation: 'thinkspace/simulation' builder: 'thinkspace/builder' # indented_list: 'thinkspace/indented_list' stripe: 'thinkspace/stripe' # Convert commonly used key values to a full namespace path. # When using a 'ns.to_' function, the type key will be converted to a namespaced path. # # The 'type' must be the first argument and match either a key in 'type_to_namespace' # or the 'namespaces'. Any remaining arguments are added to the path. # The 'ns.to_' functions return the same value only with a different seperator. # e.g. ns.to_p('team', 'arg1', 'arg2') -> 'thinkspace/team/team/arg1/arg2' # e.g. ns.to_r('team', 'arg1', 'arg2') -> 'thinkspace/team/team.arg1.arg2' # # Keys must be unique and can be made unique by using 'unique-prefix:duplicate-type'. # e.g. 'phase_template_section:parent': 'casespace' -> thinkspace/casespace/parent # e.g. 'user:parent': 'common' -> thinkspace/common/parent # # CAUTION: The 'key' must be the singular value for lookup, but the original type value # (whether singular or plural) is added to the path. type_to_namespace: # thinkspace/authorization ability: 'authorization' metadata: 'authorization' # thinkspace/common # user: 'common' # owner: 'common' # space: 'common' # space_type: 'common' # space_user: 'common' # configuration: 'common' # configurable: 'common' # component: 'common' # invitation: 'common' # password_reset: '<PASSWORD>' # thinkspace/markup # comment: 'markup' # library: 'markup' # library_comment: 'markup' # discussion: 'markup' # 'comment:parent': 'markup' # # thinkspace/resource # resourceable: 'resource' # file: 'resource' # link: 'resource' # tag: 'resource' # thinkspace/stripe customer: 'stripe' # thinkspace/team team: 'team' team_category: 'team' team_user: 'team' team_teamable: 'team' team_viewer: 'team' team_set: 'team' # thinkspace/casespace # assignment: 'casespace' # phase: 'casespace' # phase_template: 'casespace' # phase_component: 'casespace' # phase_state: 'casespace' # phase_score: 'casespace' # gradebook: 'casespace' peer_review: 'casespace' # case_manager: 'casespace' # case_manager_template: 'casespace' # content: 'html' path: 'diagnostic_path' path_item: 'diagnostic_path' path_itemable: 'diagnostic_path' viewer: 'diagnostic_path_viewer' 'path_item:parent': 'diagnostic_path' # bucket: 'artifact' # 'artifact:file': 'artifact' # 'lab:chart': 'lab' # 'lab:category': 'lab' # 'lab:result': 'lab' # 'lab:observation': 'lab' # 'wf:assessment': 'weather_forecaster' # 'wf:assessment_item': 'weather_forecaster' # 'wf:forecast': 'weather_forecaster' # 'wf:forecast_day': 'weather_forecaster' # 'wf:item': 'weather_forecaster' # 'wf:response': 'weather_forecaster' # 'wf:response_score': 'weather_forecaster' # 'wf:station': 'weather_forecaster' # list: 'observation_list' # observation: 'observation_list' # observation_note: 'observation_list' # 'observation_list:group': 'observation_list' # element: 'input_element' # response: 'input_element' 'tbl:assessment': 'peer_assessment' 'tbl:review': 'peer_assessment' 'tbl:review_set': 'peer_assessment' 'tbl:team_set': 'peer_assessment' 'tbl:overview': 'peer_assessment' 'sim:simulation': 'simulation' 'builder:template': 'builder' # 'indented:list': 'indented_list' # 'indented:response': 'indented_list' # 'indented:expert_response': 'indented_list' # query_params: # # phase: ownerable: true, authable: false # # phase_score: ownerable: true, authable: true # # phase_state: ownerable: true, authable: true # # content: ownerable: true, authable: true # # list: ownerable: true, authable: false # # response: ownerable: true, authable: true # # observation: ownerable: true, authable: true # # team_category: ownerable: true, authable: true # # path: ownerable: true, authable: false # # bucket: ownerable: true, authable: false # # comment: ownerable: true, authable: false # # discussion: ownerable: true, authable: true # # viewer: ownerable: true, authable: false # # # 'lab:chart': ownerable: true, authable: false # # 'lab:observation': ownerable: true, authable: true # # 'tbl:assessment': ownerable: true, authable: true # # 'tbl:review': ownerable: true, authable: true # # 'tbl:overview': ownerable: true, authable: true # # 'wf:assessment': ownerable: true, authable: false # # 'wf:forecast': ownerable: true, authable: false # # 'wf:response': ownerable: true, authable: true # # 'sim:simulation': ownerable: true, authable: true # # # 'indented:list': ownerable: true, authable: true # # 'indented:response': ownerable: true, authable: true # # 'indented:expert_response': ownerable: true, authable: true }
true
export default { env: {modulePrefix: 'thinkspace-models'} ns: # Namespace keys to resolve the full path for a key in the 'type_to_namespace'. # The keys values can be any value that matches a 'type_to_namespace' key's value # (or a unique key for using just the namespace). # # If want to use a 'namespaces' key in a 'ns.to_' function and resolve to the namespace path, # (e.g. without adding the type) it cannot match a key in 'type_to_namespace'. # e.g. no 'casespace' key in 'type_to_namespace': to_p('casespace') -> 'thinkspace/casespace' # e.g. casespace: 'casespace' in 'type_to_namespace': to_p('casespace') -> 'thinkspace/casespace/casespace' namespaces: authorization: 'thinkspace/authorization' # toolbar: 'thinkspace/casespace/toolbar' # right_pocket: 'thinkspace/casespace/right_pocket' # crumbs: 'thinkspace/casespace/toolbar/crumbs' # dock: 'thinkspace/dock' # common: 'thinkspace/common' # casespace: 'thinkspace/casespace' # artifact: 'thinkspace/artifact' diagnostic_path: 'thinkspace/diagnostic_path' diagnostic_path_viewer: 'thinkspace/diagnostic_path_viewer' # html: 'thinkspace/html' # input_element: 'thinkspace/input_element' # lab: 'thinkspace/lab' # markup: 'thinkspace/markup' # observation_list: 'thinkspace/observation_list' # resource: 'thinkspace/resource' team: 'thinkspace/team' peer_assessment: 'thinkspace/peer_assessment' # weather_forecaster: 'thinkspace/weather_forecaster' simulation: 'thinkspace/simulation' builder: 'thinkspace/builder' # indented_list: 'thinkspace/indented_list' stripe: 'thinkspace/stripe' # Convert commonly used key values to a full namespace path. # When using a 'ns.to_' function, the type key will be converted to a namespaced path. # # The 'type' must be the first argument and match either a key in 'type_to_namespace' # or the 'namespaces'. Any remaining arguments are added to the path. # The 'ns.to_' functions return the same value only with a different seperator. # e.g. ns.to_p('team', 'arg1', 'arg2') -> 'thinkspace/team/team/arg1/arg2' # e.g. ns.to_r('team', 'arg1', 'arg2') -> 'thinkspace/team/team.arg1.arg2' # # Keys must be unique and can be made unique by using 'unique-prefix:duplicate-type'. # e.g. 'phase_template_section:parent': 'casespace' -> thinkspace/casespace/parent # e.g. 'user:parent': 'common' -> thinkspace/common/parent # # CAUTION: The 'key' must be the singular value for lookup, but the original type value # (whether singular or plural) is added to the path. type_to_namespace: # thinkspace/authorization ability: 'authorization' metadata: 'authorization' # thinkspace/common # user: 'common' # owner: 'common' # space: 'common' # space_type: 'common' # space_user: 'common' # configuration: 'common' # configurable: 'common' # component: 'common' # invitation: 'common' # password_reset: 'PI:PASSWORD:<PASSWORD>END_PI' # thinkspace/markup # comment: 'markup' # library: 'markup' # library_comment: 'markup' # discussion: 'markup' # 'comment:parent': 'markup' # # thinkspace/resource # resourceable: 'resource' # file: 'resource' # link: 'resource' # tag: 'resource' # thinkspace/stripe customer: 'stripe' # thinkspace/team team: 'team' team_category: 'team' team_user: 'team' team_teamable: 'team' team_viewer: 'team' team_set: 'team' # thinkspace/casespace # assignment: 'casespace' # phase: 'casespace' # phase_template: 'casespace' # phase_component: 'casespace' # phase_state: 'casespace' # phase_score: 'casespace' # gradebook: 'casespace' peer_review: 'casespace' # case_manager: 'casespace' # case_manager_template: 'casespace' # content: 'html' path: 'diagnostic_path' path_item: 'diagnostic_path' path_itemable: 'diagnostic_path' viewer: 'diagnostic_path_viewer' 'path_item:parent': 'diagnostic_path' # bucket: 'artifact' # 'artifact:file': 'artifact' # 'lab:chart': 'lab' # 'lab:category': 'lab' # 'lab:result': 'lab' # 'lab:observation': 'lab' # 'wf:assessment': 'weather_forecaster' # 'wf:assessment_item': 'weather_forecaster' # 'wf:forecast': 'weather_forecaster' # 'wf:forecast_day': 'weather_forecaster' # 'wf:item': 'weather_forecaster' # 'wf:response': 'weather_forecaster' # 'wf:response_score': 'weather_forecaster' # 'wf:station': 'weather_forecaster' # list: 'observation_list' # observation: 'observation_list' # observation_note: 'observation_list' # 'observation_list:group': 'observation_list' # element: 'input_element' # response: 'input_element' 'tbl:assessment': 'peer_assessment' 'tbl:review': 'peer_assessment' 'tbl:review_set': 'peer_assessment' 'tbl:team_set': 'peer_assessment' 'tbl:overview': 'peer_assessment' 'sim:simulation': 'simulation' 'builder:template': 'builder' # 'indented:list': 'indented_list' # 'indented:response': 'indented_list' # 'indented:expert_response': 'indented_list' # query_params: # # phase: ownerable: true, authable: false # # phase_score: ownerable: true, authable: true # # phase_state: ownerable: true, authable: true # # content: ownerable: true, authable: true # # list: ownerable: true, authable: false # # response: ownerable: true, authable: true # # observation: ownerable: true, authable: true # # team_category: ownerable: true, authable: true # # path: ownerable: true, authable: false # # bucket: ownerable: true, authable: false # # comment: ownerable: true, authable: false # # discussion: ownerable: true, authable: true # # viewer: ownerable: true, authable: false # # # 'lab:chart': ownerable: true, authable: false # # 'lab:observation': ownerable: true, authable: true # # 'tbl:assessment': ownerable: true, authable: true # # 'tbl:review': ownerable: true, authable: true # # 'tbl:overview': ownerable: true, authable: true # # 'wf:assessment': ownerable: true, authable: false # # 'wf:forecast': ownerable: true, authable: false # # 'wf:response': ownerable: true, authable: true # # 'sim:simulation': ownerable: true, authable: true # # # 'indented:list': ownerable: true, authable: true # # 'indented:response': ownerable: true, authable: true # # 'indented:expert_response': ownerable: true, authable: true }
[ { "context": " ajaxSpy = spyOn(jQuery, \"ajax\")\n token = \"6ybnjsd83nsdi\"\n search = createSearch(token: token)\n\n ", "end": 540, "score": 0.9605185985565186, "start": 527, "tag": "PASSWORD", "value": "6ybnjsd83nsdi" } ]
spec/dash-autocomplete/search.coffee
samaritanministries/dash-autocomplete.js
0
describe "DashAutocomplete.Search", -> class CollectionView showResults: (data) -> showNoResults: -> showError: (result) -> searchCriteriaCleared: -> createSearch = (options) -> optionsWithDefaults = _.extend({ startSpinner: (->), stopSpinner: (->), resultsView: new CollectionView }, options) new DashAutocomplete.Search(optionsWithDefaults) describe "searching", -> it "requests with the token in the headers", -> ajaxSpy = spyOn(jQuery, "ajax") token = "6ybnjsd83nsdi" search = createSearch(token: token) search.search("test value") expect(ajaxSpy.calls.argsFor(0)[0].headers).toEqual(authorization: "Bearer #{token}") it "changes the data into a query string", -> ajaxSpy = spyOn(jQuery, "ajax") search = createSearch() search.search("test value") expect(JSON.parse(ajaxSpy.calls.argsFor(0)[0].data)).toEqual current_page: 1 filters: [] items_per_page: 10 search_string: "test value" sort_order: [] it "starts the spinner before the request is made", -> startSpinnerSpy = jasmine.createSpy("startSpinner") spyOn(jQuery, "ajax") search = createSearch(startSpinner: startSpinnerSpy) search.search("test value") expect(startSpinnerSpy).toHaveBeenCalled() it "stops the spinner on success", -> server = sinon.fakeServer.create() stopSpinnerSpy = jasmine.createSpy("stopSpinner") search = createSearch(stopSpinner: stopSpinnerSpy) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(stopSpinnerSpy).toHaveBeenCalled() it "stops the spinner on error", -> server = sinon.fakeServer.create() stopSpinnerSpy = jasmine.createSpy("stopSpinner") search = createSearch(stopSpinner: stopSpinnerSpy) server.respondWith("POST", search.url, [500, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(stopSpinnerSpy).toHaveBeenCalled() it "has the results view render the results", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showResultsSpy = spyOn(resultsView, "showResults") search = createSearch(resultsView: resultsView) taskJson = [{"task_id": "1"}, {"task_id": "2"}] server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, JSON.stringify(taskJson)]) search.search("test value") server.respond() expect(showResultsSpy).toHaveBeenCalledWith(taskJson) it "has the results view render a no results found screen", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showNoResultsSpy = spyOn(resultsView, "showNoResults") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(showNoResultsSpy).toHaveBeenCalled() it "lets the collection view know that the search criteria was cleared", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showNoResultsSpy = spyOn(resultsView, "showNoResults") searchCriteriaClearedSpy = spyOn(resultsView, "searchCriteriaCleared") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("") server.respond() expect(searchCriteriaClearedSpy).toHaveBeenCalled() it "does not trigger an additional callback when the search criteria was cleared", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showNoResultsSpy = spyOn(resultsView, "showNoResults") searchCriteriaClearedSpy = spyOn(resultsView, "searchCriteriaCleared") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("") server.respond() expect(showNoResultsSpy).not.toHaveBeenCalled() it "shows results when the search criteria was cleared and there are results", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showResultsSpy = spyOn(resultsView, "showResults") searchCriteriaClearedSpy = spyOn(resultsView, "searchCriteriaCleared") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, JSON.stringify([{id: 123}])]) search.search("") server.respond() expect(showResultsSpy).toHaveBeenCalled() it "has the collection view render an error screen", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showErrorSpy = spyOn(resultsView, "showError") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [500, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(showErrorSpy).toHaveBeenCalled()
225028
describe "DashAutocomplete.Search", -> class CollectionView showResults: (data) -> showNoResults: -> showError: (result) -> searchCriteriaCleared: -> createSearch = (options) -> optionsWithDefaults = _.extend({ startSpinner: (->), stopSpinner: (->), resultsView: new CollectionView }, options) new DashAutocomplete.Search(optionsWithDefaults) describe "searching", -> it "requests with the token in the headers", -> ajaxSpy = spyOn(jQuery, "ajax") token = "<PASSWORD>" search = createSearch(token: token) search.search("test value") expect(ajaxSpy.calls.argsFor(0)[0].headers).toEqual(authorization: "Bearer #{token}") it "changes the data into a query string", -> ajaxSpy = spyOn(jQuery, "ajax") search = createSearch() search.search("test value") expect(JSON.parse(ajaxSpy.calls.argsFor(0)[0].data)).toEqual current_page: 1 filters: [] items_per_page: 10 search_string: "test value" sort_order: [] it "starts the spinner before the request is made", -> startSpinnerSpy = jasmine.createSpy("startSpinner") spyOn(jQuery, "ajax") search = createSearch(startSpinner: startSpinnerSpy) search.search("test value") expect(startSpinnerSpy).toHaveBeenCalled() it "stops the spinner on success", -> server = sinon.fakeServer.create() stopSpinnerSpy = jasmine.createSpy("stopSpinner") search = createSearch(stopSpinner: stopSpinnerSpy) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(stopSpinnerSpy).toHaveBeenCalled() it "stops the spinner on error", -> server = sinon.fakeServer.create() stopSpinnerSpy = jasmine.createSpy("stopSpinner") search = createSearch(stopSpinner: stopSpinnerSpy) server.respondWith("POST", search.url, [500, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(stopSpinnerSpy).toHaveBeenCalled() it "has the results view render the results", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showResultsSpy = spyOn(resultsView, "showResults") search = createSearch(resultsView: resultsView) taskJson = [{"task_id": "1"}, {"task_id": "2"}] server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, JSON.stringify(taskJson)]) search.search("test value") server.respond() expect(showResultsSpy).toHaveBeenCalledWith(taskJson) it "has the results view render a no results found screen", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showNoResultsSpy = spyOn(resultsView, "showNoResults") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(showNoResultsSpy).toHaveBeenCalled() it "lets the collection view know that the search criteria was cleared", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showNoResultsSpy = spyOn(resultsView, "showNoResults") searchCriteriaClearedSpy = spyOn(resultsView, "searchCriteriaCleared") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("") server.respond() expect(searchCriteriaClearedSpy).toHaveBeenCalled() it "does not trigger an additional callback when the search criteria was cleared", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showNoResultsSpy = spyOn(resultsView, "showNoResults") searchCriteriaClearedSpy = spyOn(resultsView, "searchCriteriaCleared") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("") server.respond() expect(showNoResultsSpy).not.toHaveBeenCalled() it "shows results when the search criteria was cleared and there are results", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showResultsSpy = spyOn(resultsView, "showResults") searchCriteriaClearedSpy = spyOn(resultsView, "searchCriteriaCleared") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, JSON.stringify([{id: 123}])]) search.search("") server.respond() expect(showResultsSpy).toHaveBeenCalled() it "has the collection view render an error screen", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showErrorSpy = spyOn(resultsView, "showError") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [500, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(showErrorSpy).toHaveBeenCalled()
true
describe "DashAutocomplete.Search", -> class CollectionView showResults: (data) -> showNoResults: -> showError: (result) -> searchCriteriaCleared: -> createSearch = (options) -> optionsWithDefaults = _.extend({ startSpinner: (->), stopSpinner: (->), resultsView: new CollectionView }, options) new DashAutocomplete.Search(optionsWithDefaults) describe "searching", -> it "requests with the token in the headers", -> ajaxSpy = spyOn(jQuery, "ajax") token = "PI:PASSWORD:<PASSWORD>END_PI" search = createSearch(token: token) search.search("test value") expect(ajaxSpy.calls.argsFor(0)[0].headers).toEqual(authorization: "Bearer #{token}") it "changes the data into a query string", -> ajaxSpy = spyOn(jQuery, "ajax") search = createSearch() search.search("test value") expect(JSON.parse(ajaxSpy.calls.argsFor(0)[0].data)).toEqual current_page: 1 filters: [] items_per_page: 10 search_string: "test value" sort_order: [] it "starts the spinner before the request is made", -> startSpinnerSpy = jasmine.createSpy("startSpinner") spyOn(jQuery, "ajax") search = createSearch(startSpinner: startSpinnerSpy) search.search("test value") expect(startSpinnerSpy).toHaveBeenCalled() it "stops the spinner on success", -> server = sinon.fakeServer.create() stopSpinnerSpy = jasmine.createSpy("stopSpinner") search = createSearch(stopSpinner: stopSpinnerSpy) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(stopSpinnerSpy).toHaveBeenCalled() it "stops the spinner on error", -> server = sinon.fakeServer.create() stopSpinnerSpy = jasmine.createSpy("stopSpinner") search = createSearch(stopSpinner: stopSpinnerSpy) server.respondWith("POST", search.url, [500, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(stopSpinnerSpy).toHaveBeenCalled() it "has the results view render the results", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showResultsSpy = spyOn(resultsView, "showResults") search = createSearch(resultsView: resultsView) taskJson = [{"task_id": "1"}, {"task_id": "2"}] server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, JSON.stringify(taskJson)]) search.search("test value") server.respond() expect(showResultsSpy).toHaveBeenCalledWith(taskJson) it "has the results view render a no results found screen", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showNoResultsSpy = spyOn(resultsView, "showNoResults") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(showNoResultsSpy).toHaveBeenCalled() it "lets the collection view know that the search criteria was cleared", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showNoResultsSpy = spyOn(resultsView, "showNoResults") searchCriteriaClearedSpy = spyOn(resultsView, "searchCriteriaCleared") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("") server.respond() expect(searchCriteriaClearedSpy).toHaveBeenCalled() it "does not trigger an additional callback when the search criteria was cleared", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showNoResultsSpy = spyOn(resultsView, "showNoResults") searchCriteriaClearedSpy = spyOn(resultsView, "searchCriteriaCleared") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, "[]"]) search.search("") server.respond() expect(showNoResultsSpy).not.toHaveBeenCalled() it "shows results when the search criteria was cleared and there are results", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showResultsSpy = spyOn(resultsView, "showResults") searchCriteriaClearedSpy = spyOn(resultsView, "searchCriteriaCleared") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [200, { "Content-Type": "application/json" }, JSON.stringify([{id: 123}])]) search.search("") server.respond() expect(showResultsSpy).toHaveBeenCalled() it "has the collection view render an error screen", -> server = sinon.fakeServer.create() resultsView = new CollectionView() showErrorSpy = spyOn(resultsView, "showError") search = createSearch(resultsView: resultsView) server.respondWith("POST", search.url, [500, { "Content-Type": "application/json" }, "[]"]) search.search("test value") server.respond() expect(showErrorSpy).toHaveBeenCalled()
[ { "context": " 'value': 'name'\n\n model.set 'name', 'test'\n\n view = new View model: model\n ", "end": 403, "score": 0.6616657972335815, "start": 399, "tag": "NAME", "value": "test" }, { "context": "e.prop 'value', ''\n\n view.set('name', 'tes...
test/connect.coffee
redexp/backbone-dom-view
13
define ['chai', 'backbone', 'backbone-dom-view'], ({expect}, Backbone, DomView) -> model = null beforeEach -> model = new Backbone.Model() describe 'connect helper', -> it 'should bind prop and field', -> View = DomView.extend template: '': connect: 'value': 'name' model.set 'name', 'test' view = new View model: model el = view.$el expect(el).to.have.prop 'value', 'test' el.prop 'value', 'max' el.change() expect(model.get 'name').to.be.equal 'max' model.set 'name', 'bob' expect(el).to.have.prop 'value', 'bob' it 'should bind prop and view field', -> View = DomView.extend defaults: name: '' template: '': connect: 'value': 'name' model.set 'name', 'x' view = new View model: model el = view.$el expect(el).to.have.prop 'value', '' view.set('name', 'test') expect(el).to.have.prop 'value', 'test' expect(model.get('name')).to.equal 'x' el.prop 'value', 'max' el.change() expect(view.get 'name').to.be.equal 'max' expect(model.get 'name').to.be.equal 'x' view.set 'name', 'bob' expect(el).to.have.prop 'value', 'bob' expect(model.get 'name').to.be.equal 'x' it 'should bind prop and field with custom node event', -> View = DomView.extend template: '': connect: 'id|click': 'id' model.set 'id', 'test' view = new View model: model el = view.$el expect(el).to.have.prop 'id', 'test' el.prop 'id', 'max' el.click() expect(model.get 'id').to.be.equal 'max' model.set 'id', 'bob' expect(el).to.have.prop 'id', 'bob' it 'should handle more than one node', -> View = DomView.extend el: '<div><input type="text"/><input type="text"/></div>' template: 'input': connect: 'value': 'text' model.set('text', 'test') view = new View model: model el = view.$el.find('input') expect(el.eq(0)).to.have.prop 'value', 'test' expect(el.eq(1)).to.have.prop 'value', 'test' model.set('text', 'test2') expect(el.eq(0)).to.have.prop 'value', 'test2' expect(el.eq(1)).to.have.prop 'value', 'test2' el.eq(0).val('val1').change() expect(model.get('text')).to.equal('val1') expect(el.eq(0)).to.have.prop 'value', 'val1' expect(el.eq(1)).to.have.prop 'value', 'val1' el.eq(1).val('val2').change() expect(model.get('text')).to.equal('val2') expect(el.eq(0)).to.have.prop 'value', 'val2' expect(el.eq(1)).to.have.prop 'value', 'val2'
52436
define ['chai', 'backbone', 'backbone-dom-view'], ({expect}, Backbone, DomView) -> model = null beforeEach -> model = new Backbone.Model() describe 'connect helper', -> it 'should bind prop and field', -> View = DomView.extend template: '': connect: 'value': 'name' model.set 'name', '<NAME>' view = new View model: model el = view.$el expect(el).to.have.prop 'value', 'test' el.prop 'value', 'max' el.change() expect(model.get 'name').to.be.equal 'max' model.set 'name', 'bob' expect(el).to.have.prop 'value', 'bob' it 'should bind prop and view field', -> View = DomView.extend defaults: name: '' template: '': connect: 'value': 'name' model.set 'name', 'x' view = new View model: model el = view.$el expect(el).to.have.prop 'value', '' view.set('name', '<NAME>') expect(el).to.have.prop 'value', 'test' expect(model.get('name')).to.equal 'x' el.prop 'value', 'max' el.change() expect(view.get 'name').to.be.equal 'max' expect(model.get 'name').to.be.equal 'x' view.set 'name', 'bob' expect(el).to.have.prop 'value', 'bob' expect(model.get 'name').to.be.equal 'x' it 'should bind prop and field with custom node event', -> View = DomView.extend template: '': connect: 'id|click': 'id' model.set 'id', 'test' view = new View model: model el = view.$el expect(el).to.have.prop 'id', 'test' el.prop 'id', 'max' el.click() expect(model.get 'id').to.be.equal 'max' model.set 'id', 'bob' expect(el).to.have.prop 'id', 'bob' it 'should handle more than one node', -> View = DomView.extend el: '<div><input type="text"/><input type="text"/></div>' template: 'input': connect: 'value': 'text' model.set('text', 'test') view = new View model: model el = view.$el.find('input') expect(el.eq(0)).to.have.prop 'value', 'test' expect(el.eq(1)).to.have.prop 'value', 'test' model.set('text', 'test2') expect(el.eq(0)).to.have.prop 'value', 'test2' expect(el.eq(1)).to.have.prop 'value', 'test2' el.eq(0).val('val1').change() expect(model.get('text')).to.equal('val1') expect(el.eq(0)).to.have.prop 'value', 'val1' expect(el.eq(1)).to.have.prop 'value', 'val1' el.eq(1).val('val2').change() expect(model.get('text')).to.equal('val2') expect(el.eq(0)).to.have.prop 'value', 'val2' expect(el.eq(1)).to.have.prop 'value', 'val2'
true
define ['chai', 'backbone', 'backbone-dom-view'], ({expect}, Backbone, DomView) -> model = null beforeEach -> model = new Backbone.Model() describe 'connect helper', -> it 'should bind prop and field', -> View = DomView.extend template: '': connect: 'value': 'name' model.set 'name', 'PI:NAME:<NAME>END_PI' view = new View model: model el = view.$el expect(el).to.have.prop 'value', 'test' el.prop 'value', 'max' el.change() expect(model.get 'name').to.be.equal 'max' model.set 'name', 'bob' expect(el).to.have.prop 'value', 'bob' it 'should bind prop and view field', -> View = DomView.extend defaults: name: '' template: '': connect: 'value': 'name' model.set 'name', 'x' view = new View model: model el = view.$el expect(el).to.have.prop 'value', '' view.set('name', 'PI:NAME:<NAME>END_PI') expect(el).to.have.prop 'value', 'test' expect(model.get('name')).to.equal 'x' el.prop 'value', 'max' el.change() expect(view.get 'name').to.be.equal 'max' expect(model.get 'name').to.be.equal 'x' view.set 'name', 'bob' expect(el).to.have.prop 'value', 'bob' expect(model.get 'name').to.be.equal 'x' it 'should bind prop and field with custom node event', -> View = DomView.extend template: '': connect: 'id|click': 'id' model.set 'id', 'test' view = new View model: model el = view.$el expect(el).to.have.prop 'id', 'test' el.prop 'id', 'max' el.click() expect(model.get 'id').to.be.equal 'max' model.set 'id', 'bob' expect(el).to.have.prop 'id', 'bob' it 'should handle more than one node', -> View = DomView.extend el: '<div><input type="text"/><input type="text"/></div>' template: 'input': connect: 'value': 'text' model.set('text', 'test') view = new View model: model el = view.$el.find('input') expect(el.eq(0)).to.have.prop 'value', 'test' expect(el.eq(1)).to.have.prop 'value', 'test' model.set('text', 'test2') expect(el.eq(0)).to.have.prop 'value', 'test2' expect(el.eq(1)).to.have.prop 'value', 'test2' el.eq(0).val('val1').change() expect(model.get('text')).to.equal('val1') expect(el.eq(0)).to.have.prop 'value', 'val1' expect(el.eq(1)).to.have.prop 'value', 'val1' el.eq(1).val('val2').change() expect(model.get('text')).to.equal('val2') expect(el.eq(0)).to.have.prop 'value', 'val2' expect(el.eq(1)).to.have.prop 'value', 'val2'
[ { "context": "ion.js\n# *********************************\n# ** By Etienne Pinchon\n# ** ©2016\n\nclass Transition extends Element\n\n\t_k", "end": 147, "score": 0.9998486638069153, "start": 132, "tag": "NAME", "value": "Etienne Pinchon" } ]
sources/coffee/Transition.coffee
heschel6/Magic_Experiment
201
# ********************************* # ********************************* # Transition.js # ********************************* # ** By Etienne Pinchon # ** ©2016 class Transition extends Element _kind : 'Transition' constructor: (options) -> if options.duration options.time = options.duration # Set the default properties #@options = App.defaults.Transition options = Defaults.get @_kind, options super options @options = Utils.clone Utils.defaults options, properties: {} time: 0.3 delay: 0 view: null curve: 'ease' if options if options.properties @options.properties = options.properties else @options.properties = {} if options.view @options.view = options.view if options.duration @options.duration = options.duration if options.delay @options.delay = options.delay if options.curve @options.curve = options.curve Transition::start = (remove) -> if @options.view # *** CSS Syntax *** # animation: name duration timing-function delay iteration-count direction fill-mode play-state; @options.view.style.transition = 'all ' + @options.duration + 's ' + @options.curve + ' ' + @options.delay + 's' @options.view.props = @options.properties else return if not remove return else _view = @options.view that = this Utils.delay @options.duration, -> _view.style.transition = '' that.emit 'end' Transition::disable = -> if @options.view @options.view.style.transition = 'none' Transition::remove = -> if @options.view @options.view.style.transition = ''
48985
# ********************************* # ********************************* # Transition.js # ********************************* # ** By <NAME> # ** ©2016 class Transition extends Element _kind : 'Transition' constructor: (options) -> if options.duration options.time = options.duration # Set the default properties #@options = App.defaults.Transition options = Defaults.get @_kind, options super options @options = Utils.clone Utils.defaults options, properties: {} time: 0.3 delay: 0 view: null curve: 'ease' if options if options.properties @options.properties = options.properties else @options.properties = {} if options.view @options.view = options.view if options.duration @options.duration = options.duration if options.delay @options.delay = options.delay if options.curve @options.curve = options.curve Transition::start = (remove) -> if @options.view # *** CSS Syntax *** # animation: name duration timing-function delay iteration-count direction fill-mode play-state; @options.view.style.transition = 'all ' + @options.duration + 's ' + @options.curve + ' ' + @options.delay + 's' @options.view.props = @options.properties else return if not remove return else _view = @options.view that = this Utils.delay @options.duration, -> _view.style.transition = '' that.emit 'end' Transition::disable = -> if @options.view @options.view.style.transition = 'none' Transition::remove = -> if @options.view @options.view.style.transition = ''
true
# ********************************* # ********************************* # Transition.js # ********************************* # ** By PI:NAME:<NAME>END_PI # ** ©2016 class Transition extends Element _kind : 'Transition' constructor: (options) -> if options.duration options.time = options.duration # Set the default properties #@options = App.defaults.Transition options = Defaults.get @_kind, options super options @options = Utils.clone Utils.defaults options, properties: {} time: 0.3 delay: 0 view: null curve: 'ease' if options if options.properties @options.properties = options.properties else @options.properties = {} if options.view @options.view = options.view if options.duration @options.duration = options.duration if options.delay @options.delay = options.delay if options.curve @options.curve = options.curve Transition::start = (remove) -> if @options.view # *** CSS Syntax *** # animation: name duration timing-function delay iteration-count direction fill-mode play-state; @options.view.style.transition = 'all ' + @options.duration + 's ' + @options.curve + ' ' + @options.delay + 's' @options.view.props = @options.properties else return if not remove return else _view = @options.view that = this Utils.delay @options.duration, -> _view.style.transition = '' that.emit 'end' Transition::disable = -> if @options.view @options.view.style.transition = 'none' Transition::remove = -> if @options.view @options.view.style.transition = ''
[ { "context": "rect login example:\n # /login?app=connect&handle=jdoe&password=xxxxxx&retUrl=https%3A%2F%2Fconnect.topc", "end": 864, "score": 0.998942494392395, "start": 860, "tag": "USERNAME", "value": "jdoe" }, { "context": "mple:\n # /login?app=connect&handle=jdoe&password=xxxxx...
app/app-config.coffee
appirio-tech/accounts-app
3
`import Auth0 from "auth0-js";` `import { AUTH0_DOMAIN, AUTH0_CLIENT_ID } from "../core/constants.js"` 'use strict' config = ( $locationProvider $stateProvider angularAuth0Provider ) -> states = {} $locationProvider.html5Mode true # customer routes states['home'] = url : '/' title : 'Home' controller : 'HomeController as vm' template : require('./views/home')() # State parameters # app : tc|connect|etc.. # retUrl : URL to redirect after authentication # handle : direct login with handle/password # password : direct login with handle/password # return_to: URL of Zendesk to redirect after authentication. This is handed by Zendesk. # # Connect example: # /login?app=connect&retUrl=https%3A%2F%2Fconnect.topcoder.com # Direct login example: # /login?app=connect&handle=jdoe&password=xxxxxx&retUrl=https%3A%2F%2Fconnect.topcoder.com # Zendesk example: # /login?app=zendesk&return_to=https%3A%2F%2Ftopcoder.zendesk.com states['login'] = url: '/login?app&retUrl&handle&password&return_to' title: 'Login' controller : 'LoginController as vm' template: require('./views/login')() public: true # State parameters # retUrl : URL to redirect after logging out # message : A message handed by Zendesk when some error occurs # # Example: # /logout?retUrl=https%3A%2F%2Fconnect.topcoder.com # Zendesk example: # /logout?retUrl=https%3A%2F%2Ftopcoder.zendesk.com%2F # Zendesk Error example: # /logout?kind=error&message=User%20is%20invalid:%20External%20has%20already%20been%20taken&retUrl=https:%2F%2Fkohata.zendesk.com%2F states['logout'] = url: '/logout?retUrl&message' title: 'Logout' controller : 'LogoutController as vm' template: require('./views/logout')() public: true # State parameters # client_id : (required) ID for a client which is registered in the client database. # response_type: (required) Only "token" is supported. # redirect_uri : (required) Encoded URL to redirect after authentication. This should be registered in the client database. # state : (optional) # scope : (optional) Currently not used in anywhere. states['OAUTH'] = url: '/oauth?client_id&response_type&state&redirect_uri&scope' controller : 'OAuthController as vm' public: true states['MEMBER_LOGIN'] = url: '/member?retUrl&handle&password&return_to&client_id&response_type&state&redirect_uri&scope' title: 'Login' controller : 'TCLoginController as vm' template: require('./views/tc/login')() public: true # State parameters # retUrl : (required) URL to redirect after SSO # utm_source : (optional) UTM source for the registration # utm_medium : (optional) UTM medium for the registration # utm_campaign : (optional) UTM campaign for the registration # userJWTToken : (optional) v3 JWT Token # auth0Jwt : (optional) Auth0(v2) JWT Token # auth0Refresh : (optional) Auth0 Refresh Token # message : (optional) A message handed by Identity Service when some error occurs states['MEMBER_REGISTRATION'] = url: '/member/registration?retUrl&utm_source&utm_medium&utm_campaign&userJWTToken&auth0Jwt&auth0Refresh&message&regSource' title: 'Register' params: { 'auth0Data', 'regForm' } controller : 'TCRegistrationController as vm' template: require('./views/tc/register.jade')() public: true states['MEMBER_REGISTRATION_SUCCESS'] = url: '/member/registration-success?retUrl' params: { 'ssoUser' } template: require('./views/tc/registered-successfully.jade')() controller: 'TCRegistrationSuccessController as vm' public: true states['MEMBER_FORGOT_PASSWORD'] = url: '/member/forgot-password' controller : 'TCResetPasswordController as vm' template : require('./views/tc/reset-password.jade')() public: true states['MEMBER_RESET_PASSWORD'] = url: '/member/reset-password?token&handle' controller : 'TCResetPasswordController as vm' template : require('./views/tc/reset-password.jade')() public: true # State parameters # retUrl : (required) URL to redirect after SSO # userJWTToken : (optional) v3 JWT Token # auth0Jwt : (optional) Auth0(v2) JWT Token # auth0Refresh : (optional) Auth0 Refresh Token # message : (optional) A message handed by Identity Service when some error occurs states['SOCIAL_CALLBACK'] = url: '/social-callback?retUrl&userJWTToken&auth0Jwt&auth0Refresh&message' template : require('./views/tc/social-callback')() controller : 'SSOCallbackController as vm' public: true states['CONNECT_LOGIN'] = url: '/connect?retUrl&handle&password' params: {'passwordReset'} controller : 'ConnectLoginController as vm' template: require('./views/connect/login')() public: true states['CONNECT_REGISTRATION'] = url: '/connect/registration?retUrl&userJWTToken&auth0Jwt&auth0Refresh&message' params: { 'auth0Data', 'regForm' } controller : 'ConnectRegistrationController as vm' template: require('./views/connect/registration.jade')() public: true states['CONNECT_REGISTRATION_SUCCESS'] = url: '/connect/registration-success' params: { 'ssoUser' } template: require('./views/connect/registration-success.jade')() controller: 'TCRegistrationSuccessController as vm' public: true states['CONNECT_PIN_VERIFICATION'] = url: '/connect/pin-verification?retUrl' params: {'email', 'username', 'password', 'userId', 'afterActivationURL'} controller : 'ConnectPinVerificationController as vm' template: require('./views/connect/pin-verification.jade')() public: true states['CONNECT_WELCOME'] = url: '/connect/welcome' params: {'email', 'username', 'password', 'userId', 'afterActivationURL'} controller : 'ConnectWelcomeController as vm' template: require('./views/connect/welcome.jade')() public: true states['CONNECT_FORGOT_PASSWORD'] = url: '/connect/forgot-password' controller : 'ConnectForgotPasswordController as vm' template : require('./views/connect/forgot-password.jade')() public: true states['CONNECT_RESET_PASSWORD'] = url: '/connect/reset-password?token&handle&retUrl' controller : 'ConnectResetPasswordController as vm' template : require('./views/connect/reset-password.jade')() public: true # State parameters # see SOCIAL_CALLBACK states['SSO_LOGIN'] = url: '/sso-login/?app&email&retUrl' params: { 'regForm' } template : require('./views/sso/sso-login')() controller : 'SSOLoginController as vm' public: true # State parameters # retUrl : (required) URL to redirect after SSO # userJWTToken : (optional) v3 JWT Token # auth0Jwt : (optional) Auth0(v2) JWT Token # auth0Refresh : (optional) Auth0 Refresh Token # message : (optional) A message handed by Identity Service when some error occurs states['SSO_CALLBACK'] = url: '/sso-callback?retUrl&userJWTToken&auth0Jwt&auth0Refresh&message' template : require('./views/sso/sso-callback')() controller : 'SSOCallbackController as vm' public: true states['UNAUTHORIZED'] = url: '/401', template : require('./views/401')() public: true # This must be the last one in the list states['otherwise'] = url: '*path', template : require('./views/404')() public: true for key, state of states $stateProvider.state key, state # Setup Auth0 (for Social Login) angularAuth0Provider.init({ domain: AUTH0_DOMAIN clientID: AUTH0_CLIENT_ID sso: false }, Auth0) config.$inject = [ '$locationProvider' '$stateProvider' 'angularAuth0Provider' ] angular.module('accounts').config config
204867
`import Auth0 from "auth0-js";` `import { AUTH0_DOMAIN, AUTH0_CLIENT_ID } from "../core/constants.js"` 'use strict' config = ( $locationProvider $stateProvider angularAuth0Provider ) -> states = {} $locationProvider.html5Mode true # customer routes states['home'] = url : '/' title : 'Home' controller : 'HomeController as vm' template : require('./views/home')() # State parameters # app : tc|connect|etc.. # retUrl : URL to redirect after authentication # handle : direct login with handle/password # password : direct login with handle/password # return_to: URL of Zendesk to redirect after authentication. This is handed by Zendesk. # # Connect example: # /login?app=connect&retUrl=https%3A%2F%2Fconnect.topcoder.com # Direct login example: # /login?app=connect&handle=jdoe&password=<PASSWORD>&retUrl=https%3A%2F%2Fconnect.topcoder.com # Zendesk example: # /login?app=zendesk&return_to=https%3A%2F%2Ftopcoder.zendesk.com states['login'] = url: '/login?app&retUrl&handle&password&return_to' title: 'Login' controller : 'LoginController as vm' template: require('./views/login')() public: true # State parameters # retUrl : URL to redirect after logging out # message : A message handed by Zendesk when some error occurs # # Example: # /logout?retUrl=https%3A%2F%2Fconnect.topcoder.com # Zendesk example: # /logout?retUrl=https%3A%2F%2Ftopcoder.zendesk.com%2F # Zendesk Error example: # /logout?kind=error&message=User%20is%20invalid:%20External%20has%20already%20been%20taken&retUrl=https:%2F%2Fkohata.zendesk.com%2F states['logout'] = url: '/logout?retUrl&message' title: 'Logout' controller : 'LogoutController as vm' template: require('./views/logout')() public: true # State parameters # client_id : (required) ID for a client which is registered in the client database. # response_type: (required) Only "token" is supported. # redirect_uri : (required) Encoded URL to redirect after authentication. This should be registered in the client database. # state : (optional) # scope : (optional) Currently not used in anywhere. states['OAUTH'] = url: '/oauth?client_id&response_type&state&redirect_uri&scope' controller : 'OAuthController as vm' public: true states['MEMBER_LOGIN'] = url: '/member?retUrl&handle&password&return_to&client_id&response_type&state&redirect_uri&scope' title: 'Login' controller : 'TCLoginController as vm' template: require('./views/tc/login')() public: true # State parameters # retUrl : (required) URL to redirect after SSO # utm_source : (optional) UTM source for the registration # utm_medium : (optional) UTM medium for the registration # utm_campaign : (optional) UTM campaign for the registration # userJWTToken : (optional) v3 JWT Token # auth0Jwt : (optional) Auth0(v2) JWT Token # auth0Refresh : (optional) Auth0 Refresh Token # message : (optional) A message handed by Identity Service when some error occurs states['MEMBER_REGISTRATION'] = url: '/member/registration?retUrl&utm_source&utm_medium&utm_campaign&userJWTToken&auth0Jwt&auth0Refresh&message&regSource' title: 'Register' params: { 'auth0Data', 'regForm' } controller : 'TCRegistrationController as vm' template: require('./views/tc/register.jade')() public: true states['MEMBER_REGISTRATION_SUCCESS'] = url: '/member/registration-success?retUrl' params: { 'ssoUser' } template: require('./views/tc/registered-successfully.jade')() controller: 'TCRegistrationSuccessController as vm' public: true states['MEMBER_FORGOT_PASSWORD'] = url: '/member/forgot-password' controller : 'TCResetPasswordController as vm' template : require('./views/tc/reset-password.jade')() public: true states['MEMBER_RESET_PASSWORD'] = url: '/member/reset-password?token&handle' controller : 'TCResetPasswordController as vm' template : require('./views/tc/reset-password.jade')() public: true # State parameters # retUrl : (required) URL to redirect after SSO # userJWTToken : (optional) v3 JWT Token # auth0Jwt : (optional) Auth0(v2) JWT Token # auth0Refresh : (optional) Auth0 Refresh Token # message : (optional) A message handed by Identity Service when some error occurs states['SOCIAL_CALLBACK'] = url: '/social-callback?retUrl&userJWTToken&auth0Jwt&auth0Refresh&message' template : require('./views/tc/social-callback')() controller : 'SSOCallbackController as vm' public: true states['CONNECT_LOGIN'] = url: '/connect?retUrl&handle&password' params: {'passwordReset'} controller : 'ConnectLoginController as vm' template: require('./views/connect/login')() public: true states['CONNECT_REGISTRATION'] = url: '/connect/registration?retUrl&userJWTToken&auth0Jwt&auth0Refresh&message' params: { 'auth0Data', 'regForm' } controller : 'ConnectRegistrationController as vm' template: require('./views/connect/registration.jade')() public: true states['CONNECT_REGISTRATION_SUCCESS'] = url: '/connect/registration-success' params: { 'ssoUser' } template: require('./views/connect/registration-success.jade')() controller: 'TCRegistrationSuccessController as vm' public: true states['CONNECT_PIN_VERIFICATION'] = url: '/connect/pin-verification?retUrl' params: {'email', 'username', 'password', 'userId', 'afterActivationURL'} controller : 'ConnectPinVerificationController as vm' template: require('./views/connect/pin-verification.jade')() public: true states['CONNECT_WELCOME'] = url: '/connect/welcome' params: {'email', 'username', 'password', 'userId', 'afterActivationURL'} controller : 'ConnectWelcomeController as vm' template: require('./views/connect/welcome.jade')() public: true states['CONNECT_FORGOT_PASSWORD'] = url: '/connect/forgot-password' controller : 'ConnectForgotPasswordController as vm' template : require('./views/connect/forgot-password.jade')() public: true states['CONNECT_RESET_PASSWORD'] = url: '/connect/reset-password?token&handle&retUrl' controller : 'ConnectResetPasswordController as vm' template : require('./views/connect/reset-password.jade')() public: true # State parameters # see SOCIAL_CALLBACK states['SSO_LOGIN'] = url: '/sso-login/?app&email&retUrl' params: { 'regForm' } template : require('./views/sso/sso-login')() controller : 'SSOLoginController as vm' public: true # State parameters # retUrl : (required) URL to redirect after SSO # userJWTToken : (optional) v3 JWT Token # auth0Jwt : (optional) Auth0(v2) JWT Token # auth0Refresh : (optional) Auth0 Refresh Token # message : (optional) A message handed by Identity Service when some error occurs states['SSO_CALLBACK'] = url: '/sso-callback?retUrl&userJWTToken&auth0Jwt&auth0Refresh&message' template : require('./views/sso/sso-callback')() controller : 'SSOCallbackController as vm' public: true states['UNAUTHORIZED'] = url: '/401', template : require('./views/401')() public: true # This must be the last one in the list states['otherwise'] = url: '*path', template : require('./views/404')() public: true for key, state of states $stateProvider.state key, state # Setup Auth0 (for Social Login) angularAuth0Provider.init({ domain: AUTH0_DOMAIN clientID: AUTH0_CLIENT_ID sso: false }, Auth0) config.$inject = [ '$locationProvider' '$stateProvider' 'angularAuth0Provider' ] angular.module('accounts').config config
true
`import Auth0 from "auth0-js";` `import { AUTH0_DOMAIN, AUTH0_CLIENT_ID } from "../core/constants.js"` 'use strict' config = ( $locationProvider $stateProvider angularAuth0Provider ) -> states = {} $locationProvider.html5Mode true # customer routes states['home'] = url : '/' title : 'Home' controller : 'HomeController as vm' template : require('./views/home')() # State parameters # app : tc|connect|etc.. # retUrl : URL to redirect after authentication # handle : direct login with handle/password # password : direct login with handle/password # return_to: URL of Zendesk to redirect after authentication. This is handed by Zendesk. # # Connect example: # /login?app=connect&retUrl=https%3A%2F%2Fconnect.topcoder.com # Direct login example: # /login?app=connect&handle=jdoe&password=PI:PASSWORD:<PASSWORD>END_PI&retUrl=https%3A%2F%2Fconnect.topcoder.com # Zendesk example: # /login?app=zendesk&return_to=https%3A%2F%2Ftopcoder.zendesk.com states['login'] = url: '/login?app&retUrl&handle&password&return_to' title: 'Login' controller : 'LoginController as vm' template: require('./views/login')() public: true # State parameters # retUrl : URL to redirect after logging out # message : A message handed by Zendesk when some error occurs # # Example: # /logout?retUrl=https%3A%2F%2Fconnect.topcoder.com # Zendesk example: # /logout?retUrl=https%3A%2F%2Ftopcoder.zendesk.com%2F # Zendesk Error example: # /logout?kind=error&message=User%20is%20invalid:%20External%20has%20already%20been%20taken&retUrl=https:%2F%2Fkohata.zendesk.com%2F states['logout'] = url: '/logout?retUrl&message' title: 'Logout' controller : 'LogoutController as vm' template: require('./views/logout')() public: true # State parameters # client_id : (required) ID for a client which is registered in the client database. # response_type: (required) Only "token" is supported. # redirect_uri : (required) Encoded URL to redirect after authentication. This should be registered in the client database. # state : (optional) # scope : (optional) Currently not used in anywhere. states['OAUTH'] = url: '/oauth?client_id&response_type&state&redirect_uri&scope' controller : 'OAuthController as vm' public: true states['MEMBER_LOGIN'] = url: '/member?retUrl&handle&password&return_to&client_id&response_type&state&redirect_uri&scope' title: 'Login' controller : 'TCLoginController as vm' template: require('./views/tc/login')() public: true # State parameters # retUrl : (required) URL to redirect after SSO # utm_source : (optional) UTM source for the registration # utm_medium : (optional) UTM medium for the registration # utm_campaign : (optional) UTM campaign for the registration # userJWTToken : (optional) v3 JWT Token # auth0Jwt : (optional) Auth0(v2) JWT Token # auth0Refresh : (optional) Auth0 Refresh Token # message : (optional) A message handed by Identity Service when some error occurs states['MEMBER_REGISTRATION'] = url: '/member/registration?retUrl&utm_source&utm_medium&utm_campaign&userJWTToken&auth0Jwt&auth0Refresh&message&regSource' title: 'Register' params: { 'auth0Data', 'regForm' } controller : 'TCRegistrationController as vm' template: require('./views/tc/register.jade')() public: true states['MEMBER_REGISTRATION_SUCCESS'] = url: '/member/registration-success?retUrl' params: { 'ssoUser' } template: require('./views/tc/registered-successfully.jade')() controller: 'TCRegistrationSuccessController as vm' public: true states['MEMBER_FORGOT_PASSWORD'] = url: '/member/forgot-password' controller : 'TCResetPasswordController as vm' template : require('./views/tc/reset-password.jade')() public: true states['MEMBER_RESET_PASSWORD'] = url: '/member/reset-password?token&handle' controller : 'TCResetPasswordController as vm' template : require('./views/tc/reset-password.jade')() public: true # State parameters # retUrl : (required) URL to redirect after SSO # userJWTToken : (optional) v3 JWT Token # auth0Jwt : (optional) Auth0(v2) JWT Token # auth0Refresh : (optional) Auth0 Refresh Token # message : (optional) A message handed by Identity Service when some error occurs states['SOCIAL_CALLBACK'] = url: '/social-callback?retUrl&userJWTToken&auth0Jwt&auth0Refresh&message' template : require('./views/tc/social-callback')() controller : 'SSOCallbackController as vm' public: true states['CONNECT_LOGIN'] = url: '/connect?retUrl&handle&password' params: {'passwordReset'} controller : 'ConnectLoginController as vm' template: require('./views/connect/login')() public: true states['CONNECT_REGISTRATION'] = url: '/connect/registration?retUrl&userJWTToken&auth0Jwt&auth0Refresh&message' params: { 'auth0Data', 'regForm' } controller : 'ConnectRegistrationController as vm' template: require('./views/connect/registration.jade')() public: true states['CONNECT_REGISTRATION_SUCCESS'] = url: '/connect/registration-success' params: { 'ssoUser' } template: require('./views/connect/registration-success.jade')() controller: 'TCRegistrationSuccessController as vm' public: true states['CONNECT_PIN_VERIFICATION'] = url: '/connect/pin-verification?retUrl' params: {'email', 'username', 'password', 'userId', 'afterActivationURL'} controller : 'ConnectPinVerificationController as vm' template: require('./views/connect/pin-verification.jade')() public: true states['CONNECT_WELCOME'] = url: '/connect/welcome' params: {'email', 'username', 'password', 'userId', 'afterActivationURL'} controller : 'ConnectWelcomeController as vm' template: require('./views/connect/welcome.jade')() public: true states['CONNECT_FORGOT_PASSWORD'] = url: '/connect/forgot-password' controller : 'ConnectForgotPasswordController as vm' template : require('./views/connect/forgot-password.jade')() public: true states['CONNECT_RESET_PASSWORD'] = url: '/connect/reset-password?token&handle&retUrl' controller : 'ConnectResetPasswordController as vm' template : require('./views/connect/reset-password.jade')() public: true # State parameters # see SOCIAL_CALLBACK states['SSO_LOGIN'] = url: '/sso-login/?app&email&retUrl' params: { 'regForm' } template : require('./views/sso/sso-login')() controller : 'SSOLoginController as vm' public: true # State parameters # retUrl : (required) URL to redirect after SSO # userJWTToken : (optional) v3 JWT Token # auth0Jwt : (optional) Auth0(v2) JWT Token # auth0Refresh : (optional) Auth0 Refresh Token # message : (optional) A message handed by Identity Service when some error occurs states['SSO_CALLBACK'] = url: '/sso-callback?retUrl&userJWTToken&auth0Jwt&auth0Refresh&message' template : require('./views/sso/sso-callback')() controller : 'SSOCallbackController as vm' public: true states['UNAUTHORIZED'] = url: '/401', template : require('./views/401')() public: true # This must be the last one in the list states['otherwise'] = url: '*path', template : require('./views/404')() public: true for key, state of states $stateProvider.state key, state # Setup Auth0 (for Social Login) angularAuth0Provider.init({ domain: AUTH0_DOMAIN clientID: AUTH0_CLIENT_ID sso: false }, Auth0) config.$inject = [ '$locationProvider' '$stateProvider' 'angularAuth0Provider' ] angular.module('accounts').config config