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": "ort: 0xd00d\n uuid: 'peter'\n token: 'i-could-eat'\n privateKey: @privateKey\n appOctoblu",
"end": 1649,
"score": 0.985289454460144,
"start": 1638,
"tag": "PASSWORD",
"value": "i-could-eat"
}
] | node_modules/endo-core/test/integration/static-schemas-controller-spec.coffee | ratokeshi/endo-google-cloud-platform | 0 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
fs = require 'fs'
Encryption = require 'meshblu-encryption'
path = require 'path'
request = require 'request'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
MockStrategy = require '../mock-strategy'
Server = require '../..'
describe 'static schemas', ->
beforeEach (done) ->
@privateKey = fs.readFileSync "#{__dirname}/../data/private-key.pem", 'utf8'
@encryption = Encryption.fromPem @privateKey
encrypted =
secrets:
credentials:
secret: 'this is secret'
@encrypted = @encryption.encrypt encrypted
@publicKey = @encryption.key.exportKey 'public'
@meshblu = shmock 0xd00d
enableDestroy @meshblu
@apiStrategy = new MockStrategy name: 'api'
@octobluStrategy = new MockStrategy name: 'octoblu'
@messageHandler = messageSchema: sinon.stub()
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic cGV0ZXI6aS1jb3VsZC1lYXQ="
.reply 200, {
options:
imageUrl: "http://this-is-an-image.exe"
}
@meshblu
.get '/publickey'
.reply 200, {@publicKey}
serverOptions =
logFn: ->
port: undefined,
disableLogging: true
apiStrategy: @apiStrategy
octobluStrategy: @octobluStrategy
messageHandler: @messageHandler
serviceUrl: 'http://octoblu.xxx'
deviceType: 'endo-endor'
meshbluConfig:
hostname: 'localhost'
protocol: 'http'
port: 0xd00d
uuid: 'peter'
token: 'i-could-eat'
privateKey: @privateKey
appOctobluHost: 'http://app.octoblu.xxx'
userDeviceManagerUrl: 'http://manage-my.endo'
staticSchemasPath: path.join(__dirname, '../fixtures/schemas')
meshbluPublicKeyUri: 'http://localhost:53261/publickey'
@server = new Server serverOptions
@server.run (error) =>
return done error if error?
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.destroy done
describe 'On GET /schemas/non-extant', ->
describe 'When no non-extant.cson or non-extant.json file is available', ->
beforeEach (done) ->
options =
json: true
baseUrl: "http://localhost:#{@server.address().port}"
request.get '/schemas/non-extant', options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404, JSON.stringify @body
it 'should return an error', ->
expect(@body).to.deep.equal {error: 'Could not find a schema for that path'}
describe 'On GET /schemas/configure', ->
describe 'When configure.cson is available at <path>/configure.cson', ->
beforeEach (done) ->
options =
json: true
baseUrl: "http://localhost:#{@server.address().port}"
request.get '/schemas/configure', options, (error, @response, @body) =>
done error
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200, JSON.stringify @body
it 'should return the configure schema', ->
expect(@body).to.deep.equal {foo: 'bar'}
| 198154 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
fs = require 'fs'
Encryption = require 'meshblu-encryption'
path = require 'path'
request = require 'request'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
MockStrategy = require '../mock-strategy'
Server = require '../..'
describe 'static schemas', ->
beforeEach (done) ->
@privateKey = fs.readFileSync "#{__dirname}/../data/private-key.pem", 'utf8'
@encryption = Encryption.fromPem @privateKey
encrypted =
secrets:
credentials:
secret: 'this is secret'
@encrypted = @encryption.encrypt encrypted
@publicKey = @encryption.key.exportKey 'public'
@meshblu = shmock 0xd00d
enableDestroy @meshblu
@apiStrategy = new MockStrategy name: 'api'
@octobluStrategy = new MockStrategy name: 'octoblu'
@messageHandler = messageSchema: sinon.stub()
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic cGV0ZXI6aS1jb3VsZC1lYXQ="
.reply 200, {
options:
imageUrl: "http://this-is-an-image.exe"
}
@meshblu
.get '/publickey'
.reply 200, {@publicKey}
serverOptions =
logFn: ->
port: undefined,
disableLogging: true
apiStrategy: @apiStrategy
octobluStrategy: @octobluStrategy
messageHandler: @messageHandler
serviceUrl: 'http://octoblu.xxx'
deviceType: 'endo-endor'
meshbluConfig:
hostname: 'localhost'
protocol: 'http'
port: 0xd00d
uuid: 'peter'
token: '<PASSWORD>'
privateKey: @privateKey
appOctobluHost: 'http://app.octoblu.xxx'
userDeviceManagerUrl: 'http://manage-my.endo'
staticSchemasPath: path.join(__dirname, '../fixtures/schemas')
meshbluPublicKeyUri: 'http://localhost:53261/publickey'
@server = new Server serverOptions
@server.run (error) =>
return done error if error?
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.destroy done
describe 'On GET /schemas/non-extant', ->
describe 'When no non-extant.cson or non-extant.json file is available', ->
beforeEach (done) ->
options =
json: true
baseUrl: "http://localhost:#{@server.address().port}"
request.get '/schemas/non-extant', options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404, JSON.stringify @body
it 'should return an error', ->
expect(@body).to.deep.equal {error: 'Could not find a schema for that path'}
describe 'On GET /schemas/configure', ->
describe 'When configure.cson is available at <path>/configure.cson', ->
beforeEach (done) ->
options =
json: true
baseUrl: "http://localhost:#{@server.address().port}"
request.get '/schemas/configure', options, (error, @response, @body) =>
done error
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200, JSON.stringify @body
it 'should return the configure schema', ->
expect(@body).to.deep.equal {foo: 'bar'}
| true | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
fs = require 'fs'
Encryption = require 'meshblu-encryption'
path = require 'path'
request = require 'request'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
MockStrategy = require '../mock-strategy'
Server = require '../..'
describe 'static schemas', ->
beforeEach (done) ->
@privateKey = fs.readFileSync "#{__dirname}/../data/private-key.pem", 'utf8'
@encryption = Encryption.fromPem @privateKey
encrypted =
secrets:
credentials:
secret: 'this is secret'
@encrypted = @encryption.encrypt encrypted
@publicKey = @encryption.key.exportKey 'public'
@meshblu = shmock 0xd00d
enableDestroy @meshblu
@apiStrategy = new MockStrategy name: 'api'
@octobluStrategy = new MockStrategy name: 'octoblu'
@messageHandler = messageSchema: sinon.stub()
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic cGV0ZXI6aS1jb3VsZC1lYXQ="
.reply 200, {
options:
imageUrl: "http://this-is-an-image.exe"
}
@meshblu
.get '/publickey'
.reply 200, {@publicKey}
serverOptions =
logFn: ->
port: undefined,
disableLogging: true
apiStrategy: @apiStrategy
octobluStrategy: @octobluStrategy
messageHandler: @messageHandler
serviceUrl: 'http://octoblu.xxx'
deviceType: 'endo-endor'
meshbluConfig:
hostname: 'localhost'
protocol: 'http'
port: 0xd00d
uuid: 'peter'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
privateKey: @privateKey
appOctobluHost: 'http://app.octoblu.xxx'
userDeviceManagerUrl: 'http://manage-my.endo'
staticSchemasPath: path.join(__dirname, '../fixtures/schemas')
meshbluPublicKeyUri: 'http://localhost:53261/publickey'
@server = new Server serverOptions
@server.run (error) =>
return done error if error?
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.destroy done
describe 'On GET /schemas/non-extant', ->
describe 'When no non-extant.cson or non-extant.json file is available', ->
beforeEach (done) ->
options =
json: true
baseUrl: "http://localhost:#{@server.address().port}"
request.get '/schemas/non-extant', options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404, JSON.stringify @body
it 'should return an error', ->
expect(@body).to.deep.equal {error: 'Could not find a schema for that path'}
describe 'On GET /schemas/configure', ->
describe 'When configure.cson is available at <path>/configure.cson', ->
beforeEach (done) ->
options =
json: true
baseUrl: "http://localhost:#{@server.address().port}"
request.get '/schemas/configure', options, (error, @response, @body) =>
done error
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200, JSON.stringify @body
it 'should return the configure schema', ->
expect(@body).to.deep.equal {foo: 'bar'}
|
[
{
"context": "s\",\"Prov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"",
"end": 508,
"score": 0.7673213481903076,
"start": 505,
"tag": "NAME",
"value": "Dan"
},
{
"context": "ov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"",
"end": 514,
"score": 0.658421516418457,
"start": 511,
"tag": "NAME",
"value": "Hos"
},
{
"context": "ccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"",
"end": 521,
"score": 0.8425531387329102,
"start": 517,
"tag": "NAME",
"value": "Joel"
},
{
"context": "ong\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\"",
"end": 525,
"score": 0.5400594472885132,
"start": 524,
"tag": "NAME",
"value": "A"
},
{
"context": "sa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",",
"end": 533,
"score": 0.5387206077575684,
"start": 531,
"tag": "NAME",
"value": "Ob"
},
{
"context": "r\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Mat",
"end": 543,
"score": 0.8484860062599182,
"start": 538,
"tag": "NAME",
"value": "Jonah"
},
{
"context": ",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Ma",
"end": 549,
"score": 0.8100711703300476,
"start": 546,
"tag": "NAME",
"value": "Mic"
},
{
"context": "\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",",
"end": 553,
"score": 0.6194931864738464,
"start": 552,
"tag": "NAME",
"value": "N"
},
{
"context": "d\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",",
"end": 587,
"score": 0.5851761102676392,
"start": 584,
"tag": "NAME",
"value": "Mal"
},
{
"context": "nah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",",
"end": 594,
"score": 0.9216086268424988,
"start": 590,
"tag": "NAME",
"value": "Matt"
},
{
"context": "ic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"",
"end": 601,
"score": 0.946517825126648,
"start": 597,
"tag": "NAME",
"value": "Mark"
},
{
"context": "h\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"Eph\",\"P",
"end": 608,
"score": 0.8618631362915039,
"start": 604,
"tag": "NAME",
"value": "Luke"
},
{
"context": "\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"Eph\",\"Phil\",\"C",
"end": 615,
"score": 0.7068722248077393,
"start": 611,
"tag": "NAME",
"value": "John"
}
] | lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/template/spec.coffee | saiba-mais/bible-lessons | 149 | bcv_parser = require("../../js/$LANG_bcv_parser.js").bcv_parser
describe "Parsing", ->
p = {}
beforeEach ->
p = new bcv_parser
p.options.osis_compaction_strategy = "b"
p.options.sequence_combination_strategy = "combine"
it "should round-trip OSIS references", ->
p.set_options osis_compaction_strategy: "bc"
books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","Dan","Hos","Joel","Amos","Obad","Jonah","Mic","Nah","Hab","Zeph","Hag","Zech","Mal","Matt","Mark","Luke","John","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
it "should round-trip OSIS Apocrypha references", ->
p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b"
p.include_apocrypha true
books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
p.set_options ps151_strategy: "bc"
expect(p.parse("Ps151.1").osis()).toEqual "Ps.151"
expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1"
expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2"
p.include_apocrypha false
for book in books
bc = book + ".1"
expect(p.parse(bc).osis()).toEqual ""
it "should handle a preceding character", ->
expect(p.parse(" Gen 1").osis()).toEqual "Gen.1"
expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3"
expect(p.parse("1Ps 1").osis()).toEqual ""
expect(p.parse("11Sam 1").osis()).toEqual ""
$BOOK_TESTS
describe "Miscellaneous tests", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should return the expected language", ->
expect(p.languages).toEqual $LANG_ISOS
$MISC_TESTS
| 24589 | bcv_parser = require("../../js/$LANG_bcv_parser.js").bcv_parser
describe "Parsing", ->
p = {}
beforeEach ->
p = new bcv_parser
p.options.osis_compaction_strategy = "b"
p.options.sequence_combination_strategy = "combine"
it "should round-trip OSIS references", ->
p.set_options osis_compaction_strategy: "bc"
books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","<NAME>","<NAME>","<NAME>","<NAME>mos","<NAME>ad","<NAME>","<NAME>","<NAME>ah","Hab","Zeph","Hag","Zech","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
it "should round-trip OSIS Apocrypha references", ->
p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b"
p.include_apocrypha true
books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
p.set_options ps151_strategy: "bc"
expect(p.parse("Ps151.1").osis()).toEqual "Ps.151"
expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1"
expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2"
p.include_apocrypha false
for book in books
bc = book + ".1"
expect(p.parse(bc).osis()).toEqual ""
it "should handle a preceding character", ->
expect(p.parse(" Gen 1").osis()).toEqual "Gen.1"
expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3"
expect(p.parse("1Ps 1").osis()).toEqual ""
expect(p.parse("11Sam 1").osis()).toEqual ""
$BOOK_TESTS
describe "Miscellaneous tests", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should return the expected language", ->
expect(p.languages).toEqual $LANG_ISOS
$MISC_TESTS
| true | bcv_parser = require("../../js/$LANG_bcv_parser.js").bcv_parser
describe "Parsing", ->
p = {}
beforeEach ->
p = new bcv_parser
p.options.osis_compaction_strategy = "b"
p.options.sequence_combination_strategy = "combine"
it "should round-trip OSIS references", ->
p.set_options osis_compaction_strategy: "bc"
books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PImos","PI:NAME:<NAME>END_PIad","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIah","Hab","Zeph","Hag","Zech","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
it "should round-trip OSIS Apocrypha references", ->
p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b"
p.include_apocrypha true
books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
p.set_options ps151_strategy: "bc"
expect(p.parse("Ps151.1").osis()).toEqual "Ps.151"
expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1"
expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2"
p.include_apocrypha false
for book in books
bc = book + ".1"
expect(p.parse(bc).osis()).toEqual ""
it "should handle a preceding character", ->
expect(p.parse(" Gen 1").osis()).toEqual "Gen.1"
expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3"
expect(p.parse("1Ps 1").osis()).toEqual ""
expect(p.parse("11Sam 1").osis()).toEqual ""
$BOOK_TESTS
describe "Miscellaneous tests", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should return the expected language", ->
expect(p.languages).toEqual $LANG_ISOS
$MISC_TESTS
|
[
{
"context": " ->\n User.updateProfile id,\n password: password\n .then ->\n console.log 'success'\n ",
"end": 550,
"score": 0.9985899329185486,
"start": 542,
"tag": "PASSWORD",
"value": "password"
}
] | frontend/scripts/main-controller.coffee | rao1219/Vedio | 0 | angular.module 'vsvs'
.controller 'MainController', [
'$rootScope'
'$scope'
'ngProgressLite'
'Session'
'User'
($rootScope, $scope, ngProgressLite, Session, User) ->
# TODO debugging
# TODO set session or get /session/me on start
if not Session.initialized
Session.updateStatus()
@currentSession = Session
@getProfile = (id) ->
User.getProfile(id)
.then (e) ->
$scope.inputIDData = JSON.stringify e
@updateProfile = (id, password) ->
User.updateProfile id,
password: password
.then ->
console.log 'success'
, ->
console.log 'failed'
$rootScope.$on '$stateChangeStart',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.start()
$rootScope.$on '$stateChangeSuccess',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.inc()
$rootScope.$on '$stateChangeError',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.set(0)
$rootScope.$on '$viewContentLoading',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.inc()
$rootScope.$on '$viewContentLoaded',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.done()
return
]
| 218408 | angular.module 'vsvs'
.controller 'MainController', [
'$rootScope'
'$scope'
'ngProgressLite'
'Session'
'User'
($rootScope, $scope, ngProgressLite, Session, User) ->
# TODO debugging
# TODO set session or get /session/me on start
if not Session.initialized
Session.updateStatus()
@currentSession = Session
@getProfile = (id) ->
User.getProfile(id)
.then (e) ->
$scope.inputIDData = JSON.stringify e
@updateProfile = (id, password) ->
User.updateProfile id,
password: <PASSWORD>
.then ->
console.log 'success'
, ->
console.log 'failed'
$rootScope.$on '$stateChangeStart',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.start()
$rootScope.$on '$stateChangeSuccess',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.inc()
$rootScope.$on '$stateChangeError',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.set(0)
$rootScope.$on '$viewContentLoading',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.inc()
$rootScope.$on '$viewContentLoaded',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.done()
return
]
| true | angular.module 'vsvs'
.controller 'MainController', [
'$rootScope'
'$scope'
'ngProgressLite'
'Session'
'User'
($rootScope, $scope, ngProgressLite, Session, User) ->
# TODO debugging
# TODO set session or get /session/me on start
if not Session.initialized
Session.updateStatus()
@currentSession = Session
@getProfile = (id) ->
User.getProfile(id)
.then (e) ->
$scope.inputIDData = JSON.stringify e
@updateProfile = (id, password) ->
User.updateProfile id,
password: PI:PASSWORD:<PASSWORD>END_PI
.then ->
console.log 'success'
, ->
console.log 'failed'
$rootScope.$on '$stateChangeStart',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.start()
$rootScope.$on '$stateChangeSuccess',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.inc()
$rootScope.$on '$stateChangeError',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.set(0)
$rootScope.$on '$viewContentLoading',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.inc()
$rootScope.$on '$viewContentLoaded',
(event, toState, toParams, fromState, fromParams) ->
ngProgressLite.done()
return
]
|
[
{
"context": "esolution\n if @selectedHero.get('name') in ['Knight', 'Robot Walker'] # These are too big, so shrink",
"end": 14468,
"score": 0.9996364116668701,
"start": 14462,
"tag": "NAME",
"value": "Knight"
},
{
"context": " if @selectedHero.get('name') in ['Knight', 'Robot Walker'] # These are too big, so shrink them.\n m",
"end": 14484,
"score": 0.9996203780174255,
"start": 14472,
"tag": "NAME",
"value": "Robot Walker"
}
] | app/views/game-menu/InventoryView.coffee | enricpc/codecombat | 0 | CocoView = require 'views/kinds/CocoView'
template = require 'templates/game-menu/inventory-view'
{me} = require 'lib/auth'
ThangType = require 'models/ThangType'
CocoCollection = require 'collections/CocoCollection'
ItemView = require './ItemView'
SpriteBuilder = require 'lib/sprites/SpriteBuilder'
module.exports = class InventoryView extends CocoView
id: 'inventory-view'
className: 'tab-pane'
template: template
slots: ['head', 'eyes', 'neck', 'torso', 'wrists', 'gloves', 'left-ring', 'right-ring', 'right-hand', 'left-hand', 'waist', 'feet', 'spellbook', 'programming-book', 'pet', 'minion', 'misc-0', 'misc-1', 'misc-2', 'misc-3', 'misc-4']
events:
'click .item-slot': 'onItemSlotClick'
'click #available-equipment .list-group-item': 'onAvailableItemClick'
'dblclick #available-equipment .list-group-item': 'onAvailableItemDoubleClick'
'dblclick .item-slot .item-view': 'onEquippedItemDoubleClick'
'click #swap-button': 'onClickSwapButton'
subscriptions:
'level:hero-selection-updated': 'onHeroSelectionUpdated'
shortcuts:
'esc': 'clearSelection'
initialize: (options) ->
super(arguments...)
@items = new CocoCollection([], {model: ThangType})
@equipment = options.equipment or @options.session?.get('heroConfig')?.inventory or me.get('heroConfig')?.inventory or {}
@equipment = $.extend true, {}, @equipment
@assignLevelEquipment()
@items.url = '/db/thang.type?view=items&project=name,components,original,rasterIcon'
@supermodel.loadCollection(@items, 'items')
destroy: ->
@stage?.removeAllChildren()
super()
onLoaded: ->
item.notInLevel = true for item in @items.models
super()
getRenderData: (context={}) ->
context = super(context)
context.equipped = _.values(@equipment)
context.items = @items.models
for item in @items.models
item.classes = item.getAllowedSlots()
item.classes.push 'equipped' if item.get('original') in context.equipped
item.classes.push 'restricted' if @allowedItems and not (item.get('original') in @allowedItems)
@items.models.sort (a, b) -> ('restricted' in a.classes) - ('restricted' in b.classes)
context.slots = @slots
context.equipment = _.clone @equipment
for slot, itemOriginal of context.equipment
item = _.find @items.models, (item) -> item.get('original') is itemOriginal
context.equipment[slot] = item
context
afterRender: ->
super()
return unless @supermodel.finished()
keys = (item.get('original') for item in @items.models)
itemMap = _.zipObject keys, @items.models
# Fill in equipped items
for slottedItemStub in @$el.find('.replace-me')
itemID = $(slottedItemStub).data('item-id')
item = itemMap[itemID]
itemView = new ItemView({item: item, includes: {}})
itemView.render()
$(slottedItemStub).replaceWith(itemView.$el)
@registerSubView(itemView)
for availableItemEl in @$el.find('#available-equipment .list-group-item')
itemID = $(availableItemEl).data('item-id')
item = itemMap[itemID]
itemView = new ItemView({item: item, includes: {name: true}})
itemView.render()
$(availableItemEl).append(itemView.$el)
@registerSubView(itemView)
continue if $(availableItemEl).hasClass 'restricted'
dragHelper = itemView.$el.find('img').clone().addClass('draggable-item')
do (dragHelper, itemView) =>
itemView.$el.draggable
revert: 'invalid'
appendTo: @$el
cursorAt: {left: 35.5, top: 35.5}
helper: -> dragHelper
revertDuration: 200
distance: 10
scroll: false
zIndex: 100
itemView.$el.on 'dragstart', =>
@onAvailableItemClick target: itemView.$el.parent() unless itemView.$el.parent().hasClass 'active'
for itemSlot in @$el.find '.item-slot'
slot = $(itemSlot).data 'slot'
$(itemSlot).find('.placeholder').css('background-image', "url(/images/pages/game-menu/slot-#{slot}.png)")
do (slot) =>
$(itemSlot).droppable
drop: (e, ui) => @onAvailableItemDoubleClick()
accept: (el) -> $(el).parent().hasClass slot
activeClass: 'droppable'
hoverClass: 'droppable-hover'
tolerance: 'touch'
@$el.find('#selected-items').hide() # Hide until one is selected
@delegateEvents()
afterInsert: ->
super()
@canvasWidth = @$el.find('canvas').innerWidth()
@canvasHeight = @$el.find('canvas').innerHeight()
clearSelection: ->
@$el.find('.item-slot.selected').removeClass 'selected'
@$el.find('.list-group-item').removeClass('active')
@onSelectionChanged()
onItemSlotClick: (e) ->
slot = $(e.target).closest('.item-slot')
wasActive = slot.hasClass('selected')
@unselectAllSlots()
@unselectAllAvailableEquipment() if slot.hasClass('disabled')
if wasActive
@hideSelectedSlotItem()
@unselectAllAvailableEquipment()
else
@selectSlot(slot)
@onSelectionChanged()
onAvailableItemClick: (e) ->
itemContainer = $(e.target).closest('.list-group-item')
return if itemContainer.hasClass 'restricted'
wasActive = itemContainer.hasClass 'active'
@unselectAllAvailableEquipment()
@selectAvailableItem(itemContainer) unless wasActive
@onSelectionChanged()
onAvailableItemDoubleClick: (e) ->
if e
itemContainer = $(e.target).closest('.list-group-item')
return if itemContainer.hasClass 'restricted'
@selectAvailableItem itemContainer
@onSelectionChanged()
slot = @getSelectedSlot()
slot = @$el.find('.item-slot:not(.disabled):first') if not slot.length
@unequipItemFromSlot(slot)
@equipSelectedItemToSlot(slot)
@onSelectionChanged()
onEquippedItemDoubleClick: (e) ->
@unselectAllAvailableEquipment()
slot = $(e.target).closest('.item-slot')
@selectAvailableItem(@unequipItemFromSlot(slot))
@onSelectionChanged()
onClickSwapButton: ->
slot = @getSelectedSlot()
selectedItemContainer = @$el.find('#available-equipment .list-group-item.active')
return unless slot[0] or selectedItemContainer[0]
slot = @$el.find('.item-slot:not(.disabled):first') if not slot.length
itemContainer = @unequipItemFromSlot(slot)
@equipSelectedItemToSlot(slot)
@selectAvailableItem(itemContainer)
@selectSlot(slot)
@onSelectionChanged()
getSelectedSlot: ->
@$el.find('#equipped .item-slot.selected')
unselectAllAvailableEquipment: ->
@$el.find('#available-equipment .list-group-item').removeClass('active')
unselectAllSlots: ->
@$el.find('#equipped .item-slot.selected').removeClass('selected')
selectSlot: (slot) ->
slot.addClass('selected')
getSlot: (name) ->
@$el.find(".item-slot[data-slot=#{name}]")
getSelectedAvailableItemContainer: ->
@$el.find('#available-equipment .list-group-item.active')
getAvailableItemContainer: (itemID) ->
@$el.find("#available-equipment .list-group-item[data-item-id='#{itemID}']")
selectAvailableItem: (itemContainer) ->
itemContainer?.addClass('active')
unequipItemFromSlot: (slot) ->
itemIDToUnequip = slot.find('.item-view').data('item-id')
return unless itemIDToUnequip
slot.find('.item-view').detach()
for el in @$el.find('#available-equipment .list-group-item')
itemID = $(el).find('.item-view').data('item-id')
if itemID is itemIDToUnequip
return $(el).removeClass('equipped')
equipSelectedItemToSlot: (slot) ->
selectedItemContainer = @getSelectedAvailableItemContainer()
newItemHTML = selectedItemContainer.html()
selectedItemContainer.addClass('equipped')
slotContainer = slot.find('.item-container')
slotContainer.html(newItemHTML)
slotContainer.find('.item-view').data('item-id', selectedItemContainer.find('.item-view').data('item-id'))
@$el.find('.list-group-item').removeClass('active')
onSelectionChanged: ->
@$el.find('.item-slot').show()
selectedSlot = @$el.find('.item-slot.selected')
selectedItem = @$el.find('#available-equipment .list-group-item.active')
if selectedSlot.length
@$el.find('#available-equipment .list-group-item').hide()
count = @$el.find("#available-equipment .list-group-item.#{selectedSlot.data('slot')}").show().length
@$el.find('#stash-description').text "#{count} #{selectedSlot.data('slot')} items owned"
selectedSlotItemID = selectedSlot.find('.item-view').data('item-id')
if selectedSlotItemID
item = _.find @items.models, {id:selectedSlotItemID}
@showSelectedSlotItem(item)
else
@hideSelectedSlotItem()
else
count = @$el.find('#available-equipment .list-group-item').show().length
@$el.find('#stash-description').text "#{count} items owned"
@$el.find('#available-equipment .list-group-item.equipped').hide()
@$el.find('.item-slot').removeClass('disabled')
if selectedItem.length
item = _.find @items.models, {id:selectedItem.find('.item-view').data('item-id')}
# update which slots are enabled
allowedSlots = item.getAllowedSlots()
for slotEl in @$el.find('.item-slot')
slotName = $(slotEl).data('slot')
if slotName not in allowedSlots
$(slotEl).addClass('disabled')
@showSelectedAvailableItem(item)
else
@hideSelectedAvailableItem()
@delegateEvents()
showSelectedSlotItem: (item) ->
if not @selectedEquippedItemView
@selectedEquippedItemView = new ItemView({
item: item, includes: {name: true, stats: true, props: true}})
@insertSubView(@selectedEquippedItemView, @$el.find('#selected-equipped-item .item-view-stub'))
else
@selectedEquippedItemView.$el.show()
@selectedEquippedItemView.item = item
@selectedEquippedItemView.render()
@$el.find('#selected-items').show()
hideSelectedSlotItem: ->
@selectedEquippedItemView?.$el.hide()
@$el.find('#selected-items').hide() unless @selectedEquippedItemView?.$el?.is(':visible')
showSelectedAvailableItem: (item) ->
if not @selectedAvailableItemView
@selectedAvailableItemView = new ItemView({
item: item, includes: {name: true, stats: true, props: true}})
@insertSubView(@selectedAvailableItemView, @$el.find('#selected-available-item .item-view-stub'))
else
@selectedAvailableItemView.$el.show()
@selectedAvailableItemView.item = item
@selectedAvailableItemView.render()
@$el.find('#selected-items').show()
hideSelectedAvailableItem: ->
@selectedAvailableItemView?.$el.hide()
@$el.find('#selected-items').hide() unless @selectedEquippedItemView?.$el?.is(':visible')
getCurrentEquipmentConfig: ->
config = {}
for slot in @$el.find('.item-slot')
slotName = $(slot).data('slot')
slotItemID = $(slot).find('.item-view').data('item-id')
continue unless slotItemID
item = _.find @items.models, {id:slotItemID}
config[slotName] = item.get('original')
config
assignLevelEquipment: ->
# This is temporary, until we have a more general way of awarding items and configuring needed/restricted items per level.
gear =
'simple-boots': '53e237bf53457600003e3f05'
'longsword': '53e218d853457600003e3ebe'
'leather-tunic': '53e22eac53457600003e3efc'
#'leather-boots': '53e2384453457600003e3f07'
'programmaticon-i': '53e4108204c00d4607a89f78'
'crude-glasses': '53e238df53457600003e3f0b'
'builders-hammer': '53f4e6e3d822c23505b74f42'
gearByLevel =
'dungeons-of-kithgard': {feet: 'simple-boots'}
'gems-in-the-deep': {feet: 'simple-boots'}
'shadow-guard': {feet: 'simple-boots'}
'true-names': {feet: 'simple-boots', 'right-hand': 'longsword'}
'the-raised-sword': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic'}
'the-first-kithmaze': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i'}
'the-second-kithmaze': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i'}
'new-sight': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i'}
'lowly-kithmen': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'a-bolt-in-the-dark': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'the-final-kithmaze': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'kithgard-gates': {feet: 'simple-boots', 'right-hand': 'builders-hammer', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'defence-of-plainswood': {feet: 'simple-boots', 'right-hand': 'builders-hammer', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
necessaryGear = gearByLevel[@options.levelID]
for slot, item of necessaryGear ? {}
@equipment[slot] ?= gear[item]
# Restrict available items to those that would be available by this item.
@allowedItems = []
for level, items of gearByLevel
for slot, item of items
@allowedItems.push gear[item] unless gear[item] in @allowedItems
break if level is @options.levelID
onHeroSelectionUpdated: (e) ->
@selectedHero = e.hero
@loadHero()
loadHero: ->
return unless @selectedHero and not @$el.hasClass 'secret'
@stage?.removeAllChildren()
if @selectedHero.loaded and movieClip = @movieClips?[@selectedHero.get('original')]
@stage.addChild(movieClip)
@stage.update()
return
onLoaded = =>
return unless canvas = $(".equipped-hero-canvas")
@canvasWidth ||= canvas.width()
@canvasHeight ||= canvas.height()
canvas.prop width: @canvasWidth, height: @canvasHeight
builder = new SpriteBuilder(@selectedHero)
movieClip = builder.buildMovieClip(@selectedHero.get('actions').attack?.animation ? @selectedHero.get('actions').idle.animation)
movieClip.scaleX = movieClip.scaleY = canvas.prop('height') / 120 # Average hero height is ~110px at normal resolution
if @selectedHero.get('name') in ['Knight', 'Robot Walker'] # These are too big, so shrink them.
movieClip.scaleX *= 0.7
movieClip.scaleY *= 0.7
movieClip.regX = -@selectedHero.get('positions').registration.x
movieClip.regY = -@selectedHero.get('positions').registration.y
movieClip.x = canvas.prop('width') * 0.5
movieClip.y = canvas.prop('height') * 0.95 # This is where the feet go.
movieClip.gotoAndPlay 0
@stage ?= new createjs.Stage(canvas[0])
@stage.addChild movieClip
@stage.update()
@movieClips ?= {}
@movieClips[@selectedHero.get('original')] = movieClip
if @selectedHero.loaded
if @selectedHero.isFullyLoaded()
_.defer onLoaded
else
console.error 'Hmm, trying to render a hero we have not loaded...?', @selectedHero
else
@listenToOnce @selectedHero, 'sync', onLoaded
onShown: ->
# Called when we switch tabs to this within the modal
@loadHero()
onHidden: ->
# Called when the modal itself is dismissed
| 70714 | CocoView = require 'views/kinds/CocoView'
template = require 'templates/game-menu/inventory-view'
{me} = require 'lib/auth'
ThangType = require 'models/ThangType'
CocoCollection = require 'collections/CocoCollection'
ItemView = require './ItemView'
SpriteBuilder = require 'lib/sprites/SpriteBuilder'
module.exports = class InventoryView extends CocoView
id: 'inventory-view'
className: 'tab-pane'
template: template
slots: ['head', 'eyes', 'neck', 'torso', 'wrists', 'gloves', 'left-ring', 'right-ring', 'right-hand', 'left-hand', 'waist', 'feet', 'spellbook', 'programming-book', 'pet', 'minion', 'misc-0', 'misc-1', 'misc-2', 'misc-3', 'misc-4']
events:
'click .item-slot': 'onItemSlotClick'
'click #available-equipment .list-group-item': 'onAvailableItemClick'
'dblclick #available-equipment .list-group-item': 'onAvailableItemDoubleClick'
'dblclick .item-slot .item-view': 'onEquippedItemDoubleClick'
'click #swap-button': 'onClickSwapButton'
subscriptions:
'level:hero-selection-updated': 'onHeroSelectionUpdated'
shortcuts:
'esc': 'clearSelection'
initialize: (options) ->
super(arguments...)
@items = new CocoCollection([], {model: ThangType})
@equipment = options.equipment or @options.session?.get('heroConfig')?.inventory or me.get('heroConfig')?.inventory or {}
@equipment = $.extend true, {}, @equipment
@assignLevelEquipment()
@items.url = '/db/thang.type?view=items&project=name,components,original,rasterIcon'
@supermodel.loadCollection(@items, 'items')
destroy: ->
@stage?.removeAllChildren()
super()
onLoaded: ->
item.notInLevel = true for item in @items.models
super()
getRenderData: (context={}) ->
context = super(context)
context.equipped = _.values(@equipment)
context.items = @items.models
for item in @items.models
item.classes = item.getAllowedSlots()
item.classes.push 'equipped' if item.get('original') in context.equipped
item.classes.push 'restricted' if @allowedItems and not (item.get('original') in @allowedItems)
@items.models.sort (a, b) -> ('restricted' in a.classes) - ('restricted' in b.classes)
context.slots = @slots
context.equipment = _.clone @equipment
for slot, itemOriginal of context.equipment
item = _.find @items.models, (item) -> item.get('original') is itemOriginal
context.equipment[slot] = item
context
afterRender: ->
super()
return unless @supermodel.finished()
keys = (item.get('original') for item in @items.models)
itemMap = _.zipObject keys, @items.models
# Fill in equipped items
for slottedItemStub in @$el.find('.replace-me')
itemID = $(slottedItemStub).data('item-id')
item = itemMap[itemID]
itemView = new ItemView({item: item, includes: {}})
itemView.render()
$(slottedItemStub).replaceWith(itemView.$el)
@registerSubView(itemView)
for availableItemEl in @$el.find('#available-equipment .list-group-item')
itemID = $(availableItemEl).data('item-id')
item = itemMap[itemID]
itemView = new ItemView({item: item, includes: {name: true}})
itemView.render()
$(availableItemEl).append(itemView.$el)
@registerSubView(itemView)
continue if $(availableItemEl).hasClass 'restricted'
dragHelper = itemView.$el.find('img').clone().addClass('draggable-item')
do (dragHelper, itemView) =>
itemView.$el.draggable
revert: 'invalid'
appendTo: @$el
cursorAt: {left: 35.5, top: 35.5}
helper: -> dragHelper
revertDuration: 200
distance: 10
scroll: false
zIndex: 100
itemView.$el.on 'dragstart', =>
@onAvailableItemClick target: itemView.$el.parent() unless itemView.$el.parent().hasClass 'active'
for itemSlot in @$el.find '.item-slot'
slot = $(itemSlot).data 'slot'
$(itemSlot).find('.placeholder').css('background-image', "url(/images/pages/game-menu/slot-#{slot}.png)")
do (slot) =>
$(itemSlot).droppable
drop: (e, ui) => @onAvailableItemDoubleClick()
accept: (el) -> $(el).parent().hasClass slot
activeClass: 'droppable'
hoverClass: 'droppable-hover'
tolerance: 'touch'
@$el.find('#selected-items').hide() # Hide until one is selected
@delegateEvents()
afterInsert: ->
super()
@canvasWidth = @$el.find('canvas').innerWidth()
@canvasHeight = @$el.find('canvas').innerHeight()
clearSelection: ->
@$el.find('.item-slot.selected').removeClass 'selected'
@$el.find('.list-group-item').removeClass('active')
@onSelectionChanged()
onItemSlotClick: (e) ->
slot = $(e.target).closest('.item-slot')
wasActive = slot.hasClass('selected')
@unselectAllSlots()
@unselectAllAvailableEquipment() if slot.hasClass('disabled')
if wasActive
@hideSelectedSlotItem()
@unselectAllAvailableEquipment()
else
@selectSlot(slot)
@onSelectionChanged()
onAvailableItemClick: (e) ->
itemContainer = $(e.target).closest('.list-group-item')
return if itemContainer.hasClass 'restricted'
wasActive = itemContainer.hasClass 'active'
@unselectAllAvailableEquipment()
@selectAvailableItem(itemContainer) unless wasActive
@onSelectionChanged()
onAvailableItemDoubleClick: (e) ->
if e
itemContainer = $(e.target).closest('.list-group-item')
return if itemContainer.hasClass 'restricted'
@selectAvailableItem itemContainer
@onSelectionChanged()
slot = @getSelectedSlot()
slot = @$el.find('.item-slot:not(.disabled):first') if not slot.length
@unequipItemFromSlot(slot)
@equipSelectedItemToSlot(slot)
@onSelectionChanged()
onEquippedItemDoubleClick: (e) ->
@unselectAllAvailableEquipment()
slot = $(e.target).closest('.item-slot')
@selectAvailableItem(@unequipItemFromSlot(slot))
@onSelectionChanged()
onClickSwapButton: ->
slot = @getSelectedSlot()
selectedItemContainer = @$el.find('#available-equipment .list-group-item.active')
return unless slot[0] or selectedItemContainer[0]
slot = @$el.find('.item-slot:not(.disabled):first') if not slot.length
itemContainer = @unequipItemFromSlot(slot)
@equipSelectedItemToSlot(slot)
@selectAvailableItem(itemContainer)
@selectSlot(slot)
@onSelectionChanged()
getSelectedSlot: ->
@$el.find('#equipped .item-slot.selected')
unselectAllAvailableEquipment: ->
@$el.find('#available-equipment .list-group-item').removeClass('active')
unselectAllSlots: ->
@$el.find('#equipped .item-slot.selected').removeClass('selected')
selectSlot: (slot) ->
slot.addClass('selected')
getSlot: (name) ->
@$el.find(".item-slot[data-slot=#{name}]")
getSelectedAvailableItemContainer: ->
@$el.find('#available-equipment .list-group-item.active')
getAvailableItemContainer: (itemID) ->
@$el.find("#available-equipment .list-group-item[data-item-id='#{itemID}']")
selectAvailableItem: (itemContainer) ->
itemContainer?.addClass('active')
unequipItemFromSlot: (slot) ->
itemIDToUnequip = slot.find('.item-view').data('item-id')
return unless itemIDToUnequip
slot.find('.item-view').detach()
for el in @$el.find('#available-equipment .list-group-item')
itemID = $(el).find('.item-view').data('item-id')
if itemID is itemIDToUnequip
return $(el).removeClass('equipped')
equipSelectedItemToSlot: (slot) ->
selectedItemContainer = @getSelectedAvailableItemContainer()
newItemHTML = selectedItemContainer.html()
selectedItemContainer.addClass('equipped')
slotContainer = slot.find('.item-container')
slotContainer.html(newItemHTML)
slotContainer.find('.item-view').data('item-id', selectedItemContainer.find('.item-view').data('item-id'))
@$el.find('.list-group-item').removeClass('active')
onSelectionChanged: ->
@$el.find('.item-slot').show()
selectedSlot = @$el.find('.item-slot.selected')
selectedItem = @$el.find('#available-equipment .list-group-item.active')
if selectedSlot.length
@$el.find('#available-equipment .list-group-item').hide()
count = @$el.find("#available-equipment .list-group-item.#{selectedSlot.data('slot')}").show().length
@$el.find('#stash-description').text "#{count} #{selectedSlot.data('slot')} items owned"
selectedSlotItemID = selectedSlot.find('.item-view').data('item-id')
if selectedSlotItemID
item = _.find @items.models, {id:selectedSlotItemID}
@showSelectedSlotItem(item)
else
@hideSelectedSlotItem()
else
count = @$el.find('#available-equipment .list-group-item').show().length
@$el.find('#stash-description').text "#{count} items owned"
@$el.find('#available-equipment .list-group-item.equipped').hide()
@$el.find('.item-slot').removeClass('disabled')
if selectedItem.length
item = _.find @items.models, {id:selectedItem.find('.item-view').data('item-id')}
# update which slots are enabled
allowedSlots = item.getAllowedSlots()
for slotEl in @$el.find('.item-slot')
slotName = $(slotEl).data('slot')
if slotName not in allowedSlots
$(slotEl).addClass('disabled')
@showSelectedAvailableItem(item)
else
@hideSelectedAvailableItem()
@delegateEvents()
showSelectedSlotItem: (item) ->
if not @selectedEquippedItemView
@selectedEquippedItemView = new ItemView({
item: item, includes: {name: true, stats: true, props: true}})
@insertSubView(@selectedEquippedItemView, @$el.find('#selected-equipped-item .item-view-stub'))
else
@selectedEquippedItemView.$el.show()
@selectedEquippedItemView.item = item
@selectedEquippedItemView.render()
@$el.find('#selected-items').show()
hideSelectedSlotItem: ->
@selectedEquippedItemView?.$el.hide()
@$el.find('#selected-items').hide() unless @selectedEquippedItemView?.$el?.is(':visible')
showSelectedAvailableItem: (item) ->
if not @selectedAvailableItemView
@selectedAvailableItemView = new ItemView({
item: item, includes: {name: true, stats: true, props: true}})
@insertSubView(@selectedAvailableItemView, @$el.find('#selected-available-item .item-view-stub'))
else
@selectedAvailableItemView.$el.show()
@selectedAvailableItemView.item = item
@selectedAvailableItemView.render()
@$el.find('#selected-items').show()
hideSelectedAvailableItem: ->
@selectedAvailableItemView?.$el.hide()
@$el.find('#selected-items').hide() unless @selectedEquippedItemView?.$el?.is(':visible')
getCurrentEquipmentConfig: ->
config = {}
for slot in @$el.find('.item-slot')
slotName = $(slot).data('slot')
slotItemID = $(slot).find('.item-view').data('item-id')
continue unless slotItemID
item = _.find @items.models, {id:slotItemID}
config[slotName] = item.get('original')
config
assignLevelEquipment: ->
# This is temporary, until we have a more general way of awarding items and configuring needed/restricted items per level.
gear =
'simple-boots': '53e237bf53457600003e3f05'
'longsword': '53e218d853457600003e3ebe'
'leather-tunic': '53e22eac53457600003e3efc'
#'leather-boots': '53e2384453457600003e3f07'
'programmaticon-i': '53e4108204c00d4607a89f78'
'crude-glasses': '53e238df53457600003e3f0b'
'builders-hammer': '53f4e6e3d822c23505b74f42'
gearByLevel =
'dungeons-of-kithgard': {feet: 'simple-boots'}
'gems-in-the-deep': {feet: 'simple-boots'}
'shadow-guard': {feet: 'simple-boots'}
'true-names': {feet: 'simple-boots', 'right-hand': 'longsword'}
'the-raised-sword': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic'}
'the-first-kithmaze': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i'}
'the-second-kithmaze': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i'}
'new-sight': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i'}
'lowly-kithmen': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'a-bolt-in-the-dark': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'the-final-kithmaze': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'kithgard-gates': {feet: 'simple-boots', 'right-hand': 'builders-hammer', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'defence-of-plainswood': {feet: 'simple-boots', 'right-hand': 'builders-hammer', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
necessaryGear = gearByLevel[@options.levelID]
for slot, item of necessaryGear ? {}
@equipment[slot] ?= gear[item]
# Restrict available items to those that would be available by this item.
@allowedItems = []
for level, items of gearByLevel
for slot, item of items
@allowedItems.push gear[item] unless gear[item] in @allowedItems
break if level is @options.levelID
onHeroSelectionUpdated: (e) ->
@selectedHero = e.hero
@loadHero()
loadHero: ->
return unless @selectedHero and not @$el.hasClass 'secret'
@stage?.removeAllChildren()
if @selectedHero.loaded and movieClip = @movieClips?[@selectedHero.get('original')]
@stage.addChild(movieClip)
@stage.update()
return
onLoaded = =>
return unless canvas = $(".equipped-hero-canvas")
@canvasWidth ||= canvas.width()
@canvasHeight ||= canvas.height()
canvas.prop width: @canvasWidth, height: @canvasHeight
builder = new SpriteBuilder(@selectedHero)
movieClip = builder.buildMovieClip(@selectedHero.get('actions').attack?.animation ? @selectedHero.get('actions').idle.animation)
movieClip.scaleX = movieClip.scaleY = canvas.prop('height') / 120 # Average hero height is ~110px at normal resolution
if @selectedHero.get('name') in ['<NAME>', '<NAME>'] # These are too big, so shrink them.
movieClip.scaleX *= 0.7
movieClip.scaleY *= 0.7
movieClip.regX = -@selectedHero.get('positions').registration.x
movieClip.regY = -@selectedHero.get('positions').registration.y
movieClip.x = canvas.prop('width') * 0.5
movieClip.y = canvas.prop('height') * 0.95 # This is where the feet go.
movieClip.gotoAndPlay 0
@stage ?= new createjs.Stage(canvas[0])
@stage.addChild movieClip
@stage.update()
@movieClips ?= {}
@movieClips[@selectedHero.get('original')] = movieClip
if @selectedHero.loaded
if @selectedHero.isFullyLoaded()
_.defer onLoaded
else
console.error 'Hmm, trying to render a hero we have not loaded...?', @selectedHero
else
@listenToOnce @selectedHero, 'sync', onLoaded
onShown: ->
# Called when we switch tabs to this within the modal
@loadHero()
onHidden: ->
# Called when the modal itself is dismissed
| true | CocoView = require 'views/kinds/CocoView'
template = require 'templates/game-menu/inventory-view'
{me} = require 'lib/auth'
ThangType = require 'models/ThangType'
CocoCollection = require 'collections/CocoCollection'
ItemView = require './ItemView'
SpriteBuilder = require 'lib/sprites/SpriteBuilder'
module.exports = class InventoryView extends CocoView
id: 'inventory-view'
className: 'tab-pane'
template: template
slots: ['head', 'eyes', 'neck', 'torso', 'wrists', 'gloves', 'left-ring', 'right-ring', 'right-hand', 'left-hand', 'waist', 'feet', 'spellbook', 'programming-book', 'pet', 'minion', 'misc-0', 'misc-1', 'misc-2', 'misc-3', 'misc-4']
events:
'click .item-slot': 'onItemSlotClick'
'click #available-equipment .list-group-item': 'onAvailableItemClick'
'dblclick #available-equipment .list-group-item': 'onAvailableItemDoubleClick'
'dblclick .item-slot .item-view': 'onEquippedItemDoubleClick'
'click #swap-button': 'onClickSwapButton'
subscriptions:
'level:hero-selection-updated': 'onHeroSelectionUpdated'
shortcuts:
'esc': 'clearSelection'
initialize: (options) ->
super(arguments...)
@items = new CocoCollection([], {model: ThangType})
@equipment = options.equipment or @options.session?.get('heroConfig')?.inventory or me.get('heroConfig')?.inventory or {}
@equipment = $.extend true, {}, @equipment
@assignLevelEquipment()
@items.url = '/db/thang.type?view=items&project=name,components,original,rasterIcon'
@supermodel.loadCollection(@items, 'items')
destroy: ->
@stage?.removeAllChildren()
super()
onLoaded: ->
item.notInLevel = true for item in @items.models
super()
getRenderData: (context={}) ->
context = super(context)
context.equipped = _.values(@equipment)
context.items = @items.models
for item in @items.models
item.classes = item.getAllowedSlots()
item.classes.push 'equipped' if item.get('original') in context.equipped
item.classes.push 'restricted' if @allowedItems and not (item.get('original') in @allowedItems)
@items.models.sort (a, b) -> ('restricted' in a.classes) - ('restricted' in b.classes)
context.slots = @slots
context.equipment = _.clone @equipment
for slot, itemOriginal of context.equipment
item = _.find @items.models, (item) -> item.get('original') is itemOriginal
context.equipment[slot] = item
context
afterRender: ->
super()
return unless @supermodel.finished()
keys = (item.get('original') for item in @items.models)
itemMap = _.zipObject keys, @items.models
# Fill in equipped items
for slottedItemStub in @$el.find('.replace-me')
itemID = $(slottedItemStub).data('item-id')
item = itemMap[itemID]
itemView = new ItemView({item: item, includes: {}})
itemView.render()
$(slottedItemStub).replaceWith(itemView.$el)
@registerSubView(itemView)
for availableItemEl in @$el.find('#available-equipment .list-group-item')
itemID = $(availableItemEl).data('item-id')
item = itemMap[itemID]
itemView = new ItemView({item: item, includes: {name: true}})
itemView.render()
$(availableItemEl).append(itemView.$el)
@registerSubView(itemView)
continue if $(availableItemEl).hasClass 'restricted'
dragHelper = itemView.$el.find('img').clone().addClass('draggable-item')
do (dragHelper, itemView) =>
itemView.$el.draggable
revert: 'invalid'
appendTo: @$el
cursorAt: {left: 35.5, top: 35.5}
helper: -> dragHelper
revertDuration: 200
distance: 10
scroll: false
zIndex: 100
itemView.$el.on 'dragstart', =>
@onAvailableItemClick target: itemView.$el.parent() unless itemView.$el.parent().hasClass 'active'
for itemSlot in @$el.find '.item-slot'
slot = $(itemSlot).data 'slot'
$(itemSlot).find('.placeholder').css('background-image', "url(/images/pages/game-menu/slot-#{slot}.png)")
do (slot) =>
$(itemSlot).droppable
drop: (e, ui) => @onAvailableItemDoubleClick()
accept: (el) -> $(el).parent().hasClass slot
activeClass: 'droppable'
hoverClass: 'droppable-hover'
tolerance: 'touch'
@$el.find('#selected-items').hide() # Hide until one is selected
@delegateEvents()
afterInsert: ->
super()
@canvasWidth = @$el.find('canvas').innerWidth()
@canvasHeight = @$el.find('canvas').innerHeight()
clearSelection: ->
@$el.find('.item-slot.selected').removeClass 'selected'
@$el.find('.list-group-item').removeClass('active')
@onSelectionChanged()
onItemSlotClick: (e) ->
slot = $(e.target).closest('.item-slot')
wasActive = slot.hasClass('selected')
@unselectAllSlots()
@unselectAllAvailableEquipment() if slot.hasClass('disabled')
if wasActive
@hideSelectedSlotItem()
@unselectAllAvailableEquipment()
else
@selectSlot(slot)
@onSelectionChanged()
onAvailableItemClick: (e) ->
itemContainer = $(e.target).closest('.list-group-item')
return if itemContainer.hasClass 'restricted'
wasActive = itemContainer.hasClass 'active'
@unselectAllAvailableEquipment()
@selectAvailableItem(itemContainer) unless wasActive
@onSelectionChanged()
onAvailableItemDoubleClick: (e) ->
if e
itemContainer = $(e.target).closest('.list-group-item')
return if itemContainer.hasClass 'restricted'
@selectAvailableItem itemContainer
@onSelectionChanged()
slot = @getSelectedSlot()
slot = @$el.find('.item-slot:not(.disabled):first') if not slot.length
@unequipItemFromSlot(slot)
@equipSelectedItemToSlot(slot)
@onSelectionChanged()
onEquippedItemDoubleClick: (e) ->
@unselectAllAvailableEquipment()
slot = $(e.target).closest('.item-slot')
@selectAvailableItem(@unequipItemFromSlot(slot))
@onSelectionChanged()
onClickSwapButton: ->
slot = @getSelectedSlot()
selectedItemContainer = @$el.find('#available-equipment .list-group-item.active')
return unless slot[0] or selectedItemContainer[0]
slot = @$el.find('.item-slot:not(.disabled):first') if not slot.length
itemContainer = @unequipItemFromSlot(slot)
@equipSelectedItemToSlot(slot)
@selectAvailableItem(itemContainer)
@selectSlot(slot)
@onSelectionChanged()
getSelectedSlot: ->
@$el.find('#equipped .item-slot.selected')
unselectAllAvailableEquipment: ->
@$el.find('#available-equipment .list-group-item').removeClass('active')
unselectAllSlots: ->
@$el.find('#equipped .item-slot.selected').removeClass('selected')
selectSlot: (slot) ->
slot.addClass('selected')
getSlot: (name) ->
@$el.find(".item-slot[data-slot=#{name}]")
getSelectedAvailableItemContainer: ->
@$el.find('#available-equipment .list-group-item.active')
getAvailableItemContainer: (itemID) ->
@$el.find("#available-equipment .list-group-item[data-item-id='#{itemID}']")
selectAvailableItem: (itemContainer) ->
itemContainer?.addClass('active')
unequipItemFromSlot: (slot) ->
itemIDToUnequip = slot.find('.item-view').data('item-id')
return unless itemIDToUnequip
slot.find('.item-view').detach()
for el in @$el.find('#available-equipment .list-group-item')
itemID = $(el).find('.item-view').data('item-id')
if itemID is itemIDToUnequip
return $(el).removeClass('equipped')
equipSelectedItemToSlot: (slot) ->
selectedItemContainer = @getSelectedAvailableItemContainer()
newItemHTML = selectedItemContainer.html()
selectedItemContainer.addClass('equipped')
slotContainer = slot.find('.item-container')
slotContainer.html(newItemHTML)
slotContainer.find('.item-view').data('item-id', selectedItemContainer.find('.item-view').data('item-id'))
@$el.find('.list-group-item').removeClass('active')
onSelectionChanged: ->
@$el.find('.item-slot').show()
selectedSlot = @$el.find('.item-slot.selected')
selectedItem = @$el.find('#available-equipment .list-group-item.active')
if selectedSlot.length
@$el.find('#available-equipment .list-group-item').hide()
count = @$el.find("#available-equipment .list-group-item.#{selectedSlot.data('slot')}").show().length
@$el.find('#stash-description').text "#{count} #{selectedSlot.data('slot')} items owned"
selectedSlotItemID = selectedSlot.find('.item-view').data('item-id')
if selectedSlotItemID
item = _.find @items.models, {id:selectedSlotItemID}
@showSelectedSlotItem(item)
else
@hideSelectedSlotItem()
else
count = @$el.find('#available-equipment .list-group-item').show().length
@$el.find('#stash-description').text "#{count} items owned"
@$el.find('#available-equipment .list-group-item.equipped').hide()
@$el.find('.item-slot').removeClass('disabled')
if selectedItem.length
item = _.find @items.models, {id:selectedItem.find('.item-view').data('item-id')}
# update which slots are enabled
allowedSlots = item.getAllowedSlots()
for slotEl in @$el.find('.item-slot')
slotName = $(slotEl).data('slot')
if slotName not in allowedSlots
$(slotEl).addClass('disabled')
@showSelectedAvailableItem(item)
else
@hideSelectedAvailableItem()
@delegateEvents()
showSelectedSlotItem: (item) ->
if not @selectedEquippedItemView
@selectedEquippedItemView = new ItemView({
item: item, includes: {name: true, stats: true, props: true}})
@insertSubView(@selectedEquippedItemView, @$el.find('#selected-equipped-item .item-view-stub'))
else
@selectedEquippedItemView.$el.show()
@selectedEquippedItemView.item = item
@selectedEquippedItemView.render()
@$el.find('#selected-items').show()
hideSelectedSlotItem: ->
@selectedEquippedItemView?.$el.hide()
@$el.find('#selected-items').hide() unless @selectedEquippedItemView?.$el?.is(':visible')
showSelectedAvailableItem: (item) ->
if not @selectedAvailableItemView
@selectedAvailableItemView = new ItemView({
item: item, includes: {name: true, stats: true, props: true}})
@insertSubView(@selectedAvailableItemView, @$el.find('#selected-available-item .item-view-stub'))
else
@selectedAvailableItemView.$el.show()
@selectedAvailableItemView.item = item
@selectedAvailableItemView.render()
@$el.find('#selected-items').show()
hideSelectedAvailableItem: ->
@selectedAvailableItemView?.$el.hide()
@$el.find('#selected-items').hide() unless @selectedEquippedItemView?.$el?.is(':visible')
getCurrentEquipmentConfig: ->
config = {}
for slot in @$el.find('.item-slot')
slotName = $(slot).data('slot')
slotItemID = $(slot).find('.item-view').data('item-id')
continue unless slotItemID
item = _.find @items.models, {id:slotItemID}
config[slotName] = item.get('original')
config
assignLevelEquipment: ->
# This is temporary, until we have a more general way of awarding items and configuring needed/restricted items per level.
gear =
'simple-boots': '53e237bf53457600003e3f05'
'longsword': '53e218d853457600003e3ebe'
'leather-tunic': '53e22eac53457600003e3efc'
#'leather-boots': '53e2384453457600003e3f07'
'programmaticon-i': '53e4108204c00d4607a89f78'
'crude-glasses': '53e238df53457600003e3f0b'
'builders-hammer': '53f4e6e3d822c23505b74f42'
gearByLevel =
'dungeons-of-kithgard': {feet: 'simple-boots'}
'gems-in-the-deep': {feet: 'simple-boots'}
'shadow-guard': {feet: 'simple-boots'}
'true-names': {feet: 'simple-boots', 'right-hand': 'longsword'}
'the-raised-sword': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic'}
'the-first-kithmaze': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i'}
'the-second-kithmaze': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i'}
'new-sight': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i'}
'lowly-kithmen': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'a-bolt-in-the-dark': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'the-final-kithmaze': {feet: 'simple-boots', 'right-hand': 'longsword', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'kithgard-gates': {feet: 'simple-boots', 'right-hand': 'builders-hammer', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
'defence-of-plainswood': {feet: 'simple-boots', 'right-hand': 'builders-hammer', torso: 'leather-tunic', 'programming-book': 'programmaticon-i', eyes: 'crude-glasses'}
necessaryGear = gearByLevel[@options.levelID]
for slot, item of necessaryGear ? {}
@equipment[slot] ?= gear[item]
# Restrict available items to those that would be available by this item.
@allowedItems = []
for level, items of gearByLevel
for slot, item of items
@allowedItems.push gear[item] unless gear[item] in @allowedItems
break if level is @options.levelID
onHeroSelectionUpdated: (e) ->
@selectedHero = e.hero
@loadHero()
loadHero: ->
return unless @selectedHero and not @$el.hasClass 'secret'
@stage?.removeAllChildren()
if @selectedHero.loaded and movieClip = @movieClips?[@selectedHero.get('original')]
@stage.addChild(movieClip)
@stage.update()
return
onLoaded = =>
return unless canvas = $(".equipped-hero-canvas")
@canvasWidth ||= canvas.width()
@canvasHeight ||= canvas.height()
canvas.prop width: @canvasWidth, height: @canvasHeight
builder = new SpriteBuilder(@selectedHero)
movieClip = builder.buildMovieClip(@selectedHero.get('actions').attack?.animation ? @selectedHero.get('actions').idle.animation)
movieClip.scaleX = movieClip.scaleY = canvas.prop('height') / 120 # Average hero height is ~110px at normal resolution
if @selectedHero.get('name') in ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] # These are too big, so shrink them.
movieClip.scaleX *= 0.7
movieClip.scaleY *= 0.7
movieClip.regX = -@selectedHero.get('positions').registration.x
movieClip.regY = -@selectedHero.get('positions').registration.y
movieClip.x = canvas.prop('width') * 0.5
movieClip.y = canvas.prop('height') * 0.95 # This is where the feet go.
movieClip.gotoAndPlay 0
@stage ?= new createjs.Stage(canvas[0])
@stage.addChild movieClip
@stage.update()
@movieClips ?= {}
@movieClips[@selectedHero.get('original')] = movieClip
if @selectedHero.loaded
if @selectedHero.isFullyLoaded()
_.defer onLoaded
else
console.error 'Hmm, trying to render a hero we have not loaded...?', @selectedHero
else
@listenToOnce @selectedHero, 'sync', onLoaded
onShown: ->
# Called when we switch tabs to this within the modal
@loadHero()
onHidden: ->
# Called when the modal itself is dismissed
|
[
{
"context": "y UI datepicker editor 1.0.0\n\n Copyright (c) 2016 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-jquer",
"end": 93,
"score": 0.9998753070831299,
"start": 77,
"tag": "NAME",
"value": "Tomasz Jakub Rup"
},
{
"context": "t (c) 2016 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-jquery-ui\n\n Released under the MI",
"end": 122,
"score": 0.9995781183242798,
"start": 116,
"tag": "USERNAME",
"value": "tomi77"
}
] | src/datepicker.coffee | tomi77/backbone-forms-jquery-ui | 0 | ###
Backbone-Forms jQuery UI datepicker editor 1.0.0
Copyright (c) 2016 Tomasz Jakub Rup
https://github.com/tomi77/backbone-forms-jquery-ui
Released under the MIT license
###
((root, factory) ->
### istanbul ignore next ###
switch
when typeof define is 'function' and define.amd
define ['underscore', 'backbone-forms', 'jquery-ui/widgets/datepicker'], factory
when typeof exports is 'object'
require('jquery-ui/widgets/datepicker')
factory require('underscore'), require('backbone-forms')
else
factory root._, root.Backbone.Form
return
) @, (_, Form) ->
Form.editors['jqueryui.datepicker'] = Form.Editor.extend
className: 'bbf-jui-datepicker'
tagName: 'input'
initialize: (options) ->
Form.editors.Base::initialize.call @, options
@editorOptions = @schema.editorOptions or {}
prevOnSelect = @editorOptions.onSelect
@editorOptions.onSelect = (dateText, inst) =>
@trigger 'change', @, dateText, inst
if prevOnSelect then prevOnSelect.call @el, dateText, inst
return
prevOnClose = @editorOptions.onClose
@editorOptions.onClose = (dateText, inst) =>
@trigger 'blur', @, dateText, inst
if prevOnClose then prevOnClose.call @el, dateText, inst
return
prevBeforeShow = @editorOptions.beforeShow
@editorOptions.beforeShow = (input, inst) =>
@trigger 'focus', @, input, inst
if prevBeforeShow then return prevBeforeShow.call @el, input, inst
return {}
@value = switch
when @value and _.isDate @value then @value
when @value and _.isString @value then new Date @value
else
new Date()
@$el.attr 'type', 'text'
return
render: () ->
@$el.datepicker @editorOptions
@setValue @value
@
###
@return {Date} Selected date
###
getValue: () -> @$el.datepicker 'getDate'
setValue: (value) ->
@$el.datepicker 'setDate', value
return
return
| 39595 | ###
Backbone-Forms jQuery UI datepicker editor 1.0.0
Copyright (c) 2016 <NAME>
https://github.com/tomi77/backbone-forms-jquery-ui
Released under the MIT license
###
((root, factory) ->
### istanbul ignore next ###
switch
when typeof define is 'function' and define.amd
define ['underscore', 'backbone-forms', 'jquery-ui/widgets/datepicker'], factory
when typeof exports is 'object'
require('jquery-ui/widgets/datepicker')
factory require('underscore'), require('backbone-forms')
else
factory root._, root.Backbone.Form
return
) @, (_, Form) ->
Form.editors['jqueryui.datepicker'] = Form.Editor.extend
className: 'bbf-jui-datepicker'
tagName: 'input'
initialize: (options) ->
Form.editors.Base::initialize.call @, options
@editorOptions = @schema.editorOptions or {}
prevOnSelect = @editorOptions.onSelect
@editorOptions.onSelect = (dateText, inst) =>
@trigger 'change', @, dateText, inst
if prevOnSelect then prevOnSelect.call @el, dateText, inst
return
prevOnClose = @editorOptions.onClose
@editorOptions.onClose = (dateText, inst) =>
@trigger 'blur', @, dateText, inst
if prevOnClose then prevOnClose.call @el, dateText, inst
return
prevBeforeShow = @editorOptions.beforeShow
@editorOptions.beforeShow = (input, inst) =>
@trigger 'focus', @, input, inst
if prevBeforeShow then return prevBeforeShow.call @el, input, inst
return {}
@value = switch
when @value and _.isDate @value then @value
when @value and _.isString @value then new Date @value
else
new Date()
@$el.attr 'type', 'text'
return
render: () ->
@$el.datepicker @editorOptions
@setValue @value
@
###
@return {Date} Selected date
###
getValue: () -> @$el.datepicker 'getDate'
setValue: (value) ->
@$el.datepicker 'setDate', value
return
return
| true | ###
Backbone-Forms jQuery UI datepicker editor 1.0.0
Copyright (c) 2016 PI:NAME:<NAME>END_PI
https://github.com/tomi77/backbone-forms-jquery-ui
Released under the MIT license
###
((root, factory) ->
### istanbul ignore next ###
switch
when typeof define is 'function' and define.amd
define ['underscore', 'backbone-forms', 'jquery-ui/widgets/datepicker'], factory
when typeof exports is 'object'
require('jquery-ui/widgets/datepicker')
factory require('underscore'), require('backbone-forms')
else
factory root._, root.Backbone.Form
return
) @, (_, Form) ->
Form.editors['jqueryui.datepicker'] = Form.Editor.extend
className: 'bbf-jui-datepicker'
tagName: 'input'
initialize: (options) ->
Form.editors.Base::initialize.call @, options
@editorOptions = @schema.editorOptions or {}
prevOnSelect = @editorOptions.onSelect
@editorOptions.onSelect = (dateText, inst) =>
@trigger 'change', @, dateText, inst
if prevOnSelect then prevOnSelect.call @el, dateText, inst
return
prevOnClose = @editorOptions.onClose
@editorOptions.onClose = (dateText, inst) =>
@trigger 'blur', @, dateText, inst
if prevOnClose then prevOnClose.call @el, dateText, inst
return
prevBeforeShow = @editorOptions.beforeShow
@editorOptions.beforeShow = (input, inst) =>
@trigger 'focus', @, input, inst
if prevBeforeShow then return prevBeforeShow.call @el, input, inst
return {}
@value = switch
when @value and _.isDate @value then @value
when @value and _.isString @value then new Date @value
else
new Date()
@$el.attr 'type', 'text'
return
render: () ->
@$el.datepicker @editorOptions
@setValue @value
@
###
@return {Date} Selected date
###
getValue: () -> @$el.datepicker 'getDate'
setValue: (value) ->
@$el.datepicker 'setDate', value
return
return
|
[
{
"context": " user: 1, product: 1 }, { unique: true })\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n@abstract\r\n###\r\nclass User",
"end": 380,
"score": 0.9998679161071777,
"start": 368,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/schema/UserProductSchema.coffee | qrefdev/qref | 0 | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
###
Schema representing the relationship between an individual user and a product which they have permission to access.
@example MongoDB Collection
db.user.products
@example MongoDB Indexes
db.user.products.ensureIndex({ user: 1, product: 1 }, { unique: true })
@author Nathan Klick
@copyright QRef 2012
@abstract
###
class UserProductSchemaInternal
###
@property [ObjectId] (Required) The id of the user owning this product.
@see UserSchemaInternal
###
user:
type: ObjectId
required: true
ref: 'users'
###
@property [ObjectId] (Required) The id of the product which the user owns.
@see ProductSchemaInternal
###
product:
type: ObjectId
required: true
ref: 'products'
timestamp:
type: Date
required: false
default: new Date()
UserProductSchema = new Schema(new UserProductSchemaInternal())
UserProductSchema.index({ user: 1, product: 1 }, { unique: true })
module.exports = UserProductSchema
| 22597 | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
###
Schema representing the relationship between an individual user and a product which they have permission to access.
@example MongoDB Collection
db.user.products
@example MongoDB Indexes
db.user.products.ensureIndex({ user: 1, product: 1 }, { unique: true })
@author <NAME>
@copyright QRef 2012
@abstract
###
class UserProductSchemaInternal
###
@property [ObjectId] (Required) The id of the user owning this product.
@see UserSchemaInternal
###
user:
type: ObjectId
required: true
ref: 'users'
###
@property [ObjectId] (Required) The id of the product which the user owns.
@see ProductSchemaInternal
###
product:
type: ObjectId
required: true
ref: 'products'
timestamp:
type: Date
required: false
default: new Date()
UserProductSchema = new Schema(new UserProductSchemaInternal())
UserProductSchema.index({ user: 1, product: 1 }, { unique: true })
module.exports = UserProductSchema
| true | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
###
Schema representing the relationship between an individual user and a product which they have permission to access.
@example MongoDB Collection
db.user.products
@example MongoDB Indexes
db.user.products.ensureIndex({ user: 1, product: 1 }, { unique: true })
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
@abstract
###
class UserProductSchemaInternal
###
@property [ObjectId] (Required) The id of the user owning this product.
@see UserSchemaInternal
###
user:
type: ObjectId
required: true
ref: 'users'
###
@property [ObjectId] (Required) The id of the product which the user owns.
@see ProductSchemaInternal
###
product:
type: ObjectId
required: true
ref: 'products'
timestamp:
type: Date
required: false
default: new Date()
UserProductSchema = new Schema(new UserProductSchemaInternal())
UserProductSchema.index({ user: 1, product: 1 }, { unique: true })
module.exports = UserProductSchema
|
[
{
"context": " (done) ->\n up.layer.root.context.rootKey = 'rootValue'\n\n up.layer.open(context: { overlayKey: 'ove",
"end": 208,
"score": 0.9848500490188599,
"start": 199,
"tag": "KEY",
"value": "rootValue"
},
{
"context": " up.layer.open(context: { overlayKey: 'overlayValue' }).then (overlay) ->\n expect(overlay.cont",
"end": 267,
"score": 0.8386255502700806,
"start": 262,
"tag": "KEY",
"value": "Value"
},
{
"context": "pect(up.layer.root.context).toEqual(rootKey: 'rootValue')\n done()\n\n it 'may be mutated by the u",
"end": 484,
"score": 0.7869710326194763,
"start": 479,
"tag": "KEY",
"value": "Value"
}
] | spec/unpoly/classes/layer/base_spec.coffee | apollo13/unpoly | 1,129 | describe 'up.Layer', ->
beforeEach ->
up.motion.config.enabled = false
describe '#context', ->
it 'stores a per-layer context object', (done) ->
up.layer.root.context.rootKey = 'rootValue'
up.layer.open(context: { overlayKey: 'overlayValue' }).then (overlay) ->
expect(overlay.context).toEqual(overlayKey: 'overlayValue')
# Show that the root layer's context wasn't changed.
expect(up.layer.root.context).toEqual(rootKey: 'rootValue')
done()
it 'may be mutated by the user', ->
up.layer.context.key = 'value'
expect(up.layer.context.key).toEqual('value')
describe '#on()', ->
it 'registers a listener for events on this layer', ->
listener = jasmine.createSpy('event listener')
makeLayers(2)
up.layer.on('foo', listener)
up.emit(up.layer.element, 'foo')
expect(listener).toHaveBeenCalled()
it "does not call the listener for events on another layer", ->
listener = jasmine.createSpy('event listener')
makeLayers(3)
up.layer.stack[1].on('foo', listener)
up.emit(up.layer.stack[2].element, 'foo')
expect(listener).not.toHaveBeenCalled()
it "does not call the listener for events on another layer, even if the event target is a DOM child of the layer element", ->
listener = jasmine.createSpy('event listener')
up.layer.root.on('foo', listener)
makeLayers(2)
# Note that we're using Element#contains(), not up.Layer#contains()
expect(up.layer.root.element.contains(up.layer.current.element)).toBe(true)
up.emit(up.layer.element, 'foo')
expect(listener).not.toHaveBeenCalled()
it 'allows to pass a selector for event delegation as second argument', asyncSpec (next) ->
listener = jasmine.createSpy('event listener')
makeLayers(2)
next ->
up.layer.on('foo', '.two', listener)
one = up.layer.affix('.one')
two = up.layer.affix('.two')
up.emit(one, 'foo')
expect(listener).not.toHaveBeenCalled()
up.emit(two, 'foo')
expect(listener).toHaveBeenCalled()
it 'sets up.layer.current to this layer while the listener is running', ->
currentSpy = jasmine.createSpy()
makeLayers(3)
expect(up.layer.current).toEqual(up.layer.get(2))
up.layer.get(1).on('foo', -> currentSpy(up.layer.current))
up.emit(up.layer.get(1).element, 'foo')
expect(currentSpy).toHaveBeenCalledWith(up.layer.get(1))
expect(up.layer.current).toEqual(up.layer.get(2))
describe '#emit()', ->
it "emits an event on this layer's element", ->
targets = []
up.on 'foo', (event) -> targets.push(event.target)
makeLayers(2)
expect(up.layer.count).toBe(2)
up.layer.front.emit('foo')
expect(targets).toEqual [up.layer.front.element]
up.layer.root.emit('foo')
expect(targets).toEqual [up.layer.front.element, up.layer.root.element]
it 'sets up.layer.current to this layer while listeners are running', ->
eventLayer = null
up.on 'foo', (event) -> eventLayer = up.layer.current
makeLayers(2)
expect(up.layer.current).not.toBe(up.layer.root)
expect(up.layer.current).toBe(up.layer.front)
up.layer.root.emit('foo')
expect(eventLayer).not.toBe(up.layer.front)
expect(eventLayer).toBe(up.layer.root)
describe '#peel()', ->
it 'dismisses all descendants', ->
makeLayers(4)
expect(up.layer.count).toBe(4)
secondLayer = up.layer.get(1)
secondLayer.peel()
expect(up.layer.count).toBe(2)
it 'uses a dismissal value :peel', ->
listener = jasmine.createSpy('dismiss listener')
up.on('up:layer:dismiss', listener)
makeLayers(2)
up.layer.root.peel()
expect(listener.calls.argsFor(0)[0]).toEqual jasmine.objectContaining(value: ':peel')
| 121164 | describe 'up.Layer', ->
beforeEach ->
up.motion.config.enabled = false
describe '#context', ->
it 'stores a per-layer context object', (done) ->
up.layer.root.context.rootKey = '<KEY>'
up.layer.open(context: { overlayKey: 'overlay<KEY>' }).then (overlay) ->
expect(overlay.context).toEqual(overlayKey: 'overlayValue')
# Show that the root layer's context wasn't changed.
expect(up.layer.root.context).toEqual(rootKey: 'root<KEY>')
done()
it 'may be mutated by the user', ->
up.layer.context.key = 'value'
expect(up.layer.context.key).toEqual('value')
describe '#on()', ->
it 'registers a listener for events on this layer', ->
listener = jasmine.createSpy('event listener')
makeLayers(2)
up.layer.on('foo', listener)
up.emit(up.layer.element, 'foo')
expect(listener).toHaveBeenCalled()
it "does not call the listener for events on another layer", ->
listener = jasmine.createSpy('event listener')
makeLayers(3)
up.layer.stack[1].on('foo', listener)
up.emit(up.layer.stack[2].element, 'foo')
expect(listener).not.toHaveBeenCalled()
it "does not call the listener for events on another layer, even if the event target is a DOM child of the layer element", ->
listener = jasmine.createSpy('event listener')
up.layer.root.on('foo', listener)
makeLayers(2)
# Note that we're using Element#contains(), not up.Layer#contains()
expect(up.layer.root.element.contains(up.layer.current.element)).toBe(true)
up.emit(up.layer.element, 'foo')
expect(listener).not.toHaveBeenCalled()
it 'allows to pass a selector for event delegation as second argument', asyncSpec (next) ->
listener = jasmine.createSpy('event listener')
makeLayers(2)
next ->
up.layer.on('foo', '.two', listener)
one = up.layer.affix('.one')
two = up.layer.affix('.two')
up.emit(one, 'foo')
expect(listener).not.toHaveBeenCalled()
up.emit(two, 'foo')
expect(listener).toHaveBeenCalled()
it 'sets up.layer.current to this layer while the listener is running', ->
currentSpy = jasmine.createSpy()
makeLayers(3)
expect(up.layer.current).toEqual(up.layer.get(2))
up.layer.get(1).on('foo', -> currentSpy(up.layer.current))
up.emit(up.layer.get(1).element, 'foo')
expect(currentSpy).toHaveBeenCalledWith(up.layer.get(1))
expect(up.layer.current).toEqual(up.layer.get(2))
describe '#emit()', ->
it "emits an event on this layer's element", ->
targets = []
up.on 'foo', (event) -> targets.push(event.target)
makeLayers(2)
expect(up.layer.count).toBe(2)
up.layer.front.emit('foo')
expect(targets).toEqual [up.layer.front.element]
up.layer.root.emit('foo')
expect(targets).toEqual [up.layer.front.element, up.layer.root.element]
it 'sets up.layer.current to this layer while listeners are running', ->
eventLayer = null
up.on 'foo', (event) -> eventLayer = up.layer.current
makeLayers(2)
expect(up.layer.current).not.toBe(up.layer.root)
expect(up.layer.current).toBe(up.layer.front)
up.layer.root.emit('foo')
expect(eventLayer).not.toBe(up.layer.front)
expect(eventLayer).toBe(up.layer.root)
describe '#peel()', ->
it 'dismisses all descendants', ->
makeLayers(4)
expect(up.layer.count).toBe(4)
secondLayer = up.layer.get(1)
secondLayer.peel()
expect(up.layer.count).toBe(2)
it 'uses a dismissal value :peel', ->
listener = jasmine.createSpy('dismiss listener')
up.on('up:layer:dismiss', listener)
makeLayers(2)
up.layer.root.peel()
expect(listener.calls.argsFor(0)[0]).toEqual jasmine.objectContaining(value: ':peel')
| true | describe 'up.Layer', ->
beforeEach ->
up.motion.config.enabled = false
describe '#context', ->
it 'stores a per-layer context object', (done) ->
up.layer.root.context.rootKey = 'PI:KEY:<KEY>END_PI'
up.layer.open(context: { overlayKey: 'overlayPI:KEY:<KEY>END_PI' }).then (overlay) ->
expect(overlay.context).toEqual(overlayKey: 'overlayValue')
# Show that the root layer's context wasn't changed.
expect(up.layer.root.context).toEqual(rootKey: 'rootPI:KEY:<KEY>END_PI')
done()
it 'may be mutated by the user', ->
up.layer.context.key = 'value'
expect(up.layer.context.key).toEqual('value')
describe '#on()', ->
it 'registers a listener for events on this layer', ->
listener = jasmine.createSpy('event listener')
makeLayers(2)
up.layer.on('foo', listener)
up.emit(up.layer.element, 'foo')
expect(listener).toHaveBeenCalled()
it "does not call the listener for events on another layer", ->
listener = jasmine.createSpy('event listener')
makeLayers(3)
up.layer.stack[1].on('foo', listener)
up.emit(up.layer.stack[2].element, 'foo')
expect(listener).not.toHaveBeenCalled()
it "does not call the listener for events on another layer, even if the event target is a DOM child of the layer element", ->
listener = jasmine.createSpy('event listener')
up.layer.root.on('foo', listener)
makeLayers(2)
# Note that we're using Element#contains(), not up.Layer#contains()
expect(up.layer.root.element.contains(up.layer.current.element)).toBe(true)
up.emit(up.layer.element, 'foo')
expect(listener).not.toHaveBeenCalled()
it 'allows to pass a selector for event delegation as second argument', asyncSpec (next) ->
listener = jasmine.createSpy('event listener')
makeLayers(2)
next ->
up.layer.on('foo', '.two', listener)
one = up.layer.affix('.one')
two = up.layer.affix('.two')
up.emit(one, 'foo')
expect(listener).not.toHaveBeenCalled()
up.emit(two, 'foo')
expect(listener).toHaveBeenCalled()
it 'sets up.layer.current to this layer while the listener is running', ->
currentSpy = jasmine.createSpy()
makeLayers(3)
expect(up.layer.current).toEqual(up.layer.get(2))
up.layer.get(1).on('foo', -> currentSpy(up.layer.current))
up.emit(up.layer.get(1).element, 'foo')
expect(currentSpy).toHaveBeenCalledWith(up.layer.get(1))
expect(up.layer.current).toEqual(up.layer.get(2))
describe '#emit()', ->
it "emits an event on this layer's element", ->
targets = []
up.on 'foo', (event) -> targets.push(event.target)
makeLayers(2)
expect(up.layer.count).toBe(2)
up.layer.front.emit('foo')
expect(targets).toEqual [up.layer.front.element]
up.layer.root.emit('foo')
expect(targets).toEqual [up.layer.front.element, up.layer.root.element]
it 'sets up.layer.current to this layer while listeners are running', ->
eventLayer = null
up.on 'foo', (event) -> eventLayer = up.layer.current
makeLayers(2)
expect(up.layer.current).not.toBe(up.layer.root)
expect(up.layer.current).toBe(up.layer.front)
up.layer.root.emit('foo')
expect(eventLayer).not.toBe(up.layer.front)
expect(eventLayer).toBe(up.layer.root)
describe '#peel()', ->
it 'dismisses all descendants', ->
makeLayers(4)
expect(up.layer.count).toBe(4)
secondLayer = up.layer.get(1)
secondLayer.peel()
expect(up.layer.count).toBe(2)
it 'uses a dismissal value :peel', ->
listener = jasmine.createSpy('dismiss listener')
up.on('up:layer:dismiss', listener)
makeLayers(2)
up.layer.root.peel()
expect(listener.calls.argsFor(0)[0]).toEqual jasmine.objectContaining(value: ':peel')
|
[
{
"context": "ach (done)->\n Model = createModel\n name: 'eventcheck'\n connection: createClient()\n schema:\n ",
"end": 202,
"score": 0.961986780166626,
"start": 192,
"tag": "USERNAME",
"value": "eventcheck"
},
{
"context": "reate', (inst)->\n assert inst.doc.name == 'alice'\n Model.removeAllListeners 'create'\n ",
"end": 501,
"score": 0.996552586555481,
"start": 496,
"tag": "NAME",
"value": "alice"
},
{
"context": "\n done()\n\n alice = Model.create name:'alice', age:21\n\n describe 'delete event', ->\n it 's",
"end": 599,
"score": 0.9969634413719177,
"start": 594,
"tag": "NAME",
"value": "alice"
},
{
"context": " 'del', (inst)->\n assert inst.doc.name == 'alice'\n Model.removeAllListeners 'delete'\n ",
"end": 740,
"score": 0.9985800981521606,
"start": 735,
"tag": "NAME",
"value": "alice"
},
{
"context": "'\n done()\n alice = Model.create name:'alice', age:21\n alice.put().then ->\n alice.",
"end": 837,
"score": 0.997994065284729,
"start": 832,
"tag": "NAME",
"value": "alice"
},
{
"context": " 'put', (inst)->\n assert inst.doc.name == 'alice'\n Model.removeAllListeners 'put'\n d",
"end": 1030,
"score": 0.997871994972229,
"start": 1025,
"tag": "NAME",
"value": "alice"
},
{
"context": "'\n done()\n alice = Model.create name:'alice', age:21\n alice.put().then ->\n alice.",
"end": 1124,
"score": 0.998390257358551,
"start": 1119,
"tag": "NAME",
"value": "alice"
},
{
"context": " (done)->\n Loud = createModel\n name: 'Loud'\n connection: createClient()\n event",
"end": 1339,
"score": 0.9724506139755249,
"start": 1335,
"tag": "NAME",
"value": "Loud"
},
{
"context": ", (inst)->\n done()\n Loud.create name:'alice', age:32\n\n it 'should emit newListener event w",
"end": 1621,
"score": 0.9978429675102234,
"start": 1616,
"tag": "NAME",
"value": "alice"
},
{
"context": " (done)->\n Loud = createModel\n name: 'Loud'\n connection: createClient()\n event",
"end": 1747,
"score": 0.974845290184021,
"start": 1743,
"tag": "NAME",
"value": "Loud"
},
{
"context": "oud.on 'create', (inst)->\n Loud.create name:'alice', age:32\n",
"end": 2069,
"score": 0.9983721375465393,
"start": 2064,
"tag": "NAME",
"value": "alice"
}
] | ExampleZukaiRestApi/node_modules/zukai/test/events.coffee | radjivC/interaction-node-riak | 0 | assert = require 'assert'
{createClient} = require 'riakpbc'
{createModel} = require '../src'
Model = null
describe 'Events', ->
beforeEach (done)->
Model = createModel
name: 'eventcheck'
connection: createClient()
schema:
properties:
name:
type: 'string'
age:
type: 'number'
done()
describe 'create event', ->
it 'should fire', (done)->
Model.on 'create', (inst)->
assert inst.doc.name == 'alice'
Model.removeAllListeners 'create'
done()
alice = Model.create name:'alice', age:21
describe 'delete event', ->
it 'should fire', (done)->
Model.on 'del', (inst)->
assert inst.doc.name == 'alice'
Model.removeAllListeners 'delete'
done()
alice = Model.create name:'alice', age:21
alice.put().then ->
alice.del().then(->)
describe 'put event', ->
it 'should fire', (done)->
Model.on 'put', (inst)->
assert inst.doc.name == 'alice'
Model.removeAllListeners 'put'
done()
alice = Model.create name:'alice', age:21
alice.put().then ->
alice.del().then(->)
describe 'event emitter options', ->
it 'should send wildcard events with wildcard:true', (done)->
Loud = createModel
name: 'Loud'
connection: createClient()
events:
wildcard: true
schema:
properties:
name:
type: 'string'
age:
type: 'number'
Loud.on '*', (inst)->
done()
Loud.create name:'alice', age:32
it 'should emit newListener event with newListener:true', (done)->
Loud = createModel
name: 'Loud'
connection: createClient()
events:
newListener: true
schema:
properties:
name:
type: 'string'
age:
type: 'number'
Loud.on 'newListener', ->
done()
Loud.on 'create', (inst)->
Loud.create name:'alice', age:32
| 57532 | assert = require 'assert'
{createClient} = require 'riakpbc'
{createModel} = require '../src'
Model = null
describe 'Events', ->
beforeEach (done)->
Model = createModel
name: 'eventcheck'
connection: createClient()
schema:
properties:
name:
type: 'string'
age:
type: 'number'
done()
describe 'create event', ->
it 'should fire', (done)->
Model.on 'create', (inst)->
assert inst.doc.name == '<NAME>'
Model.removeAllListeners 'create'
done()
alice = Model.create name:'<NAME>', age:21
describe 'delete event', ->
it 'should fire', (done)->
Model.on 'del', (inst)->
assert inst.doc.name == '<NAME>'
Model.removeAllListeners 'delete'
done()
alice = Model.create name:'<NAME>', age:21
alice.put().then ->
alice.del().then(->)
describe 'put event', ->
it 'should fire', (done)->
Model.on 'put', (inst)->
assert inst.doc.name == '<NAME>'
Model.removeAllListeners 'put'
done()
alice = Model.create name:'<NAME>', age:21
alice.put().then ->
alice.del().then(->)
describe 'event emitter options', ->
it 'should send wildcard events with wildcard:true', (done)->
Loud = createModel
name: '<NAME>'
connection: createClient()
events:
wildcard: true
schema:
properties:
name:
type: 'string'
age:
type: 'number'
Loud.on '*', (inst)->
done()
Loud.create name:'<NAME>', age:32
it 'should emit newListener event with newListener:true', (done)->
Loud = createModel
name: '<NAME>'
connection: createClient()
events:
newListener: true
schema:
properties:
name:
type: 'string'
age:
type: 'number'
Loud.on 'newListener', ->
done()
Loud.on 'create', (inst)->
Loud.create name:'<NAME>', age:32
| true | assert = require 'assert'
{createClient} = require 'riakpbc'
{createModel} = require '../src'
Model = null
describe 'Events', ->
beforeEach (done)->
Model = createModel
name: 'eventcheck'
connection: createClient()
schema:
properties:
name:
type: 'string'
age:
type: 'number'
done()
describe 'create event', ->
it 'should fire', (done)->
Model.on 'create', (inst)->
assert inst.doc.name == 'PI:NAME:<NAME>END_PI'
Model.removeAllListeners 'create'
done()
alice = Model.create name:'PI:NAME:<NAME>END_PI', age:21
describe 'delete event', ->
it 'should fire', (done)->
Model.on 'del', (inst)->
assert inst.doc.name == 'PI:NAME:<NAME>END_PI'
Model.removeAllListeners 'delete'
done()
alice = Model.create name:'PI:NAME:<NAME>END_PI', age:21
alice.put().then ->
alice.del().then(->)
describe 'put event', ->
it 'should fire', (done)->
Model.on 'put', (inst)->
assert inst.doc.name == 'PI:NAME:<NAME>END_PI'
Model.removeAllListeners 'put'
done()
alice = Model.create name:'PI:NAME:<NAME>END_PI', age:21
alice.put().then ->
alice.del().then(->)
describe 'event emitter options', ->
it 'should send wildcard events with wildcard:true', (done)->
Loud = createModel
name: 'PI:NAME:<NAME>END_PI'
connection: createClient()
events:
wildcard: true
schema:
properties:
name:
type: 'string'
age:
type: 'number'
Loud.on '*', (inst)->
done()
Loud.create name:'PI:NAME:<NAME>END_PI', age:32
it 'should emit newListener event with newListener:true', (done)->
Loud = createModel
name: 'PI:NAME:<NAME>END_PI'
connection: createClient()
events:
newListener: true
schema:
properties:
name:
type: 'string'
age:
type: 'number'
Loud.on 'newListener', ->
done()
Loud.on 'create', (inst)->
Loud.create name:'PI:NAME:<NAME>END_PI', age:32
|
[
{
"context": " HTTP Factory\n# @package Angular Modules\n# @author Kim Honrubia <dev.kimberlyhonrubia@gmail.com>\n###\n\nangular.mod",
"end": 93,
"score": 0.9998792409896851,
"start": 81,
"tag": "NAME",
"value": "Kim Honrubia"
},
{
"context": " @package Angular Modules\n# @author Kim Honrubia <dev.kimberlyhonrubia@gmail.com>\n###\n\nangular.module('HttpFactory',[]).factory \"H",
"end": 125,
"score": 0.9999361634254456,
"start": 95,
"tag": "EMAIL",
"value": "dev.kimberlyhonrubia@gmail.com"
}
] | resources/assets/coffee/common/angular_modules/httpFactory.coffee | kimberlyhonrubia/local | 0 | ###*
# HTTP Factory
#
# @class HTTP Factory
# @package Angular Modules
# @author Kim Honrubia <dev.kimberlyhonrubia@gmail.com>
###
angular.module('HttpFactory',[]).factory "HttpFactory",
['$http',
'$rootScope'
'$q'
($http,
$rootScope,
$q) ->
sendRequest : (DATA,URL,METHOD,Q_DEFER,isAJAX) ->
METHOD = 'POST' if !_h.isUndefined METHOD
if isAJAX is true
@$$additionalHTTPHeader()
httpDataRequest =
method: METHOD
url: URL
headers: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' }
data: $.param(DATA)
if Q_DEFER
return @$$qDeferRequest httpDataRequest, Q_DEFER
if METHOD == 'GET'
return $http.get(URL)
return $http httpDataRequest
###
# Authentication = Site Authentication Token
# X-Requested-With = Set Http Request to AJAX FORMAT
###
$$additionalHTTPHeader : ( ) ->
$http.defaults.headers.common['Authentication'] = AuthKey || null
$http.defaults.headers.common['X-Requested-With'] = "XMLHttpRequest"
return
$$qDeferRequest : ( httpDataRequest, Q_DEFER ) ->
@qRequest = [] if angular.isUndefined @qRequest
@qRequest.push Q_DEFER
promise = $http angular.extend httpDataRequest, { timeout : Q_DEFER.promise }
promise.finally ( () ->
@qRequest = _.filter @qRequest, (request) ->
request.url != httpDataRequest.url
return
)
return promise
cancelRequest : () ->
angular.forEach @qRequest, (canceller) ->
canceller.resolve()
return
@qRequest = [] if angular.isUndefined @qRequest
]
| 55184 | ###*
# HTTP Factory
#
# @class HTTP Factory
# @package Angular Modules
# @author <NAME> <<EMAIL>>
###
angular.module('HttpFactory',[]).factory "HttpFactory",
['$http',
'$rootScope'
'$q'
($http,
$rootScope,
$q) ->
sendRequest : (DATA,URL,METHOD,Q_DEFER,isAJAX) ->
METHOD = 'POST' if !_h.isUndefined METHOD
if isAJAX is true
@$$additionalHTTPHeader()
httpDataRequest =
method: METHOD
url: URL
headers: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' }
data: $.param(DATA)
if Q_DEFER
return @$$qDeferRequest httpDataRequest, Q_DEFER
if METHOD == 'GET'
return $http.get(URL)
return $http httpDataRequest
###
# Authentication = Site Authentication Token
# X-Requested-With = Set Http Request to AJAX FORMAT
###
$$additionalHTTPHeader : ( ) ->
$http.defaults.headers.common['Authentication'] = AuthKey || null
$http.defaults.headers.common['X-Requested-With'] = "XMLHttpRequest"
return
$$qDeferRequest : ( httpDataRequest, Q_DEFER ) ->
@qRequest = [] if angular.isUndefined @qRequest
@qRequest.push Q_DEFER
promise = $http angular.extend httpDataRequest, { timeout : Q_DEFER.promise }
promise.finally ( () ->
@qRequest = _.filter @qRequest, (request) ->
request.url != httpDataRequest.url
return
)
return promise
cancelRequest : () ->
angular.forEach @qRequest, (canceller) ->
canceller.resolve()
return
@qRequest = [] if angular.isUndefined @qRequest
]
| true | ###*
# HTTP Factory
#
# @class HTTP Factory
# @package Angular Modules
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
angular.module('HttpFactory',[]).factory "HttpFactory",
['$http',
'$rootScope'
'$q'
($http,
$rootScope,
$q) ->
sendRequest : (DATA,URL,METHOD,Q_DEFER,isAJAX) ->
METHOD = 'POST' if !_h.isUndefined METHOD
if isAJAX is true
@$$additionalHTTPHeader()
httpDataRequest =
method: METHOD
url: URL
headers: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' }
data: $.param(DATA)
if Q_DEFER
return @$$qDeferRequest httpDataRequest, Q_DEFER
if METHOD == 'GET'
return $http.get(URL)
return $http httpDataRequest
###
# Authentication = Site Authentication Token
# X-Requested-With = Set Http Request to AJAX FORMAT
###
$$additionalHTTPHeader : ( ) ->
$http.defaults.headers.common['Authentication'] = AuthKey || null
$http.defaults.headers.common['X-Requested-With'] = "XMLHttpRequest"
return
$$qDeferRequest : ( httpDataRequest, Q_DEFER ) ->
@qRequest = [] if angular.isUndefined @qRequest
@qRequest.push Q_DEFER
promise = $http angular.extend httpDataRequest, { timeout : Q_DEFER.promise }
promise.finally ( () ->
@qRequest = _.filter @qRequest, (request) ->
request.url != httpDataRequest.url
return
)
return promise
cancelRequest : () ->
angular.forEach @qRequest, (canceller) ->
canceller.resolve()
return
@qRequest = [] if angular.isUndefined @qRequest
]
|
[
{
"context": "re.js')\n\npubnub = PUBNUB.init(\n subscribe_key : 'demo' # you should change this!\n publish_key : 'dem",
"end": 534,
"score": 0.9880419969558716,
"start": 530,
"tag": "KEY",
"value": "demo"
},
{
"context": "emo' # you should change this!\n publish_key : 'demo' # you should change this!\n)\n\nREDIS_ADDR = (proce",
"end": 585,
"score": 0.9898194670677185,
"start": 581,
"tag": "KEY",
"value": "demo"
}
] | src/pubnub-redis-replicate.coffee | sunnygleason/pubnub-persistence-redis | 2 | #
# PubNub Persistence: node.js replication handler
#
# "Connecting your worldwide apps to redis updates within 250ms"
#
# Usage: coffee src/pubnub-redis-replicate.coffee REDIS_ADDR CHANNEL_NAME
# - where REDIS_ADDR is the host:port
# - where CHANNEL_NAME is the Redis channel to receive updates
#
PUBNUB = require('../deps/pubnub-javascript/node.js/pubnub.js')
redisSync = require('../deps/redis-sync/redis-sync.js')
_ = require('../deps/underscore/underscore.js')
pubnub = PUBNUB.init(
subscribe_key : 'demo' # you should change this!
publish_key : 'demo' # you should change this!
)
REDIS_ADDR = (process.argv[2] || 'localhost:6379').split(":")
REDIS_HOST = REDIS_ADDR[0]
REDIS_PORT = REDIS_ADDR[1]
CHANNEL = process.argv[3]
# NOTE: this is just a partial list!
COMMANDS_TO_REPLICATE = ['set','mset','del','persist','rename','incr','incrby','decr','decrby','expire','expireat','pexpire','pexpireat','append']
COMMANDS_TO_REPLICATE_MAP = _(COMMANDS_TO_REPLICATE).reduce (a, x) ->
a[x] = true
a
, {}
# utility function for stringifying arguments
asString = (e) -> _.map(e, (x) -> x.toString())
#
# Create a Redis Sync instance (replication slave client)
#
sync = new redisSync.Sync()
#
# Set up RDB (Redis database) transfer events
#
sync.on 'rdb', (rdb) ->
console.log('starting RDB transfer')
rdb.on 'error', (err) -> console.error('ERROR!', err)
rdb.on 'end', () -> console.log('end of RDB')
#
# Set up RDB entity event handler
#
sync.on 'entity', (e) ->
entity = asString(e)
console.log 'Publishing entity:', JSON.stringify(entity)
pubnub.publish {channel:CHANNEL,message:{type:'entity',uuid:pubnub.uuid(),entity:entity}}
#
# Set up Redis command handler
#
sync.on 'command', (command, args) ->
entity = asString(args)
if COMMANDS_TO_REPLICATE_MAP[command]
payload = {channel:CHANNEL,message:{type:'command',uuid:pubnub.uuid(),command:command,args:entity}}
console.log 'Publishing command:', JSON.stringify(payload)
pubnub.publish payload
else
console.log 'Not publishing command:', JSON.stringify({command:command,args:entity})
# inline command (typically PING)
sync.on 'inlineCommand', (buffers) -> console.log('inline command (not published)', buffers.toString())
# error handler for general error events
sync.on 'error', (err) -> console.error('ERROR!', err)
# Start up and go!
console.log "Replicating from Redis host #{REDIS_ADDR} to PubNub channel \##{CHANNEL}"
sync.connect(REDIS_PORT, REDIS_HOST)
| 17227 | #
# PubNub Persistence: node.js replication handler
#
# "Connecting your worldwide apps to redis updates within 250ms"
#
# Usage: coffee src/pubnub-redis-replicate.coffee REDIS_ADDR CHANNEL_NAME
# - where REDIS_ADDR is the host:port
# - where CHANNEL_NAME is the Redis channel to receive updates
#
PUBNUB = require('../deps/pubnub-javascript/node.js/pubnub.js')
redisSync = require('../deps/redis-sync/redis-sync.js')
_ = require('../deps/underscore/underscore.js')
pubnub = PUBNUB.init(
subscribe_key : '<KEY>' # you should change this!
publish_key : '<KEY>' # you should change this!
)
REDIS_ADDR = (process.argv[2] || 'localhost:6379').split(":")
REDIS_HOST = REDIS_ADDR[0]
REDIS_PORT = REDIS_ADDR[1]
CHANNEL = process.argv[3]
# NOTE: this is just a partial list!
COMMANDS_TO_REPLICATE = ['set','mset','del','persist','rename','incr','incrby','decr','decrby','expire','expireat','pexpire','pexpireat','append']
COMMANDS_TO_REPLICATE_MAP = _(COMMANDS_TO_REPLICATE).reduce (a, x) ->
a[x] = true
a
, {}
# utility function for stringifying arguments
asString = (e) -> _.map(e, (x) -> x.toString())
#
# Create a Redis Sync instance (replication slave client)
#
sync = new redisSync.Sync()
#
# Set up RDB (Redis database) transfer events
#
sync.on 'rdb', (rdb) ->
console.log('starting RDB transfer')
rdb.on 'error', (err) -> console.error('ERROR!', err)
rdb.on 'end', () -> console.log('end of RDB')
#
# Set up RDB entity event handler
#
sync.on 'entity', (e) ->
entity = asString(e)
console.log 'Publishing entity:', JSON.stringify(entity)
pubnub.publish {channel:CHANNEL,message:{type:'entity',uuid:pubnub.uuid(),entity:entity}}
#
# Set up Redis command handler
#
sync.on 'command', (command, args) ->
entity = asString(args)
if COMMANDS_TO_REPLICATE_MAP[command]
payload = {channel:CHANNEL,message:{type:'command',uuid:pubnub.uuid(),command:command,args:entity}}
console.log 'Publishing command:', JSON.stringify(payload)
pubnub.publish payload
else
console.log 'Not publishing command:', JSON.stringify({command:command,args:entity})
# inline command (typically PING)
sync.on 'inlineCommand', (buffers) -> console.log('inline command (not published)', buffers.toString())
# error handler for general error events
sync.on 'error', (err) -> console.error('ERROR!', err)
# Start up and go!
console.log "Replicating from Redis host #{REDIS_ADDR} to PubNub channel \##{CHANNEL}"
sync.connect(REDIS_PORT, REDIS_HOST)
| true | #
# PubNub Persistence: node.js replication handler
#
# "Connecting your worldwide apps to redis updates within 250ms"
#
# Usage: coffee src/pubnub-redis-replicate.coffee REDIS_ADDR CHANNEL_NAME
# - where REDIS_ADDR is the host:port
# - where CHANNEL_NAME is the Redis channel to receive updates
#
PUBNUB = require('../deps/pubnub-javascript/node.js/pubnub.js')
redisSync = require('../deps/redis-sync/redis-sync.js')
_ = require('../deps/underscore/underscore.js')
pubnub = PUBNUB.init(
subscribe_key : 'PI:KEY:<KEY>END_PI' # you should change this!
publish_key : 'PI:KEY:<KEY>END_PI' # you should change this!
)
REDIS_ADDR = (process.argv[2] || 'localhost:6379').split(":")
REDIS_HOST = REDIS_ADDR[0]
REDIS_PORT = REDIS_ADDR[1]
CHANNEL = process.argv[3]
# NOTE: this is just a partial list!
COMMANDS_TO_REPLICATE = ['set','mset','del','persist','rename','incr','incrby','decr','decrby','expire','expireat','pexpire','pexpireat','append']
COMMANDS_TO_REPLICATE_MAP = _(COMMANDS_TO_REPLICATE).reduce (a, x) ->
a[x] = true
a
, {}
# utility function for stringifying arguments
asString = (e) -> _.map(e, (x) -> x.toString())
#
# Create a Redis Sync instance (replication slave client)
#
sync = new redisSync.Sync()
#
# Set up RDB (Redis database) transfer events
#
sync.on 'rdb', (rdb) ->
console.log('starting RDB transfer')
rdb.on 'error', (err) -> console.error('ERROR!', err)
rdb.on 'end', () -> console.log('end of RDB')
#
# Set up RDB entity event handler
#
sync.on 'entity', (e) ->
entity = asString(e)
console.log 'Publishing entity:', JSON.stringify(entity)
pubnub.publish {channel:CHANNEL,message:{type:'entity',uuid:pubnub.uuid(),entity:entity}}
#
# Set up Redis command handler
#
sync.on 'command', (command, args) ->
entity = asString(args)
if COMMANDS_TO_REPLICATE_MAP[command]
payload = {channel:CHANNEL,message:{type:'command',uuid:pubnub.uuid(),command:command,args:entity}}
console.log 'Publishing command:', JSON.stringify(payload)
pubnub.publish payload
else
console.log 'Not publishing command:', JSON.stringify({command:command,args:entity})
# inline command (typically PING)
sync.on 'inlineCommand', (buffers) -> console.log('inline command (not published)', buffers.toString())
# error handler for general error events
sync.on 'error', (err) -> console.error('ERROR!', err)
# Start up and go!
console.log "Replicating from Redis host #{REDIS_ADDR} to PubNub channel \##{CHANNEL}"
sync.connect(REDIS_PORT, REDIS_HOST)
|
[
{
"context": " defined because this is nested document.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n@abstract\r\n###\r\nclass Airc",
"end": 387,
"score": 0.9998070001602173,
"start": 375,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/schema/AircraftChecklistSectionSchema.coffee | qrefdev/qref | 0 | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
AircraftChecklistItemSchema = require('./AircraftChecklistItemSchema')
###
Nested Schema representing a specific checklist section.
@note This is a nested document and does not have a separate Mongo collection.
@note No indexes are defined because this is nested document.
@author Nathan Klick
@copyright QRef 2012
@abstract
###
class AircraftChecklistSectionSchemaInternal
###
@property [String] (Required) An enum value indicating the section type. Valid values are ['standard', 'emergency'].
###
sectionType:
type: String
required: true
enum: ['standard', 'emergency']
###
@property [Number] (Required) A numeric value indicating the position of this section relative to other sections.
###
index:
type: Number
required: true
###
@property [String] (Required) The name of this checklist section as displayed in the application.
###
name:
type: String
required: true
###
@property [Array<AircraftChecklistItemSchemaInternal>] (Optional) An array of ordered checklist items.
###
items:
type: [AircraftChecklistItemSchema]
required: false
###
@property [String] (Optional) A path to the sections icon relative to the root of the server.
###
sectionIcon:
type: String
required: false
AircraftChecklistSectionSchema = new Schema(new AircraftChecklistSectionSchemaInternal())
module.exports = AircraftChecklistSectionSchema | 214195 | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
AircraftChecklistItemSchema = require('./AircraftChecklistItemSchema')
###
Nested Schema representing a specific checklist section.
@note This is a nested document and does not have a separate Mongo collection.
@note No indexes are defined because this is nested document.
@author <NAME>
@copyright QRef 2012
@abstract
###
class AircraftChecklistSectionSchemaInternal
###
@property [String] (Required) An enum value indicating the section type. Valid values are ['standard', 'emergency'].
###
sectionType:
type: String
required: true
enum: ['standard', 'emergency']
###
@property [Number] (Required) A numeric value indicating the position of this section relative to other sections.
###
index:
type: Number
required: true
###
@property [String] (Required) The name of this checklist section as displayed in the application.
###
name:
type: String
required: true
###
@property [Array<AircraftChecklistItemSchemaInternal>] (Optional) An array of ordered checklist items.
###
items:
type: [AircraftChecklistItemSchema]
required: false
###
@property [String] (Optional) A path to the sections icon relative to the root of the server.
###
sectionIcon:
type: String
required: false
AircraftChecklistSectionSchema = new Schema(new AircraftChecklistSectionSchemaInternal())
module.exports = AircraftChecklistSectionSchema | true | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
AircraftChecklistItemSchema = require('./AircraftChecklistItemSchema')
###
Nested Schema representing a specific checklist section.
@note This is a nested document and does not have a separate Mongo collection.
@note No indexes are defined because this is nested document.
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
@abstract
###
class AircraftChecklistSectionSchemaInternal
###
@property [String] (Required) An enum value indicating the section type. Valid values are ['standard', 'emergency'].
###
sectionType:
type: String
required: true
enum: ['standard', 'emergency']
###
@property [Number] (Required) A numeric value indicating the position of this section relative to other sections.
###
index:
type: Number
required: true
###
@property [String] (Required) The name of this checklist section as displayed in the application.
###
name:
type: String
required: true
###
@property [Array<AircraftChecklistItemSchemaInternal>] (Optional) An array of ordered checklist items.
###
items:
type: [AircraftChecklistItemSchema]
required: false
###
@property [String] (Optional) A path to the sections icon relative to the root of the server.
###
sectionIcon:
type: String
required: false
AircraftChecklistSectionSchema = new Schema(new AircraftChecklistSectionSchemaInternal())
module.exports = AircraftChecklistSectionSchema |
[
{
"context": "### \n Baseline is Roxanne Vitorillo's BalloonTracker3.html modified from original\n B",
"end": 36,
"score": 0.9987238645553589,
"start": 19,
"tag": "NAME",
"value": "Roxanne Vitorillo"
}
] | app/assets/javascripts/tracker.js.coffee | lnigra/PusherProblemTest | 1 | ###
Baseline is Roxanne Vitorillo's BalloonTracker3.html modified from original
BalloonTracker2.html during ISGC summer 2013 session.
Started with scripts extracted from HTML then converted to coffeescript using
js2coffee.org.
HTML extracted minus head and scripts and placed in
app/assets/views/tracker/index.html.erb. Javascript includes covered with
ruby helper functions at end of that file.
###
hostname = window.location.hostname
port = window.location.port
### Parse data from Prediction KML file to show Balloon Burst ###
parseData = (req) ->
g = new (OpenLayers.Format.KML)(extractStyles: true)
html = ''
features = g.read(req.responseText)
for feat of features
html += '<ul>'
html += '<li>' + features[feat].attributes.description + '</li>'
html += '</ul>'
document.getElementById('output').innerHTML = html
return
load = ->
OpenLayers.loadURL '/data/aPREDICTION.kml', '', null, parseData
### must change KML file everytime before flight ###
return
#window.onbeforeunload = windowClose
### do some preliminary set up ###
oldaltitude = 0
maxaltitude = 0
###this is for the point/packet pop-ups on the maps ###
AutoSizeFramedCloud = OpenLayers.Class(OpenLayers.Popup.FramedCloud, 'autoSize': true)
###this is the default set of options used in many calls ###
OpenLayers.ImgPath = "/assets/OpenLayers/img/"
options =
projection: 'EPSG:900913'
units: 'm'
numZoomLevels: 17
maxResolution: 156543.0339
maxExtent: new (OpenLayers.Bounds)(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
controls: [new OpenLayers.Control.PanZoomBar,
new OpenLayers.Control.Navigation({dragPanOptions: {enableKinetic: true}})]
###and create a projection, size, pixel offset and icons for ###
###plotting ###
proj = new (OpenLayers.Projection)('EPSG:4326') # x/y => lat/lon
size = new (OpenLayers.Size)(8, 8)
offset = new (OpenLayers.Pixel)(-4, -4)
size2 = new (OpenLayers.Size)(12, 12)
offset2 = new (OpenLayers.Pixel)(-6, -6)
iconred = new (OpenLayers.Icon)('assets/markerSmallred.png', size, offset)
iconblue = new (OpenLayers.Icon)('assets/markerSmallblue.png', size, offset)
icongreen = new (OpenLayers.Icon)('assets/markerSmallgreen.png', size, offset)
iconpurple = new (OpenLayers.Icon)('assets/markerSmallpurple.png', size, offset)
iconlandingblue = new (OpenLayers.Icon)('assets/markerLandingblue.png', size2, offset2)
iconlandinggreen = new (OpenLayers.Icon)('assets/markerLandinggreen.png', size2, offset2)
iconlandingpurple = new (OpenLayers.Icon)('assets/markerLandingpurple.png', size2, offset2)
iconBurst = new (OpenLayers.Icon)('sunny.png', size2, offset2)
### end of set up, now start the main work ###
###start up a map ###
map = new (OpenLayers.Map)('map', options)
###and create a couple of layers for the map display ###
# NOTE: Path to stuff in app/assets/images is 'assets/<path beneath app/assets>
mapPort = $('#data').data( 'mapPort' )
streets = new (OpenLayers.Layer.TMS)('Streets', 'http://' + hostname + ':' + mapPort.toString() + '/streets/', #'assets/map.tiles/streets/',
'type': 'png'
'getURL': get_my_url)
aerial = new (OpenLayers.Layer.TMS)('Aerial', 'http://' + hostname + ':' + mapPort.toString() + '/aerial/', #'assets/map.tiles/aerial/',
'type': 'png'
'getURL': get_my_url)
###add these layers to the map ###
map.addLayer streets
map.addLayer aerial
dst = map.getProjectionObject() # EPSG:900913 (a.k.a. EPSG:3857) x/y => meters
###we can set the initial center, add a switcher and a scale ###
start_lat = 41.1000322 # degrees
start_lon = -87.9167100 # degrees
cpoint = new (OpenLayers.LonLat)( start_lon, start_lat )
map.setCenter cpoint.transform(proj, dst), 11
LaySwitch = new (OpenLayers.Control.LayerSwitcher)
map.addControl LaySwitch
map.addControl new (OpenLayers.Control.ScaleLine)(
geodesic: true
maxWidth: 200)
### Add the Layer with the Prediction Track ###
### Strategy.Fixed: requests features once and never requests new data ###
# NOTE: Path to stuff in puplic folder is <path beneath public>
predictionTrack = new (OpenLayers.Layer.Vector)('Prediction',
strategies: [ new (OpenLayers.Strategy.Fixed) ]
protocol: new (OpenLayers.Protocol.HTTP)(
url: '/data/aPREDICTION.kml'
format: new (OpenLayers.Format.KML))
style:
strokeColor: 'green'
strokeWidth: 5
strokeOpacity: 0.5
projection: proj)
map.addLayer predictionTrack
# Marker layers removed
# ---- Here's where the vector layer example code hack starts
# allow testing of specific renderers via "?renderer=Canvas", etc
renderer = OpenLayers.Util.getParameters(window.location.href).renderer
renderer = (if (renderer) then [renderer] else OpenLayers.Layer.Vector::renderers)
#
# * Layer style
#
# we want opaque external graphics and non-opaque internal graphics
layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
layer_style.fillOpacity = 0.5
layer_style.graphicOpacity = 1
#
# * Blue style
#
style_blue = OpenLayers.Util.extend({}, layer_style)
style_blue.strokeColor = "blue"
style_blue.fillColor = "blue"
style_blue.graphicName = "star"
style_blue.pointRadius = 5
style_blue.strokeWidth = 2
style_blue.rotation = 45
style_blue.strokeLinecap = "butt"
style_point_red = OpenLayers.Util.extend({}, layer_style)
style_point_red.strokeColor = "red"
style_point_red.fillColor = "red"
style_point_red.graphicName = "circle"
style_point_red.pointRadius = 3
style_point_red.strokeWidth = 1
style_point_red.rotation = 45
style_point_red.strokeLinecap = "butt"
#
# * Green style
#
style_green =
strokeColor: "#00FF00"
strokeWidth: 3
strokeDashstyle: "solid"
pointRadius: 6
pointerEvents: "visiblePainted"
title: "this is a green line"
#
# * Mark style
#
style_mark = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
style_mark.graphicOpacity = 1
style_mark.graphicWidth = 16
style_mark.graphicHeight = 16
style_mark.graphicXOffset = -style_mark.graphicWidth / 2 # default is -(style_mark.graphicWidth/2);
style_mark.graphicYOffset = -style_mark.graphicHeight
# LN - Path to vendor assets is 'assets/<path beneath javascripts>
style_mark.externalGraphic = "/assets/OpenLayers/img/marker.png"
style_mark.title = "this is a test tooltip"
#
# * Balloon style
#
style_balloon = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
style_balloon.graphicOpacity = 1
style_balloon.graphicWidth = 16
style_balloon.graphicHeight = 16
style_balloon.graphicXOffset = -style_balloon.graphicWidth / 2 # default is -(style_balloon.graphicWidth/2);
style_balloon.graphicYOffset = -style_balloon.graphicHeight
style_balloon.externalGraphic = "/assets/balloon.png"
# title only works in Firefox and Internet Explorer
style_balloon.title = "this is a test tooltip"
#
# * van style
#
style_van = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
style_van.graphicOpacity = 1
style_van.graphicWidth = 16
style_van.graphicHeight = 16
style_van.graphicXOffset = -style_van.graphicWidth / 2 # default is -(style_van.graphicWidth/2);
style_van.graphicYOffset = -style_van.graphicHeight / 2
# LN - Path to vendor assets is '/assets/<path beneath javascripts>
style_van.externalGraphic = "/assets/van.png"
# title only works in Firefox and Internet Explorer
style_van.title = "this is a test tooltip"
platformLayer = new OpenLayers.Layer.Vector("Platform",
style: layer_style
renderers: renderer
)
vehicleLayer = new OpenLayers.Layer.Vector("Vehicle",
style: layer_style
renderers: renderer
)
map.addLayer platformLayer
map.addLayer vehicleLayer
thisVehicleLastTime = null
thisVehiclePoint = new OpenLayers.Geometry.Point( null, null )
thisVehicleLocation = null
urlVehicleLoc = '/chase_vehicle_location/'
thisVehicleId = $('#data').data( 'thisVehicle' ).id
locDev = $('#data').data( 'locDev' )
updateVehicleLocation = ( vehicleId ) ->
$.getJSON urlVehicleLoc + vehicleId, (data) ->
if data and data['time'] isnt thisVehicleLastTime
vehicleLayer.destroyFeatures( [ thisVehicleLocation ] ) if thisVehicleLocation
tmpPoint = new OpenLayers.Geometry.Point( data['lon'], data['lat'] )
thisVehiclePoint = tmpPoint.clone().transform( proj, dst )
thisVehicleLocation = new OpenLayers.Feature.Vector(
thisVehiclePoint, null, style_van )
vehicleLayer.addFeatures( [ thisVehicleLocation ] )
thisVehicleLastTime = data['time']
platforms = $('#data').data('platforms')
platformIds = ( x.id for x in platforms )
urlPlatformTracks = '/platform_tracks/'
platformTracks = ( [] for x in platformIds )
platformTrackMultiPoints = ( [] for x in platformIds )
platformTrackLines = ( [] for x in platformIds )
platformTrackTimes = ( "Jan 28 1986" for x in platformIds )
platformLocations = ( [] for x in platformIds )
beaconRcvrs = $('#data').data('beaconRcvrs')
updatePlatformTracks = ( index ) ->
$.getJSON urlPlatformTracks + platformIds[index], after_time: platformTrackTimes[index], (data) ->
if data
for track in data
newTrackFlg = true
unless track is null
for temp, num in platformTracks[index]
if temp.ident is track.ident
# append new points to reference array
newTrackFlg = false
temp.points.push( track.points )
# append new points to feature point array
lastPoint = null
for point in track.points
tmpPoint = new OpenLayers.Geometry.Point( point['lon'], point['lat'] )
platformTrackMultiPoints[index][num].addPoint( tmpPoint.clone().transform( proj, dst ) )
platformTrackLines[index][num].addPoint( tmpPoint.clone().transform( proj, dst ) )
lastPoint = tmpPoint
if lastPoint
platformLayer.destroyFeatures( [ platformLocations[index][num] ] )
platformLocations[index][num] = new OpenLayers.Feature.Vector(
tmpPoint.clone().transform( proj, dst ), null, style_balloon )
platformLayer.addFeatures( [ platformLocations[index][num] ] )
temp.last_time = track.last_time
platformTrackTimes[index] = temp.last_time if temp.last_time > platformTrackTimes[index]
if newTrackFlg and track isnt null
platformTracks[index].push track
platformTrackMultiPoints[index].push new OpenLayers.Geometry.MultiPoint([])
platformTrackLines[index].push new OpenLayers.Geometry.LineString(null)
platformTrackTimes[index] = track.last_time
platformLocations[index].push null
trackIndex = platformTracks[index].length - 1
lastPoint = null
for point, num in track.points
tmpPoint = new OpenLayers.Geometry.Point( point['lon'], point['lat'] )
platformTrackMultiPoints[index][trackIndex].addPoint(
tmpPoint.clone().transform( proj, dst ) )
platformTrackLines[index][trackIndex].addPoint(
tmpPoint.clone().transform( proj, dst ) )
lastPoint = tmpPoint
platformLayer.addFeatures( [ new OpenLayers.Feature.Vector(
platformTrackLines[index][trackIndex], null, style_green ) ] )
platformLayer.addFeatures( [ new OpenLayers.Feature.Vector(
platformTrackMultiPoints[index][trackIndex], null, style_point_red ) ] )
if lastPoint
platformLocations[index][trackIndex] = new OpenLayers.Feature.Vector(
tmpPoint.clone().transform( proj, dst ), null, style_balloon )
platformLayer.addFeatures( [ platformLocations[index][trackIndex] ] )
platformLayer.redraw()
isSim = false
for rcvr in beaconRcvrs
isSim = true if rcvr.driver[-3...] is 'sim'
isSim = true if locDev.driver[-3...] is 'sim'
### update once and then set on a 5 sec cycle ###
updateVehicleLocation( thisVehicleId )
updatePlatformTracks( 0 )
count = 0
timerId =
setInterval => # 'Fat' arrow stransfers 'scope' (or whatever it's called in
# js) to the inner function.
updateVehicleLocation(thisVehicleId)
updatePlatformTracks( 0 )
#clearInterval( timerId ) if count++ is 2
, 10000
$('#control #locSimStart').click ->
if isSim
vehicleLayer.destroyFeatures()
thisVehicleLastTime = null
thisVehiclePoint = new OpenLayers.Geometry.Point( null, null )
thisVehicleLocation = null
speedup = $("#simSpeed input[type='radio']:checked").val()
url = 'http://' + hostname + ':' + port + '/location_devices/start/' + locDev.id + '/' + speedup
$.post url, (data) ->
$('#control #locDriver').html(data)
$('#control #locSimEnd').click ->
url = 'http://' + hostname + ':' + port + '/location_devices/stop/' + locDev.id
$.post url, (data) ->
$('#control #locDriver').html(data)
$('#control #beaconSimStart').click ->
if isSim
platformLayer.destroyFeatures()
platformTracks = ( [] for x in platformIds )
platformTrackMultiPoints = ( [] for x in platformIds )
platformTrackLines = ( [] for x in platformIds )
platformTrackTimes = ( "Jan 28 1986" for x in platformIds )
platformLocations = ( [] for x in platformIds )
speedup = $("#simSpeed input[type='radio']:checked").val()
for rcvr in beaconRcvrs
url = 'http://' + hostname + ':' + port + '/beacon_receivers/start/' + rcvr.id + '/' + speedup
$.post url, (data) ->
$('#control #beaconDriver').html(data)
#console.log 'Sim Start'
$('#control #beaconSimEnd').click ->
for rcvr in beaconRcvrs
url = 'http://' + hostname + ':' + port + '/beacon_receivers/stop/' + rcvr.id
#console.log 'Sim End'
$.post url, (data) ->
$('#control #beaconDriver').html(data)
###
Still to do:
Interface work.
Balloon Dynamics should include van to balloon distance and bearing
chat sign in and layout improved
look and feel improved
Van location data and marker
better handling of the creation of map markers. Probably better to recreate each marker each time. May be slower but makes it stateless which is much easier.
Better Landing estimates
Better handling of wind data
More generally, need to test out hardware/serial routines, work out wireless web serving and van gps aquisition
need to write Processing code to:
1) select serial port
2) select callsigns for tracking
3) clear up chat files
4) pull wind data
5) listen to serial port for call sign APRS packets and parse them for callsign.txt files
###
# ---
# generated by js2coffee 2.0.1 | 12492 | ###
Baseline is <NAME>'s BalloonTracker3.html modified from original
BalloonTracker2.html during ISGC summer 2013 session.
Started with scripts extracted from HTML then converted to coffeescript using
js2coffee.org.
HTML extracted minus head and scripts and placed in
app/assets/views/tracker/index.html.erb. Javascript includes covered with
ruby helper functions at end of that file.
###
hostname = window.location.hostname
port = window.location.port
### Parse data from Prediction KML file to show Balloon Burst ###
parseData = (req) ->
g = new (OpenLayers.Format.KML)(extractStyles: true)
html = ''
features = g.read(req.responseText)
for feat of features
html += '<ul>'
html += '<li>' + features[feat].attributes.description + '</li>'
html += '</ul>'
document.getElementById('output').innerHTML = html
return
load = ->
OpenLayers.loadURL '/data/aPREDICTION.kml', '', null, parseData
### must change KML file everytime before flight ###
return
#window.onbeforeunload = windowClose
### do some preliminary set up ###
oldaltitude = 0
maxaltitude = 0
###this is for the point/packet pop-ups on the maps ###
AutoSizeFramedCloud = OpenLayers.Class(OpenLayers.Popup.FramedCloud, 'autoSize': true)
###this is the default set of options used in many calls ###
OpenLayers.ImgPath = "/assets/OpenLayers/img/"
options =
projection: 'EPSG:900913'
units: 'm'
numZoomLevels: 17
maxResolution: 156543.0339
maxExtent: new (OpenLayers.Bounds)(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
controls: [new OpenLayers.Control.PanZoomBar,
new OpenLayers.Control.Navigation({dragPanOptions: {enableKinetic: true}})]
###and create a projection, size, pixel offset and icons for ###
###plotting ###
proj = new (OpenLayers.Projection)('EPSG:4326') # x/y => lat/lon
size = new (OpenLayers.Size)(8, 8)
offset = new (OpenLayers.Pixel)(-4, -4)
size2 = new (OpenLayers.Size)(12, 12)
offset2 = new (OpenLayers.Pixel)(-6, -6)
iconred = new (OpenLayers.Icon)('assets/markerSmallred.png', size, offset)
iconblue = new (OpenLayers.Icon)('assets/markerSmallblue.png', size, offset)
icongreen = new (OpenLayers.Icon)('assets/markerSmallgreen.png', size, offset)
iconpurple = new (OpenLayers.Icon)('assets/markerSmallpurple.png', size, offset)
iconlandingblue = new (OpenLayers.Icon)('assets/markerLandingblue.png', size2, offset2)
iconlandinggreen = new (OpenLayers.Icon)('assets/markerLandinggreen.png', size2, offset2)
iconlandingpurple = new (OpenLayers.Icon)('assets/markerLandingpurple.png', size2, offset2)
iconBurst = new (OpenLayers.Icon)('sunny.png', size2, offset2)
### end of set up, now start the main work ###
###start up a map ###
map = new (OpenLayers.Map)('map', options)
###and create a couple of layers for the map display ###
# NOTE: Path to stuff in app/assets/images is 'assets/<path beneath app/assets>
mapPort = $('#data').data( 'mapPort' )
streets = new (OpenLayers.Layer.TMS)('Streets', 'http://' + hostname + ':' + mapPort.toString() + '/streets/', #'assets/map.tiles/streets/',
'type': 'png'
'getURL': get_my_url)
aerial = new (OpenLayers.Layer.TMS)('Aerial', 'http://' + hostname + ':' + mapPort.toString() + '/aerial/', #'assets/map.tiles/aerial/',
'type': 'png'
'getURL': get_my_url)
###add these layers to the map ###
map.addLayer streets
map.addLayer aerial
dst = map.getProjectionObject() # EPSG:900913 (a.k.a. EPSG:3857) x/y => meters
###we can set the initial center, add a switcher and a scale ###
start_lat = 41.1000322 # degrees
start_lon = -87.9167100 # degrees
cpoint = new (OpenLayers.LonLat)( start_lon, start_lat )
map.setCenter cpoint.transform(proj, dst), 11
LaySwitch = new (OpenLayers.Control.LayerSwitcher)
map.addControl LaySwitch
map.addControl new (OpenLayers.Control.ScaleLine)(
geodesic: true
maxWidth: 200)
### Add the Layer with the Prediction Track ###
### Strategy.Fixed: requests features once and never requests new data ###
# NOTE: Path to stuff in puplic folder is <path beneath public>
predictionTrack = new (OpenLayers.Layer.Vector)('Prediction',
strategies: [ new (OpenLayers.Strategy.Fixed) ]
protocol: new (OpenLayers.Protocol.HTTP)(
url: '/data/aPREDICTION.kml'
format: new (OpenLayers.Format.KML))
style:
strokeColor: 'green'
strokeWidth: 5
strokeOpacity: 0.5
projection: proj)
map.addLayer predictionTrack
# Marker layers removed
# ---- Here's where the vector layer example code hack starts
# allow testing of specific renderers via "?renderer=Canvas", etc
renderer = OpenLayers.Util.getParameters(window.location.href).renderer
renderer = (if (renderer) then [renderer] else OpenLayers.Layer.Vector::renderers)
#
# * Layer style
#
# we want opaque external graphics and non-opaque internal graphics
layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
layer_style.fillOpacity = 0.5
layer_style.graphicOpacity = 1
#
# * Blue style
#
style_blue = OpenLayers.Util.extend({}, layer_style)
style_blue.strokeColor = "blue"
style_blue.fillColor = "blue"
style_blue.graphicName = "star"
style_blue.pointRadius = 5
style_blue.strokeWidth = 2
style_blue.rotation = 45
style_blue.strokeLinecap = "butt"
style_point_red = OpenLayers.Util.extend({}, layer_style)
style_point_red.strokeColor = "red"
style_point_red.fillColor = "red"
style_point_red.graphicName = "circle"
style_point_red.pointRadius = 3
style_point_red.strokeWidth = 1
style_point_red.rotation = 45
style_point_red.strokeLinecap = "butt"
#
# * Green style
#
style_green =
strokeColor: "#00FF00"
strokeWidth: 3
strokeDashstyle: "solid"
pointRadius: 6
pointerEvents: "visiblePainted"
title: "this is a green line"
#
# * Mark style
#
style_mark = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
style_mark.graphicOpacity = 1
style_mark.graphicWidth = 16
style_mark.graphicHeight = 16
style_mark.graphicXOffset = -style_mark.graphicWidth / 2 # default is -(style_mark.graphicWidth/2);
style_mark.graphicYOffset = -style_mark.graphicHeight
# LN - Path to vendor assets is 'assets/<path beneath javascripts>
style_mark.externalGraphic = "/assets/OpenLayers/img/marker.png"
style_mark.title = "this is a test tooltip"
#
# * Balloon style
#
style_balloon = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
style_balloon.graphicOpacity = 1
style_balloon.graphicWidth = 16
style_balloon.graphicHeight = 16
style_balloon.graphicXOffset = -style_balloon.graphicWidth / 2 # default is -(style_balloon.graphicWidth/2);
style_balloon.graphicYOffset = -style_balloon.graphicHeight
style_balloon.externalGraphic = "/assets/balloon.png"
# title only works in Firefox and Internet Explorer
style_balloon.title = "this is a test tooltip"
#
# * van style
#
style_van = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
style_van.graphicOpacity = 1
style_van.graphicWidth = 16
style_van.graphicHeight = 16
style_van.graphicXOffset = -style_van.graphicWidth / 2 # default is -(style_van.graphicWidth/2);
style_van.graphicYOffset = -style_van.graphicHeight / 2
# LN - Path to vendor assets is '/assets/<path beneath javascripts>
style_van.externalGraphic = "/assets/van.png"
# title only works in Firefox and Internet Explorer
style_van.title = "this is a test tooltip"
platformLayer = new OpenLayers.Layer.Vector("Platform",
style: layer_style
renderers: renderer
)
vehicleLayer = new OpenLayers.Layer.Vector("Vehicle",
style: layer_style
renderers: renderer
)
map.addLayer platformLayer
map.addLayer vehicleLayer
thisVehicleLastTime = null
thisVehiclePoint = new OpenLayers.Geometry.Point( null, null )
thisVehicleLocation = null
urlVehicleLoc = '/chase_vehicle_location/'
thisVehicleId = $('#data').data( 'thisVehicle' ).id
locDev = $('#data').data( 'locDev' )
updateVehicleLocation = ( vehicleId ) ->
$.getJSON urlVehicleLoc + vehicleId, (data) ->
if data and data['time'] isnt thisVehicleLastTime
vehicleLayer.destroyFeatures( [ thisVehicleLocation ] ) if thisVehicleLocation
tmpPoint = new OpenLayers.Geometry.Point( data['lon'], data['lat'] )
thisVehiclePoint = tmpPoint.clone().transform( proj, dst )
thisVehicleLocation = new OpenLayers.Feature.Vector(
thisVehiclePoint, null, style_van )
vehicleLayer.addFeatures( [ thisVehicleLocation ] )
thisVehicleLastTime = data['time']
platforms = $('#data').data('platforms')
platformIds = ( x.id for x in platforms )
urlPlatformTracks = '/platform_tracks/'
platformTracks = ( [] for x in platformIds )
platformTrackMultiPoints = ( [] for x in platformIds )
platformTrackLines = ( [] for x in platformIds )
platformTrackTimes = ( "Jan 28 1986" for x in platformIds )
platformLocations = ( [] for x in platformIds )
beaconRcvrs = $('#data').data('beaconRcvrs')
updatePlatformTracks = ( index ) ->
$.getJSON urlPlatformTracks + platformIds[index], after_time: platformTrackTimes[index], (data) ->
if data
for track in data
newTrackFlg = true
unless track is null
for temp, num in platformTracks[index]
if temp.ident is track.ident
# append new points to reference array
newTrackFlg = false
temp.points.push( track.points )
# append new points to feature point array
lastPoint = null
for point in track.points
tmpPoint = new OpenLayers.Geometry.Point( point['lon'], point['lat'] )
platformTrackMultiPoints[index][num].addPoint( tmpPoint.clone().transform( proj, dst ) )
platformTrackLines[index][num].addPoint( tmpPoint.clone().transform( proj, dst ) )
lastPoint = tmpPoint
if lastPoint
platformLayer.destroyFeatures( [ platformLocations[index][num] ] )
platformLocations[index][num] = new OpenLayers.Feature.Vector(
tmpPoint.clone().transform( proj, dst ), null, style_balloon )
platformLayer.addFeatures( [ platformLocations[index][num] ] )
temp.last_time = track.last_time
platformTrackTimes[index] = temp.last_time if temp.last_time > platformTrackTimes[index]
if newTrackFlg and track isnt null
platformTracks[index].push track
platformTrackMultiPoints[index].push new OpenLayers.Geometry.MultiPoint([])
platformTrackLines[index].push new OpenLayers.Geometry.LineString(null)
platformTrackTimes[index] = track.last_time
platformLocations[index].push null
trackIndex = platformTracks[index].length - 1
lastPoint = null
for point, num in track.points
tmpPoint = new OpenLayers.Geometry.Point( point['lon'], point['lat'] )
platformTrackMultiPoints[index][trackIndex].addPoint(
tmpPoint.clone().transform( proj, dst ) )
platformTrackLines[index][trackIndex].addPoint(
tmpPoint.clone().transform( proj, dst ) )
lastPoint = tmpPoint
platformLayer.addFeatures( [ new OpenLayers.Feature.Vector(
platformTrackLines[index][trackIndex], null, style_green ) ] )
platformLayer.addFeatures( [ new OpenLayers.Feature.Vector(
platformTrackMultiPoints[index][trackIndex], null, style_point_red ) ] )
if lastPoint
platformLocations[index][trackIndex] = new OpenLayers.Feature.Vector(
tmpPoint.clone().transform( proj, dst ), null, style_balloon )
platformLayer.addFeatures( [ platformLocations[index][trackIndex] ] )
platformLayer.redraw()
isSim = false
for rcvr in beaconRcvrs
isSim = true if rcvr.driver[-3...] is 'sim'
isSim = true if locDev.driver[-3...] is 'sim'
### update once and then set on a 5 sec cycle ###
updateVehicleLocation( thisVehicleId )
updatePlatformTracks( 0 )
count = 0
timerId =
setInterval => # 'Fat' arrow stransfers 'scope' (or whatever it's called in
# js) to the inner function.
updateVehicleLocation(thisVehicleId)
updatePlatformTracks( 0 )
#clearInterval( timerId ) if count++ is 2
, 10000
$('#control #locSimStart').click ->
if isSim
vehicleLayer.destroyFeatures()
thisVehicleLastTime = null
thisVehiclePoint = new OpenLayers.Geometry.Point( null, null )
thisVehicleLocation = null
speedup = $("#simSpeed input[type='radio']:checked").val()
url = 'http://' + hostname + ':' + port + '/location_devices/start/' + locDev.id + '/' + speedup
$.post url, (data) ->
$('#control #locDriver').html(data)
$('#control #locSimEnd').click ->
url = 'http://' + hostname + ':' + port + '/location_devices/stop/' + locDev.id
$.post url, (data) ->
$('#control #locDriver').html(data)
$('#control #beaconSimStart').click ->
if isSim
platformLayer.destroyFeatures()
platformTracks = ( [] for x in platformIds )
platformTrackMultiPoints = ( [] for x in platformIds )
platformTrackLines = ( [] for x in platformIds )
platformTrackTimes = ( "Jan 28 1986" for x in platformIds )
platformLocations = ( [] for x in platformIds )
speedup = $("#simSpeed input[type='radio']:checked").val()
for rcvr in beaconRcvrs
url = 'http://' + hostname + ':' + port + '/beacon_receivers/start/' + rcvr.id + '/' + speedup
$.post url, (data) ->
$('#control #beaconDriver').html(data)
#console.log 'Sim Start'
$('#control #beaconSimEnd').click ->
for rcvr in beaconRcvrs
url = 'http://' + hostname + ':' + port + '/beacon_receivers/stop/' + rcvr.id
#console.log 'Sim End'
$.post url, (data) ->
$('#control #beaconDriver').html(data)
###
Still to do:
Interface work.
Balloon Dynamics should include van to balloon distance and bearing
chat sign in and layout improved
look and feel improved
Van location data and marker
better handling of the creation of map markers. Probably better to recreate each marker each time. May be slower but makes it stateless which is much easier.
Better Landing estimates
Better handling of wind data
More generally, need to test out hardware/serial routines, work out wireless web serving and van gps aquisition
need to write Processing code to:
1) select serial port
2) select callsigns for tracking
3) clear up chat files
4) pull wind data
5) listen to serial port for call sign APRS packets and parse them for callsign.txt files
###
# ---
# generated by js2coffee 2.0.1 | true | ###
Baseline is PI:NAME:<NAME>END_PI's BalloonTracker3.html modified from original
BalloonTracker2.html during ISGC summer 2013 session.
Started with scripts extracted from HTML then converted to coffeescript using
js2coffee.org.
HTML extracted minus head and scripts and placed in
app/assets/views/tracker/index.html.erb. Javascript includes covered with
ruby helper functions at end of that file.
###
hostname = window.location.hostname
port = window.location.port
### Parse data from Prediction KML file to show Balloon Burst ###
parseData = (req) ->
g = new (OpenLayers.Format.KML)(extractStyles: true)
html = ''
features = g.read(req.responseText)
for feat of features
html += '<ul>'
html += '<li>' + features[feat].attributes.description + '</li>'
html += '</ul>'
document.getElementById('output').innerHTML = html
return
load = ->
OpenLayers.loadURL '/data/aPREDICTION.kml', '', null, parseData
### must change KML file everytime before flight ###
return
#window.onbeforeunload = windowClose
### do some preliminary set up ###
oldaltitude = 0
maxaltitude = 0
###this is for the point/packet pop-ups on the maps ###
AutoSizeFramedCloud = OpenLayers.Class(OpenLayers.Popup.FramedCloud, 'autoSize': true)
###this is the default set of options used in many calls ###
OpenLayers.ImgPath = "/assets/OpenLayers/img/"
options =
projection: 'EPSG:900913'
units: 'm'
numZoomLevels: 17
maxResolution: 156543.0339
maxExtent: new (OpenLayers.Bounds)(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
controls: [new OpenLayers.Control.PanZoomBar,
new OpenLayers.Control.Navigation({dragPanOptions: {enableKinetic: true}})]
###and create a projection, size, pixel offset and icons for ###
###plotting ###
proj = new (OpenLayers.Projection)('EPSG:4326') # x/y => lat/lon
size = new (OpenLayers.Size)(8, 8)
offset = new (OpenLayers.Pixel)(-4, -4)
size2 = new (OpenLayers.Size)(12, 12)
offset2 = new (OpenLayers.Pixel)(-6, -6)
iconred = new (OpenLayers.Icon)('assets/markerSmallred.png', size, offset)
iconblue = new (OpenLayers.Icon)('assets/markerSmallblue.png', size, offset)
icongreen = new (OpenLayers.Icon)('assets/markerSmallgreen.png', size, offset)
iconpurple = new (OpenLayers.Icon)('assets/markerSmallpurple.png', size, offset)
iconlandingblue = new (OpenLayers.Icon)('assets/markerLandingblue.png', size2, offset2)
iconlandinggreen = new (OpenLayers.Icon)('assets/markerLandinggreen.png', size2, offset2)
iconlandingpurple = new (OpenLayers.Icon)('assets/markerLandingpurple.png', size2, offset2)
iconBurst = new (OpenLayers.Icon)('sunny.png', size2, offset2)
### end of set up, now start the main work ###
###start up a map ###
map = new (OpenLayers.Map)('map', options)
###and create a couple of layers for the map display ###
# NOTE: Path to stuff in app/assets/images is 'assets/<path beneath app/assets>
mapPort = $('#data').data( 'mapPort' )
streets = new (OpenLayers.Layer.TMS)('Streets', 'http://' + hostname + ':' + mapPort.toString() + '/streets/', #'assets/map.tiles/streets/',
'type': 'png'
'getURL': get_my_url)
aerial = new (OpenLayers.Layer.TMS)('Aerial', 'http://' + hostname + ':' + mapPort.toString() + '/aerial/', #'assets/map.tiles/aerial/',
'type': 'png'
'getURL': get_my_url)
###add these layers to the map ###
map.addLayer streets
map.addLayer aerial
dst = map.getProjectionObject() # EPSG:900913 (a.k.a. EPSG:3857) x/y => meters
###we can set the initial center, add a switcher and a scale ###
start_lat = 41.1000322 # degrees
start_lon = -87.9167100 # degrees
cpoint = new (OpenLayers.LonLat)( start_lon, start_lat )
map.setCenter cpoint.transform(proj, dst), 11
LaySwitch = new (OpenLayers.Control.LayerSwitcher)
map.addControl LaySwitch
map.addControl new (OpenLayers.Control.ScaleLine)(
geodesic: true
maxWidth: 200)
### Add the Layer with the Prediction Track ###
### Strategy.Fixed: requests features once and never requests new data ###
# NOTE: Path to stuff in puplic folder is <path beneath public>
predictionTrack = new (OpenLayers.Layer.Vector)('Prediction',
strategies: [ new (OpenLayers.Strategy.Fixed) ]
protocol: new (OpenLayers.Protocol.HTTP)(
url: '/data/aPREDICTION.kml'
format: new (OpenLayers.Format.KML))
style:
strokeColor: 'green'
strokeWidth: 5
strokeOpacity: 0.5
projection: proj)
map.addLayer predictionTrack
# Marker layers removed
# ---- Here's where the vector layer example code hack starts
# allow testing of specific renderers via "?renderer=Canvas", etc
renderer = OpenLayers.Util.getParameters(window.location.href).renderer
renderer = (if (renderer) then [renderer] else OpenLayers.Layer.Vector::renderers)
#
# * Layer style
#
# we want opaque external graphics and non-opaque internal graphics
layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
layer_style.fillOpacity = 0.5
layer_style.graphicOpacity = 1
#
# * Blue style
#
style_blue = OpenLayers.Util.extend({}, layer_style)
style_blue.strokeColor = "blue"
style_blue.fillColor = "blue"
style_blue.graphicName = "star"
style_blue.pointRadius = 5
style_blue.strokeWidth = 2
style_blue.rotation = 45
style_blue.strokeLinecap = "butt"
style_point_red = OpenLayers.Util.extend({}, layer_style)
style_point_red.strokeColor = "red"
style_point_red.fillColor = "red"
style_point_red.graphicName = "circle"
style_point_red.pointRadius = 3
style_point_red.strokeWidth = 1
style_point_red.rotation = 45
style_point_red.strokeLinecap = "butt"
#
# * Green style
#
style_green =
strokeColor: "#00FF00"
strokeWidth: 3
strokeDashstyle: "solid"
pointRadius: 6
pointerEvents: "visiblePainted"
title: "this is a green line"
#
# * Mark style
#
style_mark = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
style_mark.graphicOpacity = 1
style_mark.graphicWidth = 16
style_mark.graphicHeight = 16
style_mark.graphicXOffset = -style_mark.graphicWidth / 2 # default is -(style_mark.graphicWidth/2);
style_mark.graphicYOffset = -style_mark.graphicHeight
# LN - Path to vendor assets is 'assets/<path beneath javascripts>
style_mark.externalGraphic = "/assets/OpenLayers/img/marker.png"
style_mark.title = "this is a test tooltip"
#
# * Balloon style
#
style_balloon = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
style_balloon.graphicOpacity = 1
style_balloon.graphicWidth = 16
style_balloon.graphicHeight = 16
style_balloon.graphicXOffset = -style_balloon.graphicWidth / 2 # default is -(style_balloon.graphicWidth/2);
style_balloon.graphicYOffset = -style_balloon.graphicHeight
style_balloon.externalGraphic = "/assets/balloon.png"
# title only works in Firefox and Internet Explorer
style_balloon.title = "this is a test tooltip"
#
# * van style
#
style_van = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style["default"])
style_van.graphicOpacity = 1
style_van.graphicWidth = 16
style_van.graphicHeight = 16
style_van.graphicXOffset = -style_van.graphicWidth / 2 # default is -(style_van.graphicWidth/2);
style_van.graphicYOffset = -style_van.graphicHeight / 2
# LN - Path to vendor assets is '/assets/<path beneath javascripts>
style_van.externalGraphic = "/assets/van.png"
# title only works in Firefox and Internet Explorer
style_van.title = "this is a test tooltip"
platformLayer = new OpenLayers.Layer.Vector("Platform",
style: layer_style
renderers: renderer
)
vehicleLayer = new OpenLayers.Layer.Vector("Vehicle",
style: layer_style
renderers: renderer
)
map.addLayer platformLayer
map.addLayer vehicleLayer
thisVehicleLastTime = null
thisVehiclePoint = new OpenLayers.Geometry.Point( null, null )
thisVehicleLocation = null
urlVehicleLoc = '/chase_vehicle_location/'
thisVehicleId = $('#data').data( 'thisVehicle' ).id
locDev = $('#data').data( 'locDev' )
updateVehicleLocation = ( vehicleId ) ->
$.getJSON urlVehicleLoc + vehicleId, (data) ->
if data and data['time'] isnt thisVehicleLastTime
vehicleLayer.destroyFeatures( [ thisVehicleLocation ] ) if thisVehicleLocation
tmpPoint = new OpenLayers.Geometry.Point( data['lon'], data['lat'] )
thisVehiclePoint = tmpPoint.clone().transform( proj, dst )
thisVehicleLocation = new OpenLayers.Feature.Vector(
thisVehiclePoint, null, style_van )
vehicleLayer.addFeatures( [ thisVehicleLocation ] )
thisVehicleLastTime = data['time']
platforms = $('#data').data('platforms')
platformIds = ( x.id for x in platforms )
urlPlatformTracks = '/platform_tracks/'
platformTracks = ( [] for x in platformIds )
platformTrackMultiPoints = ( [] for x in platformIds )
platformTrackLines = ( [] for x in platformIds )
platformTrackTimes = ( "Jan 28 1986" for x in platformIds )
platformLocations = ( [] for x in platformIds )
beaconRcvrs = $('#data').data('beaconRcvrs')
updatePlatformTracks = ( index ) ->
$.getJSON urlPlatformTracks + platformIds[index], after_time: platformTrackTimes[index], (data) ->
if data
for track in data
newTrackFlg = true
unless track is null
for temp, num in platformTracks[index]
if temp.ident is track.ident
# append new points to reference array
newTrackFlg = false
temp.points.push( track.points )
# append new points to feature point array
lastPoint = null
for point in track.points
tmpPoint = new OpenLayers.Geometry.Point( point['lon'], point['lat'] )
platformTrackMultiPoints[index][num].addPoint( tmpPoint.clone().transform( proj, dst ) )
platformTrackLines[index][num].addPoint( tmpPoint.clone().transform( proj, dst ) )
lastPoint = tmpPoint
if lastPoint
platformLayer.destroyFeatures( [ platformLocations[index][num] ] )
platformLocations[index][num] = new OpenLayers.Feature.Vector(
tmpPoint.clone().transform( proj, dst ), null, style_balloon )
platformLayer.addFeatures( [ platformLocations[index][num] ] )
temp.last_time = track.last_time
platformTrackTimes[index] = temp.last_time if temp.last_time > platformTrackTimes[index]
if newTrackFlg and track isnt null
platformTracks[index].push track
platformTrackMultiPoints[index].push new OpenLayers.Geometry.MultiPoint([])
platformTrackLines[index].push new OpenLayers.Geometry.LineString(null)
platformTrackTimes[index] = track.last_time
platformLocations[index].push null
trackIndex = platformTracks[index].length - 1
lastPoint = null
for point, num in track.points
tmpPoint = new OpenLayers.Geometry.Point( point['lon'], point['lat'] )
platformTrackMultiPoints[index][trackIndex].addPoint(
tmpPoint.clone().transform( proj, dst ) )
platformTrackLines[index][trackIndex].addPoint(
tmpPoint.clone().transform( proj, dst ) )
lastPoint = tmpPoint
platformLayer.addFeatures( [ new OpenLayers.Feature.Vector(
platformTrackLines[index][trackIndex], null, style_green ) ] )
platformLayer.addFeatures( [ new OpenLayers.Feature.Vector(
platformTrackMultiPoints[index][trackIndex], null, style_point_red ) ] )
if lastPoint
platformLocations[index][trackIndex] = new OpenLayers.Feature.Vector(
tmpPoint.clone().transform( proj, dst ), null, style_balloon )
platformLayer.addFeatures( [ platformLocations[index][trackIndex] ] )
platformLayer.redraw()
isSim = false
for rcvr in beaconRcvrs
isSim = true if rcvr.driver[-3...] is 'sim'
isSim = true if locDev.driver[-3...] is 'sim'
### update once and then set on a 5 sec cycle ###
updateVehicleLocation( thisVehicleId )
updatePlatformTracks( 0 )
count = 0
timerId =
setInterval => # 'Fat' arrow stransfers 'scope' (or whatever it's called in
# js) to the inner function.
updateVehicleLocation(thisVehicleId)
updatePlatformTracks( 0 )
#clearInterval( timerId ) if count++ is 2
, 10000
$('#control #locSimStart').click ->
if isSim
vehicleLayer.destroyFeatures()
thisVehicleLastTime = null
thisVehiclePoint = new OpenLayers.Geometry.Point( null, null )
thisVehicleLocation = null
speedup = $("#simSpeed input[type='radio']:checked").val()
url = 'http://' + hostname + ':' + port + '/location_devices/start/' + locDev.id + '/' + speedup
$.post url, (data) ->
$('#control #locDriver').html(data)
$('#control #locSimEnd').click ->
url = 'http://' + hostname + ':' + port + '/location_devices/stop/' + locDev.id
$.post url, (data) ->
$('#control #locDriver').html(data)
$('#control #beaconSimStart').click ->
if isSim
platformLayer.destroyFeatures()
platformTracks = ( [] for x in platformIds )
platformTrackMultiPoints = ( [] for x in platformIds )
platformTrackLines = ( [] for x in platformIds )
platformTrackTimes = ( "Jan 28 1986" for x in platformIds )
platformLocations = ( [] for x in platformIds )
speedup = $("#simSpeed input[type='radio']:checked").val()
for rcvr in beaconRcvrs
url = 'http://' + hostname + ':' + port + '/beacon_receivers/start/' + rcvr.id + '/' + speedup
$.post url, (data) ->
$('#control #beaconDriver').html(data)
#console.log 'Sim Start'
$('#control #beaconSimEnd').click ->
for rcvr in beaconRcvrs
url = 'http://' + hostname + ':' + port + '/beacon_receivers/stop/' + rcvr.id
#console.log 'Sim End'
$.post url, (data) ->
$('#control #beaconDriver').html(data)
###
Still to do:
Interface work.
Balloon Dynamics should include van to balloon distance and bearing
chat sign in and layout improved
look and feel improved
Van location data and marker
better handling of the creation of map markers. Probably better to recreate each marker each time. May be slower but makes it stateless which is much easier.
Better Landing estimates
Better handling of wind data
More generally, need to test out hardware/serial routines, work out wireless web serving and van gps aquisition
need to write Processing code to:
1) select serial port
2) select callsigns for tracking
3) clear up chat files
4) pull wind data
5) listen to serial port for call sign APRS packets and parse them for callsign.txt files
###
# ---
# generated by js2coffee 2.0.1 |
[
{
"context": "ush(group)\n\n )\n return groups\n ).property('txo.@each.aa')\n\n\n fetchTxo: task(->\n return unless (accoun",
"end": 1483,
"score": 0.9079452753067017,
"start": 1471,
"tag": "EMAIL",
"value": "txo.@each.aa"
}
] | app/components/account/utxo-list.coffee | melis-wallet/melis-cm-client | 1 | import Component from '@ember/component'
import { inject as service } from '@ember/service'
import { get, set, setProperties } from '@ember/object'
import { A } from '@ember/array'
import { isEmpty, isPresent } from '@ember/utils'
import RSVP from 'rsvp'
import { task, taskGroup } from 'ember-concurrency'
import groupBy from '../../utils/group-by'
import CMCore from 'melis-api-js'
import Logger from 'melis-cm-svcs/utils/logger'
C = CMCore.C
UtxoList = Component.extend(
cm: service('cm-session')
mm: service('modals-manager')
aa: service('aa-provider')
txsvc: service('cm-tx-infos')
account: null
txo: null
hasNext: false
signId: 'sign-msg'
activeAddr: null
ops: taskGroup().drop()
groupedTxo: ( ->
groups = A()
items = @get('txo')
return if isEmpty(items)
items.forEach((item) ->
value = get(item, 'aa')
group = groups.find((item) -> get(item, 'value.address') == get(value, 'address') )
if isPresent(group)
amount = get(group, 'amount') + get(item, 'amount')
firstcd = get(group, 'firstcd')
itemcd = get(item, 'cd')
firstcd = itemcd if (itemcd < firstcd)
setProperties(group,
amount: amount
firstcd: firstcd
)
get(group, 'items').push(item)
else
group = { amount: get(item, 'amount'), firstcd: get(item, 'cd'), value: value, items: [item] }
groups.push(group)
)
return groups
).property('txo.@each.aa')
fetchTxo: task(->
return unless (account = @get('account'))
try
res = yield @get('cm.api').getUnspents(account.get('cmo'), sortField: 'creationDate', sortDir: C.DIR_DESCENDING)
if list = get(res, 'list')
@set('txo', list)
@set('hasNext', get(res, 'hasNext'))
catch error
Logger.error(error)
)
signWithAddr: task((addr) ->
try
@set('activeAddr', addr)
yield @get('mm').showModal(@get('signId'))
catch error
Logger.error "Error: ", error
).group('ops')
exportKey: task((addr)->
account = @get('account.cmo')
api = @get('cm.api')
op = (tfa) =>
RSVP.resolve(api.exportAddressKeyToWIF(account, addr))
try
wif = yield @get('aa').askLocalPin(op, 'Pin', '', true, true)
set(addr, 'wif', wif)
catch error
Logger.error "Error: ", error
).group('ops')
setup: ( ->
@get('fetchTxo').perform()
).on('init').observes('account')
actions:
toggleExpanded: (addr) ->
set(addr, 'expanded', !get(addr, 'expanded'))
signWithAddr: (addr) ->
if addr && @get('account.canSignMessage')
@get('signWithAddr').perform(addr)
false
exportKey: (addr) ->
if addr && @get('account.canSignMessage')
@get('exportKey').perform(addr)
false
trashKey: (addr) ->
set(addr, 'wif', null)
)
export default UtxoList
| 207348 | import Component from '@ember/component'
import { inject as service } from '@ember/service'
import { get, set, setProperties } from '@ember/object'
import { A } from '@ember/array'
import { isEmpty, isPresent } from '@ember/utils'
import RSVP from 'rsvp'
import { task, taskGroup } from 'ember-concurrency'
import groupBy from '../../utils/group-by'
import CMCore from 'melis-api-js'
import Logger from 'melis-cm-svcs/utils/logger'
C = CMCore.C
UtxoList = Component.extend(
cm: service('cm-session')
mm: service('modals-manager')
aa: service('aa-provider')
txsvc: service('cm-tx-infos')
account: null
txo: null
hasNext: false
signId: 'sign-msg'
activeAddr: null
ops: taskGroup().drop()
groupedTxo: ( ->
groups = A()
items = @get('txo')
return if isEmpty(items)
items.forEach((item) ->
value = get(item, 'aa')
group = groups.find((item) -> get(item, 'value.address') == get(value, 'address') )
if isPresent(group)
amount = get(group, 'amount') + get(item, 'amount')
firstcd = get(group, 'firstcd')
itemcd = get(item, 'cd')
firstcd = itemcd if (itemcd < firstcd)
setProperties(group,
amount: amount
firstcd: firstcd
)
get(group, 'items').push(item)
else
group = { amount: get(item, 'amount'), firstcd: get(item, 'cd'), value: value, items: [item] }
groups.push(group)
)
return groups
).property('<EMAIL>')
fetchTxo: task(->
return unless (account = @get('account'))
try
res = yield @get('cm.api').getUnspents(account.get('cmo'), sortField: 'creationDate', sortDir: C.DIR_DESCENDING)
if list = get(res, 'list')
@set('txo', list)
@set('hasNext', get(res, 'hasNext'))
catch error
Logger.error(error)
)
signWithAddr: task((addr) ->
try
@set('activeAddr', addr)
yield @get('mm').showModal(@get('signId'))
catch error
Logger.error "Error: ", error
).group('ops')
exportKey: task((addr)->
account = @get('account.cmo')
api = @get('cm.api')
op = (tfa) =>
RSVP.resolve(api.exportAddressKeyToWIF(account, addr))
try
wif = yield @get('aa').askLocalPin(op, 'Pin', '', true, true)
set(addr, 'wif', wif)
catch error
Logger.error "Error: ", error
).group('ops')
setup: ( ->
@get('fetchTxo').perform()
).on('init').observes('account')
actions:
toggleExpanded: (addr) ->
set(addr, 'expanded', !get(addr, 'expanded'))
signWithAddr: (addr) ->
if addr && @get('account.canSignMessage')
@get('signWithAddr').perform(addr)
false
exportKey: (addr) ->
if addr && @get('account.canSignMessage')
@get('exportKey').perform(addr)
false
trashKey: (addr) ->
set(addr, 'wif', null)
)
export default UtxoList
| true | import Component from '@ember/component'
import { inject as service } from '@ember/service'
import { get, set, setProperties } from '@ember/object'
import { A } from '@ember/array'
import { isEmpty, isPresent } from '@ember/utils'
import RSVP from 'rsvp'
import { task, taskGroup } from 'ember-concurrency'
import groupBy from '../../utils/group-by'
import CMCore from 'melis-api-js'
import Logger from 'melis-cm-svcs/utils/logger'
C = CMCore.C
UtxoList = Component.extend(
cm: service('cm-session')
mm: service('modals-manager')
aa: service('aa-provider')
txsvc: service('cm-tx-infos')
account: null
txo: null
hasNext: false
signId: 'sign-msg'
activeAddr: null
ops: taskGroup().drop()
groupedTxo: ( ->
groups = A()
items = @get('txo')
return if isEmpty(items)
items.forEach((item) ->
value = get(item, 'aa')
group = groups.find((item) -> get(item, 'value.address') == get(value, 'address') )
if isPresent(group)
amount = get(group, 'amount') + get(item, 'amount')
firstcd = get(group, 'firstcd')
itemcd = get(item, 'cd')
firstcd = itemcd if (itemcd < firstcd)
setProperties(group,
amount: amount
firstcd: firstcd
)
get(group, 'items').push(item)
else
group = { amount: get(item, 'amount'), firstcd: get(item, 'cd'), value: value, items: [item] }
groups.push(group)
)
return groups
).property('PI:EMAIL:<EMAIL>END_PI')
fetchTxo: task(->
return unless (account = @get('account'))
try
res = yield @get('cm.api').getUnspents(account.get('cmo'), sortField: 'creationDate', sortDir: C.DIR_DESCENDING)
if list = get(res, 'list')
@set('txo', list)
@set('hasNext', get(res, 'hasNext'))
catch error
Logger.error(error)
)
signWithAddr: task((addr) ->
try
@set('activeAddr', addr)
yield @get('mm').showModal(@get('signId'))
catch error
Logger.error "Error: ", error
).group('ops')
exportKey: task((addr)->
account = @get('account.cmo')
api = @get('cm.api')
op = (tfa) =>
RSVP.resolve(api.exportAddressKeyToWIF(account, addr))
try
wif = yield @get('aa').askLocalPin(op, 'Pin', '', true, true)
set(addr, 'wif', wif)
catch error
Logger.error "Error: ", error
).group('ops')
setup: ( ->
@get('fetchTxo').perform()
).on('init').observes('account')
actions:
toggleExpanded: (addr) ->
set(addr, 'expanded', !get(addr, 'expanded'))
signWithAddr: (addr) ->
if addr && @get('account.canSignMessage')
@get('signWithAddr').perform(addr)
false
exportKey: (addr) ->
if addr && @get('account.canSignMessage')
@get('exportKey').perform(addr)
false
trashKey: (addr) ->
set(addr, 'wif', null)
)
export default UtxoList
|
[
{
"context": " spread operators and their expressions.\n# @author Kai Cataldo\n###\n\n'use strict'\n\n#-----------------------------",
"end": 115,
"score": 0.9998546838760376,
"start": 104,
"tag": "NAME",
"value": "Kai Cataldo"
}
] | src/tests/rules/rest-spread-spacing.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Enforce spacing between rest and spread operators and their expressions.
# @author Kai Cataldo
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/rest-spread-spacing'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'rest-spread-spacing', rule,
valid: [
'fn(...args)'
'fn(args...)'
'fn(...(args))'
'fn((args)...)'
'fn(...( args ))'
'fn(( args )...)'
,
code: 'fn(...args)', options: ['never']
,
code: 'fn(args...)', options: ['never']
,
code: 'fn(... args)', options: ['always']
,
code: 'fn(args ...)', options: ['always']
,
code: 'fn(...\targs)', options: ['always']
,
code: 'fn(args\t...)', options: ['always']
,
'[...arr, 4, 5, 6]'
'[arr..., 4, 5, 6]'
'[...(arr), 4, 5, 6]'
'[(arr)..., 4, 5, 6]'
'[...( arr ), 4, 5, 6]'
'[( arr )..., 4, 5, 6]'
,
code: '[...arr, 4, 5, 6]', options: ['never']
,
code: '[arr..., 4, 5, 6]', options: ['never']
,
code: '[... arr, 4, 5, 6]', options: ['always']
,
code: '[arr ..., 4, 5, 6]', options: ['always']
,
code: '[...\tarr, 4, 5, 6]', options: ['always']
,
code: '[arr\t..., 4, 5, 6]', options: ['always']
,
'[a, b, ...arr] = [1, 2, 3, 4, 5]'
'[a, b, arr...] = [1, 2, 3, 4, 5]'
,
code: '[a, b, ...arr] = [1, 2, 3, 4, 5]', options: ['never']
,
code: '[a, b, arr...] = [1, 2, 3, 4, 5]', options: ['never']
,
code: '[a, b, ... arr] = [1, 2, 3, 4, 5]', options: ['always']
,
code: '[a, b, arr ...] = [1, 2, 3, 4, 5]', options: ['always']
,
code: '[a, b, ...\tarr] = [1, 2, 3, 4, 5]', options: ['always']
,
code: '[a, b, arr\t...] = [1, 2, 3, 4, 5]', options: ['always']
,
code: 'n = { x, y, ...z }'
,
code: 'n = { x, y, z... }'
,
code: 'n = { x, y, ...(z) }'
,
code: 'n = { x, y, (z)... }'
,
code: 'n = { x, y, ...( z ) }'
,
code: 'n = { x, y, ( z )... }'
,
code: 'n = { x, y, ...z }'
options: ['never']
,
code: 'n = { x, y, z... }'
options: ['never']
,
code: 'n = { x, y, z ... }'
options: ['always']
,
code: 'n = { x, y, ...\tz }'
options: ['always']
,
code: 'n = { x, y, z\t... }'
options: ['always']
,
code: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
,
code: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
,
code: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
,
code: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
,
code: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
,
code: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
,
code: '{ x, y, ...\tz } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
,
code: '{ x, y, z\t... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
]
invalid: [
code: 'fn(... args)'
output: 'fn(...args)'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn ... args'
output: 'fn ...args'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args ...)'
output: 'fn(args...)'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...\targs)'
output: 'fn(...args)'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args\t...)'
output: 'fn(args...)'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(... args)'
output: 'fn(...args)'
options: ['never']
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args ...)'
output: 'fn(args...)'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...\targs)'
output: 'fn(...args)'
options: ['never']
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args\t...)'
output: 'fn(args...)'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...args)'
output: 'fn(... args)'
options: ['always']
errors: [
line: 1
column: 7
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args...)'
output: 'fn(args ...)'
options: ['always']
errors: [
line: 1
column: 11
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(... (args))'
output: 'fn(...(args))'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn((args) ...)'
output: 'fn((args)...)'
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(... ( args ))'
output: 'fn(...( args ))'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(( args ) ...)'
output: 'fn(( args )...)'
errors: [
line: 1
column: 16
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...(args))'
output: 'fn(... (args))'
options: ['always']
errors: [
line: 1
column: 7
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn((args)...)'
output: 'fn((args) ...)'
options: ['always']
errors: [
line: 1
column: 13
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...( args ))'
output: 'fn(... ( args ))'
options: ['always']
errors: [
line: 1
column: 7
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(( args )...)'
output: 'fn(( args ) ...)'
options: ['always']
errors: [
line: 1
column: 15
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... arr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr ..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...\tarr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr\t..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... arr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr ..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...\tarr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr\t..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...arr, 4, 5, 6]'
output: '[... arr, 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 5
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr..., 4, 5, 6]'
output: '[arr ..., 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 8
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... (arr), 4, 5, 6]'
output: '[...(arr), 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[(arr) ..., 4, 5, 6]'
output: '[(arr)..., 4, 5, 6]'
errors: [
line: 1
column: 11
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... ( arr ), 4, 5, 6]'
output: '[...( arr ), 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[( arr ) ..., 4, 5, 6]'
output: '[( arr )..., 4, 5, 6]'
errors: [
line: 1
column: 13
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...(arr), 4, 5, 6]'
output: '[... (arr), 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 5
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[(arr)..., 4, 5, 6]'
output: '[(arr) ..., 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 10
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...( arr ), 4, 5, 6]'
output: '[... ( arr ), 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 5
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[( arr )..., 4, 5, 6]'
output: '[( arr ) ..., 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 12
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[a, b, ... arr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr ...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ...\tarr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr\t...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ... arr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr ...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ...\tarr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr\t...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
output: '[a, b, ... arr] = [1, 2, 3, 4, 5]'
options: ['always']
errors: [
line: 1
column: 11
message: 'Expected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr ...] = [1, 2, 3, 4, 5]'
options: ['always']
errors: [
line: 1
column: 14
message: 'Expected whitespace before rest operator.'
type: 'RestElement'
]
,
code: 'n = { x, y, ... z }'
output: 'n = { x, y, ...z }'
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z ... }'
output: 'n = { x, y, z... }'
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...\tz }'
output: 'n = { x, y, ...z }'
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z\t... }'
output: 'n = { x, y, z... }'
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ... z }'
output: 'n = { x, y, ...z }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z ... }'
output: 'n = { x, y, z... }'
options: ['never']
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...\tz }'
output: 'n = { x, y, ...z }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z\t... }'
output: 'n = { x, y, z... }'
options: ['never']
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...z }'
output: 'n = { x, y, ... z }'
options: ['always']
errors: [
line: 1
column: 16
message: 'Expected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z... }'
output: 'n = { x, y, z ... }'
options: ['always']
errors: [
line: 1
column: 17
message: 'Expected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ... (z) }'
output: 'n = { x, y, ...(z) }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, (z) ... }'
output: 'n = { x, y, (z)... }'
options: ['never']
errors: [
line: 1
column: 20
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ... ( z ) }'
output: 'n = { x, y, ...( z ) }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ( z ) ... }'
output: 'n = { x, y, ( z )... }'
options: ['never']
errors: [
line: 1
column: 22
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...(z) }'
output: 'n = { x, y, ... (z) }'
options: ['always']
errors: [
line: 1
column: 16
message: 'Expected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, (z)... }'
output: 'n = { x, y, (z) ... }'
options: ['always']
errors: [
line: 1
column: 19
message: 'Expected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...( z ) }'
output: 'n = { x, y, ... ( z ) }'
options: ['always']
errors: [
line: 1
column: 16
message: 'Expected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ( z )... }'
output: 'n = { x, y, ( z ) ... }'
options: ['always']
errors: [
line: 1
column: 21
message: 'Expected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ...\tz } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z\t... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ...\tz } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z\t... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
errors: [
line: 1
column: 12
message: 'Expected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
errors: [
line: 1
column: 13
message: 'Expected whitespace before rest property operator.'
type: 'RestElement'
]
]
| 18481 | ###*
# @fileoverview Enforce spacing between rest and spread operators and their expressions.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/rest-spread-spacing'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'rest-spread-spacing', rule,
valid: [
'fn(...args)'
'fn(args...)'
'fn(...(args))'
'fn((args)...)'
'fn(...( args ))'
'fn(( args )...)'
,
code: 'fn(...args)', options: ['never']
,
code: 'fn(args...)', options: ['never']
,
code: 'fn(... args)', options: ['always']
,
code: 'fn(args ...)', options: ['always']
,
code: 'fn(...\targs)', options: ['always']
,
code: 'fn(args\t...)', options: ['always']
,
'[...arr, 4, 5, 6]'
'[arr..., 4, 5, 6]'
'[...(arr), 4, 5, 6]'
'[(arr)..., 4, 5, 6]'
'[...( arr ), 4, 5, 6]'
'[( arr )..., 4, 5, 6]'
,
code: '[...arr, 4, 5, 6]', options: ['never']
,
code: '[arr..., 4, 5, 6]', options: ['never']
,
code: '[... arr, 4, 5, 6]', options: ['always']
,
code: '[arr ..., 4, 5, 6]', options: ['always']
,
code: '[...\tarr, 4, 5, 6]', options: ['always']
,
code: '[arr\t..., 4, 5, 6]', options: ['always']
,
'[a, b, ...arr] = [1, 2, 3, 4, 5]'
'[a, b, arr...] = [1, 2, 3, 4, 5]'
,
code: '[a, b, ...arr] = [1, 2, 3, 4, 5]', options: ['never']
,
code: '[a, b, arr...] = [1, 2, 3, 4, 5]', options: ['never']
,
code: '[a, b, ... arr] = [1, 2, 3, 4, 5]', options: ['always']
,
code: '[a, b, arr ...] = [1, 2, 3, 4, 5]', options: ['always']
,
code: '[a, b, ...\tarr] = [1, 2, 3, 4, 5]', options: ['always']
,
code: '[a, b, arr\t...] = [1, 2, 3, 4, 5]', options: ['always']
,
code: 'n = { x, y, ...z }'
,
code: 'n = { x, y, z... }'
,
code: 'n = { x, y, ...(z) }'
,
code: 'n = { x, y, (z)... }'
,
code: 'n = { x, y, ...( z ) }'
,
code: 'n = { x, y, ( z )... }'
,
code: 'n = { x, y, ...z }'
options: ['never']
,
code: 'n = { x, y, z... }'
options: ['never']
,
code: 'n = { x, y, z ... }'
options: ['always']
,
code: 'n = { x, y, ...\tz }'
options: ['always']
,
code: 'n = { x, y, z\t... }'
options: ['always']
,
code: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
,
code: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
,
code: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
,
code: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
,
code: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
,
code: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
,
code: '{ x, y, ...\tz } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
,
code: '{ x, y, z\t... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
]
invalid: [
code: 'fn(... args)'
output: 'fn(...args)'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn ... args'
output: 'fn ...args'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args ...)'
output: 'fn(args...)'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...\targs)'
output: 'fn(...args)'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args\t...)'
output: 'fn(args...)'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(... args)'
output: 'fn(...args)'
options: ['never']
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args ...)'
output: 'fn(args...)'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...\targs)'
output: 'fn(...args)'
options: ['never']
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args\t...)'
output: 'fn(args...)'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...args)'
output: 'fn(... args)'
options: ['always']
errors: [
line: 1
column: 7
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args...)'
output: 'fn(args ...)'
options: ['always']
errors: [
line: 1
column: 11
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(... (args))'
output: 'fn(...(args))'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn((args) ...)'
output: 'fn((args)...)'
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(... ( args ))'
output: 'fn(...( args ))'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(( args ) ...)'
output: 'fn(( args )...)'
errors: [
line: 1
column: 16
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...(args))'
output: 'fn(... (args))'
options: ['always']
errors: [
line: 1
column: 7
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn((args)...)'
output: 'fn((args) ...)'
options: ['always']
errors: [
line: 1
column: 13
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...( args ))'
output: 'fn(... ( args ))'
options: ['always']
errors: [
line: 1
column: 7
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(( args )...)'
output: 'fn(( args ) ...)'
options: ['always']
errors: [
line: 1
column: 15
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... arr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr ..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...\tarr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr\t..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... arr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr ..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...\tarr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr\t..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...arr, 4, 5, 6]'
output: '[... arr, 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 5
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr..., 4, 5, 6]'
output: '[arr ..., 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 8
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... (arr), 4, 5, 6]'
output: '[...(arr), 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[(arr) ..., 4, 5, 6]'
output: '[(arr)..., 4, 5, 6]'
errors: [
line: 1
column: 11
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... ( arr ), 4, 5, 6]'
output: '[...( arr ), 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[( arr ) ..., 4, 5, 6]'
output: '[( arr )..., 4, 5, 6]'
errors: [
line: 1
column: 13
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...(arr), 4, 5, 6]'
output: '[... (arr), 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 5
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[(arr)..., 4, 5, 6]'
output: '[(arr) ..., 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 10
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...( arr ), 4, 5, 6]'
output: '[... ( arr ), 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 5
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[( arr )..., 4, 5, 6]'
output: '[( arr ) ..., 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 12
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[a, b, ... arr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr ...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ...\tarr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr\t...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ... arr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr ...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ...\tarr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr\t...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
output: '[a, b, ... arr] = [1, 2, 3, 4, 5]'
options: ['always']
errors: [
line: 1
column: 11
message: 'Expected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr ...] = [1, 2, 3, 4, 5]'
options: ['always']
errors: [
line: 1
column: 14
message: 'Expected whitespace before rest operator.'
type: 'RestElement'
]
,
code: 'n = { x, y, ... z }'
output: 'n = { x, y, ...z }'
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z ... }'
output: 'n = { x, y, z... }'
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...\tz }'
output: 'n = { x, y, ...z }'
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z\t... }'
output: 'n = { x, y, z... }'
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ... z }'
output: 'n = { x, y, ...z }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z ... }'
output: 'n = { x, y, z... }'
options: ['never']
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...\tz }'
output: 'n = { x, y, ...z }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z\t... }'
output: 'n = { x, y, z... }'
options: ['never']
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...z }'
output: 'n = { x, y, ... z }'
options: ['always']
errors: [
line: 1
column: 16
message: 'Expected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z... }'
output: 'n = { x, y, z ... }'
options: ['always']
errors: [
line: 1
column: 17
message: 'Expected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ... (z) }'
output: 'n = { x, y, ...(z) }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, (z) ... }'
output: 'n = { x, y, (z)... }'
options: ['never']
errors: [
line: 1
column: 20
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ... ( z ) }'
output: 'n = { x, y, ...( z ) }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ( z ) ... }'
output: 'n = { x, y, ( z )... }'
options: ['never']
errors: [
line: 1
column: 22
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...(z) }'
output: 'n = { x, y, ... (z) }'
options: ['always']
errors: [
line: 1
column: 16
message: 'Expected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, (z)... }'
output: 'n = { x, y, (z) ... }'
options: ['always']
errors: [
line: 1
column: 19
message: 'Expected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...( z ) }'
output: 'n = { x, y, ... ( z ) }'
options: ['always']
errors: [
line: 1
column: 16
message: 'Expected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ( z )... }'
output: 'n = { x, y, ( z ) ... }'
options: ['always']
errors: [
line: 1
column: 21
message: 'Expected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ...\tz } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z\t... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ...\tz } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z\t... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
errors: [
line: 1
column: 12
message: 'Expected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
errors: [
line: 1
column: 13
message: 'Expected whitespace before rest property operator.'
type: 'RestElement'
]
]
| true | ###*
# @fileoverview Enforce spacing between rest and spread operators and their expressions.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/rest-spread-spacing'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'rest-spread-spacing', rule,
valid: [
'fn(...args)'
'fn(args...)'
'fn(...(args))'
'fn((args)...)'
'fn(...( args ))'
'fn(( args )...)'
,
code: 'fn(...args)', options: ['never']
,
code: 'fn(args...)', options: ['never']
,
code: 'fn(... args)', options: ['always']
,
code: 'fn(args ...)', options: ['always']
,
code: 'fn(...\targs)', options: ['always']
,
code: 'fn(args\t...)', options: ['always']
,
'[...arr, 4, 5, 6]'
'[arr..., 4, 5, 6]'
'[...(arr), 4, 5, 6]'
'[(arr)..., 4, 5, 6]'
'[...( arr ), 4, 5, 6]'
'[( arr )..., 4, 5, 6]'
,
code: '[...arr, 4, 5, 6]', options: ['never']
,
code: '[arr..., 4, 5, 6]', options: ['never']
,
code: '[... arr, 4, 5, 6]', options: ['always']
,
code: '[arr ..., 4, 5, 6]', options: ['always']
,
code: '[...\tarr, 4, 5, 6]', options: ['always']
,
code: '[arr\t..., 4, 5, 6]', options: ['always']
,
'[a, b, ...arr] = [1, 2, 3, 4, 5]'
'[a, b, arr...] = [1, 2, 3, 4, 5]'
,
code: '[a, b, ...arr] = [1, 2, 3, 4, 5]', options: ['never']
,
code: '[a, b, arr...] = [1, 2, 3, 4, 5]', options: ['never']
,
code: '[a, b, ... arr] = [1, 2, 3, 4, 5]', options: ['always']
,
code: '[a, b, arr ...] = [1, 2, 3, 4, 5]', options: ['always']
,
code: '[a, b, ...\tarr] = [1, 2, 3, 4, 5]', options: ['always']
,
code: '[a, b, arr\t...] = [1, 2, 3, 4, 5]', options: ['always']
,
code: 'n = { x, y, ...z }'
,
code: 'n = { x, y, z... }'
,
code: 'n = { x, y, ...(z) }'
,
code: 'n = { x, y, (z)... }'
,
code: 'n = { x, y, ...( z ) }'
,
code: 'n = { x, y, ( z )... }'
,
code: 'n = { x, y, ...z }'
options: ['never']
,
code: 'n = { x, y, z... }'
options: ['never']
,
code: 'n = { x, y, z ... }'
options: ['always']
,
code: 'n = { x, y, ...\tz }'
options: ['always']
,
code: 'n = { x, y, z\t... }'
options: ['always']
,
code: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
,
code: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
,
code: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
,
code: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
,
code: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
,
code: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
,
code: '{ x, y, ...\tz } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
,
code: '{ x, y, z\t... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
]
invalid: [
code: 'fn(... args)'
output: 'fn(...args)'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn ... args'
output: 'fn ...args'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args ...)'
output: 'fn(args...)'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...\targs)'
output: 'fn(...args)'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args\t...)'
output: 'fn(args...)'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(... args)'
output: 'fn(...args)'
options: ['never']
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args ...)'
output: 'fn(args...)'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...\targs)'
output: 'fn(...args)'
options: ['never']
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args\t...)'
output: 'fn(args...)'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...args)'
output: 'fn(... args)'
options: ['always']
errors: [
line: 1
column: 7
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(args...)'
output: 'fn(args ...)'
options: ['always']
errors: [
line: 1
column: 11
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(... (args))'
output: 'fn(...(args))'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn((args) ...)'
output: 'fn((args)...)'
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(... ( args ))'
output: 'fn(...( args ))'
errors: [
line: 1
column: 7
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(( args ) ...)'
output: 'fn(( args )...)'
errors: [
line: 1
column: 16
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...(args))'
output: 'fn(... (args))'
options: ['always']
errors: [
line: 1
column: 7
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn((args)...)'
output: 'fn((args) ...)'
options: ['always']
errors: [
line: 1
column: 13
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(...( args ))'
output: 'fn(... ( args ))'
options: ['always']
errors: [
line: 1
column: 7
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: 'fn(( args )...)'
output: 'fn(( args ) ...)'
options: ['always']
errors: [
line: 1
column: 15
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... arr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr ..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...\tarr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr\t..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... arr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr ..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...\tarr, 4, 5, 6]'
output: '[...arr, 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr\t..., 4, 5, 6]'
output: '[arr..., 4, 5, 6]'
options: ['never']
errors: [
line: 1
column: 9
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...arr, 4, 5, 6]'
output: '[... arr, 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 5
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[arr..., 4, 5, 6]'
output: '[arr ..., 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 8
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... (arr), 4, 5, 6]'
output: '[...(arr), 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[(arr) ..., 4, 5, 6]'
output: '[(arr)..., 4, 5, 6]'
errors: [
line: 1
column: 11
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[... ( arr ), 4, 5, 6]'
output: '[...( arr ), 4, 5, 6]'
errors: [
line: 1
column: 5
message: 'Unexpected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[( arr ) ..., 4, 5, 6]'
output: '[( arr )..., 4, 5, 6]'
errors: [
line: 1
column: 13
message: 'Unexpected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...(arr), 4, 5, 6]'
output: '[... (arr), 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 5
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[(arr)..., 4, 5, 6]'
output: '[(arr) ..., 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 10
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[...( arr ), 4, 5, 6]'
output: '[... ( arr ), 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 5
message: 'Expected whitespace after spread operator.'
type: 'SpreadElement'
]
,
code: '[( arr )..., 4, 5, 6]'
output: '[( arr ) ..., 4, 5, 6]'
options: ['always']
errors: [
line: 1
column: 12
message: 'Expected whitespace before spread operator.'
type: 'SpreadElement'
]
,
code: '[a, b, ... arr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr ...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ...\tarr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr\t...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ... arr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr ...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ...\tarr] = [1, 2, 3, 4, 5]'
output: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 11
message: 'Unexpected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr\t...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr...] = [1, 2, 3, 4, 5]'
options: ['never']
errors: [
line: 1
column: 15
message: 'Unexpected whitespace before rest operator.'
type: 'RestElement'
]
,
code: '[a, b, ...arr] = [1, 2, 3, 4, 5]'
output: '[a, b, ... arr] = [1, 2, 3, 4, 5]'
options: ['always']
errors: [
line: 1
column: 11
message: 'Expected whitespace after rest operator.'
type: 'RestElement'
]
,
code: '[a, b, arr...] = [1, 2, 3, 4, 5]'
output: '[a, b, arr ...] = [1, 2, 3, 4, 5]'
options: ['always']
errors: [
line: 1
column: 14
message: 'Expected whitespace before rest operator.'
type: 'RestElement'
]
,
code: 'n = { x, y, ... z }'
output: 'n = { x, y, ...z }'
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z ... }'
output: 'n = { x, y, z... }'
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...\tz }'
output: 'n = { x, y, ...z }'
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z\t... }'
output: 'n = { x, y, z... }'
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ... z }'
output: 'n = { x, y, ...z }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z ... }'
output: 'n = { x, y, z... }'
options: ['never']
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...\tz }'
output: 'n = { x, y, ...z }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z\t... }'
output: 'n = { x, y, z... }'
options: ['never']
errors: [
line: 1
column: 18
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...z }'
output: 'n = { x, y, ... z }'
options: ['always']
errors: [
line: 1
column: 16
message: 'Expected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, z... }'
output: 'n = { x, y, z ... }'
options: ['always']
errors: [
line: 1
column: 17
message: 'Expected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ... (z) }'
output: 'n = { x, y, ...(z) }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, (z) ... }'
output: 'n = { x, y, (z)... }'
options: ['never']
errors: [
line: 1
column: 20
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ... ( z ) }'
output: 'n = { x, y, ...( z ) }'
options: ['never']
errors: [
line: 1
column: 16
message: 'Unexpected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ( z ) ... }'
output: 'n = { x, y, ( z )... }'
options: ['never']
errors: [
line: 1
column: 22
message: 'Unexpected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...(z) }'
output: 'n = { x, y, ... (z) }'
options: ['always']
errors: [
line: 1
column: 16
message: 'Expected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, (z)... }'
output: 'n = { x, y, (z) ... }'
options: ['always']
errors: [
line: 1
column: 19
message: 'Expected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ...( z ) }'
output: 'n = { x, y, ... ( z ) }'
options: ['always']
errors: [
line: 1
column: 16
message: 'Expected whitespace after spread property operator.'
type: 'SpreadElement'
]
,
code: 'n = { x, y, ( z )... }'
output: 'n = { x, y, ( z ) ... }'
options: ['always']
errors: [
line: 1
column: 21
message: 'Expected whitespace before spread property operator.'
type: 'SpreadElement'
]
,
code: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ...\tz } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z\t... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ...\tz } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 12
message: 'Unexpected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z\t... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['never']
errors: [
line: 1
column: 14
message: 'Unexpected whitespace before rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
errors: [
line: 1
column: 12
message: 'Expected whitespace after rest property operator.'
type: 'RestElement'
]
,
code: '{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }'
output: '{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }'
options: ['always']
errors: [
line: 1
column: 13
message: 'Expected whitespace before rest property operator.'
type: 'RestElement'
]
]
|
[
{
"context": "w.jaggy.options\n\nservice.config (jaggy)->\n key= 'jaggy:version'\n value= '0.1.17'\n localStorage.clear() if loca",
"end": 154,
"score": 0.9979895353317261,
"start": 141,
"tag": "KEY",
"value": "jaggy:version"
}
] | src/jaggy.angular.coffee | 59naga/Jaggy | 13 | Jaggy= require './jaggy'
service= angular.module 'jaggy',[]
service.constant 'jaggy',window.jaggy.options
service.config (jaggy)->
key= 'jaggy:version'
value= '0.1.17'
localStorage.clear() if localStorage.getItem(key) isnt value
localStorage.setItem key,value
service.directive 'jaggy',(
jaggy
$compile
)->
scope:{
jagged:'='
}
link:(scope,element,attrs)->
element.css 'display','none'
scope.config= jaggy
scope.$watch 'config',(-> createSVG()),yes
createSVG= ->
# fix <img ng-src="url" jaggy>
url= attrs.src
url?= attrs.ngSrc
if not url? or url.length is 0
if jaggy.emptySVG
element.replaceWith Jaggy.emptySVG()
return
options= angular.copy jaggy
if attrs.jaggy
for param in attrs.jaggy.split ';'
[key,value]= param.split ':'
options[key]= value
Jaggy.createSVG url,options,(error,svg)->
svg= Jaggy.regenerateUUID svg if svg?
svgElement= angular.element svg if svg?
if error
return element.css 'display',null if error is true # over pixelLimit
throw error if not jaggy.emptySVG
svgElement= angular.element Jaggy.emptySVG()
angularElement= $compile(svgElement) scope
element.replaceWith angularElement
element= angularElement
# fix animatedGif caching
script= element.find 'script'
eval script.html() if script?
scope.jagged scope,element,attrs if typeof scope.jagged is 'function' | 157889 | Jaggy= require './jaggy'
service= angular.module 'jaggy',[]
service.constant 'jaggy',window.jaggy.options
service.config (jaggy)->
key= '<KEY>'
value= '0.1.17'
localStorage.clear() if localStorage.getItem(key) isnt value
localStorage.setItem key,value
service.directive 'jaggy',(
jaggy
$compile
)->
scope:{
jagged:'='
}
link:(scope,element,attrs)->
element.css 'display','none'
scope.config= jaggy
scope.$watch 'config',(-> createSVG()),yes
createSVG= ->
# fix <img ng-src="url" jaggy>
url= attrs.src
url?= attrs.ngSrc
if not url? or url.length is 0
if jaggy.emptySVG
element.replaceWith Jaggy.emptySVG()
return
options= angular.copy jaggy
if attrs.jaggy
for param in attrs.jaggy.split ';'
[key,value]= param.split ':'
options[key]= value
Jaggy.createSVG url,options,(error,svg)->
svg= Jaggy.regenerateUUID svg if svg?
svgElement= angular.element svg if svg?
if error
return element.css 'display',null if error is true # over pixelLimit
throw error if not jaggy.emptySVG
svgElement= angular.element Jaggy.emptySVG()
angularElement= $compile(svgElement) scope
element.replaceWith angularElement
element= angularElement
# fix animatedGif caching
script= element.find 'script'
eval script.html() if script?
scope.jagged scope,element,attrs if typeof scope.jagged is 'function' | true | Jaggy= require './jaggy'
service= angular.module 'jaggy',[]
service.constant 'jaggy',window.jaggy.options
service.config (jaggy)->
key= 'PI:KEY:<KEY>END_PI'
value= '0.1.17'
localStorage.clear() if localStorage.getItem(key) isnt value
localStorage.setItem key,value
service.directive 'jaggy',(
jaggy
$compile
)->
scope:{
jagged:'='
}
link:(scope,element,attrs)->
element.css 'display','none'
scope.config= jaggy
scope.$watch 'config',(-> createSVG()),yes
createSVG= ->
# fix <img ng-src="url" jaggy>
url= attrs.src
url?= attrs.ngSrc
if not url? or url.length is 0
if jaggy.emptySVG
element.replaceWith Jaggy.emptySVG()
return
options= angular.copy jaggy
if attrs.jaggy
for param in attrs.jaggy.split ';'
[key,value]= param.split ':'
options[key]= value
Jaggy.createSVG url,options,(error,svg)->
svg= Jaggy.regenerateUUID svg if svg?
svgElement= angular.element svg if svg?
if error
return element.css 'display',null if error is true # over pixelLimit
throw error if not jaggy.emptySVG
svgElement= angular.element Jaggy.emptySVG()
angularElement= $compile(svgElement) scope
element.replaceWith angularElement
element= angularElement
# fix animatedGif caching
script= element.find 'script'
eval script.html() if script?
scope.jagged scope,element,attrs if typeof scope.jagged is 'function' |
[
{
"context": "\n ip: '1.1.1.1'\n user: 'root'\n ssh_key: 'overcast.key'\n ",
"end": 334,
"score": 0.6915724277496338,
"start": 330,
"tag": "USERNAME",
"value": "root"
},
{
"context": " user: 'root'\n ssh_key: 'overcast.key'\n ssh_port: '22'\n }\n ",
"end": 372,
"score": 0.7148614525794983,
"start": 364,
"tag": "KEY",
"value": "cast.key"
}
] | test/unit/port.spec.coffee | skmezanul/overcast | 238 | cli = require('../../modules/cli')
utils = require('../../modules/utils')
ssh = require('../../modules/ssh')
describe 'port', ->
beforeEach ->
spyOn(utils, 'getClusters').andReturn({
dummy: {
instances: {
'vm-01': {
name: 'vm-01'
ip: '1.1.1.1'
user: 'root'
ssh_key: 'overcast.key'
ssh_port: '22'
}
}
}
})
spyOn(cli, 'missingArgument')
spyOn(utils, 'die')
spyOn(utils, 'grey')
spyOn(utils, 'cyan')
spyOn(utils, 'dieWithList')
spyOn(ssh, 'run').andCallFake (args, callback) ->
callback()
it 'should throw an error if name is missing', ->
cli.execute('port')
expect(cli.missingArgument).toHaveBeenCalled()
it 'should throw an error if port is missing', ->
cli.execute('port vm-01')
expect(cli.missingArgument).toHaveBeenCalled()
it 'should throw an error if instance is not found', ->
cli.execute('port missing-vm 22222')
expect(utils.dieWithList).toHaveBeenCalled()
it 'should otherwise update the port', ->
spyOn(utils, 'updateInstance')
cli.execute('port vm-01 22222')
expect(utils.updateInstance).toHaveBeenCalledWith('vm-01', { ssh_port: '22222' })
| 129068 | cli = require('../../modules/cli')
utils = require('../../modules/utils')
ssh = require('../../modules/ssh')
describe 'port', ->
beforeEach ->
spyOn(utils, 'getClusters').andReturn({
dummy: {
instances: {
'vm-01': {
name: 'vm-01'
ip: '1.1.1.1'
user: 'root'
ssh_key: 'over<KEY>'
ssh_port: '22'
}
}
}
})
spyOn(cli, 'missingArgument')
spyOn(utils, 'die')
spyOn(utils, 'grey')
spyOn(utils, 'cyan')
spyOn(utils, 'dieWithList')
spyOn(ssh, 'run').andCallFake (args, callback) ->
callback()
it 'should throw an error if name is missing', ->
cli.execute('port')
expect(cli.missingArgument).toHaveBeenCalled()
it 'should throw an error if port is missing', ->
cli.execute('port vm-01')
expect(cli.missingArgument).toHaveBeenCalled()
it 'should throw an error if instance is not found', ->
cli.execute('port missing-vm 22222')
expect(utils.dieWithList).toHaveBeenCalled()
it 'should otherwise update the port', ->
spyOn(utils, 'updateInstance')
cli.execute('port vm-01 22222')
expect(utils.updateInstance).toHaveBeenCalledWith('vm-01', { ssh_port: '22222' })
| true | cli = require('../../modules/cli')
utils = require('../../modules/utils')
ssh = require('../../modules/ssh')
describe 'port', ->
beforeEach ->
spyOn(utils, 'getClusters').andReturn({
dummy: {
instances: {
'vm-01': {
name: 'vm-01'
ip: '1.1.1.1'
user: 'root'
ssh_key: 'overPI:KEY:<KEY>END_PI'
ssh_port: '22'
}
}
}
})
spyOn(cli, 'missingArgument')
spyOn(utils, 'die')
spyOn(utils, 'grey')
spyOn(utils, 'cyan')
spyOn(utils, 'dieWithList')
spyOn(ssh, 'run').andCallFake (args, callback) ->
callback()
it 'should throw an error if name is missing', ->
cli.execute('port')
expect(cli.missingArgument).toHaveBeenCalled()
it 'should throw an error if port is missing', ->
cli.execute('port vm-01')
expect(cli.missingArgument).toHaveBeenCalled()
it 'should throw an error if instance is not found', ->
cli.execute('port missing-vm 22222')
expect(utils.dieWithList).toHaveBeenCalled()
it 'should otherwise update the port', ->
spyOn(utils, 'updateInstance')
cli.execute('port vm-01 22222')
expect(utils.updateInstance).toHaveBeenCalledWith('vm-01', { ssh_port: '22222' })
|
[
{
"context": "\"guest\"\n componentUser: \"guest\"\n password: \"guest\"\n heartbeat: 10\n vhost: \"/\"\n algolia =\n ",
"end": 1399,
"score": 0.9995433688163757,
"start": 1394,
"tag": "PASSWORD",
"value": "guest"
},
{
"context": "ons.serviceHost}\"\n port: '5432'\n username: 'socialapplication'\n password: 'socialapplication'\n dbname: 's",
"end": 1603,
"score": 0.9995464086532593,
"start": 1586,
"tag": "USERNAME",
"value": "socialapplication"
},
{
"context": "\n username: 'socialapplication'\n password: 'socialapplication'\n dbname: 'social'\n kontrolPostgres =\n hos",
"end": 1637,
"score": 0.9991511106491089,
"start": 1620,
"tag": "PASSWORD",
"value": "socialapplication"
},
{
"context": "tions.serviceHost}\"\n port: 5432\n username: 'kontrolapplication'\n password: 'kontrolapplication'\n dbname: '",
"end": 1763,
"score": 0.9996428489685059,
"start": 1745,
"tag": "USERNAME",
"value": "kontrolapplication"
},
{
"context": " username: 'kontrolapplication'\n password: 'kontrolapplication'\n dbname: 'social'\n connecttimeout: 20\n pu",
"end": 1798,
"score": 0.9991199374198914,
"start": 1780,
"tag": "PASSWORD",
"value": "kontrolapplication"
},
{
"context": "cKey: \"$KONFIG_PROJECTROOT/generated/private_keys/kontrol/kontrol.pub\"\n privateKey: \"$KONFIG_PROJECTROOT/generated/p",
"end": 4590,
"score": 0.8736215233802795,
"start": 4571,
"tag": "KEY",
"value": "kontrol/kontrol.pub"
},
{
"context": "eKey: \"$KONFIG_PROJECTROOT/generated/private_keys/kontrol/kontrol.pem\"\n kloud =\n publicKey: kontrol.publicKey\n p",
"end": 4671,
"score": 0.889958918094635,
"start": 4652,
"tag": "KEY",
"value": "kontrol/kontrol.pem"
},
{
"context": "d/private_keys/kloud/kloud.pem\"\n dummyAdmins = ['superadmin', 'admin', 'koding']\n druid =\n host : options",
"end": 5090,
"score": 0.9991886615753174,
"start": 5080,
"tag": "USERNAME",
"value": "superadmin"
},
{
"context": "/kloud/kloud.pem\"\n dummyAdmins = ['superadmin', 'admin', 'koding']\n druid =\n host : options.serviceH",
"end": 5099,
"score": 0.9992104768753052,
"start": 5094,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "oud.pem\"\n dummyAdmins = ['superadmin', 'admin', 'koding']\n druid =\n host : options.serviceHost\n po",
"end": 5109,
"score": 0.9844213128089905,
"start": 5103,
"tag": "USERNAME",
"value": "koding"
}
] | config/credentials.default.coffee | lionheart1022/koding | 0 | module.exports = (options) ->
kiteHome = "$KONFIG_PROJECTROOT/generated/kite_home/koding"
kodingdev_master_2016_05 =
accessKeyId: ""
secretAccessKey: ""
awsKeys =
kodingdev_master_2016_05: kodingdev_master_2016_05
# s3 full access
worker_terraformer: kodingdev_master_2016_05
# s3 put only to koding-client bucket
worker_koding_client_s3_put_only: kodingdev_master_2016_05
# admin
worker_test: kodingdev_master_2016_05
# s3 put only
worker_test_data_exporter: kodingdev_master_2016_05
# AmazonRDSReadOnlyAccess
worker_rds_log_parser: kodingdev_master_2016_05
# ELB & EC2 -> AmazonEC2ReadOnlyAccess
worker_multi_ssh: kodingdev_master_2016_05
# AmazonEC2FullAccess
worker_test_instance_launcher: kodingdev_master_2016_05
# TunnelProxyPolicy
worker_tunnelproxymanager: kodingdev_master_2016_05
worker_tunnelproxymanager_route53: kodingdev_master_2016_05
#Encryption and Storage on S3
worker_sneakerS3 : kodingdev_master_2016_05
mongo = "#{options.serviceHost}:27017/koding"
redis =
host: "#{options.serviceHost}"
port: "6379"
db: 0
url : "#{options.serviceHost}:6379"
monitoringRedis = redis
rabbitmq =
host: "#{options.serviceHost}"
port: 5672
apiAddress: "#{options.serviceHost}"
apiPort: "15672"
login: "guest"
componentUser: "guest"
password: "guest"
heartbeat: 10
vhost: "/"
algolia =
appId: ''
apiSecretKey: ''
apiSearchOnlyKey: ''
postgres =
host: "#{options.serviceHost}"
port: '5432'
username: 'socialapplication'
password: 'socialapplication'
dbname: 'social'
kontrolPostgres =
host: "#{options.serviceHost}"
port: 5432
username: 'kontrolapplication'
password: 'kontrolapplication'
dbname: 'social'
connecttimeout: 20
pubnub =
publishkey: ""
subscribekey: ""
secretkey: ""
serverAuthKey: ""
origin: "pubsub.pubnub.com"
enabled: yes
ssl: no
terraformer =
port: 2300
region: options.region
environment: options.environment
secretKey: ''
aws:
key: awsKeys.worker_terraformer.accessKeyId
secret: awsKeys.worker_terraformer.secretAccessKey
bucket: "kodingdev-terraformer-state-#{options.configName}"
localStorePath: "$KONFIG_PROJECTROOT/go/data/terraformer"
googleapiServiceAccount =
clientId: ''
clientSecret: ''
serviceAccountEmail: ''
serviceAccountKeyFile: ''
github =
clientId: ''
clientSecret: ''
redirectUri: 'http://dev.koding.com:8090/-/oauth/github/callback'
gitlab =
host: ''
port: ''
applicationId: ''
applicationSecret: ''
team: 'gitlab'
redirectUri: ''
systemHookToken: ''
hooksEnabled: no
allowPrivateOAuthEndpoints: no
facebook =
clientId: ''
clientSecret: ''
redirectUri: "http://dev.koding.com:8090/-/oauth/facebook/callback"
mailgun =
domain: ''
privateKey: ''
publicKey: ''
unsubscribeURL: ''
slack =
clientId: ''
clientSecret: ''
redirectUri: ''
verificationToken: ''
google =
client_id: ''
client_secret: ''
redirect_uri: "http://dev.koding.com:8090/-/oauth/google/callback"
apiKey: ''
twitter =
key: ''
secret: ''
redirect_uri: "http://dev.koding.com:8090/-/oauth/twitter/callback"
request_url: "https://twitter.com/oauth/request_token"
access_url: "https://twitter.com/oauth/access_token"
secret_url: "https://twitter.com/oauth/authenticate?oauth_token="
version: "1.0"
signature: "HMAC-SHA1"
linkedin =
client_id: ''
client_secret: ''
redirect_uri: "http://dev.koding.com:8090/-/oauth/linkedin/callback"
datadog =
api_key: ''
app_key: ''
embedly =
apiKey: ''
siftScience = ''
siftSciencePublic = ''
jwt =
secret: 'somesecretkeyhere'
confirmExpiresInMinutes: 10080
papertrail =
destination: 'logs3.papertrailapp.com:13734'
groupId: 2199093
token: ''
helpscout =
apiKey: ''
baseUrl: 'https://api.helpscout.net/v1'
sneakerS3 =
awsSecretAccessKey: "#{awsKeys.worker_sneakerS3.secretAccessKey}"
awsAccessKeyId: "#{awsKeys.worker_sneakerS3.accessKeyId}"
sneakerS3Path: "s3://kodingdev-credential/"
sneakerMasterKey: ''
awsRegion: ''
stripe =
secretToken: ''
publicToken: ''
recaptcha =
secret: ''
public: ''
janitor =
port: '6700'
secretKey: ''
vmwatcher =
secretKey: ''
segment = ''
kontrol =
publicKey: "$KONFIG_PROJECTROOT/generated/private_keys/kontrol/kontrol.pub"
privateKey: "$KONFIG_PROJECTROOT/generated/private_keys/kontrol/kontrol.pem"
kloud =
publicKey: kontrol.publicKey
privateKey: kontrol.privateKey
secretKey: ''
janitorSecretKey: janitor.secretKey
vmwatcherSecretKey: vmwatcher.secretKey
terraformerSecretKey: terraformer.secretKey
userPublicKey: "$KONFIG_PROJECTROOT/generated/private_keys/kloud/kloud.pub"
userPrivateKey: "$KONFIG_PROJECTROOT/generated/private_keys/kloud/kloud.pem"
dummyAdmins = ['superadmin', 'admin', 'koding']
druid =
host : options.serviceHost
port : 8090
clearbit = '9d961e7ac862a6bc430f783da5cf9422'
intercomAppId = ''
wufoo = ''
return {
kiteHome
awsKeys
mongo
redis
monitoringRedis
rabbitmq
algolia
postgres
kontrolPostgres
pubnub
terraformer
googleapiServiceAccount
github
gitlab
facebook
mailgun
slack
google
twitter
linkedin
datadog
embedly
siftScience
siftSciencePublic
jwt
papertrail
helpscout
sneakerS3
stripe
recaptcha
janitor
segment
kontrol
kloud
vmwatcher
dummyAdmins
druid
clearbit
intercomAppId
wufoo
}
| 205825 | module.exports = (options) ->
kiteHome = "$KONFIG_PROJECTROOT/generated/kite_home/koding"
kodingdev_master_2016_05 =
accessKeyId: ""
secretAccessKey: ""
awsKeys =
kodingdev_master_2016_05: kodingdev_master_2016_05
# s3 full access
worker_terraformer: kodingdev_master_2016_05
# s3 put only to koding-client bucket
worker_koding_client_s3_put_only: kodingdev_master_2016_05
# admin
worker_test: kodingdev_master_2016_05
# s3 put only
worker_test_data_exporter: kodingdev_master_2016_05
# AmazonRDSReadOnlyAccess
worker_rds_log_parser: kodingdev_master_2016_05
# ELB & EC2 -> AmazonEC2ReadOnlyAccess
worker_multi_ssh: kodingdev_master_2016_05
# AmazonEC2FullAccess
worker_test_instance_launcher: kodingdev_master_2016_05
# TunnelProxyPolicy
worker_tunnelproxymanager: kodingdev_master_2016_05
worker_tunnelproxymanager_route53: kodingdev_master_2016_05
#Encryption and Storage on S3
worker_sneakerS3 : kodingdev_master_2016_05
mongo = "#{options.serviceHost}:27017/koding"
redis =
host: "#{options.serviceHost}"
port: "6379"
db: 0
url : "#{options.serviceHost}:6379"
monitoringRedis = redis
rabbitmq =
host: "#{options.serviceHost}"
port: 5672
apiAddress: "#{options.serviceHost}"
apiPort: "15672"
login: "guest"
componentUser: "guest"
password: "<PASSWORD>"
heartbeat: 10
vhost: "/"
algolia =
appId: ''
apiSecretKey: ''
apiSearchOnlyKey: ''
postgres =
host: "#{options.serviceHost}"
port: '5432'
username: 'socialapplication'
password: '<PASSWORD>'
dbname: 'social'
kontrolPostgres =
host: "#{options.serviceHost}"
port: 5432
username: 'kontrolapplication'
password: '<PASSWORD>'
dbname: 'social'
connecttimeout: 20
pubnub =
publishkey: ""
subscribekey: ""
secretkey: ""
serverAuthKey: ""
origin: "pubsub.pubnub.com"
enabled: yes
ssl: no
terraformer =
port: 2300
region: options.region
environment: options.environment
secretKey: ''
aws:
key: awsKeys.worker_terraformer.accessKeyId
secret: awsKeys.worker_terraformer.secretAccessKey
bucket: "kodingdev-terraformer-state-#{options.configName}"
localStorePath: "$KONFIG_PROJECTROOT/go/data/terraformer"
googleapiServiceAccount =
clientId: ''
clientSecret: ''
serviceAccountEmail: ''
serviceAccountKeyFile: ''
github =
clientId: ''
clientSecret: ''
redirectUri: 'http://dev.koding.com:8090/-/oauth/github/callback'
gitlab =
host: ''
port: ''
applicationId: ''
applicationSecret: ''
team: 'gitlab'
redirectUri: ''
systemHookToken: ''
hooksEnabled: no
allowPrivateOAuthEndpoints: no
facebook =
clientId: ''
clientSecret: ''
redirectUri: "http://dev.koding.com:8090/-/oauth/facebook/callback"
mailgun =
domain: ''
privateKey: ''
publicKey: ''
unsubscribeURL: ''
slack =
clientId: ''
clientSecret: ''
redirectUri: ''
verificationToken: ''
google =
client_id: ''
client_secret: ''
redirect_uri: "http://dev.koding.com:8090/-/oauth/google/callback"
apiKey: ''
twitter =
key: ''
secret: ''
redirect_uri: "http://dev.koding.com:8090/-/oauth/twitter/callback"
request_url: "https://twitter.com/oauth/request_token"
access_url: "https://twitter.com/oauth/access_token"
secret_url: "https://twitter.com/oauth/authenticate?oauth_token="
version: "1.0"
signature: "HMAC-SHA1"
linkedin =
client_id: ''
client_secret: ''
redirect_uri: "http://dev.koding.com:8090/-/oauth/linkedin/callback"
datadog =
api_key: ''
app_key: ''
embedly =
apiKey: ''
siftScience = ''
siftSciencePublic = ''
jwt =
secret: 'somesecretkeyhere'
confirmExpiresInMinutes: 10080
papertrail =
destination: 'logs3.papertrailapp.com:13734'
groupId: 2199093
token: ''
helpscout =
apiKey: ''
baseUrl: 'https://api.helpscout.net/v1'
sneakerS3 =
awsSecretAccessKey: "#{awsKeys.worker_sneakerS3.secretAccessKey}"
awsAccessKeyId: "#{awsKeys.worker_sneakerS3.accessKeyId}"
sneakerS3Path: "s3://kodingdev-credential/"
sneakerMasterKey: ''
awsRegion: ''
stripe =
secretToken: ''
publicToken: ''
recaptcha =
secret: ''
public: ''
janitor =
port: '6700'
secretKey: ''
vmwatcher =
secretKey: ''
segment = ''
kontrol =
publicKey: "$KONFIG_PROJECTROOT/generated/private_keys/<KEY>"
privateKey: "$KONFIG_PROJECTROOT/generated/private_keys/<KEY>"
kloud =
publicKey: kontrol.publicKey
privateKey: kontrol.privateKey
secretKey: ''
janitorSecretKey: janitor.secretKey
vmwatcherSecretKey: vmwatcher.secretKey
terraformerSecretKey: terraformer.secretKey
userPublicKey: "$KONFIG_PROJECTROOT/generated/private_keys/kloud/kloud.pub"
userPrivateKey: "$KONFIG_PROJECTROOT/generated/private_keys/kloud/kloud.pem"
dummyAdmins = ['superadmin', 'admin', 'koding']
druid =
host : options.serviceHost
port : 8090
clearbit = '9d961e7ac862a6bc430f783da5cf9422'
intercomAppId = ''
wufoo = ''
return {
kiteHome
awsKeys
mongo
redis
monitoringRedis
rabbitmq
algolia
postgres
kontrolPostgres
pubnub
terraformer
googleapiServiceAccount
github
gitlab
facebook
mailgun
slack
google
twitter
linkedin
datadog
embedly
siftScience
siftSciencePublic
jwt
papertrail
helpscout
sneakerS3
stripe
recaptcha
janitor
segment
kontrol
kloud
vmwatcher
dummyAdmins
druid
clearbit
intercomAppId
wufoo
}
| true | module.exports = (options) ->
kiteHome = "$KONFIG_PROJECTROOT/generated/kite_home/koding"
kodingdev_master_2016_05 =
accessKeyId: ""
secretAccessKey: ""
awsKeys =
kodingdev_master_2016_05: kodingdev_master_2016_05
# s3 full access
worker_terraformer: kodingdev_master_2016_05
# s3 put only to koding-client bucket
worker_koding_client_s3_put_only: kodingdev_master_2016_05
# admin
worker_test: kodingdev_master_2016_05
# s3 put only
worker_test_data_exporter: kodingdev_master_2016_05
# AmazonRDSReadOnlyAccess
worker_rds_log_parser: kodingdev_master_2016_05
# ELB & EC2 -> AmazonEC2ReadOnlyAccess
worker_multi_ssh: kodingdev_master_2016_05
# AmazonEC2FullAccess
worker_test_instance_launcher: kodingdev_master_2016_05
# TunnelProxyPolicy
worker_tunnelproxymanager: kodingdev_master_2016_05
worker_tunnelproxymanager_route53: kodingdev_master_2016_05
#Encryption and Storage on S3
worker_sneakerS3 : kodingdev_master_2016_05
mongo = "#{options.serviceHost}:27017/koding"
redis =
host: "#{options.serviceHost}"
port: "6379"
db: 0
url : "#{options.serviceHost}:6379"
monitoringRedis = redis
rabbitmq =
host: "#{options.serviceHost}"
port: 5672
apiAddress: "#{options.serviceHost}"
apiPort: "15672"
login: "guest"
componentUser: "guest"
password: "PI:PASSWORD:<PASSWORD>END_PI"
heartbeat: 10
vhost: "/"
algolia =
appId: ''
apiSecretKey: ''
apiSearchOnlyKey: ''
postgres =
host: "#{options.serviceHost}"
port: '5432'
username: 'socialapplication'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
dbname: 'social'
kontrolPostgres =
host: "#{options.serviceHost}"
port: 5432
username: 'kontrolapplication'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
dbname: 'social'
connecttimeout: 20
pubnub =
publishkey: ""
subscribekey: ""
secretkey: ""
serverAuthKey: ""
origin: "pubsub.pubnub.com"
enabled: yes
ssl: no
terraformer =
port: 2300
region: options.region
environment: options.environment
secretKey: ''
aws:
key: awsKeys.worker_terraformer.accessKeyId
secret: awsKeys.worker_terraformer.secretAccessKey
bucket: "kodingdev-terraformer-state-#{options.configName}"
localStorePath: "$KONFIG_PROJECTROOT/go/data/terraformer"
googleapiServiceAccount =
clientId: ''
clientSecret: ''
serviceAccountEmail: ''
serviceAccountKeyFile: ''
github =
clientId: ''
clientSecret: ''
redirectUri: 'http://dev.koding.com:8090/-/oauth/github/callback'
gitlab =
host: ''
port: ''
applicationId: ''
applicationSecret: ''
team: 'gitlab'
redirectUri: ''
systemHookToken: ''
hooksEnabled: no
allowPrivateOAuthEndpoints: no
facebook =
clientId: ''
clientSecret: ''
redirectUri: "http://dev.koding.com:8090/-/oauth/facebook/callback"
mailgun =
domain: ''
privateKey: ''
publicKey: ''
unsubscribeURL: ''
slack =
clientId: ''
clientSecret: ''
redirectUri: ''
verificationToken: ''
google =
client_id: ''
client_secret: ''
redirect_uri: "http://dev.koding.com:8090/-/oauth/google/callback"
apiKey: ''
twitter =
key: ''
secret: ''
redirect_uri: "http://dev.koding.com:8090/-/oauth/twitter/callback"
request_url: "https://twitter.com/oauth/request_token"
access_url: "https://twitter.com/oauth/access_token"
secret_url: "https://twitter.com/oauth/authenticate?oauth_token="
version: "1.0"
signature: "HMAC-SHA1"
linkedin =
client_id: ''
client_secret: ''
redirect_uri: "http://dev.koding.com:8090/-/oauth/linkedin/callback"
datadog =
api_key: ''
app_key: ''
embedly =
apiKey: ''
siftScience = ''
siftSciencePublic = ''
jwt =
secret: 'somesecretkeyhere'
confirmExpiresInMinutes: 10080
papertrail =
destination: 'logs3.papertrailapp.com:13734'
groupId: 2199093
token: ''
helpscout =
apiKey: ''
baseUrl: 'https://api.helpscout.net/v1'
sneakerS3 =
awsSecretAccessKey: "#{awsKeys.worker_sneakerS3.secretAccessKey}"
awsAccessKeyId: "#{awsKeys.worker_sneakerS3.accessKeyId}"
sneakerS3Path: "s3://kodingdev-credential/"
sneakerMasterKey: ''
awsRegion: ''
stripe =
secretToken: ''
publicToken: ''
recaptcha =
secret: ''
public: ''
janitor =
port: '6700'
secretKey: ''
vmwatcher =
secretKey: ''
segment = ''
kontrol =
publicKey: "$KONFIG_PROJECTROOT/generated/private_keys/PI:KEY:<KEY>END_PI"
privateKey: "$KONFIG_PROJECTROOT/generated/private_keys/PI:KEY:<KEY>END_PI"
kloud =
publicKey: kontrol.publicKey
privateKey: kontrol.privateKey
secretKey: ''
janitorSecretKey: janitor.secretKey
vmwatcherSecretKey: vmwatcher.secretKey
terraformerSecretKey: terraformer.secretKey
userPublicKey: "$KONFIG_PROJECTROOT/generated/private_keys/kloud/kloud.pub"
userPrivateKey: "$KONFIG_PROJECTROOT/generated/private_keys/kloud/kloud.pem"
dummyAdmins = ['superadmin', 'admin', 'koding']
druid =
host : options.serviceHost
port : 8090
clearbit = '9d961e7ac862a6bc430f783da5cf9422'
intercomAppId = ''
wufoo = ''
return {
kiteHome
awsKeys
mongo
redis
monitoringRedis
rabbitmq
algolia
postgres
kontrolPostgres
pubnub
terraformer
googleapiServiceAccount
github
gitlab
facebook
mailgun
slack
google
twitter
linkedin
datadog
embedly
siftScience
siftSciencePublic
jwt
papertrail
helpscout
sneakerS3
stripe
recaptcha
janitor
segment
kontrol
kloud
vmwatcher
dummyAdmins
druid
clearbit
intercomAppId
wufoo
}
|
[
{
"context": " service: 'facebook'\n username: 'lessthan3'\n }\n {\n service: 'tw",
"end": 274,
"score": 0.9995625019073486,
"start": 265,
"tag": "USERNAME",
"value": "lessthan3"
},
{
"context": " service: 'twitter'\n username: 'lessthan3'\n }\n ]\n }\n style:\n col",
"end": 363,
"score": 0.9995123147964478,
"start": 354,
"tag": "USERNAME",
"value": "lessthan3"
},
{
"context": " collection: 'pages'\n data:\n name: 'My Name'\n bio: 'welcome to my website!'\n im",
"end": 928,
"score": 0.9490728378295898,
"start": 921,
"tag": "NAME",
"value": "My Name"
}
] | bootstrap/app/setup.cson | lessthan3/dobi | 5 | {
site:
collections:
projects:
slug: 'projects'
name: 'My First Dobi App'
regions: {
header:
logo: ''
footer:
copyright: ''
social: [
{
service: 'facebook'
username: 'lessthan3'
}
{
service: 'twitter'
username: 'lessthan3'
}
]
}
style:
color: '#f00038'
theme: 'light'
objects: [
{
collection: 'projects'
data:
name: 'Airport project'
icon: 'airport'
description: 'Some project I worked on'
image: ''
type: 'project'
}
{
collection: 'projects'
data:
name: 'Helicopter project'
icon: 'heliport'
description: 'Another project I worked on'
image: ''
type: 'project'
}
{
collection: 'pages'
data:
name: 'My Name'
bio: 'welcome to my website!'
image: ''
type: 'biography'
}
]
}
| 175659 | {
site:
collections:
projects:
slug: 'projects'
name: 'My First Dobi App'
regions: {
header:
logo: ''
footer:
copyright: ''
social: [
{
service: 'facebook'
username: 'lessthan3'
}
{
service: 'twitter'
username: 'lessthan3'
}
]
}
style:
color: '#f00038'
theme: 'light'
objects: [
{
collection: 'projects'
data:
name: 'Airport project'
icon: 'airport'
description: 'Some project I worked on'
image: ''
type: 'project'
}
{
collection: 'projects'
data:
name: 'Helicopter project'
icon: 'heliport'
description: 'Another project I worked on'
image: ''
type: 'project'
}
{
collection: 'pages'
data:
name: '<NAME>'
bio: 'welcome to my website!'
image: ''
type: 'biography'
}
]
}
| true | {
site:
collections:
projects:
slug: 'projects'
name: 'My First Dobi App'
regions: {
header:
logo: ''
footer:
copyright: ''
social: [
{
service: 'facebook'
username: 'lessthan3'
}
{
service: 'twitter'
username: 'lessthan3'
}
]
}
style:
color: '#f00038'
theme: 'light'
objects: [
{
collection: 'projects'
data:
name: 'Airport project'
icon: 'airport'
description: 'Some project I worked on'
image: ''
type: 'project'
}
{
collection: 'projects'
data:
name: 'Helicopter project'
icon: 'heliport'
description: 'Another project I worked on'
image: ''
type: 'project'
}
{
collection: 'pages'
data:
name: 'PI:NAME:<NAME>END_PI'
bio: 'welcome to my website!'
image: ''
type: 'biography'
}
]
}
|
[
{
"context": "create\", ->\n\t\t\tlayer = new Layer\n\t\t\tlayer.name = \"Test\"\n\t\t\tlayer.name.should.equal \"Test\"\n\t\t\tlayer._elem",
"end": 5183,
"score": 0.6713279485702515,
"start": 5179,
"tag": "NAME",
"value": "Test"
},
{
"context": "\t\tlayer.name = \"Test\"\n\t\t\tlayer.name.should.equal \"Test\"\n\t\t\tlayer._element.getAttribute(\"name\").should.eq",
"end": 5217,
"score": 0.6215034127235413,
"start": 5213,
"tag": "NAME",
"value": "Test"
}
] | test/tests/LayerTest.coffee | HydAu/FramerJS | 0 | assert = require "assert"
simulate = require "simulate"
describe "Layer", ->
# afterEach ->
# Utils.clearAll()
# beforeEach ->
# Framer.Utils.reset()
describe "Defaults", ->
it "should set defaults", ->
Framer.Defaults =
Layer:
width: 200
height: 200
layer = new Layer()
layer.width.should.equal 200
layer.height.should.equal 200
Framer.resetDefaults()
layer = new Layer()
layer.width.should.equal 100
layer.height.should.equal 100
it "should set default background color", ->
# if the default background color is not set the content layer of scrollcomponent is not hidden when layers are added
layer = new Layer()
Color.equal(layer.backgroundColor, Framer.Defaults.Layer.backgroundColor).should.be.true
Framer.Defaults =
Layer:
backgroundColor: "red"
layer = new Layer()
layer.style.backgroundColor.should.equal new Color("red").toString()
Framer.resetDefaults()
it "should set defaults with override", ->
layer = new Layer x:50, y:50
layer.x.should.equal 50
layer.x.should.equal 50
describe "Properties", ->
it "should set defaults", ->
layer = new Layer()
layer.x.should.equal 0
layer.y.should.equal 0
layer.z.should.equal 0
layer.width.should.equal 100
layer.height.should.equal 100
it "should set width", ->
layer = new Layer width:200
layer.width.should.equal 200
layer.style.width.should.equal "200px"
it "should set width not to scientific notation", ->
n = 0.000000000000002
n.toString().should.equal("2e-15")
layer = new Layer
layer.x = n
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set x and y", ->
layer = new Layer
layer.x = 100
layer.x.should.equal 100
layer.y = 50
layer.y.should.equal 50
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(100px, 50px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set scale", ->
layer = new Layer
layer.scaleX = 100
layer.scaleY = 100
layer.scaleZ = 100
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 50)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(100, 100, 100) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set origin", ->
layer = new Layer
originZ: 80
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.originX = 0.1
layer.originY = 0.2
layer.style.webkitTransformOrigin.should.equal "10% 20%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
layer.originX = 0.5
layer.originY = 0.5
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
it "should preserve 3D by default", ->
layer = new Layer
layer._element.style.webkitTransformStyle.should.equal "preserve-3d"
it "should flatten layer", ->
layer = new Layer
flat: true
layer._element.style.webkitTransformStyle.should.equal "flat"
it "should set local image", (done) ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
layer = new Layer
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
layer.props.image.should.equal fullPath
layer.on Events.ImageLoaded, ->
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.not.equal(-1)
done()
#layer.computedStyle()["background-size"].should.equal "cover"
#layer.computedStyle()["background-repeat"].should.equal "no-repeat"
it "should set image", ->
imagePath = "../static/test.png"
layer = new Layer image:imagePath
layer.image.should.equal imagePath
it "should unset image with null", ->
layer = new Layer image:"../static/test.png"
layer.image = null
layer.image.should.equal ""
it "should unset image with empty string", ->
layer = new Layer image:"../static/test.png"
layer.image = ""
layer.image.should.equal ""
it "should test image property type", ->
f = ->
layer = new Layer
layer.image = {}
f.should.throw()
it "should set name on create", ->
layer = new Layer name:"Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should set name after create", ->
layer = new Layer
layer.name = "Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should handle background color with image", ->
# We want the background color to be there until an images
# is set UNLESS we set another backgroundColor explicitly
imagePath = "../static/test.png"
layer = new Layer image:imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer
layer.image = imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer backgroundColor:"red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
layer = new Layer
layer.backgroundColor = "red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
it "should set visible", ->
layer = new Layer
layer.visible.should.equal true
layer.style["display"].should.equal "block"
layer.visible = false
layer.visible.should.equal false
layer.style["display"].should.equal "none"
it "should set clip", ->
layer = new Layer
layer.clip.should.equal false
layer.style["overflow"].should.equal "visible"
layer.clip = true
layer.style["overflow"].should.equal "hidden"
it "should set scroll", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
layer.scroll = false
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
it "should set scroll from properties", ->
layer = new Layer
layer.props = {scroll:false}
layer.scroll.should.equal false
layer.props = {scroll:true}
layer.scroll.should.equal true
it "should set scrollHorizontal", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.ignoreEvents.should.equal true
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
it "should set style properties on create", ->
layer = new Layer backgroundColor: "red"
layer.backgroundColor.isEqual(new Color("red")).should.equal true
layer.style["backgroundColor"].should.equal new Color("red").toString()
it "should check value type", ->
f = ->
layer = new Layer
layer.x = "hello"
f.should.throw()
it "should set borderRadius", ->
testBorderRadius = (layer, value) ->
if layer.style["border-top-left-radius"] is "#{value}"
layer.style["border-top-left-radius"].should.equal "#{value}"
layer.style["border-top-right-radius"].should.equal "#{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value}"
else
layer.style["border-top-left-radius"].should.equal "#{value} #{value}"
layer.style["border-top-right-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value} #{value}"
layer = new Layer
layer.borderRadius = 10
layer.borderRadius.should.equal 10
testBorderRadius(layer, "10px")
layer.borderRadius = "50%"
layer.borderRadius.should.equal "50%"
testBorderRadius(layer, "50%")
it "should set perspective", ->
layer = new Layer
layer.perspective = 500
layer.style["-webkit-perspective"].should.equal("500")
it "should have its backface visible by default", ->
layer = new Layer
layer.style["webkitBackfaceVisibility"].should.equal "visible"
it "should allow backface to be hidden", ->
layer = new Layer
layer.backfaceVisible = false
layer.style["webkitBackfaceVisibility"].should.equal "hidden"
it "should set rotation", ->
layer = new Layer
rotationX: 200
rotationY: 200
rotationZ: 200
layer.rotationX.should.equal(200)
layer.rotationY.should.equal(200)
layer.rotationZ.should.equal(200)
it "should proxy rotation", ->
layer = new Layer
layer.rotation = 200
layer.rotation.should.equal(200)
layer.rotationZ.should.equal(200)
layer.rotationZ = 100
layer.rotation.should.equal(100)
layer.rotationZ.should.equal(100)
describe "Filter Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.webkitFilter.should.equal ""
it "should set only the filter that is non default", ->
layer = new Layer
layer.blur = 10
layer.blur.should.equal 10
layer.style.webkitFilter.should.equal "blur(10px)"
layer.contrast = 50
layer.contrast.should.equal 50
layer.style.webkitFilter.should.equal "blur(10px) contrast(50%)"
describe "Shadow Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.boxShadow.should.equal ""
it "should set the shadow", ->
layer = new Layer
layer.shadowX = 10
layer.shadowY = 10
layer.shadowBlur = 10
layer.shadowSpread = 10
layer.shadowX.should.equal 10
layer.shadowY.should.equal 10
layer.shadowBlur.should.equal 10
layer.shadowSpread.should.equal 10
layer.style.boxShadow.should.equal "rgba(123, 123, 123, 0.496094) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = "red"
layer.shadowColor.r.should.equal 255
layer.shadowColor.g.should.equal 0
layer.shadowColor.b.should.equal 0
layer.shadowColor.a.should.equal 1
layer.style.boxShadow.should.equal "rgb(255, 0, 0) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = null
layer.style.boxShadow.should.equal "rgba(0, 0, 0, 0) 10px 10px 10px 10px"
it "should remove all events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on("test", handler)
layerA.removeAllListeners("test")
layerA.listeners("test").length.should.equal 0
it "should add and clean up dom events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
# But never more then one
layerA._domEventManager.listeners(Events.Click).length.should.equal(1)
layerA.removeAllListeners(Events.Click)
# And on removal, we should get rid of the dom event
layerA._domEventManager.listeners(Events.Click).length.should.equal(0)
it "should work with event helpers", (done) ->
layer = new Layer
layer.onMouseOver (event, aLayer) ->
aLayer.should.equal(layer)
@should.equal(layer)
done()
simulate.mouseover(layer._element)
it "should only pass dom events to the event manager", ->
layer = new Layer
layer.on Events.Click, ->
layer.on Events.Move, ->
layer._domEventManager.listenerEvents().should.eql([Events.Click])
describe "Hierarchy", ->
it "should insert in dom", ->
layer = new Layer
assert.equal layer._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layer.superLayer, null
it "should check superLayer", ->
f = -> layer = new Layer superLayer:1
f.should.throw()
it "should add child", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
assert.equal layerB._element.parentNode, layerA._element
assert.equal layerB.superLayer, layerA
it "should remove child", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerB.superLayer = null
assert.equal layerB._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layerB.superLayer, null
it "should list children", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
assert.deepEqual layerA.children, [layerB, layerC]
layerB.superLayer = null
assert.equal layerA.children.length, 1
assert.deepEqual layerA.children, [layerC]
layerC.superLayer = null
assert.deepEqual layerA.children, []
it "should list sibling root layers", ->
layerA = new Layer
layerB = new Layer
layerC = new Layer
assert layerB in layerA.siblingLayers, true
assert layerC in layerA.siblingLayers, true
it "should list sibling layers", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
assert.deepEqual layerB.siblingLayers, [layerC]
assert.deepEqual layerC.siblingLayers, [layerB]
it "should list super layers", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerB
assert.deepEqual layerC.superLayers(), [layerB, layerA]
it "should list descendants deeply", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerB
layerA.descendants.should.eql [layerB, layerC]
it "should list descendants", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
layerA.descendants.should.eql [layerB, layerC]
it "should set super/parent with property", ->
layerA = new Layer
layerB = new Layer
layerB.superLayer = layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
it "should set super/parent with with constructor", ->
layerA = new Layer
layerB = new Layer
superLayer: layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
describe "Layering", ->
it "should set at creation", ->
layer = new Layer index:666
layer.index.should.equal 666
it "should change index", ->
layer = new Layer
layer.index = 666
layer.index.should.equal 666
it "should be in front for root", ->
layerA = new Layer
layerB = new Layer
assert.equal layerB.index, layerA.index + 1
it "should be in front", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should send back and front", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
layerC.sendToBack()
assert.equal layerB.index, 1
assert.equal layerC.index, -1
layerC.bringToFront()
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should place in front", ->
layerA = new Layer
layerB = new Layer superLayer:layerA # 1
layerC = new Layer superLayer:layerA # 2
layerD = new Layer superLayer:layerA # 3
layerB.placeBefore layerC
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 3
it "should place behind", ->
layerA = new Layer
layerB = new Layer superLayer:layerA # 1
layerC = new Layer superLayer:layerA # 2
layerD = new Layer superLayer:layerA # 3
layerC.placeBehind layerB
# TODO: Still something fishy here, but it works
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 4
it "should get a children by name", ->
layerA = new Layer
layerB = new Layer name:"B", superLayer:layerA
layerC = new Layer name:"C", superLayer:layerA
layerD = new Layer name:"C", superLayer:layerA
layerA.childrenWithName("B").should.eql [layerB]
layerA.childrenWithName("C").should.eql [layerC, layerD]
it "should get a siblinglayer by name", ->
layerA = new Layer
layerB = new Layer name:"B", superLayer:layerA
layerC = new Layer name:"C", superLayer:layerA
layerD = new Layer name:"C", superLayer:layerA
layerB.siblingLayersByName("C").should.eql [layerC, layerD]
layerD.siblingLayersByName("B").should.eql [layerB]
it "should get a superlayers", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerB
layerC.superLayers().should.eql [layerB, layerA]
describe "Frame", ->
it "should set on create", ->
layer = new Layer frame:{x:111, y:222, width:333, height:444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set after create", ->
layer = new Layer
layer.frame = {x:111, y:222, width:333, height:444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set minX on creation", ->
layer = new Layer minX:200, y:100, width:100, height:100
layer.x.should.equal 200
it "should set midX on creation", ->
layer = new Layer midX:200, y:100, width:100, height:100
layer.x.should.equal 150
it "should set maxX on creation", ->
layer = new Layer maxX:200, y:100, width:100, height:100
layer.x.should.equal 100
it "should set minY on creation", ->
layer = new Layer x:100, minY:200, width:100, height:100
layer.y.should.equal 200
it "should set midY on creation", ->
layer = new Layer x:100, midY:200, width:100, height:100
layer.y.should.equal 150
it "should set maxY on creation", ->
layer = new Layer x:100, maxY:200, width:100, height:100
layer.y.should.equal 100
it "should set minX", ->
layer = new Layer y:100, width:100, height:100
layer.minX = 200
layer.x.should.equal 200
it "should set midX", ->
layer = new Layer y:100, width:100, height:100
layer.midX = 200
layer.x.should.equal 150
it "should set maxX", ->
layer = new Layer y:100, width:100, height:100
layer.maxX = 200
layer.x.should.equal 100
it "should set minY", ->
layer = new Layer x:100, width:100, height:100
layer.minY = 200
layer.y.should.equal 200
it "should set midY", ->
layer = new Layer x:100, width:100, height:100
layer.midY = 200
layer.y.should.equal 150
it "should set maxY", ->
layer = new Layer x:100, width:100, height:100
layer.maxY = 200
layer.y.should.equal 100
it "should get and set canvasFrame", ->
layerA = new Layer x:100, y:100, width:100, height:100
layerB = new Layer x:300, y:300, width:100, height:100, superLayer:layerA
assert.equal layerB.canvasFrame.x, 400
assert.equal layerB.canvasFrame.y, 400
layerB.canvasFrame = {x:1000, y:1000}
assert.equal layerB.canvasFrame.x, 1000
assert.equal layerB.canvasFrame.y, 1000
assert.equal layerB.x, 900
assert.equal layerB.y, 900
layerB.superLayer = null
assert.equal layerB.canvasFrame.x, 900
assert.equal layerB.canvasFrame.y, 900
it "should calculate scale", ->
layerA = new Layer scale:0.9
layerB = new Layer scale:0.8, superLayer:layerA
layerB.screenScaleX().should.equal 0.9 * 0.8
layerB.screenScaleY().should.equal 0.9 * 0.8
it "should calculate scaled frame", ->
layerA = new Layer x:100, width:500, height:900, scale:0.5
layerA.scaledFrame().should.eql {"x":225,"y":225,"width":250,"height":450}
it "should calculate scaled screen frame", ->
layerA = new Layer x:100, width:500, height:900, scale:0.5
layerB = new Layer y:50, width:600, height:600, scale:0.8, superLayer:layerA
layerC = new Layer y:-60, width:800, height:700, scale:1.2, superLayer:layerB
layerA.screenScaledFrame().should.eql {"x":225,"y":225,"width":250,"height":450}
layerB.screenScaledFrame().should.eql {"x":255,"y":280,"width":240,"height":240}
layerC.screenScaledFrame().should.eql {"x":223,"y":228,"width":384,"height":336}
it "should accept point shortcut", ->
layer = new Layer point:10
layer.x.should.equal 10
layer.y.should.equal 10
it "should accept size shortcut", ->
layer = new Layer size:10
layer.width.should.equal 10
layer.height.should.equal 10
describe "Center", ->
it "should center", ->
layerA = new Layer width:200, height:200
layerB = new Layer width:100, height:100, superLayer:layerA
layerB.center()
assert.equal layerB.x, 50
assert.equal layerB.y, 50
it "should center with offset", ->
layerA = new Layer width:200, height:200
layerB = new Layer width:100, height:100, superLayer:layerA
layerB.centerX(50)
layerB.centerY(50)
assert.equal layerB.x, 100
assert.equal layerB.y, 100
it "should center return layer", ->
layerA = new Layer width:200, height:200
layerA.center().should.equal layerA
layerA.centerX().should.equal layerA
layerA.centerY().should.equal layerA
it "should center pixel align", ->
layerA = new Layer width:200, height:200
layerB = new Layer width:111, height:111, superLayer:layerA
layerB.center().pixelAlign()
assert.equal layerB.x, 44
assert.equal layerB.y, 44
it "should center with border", ->
layer = new Layer
width: 200
height: 200
layer.borderColor = "green"
layer.borderWidth = 30
layer.center()
layerB = new Layer
superLayer: layer
backgroundColor: "red"
layerB.center()
layerB.frame.should.eql {x:20, y:20, width:100, height:100}
describe "CSS", ->
it "classList should work", ->
layer = new Layer
layer.classList.add "test"
assert.equal layer.classList.contains("test"), true
assert.equal layer._element.classList.contains("test"), true
describe "DOM", ->
it "should destroy", ->
layer = new Layer
layer.destroy()
(layer in Framer.CurrentContext.getLayers()).should.be.false
assert.equal layer._element.parentNode, null
it "should set text", ->
layer = new Layer
layer.html = "Hello"
layer._element.childNodes[0].should.equal layer._elementHTML
layer._elementHTML.innerHTML.should.equal "Hello"
layer.ignoreEvents.should.equal true
it "should not effect children", ->
layer = new Layer
layer.html = "Hello"
Child = new Layer superLayer: layer
Child._element.offsetTop.should.equal 0
it "should set interactive html and allow pointer events", ->
tags = ["input", "select", "textarea", "option"]
html = ""
for tag in tags
html += "<#{tag}></#{tag}>"
layer = new Layer
layer.html = html
for tag in tags
element = layer.querySelectorAll(tag)[0]
style = window.getComputedStyle(element)
style["pointer-events"].should.equal "auto"
# style["-webkit-user-select"].should.equal "auto"
it "should work with querySelectorAll", ->
layer = new Layer
layer.html = "<input type='button' id='hello'>"
inputElements = layer.querySelectorAll("input")
inputElements.length.should.equal 1
inputElement = _.head(inputElements)
inputElement.getAttribute("id").should.equal "hello"
describe "Force 2D", ->
it "should switch to 2d rendering", ->
layer = new Layer
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
layer.force2d = true
layer.style.webkitTransform.should.equal "translate(0px, 0px) scale(1) skew(0deg, 0deg) rotate(0deg)"
describe "Matrices", ->
it "should have the correct matrix", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
layer.matrix.toString().should.eql "matrix(1.957079, 1.957079, -0.871348, 0.871348, 200.000000, 120.000000)"
it "should have the correct matrix when 2d is forced", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
force2d: true
layer.matrix.toString().should.eql "matrix(2.165466, 1.957079, -1.079734, 0.871348, 200.000000, 120.000000)"
it "should have the correct transform matrix", ->
layer = new Layer
scale: 20
rotation: 5
rotationY: 20
x: 200
y: 120
skew: 21
layer.transformMatrix.toString().should.eql "matrix3d(19.391455, 8.929946, -0.340719, 0.000000, 6.010074, 19.295128, 0.029809, 0.000000, 6.840403, 2.625785, 0.939693, 0.000000, -1020.076470, -1241.253701, 15.545482, 1.000000)"
it "should have the correct screen point", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
roundX = Math.round(layer.convertPointToScreen().x)
roundX.should.eql 184
it "should have the correct screen frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.screenFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 133
boundingBox.height.should.eql 144
it "should have the correct canvas frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.canvasFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 133
boundingBox.height.should.eql 144
describe "Copy", ->
it "copied Layer should hold set props", ->
X = 100
Y = 200
IMAGE = '../static/test.png'
BORDERRADIUS = 20
layer = new Layer
x:X
y:Y
image:IMAGE
layer.borderRadius = BORDERRADIUS
layer.x.should.eql X
layer.y.should.eql Y
layer.image.should.eql IMAGE
layer.borderRadius.should.eql BORDERRADIUS
copy = layer.copy()
copy.x.should.eql X
copy.y.should.eql Y
copy.image.should.eql IMAGE
copy.borderRadius.should.eql BORDERRADIUS
it "copied Layer should have defaults", ->
layer = new Layer
copy = layer.copy()
copy.width.should.equal 100
copy.height.should.equal 100
describe "Draggable", ->
it "should stop x and y animations on drag start", ->
layer = new Layer
layer.draggable.enabled = true
a1 = layer.animate properties: {x:100}
a2 = layer.animate properties: {y:100}
a3 = layer.animate properties: {blur:1}
a1.isAnimating.should.equal true
a2.isAnimating.should.equal true
a3.isAnimating.should.equal true
layer.draggable.touchStart(document.createEvent("MouseEvent"))
a1.isAnimating.should.equal false
a2.isAnimating.should.equal false
a3.isAnimating.should.equal true
| 201303 | assert = require "assert"
simulate = require "simulate"
describe "Layer", ->
# afterEach ->
# Utils.clearAll()
# beforeEach ->
# Framer.Utils.reset()
describe "Defaults", ->
it "should set defaults", ->
Framer.Defaults =
Layer:
width: 200
height: 200
layer = new Layer()
layer.width.should.equal 200
layer.height.should.equal 200
Framer.resetDefaults()
layer = new Layer()
layer.width.should.equal 100
layer.height.should.equal 100
it "should set default background color", ->
# if the default background color is not set the content layer of scrollcomponent is not hidden when layers are added
layer = new Layer()
Color.equal(layer.backgroundColor, Framer.Defaults.Layer.backgroundColor).should.be.true
Framer.Defaults =
Layer:
backgroundColor: "red"
layer = new Layer()
layer.style.backgroundColor.should.equal new Color("red").toString()
Framer.resetDefaults()
it "should set defaults with override", ->
layer = new Layer x:50, y:50
layer.x.should.equal 50
layer.x.should.equal 50
describe "Properties", ->
it "should set defaults", ->
layer = new Layer()
layer.x.should.equal 0
layer.y.should.equal 0
layer.z.should.equal 0
layer.width.should.equal 100
layer.height.should.equal 100
it "should set width", ->
layer = new Layer width:200
layer.width.should.equal 200
layer.style.width.should.equal "200px"
it "should set width not to scientific notation", ->
n = 0.000000000000002
n.toString().should.equal("2e-15")
layer = new Layer
layer.x = n
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set x and y", ->
layer = new Layer
layer.x = 100
layer.x.should.equal 100
layer.y = 50
layer.y.should.equal 50
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(100px, 50px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set scale", ->
layer = new Layer
layer.scaleX = 100
layer.scaleY = 100
layer.scaleZ = 100
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 50)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(100, 100, 100) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set origin", ->
layer = new Layer
originZ: 80
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.originX = 0.1
layer.originY = 0.2
layer.style.webkitTransformOrigin.should.equal "10% 20%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
layer.originX = 0.5
layer.originY = 0.5
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
it "should preserve 3D by default", ->
layer = new Layer
layer._element.style.webkitTransformStyle.should.equal "preserve-3d"
it "should flatten layer", ->
layer = new Layer
flat: true
layer._element.style.webkitTransformStyle.should.equal "flat"
it "should set local image", (done) ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
layer = new Layer
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
layer.props.image.should.equal fullPath
layer.on Events.ImageLoaded, ->
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.not.equal(-1)
done()
#layer.computedStyle()["background-size"].should.equal "cover"
#layer.computedStyle()["background-repeat"].should.equal "no-repeat"
it "should set image", ->
imagePath = "../static/test.png"
layer = new Layer image:imagePath
layer.image.should.equal imagePath
it "should unset image with null", ->
layer = new Layer image:"../static/test.png"
layer.image = null
layer.image.should.equal ""
it "should unset image with empty string", ->
layer = new Layer image:"../static/test.png"
layer.image = ""
layer.image.should.equal ""
it "should test image property type", ->
f = ->
layer = new Layer
layer.image = {}
f.should.throw()
it "should set name on create", ->
layer = new Layer name:"Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should set name after create", ->
layer = new Layer
layer.name = "<NAME>"
layer.name.should.equal "<NAME>"
layer._element.getAttribute("name").should.equal "Test"
it "should handle background color with image", ->
# We want the background color to be there until an images
# is set UNLESS we set another backgroundColor explicitly
imagePath = "../static/test.png"
layer = new Layer image:imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer
layer.image = imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer backgroundColor:"red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
layer = new Layer
layer.backgroundColor = "red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
it "should set visible", ->
layer = new Layer
layer.visible.should.equal true
layer.style["display"].should.equal "block"
layer.visible = false
layer.visible.should.equal false
layer.style["display"].should.equal "none"
it "should set clip", ->
layer = new Layer
layer.clip.should.equal false
layer.style["overflow"].should.equal "visible"
layer.clip = true
layer.style["overflow"].should.equal "hidden"
it "should set scroll", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
layer.scroll = false
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
it "should set scroll from properties", ->
layer = new Layer
layer.props = {scroll:false}
layer.scroll.should.equal false
layer.props = {scroll:true}
layer.scroll.should.equal true
it "should set scrollHorizontal", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.ignoreEvents.should.equal true
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
it "should set style properties on create", ->
layer = new Layer backgroundColor: "red"
layer.backgroundColor.isEqual(new Color("red")).should.equal true
layer.style["backgroundColor"].should.equal new Color("red").toString()
it "should check value type", ->
f = ->
layer = new Layer
layer.x = "hello"
f.should.throw()
it "should set borderRadius", ->
testBorderRadius = (layer, value) ->
if layer.style["border-top-left-radius"] is "#{value}"
layer.style["border-top-left-radius"].should.equal "#{value}"
layer.style["border-top-right-radius"].should.equal "#{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value}"
else
layer.style["border-top-left-radius"].should.equal "#{value} #{value}"
layer.style["border-top-right-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value} #{value}"
layer = new Layer
layer.borderRadius = 10
layer.borderRadius.should.equal 10
testBorderRadius(layer, "10px")
layer.borderRadius = "50%"
layer.borderRadius.should.equal "50%"
testBorderRadius(layer, "50%")
it "should set perspective", ->
layer = new Layer
layer.perspective = 500
layer.style["-webkit-perspective"].should.equal("500")
it "should have its backface visible by default", ->
layer = new Layer
layer.style["webkitBackfaceVisibility"].should.equal "visible"
it "should allow backface to be hidden", ->
layer = new Layer
layer.backfaceVisible = false
layer.style["webkitBackfaceVisibility"].should.equal "hidden"
it "should set rotation", ->
layer = new Layer
rotationX: 200
rotationY: 200
rotationZ: 200
layer.rotationX.should.equal(200)
layer.rotationY.should.equal(200)
layer.rotationZ.should.equal(200)
it "should proxy rotation", ->
layer = new Layer
layer.rotation = 200
layer.rotation.should.equal(200)
layer.rotationZ.should.equal(200)
layer.rotationZ = 100
layer.rotation.should.equal(100)
layer.rotationZ.should.equal(100)
describe "Filter Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.webkitFilter.should.equal ""
it "should set only the filter that is non default", ->
layer = new Layer
layer.blur = 10
layer.blur.should.equal 10
layer.style.webkitFilter.should.equal "blur(10px)"
layer.contrast = 50
layer.contrast.should.equal 50
layer.style.webkitFilter.should.equal "blur(10px) contrast(50%)"
describe "Shadow Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.boxShadow.should.equal ""
it "should set the shadow", ->
layer = new Layer
layer.shadowX = 10
layer.shadowY = 10
layer.shadowBlur = 10
layer.shadowSpread = 10
layer.shadowX.should.equal 10
layer.shadowY.should.equal 10
layer.shadowBlur.should.equal 10
layer.shadowSpread.should.equal 10
layer.style.boxShadow.should.equal "rgba(123, 123, 123, 0.496094) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = "red"
layer.shadowColor.r.should.equal 255
layer.shadowColor.g.should.equal 0
layer.shadowColor.b.should.equal 0
layer.shadowColor.a.should.equal 1
layer.style.boxShadow.should.equal "rgb(255, 0, 0) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = null
layer.style.boxShadow.should.equal "rgba(0, 0, 0, 0) 10px 10px 10px 10px"
it "should remove all events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on("test", handler)
layerA.removeAllListeners("test")
layerA.listeners("test").length.should.equal 0
it "should add and clean up dom events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
# But never more then one
layerA._domEventManager.listeners(Events.Click).length.should.equal(1)
layerA.removeAllListeners(Events.Click)
# And on removal, we should get rid of the dom event
layerA._domEventManager.listeners(Events.Click).length.should.equal(0)
it "should work with event helpers", (done) ->
layer = new Layer
layer.onMouseOver (event, aLayer) ->
aLayer.should.equal(layer)
@should.equal(layer)
done()
simulate.mouseover(layer._element)
it "should only pass dom events to the event manager", ->
layer = new Layer
layer.on Events.Click, ->
layer.on Events.Move, ->
layer._domEventManager.listenerEvents().should.eql([Events.Click])
describe "Hierarchy", ->
it "should insert in dom", ->
layer = new Layer
assert.equal layer._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layer.superLayer, null
it "should check superLayer", ->
f = -> layer = new Layer superLayer:1
f.should.throw()
it "should add child", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
assert.equal layerB._element.parentNode, layerA._element
assert.equal layerB.superLayer, layerA
it "should remove child", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerB.superLayer = null
assert.equal layerB._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layerB.superLayer, null
it "should list children", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
assert.deepEqual layerA.children, [layerB, layerC]
layerB.superLayer = null
assert.equal layerA.children.length, 1
assert.deepEqual layerA.children, [layerC]
layerC.superLayer = null
assert.deepEqual layerA.children, []
it "should list sibling root layers", ->
layerA = new Layer
layerB = new Layer
layerC = new Layer
assert layerB in layerA.siblingLayers, true
assert layerC in layerA.siblingLayers, true
it "should list sibling layers", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
assert.deepEqual layerB.siblingLayers, [layerC]
assert.deepEqual layerC.siblingLayers, [layerB]
it "should list super layers", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerB
assert.deepEqual layerC.superLayers(), [layerB, layerA]
it "should list descendants deeply", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerB
layerA.descendants.should.eql [layerB, layerC]
it "should list descendants", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
layerA.descendants.should.eql [layerB, layerC]
it "should set super/parent with property", ->
layerA = new Layer
layerB = new Layer
layerB.superLayer = layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
it "should set super/parent with with constructor", ->
layerA = new Layer
layerB = new Layer
superLayer: layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
describe "Layering", ->
it "should set at creation", ->
layer = new Layer index:666
layer.index.should.equal 666
it "should change index", ->
layer = new Layer
layer.index = 666
layer.index.should.equal 666
it "should be in front for root", ->
layerA = new Layer
layerB = new Layer
assert.equal layerB.index, layerA.index + 1
it "should be in front", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should send back and front", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
layerC.sendToBack()
assert.equal layerB.index, 1
assert.equal layerC.index, -1
layerC.bringToFront()
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should place in front", ->
layerA = new Layer
layerB = new Layer superLayer:layerA # 1
layerC = new Layer superLayer:layerA # 2
layerD = new Layer superLayer:layerA # 3
layerB.placeBefore layerC
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 3
it "should place behind", ->
layerA = new Layer
layerB = new Layer superLayer:layerA # 1
layerC = new Layer superLayer:layerA # 2
layerD = new Layer superLayer:layerA # 3
layerC.placeBehind layerB
# TODO: Still something fishy here, but it works
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 4
it "should get a children by name", ->
layerA = new Layer
layerB = new Layer name:"B", superLayer:layerA
layerC = new Layer name:"C", superLayer:layerA
layerD = new Layer name:"C", superLayer:layerA
layerA.childrenWithName("B").should.eql [layerB]
layerA.childrenWithName("C").should.eql [layerC, layerD]
it "should get a siblinglayer by name", ->
layerA = new Layer
layerB = new Layer name:"B", superLayer:layerA
layerC = new Layer name:"C", superLayer:layerA
layerD = new Layer name:"C", superLayer:layerA
layerB.siblingLayersByName("C").should.eql [layerC, layerD]
layerD.siblingLayersByName("B").should.eql [layerB]
it "should get a superlayers", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerB
layerC.superLayers().should.eql [layerB, layerA]
describe "Frame", ->
it "should set on create", ->
layer = new Layer frame:{x:111, y:222, width:333, height:444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set after create", ->
layer = new Layer
layer.frame = {x:111, y:222, width:333, height:444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set minX on creation", ->
layer = new Layer minX:200, y:100, width:100, height:100
layer.x.should.equal 200
it "should set midX on creation", ->
layer = new Layer midX:200, y:100, width:100, height:100
layer.x.should.equal 150
it "should set maxX on creation", ->
layer = new Layer maxX:200, y:100, width:100, height:100
layer.x.should.equal 100
it "should set minY on creation", ->
layer = new Layer x:100, minY:200, width:100, height:100
layer.y.should.equal 200
it "should set midY on creation", ->
layer = new Layer x:100, midY:200, width:100, height:100
layer.y.should.equal 150
it "should set maxY on creation", ->
layer = new Layer x:100, maxY:200, width:100, height:100
layer.y.should.equal 100
it "should set minX", ->
layer = new Layer y:100, width:100, height:100
layer.minX = 200
layer.x.should.equal 200
it "should set midX", ->
layer = new Layer y:100, width:100, height:100
layer.midX = 200
layer.x.should.equal 150
it "should set maxX", ->
layer = new Layer y:100, width:100, height:100
layer.maxX = 200
layer.x.should.equal 100
it "should set minY", ->
layer = new Layer x:100, width:100, height:100
layer.minY = 200
layer.y.should.equal 200
it "should set midY", ->
layer = new Layer x:100, width:100, height:100
layer.midY = 200
layer.y.should.equal 150
it "should set maxY", ->
layer = new Layer x:100, width:100, height:100
layer.maxY = 200
layer.y.should.equal 100
it "should get and set canvasFrame", ->
layerA = new Layer x:100, y:100, width:100, height:100
layerB = new Layer x:300, y:300, width:100, height:100, superLayer:layerA
assert.equal layerB.canvasFrame.x, 400
assert.equal layerB.canvasFrame.y, 400
layerB.canvasFrame = {x:1000, y:1000}
assert.equal layerB.canvasFrame.x, 1000
assert.equal layerB.canvasFrame.y, 1000
assert.equal layerB.x, 900
assert.equal layerB.y, 900
layerB.superLayer = null
assert.equal layerB.canvasFrame.x, 900
assert.equal layerB.canvasFrame.y, 900
it "should calculate scale", ->
layerA = new Layer scale:0.9
layerB = new Layer scale:0.8, superLayer:layerA
layerB.screenScaleX().should.equal 0.9 * 0.8
layerB.screenScaleY().should.equal 0.9 * 0.8
it "should calculate scaled frame", ->
layerA = new Layer x:100, width:500, height:900, scale:0.5
layerA.scaledFrame().should.eql {"x":225,"y":225,"width":250,"height":450}
it "should calculate scaled screen frame", ->
layerA = new Layer x:100, width:500, height:900, scale:0.5
layerB = new Layer y:50, width:600, height:600, scale:0.8, superLayer:layerA
layerC = new Layer y:-60, width:800, height:700, scale:1.2, superLayer:layerB
layerA.screenScaledFrame().should.eql {"x":225,"y":225,"width":250,"height":450}
layerB.screenScaledFrame().should.eql {"x":255,"y":280,"width":240,"height":240}
layerC.screenScaledFrame().should.eql {"x":223,"y":228,"width":384,"height":336}
it "should accept point shortcut", ->
layer = new Layer point:10
layer.x.should.equal 10
layer.y.should.equal 10
it "should accept size shortcut", ->
layer = new Layer size:10
layer.width.should.equal 10
layer.height.should.equal 10
describe "Center", ->
it "should center", ->
layerA = new Layer width:200, height:200
layerB = new Layer width:100, height:100, superLayer:layerA
layerB.center()
assert.equal layerB.x, 50
assert.equal layerB.y, 50
it "should center with offset", ->
layerA = new Layer width:200, height:200
layerB = new Layer width:100, height:100, superLayer:layerA
layerB.centerX(50)
layerB.centerY(50)
assert.equal layerB.x, 100
assert.equal layerB.y, 100
it "should center return layer", ->
layerA = new Layer width:200, height:200
layerA.center().should.equal layerA
layerA.centerX().should.equal layerA
layerA.centerY().should.equal layerA
it "should center pixel align", ->
layerA = new Layer width:200, height:200
layerB = new Layer width:111, height:111, superLayer:layerA
layerB.center().pixelAlign()
assert.equal layerB.x, 44
assert.equal layerB.y, 44
it "should center with border", ->
layer = new Layer
width: 200
height: 200
layer.borderColor = "green"
layer.borderWidth = 30
layer.center()
layerB = new Layer
superLayer: layer
backgroundColor: "red"
layerB.center()
layerB.frame.should.eql {x:20, y:20, width:100, height:100}
describe "CSS", ->
it "classList should work", ->
layer = new Layer
layer.classList.add "test"
assert.equal layer.classList.contains("test"), true
assert.equal layer._element.classList.contains("test"), true
describe "DOM", ->
it "should destroy", ->
layer = new Layer
layer.destroy()
(layer in Framer.CurrentContext.getLayers()).should.be.false
assert.equal layer._element.parentNode, null
it "should set text", ->
layer = new Layer
layer.html = "Hello"
layer._element.childNodes[0].should.equal layer._elementHTML
layer._elementHTML.innerHTML.should.equal "Hello"
layer.ignoreEvents.should.equal true
it "should not effect children", ->
layer = new Layer
layer.html = "Hello"
Child = new Layer superLayer: layer
Child._element.offsetTop.should.equal 0
it "should set interactive html and allow pointer events", ->
tags = ["input", "select", "textarea", "option"]
html = ""
for tag in tags
html += "<#{tag}></#{tag}>"
layer = new Layer
layer.html = html
for tag in tags
element = layer.querySelectorAll(tag)[0]
style = window.getComputedStyle(element)
style["pointer-events"].should.equal "auto"
# style["-webkit-user-select"].should.equal "auto"
it "should work with querySelectorAll", ->
layer = new Layer
layer.html = "<input type='button' id='hello'>"
inputElements = layer.querySelectorAll("input")
inputElements.length.should.equal 1
inputElement = _.head(inputElements)
inputElement.getAttribute("id").should.equal "hello"
describe "Force 2D", ->
it "should switch to 2d rendering", ->
layer = new Layer
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
layer.force2d = true
layer.style.webkitTransform.should.equal "translate(0px, 0px) scale(1) skew(0deg, 0deg) rotate(0deg)"
describe "Matrices", ->
it "should have the correct matrix", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
layer.matrix.toString().should.eql "matrix(1.957079, 1.957079, -0.871348, 0.871348, 200.000000, 120.000000)"
it "should have the correct matrix when 2d is forced", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
force2d: true
layer.matrix.toString().should.eql "matrix(2.165466, 1.957079, -1.079734, 0.871348, 200.000000, 120.000000)"
it "should have the correct transform matrix", ->
layer = new Layer
scale: 20
rotation: 5
rotationY: 20
x: 200
y: 120
skew: 21
layer.transformMatrix.toString().should.eql "matrix3d(19.391455, 8.929946, -0.340719, 0.000000, 6.010074, 19.295128, 0.029809, 0.000000, 6.840403, 2.625785, 0.939693, 0.000000, -1020.076470, -1241.253701, 15.545482, 1.000000)"
it "should have the correct screen point", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
roundX = Math.round(layer.convertPointToScreen().x)
roundX.should.eql 184
it "should have the correct screen frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.screenFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 133
boundingBox.height.should.eql 144
it "should have the correct canvas frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.canvasFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 133
boundingBox.height.should.eql 144
describe "Copy", ->
it "copied Layer should hold set props", ->
X = 100
Y = 200
IMAGE = '../static/test.png'
BORDERRADIUS = 20
layer = new Layer
x:X
y:Y
image:IMAGE
layer.borderRadius = BORDERRADIUS
layer.x.should.eql X
layer.y.should.eql Y
layer.image.should.eql IMAGE
layer.borderRadius.should.eql BORDERRADIUS
copy = layer.copy()
copy.x.should.eql X
copy.y.should.eql Y
copy.image.should.eql IMAGE
copy.borderRadius.should.eql BORDERRADIUS
it "copied Layer should have defaults", ->
layer = new Layer
copy = layer.copy()
copy.width.should.equal 100
copy.height.should.equal 100
describe "Draggable", ->
it "should stop x and y animations on drag start", ->
layer = new Layer
layer.draggable.enabled = true
a1 = layer.animate properties: {x:100}
a2 = layer.animate properties: {y:100}
a3 = layer.animate properties: {blur:1}
a1.isAnimating.should.equal true
a2.isAnimating.should.equal true
a3.isAnimating.should.equal true
layer.draggable.touchStart(document.createEvent("MouseEvent"))
a1.isAnimating.should.equal false
a2.isAnimating.should.equal false
a3.isAnimating.should.equal true
| true | assert = require "assert"
simulate = require "simulate"
describe "Layer", ->
# afterEach ->
# Utils.clearAll()
# beforeEach ->
# Framer.Utils.reset()
describe "Defaults", ->
it "should set defaults", ->
Framer.Defaults =
Layer:
width: 200
height: 200
layer = new Layer()
layer.width.should.equal 200
layer.height.should.equal 200
Framer.resetDefaults()
layer = new Layer()
layer.width.should.equal 100
layer.height.should.equal 100
it "should set default background color", ->
# if the default background color is not set the content layer of scrollcomponent is not hidden when layers are added
layer = new Layer()
Color.equal(layer.backgroundColor, Framer.Defaults.Layer.backgroundColor).should.be.true
Framer.Defaults =
Layer:
backgroundColor: "red"
layer = new Layer()
layer.style.backgroundColor.should.equal new Color("red").toString()
Framer.resetDefaults()
it "should set defaults with override", ->
layer = new Layer x:50, y:50
layer.x.should.equal 50
layer.x.should.equal 50
describe "Properties", ->
it "should set defaults", ->
layer = new Layer()
layer.x.should.equal 0
layer.y.should.equal 0
layer.z.should.equal 0
layer.width.should.equal 100
layer.height.should.equal 100
it "should set width", ->
layer = new Layer width:200
layer.width.should.equal 200
layer.style.width.should.equal "200px"
it "should set width not to scientific notation", ->
n = 0.000000000000002
n.toString().should.equal("2e-15")
layer = new Layer
layer.x = n
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set x and y", ->
layer = new Layer
layer.x = 100
layer.x.should.equal 100
layer.y = 50
layer.y.should.equal 50
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(100px, 50px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set scale", ->
layer = new Layer
layer.scaleX = 100
layer.scaleY = 100
layer.scaleZ = 100
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 50)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(100, 100, 100) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set origin", ->
layer = new Layer
originZ: 80
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.originX = 0.1
layer.originY = 0.2
layer.style.webkitTransformOrigin.should.equal "10% 20%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
layer.originX = 0.5
layer.originY = 0.5
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
it "should preserve 3D by default", ->
layer = new Layer
layer._element.style.webkitTransformStyle.should.equal "preserve-3d"
it "should flatten layer", ->
layer = new Layer
flat: true
layer._element.style.webkitTransformStyle.should.equal "flat"
it "should set local image", (done) ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
layer = new Layer
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
layer.props.image.should.equal fullPath
layer.on Events.ImageLoaded, ->
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.not.equal(-1)
done()
#layer.computedStyle()["background-size"].should.equal "cover"
#layer.computedStyle()["background-repeat"].should.equal "no-repeat"
it "should set image", ->
imagePath = "../static/test.png"
layer = new Layer image:imagePath
layer.image.should.equal imagePath
it "should unset image with null", ->
layer = new Layer image:"../static/test.png"
layer.image = null
layer.image.should.equal ""
it "should unset image with empty string", ->
layer = new Layer image:"../static/test.png"
layer.image = ""
layer.image.should.equal ""
it "should test image property type", ->
f = ->
layer = new Layer
layer.image = {}
f.should.throw()
it "should set name on create", ->
layer = new Layer name:"Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should set name after create", ->
layer = new Layer
layer.name = "PI:NAME:<NAME>END_PI"
layer.name.should.equal "PI:NAME:<NAME>END_PI"
layer._element.getAttribute("name").should.equal "Test"
it "should handle background color with image", ->
# We want the background color to be there until an images
# is set UNLESS we set another backgroundColor explicitly
imagePath = "../static/test.png"
layer = new Layer image:imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer
layer.image = imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer backgroundColor:"red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
layer = new Layer
layer.backgroundColor = "red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
it "should set visible", ->
layer = new Layer
layer.visible.should.equal true
layer.style["display"].should.equal "block"
layer.visible = false
layer.visible.should.equal false
layer.style["display"].should.equal "none"
it "should set clip", ->
layer = new Layer
layer.clip.should.equal false
layer.style["overflow"].should.equal "visible"
layer.clip = true
layer.style["overflow"].should.equal "hidden"
it "should set scroll", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
layer.scroll = false
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
it "should set scroll from properties", ->
layer = new Layer
layer.props = {scroll:false}
layer.scroll.should.equal false
layer.props = {scroll:true}
layer.scroll.should.equal true
it "should set scrollHorizontal", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.ignoreEvents.should.equal true
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
it "should set style properties on create", ->
layer = new Layer backgroundColor: "red"
layer.backgroundColor.isEqual(new Color("red")).should.equal true
layer.style["backgroundColor"].should.equal new Color("red").toString()
it "should check value type", ->
f = ->
layer = new Layer
layer.x = "hello"
f.should.throw()
it "should set borderRadius", ->
testBorderRadius = (layer, value) ->
if layer.style["border-top-left-radius"] is "#{value}"
layer.style["border-top-left-radius"].should.equal "#{value}"
layer.style["border-top-right-radius"].should.equal "#{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value}"
else
layer.style["border-top-left-radius"].should.equal "#{value} #{value}"
layer.style["border-top-right-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value} #{value}"
layer = new Layer
layer.borderRadius = 10
layer.borderRadius.should.equal 10
testBorderRadius(layer, "10px")
layer.borderRadius = "50%"
layer.borderRadius.should.equal "50%"
testBorderRadius(layer, "50%")
it "should set perspective", ->
layer = new Layer
layer.perspective = 500
layer.style["-webkit-perspective"].should.equal("500")
it "should have its backface visible by default", ->
layer = new Layer
layer.style["webkitBackfaceVisibility"].should.equal "visible"
it "should allow backface to be hidden", ->
layer = new Layer
layer.backfaceVisible = false
layer.style["webkitBackfaceVisibility"].should.equal "hidden"
it "should set rotation", ->
layer = new Layer
rotationX: 200
rotationY: 200
rotationZ: 200
layer.rotationX.should.equal(200)
layer.rotationY.should.equal(200)
layer.rotationZ.should.equal(200)
it "should proxy rotation", ->
layer = new Layer
layer.rotation = 200
layer.rotation.should.equal(200)
layer.rotationZ.should.equal(200)
layer.rotationZ = 100
layer.rotation.should.equal(100)
layer.rotationZ.should.equal(100)
describe "Filter Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.webkitFilter.should.equal ""
it "should set only the filter that is non default", ->
layer = new Layer
layer.blur = 10
layer.blur.should.equal 10
layer.style.webkitFilter.should.equal "blur(10px)"
layer.contrast = 50
layer.contrast.should.equal 50
layer.style.webkitFilter.should.equal "blur(10px) contrast(50%)"
describe "Shadow Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.boxShadow.should.equal ""
it "should set the shadow", ->
layer = new Layer
layer.shadowX = 10
layer.shadowY = 10
layer.shadowBlur = 10
layer.shadowSpread = 10
layer.shadowX.should.equal 10
layer.shadowY.should.equal 10
layer.shadowBlur.should.equal 10
layer.shadowSpread.should.equal 10
layer.style.boxShadow.should.equal "rgba(123, 123, 123, 0.496094) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = "red"
layer.shadowColor.r.should.equal 255
layer.shadowColor.g.should.equal 0
layer.shadowColor.b.should.equal 0
layer.shadowColor.a.should.equal 1
layer.style.boxShadow.should.equal "rgb(255, 0, 0) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = null
layer.style.boxShadow.should.equal "rgba(0, 0, 0, 0) 10px 10px 10px 10px"
it "should remove all events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on("test", handler)
layerA.removeAllListeners("test")
layerA.listeners("test").length.should.equal 0
it "should add and clean up dom events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
# But never more then one
layerA._domEventManager.listeners(Events.Click).length.should.equal(1)
layerA.removeAllListeners(Events.Click)
# And on removal, we should get rid of the dom event
layerA._domEventManager.listeners(Events.Click).length.should.equal(0)
it "should work with event helpers", (done) ->
layer = new Layer
layer.onMouseOver (event, aLayer) ->
aLayer.should.equal(layer)
@should.equal(layer)
done()
simulate.mouseover(layer._element)
it "should only pass dom events to the event manager", ->
layer = new Layer
layer.on Events.Click, ->
layer.on Events.Move, ->
layer._domEventManager.listenerEvents().should.eql([Events.Click])
describe "Hierarchy", ->
it "should insert in dom", ->
layer = new Layer
assert.equal layer._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layer.superLayer, null
it "should check superLayer", ->
f = -> layer = new Layer superLayer:1
f.should.throw()
it "should add child", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
assert.equal layerB._element.parentNode, layerA._element
assert.equal layerB.superLayer, layerA
it "should remove child", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerB.superLayer = null
assert.equal layerB._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layerB.superLayer, null
it "should list children", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
assert.deepEqual layerA.children, [layerB, layerC]
layerB.superLayer = null
assert.equal layerA.children.length, 1
assert.deepEqual layerA.children, [layerC]
layerC.superLayer = null
assert.deepEqual layerA.children, []
it "should list sibling root layers", ->
layerA = new Layer
layerB = new Layer
layerC = new Layer
assert layerB in layerA.siblingLayers, true
assert layerC in layerA.siblingLayers, true
it "should list sibling layers", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
assert.deepEqual layerB.siblingLayers, [layerC]
assert.deepEqual layerC.siblingLayers, [layerB]
it "should list super layers", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerB
assert.deepEqual layerC.superLayers(), [layerB, layerA]
it "should list descendants deeply", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerB
layerA.descendants.should.eql [layerB, layerC]
it "should list descendants", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
layerA.descendants.should.eql [layerB, layerC]
it "should set super/parent with property", ->
layerA = new Layer
layerB = new Layer
layerB.superLayer = layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
it "should set super/parent with with constructor", ->
layerA = new Layer
layerB = new Layer
superLayer: layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
describe "Layering", ->
it "should set at creation", ->
layer = new Layer index:666
layer.index.should.equal 666
it "should change index", ->
layer = new Layer
layer.index = 666
layer.index.should.equal 666
it "should be in front for root", ->
layerA = new Layer
layerB = new Layer
assert.equal layerB.index, layerA.index + 1
it "should be in front", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should send back and front", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerA
layerC.sendToBack()
assert.equal layerB.index, 1
assert.equal layerC.index, -1
layerC.bringToFront()
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should place in front", ->
layerA = new Layer
layerB = new Layer superLayer:layerA # 1
layerC = new Layer superLayer:layerA # 2
layerD = new Layer superLayer:layerA # 3
layerB.placeBefore layerC
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 3
it "should place behind", ->
layerA = new Layer
layerB = new Layer superLayer:layerA # 1
layerC = new Layer superLayer:layerA # 2
layerD = new Layer superLayer:layerA # 3
layerC.placeBehind layerB
# TODO: Still something fishy here, but it works
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 4
it "should get a children by name", ->
layerA = new Layer
layerB = new Layer name:"B", superLayer:layerA
layerC = new Layer name:"C", superLayer:layerA
layerD = new Layer name:"C", superLayer:layerA
layerA.childrenWithName("B").should.eql [layerB]
layerA.childrenWithName("C").should.eql [layerC, layerD]
it "should get a siblinglayer by name", ->
layerA = new Layer
layerB = new Layer name:"B", superLayer:layerA
layerC = new Layer name:"C", superLayer:layerA
layerD = new Layer name:"C", superLayer:layerA
layerB.siblingLayersByName("C").should.eql [layerC, layerD]
layerD.siblingLayersByName("B").should.eql [layerB]
it "should get a superlayers", ->
layerA = new Layer
layerB = new Layer superLayer:layerA
layerC = new Layer superLayer:layerB
layerC.superLayers().should.eql [layerB, layerA]
describe "Frame", ->
it "should set on create", ->
layer = new Layer frame:{x:111, y:222, width:333, height:444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set after create", ->
layer = new Layer
layer.frame = {x:111, y:222, width:333, height:444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set minX on creation", ->
layer = new Layer minX:200, y:100, width:100, height:100
layer.x.should.equal 200
it "should set midX on creation", ->
layer = new Layer midX:200, y:100, width:100, height:100
layer.x.should.equal 150
it "should set maxX on creation", ->
layer = new Layer maxX:200, y:100, width:100, height:100
layer.x.should.equal 100
it "should set minY on creation", ->
layer = new Layer x:100, minY:200, width:100, height:100
layer.y.should.equal 200
it "should set midY on creation", ->
layer = new Layer x:100, midY:200, width:100, height:100
layer.y.should.equal 150
it "should set maxY on creation", ->
layer = new Layer x:100, maxY:200, width:100, height:100
layer.y.should.equal 100
it "should set minX", ->
layer = new Layer y:100, width:100, height:100
layer.minX = 200
layer.x.should.equal 200
it "should set midX", ->
layer = new Layer y:100, width:100, height:100
layer.midX = 200
layer.x.should.equal 150
it "should set maxX", ->
layer = new Layer y:100, width:100, height:100
layer.maxX = 200
layer.x.should.equal 100
it "should set minY", ->
layer = new Layer x:100, width:100, height:100
layer.minY = 200
layer.y.should.equal 200
it "should set midY", ->
layer = new Layer x:100, width:100, height:100
layer.midY = 200
layer.y.should.equal 150
it "should set maxY", ->
layer = new Layer x:100, width:100, height:100
layer.maxY = 200
layer.y.should.equal 100
it "should get and set canvasFrame", ->
layerA = new Layer x:100, y:100, width:100, height:100
layerB = new Layer x:300, y:300, width:100, height:100, superLayer:layerA
assert.equal layerB.canvasFrame.x, 400
assert.equal layerB.canvasFrame.y, 400
layerB.canvasFrame = {x:1000, y:1000}
assert.equal layerB.canvasFrame.x, 1000
assert.equal layerB.canvasFrame.y, 1000
assert.equal layerB.x, 900
assert.equal layerB.y, 900
layerB.superLayer = null
assert.equal layerB.canvasFrame.x, 900
assert.equal layerB.canvasFrame.y, 900
it "should calculate scale", ->
layerA = new Layer scale:0.9
layerB = new Layer scale:0.8, superLayer:layerA
layerB.screenScaleX().should.equal 0.9 * 0.8
layerB.screenScaleY().should.equal 0.9 * 0.8
it "should calculate scaled frame", ->
layerA = new Layer x:100, width:500, height:900, scale:0.5
layerA.scaledFrame().should.eql {"x":225,"y":225,"width":250,"height":450}
it "should calculate scaled screen frame", ->
layerA = new Layer x:100, width:500, height:900, scale:0.5
layerB = new Layer y:50, width:600, height:600, scale:0.8, superLayer:layerA
layerC = new Layer y:-60, width:800, height:700, scale:1.2, superLayer:layerB
layerA.screenScaledFrame().should.eql {"x":225,"y":225,"width":250,"height":450}
layerB.screenScaledFrame().should.eql {"x":255,"y":280,"width":240,"height":240}
layerC.screenScaledFrame().should.eql {"x":223,"y":228,"width":384,"height":336}
it "should accept point shortcut", ->
layer = new Layer point:10
layer.x.should.equal 10
layer.y.should.equal 10
it "should accept size shortcut", ->
layer = new Layer size:10
layer.width.should.equal 10
layer.height.should.equal 10
describe "Center", ->
it "should center", ->
layerA = new Layer width:200, height:200
layerB = new Layer width:100, height:100, superLayer:layerA
layerB.center()
assert.equal layerB.x, 50
assert.equal layerB.y, 50
it "should center with offset", ->
layerA = new Layer width:200, height:200
layerB = new Layer width:100, height:100, superLayer:layerA
layerB.centerX(50)
layerB.centerY(50)
assert.equal layerB.x, 100
assert.equal layerB.y, 100
it "should center return layer", ->
layerA = new Layer width:200, height:200
layerA.center().should.equal layerA
layerA.centerX().should.equal layerA
layerA.centerY().should.equal layerA
it "should center pixel align", ->
layerA = new Layer width:200, height:200
layerB = new Layer width:111, height:111, superLayer:layerA
layerB.center().pixelAlign()
assert.equal layerB.x, 44
assert.equal layerB.y, 44
it "should center with border", ->
layer = new Layer
width: 200
height: 200
layer.borderColor = "green"
layer.borderWidth = 30
layer.center()
layerB = new Layer
superLayer: layer
backgroundColor: "red"
layerB.center()
layerB.frame.should.eql {x:20, y:20, width:100, height:100}
describe "CSS", ->
it "classList should work", ->
layer = new Layer
layer.classList.add "test"
assert.equal layer.classList.contains("test"), true
assert.equal layer._element.classList.contains("test"), true
describe "DOM", ->
it "should destroy", ->
layer = new Layer
layer.destroy()
(layer in Framer.CurrentContext.getLayers()).should.be.false
assert.equal layer._element.parentNode, null
it "should set text", ->
layer = new Layer
layer.html = "Hello"
layer._element.childNodes[0].should.equal layer._elementHTML
layer._elementHTML.innerHTML.should.equal "Hello"
layer.ignoreEvents.should.equal true
it "should not effect children", ->
layer = new Layer
layer.html = "Hello"
Child = new Layer superLayer: layer
Child._element.offsetTop.should.equal 0
it "should set interactive html and allow pointer events", ->
tags = ["input", "select", "textarea", "option"]
html = ""
for tag in tags
html += "<#{tag}></#{tag}>"
layer = new Layer
layer.html = html
for tag in tags
element = layer.querySelectorAll(tag)[0]
style = window.getComputedStyle(element)
style["pointer-events"].should.equal "auto"
# style["-webkit-user-select"].should.equal "auto"
it "should work with querySelectorAll", ->
layer = new Layer
layer.html = "<input type='button' id='hello'>"
inputElements = layer.querySelectorAll("input")
inputElements.length.should.equal 1
inputElement = _.head(inputElements)
inputElement.getAttribute("id").should.equal "hello"
describe "Force 2D", ->
it "should switch to 2d rendering", ->
layer = new Layer
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
layer.force2d = true
layer.style.webkitTransform.should.equal "translate(0px, 0px) scale(1) skew(0deg, 0deg) rotate(0deg)"
describe "Matrices", ->
it "should have the correct matrix", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
layer.matrix.toString().should.eql "matrix(1.957079, 1.957079, -0.871348, 0.871348, 200.000000, 120.000000)"
it "should have the correct matrix when 2d is forced", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
force2d: true
layer.matrix.toString().should.eql "matrix(2.165466, 1.957079, -1.079734, 0.871348, 200.000000, 120.000000)"
it "should have the correct transform matrix", ->
layer = new Layer
scale: 20
rotation: 5
rotationY: 20
x: 200
y: 120
skew: 21
layer.transformMatrix.toString().should.eql "matrix3d(19.391455, 8.929946, -0.340719, 0.000000, 6.010074, 19.295128, 0.029809, 0.000000, 6.840403, 2.625785, 0.939693, 0.000000, -1020.076470, -1241.253701, 15.545482, 1.000000)"
it "should have the correct screen point", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
roundX = Math.round(layer.convertPointToScreen().x)
roundX.should.eql 184
it "should have the correct screen frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.screenFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 133
boundingBox.height.should.eql 144
it "should have the correct canvas frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.canvasFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 133
boundingBox.height.should.eql 144
describe "Copy", ->
it "copied Layer should hold set props", ->
X = 100
Y = 200
IMAGE = '../static/test.png'
BORDERRADIUS = 20
layer = new Layer
x:X
y:Y
image:IMAGE
layer.borderRadius = BORDERRADIUS
layer.x.should.eql X
layer.y.should.eql Y
layer.image.should.eql IMAGE
layer.borderRadius.should.eql BORDERRADIUS
copy = layer.copy()
copy.x.should.eql X
copy.y.should.eql Y
copy.image.should.eql IMAGE
copy.borderRadius.should.eql BORDERRADIUS
it "copied Layer should have defaults", ->
layer = new Layer
copy = layer.copy()
copy.width.should.equal 100
copy.height.should.equal 100
describe "Draggable", ->
it "should stop x and y animations on drag start", ->
layer = new Layer
layer.draggable.enabled = true
a1 = layer.animate properties: {x:100}
a2 = layer.animate properties: {y:100}
a3 = layer.animate properties: {blur:1}
a1.isAnimating.should.equal true
a2.isAnimating.should.equal true
a3.isAnimating.should.equal true
layer.draggable.touchStart(document.createEvent("MouseEvent"))
a1.isAnimating.should.equal false
a2.isAnimating.should.equal false
a3.isAnimating.should.equal true
|
[
{
"context": "name = \"Michelangelo\"\nmask = \"orange\"\nweapon = \"nunchuks\"\nturtle = {na",
"end": 20,
"score": 0.9996201992034912,
"start": 8,
"tag": "NAME",
"value": "Michelangelo"
}
] | documentation/examples/objects_shorthand.coffee | Trott/coffeescript | 8,728 | name = "Michelangelo"
mask = "orange"
weapon = "nunchuks"
turtle = {name, mask, weapon}
output = "#{turtle.name} wears an #{turtle.mask} mask. Watch out for his #{turtle.weapon}!"
| 210594 | name = "<NAME>"
mask = "orange"
weapon = "nunchuks"
turtle = {name, mask, weapon}
output = "#{turtle.name} wears an #{turtle.mask} mask. Watch out for his #{turtle.weapon}!"
| true | name = "PI:NAME:<NAME>END_PI"
mask = "orange"
weapon = "nunchuks"
turtle = {name, mask, weapon}
output = "#{turtle.name} wears an #{turtle.mask} mask. Watch out for his #{turtle.weapon}!"
|
[
{
"context": "# APP INFO ###\n\tname: 'Basic Gridfw app'\n\temail: 'contact@gridfw.com'\n\tauthor: 'Gridfw team'\n\t### APP STATUS ###\n\t# mo",
"end": 111,
"score": 0.9999287724494934,
"start": 93,
"tag": "EMAIL",
"value": "contact@gridfw.com"
},
{
"context": "app'\n\temail: 'contact@gridfw.com'\n\tauthor: 'Gridfw team'\n\t### APP STATUS ###\n\t# mode\n\tisProd: '<%= isProd",
"end": 134,
"score": 0.6823883652687073,
"start": 130,
"tag": "NAME",
"value": "team"
}
] | basic/assets/gridfw-config.coffee | gridfw/gridfw-tests | 0 | ###*
* Config file
###
module.exports=
### APP INFO ###
name: 'Basic Gridfw app'
email: 'contact@gridfw.com'
author: 'Gridfw team'
### APP STATUS ###
# mode
isProd: '<%= isProd %>'
### PLUGINS ###
plugins:
# # dev plugins
<% if(!isProd){ %>
devTools:
require: '../../../dev-tools'
errorHandling:
require: '../../../gridfw-errors'
<% } %>
# common plugins
i18n:
require: '../../../i18n'
locals: 'i18n/**/*.js' # local files
default: 'en' # default local
param: 'i18n' # param name as: ctx.i18n & ctx.locals.i18n
setLangParam: 'set-lang'# query param to use to change language: ie: ?set-lang=en
cache: on # optimize memory by using cache, load only used languages
# store lang inside user session: use
session: 'i18n' # param name inside session
# or:
# session:
# get: (ctx)-> ctx.user.local
# set: (ctx, value)-> ctx.user.local = value
# - to use a context related language; ie: language is determined by the url:
# - Options1: by query param: xxxx?lang=en
# ctxLocal: (ctx)-> ctx.query.lang
# - Options 2: inside URL: like: /fr/path/to/...
# ctxLocal: (ctx)->
# matches = ctx.path.match /^\/([a-z]*)(.*)/
# ctx.path = matches[2]
# return matches[1] | 115914 | ###*
* Config file
###
module.exports=
### APP INFO ###
name: 'Basic Gridfw app'
email: '<EMAIL>'
author: 'Gridfw <NAME>'
### APP STATUS ###
# mode
isProd: '<%= isProd %>'
### PLUGINS ###
plugins:
# # dev plugins
<% if(!isProd){ %>
devTools:
require: '../../../dev-tools'
errorHandling:
require: '../../../gridfw-errors'
<% } %>
# common plugins
i18n:
require: '../../../i18n'
locals: 'i18n/**/*.js' # local files
default: 'en' # default local
param: 'i18n' # param name as: ctx.i18n & ctx.locals.i18n
setLangParam: 'set-lang'# query param to use to change language: ie: ?set-lang=en
cache: on # optimize memory by using cache, load only used languages
# store lang inside user session: use
session: 'i18n' # param name inside session
# or:
# session:
# get: (ctx)-> ctx.user.local
# set: (ctx, value)-> ctx.user.local = value
# - to use a context related language; ie: language is determined by the url:
# - Options1: by query param: xxxx?lang=en
# ctxLocal: (ctx)-> ctx.query.lang
# - Options 2: inside URL: like: /fr/path/to/...
# ctxLocal: (ctx)->
# matches = ctx.path.match /^\/([a-z]*)(.*)/
# ctx.path = matches[2]
# return matches[1] | true | ###*
* Config file
###
module.exports=
### APP INFO ###
name: 'Basic Gridfw app'
email: 'PI:EMAIL:<EMAIL>END_PI'
author: 'Gridfw PI:NAME:<NAME>END_PI'
### APP STATUS ###
# mode
isProd: '<%= isProd %>'
### PLUGINS ###
plugins:
# # dev plugins
<% if(!isProd){ %>
devTools:
require: '../../../dev-tools'
errorHandling:
require: '../../../gridfw-errors'
<% } %>
# common plugins
i18n:
require: '../../../i18n'
locals: 'i18n/**/*.js' # local files
default: 'en' # default local
param: 'i18n' # param name as: ctx.i18n & ctx.locals.i18n
setLangParam: 'set-lang'# query param to use to change language: ie: ?set-lang=en
cache: on # optimize memory by using cache, load only used languages
# store lang inside user session: use
session: 'i18n' # param name inside session
# or:
# session:
# get: (ctx)-> ctx.user.local
# set: (ctx, value)-> ctx.user.local = value
# - to use a context related language; ie: language is determined by the url:
# - Options1: by query param: xxxx?lang=en
# ctxLocal: (ctx)-> ctx.query.lang
# - Options 2: inside URL: like: /fr/path/to/...
# ctxLocal: (ctx)->
# matches = ctx.path.match /^\/([a-z]*)(.*)/
# ctx.path = matches[2]
# return matches[1] |
[
{
"context": "s/sign_in\", user: { email: $scope.email, password: $scope.password })\n request.success (data) ->\n $scope.use",
"end": 718,
"score": 0.9600969552993774,
"start": 703,
"tag": "PASSWORD",
"value": "$scope.password"
}
] | app/assets/javascripts/angularjs/orders.js.coffee | richard-ma/19wu | 252 | @OrdersCtrl = ['$scope', '$http', '$window', ($scope, $http, $window) ->
$scope.disabled = $scope.event.started
$scope.user_form = 'register'
$scope.user_wants_invoice = true
$scope.errors = {}
$scope.use_login_form = ->
$scope.user_form = 'login'
$scope.use_register_form = ->
$scope.user_form = 'register'
$scope.signup = ->
request = $http.post("/users", user: { login: $scope.user_login, email: $scope.user_email, password: $scope.user_password })
request.success (data) ->
$scope.user_login_with data
request.error (data) ->
alert data['errors']
$scope.login = ->
request = $http.post("/users/sign_in", user: { email: $scope.email, password: $scope.password })
request.success (data) ->
$scope.user_login_with data
request.error (data) ->
alert data['error'] # http://git.io/C-1_Iw
$scope.create = ->
$scope.errors = {}
return if $scope.disabled
return if $scope.validate_quantity()
return if $scope.validate_user_session()
return if $scope.validate_form()
return if $scope.validate_invoice_info()
request = $http.post("/events/#{$scope.event.id}/orders", $scope.postData())
request.success (data) ->
$scope.id = data['id']
$scope.number = data['number']
$scope.status = data['status']
$scope.pay_url = data['link']
request.error (data) ->
alert data['errors']
# private
$scope.validate_quantity = ->
for ticket in $scope.tickets
return false if parseInt(ticket.quantity, 10) > 0
$scope.errors['tickets'] = true
true
$scope.validate_user_session = ->
$scope.errors['user_session'] = true unless ($scope.user? && $scope.user.id)
$scope.validate_form = ->
$scope.validate_user_info()
$scope.validate_invoice_info()
$scope.errors['user_info'] || $scope.errors['invoice_info']
$scope.validate_user_info = ->
$scope.errors['user_info'] = true unless $scope.user.name && $scope.user.phone
$scope.require_invoice = ->
$scope.provide_invoice() && $scope.user_wants_invoice
$scope.provide_invoice = ->
for ticket in $scope.tickets
return true if parseInt(ticket.quantity, 10) > 0 && ticket.require_invoice
false
$scope.validate_invoice_info = ->
if $scope.require_invoice()
unless $scope.invoice_title && $scope.province && $scope.city && $scope.district && $scope.address && $scope.shipping_name && $scope.shipping_phone
$scope.errors['invoice_info'] = true
$scope.postData = ->
items = []
for ticket in $scope.tickets
quantity = parseInt(ticket.quantity, 10)
items.push { ticket_id: ticket.id, quantity: quantity } if quantity > 0
shipping_address = if $scope.require_invoice()
invoice_title: $scope.invoice_title,
province: $scope.province,
city: $scope.city,
district: $scope.district,
address: $scope.address,
name: $scope.shipping_name,
phone: $scope.shipping_phone
else
null
order:
items_attributes: items,
shipping_address_attributes: shipping_address,
user_wants_invoice: $scope.user_wants_invoice
user:
phone: $scope.user.phone
profile_attributes:
name: $scope.user.name
$scope.user_login_with = (data) ->
$scope.update_csrf_token(data['token'])
$scope.user = data
$scope.create()
$scope.update_csrf_token = (token) ->
$('meta[name="csrf-token"]').attr('content', token)
$http.defaults.headers.common['X-CSRF-Token'] = token
]
| 19799 | @OrdersCtrl = ['$scope', '$http', '$window', ($scope, $http, $window) ->
$scope.disabled = $scope.event.started
$scope.user_form = 'register'
$scope.user_wants_invoice = true
$scope.errors = {}
$scope.use_login_form = ->
$scope.user_form = 'login'
$scope.use_register_form = ->
$scope.user_form = 'register'
$scope.signup = ->
request = $http.post("/users", user: { login: $scope.user_login, email: $scope.user_email, password: $scope.user_password })
request.success (data) ->
$scope.user_login_with data
request.error (data) ->
alert data['errors']
$scope.login = ->
request = $http.post("/users/sign_in", user: { email: $scope.email, password: <PASSWORD> })
request.success (data) ->
$scope.user_login_with data
request.error (data) ->
alert data['error'] # http://git.io/C-1_Iw
$scope.create = ->
$scope.errors = {}
return if $scope.disabled
return if $scope.validate_quantity()
return if $scope.validate_user_session()
return if $scope.validate_form()
return if $scope.validate_invoice_info()
request = $http.post("/events/#{$scope.event.id}/orders", $scope.postData())
request.success (data) ->
$scope.id = data['id']
$scope.number = data['number']
$scope.status = data['status']
$scope.pay_url = data['link']
request.error (data) ->
alert data['errors']
# private
$scope.validate_quantity = ->
for ticket in $scope.tickets
return false if parseInt(ticket.quantity, 10) > 0
$scope.errors['tickets'] = true
true
$scope.validate_user_session = ->
$scope.errors['user_session'] = true unless ($scope.user? && $scope.user.id)
$scope.validate_form = ->
$scope.validate_user_info()
$scope.validate_invoice_info()
$scope.errors['user_info'] || $scope.errors['invoice_info']
$scope.validate_user_info = ->
$scope.errors['user_info'] = true unless $scope.user.name && $scope.user.phone
$scope.require_invoice = ->
$scope.provide_invoice() && $scope.user_wants_invoice
$scope.provide_invoice = ->
for ticket in $scope.tickets
return true if parseInt(ticket.quantity, 10) > 0 && ticket.require_invoice
false
$scope.validate_invoice_info = ->
if $scope.require_invoice()
unless $scope.invoice_title && $scope.province && $scope.city && $scope.district && $scope.address && $scope.shipping_name && $scope.shipping_phone
$scope.errors['invoice_info'] = true
$scope.postData = ->
items = []
for ticket in $scope.tickets
quantity = parseInt(ticket.quantity, 10)
items.push { ticket_id: ticket.id, quantity: quantity } if quantity > 0
shipping_address = if $scope.require_invoice()
invoice_title: $scope.invoice_title,
province: $scope.province,
city: $scope.city,
district: $scope.district,
address: $scope.address,
name: $scope.shipping_name,
phone: $scope.shipping_phone
else
null
order:
items_attributes: items,
shipping_address_attributes: shipping_address,
user_wants_invoice: $scope.user_wants_invoice
user:
phone: $scope.user.phone
profile_attributes:
name: $scope.user.name
$scope.user_login_with = (data) ->
$scope.update_csrf_token(data['token'])
$scope.user = data
$scope.create()
$scope.update_csrf_token = (token) ->
$('meta[name="csrf-token"]').attr('content', token)
$http.defaults.headers.common['X-CSRF-Token'] = token
]
| true | @OrdersCtrl = ['$scope', '$http', '$window', ($scope, $http, $window) ->
$scope.disabled = $scope.event.started
$scope.user_form = 'register'
$scope.user_wants_invoice = true
$scope.errors = {}
$scope.use_login_form = ->
$scope.user_form = 'login'
$scope.use_register_form = ->
$scope.user_form = 'register'
$scope.signup = ->
request = $http.post("/users", user: { login: $scope.user_login, email: $scope.user_email, password: $scope.user_password })
request.success (data) ->
$scope.user_login_with data
request.error (data) ->
alert data['errors']
$scope.login = ->
request = $http.post("/users/sign_in", user: { email: $scope.email, password: PI:PASSWORD:<PASSWORD>END_PI })
request.success (data) ->
$scope.user_login_with data
request.error (data) ->
alert data['error'] # http://git.io/C-1_Iw
$scope.create = ->
$scope.errors = {}
return if $scope.disabled
return if $scope.validate_quantity()
return if $scope.validate_user_session()
return if $scope.validate_form()
return if $scope.validate_invoice_info()
request = $http.post("/events/#{$scope.event.id}/orders", $scope.postData())
request.success (data) ->
$scope.id = data['id']
$scope.number = data['number']
$scope.status = data['status']
$scope.pay_url = data['link']
request.error (data) ->
alert data['errors']
# private
$scope.validate_quantity = ->
for ticket in $scope.tickets
return false if parseInt(ticket.quantity, 10) > 0
$scope.errors['tickets'] = true
true
$scope.validate_user_session = ->
$scope.errors['user_session'] = true unless ($scope.user? && $scope.user.id)
$scope.validate_form = ->
$scope.validate_user_info()
$scope.validate_invoice_info()
$scope.errors['user_info'] || $scope.errors['invoice_info']
$scope.validate_user_info = ->
$scope.errors['user_info'] = true unless $scope.user.name && $scope.user.phone
$scope.require_invoice = ->
$scope.provide_invoice() && $scope.user_wants_invoice
$scope.provide_invoice = ->
for ticket in $scope.tickets
return true if parseInt(ticket.quantity, 10) > 0 && ticket.require_invoice
false
$scope.validate_invoice_info = ->
if $scope.require_invoice()
unless $scope.invoice_title && $scope.province && $scope.city && $scope.district && $scope.address && $scope.shipping_name && $scope.shipping_phone
$scope.errors['invoice_info'] = true
$scope.postData = ->
items = []
for ticket in $scope.tickets
quantity = parseInt(ticket.quantity, 10)
items.push { ticket_id: ticket.id, quantity: quantity } if quantity > 0
shipping_address = if $scope.require_invoice()
invoice_title: $scope.invoice_title,
province: $scope.province,
city: $scope.city,
district: $scope.district,
address: $scope.address,
name: $scope.shipping_name,
phone: $scope.shipping_phone
else
null
order:
items_attributes: items,
shipping_address_attributes: shipping_address,
user_wants_invoice: $scope.user_wants_invoice
user:
phone: $scope.user.phone
profile_attributes:
name: $scope.user.name
$scope.user_login_with = (data) ->
$scope.update_csrf_token(data['token'])
$scope.user = data
$scope.create()
$scope.update_csrf_token = (token) ->
$('meta[name="csrf-token"]').attr('content', token)
$http.defaults.headers.common['X-CSRF-Token'] = token
]
|
[
{
"context": "an set strings', ->\n strings = { 'Hello': 'Hallo' }\n assert.deepEqual(catalog.strings, {})\n",
"end": 239,
"score": 0.7116603255271912,
"start": 234,
"tag": "NAME",
"value": "Hallo"
},
{
"context": "trieve strings', ->\n strings = { 'Hello': 'Hallo' }\n catalog.setStrings('nl', strings)\n ",
"end": 464,
"score": 0.6964949369430542,
"start": 459,
"tag": "NAME",
"value": "Hallo"
},
{
"context": "nknown strings', ->\n strings = { 'Hello': 'Hallo' }\n catalog.setStrings('nl', strings)\n ",
"end": 699,
"score": 0.665139377117157,
"start": 694,
"tag": "NAME",
"value": "Hallo"
}
] | test/unit/catalog.coffee | pungme/angular-gettext | 1 | assert = chai.assert
describe 'Catalog', ->
catalog = null
beforeEach module('gettext')
beforeEach inject (gettextCatalog) ->
catalog = gettextCatalog
it 'Can set strings', ->
strings = { 'Hello': 'Hallo' }
assert.deepEqual(catalog.strings, {})
catalog.setStrings('nl', strings)
assert.deepEqual(catalog.strings.nl.Hello[0], 'Hallo')
it 'Can retrieve strings', ->
strings = { 'Hello': 'Hallo' }
catalog.setStrings('nl', strings)
catalog.currentLanguage = 'nl'
assert.equal(catalog.getString('Hello'), 'Hallo')
it 'Should return original for unknown strings', ->
strings = { 'Hello': 'Hallo' }
catalog.setStrings('nl', strings)
catalog.currentLanguage = 'nl'
assert.equal(catalog.getString('Bye'), 'Bye')
it 'Should return original for unknown languages', ->
catalog.currentLanguage = 'fr'
assert.equal(catalog.getString('Hello'), 'Hello')
it 'Should add prefix for untranslated strings when in debug', ->
catalog.debug = true
catalog.currentLanguage = 'fr'
assert.equal(catalog.getString('Hello'), '[MISSING]: Hello')
it 'Should not add prefix for untranslated strings in English', ->
catalog.debug = true
catalog.currentLanguage = 'en'
assert.equal(catalog.getString('Hello'), 'Hello')
it 'Should return singular for unknown singular strings', ->
assert.equal(catalog.getPlural(1, 'Bird', 'Birds'), 'Bird')
it 'Should return plural for unknown plural strings', ->
assert.equal(catalog.getPlural(2, 'Bird', 'Birds'), 'Birds')
it 'Should return singular for singular strings', ->
catalog.currentLanguage = 'nl'
catalog.setStrings('nl', {
'Bird': [ 'Vogel', 'Vogels' ]
})
assert.equal(catalog.getPlural(1, 'Bird', 'Birds'), 'Vogel')
it 'Should return plural for plural strings', ->
catalog.currentLanguage = 'nl'
catalog.setStrings('nl', {
'Bird': [ 'Vogel', 'Vogels' ]
})
assert.equal(catalog.getPlural(2, 'Bird', 'Birds'), 'Vogels')
it 'Should add prefix for untranslated plural strings when in debug (single)', ->
catalog.debug = true
catalog.currentLanguage = 'nl'
assert.equal(catalog.getPlural(1, 'Bird', 'Birds'), '[MISSING]: Bird')
it 'Should add prefix for untranslated plural strings when in debug', ->
catalog.debug = true
catalog.currentLanguage = 'nl'
assert.equal(catalog.getPlural(2, 'Bird', 'Birds'), '[MISSING]: Birds')
| 49673 | assert = chai.assert
describe 'Catalog', ->
catalog = null
beforeEach module('gettext')
beforeEach inject (gettextCatalog) ->
catalog = gettextCatalog
it 'Can set strings', ->
strings = { 'Hello': '<NAME>' }
assert.deepEqual(catalog.strings, {})
catalog.setStrings('nl', strings)
assert.deepEqual(catalog.strings.nl.Hello[0], 'Hallo')
it 'Can retrieve strings', ->
strings = { 'Hello': '<NAME>' }
catalog.setStrings('nl', strings)
catalog.currentLanguage = 'nl'
assert.equal(catalog.getString('Hello'), 'Hallo')
it 'Should return original for unknown strings', ->
strings = { 'Hello': '<NAME>' }
catalog.setStrings('nl', strings)
catalog.currentLanguage = 'nl'
assert.equal(catalog.getString('Bye'), 'Bye')
it 'Should return original for unknown languages', ->
catalog.currentLanguage = 'fr'
assert.equal(catalog.getString('Hello'), 'Hello')
it 'Should add prefix for untranslated strings when in debug', ->
catalog.debug = true
catalog.currentLanguage = 'fr'
assert.equal(catalog.getString('Hello'), '[MISSING]: Hello')
it 'Should not add prefix for untranslated strings in English', ->
catalog.debug = true
catalog.currentLanguage = 'en'
assert.equal(catalog.getString('Hello'), 'Hello')
it 'Should return singular for unknown singular strings', ->
assert.equal(catalog.getPlural(1, 'Bird', 'Birds'), 'Bird')
it 'Should return plural for unknown plural strings', ->
assert.equal(catalog.getPlural(2, 'Bird', 'Birds'), 'Birds')
it 'Should return singular for singular strings', ->
catalog.currentLanguage = 'nl'
catalog.setStrings('nl', {
'Bird': [ 'Vogel', 'Vogels' ]
})
assert.equal(catalog.getPlural(1, 'Bird', 'Birds'), 'Vogel')
it 'Should return plural for plural strings', ->
catalog.currentLanguage = 'nl'
catalog.setStrings('nl', {
'Bird': [ 'Vogel', 'Vogels' ]
})
assert.equal(catalog.getPlural(2, 'Bird', 'Birds'), 'Vogels')
it 'Should add prefix for untranslated plural strings when in debug (single)', ->
catalog.debug = true
catalog.currentLanguage = 'nl'
assert.equal(catalog.getPlural(1, 'Bird', 'Birds'), '[MISSING]: Bird')
it 'Should add prefix for untranslated plural strings when in debug', ->
catalog.debug = true
catalog.currentLanguage = 'nl'
assert.equal(catalog.getPlural(2, 'Bird', 'Birds'), '[MISSING]: Birds')
| true | assert = chai.assert
describe 'Catalog', ->
catalog = null
beforeEach module('gettext')
beforeEach inject (gettextCatalog) ->
catalog = gettextCatalog
it 'Can set strings', ->
strings = { 'Hello': 'PI:NAME:<NAME>END_PI' }
assert.deepEqual(catalog.strings, {})
catalog.setStrings('nl', strings)
assert.deepEqual(catalog.strings.nl.Hello[0], 'Hallo')
it 'Can retrieve strings', ->
strings = { 'Hello': 'PI:NAME:<NAME>END_PI' }
catalog.setStrings('nl', strings)
catalog.currentLanguage = 'nl'
assert.equal(catalog.getString('Hello'), 'Hallo')
it 'Should return original for unknown strings', ->
strings = { 'Hello': 'PI:NAME:<NAME>END_PI' }
catalog.setStrings('nl', strings)
catalog.currentLanguage = 'nl'
assert.equal(catalog.getString('Bye'), 'Bye')
it 'Should return original for unknown languages', ->
catalog.currentLanguage = 'fr'
assert.equal(catalog.getString('Hello'), 'Hello')
it 'Should add prefix for untranslated strings when in debug', ->
catalog.debug = true
catalog.currentLanguage = 'fr'
assert.equal(catalog.getString('Hello'), '[MISSING]: Hello')
it 'Should not add prefix for untranslated strings in English', ->
catalog.debug = true
catalog.currentLanguage = 'en'
assert.equal(catalog.getString('Hello'), 'Hello')
it 'Should return singular for unknown singular strings', ->
assert.equal(catalog.getPlural(1, 'Bird', 'Birds'), 'Bird')
it 'Should return plural for unknown plural strings', ->
assert.equal(catalog.getPlural(2, 'Bird', 'Birds'), 'Birds')
it 'Should return singular for singular strings', ->
catalog.currentLanguage = 'nl'
catalog.setStrings('nl', {
'Bird': [ 'Vogel', 'Vogels' ]
})
assert.equal(catalog.getPlural(1, 'Bird', 'Birds'), 'Vogel')
it 'Should return plural for plural strings', ->
catalog.currentLanguage = 'nl'
catalog.setStrings('nl', {
'Bird': [ 'Vogel', 'Vogels' ]
})
assert.equal(catalog.getPlural(2, 'Bird', 'Birds'), 'Vogels')
it 'Should add prefix for untranslated plural strings when in debug (single)', ->
catalog.debug = true
catalog.currentLanguage = 'nl'
assert.equal(catalog.getPlural(1, 'Bird', 'Birds'), '[MISSING]: Bird')
it 'Should add prefix for untranslated plural strings when in debug', ->
catalog.debug = true
catalog.currentLanguage = 'nl'
assert.equal(catalog.getPlural(2, 'Bird', 'Birds'), '[MISSING]: Birds')
|
[
{
"context": "id', (done) ->\n product_doc =\n name: \"Cake\"\n sku: \"NOTalid090\"\n unit_price: 12",
"end": 2617,
"score": 0.7648636102676392,
"start": 2613,
"tag": "NAME",
"value": "Cake"
},
{
"context": "id', (done) ->\n product_doc =\n name: \"Cake\"\n sku: \"NOTAlid090\"\n unit_price: 12",
"end": 3120,
"score": 0.6847054958343506,
"start": 3116,
"tag": "NAME",
"value": "Cake"
},
{
"context": "email) ->\n doc =\n email: email\n password: '12345678'\n profile:\n first_name: faker.name.firstN",
"end": 5418,
"score": 0.9993194341659546,
"start": 5410,
"tag": "PASSWORD",
"value": "12345678"
},
{
"context": "one, email) ->\n Meteor.loginWithPassword email, '12345678', (err) ->\n done()\n\nlogout = (done) ->\n Meteo",
"end": 5632,
"score": 0.9968267679214478,
"start": 5624,
"tag": "PASSWORD",
"value": "12345678"
}
] | app_tests/client/products.app-tests.coffee | Phaze1D/SA-Units | 0 | faker = require 'faker'
{ chai, assert, expect } = require 'meteor/practicalmeteor:chai'
{ Meteor } = require 'meteor/meteor'
{ Accounts } = require 'meteor/accounts-base'
{ resetDatabase } = require 'meteor/xolvio:cleaner'
{ _ } = require 'meteor/underscore'
OrganizationModule = require '../../imports/api/collections/organizations/organizations.coffee'
ProductModule = require '../../imports/api/collections/products/products.coffee'
{
insert
update
} = require '../../imports/api/collections/products/methods.coffee'
{ inviteUser } = require '../../imports/api/collections/users/methods.coffee'
OMethods = require '../../imports/api/collections/organizations/methods.coffee'
IMethods = require '../../imports/api/collections/ingredients/methods.coffee'
organizationID = ""
ingredientIDS = []
xdescribe 'Product Full App Test Client', () ->
before ->
resetDatabase(null);
describe 'Product Insert', () ->
it 'create user', (done) ->
createUser done, faker.internet.email()
it 'SKU Validation Invalid 1', (done) ->
product_doc =
name: "Cake"
sku: "NOT Valid"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id = "NONONONON"
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'regExError')
done()
it 'SKU Validation Invalid 2', (done) ->
product_doc =
name: "Cake"
sku: "NOTValid-- 9-- 9"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id = "NONONONcON"
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'regExError')
done()
it 'Create Organ', (done) ->
createOrgan(done)
it 'Subscribe to ', (done) ->
callbacks =
onStop: (err) ->
onReady: () ->
done()
subHandler = Meteor.subscribe("products", organizationID, callbacks)
it "create ingredient", (done) ->
createIngredient(done)
it 'SKU Validation Valid', (done) ->
product_doc =
name: "Cake"
sku: "NOTalid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
ingredient_id: ingredientIDS[0]
amount: 123.123
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.not.exist
done()
it 'SKU unique name invalid', (done) ->
product_doc =
name: "Cake"
sku: "NOTalid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
ingredient_id: ingredientIDS[0]
amount: 123.123
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error','skuNotUnique')
done()
it 'SKU unique name valid', (done) ->
product_doc =
name: "Cake"
sku: "NOTAlid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
ingredient_id: ingredientIDS[0]
amount: 123.123
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.not.exist
done()
it 'Search Text', () ->
expect(ProductModule.Products.find({ sku: { $regex: /^NOTA/i } }).count()).to.equal(2)
expect(ProductModule.Products.find({ sku: { $regex: /^NOTAadsf/i } }).count()).to.equal(0)
it 'Checking ingredient autoValue', (done) ->
inmame = faker.name.firstName()
mu = faker.company.companyName()
product_doc =
name: "Cake"
sku: "NOTAlid-90-()"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
{ingredient_id: ingredientIDS[0]
amount: 123.123},
{ingredient_id: ingredientIDS[0]
amount: 123.123}
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'duplicateIngredients')
done()
describe 'Product Update', () ->
it 'SKU Validation', (done) ->
product_doc =
name: "Cake"
sku: "NOT Valid"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id = organizationID
product_id = ProductModule.Products.findOne()._id
update.call {organization_id, product_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'regExError')
done()
it 'SKU unique name failed', (done) ->
product_doc =
name: "Cake"
sku: "NOTAlid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id: organizationID
organization_id = organizationID
product_id = ProductModule.Products.findOne()._id
update.call {organization_id, product_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'skuNotUnique')
done()
createUser = (done, email) ->
doc =
email: email
password: '12345678'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
done()
login = (done, email) ->
Meteor.loginWithPassword email, '12345678', (err) ->
done()
logout = (done) ->
Meteor.logout( (err) ->
done()
)
createIngredient = (done) ->
ingredient_doc =
name: faker.name.firstName()
measurement_unit: 'kg'
organization_id: organizationID
IMethods.insert.call {ingredient_doc}, (err, res) ->
throw err if err?
ingredientIDS.push res
done()
createOrgan = (done) ->
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
OMethods.insert.call organ_doc, (err, res) ->
organizationID = res
expect(err).to.not.exist
done()
| 108962 | faker = require 'faker'
{ chai, assert, expect } = require 'meteor/practicalmeteor:chai'
{ Meteor } = require 'meteor/meteor'
{ Accounts } = require 'meteor/accounts-base'
{ resetDatabase } = require 'meteor/xolvio:cleaner'
{ _ } = require 'meteor/underscore'
OrganizationModule = require '../../imports/api/collections/organizations/organizations.coffee'
ProductModule = require '../../imports/api/collections/products/products.coffee'
{
insert
update
} = require '../../imports/api/collections/products/methods.coffee'
{ inviteUser } = require '../../imports/api/collections/users/methods.coffee'
OMethods = require '../../imports/api/collections/organizations/methods.coffee'
IMethods = require '../../imports/api/collections/ingredients/methods.coffee'
organizationID = ""
ingredientIDS = []
xdescribe 'Product Full App Test Client', () ->
before ->
resetDatabase(null);
describe 'Product Insert', () ->
it 'create user', (done) ->
createUser done, faker.internet.email()
it 'SKU Validation Invalid 1', (done) ->
product_doc =
name: "Cake"
sku: "NOT Valid"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id = "NONONONON"
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'regExError')
done()
it 'SKU Validation Invalid 2', (done) ->
product_doc =
name: "Cake"
sku: "NOTValid-- 9-- 9"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id = "NONONONcON"
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'regExError')
done()
it 'Create Organ', (done) ->
createOrgan(done)
it 'Subscribe to ', (done) ->
callbacks =
onStop: (err) ->
onReady: () ->
done()
subHandler = Meteor.subscribe("products", organizationID, callbacks)
it "create ingredient", (done) ->
createIngredient(done)
it 'SKU Validation Valid', (done) ->
product_doc =
name: "Cake"
sku: "NOTalid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
ingredient_id: ingredientIDS[0]
amount: 123.123
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.not.exist
done()
it 'SKU unique name invalid', (done) ->
product_doc =
name: "<NAME>"
sku: "NOTalid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
ingredient_id: ingredientIDS[0]
amount: 123.123
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error','skuNotUnique')
done()
it 'SKU unique name valid', (done) ->
product_doc =
name: "<NAME>"
sku: "NOTAlid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
ingredient_id: ingredientIDS[0]
amount: 123.123
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.not.exist
done()
it 'Search Text', () ->
expect(ProductModule.Products.find({ sku: { $regex: /^NOTA/i } }).count()).to.equal(2)
expect(ProductModule.Products.find({ sku: { $regex: /^NOTAadsf/i } }).count()).to.equal(0)
it 'Checking ingredient autoValue', (done) ->
inmame = faker.name.firstName()
mu = faker.company.companyName()
product_doc =
name: "Cake"
sku: "NOTAlid-90-()"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
{ingredient_id: ingredientIDS[0]
amount: 123.123},
{ingredient_id: ingredientIDS[0]
amount: 123.123}
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'duplicateIngredients')
done()
describe 'Product Update', () ->
it 'SKU Validation', (done) ->
product_doc =
name: "Cake"
sku: "NOT Valid"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id = organizationID
product_id = ProductModule.Products.findOne()._id
update.call {organization_id, product_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'regExError')
done()
it 'SKU unique name failed', (done) ->
product_doc =
name: "Cake"
sku: "NOTAlid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id: organizationID
organization_id = organizationID
product_id = ProductModule.Products.findOne()._id
update.call {organization_id, product_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'skuNotUnique')
done()
createUser = (done, email) ->
doc =
email: email
password: '<PASSWORD>'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
done()
login = (done, email) ->
Meteor.loginWithPassword email, '<PASSWORD>', (err) ->
done()
logout = (done) ->
Meteor.logout( (err) ->
done()
)
createIngredient = (done) ->
ingredient_doc =
name: faker.name.firstName()
measurement_unit: 'kg'
organization_id: organizationID
IMethods.insert.call {ingredient_doc}, (err, res) ->
throw err if err?
ingredientIDS.push res
done()
createOrgan = (done) ->
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
OMethods.insert.call organ_doc, (err, res) ->
organizationID = res
expect(err).to.not.exist
done()
| true | faker = require 'faker'
{ chai, assert, expect } = require 'meteor/practicalmeteor:chai'
{ Meteor } = require 'meteor/meteor'
{ Accounts } = require 'meteor/accounts-base'
{ resetDatabase } = require 'meteor/xolvio:cleaner'
{ _ } = require 'meteor/underscore'
OrganizationModule = require '../../imports/api/collections/organizations/organizations.coffee'
ProductModule = require '../../imports/api/collections/products/products.coffee'
{
insert
update
} = require '../../imports/api/collections/products/methods.coffee'
{ inviteUser } = require '../../imports/api/collections/users/methods.coffee'
OMethods = require '../../imports/api/collections/organizations/methods.coffee'
IMethods = require '../../imports/api/collections/ingredients/methods.coffee'
organizationID = ""
ingredientIDS = []
xdescribe 'Product Full App Test Client', () ->
before ->
resetDatabase(null);
describe 'Product Insert', () ->
it 'create user', (done) ->
createUser done, faker.internet.email()
it 'SKU Validation Invalid 1', (done) ->
product_doc =
name: "Cake"
sku: "NOT Valid"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id = "NONONONON"
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'regExError')
done()
it 'SKU Validation Invalid 2', (done) ->
product_doc =
name: "Cake"
sku: "NOTValid-- 9-- 9"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id = "NONONONcON"
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'regExError')
done()
it 'Create Organ', (done) ->
createOrgan(done)
it 'Subscribe to ', (done) ->
callbacks =
onStop: (err) ->
onReady: () ->
done()
subHandler = Meteor.subscribe("products", organizationID, callbacks)
it "create ingredient", (done) ->
createIngredient(done)
it 'SKU Validation Valid', (done) ->
product_doc =
name: "Cake"
sku: "NOTalid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
ingredient_id: ingredientIDS[0]
amount: 123.123
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.not.exist
done()
it 'SKU unique name invalid', (done) ->
product_doc =
name: "PI:NAME:<NAME>END_PI"
sku: "NOTalid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
ingredient_id: ingredientIDS[0]
amount: 123.123
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error','skuNotUnique')
done()
it 'SKU unique name valid', (done) ->
product_doc =
name: "PI:NAME:<NAME>END_PI"
sku: "NOTAlid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
ingredient_id: ingredientIDS[0]
amount: 123.123
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.not.exist
done()
it 'Search Text', () ->
expect(ProductModule.Products.find({ sku: { $regex: /^NOTA/i } }).count()).to.equal(2)
expect(ProductModule.Products.find({ sku: { $regex: /^NOTAadsf/i } }).count()).to.equal(0)
it 'Checking ingredient autoValue', (done) ->
inmame = faker.name.firstName()
mu = faker.company.companyName()
product_doc =
name: "Cake"
sku: "NOTAlid-90-()"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
ingredients: [
{ingredient_id: ingredientIDS[0]
amount: 123.123},
{ingredient_id: ingredientIDS[0]
amount: 123.123}
]
organization_id: organizationID
organization_id = organizationID
insert.call {organization_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'duplicateIngredients')
done()
describe 'Product Update', () ->
it 'SKU Validation', (done) ->
product_doc =
name: "Cake"
sku: "NOT Valid"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id = organizationID
product_id = ProductModule.Products.findOne()._id
update.call {organization_id, product_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'regExError')
done()
it 'SKU unique name failed', (done) ->
product_doc =
name: "Cake"
sku: "NOTAlid090"
unit_price: 12.21
currency: "MXN"
tax_rate: 10
organization_id: organizationID
organization_id = organizationID
product_id = ProductModule.Products.findOne()._id
update.call {organization_id, product_id, product_doc}, (err, res) ->
expect(err).to.have.property('error', 'skuNotUnique')
done()
createUser = (done, email) ->
doc =
email: email
password: 'PI:PASSWORD:<PASSWORD>END_PI'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
done()
login = (done, email) ->
Meteor.loginWithPassword email, 'PI:PASSWORD:<PASSWORD>END_PI', (err) ->
done()
logout = (done) ->
Meteor.logout( (err) ->
done()
)
createIngredient = (done) ->
ingredient_doc =
name: faker.name.firstName()
measurement_unit: 'kg'
organization_id: organizationID
IMethods.insert.call {ingredient_doc}, (err, res) ->
throw err if err?
ingredientIDS.push res
done()
createOrgan = (done) ->
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
OMethods.insert.call organ_doc, (err, res) ->
organizationID = res
expect(err).to.not.exist
done()
|
[
{
"context": "> f is 'markup/home']\n args: [ ['Michael', 'Angelo' ] ]\n ]\n ]\n\n dev:\n",
"end": 1497,
"score": 0.999852180480957,
"start": 1490,
"tag": "NAME",
"value": "Michael"
},
{
"context": "kup/home']\n args: [ ['Michael', 'Angelo' ] ]\n ]\n ]\n\n dev:\n # ",
"end": 1507,
"score": 0.9997057318687439,
"start": 1501,
"tag": "NAME",
"value": "Angelo"
}
] | Gruntfile.coffee | anodynos/urequire-example-testbed | 0 | module.exports = (grunt) ->
gruntConfig =
urequire:
_all:
dependencies:
paths: bower: true
imports: lodash: ['_']
# 'when/callbacks': 'whenCallbacks'
clean: true
template: banner: true
debugLevel: 0
#verbose:true
_defaults: #for library only
name: 'urequire-example'
main: "my-main"
path: "source/code"
filez: [/./, '!uRequireConfig.coffee']
resources: [
'babeljs'
'inject-version'
['less', {$srcMain: 'style/myMainStyle.less', compress: true}]
['teacup-js', tags: 'html, doctype, body, div, ul, li']
]
dependencies:
node: [
'nodeOnly/*'
'fileRelative/missing/dep'
]
# add to those already delcared in module it self
rootExports: 'my-main': 'myMain'
#locals: 'when' : 'bower_components/when' # auto discovers it with wrong bower's path
rootExports:
runtimes: ['AMD', 'node', 'script'] # renamed to `rootExports.runtimes`
UMD:
template: 'UMDplain'
dstPath: "build/UMD"
resources: [
['teacup-js2html', # works only with nodejs/UMD templates
# deleteJs: true,
args: #['World!']
'markup/**/home': ['World!']
allButHome:
isFileIn: ['**/*', '!', (f)-> f is 'markup/home']
args: [ ['Michael', 'Angelo' ] ]
]
]
dev:
# dependencies: locals: 'when': [[null], 'bower_components/when/when'] # auto discovers it (with wrong bower's path)
template:
name: 'combined'
moduleName: 'urequire-example-testbed'
dstPath: "build/minified/urequire-example-testbed-dev.js"
min:
derive: ['dev', '_defaults']
dstPath: "build/minified/urequire-example-testbed-min.js"
optimize: uglify2: output:
beautify: true
compress: false
mangle: false
rjs: preserveLicenseComments: false
debugLevel: 0
#rootExports: noConflict: false # makes min fail cause it overrides module's `noConflict` setting
spec:
name: 'specs-for-urequire-example' # can be anything
derive: []
path: "source/spec"
copy: [/./]
dstPath: "build/spec"
clean: true
globalWindow: ['urequire-spec']
dependencies:
imports:
chai: 'chai'
lodash: ['_']
uberscore: '_B'
'urequire-example-testbed': ['uEx']
'specHelpers': 'spH'
resources: [
[ '+inject-_B.logger', ['**/*.js'], (m)-> m.beforeBody = "var l = new _B.Logger('#{m.dstFilename}');"]
['import-keys',
'specHelpers': [ 'tru', ['equal', 'eq'], 'fals' ]
'lodash': [ 'isFunction' ] # just for test
'chai': ['expect']
]
]
specDev:
derive: ['spec']
dstPath: "build/spec_combined/index-combined.js"
template: name: 'combined'
specRun:
derive:['spec']
afterBuild: require('urequire-ab-specrunner').options
injectCode: testNoConflict = """
// test `noConflict()`: create two globals that 'll be 'hijacked' by rootExports
window.urequireExample = 'Old global `urequireExample`';
window.uEx = 'Old global `uEx`';
"""
specDevRun:
derive:['specDev', 'specRun']
specWatch:
derive: ['spec']
watch: 1444
afterBuild: require('urequire-ab-specrunner').options
injectCode: testNoConflict
mochaOptions: '-R dot'
specDevWatch:
derive: ['specDev', 'specWatch']
_ = require 'lodash'
splitTasks = (tasks)-> if _.isArray tasks then tasks else _.filter tasks.split /\s/
grunt.registerTask shortCut, "urequire:#{shortCut}" for shortCut of gruntConfig.urequire
grunt.registerTask shortCut, splitTasks tasks for shortCut, tasks of {
default: "UMD specRun min specDevRun"
develop: "dev specDevWatch"
all: "UMD specRun UMD specDevRun dev specDevRun min specRun min specDevRun"
}
grunt.loadNpmTasks task for task of grunt.file.readJSON('package.json').devDependencies when task.lastIndexOf('grunt-', 0) is 0
grunt.initConfig gruntConfig
| 197629 | module.exports = (grunt) ->
gruntConfig =
urequire:
_all:
dependencies:
paths: bower: true
imports: lodash: ['_']
# 'when/callbacks': 'whenCallbacks'
clean: true
template: banner: true
debugLevel: 0
#verbose:true
_defaults: #for library only
name: 'urequire-example'
main: "my-main"
path: "source/code"
filez: [/./, '!uRequireConfig.coffee']
resources: [
'babeljs'
'inject-version'
['less', {$srcMain: 'style/myMainStyle.less', compress: true}]
['teacup-js', tags: 'html, doctype, body, div, ul, li']
]
dependencies:
node: [
'nodeOnly/*'
'fileRelative/missing/dep'
]
# add to those already delcared in module it self
rootExports: 'my-main': 'myMain'
#locals: 'when' : 'bower_components/when' # auto discovers it with wrong bower's path
rootExports:
runtimes: ['AMD', 'node', 'script'] # renamed to `rootExports.runtimes`
UMD:
template: 'UMDplain'
dstPath: "build/UMD"
resources: [
['teacup-js2html', # works only with nodejs/UMD templates
# deleteJs: true,
args: #['World!']
'markup/**/home': ['World!']
allButHome:
isFileIn: ['**/*', '!', (f)-> f is 'markup/home']
args: [ ['<NAME>', '<NAME>' ] ]
]
]
dev:
# dependencies: locals: 'when': [[null], 'bower_components/when/when'] # auto discovers it (with wrong bower's path)
template:
name: 'combined'
moduleName: 'urequire-example-testbed'
dstPath: "build/minified/urequire-example-testbed-dev.js"
min:
derive: ['dev', '_defaults']
dstPath: "build/minified/urequire-example-testbed-min.js"
optimize: uglify2: output:
beautify: true
compress: false
mangle: false
rjs: preserveLicenseComments: false
debugLevel: 0
#rootExports: noConflict: false # makes min fail cause it overrides module's `noConflict` setting
spec:
name: 'specs-for-urequire-example' # can be anything
derive: []
path: "source/spec"
copy: [/./]
dstPath: "build/spec"
clean: true
globalWindow: ['urequire-spec']
dependencies:
imports:
chai: 'chai'
lodash: ['_']
uberscore: '_B'
'urequire-example-testbed': ['uEx']
'specHelpers': 'spH'
resources: [
[ '+inject-_B.logger', ['**/*.js'], (m)-> m.beforeBody = "var l = new _B.Logger('#{m.dstFilename}');"]
['import-keys',
'specHelpers': [ 'tru', ['equal', 'eq'], 'fals' ]
'lodash': [ 'isFunction' ] # just for test
'chai': ['expect']
]
]
specDev:
derive: ['spec']
dstPath: "build/spec_combined/index-combined.js"
template: name: 'combined'
specRun:
derive:['spec']
afterBuild: require('urequire-ab-specrunner').options
injectCode: testNoConflict = """
// test `noConflict()`: create two globals that 'll be 'hijacked' by rootExports
window.urequireExample = 'Old global `urequireExample`';
window.uEx = 'Old global `uEx`';
"""
specDevRun:
derive:['specDev', 'specRun']
specWatch:
derive: ['spec']
watch: 1444
afterBuild: require('urequire-ab-specrunner').options
injectCode: testNoConflict
mochaOptions: '-R dot'
specDevWatch:
derive: ['specDev', 'specWatch']
_ = require 'lodash'
splitTasks = (tasks)-> if _.isArray tasks then tasks else _.filter tasks.split /\s/
grunt.registerTask shortCut, "urequire:#{shortCut}" for shortCut of gruntConfig.urequire
grunt.registerTask shortCut, splitTasks tasks for shortCut, tasks of {
default: "UMD specRun min specDevRun"
develop: "dev specDevWatch"
all: "UMD specRun UMD specDevRun dev specDevRun min specRun min specDevRun"
}
grunt.loadNpmTasks task for task of grunt.file.readJSON('package.json').devDependencies when task.lastIndexOf('grunt-', 0) is 0
grunt.initConfig gruntConfig
| true | module.exports = (grunt) ->
gruntConfig =
urequire:
_all:
dependencies:
paths: bower: true
imports: lodash: ['_']
# 'when/callbacks': 'whenCallbacks'
clean: true
template: banner: true
debugLevel: 0
#verbose:true
_defaults: #for library only
name: 'urequire-example'
main: "my-main"
path: "source/code"
filez: [/./, '!uRequireConfig.coffee']
resources: [
'babeljs'
'inject-version'
['less', {$srcMain: 'style/myMainStyle.less', compress: true}]
['teacup-js', tags: 'html, doctype, body, div, ul, li']
]
dependencies:
node: [
'nodeOnly/*'
'fileRelative/missing/dep'
]
# add to those already delcared in module it self
rootExports: 'my-main': 'myMain'
#locals: 'when' : 'bower_components/when' # auto discovers it with wrong bower's path
rootExports:
runtimes: ['AMD', 'node', 'script'] # renamed to `rootExports.runtimes`
UMD:
template: 'UMDplain'
dstPath: "build/UMD"
resources: [
['teacup-js2html', # works only with nodejs/UMD templates
# deleteJs: true,
args: #['World!']
'markup/**/home': ['World!']
allButHome:
isFileIn: ['**/*', '!', (f)-> f is 'markup/home']
args: [ ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI' ] ]
]
]
dev:
# dependencies: locals: 'when': [[null], 'bower_components/when/when'] # auto discovers it (with wrong bower's path)
template:
name: 'combined'
moduleName: 'urequire-example-testbed'
dstPath: "build/minified/urequire-example-testbed-dev.js"
min:
derive: ['dev', '_defaults']
dstPath: "build/minified/urequire-example-testbed-min.js"
optimize: uglify2: output:
beautify: true
compress: false
mangle: false
rjs: preserveLicenseComments: false
debugLevel: 0
#rootExports: noConflict: false # makes min fail cause it overrides module's `noConflict` setting
spec:
name: 'specs-for-urequire-example' # can be anything
derive: []
path: "source/spec"
copy: [/./]
dstPath: "build/spec"
clean: true
globalWindow: ['urequire-spec']
dependencies:
imports:
chai: 'chai'
lodash: ['_']
uberscore: '_B'
'urequire-example-testbed': ['uEx']
'specHelpers': 'spH'
resources: [
[ '+inject-_B.logger', ['**/*.js'], (m)-> m.beforeBody = "var l = new _B.Logger('#{m.dstFilename}');"]
['import-keys',
'specHelpers': [ 'tru', ['equal', 'eq'], 'fals' ]
'lodash': [ 'isFunction' ] # just for test
'chai': ['expect']
]
]
specDev:
derive: ['spec']
dstPath: "build/spec_combined/index-combined.js"
template: name: 'combined'
specRun:
derive:['spec']
afterBuild: require('urequire-ab-specrunner').options
injectCode: testNoConflict = """
// test `noConflict()`: create two globals that 'll be 'hijacked' by rootExports
window.urequireExample = 'Old global `urequireExample`';
window.uEx = 'Old global `uEx`';
"""
specDevRun:
derive:['specDev', 'specRun']
specWatch:
derive: ['spec']
watch: 1444
afterBuild: require('urequire-ab-specrunner').options
injectCode: testNoConflict
mochaOptions: '-R dot'
specDevWatch:
derive: ['specDev', 'specWatch']
_ = require 'lodash'
splitTasks = (tasks)-> if _.isArray tasks then tasks else _.filter tasks.split /\s/
grunt.registerTask shortCut, "urequire:#{shortCut}" for shortCut of gruntConfig.urequire
grunt.registerTask shortCut, splitTasks tasks for shortCut, tasks of {
default: "UMD specRun min specDevRun"
develop: "dev specDevWatch"
all: "UMD specRun UMD specDevRun dev specDevRun min specRun min specDevRun"
}
grunt.loadNpmTasks task for task of grunt.file.readJSON('package.json').devDependencies when task.lastIndexOf('grunt-', 0) is 0
grunt.initConfig gruntConfig
|
[
{
"context": "# Alan Smith\n# MIT License\n# Updated 23-10-2016\n# github.com/s",
"end": 12,
"score": 0.9998237490653992,
"start": 2,
"tag": "NAME",
"value": "Alan Smith"
},
{
"context": "h\n# MIT License\n# Updated 23-10-2016\n# github.com/smithalan92 \n\n# URL patterns we want the context menu to appe",
"end": 72,
"score": 0.9994637966156006,
"start": 61,
"tag": "USERNAME",
"value": "smithalan92"
}
] | src/main.coffee | smithalan92/chrome-imageoid | 0 | # Alan Smith
# MIT License
# Updated 23-10-2016
# github.com/smithalan92
# URL patterns we want the context menu to appear for
targetUrls = [
"http://reddit.com/r/*"
"http://www.reddit.com/r/*"
"https://reddit.com/r/*"
"https://www.reddit.com/r/*"
]
# Context Menu Title
contextMenuTitle = 'Open on Imagoid'
# Context menu context targets
contexts = ['link']
# Handle click of context menu
OnClick = (info) ->
# We just want the subreddit name
subreddit = info.linkUrl.split("/")[4]
# Open imagoid in a new tab
chrome.tabs.create
url: "http://www.imagoid.com/r/#{subreddit}"
# Create the context menu
chrome.contextMenus.create
title: contextMenuTitle
contexts: contexts
targetUrlPatterns: targetUrls
onclick: OnClick
| 153477 | # <NAME>
# MIT License
# Updated 23-10-2016
# github.com/smithalan92
# URL patterns we want the context menu to appear for
targetUrls = [
"http://reddit.com/r/*"
"http://www.reddit.com/r/*"
"https://reddit.com/r/*"
"https://www.reddit.com/r/*"
]
# Context Menu Title
contextMenuTitle = 'Open on Imagoid'
# Context menu context targets
contexts = ['link']
# Handle click of context menu
OnClick = (info) ->
# We just want the subreddit name
subreddit = info.linkUrl.split("/")[4]
# Open imagoid in a new tab
chrome.tabs.create
url: "http://www.imagoid.com/r/#{subreddit}"
# Create the context menu
chrome.contextMenus.create
title: contextMenuTitle
contexts: contexts
targetUrlPatterns: targetUrls
onclick: OnClick
| true | # PI:NAME:<NAME>END_PI
# MIT License
# Updated 23-10-2016
# github.com/smithalan92
# URL patterns we want the context menu to appear for
targetUrls = [
"http://reddit.com/r/*"
"http://www.reddit.com/r/*"
"https://reddit.com/r/*"
"https://www.reddit.com/r/*"
]
# Context Menu Title
contextMenuTitle = 'Open on Imagoid'
# Context menu context targets
contexts = ['link']
# Handle click of context menu
OnClick = (info) ->
# We just want the subreddit name
subreddit = info.linkUrl.split("/")[4]
# Open imagoid in a new tab
chrome.tabs.create
url: "http://www.imagoid.com/r/#{subreddit}"
# Create the context menu
chrome.contextMenus.create
title: contextMenuTitle
contexts: contexts
targetUrlPatterns: targetUrls
onclick: OnClick
|
[
{
"context": " metric\n ws.write\n key: \"metrics:#{id}:#{timestamp}\"\n value: value\n ws.end()\n\n ",
"end": 1039,
"score": 0.5461087226867676,
"start": 1038,
"tag": "KEY",
"value": "#"
}
] | src/metrics.coffee | steven9neuf/ast_project | 0 | module.exports = (db) ->
# get(id, callback)
# Get metrics
# - id: metric's id
# - callback: the callback function, callback(err, data)
get: (username, callback) ->
db.get "metrics:", (err, data) ->
metrics = {
metrics: []
}
rs = db.createReadStream()
rs.on 'data' , (data) ->
regex = new RegExp('metrics:' + username)
if (regex.test data.key)
metrics.metrics.push {
key: data.key
value: data.value
}
rs.on 'error', () ->
rs.on 'close', () ->
rs.on 'end', () ->
console.log(metrics)
callback null, metrics
# save(id, metrics, callback)
# Save given metrics
# - id: metric id
# - metrics: an array of { timestamp, value }
# - callback: the callback function
save: (id, metrics, callback) ->
ws = db.createWriteStream()
ws.on 'error', callback
ws.on 'close', callback
for metric in metrics
{ timestamp, value } = metric
ws.write
key: "metrics:#{id}:#{timestamp}"
value: value
ws.end()
# delete(metrics, callback)
# Delete given metric
# - metric : key of the metric to be deleted
# - callback: the callback function
delete: (metric, callback) ->
db.del metric, (err) ->
throw err if err
callback null
| 215967 | module.exports = (db) ->
# get(id, callback)
# Get metrics
# - id: metric's id
# - callback: the callback function, callback(err, data)
get: (username, callback) ->
db.get "metrics:", (err, data) ->
metrics = {
metrics: []
}
rs = db.createReadStream()
rs.on 'data' , (data) ->
regex = new RegExp('metrics:' + username)
if (regex.test data.key)
metrics.metrics.push {
key: data.key
value: data.value
}
rs.on 'error', () ->
rs.on 'close', () ->
rs.on 'end', () ->
console.log(metrics)
callback null, metrics
# save(id, metrics, callback)
# Save given metrics
# - id: metric id
# - metrics: an array of { timestamp, value }
# - callback: the callback function
save: (id, metrics, callback) ->
ws = db.createWriteStream()
ws.on 'error', callback
ws.on 'close', callback
for metric in metrics
{ timestamp, value } = metric
ws.write
key: "metrics:#{id}:<KEY>{timestamp}"
value: value
ws.end()
# delete(metrics, callback)
# Delete given metric
# - metric : key of the metric to be deleted
# - callback: the callback function
delete: (metric, callback) ->
db.del metric, (err) ->
throw err if err
callback null
| true | module.exports = (db) ->
# get(id, callback)
# Get metrics
# - id: metric's id
# - callback: the callback function, callback(err, data)
get: (username, callback) ->
db.get "metrics:", (err, data) ->
metrics = {
metrics: []
}
rs = db.createReadStream()
rs.on 'data' , (data) ->
regex = new RegExp('metrics:' + username)
if (regex.test data.key)
metrics.metrics.push {
key: data.key
value: data.value
}
rs.on 'error', () ->
rs.on 'close', () ->
rs.on 'end', () ->
console.log(metrics)
callback null, metrics
# save(id, metrics, callback)
# Save given metrics
# - id: metric id
# - metrics: an array of { timestamp, value }
# - callback: the callback function
save: (id, metrics, callback) ->
ws = db.createWriteStream()
ws.on 'error', callback
ws.on 'close', callback
for metric in metrics
{ timestamp, value } = metric
ws.write
key: "metrics:#{id}:PI:KEY:<KEY>END_PI{timestamp}"
value: value
ws.end()
# delete(metrics, callback)
# Delete given metric
# - metric : key of the metric to be deleted
# - callback: the callback function
delete: (metric, callback) ->
db.del metric, (err) ->
throw err if err
callback null
|
[
{
"context": "Item and selectedItem._id\n\t\tsidebar_filter_key = \"organizations\"\n\t\tsidebarFilter = [ sidebar_filter_key, \"=\", sel",
"end": 116,
"score": 0.9958474040031433,
"start": 103,
"tag": "KEY",
"value": "organizations"
},
{
"context": "时,特殊处理name_field_key为name字段\n\t\t\t\tname_field_key = \"name\"\n\t\t\tSession.set(\"action_fields\", undefined)\n\t\t\tSe",
"end": 1869,
"score": 0.812809944152832,
"start": 1865,
"tag": "KEY",
"value": "name"
}
] | creator/packages/steedos-creator/client/views/grid_sidebar_organizations.coffee | steedos/object-server | 10 | setGridSidebarFilters = (selectedItem)->
if selectedItem and selectedItem._id
sidebar_filter_key = "organizations"
sidebarFilter = [ sidebar_filter_key, "=", selectedItem._id ]
Session.set "grid_sidebar_filters", sidebarFilter
else
Session.set "grid_sidebar_filters", null
resetFilters = ()->
Session.set("standard_query", null)
Session.set("filter_items", null)
$("#grid-search").val('')
_actionItems = (object_name, record_id, record_permissions)->
self = this
obj = Creator.getObject(object_name)
actions = Creator.getActions(object_name)
actions = _.filter actions, (action)->
if action.on == "record" or action.on == "record_more" or action.on == "list_item"
if typeof action.visible == "function"
return action.visible(object_name, record_id, record_permissions)
else
return action.visible
else
return false
return actions
_itemDropdownClick = (e, selectionInfo)->
self = this
record = selectionInfo.itemData
curObjectName = "organizations"
record_permissions = Creator.getRecordPermissions curObjectName, record, Meteor.userId()
actions = _actionItems.bind(self)(curObjectName, record._id, record_permissions)
if actions.length
actionSheetItems = _.map actions, (action)->
return {text: action.label, record: record, action: action, object_name: curObjectName}
else
actionSheetItems = [{text: t("creator_list_no_actions_tip")}]
actionSheetOption =
dataSource: actionSheetItems
showTitle: false
usePopover: true
width: "auto"
onItemClick: (value)->
object = Creator.getObject(curObjectName)
action = value.itemData.action
recordId = value.itemData.record._id
curObjectName = value.itemData.object_name
collectionName = object.label
name_field_key = object.NAME_FIELD_KEY
if curObjectName == "organizations"
# 显示组织列表时,特殊处理name_field_key为name字段
name_field_key = "name"
Session.set("action_fields", undefined)
Session.set("action_collection", "Creator.Collections.#{curObjectName}")
Session.set("action_collection_name", collectionName)
Session.set("action_save_and_insert", true)
if action.todo == "standard_delete"
action_record_title = value.itemData.record[name_field_key]
Creator.executeAction curObjectName, action, recordId, action_record_title, null, value.itemData.record, ()->
# 删除组织时,重新加载相关列表数据
if curObjectName == "organizations"
self.dxTreeViewInstance.dispose()
self.needToRefreshTree.set(new Date())
else if action.todo == "standard_edit"
record = Creator.odata.get(curObjectName, recordId)
Session.set 'action_object_name', curObjectName
Session.set 'action_record_id', recordId
Session.set 'cmDoc', record
Meteor.defer ()->
$(".btn.creator-sidebar-orgs-edit").click()
else if action.name == "addSubOrganization"
Session.set 'action_object_name', curObjectName
Session.set 'action_record_id', recordId
if recordId
if Steedos.isMobile()
Session.set 'cmDoc', parent: recordId
Session.set 'reload_dxlist', false
Meteor.defer ()->
$('.btn.creator-add').click()
else
Session.set 'cmDoc', parent: recordId
Meteor.defer ()->
$(".btn.creator-sidebar-orgs-add").click()
else
Creator.executeAction curObjectName, action, recordId, value.itemElement
if actions.length
actionSheetOption.itemTemplate = "item"
else
actionSheetOption.itemTemplate = (itemData, itemIndex, itemElement)->
itemElement.html "<span class='text-muted'>#{itemData.text}</span>"
actionSheet = this.$(".action-sheet").dxActionSheet(actionSheetOption).dxActionSheet("instance")
actionSheet.option("target", e.target);
actionSheet.option("visible", true);
Template.creator_grid_sidebar_organizations.onRendered ->
self = this
self.autorun (c)->
list_view_id = "all"
object_name = "organizations"
spaceId = Steedos.spaceId()
userId = Meteor.userId()
loginToken = Accounts._storedLoginToken()
needToRefreshTree = self.needToRefreshTree.get()
is_admin = Steedos.isSpaceAdmin()
orgIds = Steedos.getUserCompanyOrganizationIds()
orgDocs = db.organizations.find({$or:[{_id:{$in:orgIds}},{parents:{$in:orgIds}}]}).fetch()
if !is_admin
if !orgIds || !orgIds.length
return null
# 等待orgDocs订阅完成再显示组织树
if !orgDocs || !orgDocs.length
return null
# 权限筛选,只显示当前有权限的组织本身及其所有子组织和孙组织(包括任意深度的子孙组织)
filters = [["_id", "=", orgIds], "or", ["parents", "=", orgIds]]
steedosFilters = require("@steedos/filters")
filters = steedosFilters.formatFiltersToDev(filters)
if spaceId and userId
url = "/api/odata/v4/#{spaceId}/#{object_name}"
dxOptions =
searchEnabled: false
dataSource:
store:
type: "odata"
version: 4
url: Steedos.absoluteUrl(url)
withCredentials: false
onLoading: (loadOptions)->
loadOptions.select = ["name", "parent", "children", "company_id", "sort_no"]
loadOptions.expand = ["company_id($select=admins)"]
onLoaded: (results)->
if results and _.isArray(results) and results.length
selectedItem = Session.get "organization"
if selectedItem
setGridSidebarFilters(selectedItem)
_.each results, (item)->
if selectedItem and item._id == selectedItem._id
item.selected = true
# 判断是否有下级节点
item.hasItems = false
if item.children?.length > 0
item.hasItems = true
# 根节点自动展开
if !item.parent
item.expanded = true
beforeSend: (request) ->
request.headers['X-User-Id'] = userId
request.headers['X-Space-Id'] = spaceId
request.headers['X-Auth-Token'] = loginToken
errorHandler: (error) ->
if error.httpStatus == 404 || error.httpStatus == 400
error.message = t "creator_odata_api_not_found"
else if error.httpStatus == 401
error.message = t "creator_odata_unexpected_character"
else if error.httpStatus == 403
error.message = t "creator_odata_user_privileges"
else if error.httpStatus == 500
if error.message == "Unexpected character at 106" or error.message == 'Unexpected character at 374'
error.message = t "creator_odata_unexpected_character"
toastr.error(error.message)
fieldTypes: {
'_id': 'String'
}
filter: filters
sort: [ {
selector: 'sort_no'
desc: true
},{
selector: 'name'
desc: false
} ]
itemTemplate: (itemData, itemIndex, itemElement)->
itemElement.attr("title", itemData.name)
if itemData.icon
itemElement.append("<i class=\"dx-icon #{itemData.icon}\"></i>");
itemElement.append("<span>" + itemData.name + "</span>");
unless Steedos.isMobile()
record = itemData
record_permissions = Creator.getRecordPermissions object_name, record, Meteor.userId()
actions = _actionItems.bind(self)(object_name, record._id, record_permissions)
if actions.length
htmlText = """
<span class="slds-grid slds-grid--align-spread creator-table-actions">
<div class="forceVirtualActionMarker forceVirtualAction">
<a class="rowActionsPlaceHolder slds-button slds-button--icon-x-small keyboardMode--trigger" aria-haspopup="true" role="button" title="" href="javascript:void(0);" data-toggle="dropdown">
<span class="slds-icon_container slds-icon-utility-down">
<span class="lightningPrimitiveIcon">
#{Blaze.toHTMLWithData Template.steedos_button_icon, {class: "slds-icon slds-icon-text-default slds-icon--xx-small", source: "utility-sprite", name:"threedots_vertical"}}
</span>
<span class="slds-assistive-text" data-aura-rendered-by="15534:0">显示更多信息</span>
</span>
</a>
</div>
</span>
"""
itemElement.append(htmlText)
sidebar_multiple = false
dxOptions.selectNodesRecursive = false
dxOptions.selectByClick = true
dxOptions.selectionMode = if sidebar_multiple then "multiple" else "single"
dxOptions.showCheckBoxesMode = if sidebar_multiple then "normal" else "none"
dxOptions.onItemClick = (selectionInfo)->
targetDropdown = $(event.target).closest(".creator-table-actions")
if targetDropdown.length
# 如果点击的是右侧下拉箭头,则弹出菜单
selectionInfo.event.preventDefault()
_itemDropdownClick.call(self, event, selectionInfo)
dxOptions.onItemSelectionChanged = (selectionInfo)->
selectionItemData = if selectionInfo.node.selected then selectionInfo.itemData else null;
if selectionItemData?._id
Session.set "organization", selectionItemData
else
Session.set "organization", null
selectionInfo.itemElement?.parent().removeClass("dx-state-focused")
selectionInfo.component?._cleanFocusState()
resetFilters()
setGridSidebarFilters(selectionItemData)
dxOptions.keyExpr = "_id"
dxOptions.parentIdExpr = "parent"
dxOptions.displayExpr = "name"
dxOptions.hasItemsExpr = "hasItems"
if is_admin
dxOptions.rootValue = null
else
# 这里不可以直接把dxOptions.rootValue设置为orgIds[0],因为这样的话,不会显示orgIds[0]本身而只会显示其子组织
# 所以这里取orgIds[0]对应的组织的父组织ID值为根组织
dxOptions.rootValue = orgDocs[0].parent
unless dxOptions.rootValue
# 如果第一个组织parent不存在说明当前用户主部门为根组织
dxOptions.rootValue = null
dxOptions.dataStructure = "plain"
dxOptions.virtualModeEnabled = true
self.dxTreeViewInstance = self.$(".gridSidebarContainer").dxTreeView(dxOptions).dxTreeView('instance')
Template.creator_grid_sidebar_organizations.helpers Creator.helpers
Template.creator_grid_sidebar_organizations.helpers
organization:() ->
return Session.get("organization")
collection: ()->
return Session.get("action_collection")
fields: ->
return Session.get("action_fields")
collectionName: ()->
return Session.get("action_collection_name")
doc: ()->
return Session.get("action_record_id")
saveAndInsert: ()->
allowSaveAndInsert = Session.get("action_save_and_insert")
if allowSaveAndInsert
collectionName = Session.get("action_collection")
objectName = collectionName.replace(/Creator.Collections./, "")
# 只有有新建权限的情况下显示“保存并新建”按钮
return Creator.getPermissions(objectName)?.allowCreate
else
return false
Template.creator_grid_sidebar_organizations.events
Template.creator_grid_sidebar_organizations.onCreated ->
self = this
self.needToRefreshTree = new ReactiveVar(null)
AutoForm.hooks creatorSidebarOrgsEditForm:
onSuccess: (formType,result)->
# 编辑组织,重新加载左侧树
if result.object_name == "organizations"
self.dxTreeViewInstance?.dispose()
self.needToRefreshTree.set(new Date())
AutoForm.hooks creatorSidebarOrgsAddForm:
onSuccess: (formType,result)->
# 新建组织,重新加载左侧树
if result.object_name == "organizations"
self.dxTreeViewInstance?.dispose()
self.needToRefreshTree.set(new Date())
Template.creator_grid_sidebar_organizations.onDestroyed ->
Session.set "organization", null
Session.set "grid_sidebar_filters", null | 56718 | setGridSidebarFilters = (selectedItem)->
if selectedItem and selectedItem._id
sidebar_filter_key = "<KEY>"
sidebarFilter = [ sidebar_filter_key, "=", selectedItem._id ]
Session.set "grid_sidebar_filters", sidebarFilter
else
Session.set "grid_sidebar_filters", null
resetFilters = ()->
Session.set("standard_query", null)
Session.set("filter_items", null)
$("#grid-search").val('')
_actionItems = (object_name, record_id, record_permissions)->
self = this
obj = Creator.getObject(object_name)
actions = Creator.getActions(object_name)
actions = _.filter actions, (action)->
if action.on == "record" or action.on == "record_more" or action.on == "list_item"
if typeof action.visible == "function"
return action.visible(object_name, record_id, record_permissions)
else
return action.visible
else
return false
return actions
_itemDropdownClick = (e, selectionInfo)->
self = this
record = selectionInfo.itemData
curObjectName = "organizations"
record_permissions = Creator.getRecordPermissions curObjectName, record, Meteor.userId()
actions = _actionItems.bind(self)(curObjectName, record._id, record_permissions)
if actions.length
actionSheetItems = _.map actions, (action)->
return {text: action.label, record: record, action: action, object_name: curObjectName}
else
actionSheetItems = [{text: t("creator_list_no_actions_tip")}]
actionSheetOption =
dataSource: actionSheetItems
showTitle: false
usePopover: true
width: "auto"
onItemClick: (value)->
object = Creator.getObject(curObjectName)
action = value.itemData.action
recordId = value.itemData.record._id
curObjectName = value.itemData.object_name
collectionName = object.label
name_field_key = object.NAME_FIELD_KEY
if curObjectName == "organizations"
# 显示组织列表时,特殊处理name_field_key为name字段
name_field_key = "<KEY>"
Session.set("action_fields", undefined)
Session.set("action_collection", "Creator.Collections.#{curObjectName}")
Session.set("action_collection_name", collectionName)
Session.set("action_save_and_insert", true)
if action.todo == "standard_delete"
action_record_title = value.itemData.record[name_field_key]
Creator.executeAction curObjectName, action, recordId, action_record_title, null, value.itemData.record, ()->
# 删除组织时,重新加载相关列表数据
if curObjectName == "organizations"
self.dxTreeViewInstance.dispose()
self.needToRefreshTree.set(new Date())
else if action.todo == "standard_edit"
record = Creator.odata.get(curObjectName, recordId)
Session.set 'action_object_name', curObjectName
Session.set 'action_record_id', recordId
Session.set 'cmDoc', record
Meteor.defer ()->
$(".btn.creator-sidebar-orgs-edit").click()
else if action.name == "addSubOrganization"
Session.set 'action_object_name', curObjectName
Session.set 'action_record_id', recordId
if recordId
if Steedos.isMobile()
Session.set 'cmDoc', parent: recordId
Session.set 'reload_dxlist', false
Meteor.defer ()->
$('.btn.creator-add').click()
else
Session.set 'cmDoc', parent: recordId
Meteor.defer ()->
$(".btn.creator-sidebar-orgs-add").click()
else
Creator.executeAction curObjectName, action, recordId, value.itemElement
if actions.length
actionSheetOption.itemTemplate = "item"
else
actionSheetOption.itemTemplate = (itemData, itemIndex, itemElement)->
itemElement.html "<span class='text-muted'>#{itemData.text}</span>"
actionSheet = this.$(".action-sheet").dxActionSheet(actionSheetOption).dxActionSheet("instance")
actionSheet.option("target", e.target);
actionSheet.option("visible", true);
Template.creator_grid_sidebar_organizations.onRendered ->
self = this
self.autorun (c)->
list_view_id = "all"
object_name = "organizations"
spaceId = Steedos.spaceId()
userId = Meteor.userId()
loginToken = Accounts._storedLoginToken()
needToRefreshTree = self.needToRefreshTree.get()
is_admin = Steedos.isSpaceAdmin()
orgIds = Steedos.getUserCompanyOrganizationIds()
orgDocs = db.organizations.find({$or:[{_id:{$in:orgIds}},{parents:{$in:orgIds}}]}).fetch()
if !is_admin
if !orgIds || !orgIds.length
return null
# 等待orgDocs订阅完成再显示组织树
if !orgDocs || !orgDocs.length
return null
# 权限筛选,只显示当前有权限的组织本身及其所有子组织和孙组织(包括任意深度的子孙组织)
filters = [["_id", "=", orgIds], "or", ["parents", "=", orgIds]]
steedosFilters = require("@steedos/filters")
filters = steedosFilters.formatFiltersToDev(filters)
if spaceId and userId
url = "/api/odata/v4/#{spaceId}/#{object_name}"
dxOptions =
searchEnabled: false
dataSource:
store:
type: "odata"
version: 4
url: Steedos.absoluteUrl(url)
withCredentials: false
onLoading: (loadOptions)->
loadOptions.select = ["name", "parent", "children", "company_id", "sort_no"]
loadOptions.expand = ["company_id($select=admins)"]
onLoaded: (results)->
if results and _.isArray(results) and results.length
selectedItem = Session.get "organization"
if selectedItem
setGridSidebarFilters(selectedItem)
_.each results, (item)->
if selectedItem and item._id == selectedItem._id
item.selected = true
# 判断是否有下级节点
item.hasItems = false
if item.children?.length > 0
item.hasItems = true
# 根节点自动展开
if !item.parent
item.expanded = true
beforeSend: (request) ->
request.headers['X-User-Id'] = userId
request.headers['X-Space-Id'] = spaceId
request.headers['X-Auth-Token'] = loginToken
errorHandler: (error) ->
if error.httpStatus == 404 || error.httpStatus == 400
error.message = t "creator_odata_api_not_found"
else if error.httpStatus == 401
error.message = t "creator_odata_unexpected_character"
else if error.httpStatus == 403
error.message = t "creator_odata_user_privileges"
else if error.httpStatus == 500
if error.message == "Unexpected character at 106" or error.message == 'Unexpected character at 374'
error.message = t "creator_odata_unexpected_character"
toastr.error(error.message)
fieldTypes: {
'_id': 'String'
}
filter: filters
sort: [ {
selector: 'sort_no'
desc: true
},{
selector: 'name'
desc: false
} ]
itemTemplate: (itemData, itemIndex, itemElement)->
itemElement.attr("title", itemData.name)
if itemData.icon
itemElement.append("<i class=\"dx-icon #{itemData.icon}\"></i>");
itemElement.append("<span>" + itemData.name + "</span>");
unless Steedos.isMobile()
record = itemData
record_permissions = Creator.getRecordPermissions object_name, record, Meteor.userId()
actions = _actionItems.bind(self)(object_name, record._id, record_permissions)
if actions.length
htmlText = """
<span class="slds-grid slds-grid--align-spread creator-table-actions">
<div class="forceVirtualActionMarker forceVirtualAction">
<a class="rowActionsPlaceHolder slds-button slds-button--icon-x-small keyboardMode--trigger" aria-haspopup="true" role="button" title="" href="javascript:void(0);" data-toggle="dropdown">
<span class="slds-icon_container slds-icon-utility-down">
<span class="lightningPrimitiveIcon">
#{Blaze.toHTMLWithData Template.steedos_button_icon, {class: "slds-icon slds-icon-text-default slds-icon--xx-small", source: "utility-sprite", name:"threedots_vertical"}}
</span>
<span class="slds-assistive-text" data-aura-rendered-by="15534:0">显示更多信息</span>
</span>
</a>
</div>
</span>
"""
itemElement.append(htmlText)
sidebar_multiple = false
dxOptions.selectNodesRecursive = false
dxOptions.selectByClick = true
dxOptions.selectionMode = if sidebar_multiple then "multiple" else "single"
dxOptions.showCheckBoxesMode = if sidebar_multiple then "normal" else "none"
dxOptions.onItemClick = (selectionInfo)->
targetDropdown = $(event.target).closest(".creator-table-actions")
if targetDropdown.length
# 如果点击的是右侧下拉箭头,则弹出菜单
selectionInfo.event.preventDefault()
_itemDropdownClick.call(self, event, selectionInfo)
dxOptions.onItemSelectionChanged = (selectionInfo)->
selectionItemData = if selectionInfo.node.selected then selectionInfo.itemData else null;
if selectionItemData?._id
Session.set "organization", selectionItemData
else
Session.set "organization", null
selectionInfo.itemElement?.parent().removeClass("dx-state-focused")
selectionInfo.component?._cleanFocusState()
resetFilters()
setGridSidebarFilters(selectionItemData)
dxOptions.keyExpr = "_id"
dxOptions.parentIdExpr = "parent"
dxOptions.displayExpr = "name"
dxOptions.hasItemsExpr = "hasItems"
if is_admin
dxOptions.rootValue = null
else
# 这里不可以直接把dxOptions.rootValue设置为orgIds[0],因为这样的话,不会显示orgIds[0]本身而只会显示其子组织
# 所以这里取orgIds[0]对应的组织的父组织ID值为根组织
dxOptions.rootValue = orgDocs[0].parent
unless dxOptions.rootValue
# 如果第一个组织parent不存在说明当前用户主部门为根组织
dxOptions.rootValue = null
dxOptions.dataStructure = "plain"
dxOptions.virtualModeEnabled = true
self.dxTreeViewInstance = self.$(".gridSidebarContainer").dxTreeView(dxOptions).dxTreeView('instance')
Template.creator_grid_sidebar_organizations.helpers Creator.helpers
Template.creator_grid_sidebar_organizations.helpers
organization:() ->
return Session.get("organization")
collection: ()->
return Session.get("action_collection")
fields: ->
return Session.get("action_fields")
collectionName: ()->
return Session.get("action_collection_name")
doc: ()->
return Session.get("action_record_id")
saveAndInsert: ()->
allowSaveAndInsert = Session.get("action_save_and_insert")
if allowSaveAndInsert
collectionName = Session.get("action_collection")
objectName = collectionName.replace(/Creator.Collections./, "")
# 只有有新建权限的情况下显示“保存并新建”按钮
return Creator.getPermissions(objectName)?.allowCreate
else
return false
Template.creator_grid_sidebar_organizations.events
Template.creator_grid_sidebar_organizations.onCreated ->
self = this
self.needToRefreshTree = new ReactiveVar(null)
AutoForm.hooks creatorSidebarOrgsEditForm:
onSuccess: (formType,result)->
# 编辑组织,重新加载左侧树
if result.object_name == "organizations"
self.dxTreeViewInstance?.dispose()
self.needToRefreshTree.set(new Date())
AutoForm.hooks creatorSidebarOrgsAddForm:
onSuccess: (formType,result)->
# 新建组织,重新加载左侧树
if result.object_name == "organizations"
self.dxTreeViewInstance?.dispose()
self.needToRefreshTree.set(new Date())
Template.creator_grid_sidebar_organizations.onDestroyed ->
Session.set "organization", null
Session.set "grid_sidebar_filters", null | true | setGridSidebarFilters = (selectedItem)->
if selectedItem and selectedItem._id
sidebar_filter_key = "PI:KEY:<KEY>END_PI"
sidebarFilter = [ sidebar_filter_key, "=", selectedItem._id ]
Session.set "grid_sidebar_filters", sidebarFilter
else
Session.set "grid_sidebar_filters", null
resetFilters = ()->
Session.set("standard_query", null)
Session.set("filter_items", null)
$("#grid-search").val('')
_actionItems = (object_name, record_id, record_permissions)->
self = this
obj = Creator.getObject(object_name)
actions = Creator.getActions(object_name)
actions = _.filter actions, (action)->
if action.on == "record" or action.on == "record_more" or action.on == "list_item"
if typeof action.visible == "function"
return action.visible(object_name, record_id, record_permissions)
else
return action.visible
else
return false
return actions
_itemDropdownClick = (e, selectionInfo)->
self = this
record = selectionInfo.itemData
curObjectName = "organizations"
record_permissions = Creator.getRecordPermissions curObjectName, record, Meteor.userId()
actions = _actionItems.bind(self)(curObjectName, record._id, record_permissions)
if actions.length
actionSheetItems = _.map actions, (action)->
return {text: action.label, record: record, action: action, object_name: curObjectName}
else
actionSheetItems = [{text: t("creator_list_no_actions_tip")}]
actionSheetOption =
dataSource: actionSheetItems
showTitle: false
usePopover: true
width: "auto"
onItemClick: (value)->
object = Creator.getObject(curObjectName)
action = value.itemData.action
recordId = value.itemData.record._id
curObjectName = value.itemData.object_name
collectionName = object.label
name_field_key = object.NAME_FIELD_KEY
if curObjectName == "organizations"
# 显示组织列表时,特殊处理name_field_key为name字段
name_field_key = "PI:KEY:<KEY>END_PI"
Session.set("action_fields", undefined)
Session.set("action_collection", "Creator.Collections.#{curObjectName}")
Session.set("action_collection_name", collectionName)
Session.set("action_save_and_insert", true)
if action.todo == "standard_delete"
action_record_title = value.itemData.record[name_field_key]
Creator.executeAction curObjectName, action, recordId, action_record_title, null, value.itemData.record, ()->
# 删除组织时,重新加载相关列表数据
if curObjectName == "organizations"
self.dxTreeViewInstance.dispose()
self.needToRefreshTree.set(new Date())
else if action.todo == "standard_edit"
record = Creator.odata.get(curObjectName, recordId)
Session.set 'action_object_name', curObjectName
Session.set 'action_record_id', recordId
Session.set 'cmDoc', record
Meteor.defer ()->
$(".btn.creator-sidebar-orgs-edit").click()
else if action.name == "addSubOrganization"
Session.set 'action_object_name', curObjectName
Session.set 'action_record_id', recordId
if recordId
if Steedos.isMobile()
Session.set 'cmDoc', parent: recordId
Session.set 'reload_dxlist', false
Meteor.defer ()->
$('.btn.creator-add').click()
else
Session.set 'cmDoc', parent: recordId
Meteor.defer ()->
$(".btn.creator-sidebar-orgs-add").click()
else
Creator.executeAction curObjectName, action, recordId, value.itemElement
if actions.length
actionSheetOption.itemTemplate = "item"
else
actionSheetOption.itemTemplate = (itemData, itemIndex, itemElement)->
itemElement.html "<span class='text-muted'>#{itemData.text}</span>"
actionSheet = this.$(".action-sheet").dxActionSheet(actionSheetOption).dxActionSheet("instance")
actionSheet.option("target", e.target);
actionSheet.option("visible", true);
Template.creator_grid_sidebar_organizations.onRendered ->
self = this
self.autorun (c)->
list_view_id = "all"
object_name = "organizations"
spaceId = Steedos.spaceId()
userId = Meteor.userId()
loginToken = Accounts._storedLoginToken()
needToRefreshTree = self.needToRefreshTree.get()
is_admin = Steedos.isSpaceAdmin()
orgIds = Steedos.getUserCompanyOrganizationIds()
orgDocs = db.organizations.find({$or:[{_id:{$in:orgIds}},{parents:{$in:orgIds}}]}).fetch()
if !is_admin
if !orgIds || !orgIds.length
return null
# 等待orgDocs订阅完成再显示组织树
if !orgDocs || !orgDocs.length
return null
# 权限筛选,只显示当前有权限的组织本身及其所有子组织和孙组织(包括任意深度的子孙组织)
filters = [["_id", "=", orgIds], "or", ["parents", "=", orgIds]]
steedosFilters = require("@steedos/filters")
filters = steedosFilters.formatFiltersToDev(filters)
if spaceId and userId
url = "/api/odata/v4/#{spaceId}/#{object_name}"
dxOptions =
searchEnabled: false
dataSource:
store:
type: "odata"
version: 4
url: Steedos.absoluteUrl(url)
withCredentials: false
onLoading: (loadOptions)->
loadOptions.select = ["name", "parent", "children", "company_id", "sort_no"]
loadOptions.expand = ["company_id($select=admins)"]
onLoaded: (results)->
if results and _.isArray(results) and results.length
selectedItem = Session.get "organization"
if selectedItem
setGridSidebarFilters(selectedItem)
_.each results, (item)->
if selectedItem and item._id == selectedItem._id
item.selected = true
# 判断是否有下级节点
item.hasItems = false
if item.children?.length > 0
item.hasItems = true
# 根节点自动展开
if !item.parent
item.expanded = true
beforeSend: (request) ->
request.headers['X-User-Id'] = userId
request.headers['X-Space-Id'] = spaceId
request.headers['X-Auth-Token'] = loginToken
errorHandler: (error) ->
if error.httpStatus == 404 || error.httpStatus == 400
error.message = t "creator_odata_api_not_found"
else if error.httpStatus == 401
error.message = t "creator_odata_unexpected_character"
else if error.httpStatus == 403
error.message = t "creator_odata_user_privileges"
else if error.httpStatus == 500
if error.message == "Unexpected character at 106" or error.message == 'Unexpected character at 374'
error.message = t "creator_odata_unexpected_character"
toastr.error(error.message)
fieldTypes: {
'_id': 'String'
}
filter: filters
sort: [ {
selector: 'sort_no'
desc: true
},{
selector: 'name'
desc: false
} ]
itemTemplate: (itemData, itemIndex, itemElement)->
itemElement.attr("title", itemData.name)
if itemData.icon
itemElement.append("<i class=\"dx-icon #{itemData.icon}\"></i>");
itemElement.append("<span>" + itemData.name + "</span>");
unless Steedos.isMobile()
record = itemData
record_permissions = Creator.getRecordPermissions object_name, record, Meteor.userId()
actions = _actionItems.bind(self)(object_name, record._id, record_permissions)
if actions.length
htmlText = """
<span class="slds-grid slds-grid--align-spread creator-table-actions">
<div class="forceVirtualActionMarker forceVirtualAction">
<a class="rowActionsPlaceHolder slds-button slds-button--icon-x-small keyboardMode--trigger" aria-haspopup="true" role="button" title="" href="javascript:void(0);" data-toggle="dropdown">
<span class="slds-icon_container slds-icon-utility-down">
<span class="lightningPrimitiveIcon">
#{Blaze.toHTMLWithData Template.steedos_button_icon, {class: "slds-icon slds-icon-text-default slds-icon--xx-small", source: "utility-sprite", name:"threedots_vertical"}}
</span>
<span class="slds-assistive-text" data-aura-rendered-by="15534:0">显示更多信息</span>
</span>
</a>
</div>
</span>
"""
itemElement.append(htmlText)
sidebar_multiple = false
dxOptions.selectNodesRecursive = false
dxOptions.selectByClick = true
dxOptions.selectionMode = if sidebar_multiple then "multiple" else "single"
dxOptions.showCheckBoxesMode = if sidebar_multiple then "normal" else "none"
dxOptions.onItemClick = (selectionInfo)->
targetDropdown = $(event.target).closest(".creator-table-actions")
if targetDropdown.length
# 如果点击的是右侧下拉箭头,则弹出菜单
selectionInfo.event.preventDefault()
_itemDropdownClick.call(self, event, selectionInfo)
dxOptions.onItemSelectionChanged = (selectionInfo)->
selectionItemData = if selectionInfo.node.selected then selectionInfo.itemData else null;
if selectionItemData?._id
Session.set "organization", selectionItemData
else
Session.set "organization", null
selectionInfo.itemElement?.parent().removeClass("dx-state-focused")
selectionInfo.component?._cleanFocusState()
resetFilters()
setGridSidebarFilters(selectionItemData)
dxOptions.keyExpr = "_id"
dxOptions.parentIdExpr = "parent"
dxOptions.displayExpr = "name"
dxOptions.hasItemsExpr = "hasItems"
if is_admin
dxOptions.rootValue = null
else
# 这里不可以直接把dxOptions.rootValue设置为orgIds[0],因为这样的话,不会显示orgIds[0]本身而只会显示其子组织
# 所以这里取orgIds[0]对应的组织的父组织ID值为根组织
dxOptions.rootValue = orgDocs[0].parent
unless dxOptions.rootValue
# 如果第一个组织parent不存在说明当前用户主部门为根组织
dxOptions.rootValue = null
dxOptions.dataStructure = "plain"
dxOptions.virtualModeEnabled = true
self.dxTreeViewInstance = self.$(".gridSidebarContainer").dxTreeView(dxOptions).dxTreeView('instance')
Template.creator_grid_sidebar_organizations.helpers Creator.helpers
Template.creator_grid_sidebar_organizations.helpers
organization:() ->
return Session.get("organization")
collection: ()->
return Session.get("action_collection")
fields: ->
return Session.get("action_fields")
collectionName: ()->
return Session.get("action_collection_name")
doc: ()->
return Session.get("action_record_id")
saveAndInsert: ()->
allowSaveAndInsert = Session.get("action_save_and_insert")
if allowSaveAndInsert
collectionName = Session.get("action_collection")
objectName = collectionName.replace(/Creator.Collections./, "")
# 只有有新建权限的情况下显示“保存并新建”按钮
return Creator.getPermissions(objectName)?.allowCreate
else
return false
Template.creator_grid_sidebar_organizations.events
Template.creator_grid_sidebar_organizations.onCreated ->
self = this
self.needToRefreshTree = new ReactiveVar(null)
AutoForm.hooks creatorSidebarOrgsEditForm:
onSuccess: (formType,result)->
# 编辑组织,重新加载左侧树
if result.object_name == "organizations"
self.dxTreeViewInstance?.dispose()
self.needToRefreshTree.set(new Date())
AutoForm.hooks creatorSidebarOrgsAddForm:
onSuccess: (formType,result)->
# 新建组织,重新加载左侧树
if result.object_name == "organizations"
self.dxTreeViewInstance?.dispose()
self.needToRefreshTree.set(new Date())
Template.creator_grid_sidebar_organizations.onDestroyed ->
Session.set "organization", null
Session.set "grid_sidebar_filters", null |
[
{
"context": "orked from the origina [Docco](https://github.com/jashkenas/docco) project, updated with abandon*\n#\n# **Docco",
"end": 65,
"score": 0.9996953010559082,
"start": 56,
"tag": "USERNAME",
"value": "jashkenas"
},
{
"context": "der.\n#\n# The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,\n# and released und",
"end": 834,
"score": 0.999512791633606,
"start": 825,
"tag": "USERNAME",
"value": "jashkenas"
},
{
"context": "r you'd prefer a more \n# convenient package, get [Ryan Tomayko](http://github.com/rtomayko)'s \n# [Rocco](http://",
"end": 1519,
"score": 0.9968507885932922,
"start": 1507,
"tag": "NAME",
"value": "Ryan Tomayko"
},
{
"context": "ent package, get [Ryan Tomayko](http://github.com/rtomayko)'s \n# [Rocco](http://rtomayko.github.com/rocco/ro",
"end": 1547,
"score": 0.999511182308197,
"start": 1539,
"tag": "USERNAME",
"value": "rtomayko"
},
{
"context": "rtomayko)'s \n# [Rocco](http://rtomayko.github.com/rocco/rocco.html), the Ruby port that's \n# available as",
"end": 1594,
"score": 0.9922668933868408,
"start": 1589,
"tag": "USERNAME",
"value": "rocco"
},
{
"context": "* If Python's more your speed, take a look at \n# [Nick Fitzgerald](http://github.com/fitzgen)'s [Pycco](http://fitz",
"end": 1870,
"score": 0.999829113483429,
"start": 1855,
"tag": "NAME",
"value": "Nick Fitzgerald"
},
{
"context": " a look at \n# [Nick Fitzgerald](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.com/pycco/). \n#\n",
"end": 1897,
"score": 0.9997242093086243,
"start": 1890,
"tag": "USERNAME",
"value": "fitzgen"
},
{
"context": " * **Lua** enthusiasts can get their fix with \n# [Robert Gieseke](https://github.com/rgieseke)'s [Locco](http://rg",
"end": 2201,
"score": 0.9998137950897217,
"start": 2187,
"tag": "NAME",
"value": "Robert Gieseke"
},
{
"context": "r fix with \n# [Robert Gieseke](https://github.com/rgieseke)'s [Locco](http://rgieseke.github.com/locco/).\n# ",
"end": 2230,
"score": 0.9997148513793945,
"start": 2222,
"tag": "USERNAME",
"value": "rgieseke"
},
{
"context": " happen to be a **.NET**\n# aficionado, check out [Don Wilson](https://github.com/dontangg)'s \n# [Nocco](http:/",
"end": 2355,
"score": 0.9997420310974121,
"start": 2345,
"tag": "NAME",
"value": "Don Wilson"
},
{
"context": "ionado, check out [Don Wilson](https://github.com/dontangg)'s \n# [Nocco](http://dontangg.github.com/nocco/).",
"end": 2384,
"score": 0.999343991279602,
"start": 2376,
"tag": "USERNAME",
"value": "dontangg"
}
] | node_modules/docco-husky/src/docco.coffee | timmyg/pedalwagon-api | 0 | # > *forked from the origina [Docco](https://github.com/jashkenas/docco) project, updated with abandon*
#
# **Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style
# documentation generator. It produces HTML
# that displays your comments alongside your code. Comments are passed through
# [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
# passed through [Pygments](http://pygments.org/) syntax highlighting.
# This page is the result of running Docco against its own source file.
#
# If you install Docco, you can run it from the command-line:
#
# docco src/*.coffee
#
# ...will generate an HTML documentation page for each of the named source files,
# with a menu linking to the other pages, saving it into a `docs` folder.
#
# The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,
# and released under the MIT license.
#
# To install Docco, first make sure you have [Node.js](http://nodejs.org/),
# [Pygments](http://pygments.org/) (install the latest dev version of Pygments
# from [its Mercurial repo](http://dev.pocoo.org/hg/pygments-main)), and
# [CoffeeScript](http://coffeescript.org/). Then, with NPM:
#
# sudo npm install docco
#
# Docco can be used to process CoffeeScript, JavaScript, Ruby or Python files.
# Only single-line comments are processed -- block comments are ignored.
#
#### Partners in Crime:
#
# * If **Node.js** doesn't run on your platform, or you'd prefer a more
# convenient package, get [Ryan Tomayko](http://github.com/rtomayko)'s
# [Rocco](http://rtomayko.github.com/rocco/rocco.html), the Ruby port that's
# available as a gem.
#
# * If you're writing shell scripts, try
# [Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**,
# also by Mr. Tomayko.
#
# * If Python's more your speed, take a look at
# [Nick Fitzgerald](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.com/pycco/).
#
# * For **Clojure** fans, [Fogus](http://blog.fogus.me/)'s
# [Marginalia](http://fogus.me/fun/marginalia/) is a bit of a departure from
# "quick-and-dirty", but it'll get the job done.
#
# * **Lua** enthusiasts can get their fix with
# [Robert Gieseke](https://github.com/rgieseke)'s [Locco](http://rgieseke.github.com/locco/).
#
# * And if you happen to be a **.NET**
# aficionado, check out [Don Wilson](https://github.com/dontangg)'s
# [Nocco](http://dontangg.github.com/nocco/).
#### Main Documentation Generation Functions
# Generate the documentation for a source file by reading it in, splitting it
# up into comment/code sections, highlighting them for the appropriate language,
# and merging them into an HTML template.
generate_documentation = (source, context, callback) ->
fs.readFile source, "utf-8", (error, code) ->
throw error if error
sections = parse source, code
highlight source, sections, ->
generate_source_html source, context, sections
callback()
# Given a string of source code, parse out each comment and the code that
# follows it, and create an individual **section** for it.
# Sections take the form:
#
# {
# docs_text: ...
# docs_html: ...
# code_text: ...
# code_html: ...
# }
#
parse = (source, code) ->
lines = code.split '\n'
sections = []
language = get_language source
has_code = docs_text = code_text = ''
in_multi = false
multi_accum = ""
save = (docs, code) ->
sections.push docs_text: docs, code_text: code
for line in lines
if line.match(language.multi_start_matcher) or in_multi
if has_code
save docs_text, code_text
has_code = docs_text = code_text = ''
# Found the start of a multiline comment line, set in_multi to true
# and begin accumulating lines untime we reach a line that finishes
# the multiline comment
in_multi = true
multi_accum += line + '\n'
# If we reached the end of a multiline comment, template the result
# and set in_multi to false, reset multi_accum
if line.match(language.multi_end_matcher)
in_multi = false
try
parsed = dox.parseComments( multi_accum )[0]
docs_text += dox_template(parsed)
catch error
console.log "Error parsing comments with Dox: #{error}"
docs_text = multi_accum
multi_accum = ''
else if line.match(language.comment_matcher) and not line.match(language.comment_filter)
if has_code
save docs_text, code_text
has_code = docs_text = code_text = ''
docs_text += line.replace(language.comment_matcher, '') + '\n'
else
has_code = yes
code_text += line + '\n'
save docs_text, code_text
sections
# Highlights a single chunk of CoffeeScript code, using **Pygments** over stdio,
# and runs the text of its corresponding comment through **Markdown**, using
# [Showdown.js](http://attacklab.net/showdown/).
#
# We process the entire file in a single call to Pygments by inserting little
# marker comments between each section and then splitting the result string
# wherever our markers occur.
highlight = (source, sections, callback) ->
language = get_language source
pygments = spawn 'pygmentize', ['-l', language.name, '-f', 'html', '-O', 'encoding=utf-8,tabsize=2']
output = ''
pygments.stderr.addListener 'data', (error) ->
console.error error.toString() if error
pygments.stdin.addListener 'error', (error) ->
console.error "Could not use Pygments to highlight the source."
process.exit 1
pygments.stdout.addListener 'data', (result) ->
output += result if result
pygments.addListener 'exit', ->
output = output.replace(highlight_start, '').replace(highlight_end, '')
fragments = output.split language.divider_html
for section, i in sections
section.code_html = highlight_start + fragments[i] + highlight_end
section.docs_html = showdown.makeHtml section.docs_text
callback()
if pygments.stdin.writable
pygments.stdin.write((section.code_text for section in sections).join(language.divider_text))
pygments.stdin.end()
# Once all of the code is finished highlighting, we can generate the HTML file
# and write out the documentation. Pass the completed sections into the template
# found in `resources/docco.jst`
generate_source_html = (source, context, sections) ->
title = path.basename source
dest = destination source, context
html = docco_template {
title: title, file_path: source, sections: sections, context: context, path: path, relative_base: relative_base
}
console.log "docco: #{source} -> #{dest}"
write_file(dest, html)
generate_readme = (context, sources, package_json) ->
title = "README"
dest = "#{context.config.output_dir}/index.html"
source = "README.md"
# README.md template to be use to generate the main REAME file
readme_template = jade.compile fs.readFileSync(__dirname + '/../resources/readme.jade').toString(), { filename: __dirname + '/../resources/readme.jade' }
readme_path = "#{process.cwd()}/#{source}"
content_index_path = "#{process.cwd()}/#{context.config.content_dir}/content_index.md"
console.log content_index_path
# generate the content index if it exists under the content sources
if file_exists(content_index_path)
content_index = parse_markdown context, content_index_path
else
content_index = ""
# parse the markdown the the readme
if file_exists(readme_path)
content = parse_markdown(context, readme_path)
else
content = "There is no #{source} for this project yet :( "
# run cloc
cloc sources.join(" "), (code_stats) ->
html = readme_template {
title: title,
context: context,
content: content,
content_index: content_index,
file_path: source,
path: path,
relative_base: relative_base,
package_json: package_json,
code_stats: code_stats,
gravatar: gravatar
}
console.log "docco: #{source} -> #{dest}"
write_file(dest, html)
generate_content = (context, dir) ->
walker = walk.walk(dir, { followLinks: false });
walker.on 'file', (root, fileStats, next) ->
# only match files that end in *.md
if fileStats.name.match(new RegExp ".md$")
src = "#{root}/#{fileStats.name}"
dest = destination(src.replace(context.config.content_dir, ""), context)
console.log "markdown: #{src} --> #{dest}"
html = parse_markdown context, src
html = content_template {
title: fileStats.name, context: context, content: html, file_path: fileStats.name, path: path, relative_base: relative_base
}
write_file dest, html
next()
# Write a file to the filesystem
write_file = (dest, contents) ->
target_dir = path.dirname(dest)
write_func = ->
fs.writeFile dest, contents, (err) -> throw err if err
fs.stat target_dir, (err, stats) ->
throw err if err and err.code != 'ENOENT'
return write_func() unless err
if err
exec "mkdir -p #{target_dir}", (err) ->
throw err if err
write_func()
# Parse a markdown file and return the HTML
parse_markdown = (context, src) ->
markdown = fs.readFileSync(src).toString()
return showdown.makeHtml markdown
cloc = (paths, callback) ->
exec "'#{__dirname}/../vendor/cloc.pl' --quiet --read-lang-def='#{__dirname}/../resources/cloc_definitions.txt' #{paths}", (err, stdout) ->
console.log "Calculating project stats failed #{err}" if err
callback stdout
#### Helpers & Setup
# Require our external dependencies, including **Showdown.js**
# (the JavaScript implementation of Markdown).
fs = require 'fs'
path = require 'path'
showdown = require('./../vendor/showdown').Showdown
jade = require 'jade'
dox = require 'dox'
gravatar = require 'gravatar'
_ = require 'underscore'
walk = require 'walk'
{spawn, exec} = require 'child_process'
# A list of the languages that Docco supports, mapping the file extension to
# the name of the Pygments lexer and the symbol that indicates a comment. To
# add another language to Docco's repertoire, add it here.
languages =
'.coffee':
name: 'coffee-script', symbol: '#'
'.js':
name: 'javascript', symbol: '//', multi_start: "/*", multi_end: "*/"
'.rb':
name: 'ruby', symbol: '#'
'.py':
name: 'python', symbol: '#'
'.java':
name: 'java', symbol: '//', multi_start: "/*", multi_end: "*/"
# Build out the appropriate matchers and delimiters for each language.
for ext, l of languages
# Does the line begin with a comment?
l.comment_matcher = new RegExp('^\\s*' + l.symbol + '\\s?')
# Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix))
# and interpolations...
l.comment_filter = new RegExp('(^#![/]|^\\s*#\\{)')
# The dividing token we feed into Pygments, to delimit the boundaries between
# sections.
l.divider_text = '\n' + l.symbol + 'DIVIDER\n'
# The mirror of `divider_text` that we expect Pygments to return. We can split
# on this to recover the original sections.
# Note: the class is "c" for Python and "c1" for the other languages
l.divider_html = new RegExp('\\n*<span class="c1?">' + l.symbol + 'DIVIDER<\\/span>\\n*')
# Since we'll only handle /* */ multilin comments for now, test for them explicitly
# Otherwise set the multi matchers to an unmatchable RegEx
if l.multi_start == "/*"
l.multi_start_matcher = new RegExp(/^[\s]*\/\*[.]*/)
else
l.multi_start_matcher = new RegExp(/a^/)
if l.multi_end == "*/"
l.multi_end_matcher = new RegExp(/.*\*\/.*/)
else
l.multi_end_matcher = new RegExp(/a^/)
# Get the current language we're documenting, based on the extension.
get_language = (source) -> languages[path.extname(source)]
# Compute the path of a source file relative to the docs folder
relative_base = (filepath, context) ->
result = path.dirname(filepath) + '/'
if result == '/' or result == '//' then '' else result
# Compute the destination HTML path for an input source file path. If the source
# is `lib/example.coffee`, the HTML will be at `docs/example.coffee.html`.
destination = (filepath, context) ->
base_path = relative_base filepath, context
"#{context.config.output_dir}/" + filepath + '.html'
# Ensure that the destination directory exists.
ensure_directory = (dir, callback) ->
exec "mkdir -p #{dir}", -> callback()
file_exists = (path) ->
try
return fs.lstatSync(path).isFile
catch ex
return false
# Create the template that we will use to generate the Docco HTML page.
docco_template = jade.compile fs.readFileSync(__dirname + '/../resources/docco.jade').toString(), { filename: __dirname + '/../resources/docco.jade' }
dox_template = jade.compile fs.readFileSync(__dirname + '/../resources/dox.jade').toString(), { filename: __dirname + '/../resources/dox.jade' }
content_template = jade.compile fs.readFileSync(__dirname + '/../resources/content.jade').toString(), { filename: __dirname + '/../resources/content.jade' }
# The CSS styles we'd like to apply to the documentation.
docco_styles = fs.readFileSync(__dirname + '/../resources/docco.css').toString()
# The start of each Pygments highlight block.
highlight_start = '<div class="highlight"><pre>'
# The end of each Pygments highlight block.
highlight_end = '</pre></div>'
# Process our arguments, passing an array of sources to generate docs for,
# and an optional relative root.
parse_args = (callback) ->
args = process.ARGV
project_name = ""
# Optional Project name following -name option
if args[0] == "-name"
args.shift()
project_name = args.shift()
# Sort the list of files and directories
args = args.sort()
# Preserving past behavior: if no args are given, we do nothing (eventually
# display help?)
return unless args.length
# Collect all of the directories or file paths to then pass onto the 'find'
# command
roots = (a.replace(/\/+$/, '') for a in args)
roots = roots.join(" ")
# Only include files that we know how to handle
lang_filter = for ext of languages
" -name '*#{ext}' "
lang_filter = lang_filter.join ' -o '
# Rather than deal with building a recursive tree walker via the fs module,
# let's save ourselves typing and testing and drop to the shell
exec "find #{roots} -type f \\( #{lang_filter} \\)", (err, stdout) ->
throw err if err
# Don't include hidden files, either
sources = stdout.split("\n").filter (file) -> file != '' and path.basename(file)[0] != '.'
console.log "docco: Recursively generating documentation for #{roots}"
callback(sources, project_name, args)
check_config = (context,pkg)->
defaults = {
# the primary CSS file to load
css: (__dirname + '/../resources/docco.css')
# show the timestamp on generated docs
show_timestamp: true,
# output directory for generated docs
output_dir: "docs",
# the projectname
project_name: context.options.project_name || '',
# source directory for any additional markdown documents including a
# index.md that will be included in the main generated page
content_dir: null
}
context.config = _.extend(defaults, pkg.docco_husky || {})
parse_args (sources, project_name, raw_paths) ->
# Rather than relying on globals, let's pass around a context w/ misc info
# that we require down the line.
context = sources: sources, options: { project_name: project_name }
package_path = process.cwd() + '/package.json'
try
package_json = if file_exists(package_path) then JSON.parse(fs.readFileSync(package_path).toString()) else {}
catch err
console.log "Error parsing package.json"
console.log err
check_config(context, package_json)
ensure_directory context.config.output_dir, ->
generate_readme(context, raw_paths,package_json)
fs.writeFile "#{context.config.output_dir}/docco.css", fs.readFileSync(context.config.css).toString()
files = sources[0..sources.length]
next_file = -> generate_documentation files.shift(), context, next_file if files.length
next_file()
if context.config.content_dir then generate_content context, context.config.content_dir
| 114726 | # > *forked from the origina [Docco](https://github.com/jashkenas/docco) project, updated with abandon*
#
# **Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style
# documentation generator. It produces HTML
# that displays your comments alongside your code. Comments are passed through
# [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
# passed through [Pygments](http://pygments.org/) syntax highlighting.
# This page is the result of running Docco against its own source file.
#
# If you install Docco, you can run it from the command-line:
#
# docco src/*.coffee
#
# ...will generate an HTML documentation page for each of the named source files,
# with a menu linking to the other pages, saving it into a `docs` folder.
#
# The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,
# and released under the MIT license.
#
# To install Docco, first make sure you have [Node.js](http://nodejs.org/),
# [Pygments](http://pygments.org/) (install the latest dev version of Pygments
# from [its Mercurial repo](http://dev.pocoo.org/hg/pygments-main)), and
# [CoffeeScript](http://coffeescript.org/). Then, with NPM:
#
# sudo npm install docco
#
# Docco can be used to process CoffeeScript, JavaScript, Ruby or Python files.
# Only single-line comments are processed -- block comments are ignored.
#
#### Partners in Crime:
#
# * If **Node.js** doesn't run on your platform, or you'd prefer a more
# convenient package, get [<NAME>](http://github.com/rtomayko)'s
# [Rocco](http://rtomayko.github.com/rocco/rocco.html), the Ruby port that's
# available as a gem.
#
# * If you're writing shell scripts, try
# [Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**,
# also by Mr. Tomayko.
#
# * If Python's more your speed, take a look at
# [<NAME>](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.com/pycco/).
#
# * For **Clojure** fans, [Fogus](http://blog.fogus.me/)'s
# [Marginalia](http://fogus.me/fun/marginalia/) is a bit of a departure from
# "quick-and-dirty", but it'll get the job done.
#
# * **Lua** enthusiasts can get their fix with
# [<NAME>](https://github.com/rgieseke)'s [Locco](http://rgieseke.github.com/locco/).
#
# * And if you happen to be a **.NET**
# aficionado, check out [<NAME>](https://github.com/dontangg)'s
# [Nocco](http://dontangg.github.com/nocco/).
#### Main Documentation Generation Functions
# Generate the documentation for a source file by reading it in, splitting it
# up into comment/code sections, highlighting them for the appropriate language,
# and merging them into an HTML template.
generate_documentation = (source, context, callback) ->
fs.readFile source, "utf-8", (error, code) ->
throw error if error
sections = parse source, code
highlight source, sections, ->
generate_source_html source, context, sections
callback()
# Given a string of source code, parse out each comment and the code that
# follows it, and create an individual **section** for it.
# Sections take the form:
#
# {
# docs_text: ...
# docs_html: ...
# code_text: ...
# code_html: ...
# }
#
parse = (source, code) ->
lines = code.split '\n'
sections = []
language = get_language source
has_code = docs_text = code_text = ''
in_multi = false
multi_accum = ""
save = (docs, code) ->
sections.push docs_text: docs, code_text: code
for line in lines
if line.match(language.multi_start_matcher) or in_multi
if has_code
save docs_text, code_text
has_code = docs_text = code_text = ''
# Found the start of a multiline comment line, set in_multi to true
# and begin accumulating lines untime we reach a line that finishes
# the multiline comment
in_multi = true
multi_accum += line + '\n'
# If we reached the end of a multiline comment, template the result
# and set in_multi to false, reset multi_accum
if line.match(language.multi_end_matcher)
in_multi = false
try
parsed = dox.parseComments( multi_accum )[0]
docs_text += dox_template(parsed)
catch error
console.log "Error parsing comments with Dox: #{error}"
docs_text = multi_accum
multi_accum = ''
else if line.match(language.comment_matcher) and not line.match(language.comment_filter)
if has_code
save docs_text, code_text
has_code = docs_text = code_text = ''
docs_text += line.replace(language.comment_matcher, '') + '\n'
else
has_code = yes
code_text += line + '\n'
save docs_text, code_text
sections
# Highlights a single chunk of CoffeeScript code, using **Pygments** over stdio,
# and runs the text of its corresponding comment through **Markdown**, using
# [Showdown.js](http://attacklab.net/showdown/).
#
# We process the entire file in a single call to Pygments by inserting little
# marker comments between each section and then splitting the result string
# wherever our markers occur.
highlight = (source, sections, callback) ->
language = get_language source
pygments = spawn 'pygmentize', ['-l', language.name, '-f', 'html', '-O', 'encoding=utf-8,tabsize=2']
output = ''
pygments.stderr.addListener 'data', (error) ->
console.error error.toString() if error
pygments.stdin.addListener 'error', (error) ->
console.error "Could not use Pygments to highlight the source."
process.exit 1
pygments.stdout.addListener 'data', (result) ->
output += result if result
pygments.addListener 'exit', ->
output = output.replace(highlight_start, '').replace(highlight_end, '')
fragments = output.split language.divider_html
for section, i in sections
section.code_html = highlight_start + fragments[i] + highlight_end
section.docs_html = showdown.makeHtml section.docs_text
callback()
if pygments.stdin.writable
pygments.stdin.write((section.code_text for section in sections).join(language.divider_text))
pygments.stdin.end()
# Once all of the code is finished highlighting, we can generate the HTML file
# and write out the documentation. Pass the completed sections into the template
# found in `resources/docco.jst`
generate_source_html = (source, context, sections) ->
title = path.basename source
dest = destination source, context
html = docco_template {
title: title, file_path: source, sections: sections, context: context, path: path, relative_base: relative_base
}
console.log "docco: #{source} -> #{dest}"
write_file(dest, html)
generate_readme = (context, sources, package_json) ->
title = "README"
dest = "#{context.config.output_dir}/index.html"
source = "README.md"
# README.md template to be use to generate the main REAME file
readme_template = jade.compile fs.readFileSync(__dirname + '/../resources/readme.jade').toString(), { filename: __dirname + '/../resources/readme.jade' }
readme_path = "#{process.cwd()}/#{source}"
content_index_path = "#{process.cwd()}/#{context.config.content_dir}/content_index.md"
console.log content_index_path
# generate the content index if it exists under the content sources
if file_exists(content_index_path)
content_index = parse_markdown context, content_index_path
else
content_index = ""
# parse the markdown the the readme
if file_exists(readme_path)
content = parse_markdown(context, readme_path)
else
content = "There is no #{source} for this project yet :( "
# run cloc
cloc sources.join(" "), (code_stats) ->
html = readme_template {
title: title,
context: context,
content: content,
content_index: content_index,
file_path: source,
path: path,
relative_base: relative_base,
package_json: package_json,
code_stats: code_stats,
gravatar: gravatar
}
console.log "docco: #{source} -> #{dest}"
write_file(dest, html)
generate_content = (context, dir) ->
walker = walk.walk(dir, { followLinks: false });
walker.on 'file', (root, fileStats, next) ->
# only match files that end in *.md
if fileStats.name.match(new RegExp ".md$")
src = "#{root}/#{fileStats.name}"
dest = destination(src.replace(context.config.content_dir, ""), context)
console.log "markdown: #{src} --> #{dest}"
html = parse_markdown context, src
html = content_template {
title: fileStats.name, context: context, content: html, file_path: fileStats.name, path: path, relative_base: relative_base
}
write_file dest, html
next()
# Write a file to the filesystem
write_file = (dest, contents) ->
target_dir = path.dirname(dest)
write_func = ->
fs.writeFile dest, contents, (err) -> throw err if err
fs.stat target_dir, (err, stats) ->
throw err if err and err.code != 'ENOENT'
return write_func() unless err
if err
exec "mkdir -p #{target_dir}", (err) ->
throw err if err
write_func()
# Parse a markdown file and return the HTML
parse_markdown = (context, src) ->
markdown = fs.readFileSync(src).toString()
return showdown.makeHtml markdown
cloc = (paths, callback) ->
exec "'#{__dirname}/../vendor/cloc.pl' --quiet --read-lang-def='#{__dirname}/../resources/cloc_definitions.txt' #{paths}", (err, stdout) ->
console.log "Calculating project stats failed #{err}" if err
callback stdout
#### Helpers & Setup
# Require our external dependencies, including **Showdown.js**
# (the JavaScript implementation of Markdown).
fs = require 'fs'
path = require 'path'
showdown = require('./../vendor/showdown').Showdown
jade = require 'jade'
dox = require 'dox'
gravatar = require 'gravatar'
_ = require 'underscore'
walk = require 'walk'
{spawn, exec} = require 'child_process'
# A list of the languages that Docco supports, mapping the file extension to
# the name of the Pygments lexer and the symbol that indicates a comment. To
# add another language to Docco's repertoire, add it here.
languages =
'.coffee':
name: 'coffee-script', symbol: '#'
'.js':
name: 'javascript', symbol: '//', multi_start: "/*", multi_end: "*/"
'.rb':
name: 'ruby', symbol: '#'
'.py':
name: 'python', symbol: '#'
'.java':
name: 'java', symbol: '//', multi_start: "/*", multi_end: "*/"
# Build out the appropriate matchers and delimiters for each language.
for ext, l of languages
# Does the line begin with a comment?
l.comment_matcher = new RegExp('^\\s*' + l.symbol + '\\s?')
# Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix))
# and interpolations...
l.comment_filter = new RegExp('(^#![/]|^\\s*#\\{)')
# The dividing token we feed into Pygments, to delimit the boundaries between
# sections.
l.divider_text = '\n' + l.symbol + 'DIVIDER\n'
# The mirror of `divider_text` that we expect Pygments to return. We can split
# on this to recover the original sections.
# Note: the class is "c" for Python and "c1" for the other languages
l.divider_html = new RegExp('\\n*<span class="c1?">' + l.symbol + 'DIVIDER<\\/span>\\n*')
# Since we'll only handle /* */ multilin comments for now, test for them explicitly
# Otherwise set the multi matchers to an unmatchable RegEx
if l.multi_start == "/*"
l.multi_start_matcher = new RegExp(/^[\s]*\/\*[.]*/)
else
l.multi_start_matcher = new RegExp(/a^/)
if l.multi_end == "*/"
l.multi_end_matcher = new RegExp(/.*\*\/.*/)
else
l.multi_end_matcher = new RegExp(/a^/)
# Get the current language we're documenting, based on the extension.
get_language = (source) -> languages[path.extname(source)]
# Compute the path of a source file relative to the docs folder
relative_base = (filepath, context) ->
result = path.dirname(filepath) + '/'
if result == '/' or result == '//' then '' else result
# Compute the destination HTML path for an input source file path. If the source
# is `lib/example.coffee`, the HTML will be at `docs/example.coffee.html`.
destination = (filepath, context) ->
base_path = relative_base filepath, context
"#{context.config.output_dir}/" + filepath + '.html'
# Ensure that the destination directory exists.
ensure_directory = (dir, callback) ->
exec "mkdir -p #{dir}", -> callback()
file_exists = (path) ->
try
return fs.lstatSync(path).isFile
catch ex
return false
# Create the template that we will use to generate the Docco HTML page.
docco_template = jade.compile fs.readFileSync(__dirname + '/../resources/docco.jade').toString(), { filename: __dirname + '/../resources/docco.jade' }
dox_template = jade.compile fs.readFileSync(__dirname + '/../resources/dox.jade').toString(), { filename: __dirname + '/../resources/dox.jade' }
content_template = jade.compile fs.readFileSync(__dirname + '/../resources/content.jade').toString(), { filename: __dirname + '/../resources/content.jade' }
# The CSS styles we'd like to apply to the documentation.
docco_styles = fs.readFileSync(__dirname + '/../resources/docco.css').toString()
# The start of each Pygments highlight block.
highlight_start = '<div class="highlight"><pre>'
# The end of each Pygments highlight block.
highlight_end = '</pre></div>'
# Process our arguments, passing an array of sources to generate docs for,
# and an optional relative root.
parse_args = (callback) ->
args = process.ARGV
project_name = ""
# Optional Project name following -name option
if args[0] == "-name"
args.shift()
project_name = args.shift()
# Sort the list of files and directories
args = args.sort()
# Preserving past behavior: if no args are given, we do nothing (eventually
# display help?)
return unless args.length
# Collect all of the directories or file paths to then pass onto the 'find'
# command
roots = (a.replace(/\/+$/, '') for a in args)
roots = roots.join(" ")
# Only include files that we know how to handle
lang_filter = for ext of languages
" -name '*#{ext}' "
lang_filter = lang_filter.join ' -o '
# Rather than deal with building a recursive tree walker via the fs module,
# let's save ourselves typing and testing and drop to the shell
exec "find #{roots} -type f \\( #{lang_filter} \\)", (err, stdout) ->
throw err if err
# Don't include hidden files, either
sources = stdout.split("\n").filter (file) -> file != '' and path.basename(file)[0] != '.'
console.log "docco: Recursively generating documentation for #{roots}"
callback(sources, project_name, args)
check_config = (context,pkg)->
defaults = {
# the primary CSS file to load
css: (__dirname + '/../resources/docco.css')
# show the timestamp on generated docs
show_timestamp: true,
# output directory for generated docs
output_dir: "docs",
# the projectname
project_name: context.options.project_name || '',
# source directory for any additional markdown documents including a
# index.md that will be included in the main generated page
content_dir: null
}
context.config = _.extend(defaults, pkg.docco_husky || {})
parse_args (sources, project_name, raw_paths) ->
# Rather than relying on globals, let's pass around a context w/ misc info
# that we require down the line.
context = sources: sources, options: { project_name: project_name }
package_path = process.cwd() + '/package.json'
try
package_json = if file_exists(package_path) then JSON.parse(fs.readFileSync(package_path).toString()) else {}
catch err
console.log "Error parsing package.json"
console.log err
check_config(context, package_json)
ensure_directory context.config.output_dir, ->
generate_readme(context, raw_paths,package_json)
fs.writeFile "#{context.config.output_dir}/docco.css", fs.readFileSync(context.config.css).toString()
files = sources[0..sources.length]
next_file = -> generate_documentation files.shift(), context, next_file if files.length
next_file()
if context.config.content_dir then generate_content context, context.config.content_dir
| true | # > *forked from the origina [Docco](https://github.com/jashkenas/docco) project, updated with abandon*
#
# **Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style
# documentation generator. It produces HTML
# that displays your comments alongside your code. Comments are passed through
# [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
# passed through [Pygments](http://pygments.org/) syntax highlighting.
# This page is the result of running Docco against its own source file.
#
# If you install Docco, you can run it from the command-line:
#
# docco src/*.coffee
#
# ...will generate an HTML documentation page for each of the named source files,
# with a menu linking to the other pages, saving it into a `docs` folder.
#
# The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,
# and released under the MIT license.
#
# To install Docco, first make sure you have [Node.js](http://nodejs.org/),
# [Pygments](http://pygments.org/) (install the latest dev version of Pygments
# from [its Mercurial repo](http://dev.pocoo.org/hg/pygments-main)), and
# [CoffeeScript](http://coffeescript.org/). Then, with NPM:
#
# sudo npm install docco
#
# Docco can be used to process CoffeeScript, JavaScript, Ruby or Python files.
# Only single-line comments are processed -- block comments are ignored.
#
#### Partners in Crime:
#
# * If **Node.js** doesn't run on your platform, or you'd prefer a more
# convenient package, get [PI:NAME:<NAME>END_PI](http://github.com/rtomayko)'s
# [Rocco](http://rtomayko.github.com/rocco/rocco.html), the Ruby port that's
# available as a gem.
#
# * If you're writing shell scripts, try
# [Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**,
# also by Mr. Tomayko.
#
# * If Python's more your speed, take a look at
# [PI:NAME:<NAME>END_PI](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.com/pycco/).
#
# * For **Clojure** fans, [Fogus](http://blog.fogus.me/)'s
# [Marginalia](http://fogus.me/fun/marginalia/) is a bit of a departure from
# "quick-and-dirty", but it'll get the job done.
#
# * **Lua** enthusiasts can get their fix with
# [PI:NAME:<NAME>END_PI](https://github.com/rgieseke)'s [Locco](http://rgieseke.github.com/locco/).
#
# * And if you happen to be a **.NET**
# aficionado, check out [PI:NAME:<NAME>END_PI](https://github.com/dontangg)'s
# [Nocco](http://dontangg.github.com/nocco/).
#### Main Documentation Generation Functions
# Generate the documentation for a source file by reading it in, splitting it
# up into comment/code sections, highlighting them for the appropriate language,
# and merging them into an HTML template.
generate_documentation = (source, context, callback) ->
fs.readFile source, "utf-8", (error, code) ->
throw error if error
sections = parse source, code
highlight source, sections, ->
generate_source_html source, context, sections
callback()
# Given a string of source code, parse out each comment and the code that
# follows it, and create an individual **section** for it.
# Sections take the form:
#
# {
# docs_text: ...
# docs_html: ...
# code_text: ...
# code_html: ...
# }
#
parse = (source, code) ->
lines = code.split '\n'
sections = []
language = get_language source
has_code = docs_text = code_text = ''
in_multi = false
multi_accum = ""
save = (docs, code) ->
sections.push docs_text: docs, code_text: code
for line in lines
if line.match(language.multi_start_matcher) or in_multi
if has_code
save docs_text, code_text
has_code = docs_text = code_text = ''
# Found the start of a multiline comment line, set in_multi to true
# and begin accumulating lines untime we reach a line that finishes
# the multiline comment
in_multi = true
multi_accum += line + '\n'
# If we reached the end of a multiline comment, template the result
# and set in_multi to false, reset multi_accum
if line.match(language.multi_end_matcher)
in_multi = false
try
parsed = dox.parseComments( multi_accum )[0]
docs_text += dox_template(parsed)
catch error
console.log "Error parsing comments with Dox: #{error}"
docs_text = multi_accum
multi_accum = ''
else if line.match(language.comment_matcher) and not line.match(language.comment_filter)
if has_code
save docs_text, code_text
has_code = docs_text = code_text = ''
docs_text += line.replace(language.comment_matcher, '') + '\n'
else
has_code = yes
code_text += line + '\n'
save docs_text, code_text
sections
# Highlights a single chunk of CoffeeScript code, using **Pygments** over stdio,
# and runs the text of its corresponding comment through **Markdown**, using
# [Showdown.js](http://attacklab.net/showdown/).
#
# We process the entire file in a single call to Pygments by inserting little
# marker comments between each section and then splitting the result string
# wherever our markers occur.
highlight = (source, sections, callback) ->
language = get_language source
pygments = spawn 'pygmentize', ['-l', language.name, '-f', 'html', '-O', 'encoding=utf-8,tabsize=2']
output = ''
pygments.stderr.addListener 'data', (error) ->
console.error error.toString() if error
pygments.stdin.addListener 'error', (error) ->
console.error "Could not use Pygments to highlight the source."
process.exit 1
pygments.stdout.addListener 'data', (result) ->
output += result if result
pygments.addListener 'exit', ->
output = output.replace(highlight_start, '').replace(highlight_end, '')
fragments = output.split language.divider_html
for section, i in sections
section.code_html = highlight_start + fragments[i] + highlight_end
section.docs_html = showdown.makeHtml section.docs_text
callback()
if pygments.stdin.writable
pygments.stdin.write((section.code_text for section in sections).join(language.divider_text))
pygments.stdin.end()
# Once all of the code is finished highlighting, we can generate the HTML file
# and write out the documentation. Pass the completed sections into the template
# found in `resources/docco.jst`
generate_source_html = (source, context, sections) ->
title = path.basename source
dest = destination source, context
html = docco_template {
title: title, file_path: source, sections: sections, context: context, path: path, relative_base: relative_base
}
console.log "docco: #{source} -> #{dest}"
write_file(dest, html)
generate_readme = (context, sources, package_json) ->
title = "README"
dest = "#{context.config.output_dir}/index.html"
source = "README.md"
# README.md template to be use to generate the main REAME file
readme_template = jade.compile fs.readFileSync(__dirname + '/../resources/readme.jade').toString(), { filename: __dirname + '/../resources/readme.jade' }
readme_path = "#{process.cwd()}/#{source}"
content_index_path = "#{process.cwd()}/#{context.config.content_dir}/content_index.md"
console.log content_index_path
# generate the content index if it exists under the content sources
if file_exists(content_index_path)
content_index = parse_markdown context, content_index_path
else
content_index = ""
# parse the markdown the the readme
if file_exists(readme_path)
content = parse_markdown(context, readme_path)
else
content = "There is no #{source} for this project yet :( "
# run cloc
cloc sources.join(" "), (code_stats) ->
html = readme_template {
title: title,
context: context,
content: content,
content_index: content_index,
file_path: source,
path: path,
relative_base: relative_base,
package_json: package_json,
code_stats: code_stats,
gravatar: gravatar
}
console.log "docco: #{source} -> #{dest}"
write_file(dest, html)
generate_content = (context, dir) ->
walker = walk.walk(dir, { followLinks: false });
walker.on 'file', (root, fileStats, next) ->
# only match files that end in *.md
if fileStats.name.match(new RegExp ".md$")
src = "#{root}/#{fileStats.name}"
dest = destination(src.replace(context.config.content_dir, ""), context)
console.log "markdown: #{src} --> #{dest}"
html = parse_markdown context, src
html = content_template {
title: fileStats.name, context: context, content: html, file_path: fileStats.name, path: path, relative_base: relative_base
}
write_file dest, html
next()
# Write a file to the filesystem
write_file = (dest, contents) ->
target_dir = path.dirname(dest)
write_func = ->
fs.writeFile dest, contents, (err) -> throw err if err
fs.stat target_dir, (err, stats) ->
throw err if err and err.code != 'ENOENT'
return write_func() unless err
if err
exec "mkdir -p #{target_dir}", (err) ->
throw err if err
write_func()
# Parse a markdown file and return the HTML
parse_markdown = (context, src) ->
markdown = fs.readFileSync(src).toString()
return showdown.makeHtml markdown
cloc = (paths, callback) ->
exec "'#{__dirname}/../vendor/cloc.pl' --quiet --read-lang-def='#{__dirname}/../resources/cloc_definitions.txt' #{paths}", (err, stdout) ->
console.log "Calculating project stats failed #{err}" if err
callback stdout
#### Helpers & Setup
# Require our external dependencies, including **Showdown.js**
# (the JavaScript implementation of Markdown).
fs = require 'fs'
path = require 'path'
showdown = require('./../vendor/showdown').Showdown
jade = require 'jade'
dox = require 'dox'
gravatar = require 'gravatar'
_ = require 'underscore'
walk = require 'walk'
{spawn, exec} = require 'child_process'
# A list of the languages that Docco supports, mapping the file extension to
# the name of the Pygments lexer and the symbol that indicates a comment. To
# add another language to Docco's repertoire, add it here.
languages =
'.coffee':
name: 'coffee-script', symbol: '#'
'.js':
name: 'javascript', symbol: '//', multi_start: "/*", multi_end: "*/"
'.rb':
name: 'ruby', symbol: '#'
'.py':
name: 'python', symbol: '#'
'.java':
name: 'java', symbol: '//', multi_start: "/*", multi_end: "*/"
# Build out the appropriate matchers and delimiters for each language.
for ext, l of languages
# Does the line begin with a comment?
l.comment_matcher = new RegExp('^\\s*' + l.symbol + '\\s?')
# Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix))
# and interpolations...
l.comment_filter = new RegExp('(^#![/]|^\\s*#\\{)')
# The dividing token we feed into Pygments, to delimit the boundaries between
# sections.
l.divider_text = '\n' + l.symbol + 'DIVIDER\n'
# The mirror of `divider_text` that we expect Pygments to return. We can split
# on this to recover the original sections.
# Note: the class is "c" for Python and "c1" for the other languages
l.divider_html = new RegExp('\\n*<span class="c1?">' + l.symbol + 'DIVIDER<\\/span>\\n*')
# Since we'll only handle /* */ multilin comments for now, test for them explicitly
# Otherwise set the multi matchers to an unmatchable RegEx
if l.multi_start == "/*"
l.multi_start_matcher = new RegExp(/^[\s]*\/\*[.]*/)
else
l.multi_start_matcher = new RegExp(/a^/)
if l.multi_end == "*/"
l.multi_end_matcher = new RegExp(/.*\*\/.*/)
else
l.multi_end_matcher = new RegExp(/a^/)
# Get the current language we're documenting, based on the extension.
get_language = (source) -> languages[path.extname(source)]
# Compute the path of a source file relative to the docs folder
relative_base = (filepath, context) ->
result = path.dirname(filepath) + '/'
if result == '/' or result == '//' then '' else result
# Compute the destination HTML path for an input source file path. If the source
# is `lib/example.coffee`, the HTML will be at `docs/example.coffee.html`.
destination = (filepath, context) ->
base_path = relative_base filepath, context
"#{context.config.output_dir}/" + filepath + '.html'
# Ensure that the destination directory exists.
ensure_directory = (dir, callback) ->
exec "mkdir -p #{dir}", -> callback()
file_exists = (path) ->
try
return fs.lstatSync(path).isFile
catch ex
return false
# Create the template that we will use to generate the Docco HTML page.
docco_template = jade.compile fs.readFileSync(__dirname + '/../resources/docco.jade').toString(), { filename: __dirname + '/../resources/docco.jade' }
dox_template = jade.compile fs.readFileSync(__dirname + '/../resources/dox.jade').toString(), { filename: __dirname + '/../resources/dox.jade' }
content_template = jade.compile fs.readFileSync(__dirname + '/../resources/content.jade').toString(), { filename: __dirname + '/../resources/content.jade' }
# The CSS styles we'd like to apply to the documentation.
docco_styles = fs.readFileSync(__dirname + '/../resources/docco.css').toString()
# The start of each Pygments highlight block.
highlight_start = '<div class="highlight"><pre>'
# The end of each Pygments highlight block.
highlight_end = '</pre></div>'
# Process our arguments, passing an array of sources to generate docs for,
# and an optional relative root.
parse_args = (callback) ->
args = process.ARGV
project_name = ""
# Optional Project name following -name option
if args[0] == "-name"
args.shift()
project_name = args.shift()
# Sort the list of files and directories
args = args.sort()
# Preserving past behavior: if no args are given, we do nothing (eventually
# display help?)
return unless args.length
# Collect all of the directories or file paths to then pass onto the 'find'
# command
roots = (a.replace(/\/+$/, '') for a in args)
roots = roots.join(" ")
# Only include files that we know how to handle
lang_filter = for ext of languages
" -name '*#{ext}' "
lang_filter = lang_filter.join ' -o '
# Rather than deal with building a recursive tree walker via the fs module,
# let's save ourselves typing and testing and drop to the shell
exec "find #{roots} -type f \\( #{lang_filter} \\)", (err, stdout) ->
throw err if err
# Don't include hidden files, either
sources = stdout.split("\n").filter (file) -> file != '' and path.basename(file)[0] != '.'
console.log "docco: Recursively generating documentation for #{roots}"
callback(sources, project_name, args)
check_config = (context,pkg)->
defaults = {
# the primary CSS file to load
css: (__dirname + '/../resources/docco.css')
# show the timestamp on generated docs
show_timestamp: true,
# output directory for generated docs
output_dir: "docs",
# the projectname
project_name: context.options.project_name || '',
# source directory for any additional markdown documents including a
# index.md that will be included in the main generated page
content_dir: null
}
context.config = _.extend(defaults, pkg.docco_husky || {})
parse_args (sources, project_name, raw_paths) ->
# Rather than relying on globals, let's pass around a context w/ misc info
# that we require down the line.
context = sources: sources, options: { project_name: project_name }
package_path = process.cwd() + '/package.json'
try
package_json = if file_exists(package_path) then JSON.parse(fs.readFileSync(package_path).toString()) else {}
catch err
console.log "Error parsing package.json"
console.log err
check_config(context, package_json)
ensure_directory context.config.output_dir, ->
generate_readme(context, raw_paths,package_json)
fs.writeFile "#{context.config.output_dir}/docco.css", fs.readFileSync(context.config.css).toString()
files = sources[0..sources.length]
next_file = -> generate_documentation files.shift(), context, next_file if files.length
next_file()
if context.config.content_dir then generate_content context, context.config.content_dir
|
[
{
"context": " require('../index')\n\n\nlome =\n admin1Name: \"Maritime\"\n countryName: \"Togolese Republic\"\n featureClas",
"end": 479,
"score": 0.6061056852340698,
"start": 476,
"tag": "NAME",
"value": "ime"
},
{
"context": " \"population\": 88485,\n \"admin2Name\": \"Fairfield County\",\n \"admin1Name\": \"Connecticut\",\n ",
"end": 3452,
"score": 0.9973869919776917,
"start": 3436,
"tag": "NAME",
"value": "Fairfield County"
},
{
"context": "rfield County\",\n \"admin1Name\": \"Connecticut\",\n \"countryName\": \"United States\"\n ",
"end": 3493,
"score": 0.8317368030548096,
"start": 3489,
"tag": "NAME",
"value": "icut"
},
{
"context": " \"id\": \"4839822\",\n \"name\": \"Norwalk\",\n \"latitude\": 41.1176,\n \"l",
"end": 3876,
"score": 0.9939029216766357,
"start": 3869,
"tag": "NAME",
"value": "Norwalk"
},
{
"context": " \"population\": 88485,\n \"admin2Name\": \"Fairfield County\",\n \"admin1Name\": \"Connecticut\",\n ",
"end": 4188,
"score": 0.9973543286323547,
"start": 4172,
"tag": "NAME",
"value": "Fairfield County"
},
{
"context": "\": \"Fairfield County\",\n \"admin1Name\": \"Connecticut\",\n \"countryName\": \"United States\"\n ",
"end": 4229,
"score": 0.8094709515571594,
"start": 4218,
"tag": "NAME",
"value": "Connecticut"
}
] | imports/incident-resolution/test/activeCases.test.coffee | ecohealthalliance/eidr-connect | 1 | import { chai } from 'meteor/practicalmeteor:chai'
import incidents from './incidents'
{
LocationTree,
convertAllIncidentsToDifferentials,
differentialIncidentsToSubIntervals,
subIntervalsToLP,
intervalToEndpoints,
removeOutlierIncidents,
createSupplementalIncidents,
extendSubIntervalsWithValues,
dailyRatesToActiveCases,
subIntervalsToDailyRates,
enumerateDateRange,
mapLocationsToMaxSubIntervals
} = require('../index')
lome =
admin1Name: "Maritime"
countryName: "Togolese Republic"
featureClass: "P"
featureCode: "PPLC"
id: "2365267"
name: "Lomé"
tongo =
countryName: "Togolese Republic"
featureClass: "A"
featureCode: "PCLI"
id: "2363686"
name: "Togolese Republic"
overlappingIncidents = [{
cases: 40
dateRange:
start: new Date("Dec 31 2010 UTC")
end: new Date("Jan 5 2011 UTC")
locations: [lome]
}, {
cases: 10
dateRange:
start: new Date("Jan 3 2011 UTC")
end: new Date("Jan 7 2011 UTC")
locations: [lome]
}]
describe 'Active Case Utils', ->
it 'can enumerate a date range', ->
result = enumerateDateRange(new Date('2010-10-10'), new Date('2010-11-10'))
chai.assert.equal(result.length, 31)
chai.assert.equal(""+result[0], ""+new Date('2010-10-10'))
chai.assert.equal(""+result.slice(-1)[0], ""+new Date('2010-11-09'))
it 'can convert sub-intervals to daily rates', ->
differentialIncidents = convertAllIncidentsToDifferentials(overlappingIncidents)
subIntervals = differentialIncidentsToSubIntervals(differentialIncidents)
extendSubIntervalsWithValues(differentialIncidents, subIntervals)
total = subIntervalsToDailyRates(subIntervals).slice(0, 5).reduce (sofar, [date, rate]) ->
sofar + rate
, 0
chai.assert.equal(total, 40)
it 'can convert sub-intervals to active cases', ->
differentialIncidents = convertAllIncidentsToDifferentials(overlappingIncidents)
subIntervals = differentialIncidentsToSubIntervals(differentialIncidents)
extendSubIntervalsWithValues(differentialIncidents, subIntervals)
maxRate = _.max(dailyRatesToActiveCases(subIntervalsToDailyRates(subIntervals), .9, {
startDate: "2011-01-01"
endDate: "2011-03-01"
}), ([date, rate])->
rate
)
chai.assert.equal(maxRate[0], "2011-01-04")
it 'creates a timeseries that covers the given date window', ->
norwalkIncidents = [
{
"_id": "6jAadicpuhkBvNEDd",
"locations": [
{
"id": "6252001",
"name": "United States",
"latitude": 39.76,
"longitude": -98.5,
"featureClass": "A",
"featureCode": "PCLI",
"countryCode": "US",
"admin1Code": "00",
"population": 310232863,
"countryName": "United States"
}
],
"dateRange": {
"start": "2018-02-08T00:00:00.000Z",
"end": "2018-02-09T00:00:00.000Z",
"type": "day"
},
"cases": 1
},
{
"_id": "o8rJrwcwBksQmodNF",
"locations": [
{
"id": "4839822",
"name": "Norwalk",
"latitude": 41.1176,
"longitude": -73.4079,
"featureClass": "P",
"featureCode": "PPL",
"countryCode": "US",
"admin1Code": "CT",
"admin2Code": "001",
"population": 88485,
"admin2Name": "Fairfield County",
"admin1Name": "Connecticut",
"countryName": "United States"
}
],
"dateRange": {
"start": "2018-02-08T00:00:00.000Z",
"end": "2018-02-09T00:00:00.000Z",
"type": "day"
},
"cases": 1
},
{
"_id": "te3KQKMuh6T5L3dds",
"locations": [
{
"id": "4839822",
"name": "Norwalk",
"latitude": 41.1176,
"longitude": -73.4079,
"featureClass": "P",
"featureCode": "PPL",
"countryCode": "US",
"admin1Code": "CT",
"admin2Code": "001",
"population": 88485,
"admin2Name": "Fairfield County",
"admin1Name": "Connecticut",
"countryName": "United States"
}
],
"dateRange": {
"start": "2017-12-01T00:00:00.000Z",
"end": "2018-02-18T00:00:00.000Z",
"type": "precise"
},
"cases": 20,
"type": "caseCount"
}
]
differentialIncidents = convertAllIncidentsToDifferentials(norwalkIncidents)
subIntervals = differentialIncidentsToSubIntervals(differentialIncidents)
extendSubIntervalsWithValues(differentialIncidents, subIntervals)
locationTree = LocationTree.from(subIntervals.map (x) -> x.location)
locationsToMaxSubintervals = mapLocationsToMaxSubIntervals(locationTree, subIntervals)
locationsToActiveCases = _.object(_.map(locationsToMaxSubintervals, (s, locationId) ->
[
locationId,
dailyRatesToActiveCases(subIntervalsToDailyRates(s), .9, {
startDate: "2018-02-07"
endDate: "2018-02-12"
})
]
))
_.zip(locationsToActiveCases["6252001"], locationsToActiveCases["4839822"]).forEach ([parent, child]) ->
chai.assert.equal(parent[0], child[0])
chai.expect(parent[1] + 0.1).to.be.above(child[1], parent[0])
| 154503 | import { chai } from 'meteor/practicalmeteor:chai'
import incidents from './incidents'
{
LocationTree,
convertAllIncidentsToDifferentials,
differentialIncidentsToSubIntervals,
subIntervalsToLP,
intervalToEndpoints,
removeOutlierIncidents,
createSupplementalIncidents,
extendSubIntervalsWithValues,
dailyRatesToActiveCases,
subIntervalsToDailyRates,
enumerateDateRange,
mapLocationsToMaxSubIntervals
} = require('../index')
lome =
admin1Name: "Marit<NAME>"
countryName: "Togolese Republic"
featureClass: "P"
featureCode: "PPLC"
id: "2365267"
name: "Lomé"
tongo =
countryName: "Togolese Republic"
featureClass: "A"
featureCode: "PCLI"
id: "2363686"
name: "Togolese Republic"
overlappingIncidents = [{
cases: 40
dateRange:
start: new Date("Dec 31 2010 UTC")
end: new Date("Jan 5 2011 UTC")
locations: [lome]
}, {
cases: 10
dateRange:
start: new Date("Jan 3 2011 UTC")
end: new Date("Jan 7 2011 UTC")
locations: [lome]
}]
describe 'Active Case Utils', ->
it 'can enumerate a date range', ->
result = enumerateDateRange(new Date('2010-10-10'), new Date('2010-11-10'))
chai.assert.equal(result.length, 31)
chai.assert.equal(""+result[0], ""+new Date('2010-10-10'))
chai.assert.equal(""+result.slice(-1)[0], ""+new Date('2010-11-09'))
it 'can convert sub-intervals to daily rates', ->
differentialIncidents = convertAllIncidentsToDifferentials(overlappingIncidents)
subIntervals = differentialIncidentsToSubIntervals(differentialIncidents)
extendSubIntervalsWithValues(differentialIncidents, subIntervals)
total = subIntervalsToDailyRates(subIntervals).slice(0, 5).reduce (sofar, [date, rate]) ->
sofar + rate
, 0
chai.assert.equal(total, 40)
it 'can convert sub-intervals to active cases', ->
differentialIncidents = convertAllIncidentsToDifferentials(overlappingIncidents)
subIntervals = differentialIncidentsToSubIntervals(differentialIncidents)
extendSubIntervalsWithValues(differentialIncidents, subIntervals)
maxRate = _.max(dailyRatesToActiveCases(subIntervalsToDailyRates(subIntervals), .9, {
startDate: "2011-01-01"
endDate: "2011-03-01"
}), ([date, rate])->
rate
)
chai.assert.equal(maxRate[0], "2011-01-04")
it 'creates a timeseries that covers the given date window', ->
norwalkIncidents = [
{
"_id": "6jAadicpuhkBvNEDd",
"locations": [
{
"id": "6252001",
"name": "United States",
"latitude": 39.76,
"longitude": -98.5,
"featureClass": "A",
"featureCode": "PCLI",
"countryCode": "US",
"admin1Code": "00",
"population": 310232863,
"countryName": "United States"
}
],
"dateRange": {
"start": "2018-02-08T00:00:00.000Z",
"end": "2018-02-09T00:00:00.000Z",
"type": "day"
},
"cases": 1
},
{
"_id": "o8rJrwcwBksQmodNF",
"locations": [
{
"id": "4839822",
"name": "Norwalk",
"latitude": 41.1176,
"longitude": -73.4079,
"featureClass": "P",
"featureCode": "PPL",
"countryCode": "US",
"admin1Code": "CT",
"admin2Code": "001",
"population": 88485,
"admin2Name": "<NAME>",
"admin1Name": "Connect<NAME>",
"countryName": "United States"
}
],
"dateRange": {
"start": "2018-02-08T00:00:00.000Z",
"end": "2018-02-09T00:00:00.000Z",
"type": "day"
},
"cases": 1
},
{
"_id": "te3KQKMuh6T5L3dds",
"locations": [
{
"id": "4839822",
"name": "<NAME>",
"latitude": 41.1176,
"longitude": -73.4079,
"featureClass": "P",
"featureCode": "PPL",
"countryCode": "US",
"admin1Code": "CT",
"admin2Code": "001",
"population": 88485,
"admin2Name": "<NAME>",
"admin1Name": "<NAME>",
"countryName": "United States"
}
],
"dateRange": {
"start": "2017-12-01T00:00:00.000Z",
"end": "2018-02-18T00:00:00.000Z",
"type": "precise"
},
"cases": 20,
"type": "caseCount"
}
]
differentialIncidents = convertAllIncidentsToDifferentials(norwalkIncidents)
subIntervals = differentialIncidentsToSubIntervals(differentialIncidents)
extendSubIntervalsWithValues(differentialIncidents, subIntervals)
locationTree = LocationTree.from(subIntervals.map (x) -> x.location)
locationsToMaxSubintervals = mapLocationsToMaxSubIntervals(locationTree, subIntervals)
locationsToActiveCases = _.object(_.map(locationsToMaxSubintervals, (s, locationId) ->
[
locationId,
dailyRatesToActiveCases(subIntervalsToDailyRates(s), .9, {
startDate: "2018-02-07"
endDate: "2018-02-12"
})
]
))
_.zip(locationsToActiveCases["6252001"], locationsToActiveCases["4839822"]).forEach ([parent, child]) ->
chai.assert.equal(parent[0], child[0])
chai.expect(parent[1] + 0.1).to.be.above(child[1], parent[0])
| true | import { chai } from 'meteor/practicalmeteor:chai'
import incidents from './incidents'
{
LocationTree,
convertAllIncidentsToDifferentials,
differentialIncidentsToSubIntervals,
subIntervalsToLP,
intervalToEndpoints,
removeOutlierIncidents,
createSupplementalIncidents,
extendSubIntervalsWithValues,
dailyRatesToActiveCases,
subIntervalsToDailyRates,
enumerateDateRange,
mapLocationsToMaxSubIntervals
} = require('../index')
lome =
admin1Name: "MaritPI:NAME:<NAME>END_PI"
countryName: "Togolese Republic"
featureClass: "P"
featureCode: "PPLC"
id: "2365267"
name: "Lomé"
tongo =
countryName: "Togolese Republic"
featureClass: "A"
featureCode: "PCLI"
id: "2363686"
name: "Togolese Republic"
overlappingIncidents = [{
cases: 40
dateRange:
start: new Date("Dec 31 2010 UTC")
end: new Date("Jan 5 2011 UTC")
locations: [lome]
}, {
cases: 10
dateRange:
start: new Date("Jan 3 2011 UTC")
end: new Date("Jan 7 2011 UTC")
locations: [lome]
}]
describe 'Active Case Utils', ->
it 'can enumerate a date range', ->
result = enumerateDateRange(new Date('2010-10-10'), new Date('2010-11-10'))
chai.assert.equal(result.length, 31)
chai.assert.equal(""+result[0], ""+new Date('2010-10-10'))
chai.assert.equal(""+result.slice(-1)[0], ""+new Date('2010-11-09'))
it 'can convert sub-intervals to daily rates', ->
differentialIncidents = convertAllIncidentsToDifferentials(overlappingIncidents)
subIntervals = differentialIncidentsToSubIntervals(differentialIncidents)
extendSubIntervalsWithValues(differentialIncidents, subIntervals)
total = subIntervalsToDailyRates(subIntervals).slice(0, 5).reduce (sofar, [date, rate]) ->
sofar + rate
, 0
chai.assert.equal(total, 40)
it 'can convert sub-intervals to active cases', ->
differentialIncidents = convertAllIncidentsToDifferentials(overlappingIncidents)
subIntervals = differentialIncidentsToSubIntervals(differentialIncidents)
extendSubIntervalsWithValues(differentialIncidents, subIntervals)
maxRate = _.max(dailyRatesToActiveCases(subIntervalsToDailyRates(subIntervals), .9, {
startDate: "2011-01-01"
endDate: "2011-03-01"
}), ([date, rate])->
rate
)
chai.assert.equal(maxRate[0], "2011-01-04")
it 'creates a timeseries that covers the given date window', ->
norwalkIncidents = [
{
"_id": "6jAadicpuhkBvNEDd",
"locations": [
{
"id": "6252001",
"name": "United States",
"latitude": 39.76,
"longitude": -98.5,
"featureClass": "A",
"featureCode": "PCLI",
"countryCode": "US",
"admin1Code": "00",
"population": 310232863,
"countryName": "United States"
}
],
"dateRange": {
"start": "2018-02-08T00:00:00.000Z",
"end": "2018-02-09T00:00:00.000Z",
"type": "day"
},
"cases": 1
},
{
"_id": "o8rJrwcwBksQmodNF",
"locations": [
{
"id": "4839822",
"name": "Norwalk",
"latitude": 41.1176,
"longitude": -73.4079,
"featureClass": "P",
"featureCode": "PPL",
"countryCode": "US",
"admin1Code": "CT",
"admin2Code": "001",
"population": 88485,
"admin2Name": "PI:NAME:<NAME>END_PI",
"admin1Name": "ConnectPI:NAME:<NAME>END_PI",
"countryName": "United States"
}
],
"dateRange": {
"start": "2018-02-08T00:00:00.000Z",
"end": "2018-02-09T00:00:00.000Z",
"type": "day"
},
"cases": 1
},
{
"_id": "te3KQKMuh6T5L3dds",
"locations": [
{
"id": "4839822",
"name": "PI:NAME:<NAME>END_PI",
"latitude": 41.1176,
"longitude": -73.4079,
"featureClass": "P",
"featureCode": "PPL",
"countryCode": "US",
"admin1Code": "CT",
"admin2Code": "001",
"population": 88485,
"admin2Name": "PI:NAME:<NAME>END_PI",
"admin1Name": "PI:NAME:<NAME>END_PI",
"countryName": "United States"
}
],
"dateRange": {
"start": "2017-12-01T00:00:00.000Z",
"end": "2018-02-18T00:00:00.000Z",
"type": "precise"
},
"cases": 20,
"type": "caseCount"
}
]
differentialIncidents = convertAllIncidentsToDifferentials(norwalkIncidents)
subIntervals = differentialIncidentsToSubIntervals(differentialIncidents)
extendSubIntervalsWithValues(differentialIncidents, subIntervals)
locationTree = LocationTree.from(subIntervals.map (x) -> x.location)
locationsToMaxSubintervals = mapLocationsToMaxSubIntervals(locationTree, subIntervals)
locationsToActiveCases = _.object(_.map(locationsToMaxSubintervals, (s, locationId) ->
[
locationId,
dailyRatesToActiveCases(subIntervalsToDailyRates(s), .9, {
startDate: "2018-02-07"
endDate: "2018-02-12"
})
]
))
_.zip(locationsToActiveCases["6252001"], locationsToActiveCases["4839822"]).forEach ([parent, child]) ->
chai.assert.equal(parent[0], child[0])
chai.expect(parent[1] + 0.1).to.be.above(child[1], parent[0])
|
[
{
"context": " ldap:\n binddn: ldap.binddn\n passwd: ldap.passwd\n uri: ldap.uri\n $ssh: ssh\n , ->\n ",
"end": 296,
"score": 0.9982772469520569,
"start": 285,
"tag": "PASSWORD",
"value": "ldap.passwd"
},
{
"context": "=nikita,#{ldap.suffix_dn}\"\n userPassword: 'secret'\n uid: 'nikita'\n objectClass: [ 'to",
"end": 429,
"score": 0.9995889663696289,
"start": 423,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "\n name: 'userPassword'\n value: 'newsecret'\n ]\n ]\n @ldap.delete\n dn:",
"end": 778,
"score": 0.9989827871322632,
"start": 769,
"tag": "PASSWORD",
"value": "newsecret"
},
{
"context": " ldap:\n binddn: ldap.binddn\n passwd: ldap.passwd\n uri: ldap.uri\n $ssh: ssh\n , ->\n ",
"end": 1253,
"score": 0.9988505244255066,
"start": 1242,
"tag": "PASSWORD",
"value": "ldap.passwd"
},
{
"context": "objectClass: [ 'top', 'posixGroup' ]\n cn: 'nikita'\n gidNumber: '3000'\n memberUid: ",
"end": 1418,
"score": 0.6448461413383484,
"start": 1415,
"tag": "NAME",
"value": "nik"
}
] | packages/ldap/test/modify.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
nikita = require '@nikitajs/core/lib'
{tags, config, ldap} = require './test'
they = require('mocha-they')(config)
return unless tags.ldap_user
describe 'ldap.modify', ->
they 'entry with password', ({ssh}) ->
nikita
ldap:
binddn: ldap.binddn
passwd: ldap.passwd
uri: ldap.uri
$ssh: ssh
, ->
entry =
dn: "cn=nikita,#{ldap.suffix_dn}"
userPassword: 'secret'
uid: 'nikita'
objectClass: [ 'top', 'account', 'posixAccount' ]
uidNumber: '9610'
gidNumber: '9610'
homeDirectory: '/home/nikita'
operations = [
dn: entry.dn
changetype: 'modify'
attributes: [
type: 'replace'
name: 'userPassword'
value: 'newsecret'
]
]
@ldap.delete
dn: entry.dn
{$status} = await @ldap.add
entry: entry
{$status} = await @ldap.modify
operations: operations
$status.should.be.true()
{$status} = await @ldap.modify
operations: operations
$status.should.be.false()
@ldap.delete
dn: entry.dn
they 'entry with array', ({ssh}) ->
nikita
ldap:
binddn: ldap.binddn
passwd: ldap.passwd
uri: ldap.uri
$ssh: ssh
, ->
entry =
dn: "cn=nikita,#{ldap.suffix_dn}"
objectClass: [ 'top', 'posixGroup' ]
cn: 'nikita'
gidNumber: '3000'
memberUid: '4001'
operations = [
dn: entry.dn
changetype: 'modify'
attributes: [
type: 'replace'
name: 'memberUid'
value: '4002'
,
type: 'add'
name: 'memberUid'
value: '4003'
]
]
@ldap.delete
dn: entry.dn
{$status} = await @ldap.add
entry: entry
{$status} = await @ldap.modify
operations: operations
$status.should.be.true()
{$status} = await @ldap.modify
operations: operations
$status.should.be.false()
@ldap.delete
dn: entry.dn
| 200925 |
nikita = require '@nikitajs/core/lib'
{tags, config, ldap} = require './test'
they = require('mocha-they')(config)
return unless tags.ldap_user
describe 'ldap.modify', ->
they 'entry with password', ({ssh}) ->
nikita
ldap:
binddn: ldap.binddn
passwd: <PASSWORD>
uri: ldap.uri
$ssh: ssh
, ->
entry =
dn: "cn=nikita,#{ldap.suffix_dn}"
userPassword: '<PASSWORD>'
uid: 'nikita'
objectClass: [ 'top', 'account', 'posixAccount' ]
uidNumber: '9610'
gidNumber: '9610'
homeDirectory: '/home/nikita'
operations = [
dn: entry.dn
changetype: 'modify'
attributes: [
type: 'replace'
name: 'userPassword'
value: '<PASSWORD>'
]
]
@ldap.delete
dn: entry.dn
{$status} = await @ldap.add
entry: entry
{$status} = await @ldap.modify
operations: operations
$status.should.be.true()
{$status} = await @ldap.modify
operations: operations
$status.should.be.false()
@ldap.delete
dn: entry.dn
they 'entry with array', ({ssh}) ->
nikita
ldap:
binddn: ldap.binddn
passwd: <PASSWORD>
uri: ldap.uri
$ssh: ssh
, ->
entry =
dn: "cn=nikita,#{ldap.suffix_dn}"
objectClass: [ 'top', 'posixGroup' ]
cn: '<NAME>ita'
gidNumber: '3000'
memberUid: '4001'
operations = [
dn: entry.dn
changetype: 'modify'
attributes: [
type: 'replace'
name: 'memberUid'
value: '4002'
,
type: 'add'
name: 'memberUid'
value: '4003'
]
]
@ldap.delete
dn: entry.dn
{$status} = await @ldap.add
entry: entry
{$status} = await @ldap.modify
operations: operations
$status.should.be.true()
{$status} = await @ldap.modify
operations: operations
$status.should.be.false()
@ldap.delete
dn: entry.dn
| true |
nikita = require '@nikitajs/core/lib'
{tags, config, ldap} = require './test'
they = require('mocha-they')(config)
return unless tags.ldap_user
describe 'ldap.modify', ->
they 'entry with password', ({ssh}) ->
nikita
ldap:
binddn: ldap.binddn
passwd: PI:PASSWORD:<PASSWORD>END_PI
uri: ldap.uri
$ssh: ssh
, ->
entry =
dn: "cn=nikita,#{ldap.suffix_dn}"
userPassword: 'PI:PASSWORD:<PASSWORD>END_PI'
uid: 'nikita'
objectClass: [ 'top', 'account', 'posixAccount' ]
uidNumber: '9610'
gidNumber: '9610'
homeDirectory: '/home/nikita'
operations = [
dn: entry.dn
changetype: 'modify'
attributes: [
type: 'replace'
name: 'userPassword'
value: 'PI:PASSWORD:<PASSWORD>END_PI'
]
]
@ldap.delete
dn: entry.dn
{$status} = await @ldap.add
entry: entry
{$status} = await @ldap.modify
operations: operations
$status.should.be.true()
{$status} = await @ldap.modify
operations: operations
$status.should.be.false()
@ldap.delete
dn: entry.dn
they 'entry with array', ({ssh}) ->
nikita
ldap:
binddn: ldap.binddn
passwd: PI:PASSWORD:<PASSWORD>END_PI
uri: ldap.uri
$ssh: ssh
, ->
entry =
dn: "cn=nikita,#{ldap.suffix_dn}"
objectClass: [ 'top', 'posixGroup' ]
cn: 'PI:NAME:<NAME>END_PIita'
gidNumber: '3000'
memberUid: '4001'
operations = [
dn: entry.dn
changetype: 'modify'
attributes: [
type: 'replace'
name: 'memberUid'
value: '4002'
,
type: 'add'
name: 'memberUid'
value: '4003'
]
]
@ldap.delete
dn: entry.dn
{$status} = await @ldap.add
entry: entry
{$status} = await @ldap.modify
operations: operations
$status.should.be.true()
{$status} = await @ldap.modify
operations: operations
$status.should.be.false()
@ldap.delete
dn: entry.dn
|
[
{
"context": "eDetection extends App.TrackFilters.Base\n name: 'Frei Chen Edge Detection'\n filterClass: WAGNER.FreiC",
"end": 87,
"score": 0.7083620429039001,
"start": 84,
"tag": "NAME",
"value": "Fre"
}
] | public-source/javascripts/models/trackFilters/freiChenEdgeDetection.coffee | lekevicius/vijual | 1 | class App.TrackFilters.FreiChenEdgeDetection extends App.TrackFilters.Base
name: 'Frei Chen Edge Detection'
filterClass: WAGNER.FreiChenEdgeDetectionPass
| 107147 | class App.TrackFilters.FreiChenEdgeDetection extends App.TrackFilters.Base
name: '<NAME>i Chen Edge Detection'
filterClass: WAGNER.FreiChenEdgeDetectionPass
| true | class App.TrackFilters.FreiChenEdgeDetection extends App.TrackFilters.Base
name: 'PI:NAME:<NAME>END_PIi Chen Edge Detection'
filterClass: WAGNER.FreiChenEdgeDetectionPass
|
[
{
"context": "# Helper of BanaJs\n# author: dreampuf(soddyque@gmail.com)\n\nassert = require \"assert\"\ncr",
"end": 37,
"score": 0.9996564984321594,
"start": 29,
"tag": "USERNAME",
"value": "dreampuf"
},
{
"context": "# Helper of BanaJs\n# author: dreampuf(soddyque@gmail.com)\n\nassert = require \"assert\"\ncrypto = require \"cry",
"end": 56,
"score": 0.9999232292175293,
"start": 38,
"tag": "EMAIL",
"value": "soddyque@gmail.com"
},
{
"context": " methd: \"GET\"\n query:\n key: \"AIzaSyD3_KyaIis7pklJsNXt_isG7QzkTYPmf2w\"\n q: ct\n source: source\n ",
"end": 3532,
"score": 0.9997643232345581,
"start": 3493,
"tag": "KEY",
"value": "AIzaSyD3_KyaIis7pklJsNXt_isG7QzkTYPmf2w"
}
] | helper.coffee | dreampuf/banajs | 3 | # Helper of BanaJs
# author: dreampuf(soddyque@gmail.com)
assert = require "assert"
crypto = require "crypto"
http = require "http"
https = require "https"
url = require "url"
md = require("node-markdown").Markdown
libxml = require "libxmljs"
request = require "request"
fs = require "fs"
helper = module.exports =
sha1: (data, type="sha1")->
allowtype = ["sha1", "md5", "sha256", "sha512"]
throw new Error("type Must in #{allowtype} but then #{type}") if type not in allowtype
sha1sum = crypto.createHash type
sha1sum.update data
sha1sum.digest "hex"
rand: (min=10, max=min)->
if min == max
Math.random()*min | 0
else
assert.ok min < max, "min(#{min}) MUST less then max(#{max})"
min + Math.random()*(max-min) | 0
randstr: do ()->
tmp = (String.fromCharCode i for i in [65..122] when i not in [91..96])
tmplen = tmp.length
(min=5, max=min)->
if min == max
(tmp[Math.random()*tmplen | 0] for i in [0..min]).join("")
else
assert.ok min < max, "min MUST less then max"
(tmp[Math.random()*tmplen | 0] for i in [min..(min + helper.rand(max-min))]).join("")
converthtml: do ()->
""" 生成类似于rST的文档目录结构 """
(html)->
tr = libxml.parseHtmlString html
fcd = tr.find "/html/body/*"
tree = []
push_node = (t, i) ->
t.push
tag : i.name()
text : i.text()
href : "##{i.text()}"
items : []
for i in fcd
iname = i.name()
if iname?[0] == "h"
tlen = if tree.length > 0 then tree.length - 1 else 0
if tree[-1]?.tag == iname
push_node tree, i
else if tree[tlen]?.tag
last = parseInt tree[tlen].tag[1..]
now = parseInt iname[1..]
if last < now
push_node tree[tlen].items, i
else
push_node tree, i
else
push_node tree, i
section = new libxml.Element tr, "section"
section.attr "id", i.text() # id: i.text()
header = new libxml.Element(tr, "header")
section.addChild header
nt = i.nextSibling()
pt = i.parent()
i.remove()
header.addChild i
if nt then nt.addPrevSibling section else pt.addChild section
[((i.toString() for i in tr.find("/html/body/*")).join ""), tree]
fetch_title : (html, len=20) ->
doc = libxml.parseHtmlString html
fcd = doc.find "//h1"
if fcd.length > 0
fcd[0].text()
else
nodes = doc.find "//*[starts-with(name(), 'h') and string-length(name())=2]"
#console.log html, (i.name() for i in nodes when /h\d/i.test(i.name())), "\n\n"
#if (i.name() for i in nodes when /h\d/i.test(i.name())).length == 0
# return null
if nodes.length == 0
return null
ret = nodes[0].text()#(i.text() for i in nodes).join("").replace(/\s+/g, "")
if ret.length > len
ret = "#{ ret[..len-3]}..."
ret
net_mt_google : do ()->
re_ret = /"translatedText": "([\w\W]+)"/g
(ct, source="zh-CN", target="en", cb=null)->
if arguments.length == 2 and typeof(source) == "function"
cb = source
source = "zh-CN"
if not cb
throw new Error "callback function is null!"
turl = url.format
host: "www.googleapis.com"
protocol: "https:"
pathname: "/language/translate/v2"
methd: "GET"
query:
key: "AIzaSyD3_KyaIis7pklJsNXt_isG7QzkTYPmf2w"
q: ct
source: source
target: target
callback: "BANAJS"
_: (new Date).getTime()
do (cb)->
request
method: "GET"
uri: turl
, (err, res, body)->
if err
ret = ""
else
body = body[body.indexOf("(")+1..body.length-3]
obj = JSON.parse body
ret = obj.data?.translations?[0].translatedText
cb ret
net_mt: do ()->
(ct, source="zh-CN", target="en", cb=null)->
if arguments.length == 2 and typeof(source) == "function"
cb = source
source = "zh-CN"
if not cb
throw new Error "callback function is null!"
turl = url.format
host: "api.microsofttranslator.com"
protocol: "http:"
pathname: "/V2/Ajax.svc/Translate"
methd: "GET"
query:
appid: "6D59EC9FB44063B2D9824487AF0DD071532E416D"
text: ct
from: source
to: target
_: (new Date).getTime()
do (cb)->
request
method: "GET"
uri: turl
, (err, res, body)->
cb body[2..body.length-2]
parser_content : (body, cb)->
ct_html = md body
title = (helper.fetch_title ct_html) or ""
ctime = new Date
helper.net_mt title,(path)->
if path
path = path.toLowerCase().replace /[\s\W]+/g, "_"
else
#TODO maybe more fail in this convert
path = "#{ctime.getYear()+1900}#{ctime.getMonth()+1}#{ctime.getDate()}"
cb
path: path
title: title
body: body
create: ctime
title_url : (title)->
title.replace(/["'\.]/g, "").trim().toLowerCase().replace(/[-+\s]+/g, "_")
update: (source, obj)->
for k, v of obj
source[k] = v
source
html_escape : (text)->
text.replace(/\&/g,'&')
.replace(/\</g, '<')
.replace(/\"/g, '"')
.replace(/\'/g, ''')
int2date : (int)->
d = new Date
d.setTime int
d
dateds : (dsint)->
od = helper.int2date dsint
n = new Date
ds = n - od
if 0 <= ds < 900000 #15 * 60 * 1000
"刚刚"
else if 900000 <= ds < 3600000 #1 * 60 * 60 * 1000
"一会儿前"
else if 3600000 <= ds < 28800000 #8 * 60 * 60 * 1000
"早先"
else if 28800000 <= ds < 86400000 #24 * 60 * 60 * 1000
"今天"
else if 86400000 <= ds < 172800000 # 48 h
"昨天"
else
d = ds / 86400000 | 0
if d <= 5
"#{ arab2chi[d] }天前"
else
"#{od.getYear()+1900}-#{od.getMonth()+1}-#{od.getDate()}"
ispic: do ()->
fmap =
png: 1
jpg: 1
jpge: 1
gif: 1
tiff: 1
bmp: 1
(filename)->
fmap[filename[-3..]]
walk: (dir, done)->
result = []
fs.readdir dir, (err, list)->
return done(err) if err
pending = list.length
return done(null, result) if not pending
list.forEach (file)->
file = dir + '/' + file
fs.stat file, (err, stat)->
if stat and stat.isDirectory()
helper.walk file, (err, res)->
console.log err if err
result = result.concat res
done(null, result) if not --pending
else
result.push file
done(null, result) if not --pending
arab2chi =
"1": "一", "2": "二", "3": "三", "4": "四", "5": "五"
"6": "六", "7": "七", "8": "八", "9": "九", "0": "〇"
if require.main == module #Unit Test
do ()-> #title_url
console.log helper.title_url "The other day I and founder of Excite.com ..."
do ()-> #parser content
helper.parser_content """<h1>你好BanaJS</h1>
<p>萨打算打算</p>
<h2>开篇</h2>
<p>aaaaaaaaaaaaa</p>
"""
, (obj)->
assert.equal "hello_banajs", obj.path
do ()-> #net_mt
#helper.net_mt_google "你好", (ret)->
# assert.equal ret, "Hello"
helper.net_mt "今天天气真好,不是刮风就是下雨", (ret)->
assert.equal ret, "Today the weather is really good, either windy or raining"
do ()-> #fetch_title
assert.equal helper.fetch_title("""<h1>ttt</h1>
<p>asdasd</p>""")
, "ttt"
assert.equal helper.fetch_title("""<p>some other story</p>
<h1>title</h1>""")
, "title"
assert.equal helper.fetch_title(md("""## asdasdad\r\nfsdafsadf\r\n\r\n## cccc\r\nsdfsadfsdfsadf"""))
, "asdasdad"
assert.equal helper.fetch_title(md("""ppppp
aaaaa
fffff""")), null
do ()-> #converthtml
assert.ok helper.converthtml """<h1>简介</h1>
<p>萨打算打算</p>
<h2>开篇</h2>
<p>asdasdasd</p>
<h3>测试</h3>
<p>asdadasd</p>
<h1>开始</h1>
<h2>1</h2>
<p>aaa</p>
<h2>2</h2>
<h2>3</h2>
<h3>内容</h3>
<p>aaaaaaaaaaaaa</p>
"""
do ()-> #sha1
assert.equal (helper.sha1 "soddy"), "65afec57cb15cfd8eeb080daaa9e538aa8f85469", "sha1 Error"
do ()-> #rand
assert.notEqual (helper.rand 5 for i in [0..5]), (helper.rand 5 for i in [0..5])
for i in [0..10]
assert.ok 5 <= helper.rand(5, 10) < 10 , "#{_ref} don't in [5,10)"
do ()-> #randstr
assert.notEqual (helper.randstr 10), (helper.randstr 10)
| 119430 | # Helper of BanaJs
# author: dreampuf(<EMAIL>)
assert = require "assert"
crypto = require "crypto"
http = require "http"
https = require "https"
url = require "url"
md = require("node-markdown").Markdown
libxml = require "libxmljs"
request = require "request"
fs = require "fs"
helper = module.exports =
sha1: (data, type="sha1")->
allowtype = ["sha1", "md5", "sha256", "sha512"]
throw new Error("type Must in #{allowtype} but then #{type}") if type not in allowtype
sha1sum = crypto.createHash type
sha1sum.update data
sha1sum.digest "hex"
rand: (min=10, max=min)->
if min == max
Math.random()*min | 0
else
assert.ok min < max, "min(#{min}) MUST less then max(#{max})"
min + Math.random()*(max-min) | 0
randstr: do ()->
tmp = (String.fromCharCode i for i in [65..122] when i not in [91..96])
tmplen = tmp.length
(min=5, max=min)->
if min == max
(tmp[Math.random()*tmplen | 0] for i in [0..min]).join("")
else
assert.ok min < max, "min MUST less then max"
(tmp[Math.random()*tmplen | 0] for i in [min..(min + helper.rand(max-min))]).join("")
converthtml: do ()->
""" 生成类似于rST的文档目录结构 """
(html)->
tr = libxml.parseHtmlString html
fcd = tr.find "/html/body/*"
tree = []
push_node = (t, i) ->
t.push
tag : i.name()
text : i.text()
href : "##{i.text()}"
items : []
for i in fcd
iname = i.name()
if iname?[0] == "h"
tlen = if tree.length > 0 then tree.length - 1 else 0
if tree[-1]?.tag == iname
push_node tree, i
else if tree[tlen]?.tag
last = parseInt tree[tlen].tag[1..]
now = parseInt iname[1..]
if last < now
push_node tree[tlen].items, i
else
push_node tree, i
else
push_node tree, i
section = new libxml.Element tr, "section"
section.attr "id", i.text() # id: i.text()
header = new libxml.Element(tr, "header")
section.addChild header
nt = i.nextSibling()
pt = i.parent()
i.remove()
header.addChild i
if nt then nt.addPrevSibling section else pt.addChild section
[((i.toString() for i in tr.find("/html/body/*")).join ""), tree]
fetch_title : (html, len=20) ->
doc = libxml.parseHtmlString html
fcd = doc.find "//h1"
if fcd.length > 0
fcd[0].text()
else
nodes = doc.find "//*[starts-with(name(), 'h') and string-length(name())=2]"
#console.log html, (i.name() for i in nodes when /h\d/i.test(i.name())), "\n\n"
#if (i.name() for i in nodes when /h\d/i.test(i.name())).length == 0
# return null
if nodes.length == 0
return null
ret = nodes[0].text()#(i.text() for i in nodes).join("").replace(/\s+/g, "")
if ret.length > len
ret = "#{ ret[..len-3]}..."
ret
net_mt_google : do ()->
re_ret = /"translatedText": "([\w\W]+)"/g
(ct, source="zh-CN", target="en", cb=null)->
if arguments.length == 2 and typeof(source) == "function"
cb = source
source = "zh-CN"
if not cb
throw new Error "callback function is null!"
turl = url.format
host: "www.googleapis.com"
protocol: "https:"
pathname: "/language/translate/v2"
methd: "GET"
query:
key: "<KEY>"
q: ct
source: source
target: target
callback: "BANAJS"
_: (new Date).getTime()
do (cb)->
request
method: "GET"
uri: turl
, (err, res, body)->
if err
ret = ""
else
body = body[body.indexOf("(")+1..body.length-3]
obj = JSON.parse body
ret = obj.data?.translations?[0].translatedText
cb ret
net_mt: do ()->
(ct, source="zh-CN", target="en", cb=null)->
if arguments.length == 2 and typeof(source) == "function"
cb = source
source = "zh-CN"
if not cb
throw new Error "callback function is null!"
turl = url.format
host: "api.microsofttranslator.com"
protocol: "http:"
pathname: "/V2/Ajax.svc/Translate"
methd: "GET"
query:
appid: "6D59EC9FB44063B2D9824487AF0DD071532E416D"
text: ct
from: source
to: target
_: (new Date).getTime()
do (cb)->
request
method: "GET"
uri: turl
, (err, res, body)->
cb body[2..body.length-2]
parser_content : (body, cb)->
ct_html = md body
title = (helper.fetch_title ct_html) or ""
ctime = new Date
helper.net_mt title,(path)->
if path
path = path.toLowerCase().replace /[\s\W]+/g, "_"
else
#TODO maybe more fail in this convert
path = "#{ctime.getYear()+1900}#{ctime.getMonth()+1}#{ctime.getDate()}"
cb
path: path
title: title
body: body
create: ctime
title_url : (title)->
title.replace(/["'\.]/g, "").trim().toLowerCase().replace(/[-+\s]+/g, "_")
update: (source, obj)->
for k, v of obj
source[k] = v
source
html_escape : (text)->
text.replace(/\&/g,'&')
.replace(/\</g, '<')
.replace(/\"/g, '"')
.replace(/\'/g, ''')
int2date : (int)->
d = new Date
d.setTime int
d
dateds : (dsint)->
od = helper.int2date dsint
n = new Date
ds = n - od
if 0 <= ds < 900000 #15 * 60 * 1000
"刚刚"
else if 900000 <= ds < 3600000 #1 * 60 * 60 * 1000
"一会儿前"
else if 3600000 <= ds < 28800000 #8 * 60 * 60 * 1000
"早先"
else if 28800000 <= ds < 86400000 #24 * 60 * 60 * 1000
"今天"
else if 86400000 <= ds < 172800000 # 48 h
"昨天"
else
d = ds / 86400000 | 0
if d <= 5
"#{ arab2chi[d] }天前"
else
"#{od.getYear()+1900}-#{od.getMonth()+1}-#{od.getDate()}"
ispic: do ()->
fmap =
png: 1
jpg: 1
jpge: 1
gif: 1
tiff: 1
bmp: 1
(filename)->
fmap[filename[-3..]]
walk: (dir, done)->
result = []
fs.readdir dir, (err, list)->
return done(err) if err
pending = list.length
return done(null, result) if not pending
list.forEach (file)->
file = dir + '/' + file
fs.stat file, (err, stat)->
if stat and stat.isDirectory()
helper.walk file, (err, res)->
console.log err if err
result = result.concat res
done(null, result) if not --pending
else
result.push file
done(null, result) if not --pending
arab2chi =
"1": "一", "2": "二", "3": "三", "4": "四", "5": "五"
"6": "六", "7": "七", "8": "八", "9": "九", "0": "〇"
if require.main == module #Unit Test
do ()-> #title_url
console.log helper.title_url "The other day I and founder of Excite.com ..."
do ()-> #parser content
helper.parser_content """<h1>你好BanaJS</h1>
<p>萨打算打算</p>
<h2>开篇</h2>
<p>aaaaaaaaaaaaa</p>
"""
, (obj)->
assert.equal "hello_banajs", obj.path
do ()-> #net_mt
#helper.net_mt_google "你好", (ret)->
# assert.equal ret, "Hello"
helper.net_mt "今天天气真好,不是刮风就是下雨", (ret)->
assert.equal ret, "Today the weather is really good, either windy or raining"
do ()-> #fetch_title
assert.equal helper.fetch_title("""<h1>ttt</h1>
<p>asdasd</p>""")
, "ttt"
assert.equal helper.fetch_title("""<p>some other story</p>
<h1>title</h1>""")
, "title"
assert.equal helper.fetch_title(md("""## asdasdad\r\nfsdafsadf\r\n\r\n## cccc\r\nsdfsadfsdfsadf"""))
, "asdasdad"
assert.equal helper.fetch_title(md("""ppppp
aaaaa
fffff""")), null
do ()-> #converthtml
assert.ok helper.converthtml """<h1>简介</h1>
<p>萨打算打算</p>
<h2>开篇</h2>
<p>asdasdasd</p>
<h3>测试</h3>
<p>asdadasd</p>
<h1>开始</h1>
<h2>1</h2>
<p>aaa</p>
<h2>2</h2>
<h2>3</h2>
<h3>内容</h3>
<p>aaaaaaaaaaaaa</p>
"""
do ()-> #sha1
assert.equal (helper.sha1 "soddy"), "65afec57cb15cfd8eeb080daaa9e538aa8f85469", "sha1 Error"
do ()-> #rand
assert.notEqual (helper.rand 5 for i in [0..5]), (helper.rand 5 for i in [0..5])
for i in [0..10]
assert.ok 5 <= helper.rand(5, 10) < 10 , "#{_ref} don't in [5,10)"
do ()-> #randstr
assert.notEqual (helper.randstr 10), (helper.randstr 10)
| true | # Helper of BanaJs
# author: dreampuf(PI:EMAIL:<EMAIL>END_PI)
assert = require "assert"
crypto = require "crypto"
http = require "http"
https = require "https"
url = require "url"
md = require("node-markdown").Markdown
libxml = require "libxmljs"
request = require "request"
fs = require "fs"
helper = module.exports =
sha1: (data, type="sha1")->
allowtype = ["sha1", "md5", "sha256", "sha512"]
throw new Error("type Must in #{allowtype} but then #{type}") if type not in allowtype
sha1sum = crypto.createHash type
sha1sum.update data
sha1sum.digest "hex"
rand: (min=10, max=min)->
if min == max
Math.random()*min | 0
else
assert.ok min < max, "min(#{min}) MUST less then max(#{max})"
min + Math.random()*(max-min) | 0
randstr: do ()->
tmp = (String.fromCharCode i for i in [65..122] when i not in [91..96])
tmplen = tmp.length
(min=5, max=min)->
if min == max
(tmp[Math.random()*tmplen | 0] for i in [0..min]).join("")
else
assert.ok min < max, "min MUST less then max"
(tmp[Math.random()*tmplen | 0] for i in [min..(min + helper.rand(max-min))]).join("")
converthtml: do ()->
""" 生成类似于rST的文档目录结构 """
(html)->
tr = libxml.parseHtmlString html
fcd = tr.find "/html/body/*"
tree = []
push_node = (t, i) ->
t.push
tag : i.name()
text : i.text()
href : "##{i.text()}"
items : []
for i in fcd
iname = i.name()
if iname?[0] == "h"
tlen = if tree.length > 0 then tree.length - 1 else 0
if tree[-1]?.tag == iname
push_node tree, i
else if tree[tlen]?.tag
last = parseInt tree[tlen].tag[1..]
now = parseInt iname[1..]
if last < now
push_node tree[tlen].items, i
else
push_node tree, i
else
push_node tree, i
section = new libxml.Element tr, "section"
section.attr "id", i.text() # id: i.text()
header = new libxml.Element(tr, "header")
section.addChild header
nt = i.nextSibling()
pt = i.parent()
i.remove()
header.addChild i
if nt then nt.addPrevSibling section else pt.addChild section
[((i.toString() for i in tr.find("/html/body/*")).join ""), tree]
fetch_title : (html, len=20) ->
doc = libxml.parseHtmlString html
fcd = doc.find "//h1"
if fcd.length > 0
fcd[0].text()
else
nodes = doc.find "//*[starts-with(name(), 'h') and string-length(name())=2]"
#console.log html, (i.name() for i in nodes when /h\d/i.test(i.name())), "\n\n"
#if (i.name() for i in nodes when /h\d/i.test(i.name())).length == 0
# return null
if nodes.length == 0
return null
ret = nodes[0].text()#(i.text() for i in nodes).join("").replace(/\s+/g, "")
if ret.length > len
ret = "#{ ret[..len-3]}..."
ret
net_mt_google : do ()->
re_ret = /"translatedText": "([\w\W]+)"/g
(ct, source="zh-CN", target="en", cb=null)->
if arguments.length == 2 and typeof(source) == "function"
cb = source
source = "zh-CN"
if not cb
throw new Error "callback function is null!"
turl = url.format
host: "www.googleapis.com"
protocol: "https:"
pathname: "/language/translate/v2"
methd: "GET"
query:
key: "PI:KEY:<KEY>END_PI"
q: ct
source: source
target: target
callback: "BANAJS"
_: (new Date).getTime()
do (cb)->
request
method: "GET"
uri: turl
, (err, res, body)->
if err
ret = ""
else
body = body[body.indexOf("(")+1..body.length-3]
obj = JSON.parse body
ret = obj.data?.translations?[0].translatedText
cb ret
net_mt: do ()->
(ct, source="zh-CN", target="en", cb=null)->
if arguments.length == 2 and typeof(source) == "function"
cb = source
source = "zh-CN"
if not cb
throw new Error "callback function is null!"
turl = url.format
host: "api.microsofttranslator.com"
protocol: "http:"
pathname: "/V2/Ajax.svc/Translate"
methd: "GET"
query:
appid: "6D59EC9FB44063B2D9824487AF0DD071532E416D"
text: ct
from: source
to: target
_: (new Date).getTime()
do (cb)->
request
method: "GET"
uri: turl
, (err, res, body)->
cb body[2..body.length-2]
parser_content : (body, cb)->
ct_html = md body
title = (helper.fetch_title ct_html) or ""
ctime = new Date
helper.net_mt title,(path)->
if path
path = path.toLowerCase().replace /[\s\W]+/g, "_"
else
#TODO maybe more fail in this convert
path = "#{ctime.getYear()+1900}#{ctime.getMonth()+1}#{ctime.getDate()}"
cb
path: path
title: title
body: body
create: ctime
title_url : (title)->
title.replace(/["'\.]/g, "").trim().toLowerCase().replace(/[-+\s]+/g, "_")
update: (source, obj)->
for k, v of obj
source[k] = v
source
html_escape : (text)->
text.replace(/\&/g,'&')
.replace(/\</g, '<')
.replace(/\"/g, '"')
.replace(/\'/g, ''')
int2date : (int)->
d = new Date
d.setTime int
d
dateds : (dsint)->
od = helper.int2date dsint
n = new Date
ds = n - od
if 0 <= ds < 900000 #15 * 60 * 1000
"刚刚"
else if 900000 <= ds < 3600000 #1 * 60 * 60 * 1000
"一会儿前"
else if 3600000 <= ds < 28800000 #8 * 60 * 60 * 1000
"早先"
else if 28800000 <= ds < 86400000 #24 * 60 * 60 * 1000
"今天"
else if 86400000 <= ds < 172800000 # 48 h
"昨天"
else
d = ds / 86400000 | 0
if d <= 5
"#{ arab2chi[d] }天前"
else
"#{od.getYear()+1900}-#{od.getMonth()+1}-#{od.getDate()}"
ispic: do ()->
fmap =
png: 1
jpg: 1
jpge: 1
gif: 1
tiff: 1
bmp: 1
(filename)->
fmap[filename[-3..]]
walk: (dir, done)->
result = []
fs.readdir dir, (err, list)->
return done(err) if err
pending = list.length
return done(null, result) if not pending
list.forEach (file)->
file = dir + '/' + file
fs.stat file, (err, stat)->
if stat and stat.isDirectory()
helper.walk file, (err, res)->
console.log err if err
result = result.concat res
done(null, result) if not --pending
else
result.push file
done(null, result) if not --pending
arab2chi =
"1": "一", "2": "二", "3": "三", "4": "四", "5": "五"
"6": "六", "7": "七", "8": "八", "9": "九", "0": "〇"
if require.main == module #Unit Test
do ()-> #title_url
console.log helper.title_url "The other day I and founder of Excite.com ..."
do ()-> #parser content
helper.parser_content """<h1>你好BanaJS</h1>
<p>萨打算打算</p>
<h2>开篇</h2>
<p>aaaaaaaaaaaaa</p>
"""
, (obj)->
assert.equal "hello_banajs", obj.path
do ()-> #net_mt
#helper.net_mt_google "你好", (ret)->
# assert.equal ret, "Hello"
helper.net_mt "今天天气真好,不是刮风就是下雨", (ret)->
assert.equal ret, "Today the weather is really good, either windy or raining"
do ()-> #fetch_title
assert.equal helper.fetch_title("""<h1>ttt</h1>
<p>asdasd</p>""")
, "ttt"
assert.equal helper.fetch_title("""<p>some other story</p>
<h1>title</h1>""")
, "title"
assert.equal helper.fetch_title(md("""## asdasdad\r\nfsdafsadf\r\n\r\n## cccc\r\nsdfsadfsdfsadf"""))
, "asdasdad"
assert.equal helper.fetch_title(md("""ppppp
aaaaa
fffff""")), null
do ()-> #converthtml
assert.ok helper.converthtml """<h1>简介</h1>
<p>萨打算打算</p>
<h2>开篇</h2>
<p>asdasdasd</p>
<h3>测试</h3>
<p>asdadasd</p>
<h1>开始</h1>
<h2>1</h2>
<p>aaa</p>
<h2>2</h2>
<h2>3</h2>
<h3>内容</h3>
<p>aaaaaaaaaaaaa</p>
"""
do ()-> #sha1
assert.equal (helper.sha1 "soddy"), "65afec57cb15cfd8eeb080daaa9e538aa8f85469", "sha1 Error"
do ()-> #rand
assert.notEqual (helper.rand 5 for i in [0..5]), (helper.rand 5 for i in [0..5])
for i in [0..10]
assert.ok 5 <= helper.rand(5, 10) < 10 , "#{_ref} don't in [5,10)"
do ()-> #randstr
assert.notEqual (helper.randstr 10), (helper.randstr 10)
|
[
{
"context": "@memoize 'wingY4', -> - (-@wingY2() + @la())\n\n # DIEDERICH\n M_Prof: @memoize 'M_Prof', -> @cruisingSpeed() ",
"end": 2876,
"score": 0.9892868995666504,
"start": 2867,
"tag": "NAME",
"value": "DIEDERICH"
}
] | app/js/lib/apps/liftDistribution/models/calculator.coffee | velaluqa/aircraft-construction-apps | 0 | # coding: utf-8
ILR.LiftDistribution ?= {}
ILR.LiftDistribution.Models ?= {}
class ILR.LiftDistribution.Models.Calculator extends ILR.Models.BaseCalculator
curveGroups: [['gamma', 'gamma_a', 'gamma_b', 'elliptic', 'C_a'], ['C_A'], ['geometry']]
COF = [
[ 2.1511 , 0.009 , -7.3509 , 7.3094 , -2.3048, -0.4104 ]
[ 1.7988 , 0.4009, -7.887 , 17.856 , -23.375 , 10.867 ]
[ 1.53045, 0.2337, -3.75395, 5.9553 , -6.447 , 2.31195 ]
[ 1.2621 , 0.0665, 0.3791 , -5.9454 , 10.481 , -6.2431 ]
[ 1.08715, 0.1467, 4.39155, -16.4117, 20.644 , -9.88955 ]
[ 0.9122 , 0.2209, 8.404 , -26.878 , 30.807 , -13.536 ]
[ 0.6533 , 1.3704, 6.9543 , -25.579 , 29.78 , -13.249 ]
[ 0.559 , 0.8908, 11.602 , -37.973 , 44.477 , -19.627 ]
]
accuracy: 50
interpolationTension: 0.25
constructor: (options = {}) ->
super(_.defaults(options, required: ['liftDistribution']))
minX: @reactive 'minX', -> 0
maxX: @reactive 'maxX', -> 1.0
xRange: (func) -> 1.0
# Streckung
aspectRatio: @reactive 'aspectRatio', -> @liftDistribution.get('aspectRatio')
# Verwindung
linearTwist: @reactive 'linearTwist', -> @liftDistribution.get('linearTwist')
linearTwistRad: @reactive 'linearTwistRad', -> @linearTwist() * Math.PI / 180.0
# Pfeilung
sweep: @reactive 'sweep', -> @liftDistribution.get('sweep')
sweepRad: @reactive 'sqeepRad', -> @sweep() * Math.PI / 180.0
# Zuspitzung
taperRatio: @reactive 'taperRatio', -> @liftDistribution.get('taperRatio')
# C_A
liftCoefficient: @reactive 'liftCoefficient', -> @liftDistribution.get('liftCoefficient')
# M_Reise
cruisingSpeed: @reactive 'cruisingSpeed', -> @liftDistribution.get('cruisingSpeed')
# Spannweite
l: @reactive 'wingSpan', -> @liftDistribution.get('wingSpan')
# WING GRAPHIC
wing: @memoize 'wing', -> null
Phi_VK: @memoize 'Phi_VK', -> Math.atan( Math.tan(@sweepRad()) + (1 - @taperRatio()) / (@aspectRatio() * (1 + @taperRatio()))) / Math.PI * 180.0
dya: @memoize 'dya', -> Math.tan(@sweepRad()) * @l();
yl: @memoize 'yl', -> 2 * @l() / @aspectRatio()
la: @memoize 'la', -> 2 * @yl() / (1 / @taperRatio() + 1)
li: @memoize 'li', -> @la() / @taperRatio()
wingY01: @memoize 'wingY01', -> -1 * (- @yl() / 4 - @dya() / 2)
wingY02: @memoize 'wingY02', -> -1 * (- @wingY01() + @dya())
wingX1: @memoize 'wingX1', -> 0
wingY1: @memoize 'wingY1', -> - (- @wingY01() - @li()/4)
wingX2: @memoize 'wingX2', -> 1
wingY2: @memoize 'wingY2', -> + (@wingY02() + @la()/4)
wingX3: @memoize 'wingX3', -> 0
wingY3: @memoize 'wingY3', -> - (-@wingY1() + @li())
wingX4: @memoize 'wingX4', -> 1
wingY4: @memoize 'wingY4', -> - (-@wingY2() + @la())
# DIEDERICH
M_Prof: @memoize 'M_Prof', -> @cruisingSpeed() * Math.sqrt(Math.cos(@sweepRad()))
c_a_: @memoize 'c_a_', -> 2 * Math.PI / Math.sqrt(1 - Math.pow(@M_Prof(), 2))
FF: @memoize 'FF', -> @aspectRatio() / @c_a_() * 2 * Math.PI / Math.cos(@sweepRad())
k0: @memoize 'k0', ->
FF = @FF()
0.2692 * FF - 0.0387 * Math.pow(FF, 2) + 0.002951 * Math.pow(FF, 3) - 0.0001106 * Math.pow(FF, 4) + 1.559 * Math.pow(10, -6) * Math.pow(FF, 5)
k1: @memoize 'k1', ->
F = @FF()
0.3064 + F * (0.05185 - 0.0014 * F)
c1: @memoize 'c1', ->
F = @FF()
0.003647 + F * (0.05614 - 0.0009842 * F)
c2: @memoize 'c2', ->
F = @FF()
1 + F * (0.002721 * F - 0.1098)
c3: @memoize 'c3', ->
F = @FF()
-0.008265 + F * (0.05493 - 0.001816 * F)
C_A_: @memoize 'C_A_', ->
@c_a_() * @k0() * Math.cos(@sweepRad())
Phi_e: @memoize 'Phi_e', ->
Math.atan(Math.tan(@sweepRad()) / Math.sqrt(1 - Math.pow(@cruisingSpeed(), 2)))
cof: @memoize 'cof', ->
phi = @Phi_e()
indices = if phi < -30 then [0, 1]
else if -30 <= phi < -15 then [1, 2]
else if -15 <= phi < 0 then [2, 3]
else if 0 <= phi < 15 then [3, 4]
else if 15 <= phi < 30 then [4, 5]
else if 30 <= phi < 45 then [5, 6]
else if 45 <= phi then [6, 7]
upAndLow = _.zip.apply(_, (COF[i] for i in indices))
m = ((low - up)/15 for [up, low] in upAndLow)
n = COF[3] # at 0°
m[i]*phi + n[i] for i in [0...m.length]
f: @reactive 'f', (n) ->
c = @cof()
c[0] + c[1]*n + c[2]*Math.pow(n,2) + c[3]*Math.pow(n,3) + c[4]*Math.pow(n,4) + c[5]*Math.pow(n,5)
lm_l: @reactive 'lm_l', (n) ->
@yl() / (@la() / @taperRatio() * (1 - n * (1 - @taperRatio())))
l_lm: @reactive 'l_lm', (n) ->
2 / (1 + @taperRatio()) * (1 - n * (1 - @taperRatio()))
elliptic_value: @reactive 'elliptic_value', (n) ->
if 0 <= n <= 1.0
@liftCoefficient() * 4 / Math.PI * Math.sqrt(1 - Math.pow(n, 2))
elliptic: @reactive 'elliptic', ->
points = []
minY = 0
maxY = 0
for i in [0..@accuracy]
n = i/@accuracy
y = @elliptic_value(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
gamma_a_value: @reactive 'gamma_a_', (n) ->
if 0 <= n <= 1.0
@c1() * @l_lm(n) + @c2() * 4 * Math.sqrt(1 - Math.pow(n, 2)) / Math.PI + @c3() * @f(n)
gamma_a: @memoize 'gamma_a', ->
points = []
minY = 0
maxY = 0
for i in [0..@accuracy]
n = i/@accuracy
y = @gamma_a_value(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
epsylon: @reactive 'epsylon', (n) ->
@linearTwistRad() * n
integral: ->
sum = @gamma_a_value(0) * @epsylon(0)
for i in [1..@accuracy]
nPrev = (i-1)/@accuracy
n = i/@accuracy
sum += (@gamma_a_value(nPrev)*@epsylon(nPrev) + @gamma_a_value(n)*@epsylon(n))*(1/@accuracy)/2
sum
gamma_b_value: @reactive 'gamma_b_value', (n) ->
if 0 <= n <= 1.0
@k1() * @C_A_() * @gamma_a_value(n) * (@epsylon(n) - @integral())
gamma_b: @memoize 'gamma_b', ->
points = []
minY = Infinity
maxY = -Infinity
for i in [0..@accuracy]
n = i/@accuracy
y = @gamma_b_value(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
gamma_value: @reactive 'gamma_value', (n) ->
if 0 <= n <= 1.0
@gamma_a_value(n) * @liftCoefficient() + @gamma_b_value(n)
gamma: @reactive 'gamma', (n) ->
pointsA = @gamma_a().points
pointsB = @gamma_b().points
minY = Infinity
maxY = -Infinity
points = []
for i in [0..pointsA.length-1] by 2
n = pointsA[i]
y = pointsA[i+1] * @liftCoefficient() + pointsB[i+1]
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
C_a_value: @reactive 'C_a_value', (n) ->
if 0 <= n <= 1.0
@gamma_value(n) * @lm_l(n)
C_a: @memoize 'C_a', ->
gammaPoints = @gamma().points
minY = Infinity
maxY = -Infinity
points = []
for i in [0..gammaPoints.length-1] by 2
n = gammaPoints[i]
y = gammaPoints[i+1] * @lm_l(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
C_A_value: @reactive 'C_A_value', (n) ->
@C_A_() if 0 <= n <= 1.0
C_A: @memoize 'C_A', ->
val = @C_A_()
return {
points: [@minX(), val, @maxX(), val]
tension: 0
minY: val
maxY: val
}
geometry_value: @reactive 'geometry_value', (n) -> 0
geometry: @memoize 'geometry', ->
return {
points: [@wingX1(), @wingY1(), @wingX2(), @wingY2(), @wingX4(), @wingY4(), @wingX3(), @wingY3()]
tension: 0
minY: -50
maxY: 50
}
| 209093 | # coding: utf-8
ILR.LiftDistribution ?= {}
ILR.LiftDistribution.Models ?= {}
class ILR.LiftDistribution.Models.Calculator extends ILR.Models.BaseCalculator
curveGroups: [['gamma', 'gamma_a', 'gamma_b', 'elliptic', 'C_a'], ['C_A'], ['geometry']]
COF = [
[ 2.1511 , 0.009 , -7.3509 , 7.3094 , -2.3048, -0.4104 ]
[ 1.7988 , 0.4009, -7.887 , 17.856 , -23.375 , 10.867 ]
[ 1.53045, 0.2337, -3.75395, 5.9553 , -6.447 , 2.31195 ]
[ 1.2621 , 0.0665, 0.3791 , -5.9454 , 10.481 , -6.2431 ]
[ 1.08715, 0.1467, 4.39155, -16.4117, 20.644 , -9.88955 ]
[ 0.9122 , 0.2209, 8.404 , -26.878 , 30.807 , -13.536 ]
[ 0.6533 , 1.3704, 6.9543 , -25.579 , 29.78 , -13.249 ]
[ 0.559 , 0.8908, 11.602 , -37.973 , 44.477 , -19.627 ]
]
accuracy: 50
interpolationTension: 0.25
constructor: (options = {}) ->
super(_.defaults(options, required: ['liftDistribution']))
minX: @reactive 'minX', -> 0
maxX: @reactive 'maxX', -> 1.0
xRange: (func) -> 1.0
# Streckung
aspectRatio: @reactive 'aspectRatio', -> @liftDistribution.get('aspectRatio')
# Verwindung
linearTwist: @reactive 'linearTwist', -> @liftDistribution.get('linearTwist')
linearTwistRad: @reactive 'linearTwistRad', -> @linearTwist() * Math.PI / 180.0
# Pfeilung
sweep: @reactive 'sweep', -> @liftDistribution.get('sweep')
sweepRad: @reactive 'sqeepRad', -> @sweep() * Math.PI / 180.0
# Zuspitzung
taperRatio: @reactive 'taperRatio', -> @liftDistribution.get('taperRatio')
# C_A
liftCoefficient: @reactive 'liftCoefficient', -> @liftDistribution.get('liftCoefficient')
# M_Reise
cruisingSpeed: @reactive 'cruisingSpeed', -> @liftDistribution.get('cruisingSpeed')
# Spannweite
l: @reactive 'wingSpan', -> @liftDistribution.get('wingSpan')
# WING GRAPHIC
wing: @memoize 'wing', -> null
Phi_VK: @memoize 'Phi_VK', -> Math.atan( Math.tan(@sweepRad()) + (1 - @taperRatio()) / (@aspectRatio() * (1 + @taperRatio()))) / Math.PI * 180.0
dya: @memoize 'dya', -> Math.tan(@sweepRad()) * @l();
yl: @memoize 'yl', -> 2 * @l() / @aspectRatio()
la: @memoize 'la', -> 2 * @yl() / (1 / @taperRatio() + 1)
li: @memoize 'li', -> @la() / @taperRatio()
wingY01: @memoize 'wingY01', -> -1 * (- @yl() / 4 - @dya() / 2)
wingY02: @memoize 'wingY02', -> -1 * (- @wingY01() + @dya())
wingX1: @memoize 'wingX1', -> 0
wingY1: @memoize 'wingY1', -> - (- @wingY01() - @li()/4)
wingX2: @memoize 'wingX2', -> 1
wingY2: @memoize 'wingY2', -> + (@wingY02() + @la()/4)
wingX3: @memoize 'wingX3', -> 0
wingY3: @memoize 'wingY3', -> - (-@wingY1() + @li())
wingX4: @memoize 'wingX4', -> 1
wingY4: @memoize 'wingY4', -> - (-@wingY2() + @la())
# <NAME>
M_Prof: @memoize 'M_Prof', -> @cruisingSpeed() * Math.sqrt(Math.cos(@sweepRad()))
c_a_: @memoize 'c_a_', -> 2 * Math.PI / Math.sqrt(1 - Math.pow(@M_Prof(), 2))
FF: @memoize 'FF', -> @aspectRatio() / @c_a_() * 2 * Math.PI / Math.cos(@sweepRad())
k0: @memoize 'k0', ->
FF = @FF()
0.2692 * FF - 0.0387 * Math.pow(FF, 2) + 0.002951 * Math.pow(FF, 3) - 0.0001106 * Math.pow(FF, 4) + 1.559 * Math.pow(10, -6) * Math.pow(FF, 5)
k1: @memoize 'k1', ->
F = @FF()
0.3064 + F * (0.05185 - 0.0014 * F)
c1: @memoize 'c1', ->
F = @FF()
0.003647 + F * (0.05614 - 0.0009842 * F)
c2: @memoize 'c2', ->
F = @FF()
1 + F * (0.002721 * F - 0.1098)
c3: @memoize 'c3', ->
F = @FF()
-0.008265 + F * (0.05493 - 0.001816 * F)
C_A_: @memoize 'C_A_', ->
@c_a_() * @k0() * Math.cos(@sweepRad())
Phi_e: @memoize 'Phi_e', ->
Math.atan(Math.tan(@sweepRad()) / Math.sqrt(1 - Math.pow(@cruisingSpeed(), 2)))
cof: @memoize 'cof', ->
phi = @Phi_e()
indices = if phi < -30 then [0, 1]
else if -30 <= phi < -15 then [1, 2]
else if -15 <= phi < 0 then [2, 3]
else if 0 <= phi < 15 then [3, 4]
else if 15 <= phi < 30 then [4, 5]
else if 30 <= phi < 45 then [5, 6]
else if 45 <= phi then [6, 7]
upAndLow = _.zip.apply(_, (COF[i] for i in indices))
m = ((low - up)/15 for [up, low] in upAndLow)
n = COF[3] # at 0°
m[i]*phi + n[i] for i in [0...m.length]
f: @reactive 'f', (n) ->
c = @cof()
c[0] + c[1]*n + c[2]*Math.pow(n,2) + c[3]*Math.pow(n,3) + c[4]*Math.pow(n,4) + c[5]*Math.pow(n,5)
lm_l: @reactive 'lm_l', (n) ->
@yl() / (@la() / @taperRatio() * (1 - n * (1 - @taperRatio())))
l_lm: @reactive 'l_lm', (n) ->
2 / (1 + @taperRatio()) * (1 - n * (1 - @taperRatio()))
elliptic_value: @reactive 'elliptic_value', (n) ->
if 0 <= n <= 1.0
@liftCoefficient() * 4 / Math.PI * Math.sqrt(1 - Math.pow(n, 2))
elliptic: @reactive 'elliptic', ->
points = []
minY = 0
maxY = 0
for i in [0..@accuracy]
n = i/@accuracy
y = @elliptic_value(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
gamma_a_value: @reactive 'gamma_a_', (n) ->
if 0 <= n <= 1.0
@c1() * @l_lm(n) + @c2() * 4 * Math.sqrt(1 - Math.pow(n, 2)) / Math.PI + @c3() * @f(n)
gamma_a: @memoize 'gamma_a', ->
points = []
minY = 0
maxY = 0
for i in [0..@accuracy]
n = i/@accuracy
y = @gamma_a_value(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
epsylon: @reactive 'epsylon', (n) ->
@linearTwistRad() * n
integral: ->
sum = @gamma_a_value(0) * @epsylon(0)
for i in [1..@accuracy]
nPrev = (i-1)/@accuracy
n = i/@accuracy
sum += (@gamma_a_value(nPrev)*@epsylon(nPrev) + @gamma_a_value(n)*@epsylon(n))*(1/@accuracy)/2
sum
gamma_b_value: @reactive 'gamma_b_value', (n) ->
if 0 <= n <= 1.0
@k1() * @C_A_() * @gamma_a_value(n) * (@epsylon(n) - @integral())
gamma_b: @memoize 'gamma_b', ->
points = []
minY = Infinity
maxY = -Infinity
for i in [0..@accuracy]
n = i/@accuracy
y = @gamma_b_value(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
gamma_value: @reactive 'gamma_value', (n) ->
if 0 <= n <= 1.0
@gamma_a_value(n) * @liftCoefficient() + @gamma_b_value(n)
gamma: @reactive 'gamma', (n) ->
pointsA = @gamma_a().points
pointsB = @gamma_b().points
minY = Infinity
maxY = -Infinity
points = []
for i in [0..pointsA.length-1] by 2
n = pointsA[i]
y = pointsA[i+1] * @liftCoefficient() + pointsB[i+1]
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
C_a_value: @reactive 'C_a_value', (n) ->
if 0 <= n <= 1.0
@gamma_value(n) * @lm_l(n)
C_a: @memoize 'C_a', ->
gammaPoints = @gamma().points
minY = Infinity
maxY = -Infinity
points = []
for i in [0..gammaPoints.length-1] by 2
n = gammaPoints[i]
y = gammaPoints[i+1] * @lm_l(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
C_A_value: @reactive 'C_A_value', (n) ->
@C_A_() if 0 <= n <= 1.0
C_A: @memoize 'C_A', ->
val = @C_A_()
return {
points: [@minX(), val, @maxX(), val]
tension: 0
minY: val
maxY: val
}
geometry_value: @reactive 'geometry_value', (n) -> 0
geometry: @memoize 'geometry', ->
return {
points: [@wingX1(), @wingY1(), @wingX2(), @wingY2(), @wingX4(), @wingY4(), @wingX3(), @wingY3()]
tension: 0
minY: -50
maxY: 50
}
| true | # coding: utf-8
ILR.LiftDistribution ?= {}
ILR.LiftDistribution.Models ?= {}
class ILR.LiftDistribution.Models.Calculator extends ILR.Models.BaseCalculator
curveGroups: [['gamma', 'gamma_a', 'gamma_b', 'elliptic', 'C_a'], ['C_A'], ['geometry']]
COF = [
[ 2.1511 , 0.009 , -7.3509 , 7.3094 , -2.3048, -0.4104 ]
[ 1.7988 , 0.4009, -7.887 , 17.856 , -23.375 , 10.867 ]
[ 1.53045, 0.2337, -3.75395, 5.9553 , -6.447 , 2.31195 ]
[ 1.2621 , 0.0665, 0.3791 , -5.9454 , 10.481 , -6.2431 ]
[ 1.08715, 0.1467, 4.39155, -16.4117, 20.644 , -9.88955 ]
[ 0.9122 , 0.2209, 8.404 , -26.878 , 30.807 , -13.536 ]
[ 0.6533 , 1.3704, 6.9543 , -25.579 , 29.78 , -13.249 ]
[ 0.559 , 0.8908, 11.602 , -37.973 , 44.477 , -19.627 ]
]
accuracy: 50
interpolationTension: 0.25
constructor: (options = {}) ->
super(_.defaults(options, required: ['liftDistribution']))
minX: @reactive 'minX', -> 0
maxX: @reactive 'maxX', -> 1.0
xRange: (func) -> 1.0
# Streckung
aspectRatio: @reactive 'aspectRatio', -> @liftDistribution.get('aspectRatio')
# Verwindung
linearTwist: @reactive 'linearTwist', -> @liftDistribution.get('linearTwist')
linearTwistRad: @reactive 'linearTwistRad', -> @linearTwist() * Math.PI / 180.0
# Pfeilung
sweep: @reactive 'sweep', -> @liftDistribution.get('sweep')
sweepRad: @reactive 'sqeepRad', -> @sweep() * Math.PI / 180.0
# Zuspitzung
taperRatio: @reactive 'taperRatio', -> @liftDistribution.get('taperRatio')
# C_A
liftCoefficient: @reactive 'liftCoefficient', -> @liftDistribution.get('liftCoefficient')
# M_Reise
cruisingSpeed: @reactive 'cruisingSpeed', -> @liftDistribution.get('cruisingSpeed')
# Spannweite
l: @reactive 'wingSpan', -> @liftDistribution.get('wingSpan')
# WING GRAPHIC
wing: @memoize 'wing', -> null
Phi_VK: @memoize 'Phi_VK', -> Math.atan( Math.tan(@sweepRad()) + (1 - @taperRatio()) / (@aspectRatio() * (1 + @taperRatio()))) / Math.PI * 180.0
dya: @memoize 'dya', -> Math.tan(@sweepRad()) * @l();
yl: @memoize 'yl', -> 2 * @l() / @aspectRatio()
la: @memoize 'la', -> 2 * @yl() / (1 / @taperRatio() + 1)
li: @memoize 'li', -> @la() / @taperRatio()
wingY01: @memoize 'wingY01', -> -1 * (- @yl() / 4 - @dya() / 2)
wingY02: @memoize 'wingY02', -> -1 * (- @wingY01() + @dya())
wingX1: @memoize 'wingX1', -> 0
wingY1: @memoize 'wingY1', -> - (- @wingY01() - @li()/4)
wingX2: @memoize 'wingX2', -> 1
wingY2: @memoize 'wingY2', -> + (@wingY02() + @la()/4)
wingX3: @memoize 'wingX3', -> 0
wingY3: @memoize 'wingY3', -> - (-@wingY1() + @li())
wingX4: @memoize 'wingX4', -> 1
wingY4: @memoize 'wingY4', -> - (-@wingY2() + @la())
# PI:NAME:<NAME>END_PI
M_Prof: @memoize 'M_Prof', -> @cruisingSpeed() * Math.sqrt(Math.cos(@sweepRad()))
c_a_: @memoize 'c_a_', -> 2 * Math.PI / Math.sqrt(1 - Math.pow(@M_Prof(), 2))
FF: @memoize 'FF', -> @aspectRatio() / @c_a_() * 2 * Math.PI / Math.cos(@sweepRad())
k0: @memoize 'k0', ->
FF = @FF()
0.2692 * FF - 0.0387 * Math.pow(FF, 2) + 0.002951 * Math.pow(FF, 3) - 0.0001106 * Math.pow(FF, 4) + 1.559 * Math.pow(10, -6) * Math.pow(FF, 5)
k1: @memoize 'k1', ->
F = @FF()
0.3064 + F * (0.05185 - 0.0014 * F)
c1: @memoize 'c1', ->
F = @FF()
0.003647 + F * (0.05614 - 0.0009842 * F)
c2: @memoize 'c2', ->
F = @FF()
1 + F * (0.002721 * F - 0.1098)
c3: @memoize 'c3', ->
F = @FF()
-0.008265 + F * (0.05493 - 0.001816 * F)
C_A_: @memoize 'C_A_', ->
@c_a_() * @k0() * Math.cos(@sweepRad())
Phi_e: @memoize 'Phi_e', ->
Math.atan(Math.tan(@sweepRad()) / Math.sqrt(1 - Math.pow(@cruisingSpeed(), 2)))
cof: @memoize 'cof', ->
phi = @Phi_e()
indices = if phi < -30 then [0, 1]
else if -30 <= phi < -15 then [1, 2]
else if -15 <= phi < 0 then [2, 3]
else if 0 <= phi < 15 then [3, 4]
else if 15 <= phi < 30 then [4, 5]
else if 30 <= phi < 45 then [5, 6]
else if 45 <= phi then [6, 7]
upAndLow = _.zip.apply(_, (COF[i] for i in indices))
m = ((low - up)/15 for [up, low] in upAndLow)
n = COF[3] # at 0°
m[i]*phi + n[i] for i in [0...m.length]
f: @reactive 'f', (n) ->
c = @cof()
c[0] + c[1]*n + c[2]*Math.pow(n,2) + c[3]*Math.pow(n,3) + c[4]*Math.pow(n,4) + c[5]*Math.pow(n,5)
lm_l: @reactive 'lm_l', (n) ->
@yl() / (@la() / @taperRatio() * (1 - n * (1 - @taperRatio())))
l_lm: @reactive 'l_lm', (n) ->
2 / (1 + @taperRatio()) * (1 - n * (1 - @taperRatio()))
elliptic_value: @reactive 'elliptic_value', (n) ->
if 0 <= n <= 1.0
@liftCoefficient() * 4 / Math.PI * Math.sqrt(1 - Math.pow(n, 2))
elliptic: @reactive 'elliptic', ->
points = []
minY = 0
maxY = 0
for i in [0..@accuracy]
n = i/@accuracy
y = @elliptic_value(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
gamma_a_value: @reactive 'gamma_a_', (n) ->
if 0 <= n <= 1.0
@c1() * @l_lm(n) + @c2() * 4 * Math.sqrt(1 - Math.pow(n, 2)) / Math.PI + @c3() * @f(n)
gamma_a: @memoize 'gamma_a', ->
points = []
minY = 0
maxY = 0
for i in [0..@accuracy]
n = i/@accuracy
y = @gamma_a_value(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
epsylon: @reactive 'epsylon', (n) ->
@linearTwistRad() * n
integral: ->
sum = @gamma_a_value(0) * @epsylon(0)
for i in [1..@accuracy]
nPrev = (i-1)/@accuracy
n = i/@accuracy
sum += (@gamma_a_value(nPrev)*@epsylon(nPrev) + @gamma_a_value(n)*@epsylon(n))*(1/@accuracy)/2
sum
gamma_b_value: @reactive 'gamma_b_value', (n) ->
if 0 <= n <= 1.0
@k1() * @C_A_() * @gamma_a_value(n) * (@epsylon(n) - @integral())
gamma_b: @memoize 'gamma_b', ->
points = []
minY = Infinity
maxY = -Infinity
for i in [0..@accuracy]
n = i/@accuracy
y = @gamma_b_value(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
gamma_value: @reactive 'gamma_value', (n) ->
if 0 <= n <= 1.0
@gamma_a_value(n) * @liftCoefficient() + @gamma_b_value(n)
gamma: @reactive 'gamma', (n) ->
pointsA = @gamma_a().points
pointsB = @gamma_b().points
minY = Infinity
maxY = -Infinity
points = []
for i in [0..pointsA.length-1] by 2
n = pointsA[i]
y = pointsA[i+1] * @liftCoefficient() + pointsB[i+1]
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
C_a_value: @reactive 'C_a_value', (n) ->
if 0 <= n <= 1.0
@gamma_value(n) * @lm_l(n)
C_a: @memoize 'C_a', ->
gammaPoints = @gamma().points
minY = Infinity
maxY = -Infinity
points = []
for i in [0..gammaPoints.length-1] by 2
n = gammaPoints[i]
y = gammaPoints[i+1] * @lm_l(n)
minY = y if y < minY
maxY = y if y > maxY
points.push(n, y)
return {
points: points
tension: @interpolationTension
minY: minY
maxY: maxY
}
C_A_value: @reactive 'C_A_value', (n) ->
@C_A_() if 0 <= n <= 1.0
C_A: @memoize 'C_A', ->
val = @C_A_()
return {
points: [@minX(), val, @maxX(), val]
tension: 0
minY: val
maxY: val
}
geometry_value: @reactive 'geometry_value', (n) -> 0
geometry: @memoize 'geometry', ->
return {
points: [@wingX1(), @wingY1(), @wingX2(), @wingY2(), @wingX4(), @wingY4(), @wingX3(), @wingY3()]
tension: 0
minY: -50
maxY: 50
}
|
[
{
"context": "()\n params = api_params()\n params.password = password\n post_api(dfd, op_type, params).done (response",
"end": 3937,
"score": 0.9993811845779419,
"start": 3929,
"tag": "PASSWORD",
"value": "password"
}
] | app/assets/javascripts/ec2_view_model.js.coffee | kazumax55/AWSSimpleConsole | 0 | AWSSC = window.AWSSC = window.AWSSC ? {}
AWSSC.EC2ViewModel = (parent, in_data) ->
self = {}
self.data = ko.observable in_data
self.region = in_data.region
self.account_name = in_data.account_name
self.name = in_data.tags.Name
api_params = ->
region: self.region
account_name: self.account_name
polling_sec = 10000
# view event handlers
self.onReload = ->
self.update()
self.onInfo = ->
data = self.data()
info = ["",
"ID: #{data.ec2_id}"
"Name: #{self.name}"
"type: #{data.instance_type}"
"private IP: #{data.private_ip}"
"public IP: #{data.public_ip}"
"status: #{data.status}"
"tags: <ul><li>#{("#{k}: #{v}" for k,v of data.tags).join("</li><li>")}</li></ul>"
].join("<br>")
parent.show_message(info, name)
self.onLockUnlock = ->
if self.can_start_stop()
prm = parent.confirm_admin("Do you really want to LOCK<br/> '#{self.name}' ?").then (password) ->
self.lock_operation(password)
else
prm = parent.confirm_admin("Do you really want to UNLOCK '#{self.name}' ?").then (password) ->
self.unlock_operation(password)
if prm
prm.done ->
self.update()
.fail (reason) ->
parent.show_message(reason, "failure") if reason
self.onEditSchedule = ->
checkbox = $('<input type="checkbox">')
if self.use_stop_only()
checkbox.prop("checked", true)
extra = $('<div>').append(checkbox).append($("<span> 自動STARTは行わない</span>"))
AWSSC.ModalPrompt().show
title: "Enter Schedule"
body: "ex1) 月-金 && 9-21<br/>ex2) 月,水,金 && 9-12,13-20<br/>ex3) 9-21"
value: self.run_schedule() || "月-金 && 10-22"
extra: extra
.done (val) ->
self.update_schedule(val, checkbox.prop("checked"))
.done ->
self.update()
.fail (reason) ->
show_message(reason, "failure") if reason
self.onStart = ->
parent.confirm_action("Start #{self.name}?").done ->
self.start_instance()
self.onStop = ->
parent.confirm_action("Stop #{self.name}?").done ->
self.stop_instance()
# logic
self.is_running = ko.computed -> self.data().status == "running"
self.is_stopped = ko.computed -> self.data().status == "stopped"
self.is_state_changing = ko.computed -> !self.is_running() && !self.is_stopped()
self.can_start_stop = ko.computed ->
self.data().tags['APIStartStop'] == 'YES'
self.use_stop_only = ko.computed ->
self.data().tags['APIAutoOperationMode'] == 'STOP'
self.run_schedule = ko.computed ->
self.data().tags['APIRunSchedule']
self.update = ->
$.get("#{AWSSC.config.API_BASE}#{self.data().ec2_id}", api_params())
.done (response) ->
self.data(response.ec2)
.always (response) ->
console.log response
check_state = (dfd, ok_func, ng_func) ->
self.update().done ->
if ok_func()
dfd.resolve()
else if ng_func()
dfd.fail()
else
dfd.notify()
$.wait(polling_sec).done ->
check_state(dfd, ok_func, ng_func)
post_api = (dfd, op_type, params=api_params()) ->
$.post("#{AWSSC.config.API_BASE}#{self.data().ec2_id}/#{op_type}", params)
.always (response) ->
console.log(response)
.fail (response) ->
console.log(response.responseText)
dfd.reject("ERROR Status=#{response.status}")
self.start_instance = ->
dfd = $.Deferred()
post_api(dfd, "start").done ->
check_state(dfd, self.is_running, self.is_stopped)
data = self.data()
data.status = '-'
self.data(data)
dfd.promise()
self.stop_instance = ->
dfd = $.Deferred()
post_api(dfd, "stop").done ->
check_state(dfd, self.is_stopped, self.is_running)
dfd.promise()
lock_unlock_operation = (op_type, password) ->
dfd = $.Deferred()
params = api_params()
params.password = password
post_api(dfd, op_type, params).done (response) ->
if response.success
$.wait(500).done ->
dfd.resolve()
else
dfd.reject(response.message)
dfd.promise()
self.lock_operation = (password) ->
lock_unlock_operation("lock", password)
self.unlock_operation = (password) ->
lock_unlock_operation("unlock", password)
self.update_schedule = (val, use_stop_only) ->
dfd = $.Deferred()
params = api_params()
params.schedule = val
params.use_stop_only = if use_stop_only then "1" else "0"
post_api(dfd, "schedule", params).done (response) ->
if response.success
dfd.resolve()
else
dfd.reject(response.message)
dfd.promise()
# properties
self.launch_time = ko.computed ->
new Date(self.data().launch_time).toLocaleDateString()
self.instance_type = self.data().instance_type
self.hideStop = ko.observable(false)
self.filterText = ko.observable("")
self.status = ko.computed -> self.data().status
self.cost = ko.computed ->
now = new Date()
data = self.data()
launch_time = new Date(data.launch_time)
hours = Math.floor((now - launch_time)/1000/3600)
cost_per_hour = Math.floor(cost_table[data.instance_type] * region_rate["ap-southeast-1"] * 10000) / 10000
cost = Math.floor(cost_per_hour * hours)
"#{hours}H × #{cost_per_hour}$ ≒ #{cost}$"
self.instanceTypeCSS = ko.computed ->
self.data().instance_type.replace(".", "")
self.toggle_hide_stop = (hideStopped) ->
self.hideStop(hideStopped)
self.isIncludeFilterText = ko.computed ->
if !self.filterText()
true
else
ft = self.filterText().toLocaleLowerCase()
for k, v of self.data().tags
if v && v.toLocaleLowerCase().indexOf(ft) >= 0
return true
false
self.shouldHide = ko.computed ->
(self.hideStop() && self.is_stopped()) || !self.isIncludeFilterText()
self.check_need_update = (expire_span=86400) ->
updated_time = new Date(self.data().updated_at)
now = new Date()
return (now - updated_time)/1000 > expire_span
return self
cost_table = # virginia, US doller per hour
"m4.large": 0.126
"m4.xlarge": 0.252
"m4.2xlarge": 0.504
"m4.4xlarge": 1.008
"m4.10xlarge": 2.520
"m3.medium": 0.067
"m3.large": 0.133
"m3.xlarge": 0.266
"m3.2xlarge": 0.532
"m1.small": 0.044
"m1.medium": 0.087
"m1.large": 0.175
"m1.xlarge": 0.350
"c4.large": 0.110
"c4.xlarge": 0.220
"c4.2xlarge": 0.441
"c4.4xlarge": 0.882
"c4.8xlarge": 1.763
"c3.large": 0.105
"c3.xlarge": 0.210
"c3.2xlarge": 0.420
"c3.4xlarge": 0.840
"c3.8xlarge": 1.680
"c1.medium": 0.130
"c1.xlarge": 0.520
"cc2.8xlarge": 2.0
"g2.2xlarge": 0.65
"g2.8xlarge": 2.60
"cg1.4xlarge": 2.1
"m2.xlarge": 0.245
"m2.2xlarge": 0.490
"m2.4xlarge": 0.980
"cr1.8xlarge": 3.5
"i2.xlarge": 0.853
"i2.2xlarge": 1.705
"i2.4xlarge": 3.41
"i2.8xlarge": 6.82
"d2.xlarge": 0.690
"d2.2xlarge": 1.380
"d2.4xlarge": 2.760
"d2.8xlarge": 5.520
"hs1.8xlarge": 4.6
"hi1.4xlarge": 3.1
"t1.micro": 0.02
"t2.nano": 0.0065
"t2.micro": 0.013
"t2.small": 0.026
"t2.medium": 0.052
"t2.large": 0.104
"r3.large": 0.175
"r3.xlarge": 0.350
"r3.2xlarge": 0.700
"r3.4xlarge": 1.400
"r3.8xlarge": 2.800
region_rate =
"ap-southeast-1": 8/6.0
| 47753 | AWSSC = window.AWSSC = window.AWSSC ? {}
AWSSC.EC2ViewModel = (parent, in_data) ->
self = {}
self.data = ko.observable in_data
self.region = in_data.region
self.account_name = in_data.account_name
self.name = in_data.tags.Name
api_params = ->
region: self.region
account_name: self.account_name
polling_sec = 10000
# view event handlers
self.onReload = ->
self.update()
self.onInfo = ->
data = self.data()
info = ["",
"ID: #{data.ec2_id}"
"Name: #{self.name}"
"type: #{data.instance_type}"
"private IP: #{data.private_ip}"
"public IP: #{data.public_ip}"
"status: #{data.status}"
"tags: <ul><li>#{("#{k}: #{v}" for k,v of data.tags).join("</li><li>")}</li></ul>"
].join("<br>")
parent.show_message(info, name)
self.onLockUnlock = ->
if self.can_start_stop()
prm = parent.confirm_admin("Do you really want to LOCK<br/> '#{self.name}' ?").then (password) ->
self.lock_operation(password)
else
prm = parent.confirm_admin("Do you really want to UNLOCK '#{self.name}' ?").then (password) ->
self.unlock_operation(password)
if prm
prm.done ->
self.update()
.fail (reason) ->
parent.show_message(reason, "failure") if reason
self.onEditSchedule = ->
checkbox = $('<input type="checkbox">')
if self.use_stop_only()
checkbox.prop("checked", true)
extra = $('<div>').append(checkbox).append($("<span> 自動STARTは行わない</span>"))
AWSSC.ModalPrompt().show
title: "Enter Schedule"
body: "ex1) 月-金 && 9-21<br/>ex2) 月,水,金 && 9-12,13-20<br/>ex3) 9-21"
value: self.run_schedule() || "月-金 && 10-22"
extra: extra
.done (val) ->
self.update_schedule(val, checkbox.prop("checked"))
.done ->
self.update()
.fail (reason) ->
show_message(reason, "failure") if reason
self.onStart = ->
parent.confirm_action("Start #{self.name}?").done ->
self.start_instance()
self.onStop = ->
parent.confirm_action("Stop #{self.name}?").done ->
self.stop_instance()
# logic
self.is_running = ko.computed -> self.data().status == "running"
self.is_stopped = ko.computed -> self.data().status == "stopped"
self.is_state_changing = ko.computed -> !self.is_running() && !self.is_stopped()
self.can_start_stop = ko.computed ->
self.data().tags['APIStartStop'] == 'YES'
self.use_stop_only = ko.computed ->
self.data().tags['APIAutoOperationMode'] == 'STOP'
self.run_schedule = ko.computed ->
self.data().tags['APIRunSchedule']
self.update = ->
$.get("#{AWSSC.config.API_BASE}#{self.data().ec2_id}", api_params())
.done (response) ->
self.data(response.ec2)
.always (response) ->
console.log response
check_state = (dfd, ok_func, ng_func) ->
self.update().done ->
if ok_func()
dfd.resolve()
else if ng_func()
dfd.fail()
else
dfd.notify()
$.wait(polling_sec).done ->
check_state(dfd, ok_func, ng_func)
post_api = (dfd, op_type, params=api_params()) ->
$.post("#{AWSSC.config.API_BASE}#{self.data().ec2_id}/#{op_type}", params)
.always (response) ->
console.log(response)
.fail (response) ->
console.log(response.responseText)
dfd.reject("ERROR Status=#{response.status}")
self.start_instance = ->
dfd = $.Deferred()
post_api(dfd, "start").done ->
check_state(dfd, self.is_running, self.is_stopped)
data = self.data()
data.status = '-'
self.data(data)
dfd.promise()
self.stop_instance = ->
dfd = $.Deferred()
post_api(dfd, "stop").done ->
check_state(dfd, self.is_stopped, self.is_running)
dfd.promise()
lock_unlock_operation = (op_type, password) ->
dfd = $.Deferred()
params = api_params()
params.password = <PASSWORD>
post_api(dfd, op_type, params).done (response) ->
if response.success
$.wait(500).done ->
dfd.resolve()
else
dfd.reject(response.message)
dfd.promise()
self.lock_operation = (password) ->
lock_unlock_operation("lock", password)
self.unlock_operation = (password) ->
lock_unlock_operation("unlock", password)
self.update_schedule = (val, use_stop_only) ->
dfd = $.Deferred()
params = api_params()
params.schedule = val
params.use_stop_only = if use_stop_only then "1" else "0"
post_api(dfd, "schedule", params).done (response) ->
if response.success
dfd.resolve()
else
dfd.reject(response.message)
dfd.promise()
# properties
self.launch_time = ko.computed ->
new Date(self.data().launch_time).toLocaleDateString()
self.instance_type = self.data().instance_type
self.hideStop = ko.observable(false)
self.filterText = ko.observable("")
self.status = ko.computed -> self.data().status
self.cost = ko.computed ->
now = new Date()
data = self.data()
launch_time = new Date(data.launch_time)
hours = Math.floor((now - launch_time)/1000/3600)
cost_per_hour = Math.floor(cost_table[data.instance_type] * region_rate["ap-southeast-1"] * 10000) / 10000
cost = Math.floor(cost_per_hour * hours)
"#{hours}H × #{cost_per_hour}$ ≒ #{cost}$"
self.instanceTypeCSS = ko.computed ->
self.data().instance_type.replace(".", "")
self.toggle_hide_stop = (hideStopped) ->
self.hideStop(hideStopped)
self.isIncludeFilterText = ko.computed ->
if !self.filterText()
true
else
ft = self.filterText().toLocaleLowerCase()
for k, v of self.data().tags
if v && v.toLocaleLowerCase().indexOf(ft) >= 0
return true
false
self.shouldHide = ko.computed ->
(self.hideStop() && self.is_stopped()) || !self.isIncludeFilterText()
self.check_need_update = (expire_span=86400) ->
updated_time = new Date(self.data().updated_at)
now = new Date()
return (now - updated_time)/1000 > expire_span
return self
cost_table = # virginia, US doller per hour
"m4.large": 0.126
"m4.xlarge": 0.252
"m4.2xlarge": 0.504
"m4.4xlarge": 1.008
"m4.10xlarge": 2.520
"m3.medium": 0.067
"m3.large": 0.133
"m3.xlarge": 0.266
"m3.2xlarge": 0.532
"m1.small": 0.044
"m1.medium": 0.087
"m1.large": 0.175
"m1.xlarge": 0.350
"c4.large": 0.110
"c4.xlarge": 0.220
"c4.2xlarge": 0.441
"c4.4xlarge": 0.882
"c4.8xlarge": 1.763
"c3.large": 0.105
"c3.xlarge": 0.210
"c3.2xlarge": 0.420
"c3.4xlarge": 0.840
"c3.8xlarge": 1.680
"c1.medium": 0.130
"c1.xlarge": 0.520
"cc2.8xlarge": 2.0
"g2.2xlarge": 0.65
"g2.8xlarge": 2.60
"cg1.4xlarge": 2.1
"m2.xlarge": 0.245
"m2.2xlarge": 0.490
"m2.4xlarge": 0.980
"cr1.8xlarge": 3.5
"i2.xlarge": 0.853
"i2.2xlarge": 1.705
"i2.4xlarge": 3.41
"i2.8xlarge": 6.82
"d2.xlarge": 0.690
"d2.2xlarge": 1.380
"d2.4xlarge": 2.760
"d2.8xlarge": 5.520
"hs1.8xlarge": 4.6
"hi1.4xlarge": 3.1
"t1.micro": 0.02
"t2.nano": 0.0065
"t2.micro": 0.013
"t2.small": 0.026
"t2.medium": 0.052
"t2.large": 0.104
"r3.large": 0.175
"r3.xlarge": 0.350
"r3.2xlarge": 0.700
"r3.4xlarge": 1.400
"r3.8xlarge": 2.800
region_rate =
"ap-southeast-1": 8/6.0
| true | AWSSC = window.AWSSC = window.AWSSC ? {}
AWSSC.EC2ViewModel = (parent, in_data) ->
self = {}
self.data = ko.observable in_data
self.region = in_data.region
self.account_name = in_data.account_name
self.name = in_data.tags.Name
api_params = ->
region: self.region
account_name: self.account_name
polling_sec = 10000
# view event handlers
self.onReload = ->
self.update()
self.onInfo = ->
data = self.data()
info = ["",
"ID: #{data.ec2_id}"
"Name: #{self.name}"
"type: #{data.instance_type}"
"private IP: #{data.private_ip}"
"public IP: #{data.public_ip}"
"status: #{data.status}"
"tags: <ul><li>#{("#{k}: #{v}" for k,v of data.tags).join("</li><li>")}</li></ul>"
].join("<br>")
parent.show_message(info, name)
self.onLockUnlock = ->
if self.can_start_stop()
prm = parent.confirm_admin("Do you really want to LOCK<br/> '#{self.name}' ?").then (password) ->
self.lock_operation(password)
else
prm = parent.confirm_admin("Do you really want to UNLOCK '#{self.name}' ?").then (password) ->
self.unlock_operation(password)
if prm
prm.done ->
self.update()
.fail (reason) ->
parent.show_message(reason, "failure") if reason
self.onEditSchedule = ->
checkbox = $('<input type="checkbox">')
if self.use_stop_only()
checkbox.prop("checked", true)
extra = $('<div>').append(checkbox).append($("<span> 自動STARTは行わない</span>"))
AWSSC.ModalPrompt().show
title: "Enter Schedule"
body: "ex1) 月-金 && 9-21<br/>ex2) 月,水,金 && 9-12,13-20<br/>ex3) 9-21"
value: self.run_schedule() || "月-金 && 10-22"
extra: extra
.done (val) ->
self.update_schedule(val, checkbox.prop("checked"))
.done ->
self.update()
.fail (reason) ->
show_message(reason, "failure") if reason
self.onStart = ->
parent.confirm_action("Start #{self.name}?").done ->
self.start_instance()
self.onStop = ->
parent.confirm_action("Stop #{self.name}?").done ->
self.stop_instance()
# logic
self.is_running = ko.computed -> self.data().status == "running"
self.is_stopped = ko.computed -> self.data().status == "stopped"
self.is_state_changing = ko.computed -> !self.is_running() && !self.is_stopped()
self.can_start_stop = ko.computed ->
self.data().tags['APIStartStop'] == 'YES'
self.use_stop_only = ko.computed ->
self.data().tags['APIAutoOperationMode'] == 'STOP'
self.run_schedule = ko.computed ->
self.data().tags['APIRunSchedule']
self.update = ->
$.get("#{AWSSC.config.API_BASE}#{self.data().ec2_id}", api_params())
.done (response) ->
self.data(response.ec2)
.always (response) ->
console.log response
check_state = (dfd, ok_func, ng_func) ->
self.update().done ->
if ok_func()
dfd.resolve()
else if ng_func()
dfd.fail()
else
dfd.notify()
$.wait(polling_sec).done ->
check_state(dfd, ok_func, ng_func)
post_api = (dfd, op_type, params=api_params()) ->
$.post("#{AWSSC.config.API_BASE}#{self.data().ec2_id}/#{op_type}", params)
.always (response) ->
console.log(response)
.fail (response) ->
console.log(response.responseText)
dfd.reject("ERROR Status=#{response.status}")
self.start_instance = ->
dfd = $.Deferred()
post_api(dfd, "start").done ->
check_state(dfd, self.is_running, self.is_stopped)
data = self.data()
data.status = '-'
self.data(data)
dfd.promise()
self.stop_instance = ->
dfd = $.Deferred()
post_api(dfd, "stop").done ->
check_state(dfd, self.is_stopped, self.is_running)
dfd.promise()
lock_unlock_operation = (op_type, password) ->
dfd = $.Deferred()
params = api_params()
params.password = PI:PASSWORD:<PASSWORD>END_PI
post_api(dfd, op_type, params).done (response) ->
if response.success
$.wait(500).done ->
dfd.resolve()
else
dfd.reject(response.message)
dfd.promise()
self.lock_operation = (password) ->
lock_unlock_operation("lock", password)
self.unlock_operation = (password) ->
lock_unlock_operation("unlock", password)
self.update_schedule = (val, use_stop_only) ->
dfd = $.Deferred()
params = api_params()
params.schedule = val
params.use_stop_only = if use_stop_only then "1" else "0"
post_api(dfd, "schedule", params).done (response) ->
if response.success
dfd.resolve()
else
dfd.reject(response.message)
dfd.promise()
# properties
self.launch_time = ko.computed ->
new Date(self.data().launch_time).toLocaleDateString()
self.instance_type = self.data().instance_type
self.hideStop = ko.observable(false)
self.filterText = ko.observable("")
self.status = ko.computed -> self.data().status
self.cost = ko.computed ->
now = new Date()
data = self.data()
launch_time = new Date(data.launch_time)
hours = Math.floor((now - launch_time)/1000/3600)
cost_per_hour = Math.floor(cost_table[data.instance_type] * region_rate["ap-southeast-1"] * 10000) / 10000
cost = Math.floor(cost_per_hour * hours)
"#{hours}H × #{cost_per_hour}$ ≒ #{cost}$"
self.instanceTypeCSS = ko.computed ->
self.data().instance_type.replace(".", "")
self.toggle_hide_stop = (hideStopped) ->
self.hideStop(hideStopped)
self.isIncludeFilterText = ko.computed ->
if !self.filterText()
true
else
ft = self.filterText().toLocaleLowerCase()
for k, v of self.data().tags
if v && v.toLocaleLowerCase().indexOf(ft) >= 0
return true
false
self.shouldHide = ko.computed ->
(self.hideStop() && self.is_stopped()) || !self.isIncludeFilterText()
self.check_need_update = (expire_span=86400) ->
updated_time = new Date(self.data().updated_at)
now = new Date()
return (now - updated_time)/1000 > expire_span
return self
cost_table = # virginia, US doller per hour
"m4.large": 0.126
"m4.xlarge": 0.252
"m4.2xlarge": 0.504
"m4.4xlarge": 1.008
"m4.10xlarge": 2.520
"m3.medium": 0.067
"m3.large": 0.133
"m3.xlarge": 0.266
"m3.2xlarge": 0.532
"m1.small": 0.044
"m1.medium": 0.087
"m1.large": 0.175
"m1.xlarge": 0.350
"c4.large": 0.110
"c4.xlarge": 0.220
"c4.2xlarge": 0.441
"c4.4xlarge": 0.882
"c4.8xlarge": 1.763
"c3.large": 0.105
"c3.xlarge": 0.210
"c3.2xlarge": 0.420
"c3.4xlarge": 0.840
"c3.8xlarge": 1.680
"c1.medium": 0.130
"c1.xlarge": 0.520
"cc2.8xlarge": 2.0
"g2.2xlarge": 0.65
"g2.8xlarge": 2.60
"cg1.4xlarge": 2.1
"m2.xlarge": 0.245
"m2.2xlarge": 0.490
"m2.4xlarge": 0.980
"cr1.8xlarge": 3.5
"i2.xlarge": 0.853
"i2.2xlarge": 1.705
"i2.4xlarge": 3.41
"i2.8xlarge": 6.82
"d2.xlarge": 0.690
"d2.2xlarge": 1.380
"d2.4xlarge": 2.760
"d2.8xlarge": 5.520
"hs1.8xlarge": 4.6
"hi1.4xlarge": 3.1
"t1.micro": 0.02
"t2.nano": 0.0065
"t2.micro": 0.013
"t2.small": 0.026
"t2.medium": 0.052
"t2.large": 0.104
"r3.large": 0.175
"r3.xlarge": 0.350
"r3.2xlarge": 0.700
"r3.4xlarge": 1.400
"r3.8xlarge": 2.800
region_rate =
"ap-southeast-1": 8/6.0
|
[
{
"context": "s MyFirstPlugin\n constructor: () ->\n @name = 'My First Plugin'\n @response = null\n\n handle: (auth, spotify, ",
"end": 69,
"score": 0.7327477335929871,
"start": 54,
"tag": "NAME",
"value": "My First Plugin"
},
{
"context": "l be sent.\n @response = \"This is a reply from #{@name}.\"\n return true\n else\n return false\n",
"end": 296,
"score": 0.8028978109359741,
"start": 289,
"tag": "USERNAME",
"value": "#{@name"
}
] | examples/my_first_plugin.coffee | leek/crispyfi | 127 | class MyFirstPlugin
constructor: () ->
@name = 'My First Plugin'
@response = null
handle: (auth, spotify, volume) ->
if auth.command == 'plugin'
# This will be replied to the channel. If nothing is set, no reply will be sent.
@response = "This is a reply from #{@name}."
return true
else
return false
module.exports = () ->
return new MyFirstPlugin()
| 7338 | class MyFirstPlugin
constructor: () ->
@name = '<NAME>'
@response = null
handle: (auth, spotify, volume) ->
if auth.command == 'plugin'
# This will be replied to the channel. If nothing is set, no reply will be sent.
@response = "This is a reply from #{@name}."
return true
else
return false
module.exports = () ->
return new MyFirstPlugin()
| true | class MyFirstPlugin
constructor: () ->
@name = 'PI:NAME:<NAME>END_PI'
@response = null
handle: (auth, spotify, volume) ->
if auth.command == 'plugin'
# This will be replied to the channel. If nothing is set, no reply will be sent.
@response = "This is a reply from #{@name}."
return true
else
return false
module.exports = () ->
return new MyFirstPlugin()
|
[
{
"context": "ey}) ->\n collection ?= 'videos'\n key ?= 'videoUrl'\n (files, metalsmith, done) ->\n collections =",
"end": 139,
"score": 0.8554819822311401,
"start": 131,
"tag": "KEY",
"value": "videoUrl"
}
] | .metalsmith/plugins/video-scraper.coffee | leeola/kdlearn | 40 | #
# # Video Scrape
#
clone = require 'clone'
module.exports = ({collection, key}) ->
collection ?= 'videos'
key ?= 'videoUrl'
(files, metalsmith, done) ->
collections = metalsmith.metadata().collections
if not collections?
return console.warn 'videoScraper should be run after collections()'
collections[collection] ?= []
coll = collections[collection]
previous = null
for name, file of files
if file[key]?
file = clone file
previous.next = file if previous?
file.previous = previous
file.next = null
previous = file
coll.push file
done()
| 128877 | #
# # Video Scrape
#
clone = require 'clone'
module.exports = ({collection, key}) ->
collection ?= 'videos'
key ?= '<KEY>'
(files, metalsmith, done) ->
collections = metalsmith.metadata().collections
if not collections?
return console.warn 'videoScraper should be run after collections()'
collections[collection] ?= []
coll = collections[collection]
previous = null
for name, file of files
if file[key]?
file = clone file
previous.next = file if previous?
file.previous = previous
file.next = null
previous = file
coll.push file
done()
| true | #
# # Video Scrape
#
clone = require 'clone'
module.exports = ({collection, key}) ->
collection ?= 'videos'
key ?= 'PI:KEY:<KEY>END_PI'
(files, metalsmith, done) ->
collections = metalsmith.metadata().collections
if not collections?
return console.warn 'videoScraper should be run after collections()'
collections[collection] ?= []
coll = collections[collection]
previous = null
for name, file of files
if file[key]?
file = clone file
previous.next = file if previous?
file.previous = previous
file.next = null
previous = file
coll.push file
done()
|
[
{
"context": "_map'\n\ndescribe \"filterMap\", ->\n data = imm\n \"Samus (e2)\":\n animation: [\n { type: \"animat",
"end": 315,
"score": 0.6099522709846497,
"start": 310,
"tag": "NAME",
"value": "Samus"
},
{
"context": " \"animation\", cid: \"c1\", eid: \"e2\", spriteName: \"samus\", state: \"stand-right\" }\n ]\n timer: [",
"end": 410,
"score": 0.5762378573417664,
"start": 407,
"tag": "NAME",
"value": "sam"
},
{
"context": "s\", state: \"stand-right\" }\n ]\n\n samusKey = \"Samus (e2)\"\n zoomerKey = \"Zoomer (e9)\"\n myisamKey = \"myis",
"end": 969,
"score": 0.9911004900932312,
"start": 960,
"tag": "KEY",
"value": "Samus (e2"
},
{
"context": " ]\n\n samusKey = \"Samus (e2)\"\n zoomerKey = \"Zoomer (e9)\"\n myisamKey = \"myisam (e99)\"\n\n describe \"when ",
"end": 997,
"score": 0.9091142416000366,
"start": 987,
"tag": "KEY",
"value": "Zoomer (e9"
},
{
"context": " (e2)\"\n zoomerKey = \"Zoomer (e9)\"\n myisamKey = \"myisam (e99)\"\n\n describe \"when blank or null\", ->\n it \"re",
"end": 1026,
"score": 0.9554958939552307,
"start": 1015,
"tag": "KEY",
"value": "myisam (e99"
},
{
"context": "ata.get(samusKey)\n expectIs filterMap(data, 'Samus'), expected\n expectIs filterMap(data, 'samu'",
"end": 2018,
"score": 0.984320342540741,
"start": 2013,
"tag": "NAME",
"value": "Samus"
}
] | spec/utils/filter_map_spec.coffee | dcrosby42/metroid-clone | 5 | Immutable = require 'immutable'
imm = Immutable.fromJS
{Map,List,Set} = Immutable
chai = require('chai')
expect = chai.expect
assert = chai.assert
expectIs = require('../helpers/expect_helpers').expectIs
filterMap = require '../../src/javascript/utils/filter_map'
describe "filterMap", ->
data = imm
"Samus (e2)":
animation: [
{ type: "animation", cid: "c1", eid: "e2", spriteName: "samus", state: "stand-right" }
]
timer: [
{ type: "timer", value: "100" }
]
"Zoomer (e9)":
zoomer: [
{ type: "zoomer", orientation: "up", crawlDir: "forward" }
]
animation: [
{ type: "animation", cid: "c3", eid: "e9", spriteName: "basic_zoomer", state: "stand-right" }
]
"myisam (e99)":
thingy: [
{ type: 'thingy' }
]
animatorator: [
{ type: "whoknows", cid: "c1", eid: "e2", spriteName: "samus", state: "stand-right" }
]
samusKey = "Samus (e2)"
zoomerKey = "Zoomer (e9)"
myisamKey = "myisam (e99)"
describe "when blank or null", ->
it "returns data", ->
expectIs filterMap(data), data
expectIs filterMap(data,''), data
expectIs filterMap(data,' \t \n '), data
describe "filtering simple maps", ->
it "returns a Map less the keys that don't match the filter", ->
simple = Map
bird: "cardinal"
region: "NA"
tird: "lots"
expectIs filterMap(simple, 'bird'), simple.remove('region').remove('tird')
expectIs filterMap(simple, 'r'), simple
expectIs filterMap(simple, 'ird'), simple.remove('region')
expectIs filterMap(simple, 't'), simple.remove('region').remove('bird')
describe "filtering the toplevel map", ->
it "returns a map with only the keys who match the given text", ->
expected = Map
"#{zoomerKey}": data.get(zoomerKey)
expectIs filterMap(data, 'zoome'), expected
expected = Map
"#{samusKey}": data.get(samusKey)
expectIs filterMap(data, 'Samus'), expected
expectIs filterMap(data, 'samu'), expected
expectIs filterMap(data, 'amu'), expected
expected = Map
"#{samusKey}": data.get(samusKey)
"#{myisamKey}": data.get(myisamKey)
expectIs filterMap(data, 'sam'), expected
describe "keypath-style filter text for first layer of submaps", ->
it "filters child maps", ->
expected = Map
"#{samusKey}": data.get(samusKey).remove("timer")
expectIs filterMap(data, 'samu.anim'), expected
expected = Map
"#{samusKey}": data.get(samusKey).remove("timer")
"#{myisamKey}": data.get(myisamKey).remove("thingy")
expectIs filterMap(data, 'sam.anima'), expected
it "excludes toplevel keys if further steps exclude all children", ->
expectIs filterMap(data, 'sam.funk'), Map()
it "filters subarrays", ->
expected = imm
"#{samusKey}":
animation: [
{ cid: "c1", eid: "e2" }
]
expectIs filterMap(data, 'samu.anim.id'), expected
expected = imm
"#{samusKey}":
animation: [ { type: 'animation' } ]
"#{myisamKey}":
animatorator: [ { type: 'whoknows' } ]
expectIs filterMap(data, 'sam.an.type'), expected
it "supports wildcards", ->
expected = imm
"#{samusKey}":
animation: [ { type: 'animation' } ]
timer: [ { type: 'timer' } ]
"#{zoomerKey}":
animation: [ { type: 'animation' } ]
zoomer: [ { type: 'zoomer' } ]
"#{myisamKey}":
thingy: [ { type: 'thingy' } ]
animatorator: [ { type: 'whoknows' } ]
expectIs filterMap(data, '*.*.type'), expected
| 1856 | Immutable = require 'immutable'
imm = Immutable.fromJS
{Map,List,Set} = Immutable
chai = require('chai')
expect = chai.expect
assert = chai.assert
expectIs = require('../helpers/expect_helpers').expectIs
filterMap = require '../../src/javascript/utils/filter_map'
describe "filterMap", ->
data = imm
"<NAME> (e2)":
animation: [
{ type: "animation", cid: "c1", eid: "e2", spriteName: "<NAME>us", state: "stand-right" }
]
timer: [
{ type: "timer", value: "100" }
]
"Zoomer (e9)":
zoomer: [
{ type: "zoomer", orientation: "up", crawlDir: "forward" }
]
animation: [
{ type: "animation", cid: "c3", eid: "e9", spriteName: "basic_zoomer", state: "stand-right" }
]
"myisam (e99)":
thingy: [
{ type: 'thingy' }
]
animatorator: [
{ type: "whoknows", cid: "c1", eid: "e2", spriteName: "samus", state: "stand-right" }
]
samusKey = "<KEY>)"
zoomerKey = "<KEY>)"
myisamKey = "<KEY>)"
describe "when blank or null", ->
it "returns data", ->
expectIs filterMap(data), data
expectIs filterMap(data,''), data
expectIs filterMap(data,' \t \n '), data
describe "filtering simple maps", ->
it "returns a Map less the keys that don't match the filter", ->
simple = Map
bird: "cardinal"
region: "NA"
tird: "lots"
expectIs filterMap(simple, 'bird'), simple.remove('region').remove('tird')
expectIs filterMap(simple, 'r'), simple
expectIs filterMap(simple, 'ird'), simple.remove('region')
expectIs filterMap(simple, 't'), simple.remove('region').remove('bird')
describe "filtering the toplevel map", ->
it "returns a map with only the keys who match the given text", ->
expected = Map
"#{zoomerKey}": data.get(zoomerKey)
expectIs filterMap(data, 'zoome'), expected
expected = Map
"#{samusKey}": data.get(samusKey)
expectIs filterMap(data, '<NAME>'), expected
expectIs filterMap(data, 'samu'), expected
expectIs filterMap(data, 'amu'), expected
expected = Map
"#{samusKey}": data.get(samusKey)
"#{myisamKey}": data.get(myisamKey)
expectIs filterMap(data, 'sam'), expected
describe "keypath-style filter text for first layer of submaps", ->
it "filters child maps", ->
expected = Map
"#{samusKey}": data.get(samusKey).remove("timer")
expectIs filterMap(data, 'samu.anim'), expected
expected = Map
"#{samusKey}": data.get(samusKey).remove("timer")
"#{myisamKey}": data.get(myisamKey).remove("thingy")
expectIs filterMap(data, 'sam.anima'), expected
it "excludes toplevel keys if further steps exclude all children", ->
expectIs filterMap(data, 'sam.funk'), Map()
it "filters subarrays", ->
expected = imm
"#{samusKey}":
animation: [
{ cid: "c1", eid: "e2" }
]
expectIs filterMap(data, 'samu.anim.id'), expected
expected = imm
"#{samusKey}":
animation: [ { type: 'animation' } ]
"#{myisamKey}":
animatorator: [ { type: 'whoknows' } ]
expectIs filterMap(data, 'sam.an.type'), expected
it "supports wildcards", ->
expected = imm
"#{samusKey}":
animation: [ { type: 'animation' } ]
timer: [ { type: 'timer' } ]
"#{zoomerKey}":
animation: [ { type: 'animation' } ]
zoomer: [ { type: 'zoomer' } ]
"#{myisamKey}":
thingy: [ { type: 'thingy' } ]
animatorator: [ { type: 'whoknows' } ]
expectIs filterMap(data, '*.*.type'), expected
| true | Immutable = require 'immutable'
imm = Immutable.fromJS
{Map,List,Set} = Immutable
chai = require('chai')
expect = chai.expect
assert = chai.assert
expectIs = require('../helpers/expect_helpers').expectIs
filterMap = require '../../src/javascript/utils/filter_map'
describe "filterMap", ->
data = imm
"PI:NAME:<NAME>END_PI (e2)":
animation: [
{ type: "animation", cid: "c1", eid: "e2", spriteName: "PI:NAME:<NAME>END_PIus", state: "stand-right" }
]
timer: [
{ type: "timer", value: "100" }
]
"Zoomer (e9)":
zoomer: [
{ type: "zoomer", orientation: "up", crawlDir: "forward" }
]
animation: [
{ type: "animation", cid: "c3", eid: "e9", spriteName: "basic_zoomer", state: "stand-right" }
]
"myisam (e99)":
thingy: [
{ type: 'thingy' }
]
animatorator: [
{ type: "whoknows", cid: "c1", eid: "e2", spriteName: "samus", state: "stand-right" }
]
samusKey = "PI:KEY:<KEY>END_PI)"
zoomerKey = "PI:KEY:<KEY>END_PI)"
myisamKey = "PI:KEY:<KEY>END_PI)"
describe "when blank or null", ->
it "returns data", ->
expectIs filterMap(data), data
expectIs filterMap(data,''), data
expectIs filterMap(data,' \t \n '), data
describe "filtering simple maps", ->
it "returns a Map less the keys that don't match the filter", ->
simple = Map
bird: "cardinal"
region: "NA"
tird: "lots"
expectIs filterMap(simple, 'bird'), simple.remove('region').remove('tird')
expectIs filterMap(simple, 'r'), simple
expectIs filterMap(simple, 'ird'), simple.remove('region')
expectIs filterMap(simple, 't'), simple.remove('region').remove('bird')
describe "filtering the toplevel map", ->
it "returns a map with only the keys who match the given text", ->
expected = Map
"#{zoomerKey}": data.get(zoomerKey)
expectIs filterMap(data, 'zoome'), expected
expected = Map
"#{samusKey}": data.get(samusKey)
expectIs filterMap(data, 'PI:NAME:<NAME>END_PI'), expected
expectIs filterMap(data, 'samu'), expected
expectIs filterMap(data, 'amu'), expected
expected = Map
"#{samusKey}": data.get(samusKey)
"#{myisamKey}": data.get(myisamKey)
expectIs filterMap(data, 'sam'), expected
describe "keypath-style filter text for first layer of submaps", ->
it "filters child maps", ->
expected = Map
"#{samusKey}": data.get(samusKey).remove("timer")
expectIs filterMap(data, 'samu.anim'), expected
expected = Map
"#{samusKey}": data.get(samusKey).remove("timer")
"#{myisamKey}": data.get(myisamKey).remove("thingy")
expectIs filterMap(data, 'sam.anima'), expected
it "excludes toplevel keys if further steps exclude all children", ->
expectIs filterMap(data, 'sam.funk'), Map()
it "filters subarrays", ->
expected = imm
"#{samusKey}":
animation: [
{ cid: "c1", eid: "e2" }
]
expectIs filterMap(data, 'samu.anim.id'), expected
expected = imm
"#{samusKey}":
animation: [ { type: 'animation' } ]
"#{myisamKey}":
animatorator: [ { type: 'whoknows' } ]
expectIs filterMap(data, 'sam.an.type'), expected
it "supports wildcards", ->
expected = imm
"#{samusKey}":
animation: [ { type: 'animation' } ]
timer: [ { type: 'timer' } ]
"#{zoomerKey}":
animation: [ { type: 'animation' } ]
zoomer: [ { type: 'zoomer' } ]
"#{myisamKey}":
thingy: [ { type: 'thingy' } ]
animatorator: [ { type: 'whoknows' } ]
expectIs filterMap(data, '*.*.type'), expected
|
[
{
"context": "ew text\n\tmyText = new Text\n\t\twidth: auto\n\t\ttext: 'Hello'\n\t\timage: 'http://goo.gl/TY8mx3'\n\t\timagePosition:",
"end": 189,
"score": 0.9980528354644775,
"start": 184,
"tag": "NAME",
"value": "Hello"
},
{
"context": ".io/about-svg/assets/img/parts/fire.gif'\n\t\ttext: 'Hello'\n\t\timagePosition: center\n\t\timageScale: 1.5\n\t\tback",
"end": 3174,
"score": 0.6035387516021729,
"start": 3169,
"tag": "NAME",
"value": "Hello"
},
{
"context": " yes\n\t\timagePosition:\n\t\t\tx: 0\n\t\t\ty: -308\n\t\ttext: 'Hello'\n\t\tbackgroundClip: text\n\t\timageSize: '100% 100%'\n",
"end": 3907,
"score": 0.6882554888725281,
"start": 3902,
"tag": "NAME",
"value": "Hello"
},
{
"context": "\t\t\t\thref: '/haha'\n\t\t\t\tfontSize: 90\n\t\t\t\tfontName: 'Baloo Bhai'\n\t\t\t\tfontWeight: 400\n\t\t\t\tcolor: black\n\t\t\t\tbackgro",
"end": 4329,
"score": 0.9998542666435242,
"start": 4319,
"tag": "NAME",
"value": "Baloo Bhai"
},
{
"context": "00\n\t\t\t\t#href: '/'\n\t\t\t\tfontSize: 90\n\t\t\t\tfontName: 'Baloo Bhai'\n\t\t\t\tfontWeight: 400\n\t\t\t\tcolor: black\n\t\t\t\tbackgro",
"end": 5060,
"score": 0.9998534321784973,
"start": 5050,
"tag": "NAME",
"value": "Baloo Bhai"
},
{
"context": " data\n\t# # \t\treq = usersStore.add\n\t# # \t\t\temail: 'etienne@orbe.io'\n\t# # \t\t\tage: 21\n\t# # \t\treq.onSuccess ->\n\t# # \t\t\t",
"end": 6618,
"score": 0.9999232888221741,
"start": 6603,
"tag": "EMAIL",
"value": "etienne@orbe.io"
},
{
"context": "\t# \thref: '/haha'\n\t# \tfontSize: 90\n\t# \tfontName: 'Baloo Bhai'\n\t# \tfontWeight: 400\n\t# \tcolor: black\n\t# \tbackgro",
"end": 7037,
"score": 0.999859094619751,
"start": 7027,
"tag": "NAME",
"value": "Baloo Bhai"
},
{
"context": "300\n\t# \thref: '/'\n\t# \tfontSize: 90\n\t# \tfontName: 'Baloo Bhai'\n\t# \tfontWeight: 400\n\t# \tcolor: black\n\t# \tbackgro",
"end": 7364,
"score": 0.999857485294342,
"start": 7354,
"tag": "NAME",
"value": "Baloo Bhai"
},
{
"context": "dom(), Color.random()\n\n\thello = new Text\n\t\ttext: 'Hello'\n\t\twidth: 300\n\t\tfontSize: 90\n\t\tfontWeight: 300\n\t\t",
"end": 7974,
"score": 0.5756347179412842,
"start": 7969,
"tag": "NAME",
"value": "Hello"
}
] | test/dev/index.coffee | heschel6/Magic_Experiment | 201 |
App.run ->
Import 'dss'
Font 'Montserrat', '400, 700'
# Choose device to emulate
App.setDevice Device.iPhoneGold
# Create a new text
myText = new Text
width: auto
text: 'Hello'
image: 'http://goo.gl/TY8mx3'
imagePosition: center
imageScale: 1
backgroundClip: text
fontSize: 120
fontWeight: 700
color: clear
myText.center()
Request.send 'http://localhost:8880',
parameters:
data: 42
###
# Create a new list
myList = new List
y: 100
width: 300
length: 20
myList.centerX()
App.page.background = red
# For each element of the list
myList.each (item, index) ->
if not item
item = new ListItem
width: '100%'
height: 128
marginBottom: 10
borderRadius: 5
transition: yes
container = new View
width: '100%'
height: '100%'
backgroundColor: white
parent: item
item.onSwipeLeftEnd ->
container.fadeOut
x: -300
duration: .3
then: ->
item.height = 0
item.marginBottom = 0
return item
###
###
test = new View
bc: red
width: 750
height: 120
App.device.background = Color.random()
Below Tablet, test,
width: 100
backgroundColor: blue
###
#App.setDevice Device.iPad
###
myPlayer = new Player
width: 400
height: 400
video: 'http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4'
myPlayer.play()
###
#device = new Device
# background: Color.gradient('#f52fee', '#6600ff', 120)
# index: 100
#device.content.backgroundColor = blue
#grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
#speechRecognitionList = new SpeechGrammarList()
#speechRecognitionList.addFromString(grammar, 1)
###
test = new Button
bc: red
width: 310
height: 120
mouseDown: ->
this.animate
properties:
x: 10
# this.backgroundColor = Color.random()
###
#App.device.type = NULL
#TouchEmulator.enable()
###
Below iPhone7, test,
width: 100
backgroundColor: blue
###
#Interval .5, ->
# console.log 'dd'
# App.device.type = Utils.pickRandomProperty(Devices)
###
speech = new SpeechRecognition
continuous: yes
lang: 'en-US'
interimResults: yes
#grammars: speechRecognitionList
speech.onResult (event) ->
console.log event
test = new View
bc: red
width: 750
height: 120
click: ->
speech.start()
###
#parent: device.content
###
myPlayer = new Player
width: 480
myCapture = new Capture
video: true
audio: true
success: (stream) ->
myPlayer.video = stream
myPlayer.play()
error: ->
console.log 'err'
###
###
demo = new Text
width: auto
image: 'http://yoksel.github.io/about-svg/assets/img/parts/fire.gif'
text: 'Hello'
imagePosition: center
imageScale: 1.5
backgroundClip: text
fontSize: 140
color: clear
demo.center()
App.page.backgroundColor = black
started = no
speech = NULL
demo.onClick ->
if started is no
speech = new SpeechRecognition()
if speech.supported
started = yes
speech.onEnd (event)->
console.log event
speech.onResult (event)->
console.log event
speech.start()
else
started = no
speech.stop()
###
###
demo = new Text
width: auto
#image: 'http://yoksel.github.io/about-svg/assets/img/parts/fire.gif'
image: '-webkit-linear-gradient(90deg, rgba(0, 0, 0, 0), rgba(0, 0, 0, 1), rgba(0, 0, 0, 0))'
imageRepeat: yes
imagePosition:
x: 0
y: -308
text: 'Hello'
backgroundClip: text
imageSize: '100% 100%'
fontSize: 140
color: clear
demo.center()
App.page.backgroundColor = '#f5f5f5'
demo.animate
props:
imagePositionY: -500
duration: 2
repeat: 10
curve: 'linear'
###
###
Routes
main: ->
firstPage = new Page
backgroundColor: red
hello = new Link
text: 'Hello'
width: 300
href: '/haha'
fontSize: 90
fontName: 'Baloo Bhai'
fontWeight: 400
color: black
background: blue
spacing: 4
hello.background = clear
hello.center()
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say '11:42, congrats to everyone'
return firstPage
haha : ->
secondPage = new Page
backgroundColor: green
hello = new Link
text: 'home'
width: 300
#href: '/'
fontSize: 90
fontName: 'Comfortaa'
fontWeight: 400
color: black
background: blue
spacing: 4
x: 300
y: 40
#margin: 40
hello.center()
hello2 = new Link
text: 'home'
width: 300
#href: '/'
fontSize: 90
fontName: 'Baloo Bhai'
fontWeight: 400
color: black
background: blue
spacing: 4
x: 300
y: 40
#margin: 40
click: ->
hello.animate
duration: 0.3
delay: 1
props:
backgroundColor: red
hello2.animate
duration: 10
props:
x: 0
y: 0
return secondPage
###
# # Instanciate DB
# db = new WebDB
# name: 'demoDB'
# version: 13
# db.onUpgradeNeeded ->
# console.log 'jj'
# usersStore = db.createStore
# name: 'usersdd'
# keyPath: "email"
# usersStore.onSuccess ->
# console.log 'dd'
# # Create index
# usersStore.createIndex
# store: 'usersdd'
# name: 'name'
# keyPath: 'name'
# unique: yes
# usersStore.createIndex
# store: 'usersdd'
# name: 'age'
# keyPath: 'age'
# unique: no
# db.onSuccess ->
# console.log db.request.result
# # transation = db.transaction 'users'
# # #transation.getStore 'us'
# # transation.onComplete (e)->
# # console.log e
# # Create new Store
# db.onVersionChange ->
# console.log db.db
# # # Create new Store
# # usersStore = db.createStore
# # name: 'users'
# # keyPath: "email"
# # usersStore.onSuccess ->
# # console.log 'dd'
# # # Create index
# # usersStore.createIndex
# # store: 'users'
# # name: 'name'
# # keyPath: 'name'
# # unique: yes
# # usersStore.createIndex
# # store: 'users'
# # name: 'age'
# # keyPath: 'age'
# # unique: no
# # # Add data
# # req = usersStore.add
# # email: 'etienne@orbe.io'
# # age: 21
# # req.onSuccess ->
# # log 'nice'
# # console.log usersStore.getAll()
# firstPage = new Page
# backgroundColor: red
# url: '/'
# #Require 'http://d1n0x3qji82z53.cloudfront.net/src-min-noconflict/ace.js'
# #new say 'App fully loaded',
# # voiceID: 4
# hello = new Link
# text: 'Hello'
# width: 300
# href: '/haha'
# fontSize: 90
# fontName: 'Baloo Bhai'
# fontWeight: 400
# color: black
# background: blue
# spacing: 4
# parent: firstPage
# hello.background = clear
# hello.center()
# secondPage = new Page
# backgroundColor: green
# url: '/haha'
# hello = new Link
# text: 'home'
# width: 300
# href: '/'
# fontSize: 90
# fontName: 'Baloo Bhai'
# fontWeight: 400
# color: black
# background: blue
# spacing: 4
# parent: secondPage
###
voice = new Say 'Welcome',
auto: no
voice.onEnd ->
log 'ok'
voice.speak()
###
###
# Import fonts
Fonts [
name: 'Raleway'
weight: '600,500,400,300,100'
,
name: 'Roboto Mono'
weight: '400'
,
name: 'Montserrat'
weight: '600,500,400,300,100'
]
#say Color.gradient Color.gradient Color.random(), Color.random()
Playground.background = Color.gradient Color.random(), Color.random(), Color.random(), Color.random(), Color.random(), Color.random()
hello = new Text
text: 'Hello'
width: 300
fontSize: 90
fontWeight: 300
color: black
spacing: 4
parent: Playground
hello.center()
a = new Layer
props:
bc: red
parent: Playground
Below Tablet, hello,
fontSize: 32
bc: clear
Below Mobile, hello,
fontSize: 16
bc: green
Above TV, hello,
fontSize: 64
bc: blue
###
# Defaults.set 'TextLayer',
# backgroundColor: 'blue'
# h: 200
# Defaults.set 'Text',
# align: 'left'
# width: 'auto'
# Fonts
# name: 'Raleway',
# weight: '600,500,400,300,100'
# Routes
# main: ->
# new MyPage
# about: ->
# new MyPage
# default: ->
# console.log 'default'
# , ->
# console.log 'Before request'
# class MyPage extends Page
# didAppear : ->
# hello = new Layer
# width: 300
# height: 300
# bc: red
# parent: @
# hello.center()
# vr = new VR()
# #vr.getDevices ->
# # console.log 'all good'
# # console.log vr.sensor
| 211939 |
App.run ->
Import 'dss'
Font 'Montserrat', '400, 700'
# Choose device to emulate
App.setDevice Device.iPhoneGold
# Create a new text
myText = new Text
width: auto
text: '<NAME>'
image: 'http://goo.gl/TY8mx3'
imagePosition: center
imageScale: 1
backgroundClip: text
fontSize: 120
fontWeight: 700
color: clear
myText.center()
Request.send 'http://localhost:8880',
parameters:
data: 42
###
# Create a new list
myList = new List
y: 100
width: 300
length: 20
myList.centerX()
App.page.background = red
# For each element of the list
myList.each (item, index) ->
if not item
item = new ListItem
width: '100%'
height: 128
marginBottom: 10
borderRadius: 5
transition: yes
container = new View
width: '100%'
height: '100%'
backgroundColor: white
parent: item
item.onSwipeLeftEnd ->
container.fadeOut
x: -300
duration: .3
then: ->
item.height = 0
item.marginBottom = 0
return item
###
###
test = new View
bc: red
width: 750
height: 120
App.device.background = Color.random()
Below Tablet, test,
width: 100
backgroundColor: blue
###
#App.setDevice Device.iPad
###
myPlayer = new Player
width: 400
height: 400
video: 'http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4'
myPlayer.play()
###
#device = new Device
# background: Color.gradient('#f52fee', '#6600ff', 120)
# index: 100
#device.content.backgroundColor = blue
#grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
#speechRecognitionList = new SpeechGrammarList()
#speechRecognitionList.addFromString(grammar, 1)
###
test = new Button
bc: red
width: 310
height: 120
mouseDown: ->
this.animate
properties:
x: 10
# this.backgroundColor = Color.random()
###
#App.device.type = NULL
#TouchEmulator.enable()
###
Below iPhone7, test,
width: 100
backgroundColor: blue
###
#Interval .5, ->
# console.log 'dd'
# App.device.type = Utils.pickRandomProperty(Devices)
###
speech = new SpeechRecognition
continuous: yes
lang: 'en-US'
interimResults: yes
#grammars: speechRecognitionList
speech.onResult (event) ->
console.log event
test = new View
bc: red
width: 750
height: 120
click: ->
speech.start()
###
#parent: device.content
###
myPlayer = new Player
width: 480
myCapture = new Capture
video: true
audio: true
success: (stream) ->
myPlayer.video = stream
myPlayer.play()
error: ->
console.log 'err'
###
###
demo = new Text
width: auto
image: 'http://yoksel.github.io/about-svg/assets/img/parts/fire.gif'
text: '<NAME>'
imagePosition: center
imageScale: 1.5
backgroundClip: text
fontSize: 140
color: clear
demo.center()
App.page.backgroundColor = black
started = no
speech = NULL
demo.onClick ->
if started is no
speech = new SpeechRecognition()
if speech.supported
started = yes
speech.onEnd (event)->
console.log event
speech.onResult (event)->
console.log event
speech.start()
else
started = no
speech.stop()
###
###
demo = new Text
width: auto
#image: 'http://yoksel.github.io/about-svg/assets/img/parts/fire.gif'
image: '-webkit-linear-gradient(90deg, rgba(0, 0, 0, 0), rgba(0, 0, 0, 1), rgba(0, 0, 0, 0))'
imageRepeat: yes
imagePosition:
x: 0
y: -308
text: '<NAME>'
backgroundClip: text
imageSize: '100% 100%'
fontSize: 140
color: clear
demo.center()
App.page.backgroundColor = '#f5f5f5'
demo.animate
props:
imagePositionY: -500
duration: 2
repeat: 10
curve: 'linear'
###
###
Routes
main: ->
firstPage = new Page
backgroundColor: red
hello = new Link
text: 'Hello'
width: 300
href: '/haha'
fontSize: 90
fontName: '<NAME>'
fontWeight: 400
color: black
background: blue
spacing: 4
hello.background = clear
hello.center()
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say '11:42, congrats to everyone'
return firstPage
haha : ->
secondPage = new Page
backgroundColor: green
hello = new Link
text: 'home'
width: 300
#href: '/'
fontSize: 90
fontName: 'Comfortaa'
fontWeight: 400
color: black
background: blue
spacing: 4
x: 300
y: 40
#margin: 40
hello.center()
hello2 = new Link
text: 'home'
width: 300
#href: '/'
fontSize: 90
fontName: '<NAME>'
fontWeight: 400
color: black
background: blue
spacing: 4
x: 300
y: 40
#margin: 40
click: ->
hello.animate
duration: 0.3
delay: 1
props:
backgroundColor: red
hello2.animate
duration: 10
props:
x: 0
y: 0
return secondPage
###
# # Instanciate DB
# db = new WebDB
# name: 'demoDB'
# version: 13
# db.onUpgradeNeeded ->
# console.log 'jj'
# usersStore = db.createStore
# name: 'usersdd'
# keyPath: "email"
# usersStore.onSuccess ->
# console.log 'dd'
# # Create index
# usersStore.createIndex
# store: 'usersdd'
# name: 'name'
# keyPath: 'name'
# unique: yes
# usersStore.createIndex
# store: 'usersdd'
# name: 'age'
# keyPath: 'age'
# unique: no
# db.onSuccess ->
# console.log db.request.result
# # transation = db.transaction 'users'
# # #transation.getStore 'us'
# # transation.onComplete (e)->
# # console.log e
# # Create new Store
# db.onVersionChange ->
# console.log db.db
# # # Create new Store
# # usersStore = db.createStore
# # name: 'users'
# # keyPath: "email"
# # usersStore.onSuccess ->
# # console.log 'dd'
# # # Create index
# # usersStore.createIndex
# # store: 'users'
# # name: 'name'
# # keyPath: 'name'
# # unique: yes
# # usersStore.createIndex
# # store: 'users'
# # name: 'age'
# # keyPath: 'age'
# # unique: no
# # # Add data
# # req = usersStore.add
# # email: '<EMAIL>'
# # age: 21
# # req.onSuccess ->
# # log 'nice'
# # console.log usersStore.getAll()
# firstPage = new Page
# backgroundColor: red
# url: '/'
# #Require 'http://d1n0x3qji82z53.cloudfront.net/src-min-noconflict/ace.js'
# #new say 'App fully loaded',
# # voiceID: 4
# hello = new Link
# text: 'Hello'
# width: 300
# href: '/haha'
# fontSize: 90
# fontName: '<NAME>'
# fontWeight: 400
# color: black
# background: blue
# spacing: 4
# parent: firstPage
# hello.background = clear
# hello.center()
# secondPage = new Page
# backgroundColor: green
# url: '/haha'
# hello = new Link
# text: 'home'
# width: 300
# href: '/'
# fontSize: 90
# fontName: '<NAME>'
# fontWeight: 400
# color: black
# background: blue
# spacing: 4
# parent: secondPage
###
voice = new Say 'Welcome',
auto: no
voice.onEnd ->
log 'ok'
voice.speak()
###
###
# Import fonts
Fonts [
name: 'Raleway'
weight: '600,500,400,300,100'
,
name: 'Roboto Mono'
weight: '400'
,
name: 'Montserrat'
weight: '600,500,400,300,100'
]
#say Color.gradient Color.gradient Color.random(), Color.random()
Playground.background = Color.gradient Color.random(), Color.random(), Color.random(), Color.random(), Color.random(), Color.random()
hello = new Text
text: '<NAME>'
width: 300
fontSize: 90
fontWeight: 300
color: black
spacing: 4
parent: Playground
hello.center()
a = new Layer
props:
bc: red
parent: Playground
Below Tablet, hello,
fontSize: 32
bc: clear
Below Mobile, hello,
fontSize: 16
bc: green
Above TV, hello,
fontSize: 64
bc: blue
###
# Defaults.set 'TextLayer',
# backgroundColor: 'blue'
# h: 200
# Defaults.set 'Text',
# align: 'left'
# width: 'auto'
# Fonts
# name: 'Raleway',
# weight: '600,500,400,300,100'
# Routes
# main: ->
# new MyPage
# about: ->
# new MyPage
# default: ->
# console.log 'default'
# , ->
# console.log 'Before request'
# class MyPage extends Page
# didAppear : ->
# hello = new Layer
# width: 300
# height: 300
# bc: red
# parent: @
# hello.center()
# vr = new VR()
# #vr.getDevices ->
# # console.log 'all good'
# # console.log vr.sensor
| true |
App.run ->
Import 'dss'
Font 'Montserrat', '400, 700'
# Choose device to emulate
App.setDevice Device.iPhoneGold
# Create a new text
myText = new Text
width: auto
text: 'PI:NAME:<NAME>END_PI'
image: 'http://goo.gl/TY8mx3'
imagePosition: center
imageScale: 1
backgroundClip: text
fontSize: 120
fontWeight: 700
color: clear
myText.center()
Request.send 'http://localhost:8880',
parameters:
data: 42
###
# Create a new list
myList = new List
y: 100
width: 300
length: 20
myList.centerX()
App.page.background = red
# For each element of the list
myList.each (item, index) ->
if not item
item = new ListItem
width: '100%'
height: 128
marginBottom: 10
borderRadius: 5
transition: yes
container = new View
width: '100%'
height: '100%'
backgroundColor: white
parent: item
item.onSwipeLeftEnd ->
container.fadeOut
x: -300
duration: .3
then: ->
item.height = 0
item.marginBottom = 0
return item
###
###
test = new View
bc: red
width: 750
height: 120
App.device.background = Color.random()
Below Tablet, test,
width: 100
backgroundColor: blue
###
#App.setDevice Device.iPad
###
myPlayer = new Player
width: 400
height: 400
video: 'http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4'
myPlayer.play()
###
#device = new Device
# background: Color.gradient('#f52fee', '#6600ff', 120)
# index: 100
#device.content.backgroundColor = blue
#grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
#speechRecognitionList = new SpeechGrammarList()
#speechRecognitionList.addFromString(grammar, 1)
###
test = new Button
bc: red
width: 310
height: 120
mouseDown: ->
this.animate
properties:
x: 10
# this.backgroundColor = Color.random()
###
#App.device.type = NULL
#TouchEmulator.enable()
###
Below iPhone7, test,
width: 100
backgroundColor: blue
###
#Interval .5, ->
# console.log 'dd'
# App.device.type = Utils.pickRandomProperty(Devices)
###
speech = new SpeechRecognition
continuous: yes
lang: 'en-US'
interimResults: yes
#grammars: speechRecognitionList
speech.onResult (event) ->
console.log event
test = new View
bc: red
width: 750
height: 120
click: ->
speech.start()
###
#parent: device.content
###
myPlayer = new Player
width: 480
myCapture = new Capture
video: true
audio: true
success: (stream) ->
myPlayer.video = stream
myPlayer.play()
error: ->
console.log 'err'
###
###
demo = new Text
width: auto
image: 'http://yoksel.github.io/about-svg/assets/img/parts/fire.gif'
text: 'PI:NAME:<NAME>END_PI'
imagePosition: center
imageScale: 1.5
backgroundClip: text
fontSize: 140
color: clear
demo.center()
App.page.backgroundColor = black
started = no
speech = NULL
demo.onClick ->
if started is no
speech = new SpeechRecognition()
if speech.supported
started = yes
speech.onEnd (event)->
console.log event
speech.onResult (event)->
console.log event
speech.start()
else
started = no
speech.stop()
###
###
demo = new Text
width: auto
#image: 'http://yoksel.github.io/about-svg/assets/img/parts/fire.gif'
image: '-webkit-linear-gradient(90deg, rgba(0, 0, 0, 0), rgba(0, 0, 0, 1), rgba(0, 0, 0, 0))'
imageRepeat: yes
imagePosition:
x: 0
y: -308
text: 'PI:NAME:<NAME>END_PI'
backgroundClip: text
imageSize: '100% 100%'
fontSize: 140
color: clear
demo.center()
App.page.backgroundColor = '#f5f5f5'
demo.animate
props:
imagePositionY: -500
duration: 2
repeat: 10
curve: 'linear'
###
###
Routes
main: ->
firstPage = new Page
backgroundColor: red
hello = new Link
text: 'Hello'
width: 300
href: '/haha'
fontSize: 90
fontName: 'PI:NAME:<NAME>END_PI'
fontWeight: 400
color: black
background: blue
spacing: 4
hello.background = clear
hello.center()
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say 'PUSH'
# say '11:42, congrats to everyone'
return firstPage
haha : ->
secondPage = new Page
backgroundColor: green
hello = new Link
text: 'home'
width: 300
#href: '/'
fontSize: 90
fontName: 'Comfortaa'
fontWeight: 400
color: black
background: blue
spacing: 4
x: 300
y: 40
#margin: 40
hello.center()
hello2 = new Link
text: 'home'
width: 300
#href: '/'
fontSize: 90
fontName: 'PI:NAME:<NAME>END_PI'
fontWeight: 400
color: black
background: blue
spacing: 4
x: 300
y: 40
#margin: 40
click: ->
hello.animate
duration: 0.3
delay: 1
props:
backgroundColor: red
hello2.animate
duration: 10
props:
x: 0
y: 0
return secondPage
###
# # Instanciate DB
# db = new WebDB
# name: 'demoDB'
# version: 13
# db.onUpgradeNeeded ->
# console.log 'jj'
# usersStore = db.createStore
# name: 'usersdd'
# keyPath: "email"
# usersStore.onSuccess ->
# console.log 'dd'
# # Create index
# usersStore.createIndex
# store: 'usersdd'
# name: 'name'
# keyPath: 'name'
# unique: yes
# usersStore.createIndex
# store: 'usersdd'
# name: 'age'
# keyPath: 'age'
# unique: no
# db.onSuccess ->
# console.log db.request.result
# # transation = db.transaction 'users'
# # #transation.getStore 'us'
# # transation.onComplete (e)->
# # console.log e
# # Create new Store
# db.onVersionChange ->
# console.log db.db
# # # Create new Store
# # usersStore = db.createStore
# # name: 'users'
# # keyPath: "email"
# # usersStore.onSuccess ->
# # console.log 'dd'
# # # Create index
# # usersStore.createIndex
# # store: 'users'
# # name: 'name'
# # keyPath: 'name'
# # unique: yes
# # usersStore.createIndex
# # store: 'users'
# # name: 'age'
# # keyPath: 'age'
# # unique: no
# # # Add data
# # req = usersStore.add
# # email: 'PI:EMAIL:<EMAIL>END_PI'
# # age: 21
# # req.onSuccess ->
# # log 'nice'
# # console.log usersStore.getAll()
# firstPage = new Page
# backgroundColor: red
# url: '/'
# #Require 'http://d1n0x3qji82z53.cloudfront.net/src-min-noconflict/ace.js'
# #new say 'App fully loaded',
# # voiceID: 4
# hello = new Link
# text: 'Hello'
# width: 300
# href: '/haha'
# fontSize: 90
# fontName: 'PI:NAME:<NAME>END_PI'
# fontWeight: 400
# color: black
# background: blue
# spacing: 4
# parent: firstPage
# hello.background = clear
# hello.center()
# secondPage = new Page
# backgroundColor: green
# url: '/haha'
# hello = new Link
# text: 'home'
# width: 300
# href: '/'
# fontSize: 90
# fontName: 'PI:NAME:<NAME>END_PI'
# fontWeight: 400
# color: black
# background: blue
# spacing: 4
# parent: secondPage
###
voice = new Say 'Welcome',
auto: no
voice.onEnd ->
log 'ok'
voice.speak()
###
###
# Import fonts
Fonts [
name: 'Raleway'
weight: '600,500,400,300,100'
,
name: 'Roboto Mono'
weight: '400'
,
name: 'Montserrat'
weight: '600,500,400,300,100'
]
#say Color.gradient Color.gradient Color.random(), Color.random()
Playground.background = Color.gradient Color.random(), Color.random(), Color.random(), Color.random(), Color.random(), Color.random()
hello = new Text
text: 'PI:NAME:<NAME>END_PI'
width: 300
fontSize: 90
fontWeight: 300
color: black
spacing: 4
parent: Playground
hello.center()
a = new Layer
props:
bc: red
parent: Playground
Below Tablet, hello,
fontSize: 32
bc: clear
Below Mobile, hello,
fontSize: 16
bc: green
Above TV, hello,
fontSize: 64
bc: blue
###
# Defaults.set 'TextLayer',
# backgroundColor: 'blue'
# h: 200
# Defaults.set 'Text',
# align: 'left'
# width: 'auto'
# Fonts
# name: 'Raleway',
# weight: '600,500,400,300,100'
# Routes
# main: ->
# new MyPage
# about: ->
# new MyPage
# default: ->
# console.log 'default'
# , ->
# console.log 'Before request'
# class MyPage extends Page
# didAppear : ->
# hello = new Layer
# width: 300
# height: 300
# bc: red
# parent: @
# hello.center()
# vr = new VR()
# #vr.getDevices ->
# # console.log 'all good'
# # console.log vr.sensor
|
[
{
"context": "e.toJSON\", ->\n json = App.User.new(firstName: \"Lance\").toJSON()\n \n expected =\n id: ",
"end": 163,
"score": 0.999642014503479,
"start": 158,
"tag": "NAME",
"value": "Lance"
},
{
"context": " undefined,\n firstName: 'Lance'\n rating: 2.5\n admin: ",
"end": 434,
"score": 0.9996109008789062,
"start": 429,
"tag": "NAME",
"value": "Lance"
}
] | test/cases/model/shared/serializationTest.coffee | jivagoalves/tower | 1 | scope = null
criteria = null
user = null
describe 'Tower.ModelSerialization', ->
test "instance.toJSON", ->
json = App.User.new(firstName: "Lance").toJSON()
expected =
id: undefined,
createdAt: undefined,
likes: 0,
tags: [],
postIds: [],
updatedAt: undefined,
firstName: 'Lance'
rating: 2.5
admin: false
cachedMembershipIds: []
for key, value of expected
assert.deepEqual value, json[key] | 46253 | scope = null
criteria = null
user = null
describe 'Tower.ModelSerialization', ->
test "instance.toJSON", ->
json = App.User.new(firstName: "<NAME>").toJSON()
expected =
id: undefined,
createdAt: undefined,
likes: 0,
tags: [],
postIds: [],
updatedAt: undefined,
firstName: '<NAME>'
rating: 2.5
admin: false
cachedMembershipIds: []
for key, value of expected
assert.deepEqual value, json[key] | true | scope = null
criteria = null
user = null
describe 'Tower.ModelSerialization', ->
test "instance.toJSON", ->
json = App.User.new(firstName: "PI:NAME:<NAME>END_PI").toJSON()
expected =
id: undefined,
createdAt: undefined,
likes: 0,
tags: [],
postIds: [],
updatedAt: undefined,
firstName: 'PI:NAME:<NAME>END_PI'
rating: 2.5
admin: false
cachedMembershipIds: []
for key, value of expected
assert.deepEqual value, json[key] |
[
{
"context": "1,\n \"vm_forwarding_email\" : \"sridhar.2@choochee.com\",\n \"vm_forwarding_enabled\" :",
"end": 1017,
"score": 0.9999263286590576,
"start": 995,
"tag": "EMAIL",
"value": "sridhar.2@choochee.com"
},
{
"context": ",\n \"member_email_address\" : \"sridhar.2@choochee.com\",\n \"member_extension_number\"",
"end": 1457,
"score": 0.9999271631240845,
"start": 1435,
"tag": "EMAIL",
"value": "sridhar.2@choochee.com"
},
{
"context": "008,\n \"member_first_name\" : \"sridh\",\n \"member_last_name\" : \"jal",
"end": 1620,
"score": 0.9997519850730896,
"start": 1615,
"tag": "NAME",
"value": "sridh"
},
{
"context": "idh\",\n \"member_last_name\" : \"jall\",\n \"memberid\" : 10000001\n ",
"end": 1671,
"score": 0.9997107982635498,
"start": 1667,
"tag": "NAME",
"value": "jall"
},
{
"context": "001,\n \"voicemail_forward_email\" : \"sridhar.2@choochee.com\"\n },\n { \"allow_member_f",
"end": 1849,
"score": 0.9999281167984009,
"start": 1827,
"tag": "EMAIL",
"value": "sridhar.2@choochee.com"
},
{
"context": "1,\n \"vm_forwarding_email\" : \"sridhar.2@choochee.com\",\n \"vm_forwarding_enabled\" :",
"end": 4154,
"score": 0.9999306201934814,
"start": 4132,
"tag": "EMAIL",
"value": "sridhar.2@choochee.com"
},
{
"context": ",\n \"member_email_address\" : \"sridhar.2@choochee.com\",\n \"member_extension_number\"",
"end": 4574,
"score": 0.9999315738677979,
"start": 4552,
"tag": "EMAIL",
"value": "sridhar.2@choochee.com"
},
{
"context": "008,\n \"member_first_name\" : \"sridh\",\n \"member_last_name\" : \"jal",
"end": 4737,
"score": 0.9963852763175964,
"start": 4732,
"tag": "NAME",
"value": "sridh"
},
{
"context": "idh\",\n \"member_last_name\" : \"jall\",\n \"memberid\" : 10000001\n ",
"end": 4788,
"score": 0.9955421686172485,
"start": 4784,
"tag": "NAME",
"value": "jall"
},
{
"context": "001,\n \"voicemail_forward_email\" : \"sridhar.2@choochee.com\"\n },\n { \"allow_member_f",
"end": 4966,
"score": 0.9999303817749023,
"start": 4944,
"tag": "EMAIL",
"value": "sridhar.2@choochee.com"
},
{
"context": "1,\n \"vm_forwarding_email\" : \"forwarding@email.com\",\n \"vm_forwarding_enabled\" :",
"end": 5786,
"score": 0.9999163746833801,
"start": 5766,
"tag": "EMAIL",
"value": "forwarding@email.com"
},
{
"context": ",\n \"member_email_address\" : \"sridhar.2@choochee.com\",\n \"member_extension_number\"",
"end": 6224,
"score": 0.9999282956123352,
"start": 6202,
"tag": "EMAIL",
"value": "sridhar.2@choochee.com"
},
{
"context": "008,\n \"member_first_name\" : \"sridh\",\n \"member_last_name\" : \"jal",
"end": 6387,
"score": 0.9991686940193176,
"start": 6382,
"tag": "NAME",
"value": "sridh"
},
{
"context": "idh\",\n \"member_last_name\" : \"jall\",\n \"memberid\" : 10000001\n ",
"end": 6438,
"score": 0.9993504285812378,
"start": 6434,
"tag": "NAME",
"value": "jall"
},
{
"context": "rue,\n \"voicemail_forward_email\" : \"forwarding@email.com\"\n }\n ] },\n \"service\"",
"end": 6669,
"score": 0.9999146461486816,
"start": 6649,
"tag": "EMAIL",
"value": "forwarding@email.com"
}
] | models/group/fixture/get_groups.coffee | signonsridhar/sridhar_hbs | 0 | define(['can_fixture'], (can)->
can.fixture('GET /bss/group?action=getgroups', (req, resp)->
return `{ "response" : { "execution_time" : 198,
"response_code" : 100,
"response_data" : { "call_groups" : [ { "allow_member_forward" : false,
"enable_custom_greeting" : false,
"enable_dnd" : false,
"enable_voicemail" : true,
"enable_voicemail_forward_email" : false,
"extensions" : [ { "call_waiting_enabled" : false,
"devices" : [ ],
"dnd_enabled" : false,
"extension_number" : 888,
"extensionid" : 10000011,
"forwarding_enabled" : false,
"group_members" : [ ],
"international_calls_enabled" : false,
"phone_numbers" : [ ],
"tenantid" : 10000001,
"vm_forwarding_email" : "sridhar.2@choochee.com",
"vm_forwarding_enabled" : false
} ],
"group_call_type" : "conference",
"group_name" : "Conference",
"groupid" : 10000001,
"members" : [ { "enable_phone_ring" : true,
"group_name" : "Conference",
"groupid" : 10000001,
"member_email_address" : "sridhar.2@choochee.com",
"member_extension_number" : 201,
"member_extensionid" : 10000008,
"member_first_name" : "sridh",
"member_last_name" : "jall",
"memberid" : 10000001
} ],
"tenantid" : 10000001,
"voicemail_forward_email" : "sridhar.2@choochee.com"
},
{ "allow_member_forward" : false,
"enable_auto_attendant" : true,
"enable_company_directory" : true,
"enable_company_extensions" : true,
"enable_custom_greeting" : false,
"enable_dnd" : false,
"enable_group_menu" : true,
"enable_group_ring" : false,
"enable_voicemail" : true,
"enable_voicemail_forward_email" : true,
"extensions" : [ { "call_waiting_enabled" : false,
"devices" : [ ],
"dnd_enabled" : false,
"extension_number" : 200,
"extensionid" : 10000012,
"forwarding_enabled" : false,
"group_members" : [ ],
"international_calls_enabled" : false,
"phone_numbers" : [ { "area_code" : "408",
"caller_id" : 0,
"city" : "MORGAN HILL",
"country_code" : "1",
"didid" : 10000074,
"extension" : 0,
"is_assigned" : true,
"is_conference" : false,
"is_toll_free" : false,
"partner_code" : "tmus",
"phone_number_address" : { "address_city" : "san jose",
"address_country" : "US",
"address_state" : "CA",
"address_street1" : "441 camille cir",
"address_street2" : "441 camille cir",
"address_zip" : "95134",
"did_id" : 10000074,
"extension_id" : 10000012,
"user_id" : 10000001
},
"phonenumber" : 14085000775,
"state" : "CA",
"type" : "main_line"
} ],
"tenantid" : 10000001,
"vm_forwarding_email" : "sridhar.2@choochee.com",
"vm_forwarding_enabled" : true
} ],
"group_call_type" : "ivr",
"group_name" : "Main",
"groupid" : 10000002,
"members" : [ { "enable_phone_ring" : true,
"group_name" : "Main",
"groupid" : 10000002,
"member_email_address" : "sridhar.2@choochee.com",
"member_extension_number" : 201,
"member_extensionid" : 10000008,
"member_first_name" : "sridh",
"member_last_name" : "jall",
"memberid" : 10000001
} ],
"tenantid" : 10000001,
"voicemail_forward_email" : "sridhar.2@choochee.com"
},
{ "allow_member_forward" : true,
"enable_custom_greeting" : false,
"enable_dnd" : false,
"enable_voicemail" : true,
"enable_voicemail_forward_email" : false,
"extensions" : [ { "call_waiting_enabled" : false,
"devices" : [ ],
"dnd_enabled" : false,
"extension_number" : 221,
"extensionid" : 10000014,
"forwarding_enabled" : false,
"group_members" : [ ],
"international_calls_enabled" : false,
"phone_numbers" : [ ],
"tenantid" : 10000001,
"vm_forwarding_email" : "forwarding@email.com",
"vm_forwarding_enabled" : false
} ],
"group_call_type" : "sequential",
"group_name" : "Marketing",
"groupid" : 10000003,
"members" : [ { "enable_phone_ring" : true,
"group_name" : "Marketing",
"groupid" : 10000003,
"member_email_address" : "sridhar.2@choochee.com",
"member_extension_number" : 201,
"member_extensionid" : 10000008,
"member_first_name" : "sridh",
"member_last_name" : "jall",
"memberid" : 10000001
} ],
"tenantid" : 10000001,
"use_in_groups_auto_attendant" : true,
"voicemail_forward_email" : "forwarding@email.com"
}
] },
"service" : "getgroups",
"timestamp" : "2013-11-19T23:08:13+0000",
"version" : "1.0"
} }`
)
) | 128615 | define(['can_fixture'], (can)->
can.fixture('GET /bss/group?action=getgroups', (req, resp)->
return `{ "response" : { "execution_time" : 198,
"response_code" : 100,
"response_data" : { "call_groups" : [ { "allow_member_forward" : false,
"enable_custom_greeting" : false,
"enable_dnd" : false,
"enable_voicemail" : true,
"enable_voicemail_forward_email" : false,
"extensions" : [ { "call_waiting_enabled" : false,
"devices" : [ ],
"dnd_enabled" : false,
"extension_number" : 888,
"extensionid" : 10000011,
"forwarding_enabled" : false,
"group_members" : [ ],
"international_calls_enabled" : false,
"phone_numbers" : [ ],
"tenantid" : 10000001,
"vm_forwarding_email" : "<EMAIL>",
"vm_forwarding_enabled" : false
} ],
"group_call_type" : "conference",
"group_name" : "Conference",
"groupid" : 10000001,
"members" : [ { "enable_phone_ring" : true,
"group_name" : "Conference",
"groupid" : 10000001,
"member_email_address" : "<EMAIL>",
"member_extension_number" : 201,
"member_extensionid" : 10000008,
"member_first_name" : "<NAME>",
"member_last_name" : "<NAME>",
"memberid" : 10000001
} ],
"tenantid" : 10000001,
"voicemail_forward_email" : "<EMAIL>"
},
{ "allow_member_forward" : false,
"enable_auto_attendant" : true,
"enable_company_directory" : true,
"enable_company_extensions" : true,
"enable_custom_greeting" : false,
"enable_dnd" : false,
"enable_group_menu" : true,
"enable_group_ring" : false,
"enable_voicemail" : true,
"enable_voicemail_forward_email" : true,
"extensions" : [ { "call_waiting_enabled" : false,
"devices" : [ ],
"dnd_enabled" : false,
"extension_number" : 200,
"extensionid" : 10000012,
"forwarding_enabled" : false,
"group_members" : [ ],
"international_calls_enabled" : false,
"phone_numbers" : [ { "area_code" : "408",
"caller_id" : 0,
"city" : "MORGAN HILL",
"country_code" : "1",
"didid" : 10000074,
"extension" : 0,
"is_assigned" : true,
"is_conference" : false,
"is_toll_free" : false,
"partner_code" : "tmus",
"phone_number_address" : { "address_city" : "san jose",
"address_country" : "US",
"address_state" : "CA",
"address_street1" : "441 camille cir",
"address_street2" : "441 camille cir",
"address_zip" : "95134",
"did_id" : 10000074,
"extension_id" : 10000012,
"user_id" : 10000001
},
"phonenumber" : 14085000775,
"state" : "CA",
"type" : "main_line"
} ],
"tenantid" : 10000001,
"vm_forwarding_email" : "<EMAIL>",
"vm_forwarding_enabled" : true
} ],
"group_call_type" : "ivr",
"group_name" : "Main",
"groupid" : 10000002,
"members" : [ { "enable_phone_ring" : true,
"group_name" : "Main",
"groupid" : 10000002,
"member_email_address" : "<EMAIL>",
"member_extension_number" : 201,
"member_extensionid" : 10000008,
"member_first_name" : "<NAME>",
"member_last_name" : "<NAME>",
"memberid" : 10000001
} ],
"tenantid" : 10000001,
"voicemail_forward_email" : "<EMAIL>"
},
{ "allow_member_forward" : true,
"enable_custom_greeting" : false,
"enable_dnd" : false,
"enable_voicemail" : true,
"enable_voicemail_forward_email" : false,
"extensions" : [ { "call_waiting_enabled" : false,
"devices" : [ ],
"dnd_enabled" : false,
"extension_number" : 221,
"extensionid" : 10000014,
"forwarding_enabled" : false,
"group_members" : [ ],
"international_calls_enabled" : false,
"phone_numbers" : [ ],
"tenantid" : 10000001,
"vm_forwarding_email" : "<EMAIL>",
"vm_forwarding_enabled" : false
} ],
"group_call_type" : "sequential",
"group_name" : "Marketing",
"groupid" : 10000003,
"members" : [ { "enable_phone_ring" : true,
"group_name" : "Marketing",
"groupid" : 10000003,
"member_email_address" : "<EMAIL>",
"member_extension_number" : 201,
"member_extensionid" : 10000008,
"member_first_name" : "<NAME>",
"member_last_name" : "<NAME>",
"memberid" : 10000001
} ],
"tenantid" : 10000001,
"use_in_groups_auto_attendant" : true,
"voicemail_forward_email" : "<EMAIL>"
}
] },
"service" : "getgroups",
"timestamp" : "2013-11-19T23:08:13+0000",
"version" : "1.0"
} }`
)
) | true | define(['can_fixture'], (can)->
can.fixture('GET /bss/group?action=getgroups', (req, resp)->
return `{ "response" : { "execution_time" : 198,
"response_code" : 100,
"response_data" : { "call_groups" : [ { "allow_member_forward" : false,
"enable_custom_greeting" : false,
"enable_dnd" : false,
"enable_voicemail" : true,
"enable_voicemail_forward_email" : false,
"extensions" : [ { "call_waiting_enabled" : false,
"devices" : [ ],
"dnd_enabled" : false,
"extension_number" : 888,
"extensionid" : 10000011,
"forwarding_enabled" : false,
"group_members" : [ ],
"international_calls_enabled" : false,
"phone_numbers" : [ ],
"tenantid" : 10000001,
"vm_forwarding_email" : "PI:EMAIL:<EMAIL>END_PI",
"vm_forwarding_enabled" : false
} ],
"group_call_type" : "conference",
"group_name" : "Conference",
"groupid" : 10000001,
"members" : [ { "enable_phone_ring" : true,
"group_name" : "Conference",
"groupid" : 10000001,
"member_email_address" : "PI:EMAIL:<EMAIL>END_PI",
"member_extension_number" : 201,
"member_extensionid" : 10000008,
"member_first_name" : "PI:NAME:<NAME>END_PI",
"member_last_name" : "PI:NAME:<NAME>END_PI",
"memberid" : 10000001
} ],
"tenantid" : 10000001,
"voicemail_forward_email" : "PI:EMAIL:<EMAIL>END_PI"
},
{ "allow_member_forward" : false,
"enable_auto_attendant" : true,
"enable_company_directory" : true,
"enable_company_extensions" : true,
"enable_custom_greeting" : false,
"enable_dnd" : false,
"enable_group_menu" : true,
"enable_group_ring" : false,
"enable_voicemail" : true,
"enable_voicemail_forward_email" : true,
"extensions" : [ { "call_waiting_enabled" : false,
"devices" : [ ],
"dnd_enabled" : false,
"extension_number" : 200,
"extensionid" : 10000012,
"forwarding_enabled" : false,
"group_members" : [ ],
"international_calls_enabled" : false,
"phone_numbers" : [ { "area_code" : "408",
"caller_id" : 0,
"city" : "MORGAN HILL",
"country_code" : "1",
"didid" : 10000074,
"extension" : 0,
"is_assigned" : true,
"is_conference" : false,
"is_toll_free" : false,
"partner_code" : "tmus",
"phone_number_address" : { "address_city" : "san jose",
"address_country" : "US",
"address_state" : "CA",
"address_street1" : "441 camille cir",
"address_street2" : "441 camille cir",
"address_zip" : "95134",
"did_id" : 10000074,
"extension_id" : 10000012,
"user_id" : 10000001
},
"phonenumber" : 14085000775,
"state" : "CA",
"type" : "main_line"
} ],
"tenantid" : 10000001,
"vm_forwarding_email" : "PI:EMAIL:<EMAIL>END_PI",
"vm_forwarding_enabled" : true
} ],
"group_call_type" : "ivr",
"group_name" : "Main",
"groupid" : 10000002,
"members" : [ { "enable_phone_ring" : true,
"group_name" : "Main",
"groupid" : 10000002,
"member_email_address" : "PI:EMAIL:<EMAIL>END_PI",
"member_extension_number" : 201,
"member_extensionid" : 10000008,
"member_first_name" : "PI:NAME:<NAME>END_PI",
"member_last_name" : "PI:NAME:<NAME>END_PI",
"memberid" : 10000001
} ],
"tenantid" : 10000001,
"voicemail_forward_email" : "PI:EMAIL:<EMAIL>END_PI"
},
{ "allow_member_forward" : true,
"enable_custom_greeting" : false,
"enable_dnd" : false,
"enable_voicemail" : true,
"enable_voicemail_forward_email" : false,
"extensions" : [ { "call_waiting_enabled" : false,
"devices" : [ ],
"dnd_enabled" : false,
"extension_number" : 221,
"extensionid" : 10000014,
"forwarding_enabled" : false,
"group_members" : [ ],
"international_calls_enabled" : false,
"phone_numbers" : [ ],
"tenantid" : 10000001,
"vm_forwarding_email" : "PI:EMAIL:<EMAIL>END_PI",
"vm_forwarding_enabled" : false
} ],
"group_call_type" : "sequential",
"group_name" : "Marketing",
"groupid" : 10000003,
"members" : [ { "enable_phone_ring" : true,
"group_name" : "Marketing",
"groupid" : 10000003,
"member_email_address" : "PI:EMAIL:<EMAIL>END_PI",
"member_extension_number" : 201,
"member_extensionid" : 10000008,
"member_first_name" : "PI:NAME:<NAME>END_PI",
"member_last_name" : "PI:NAME:<NAME>END_PI",
"memberid" : 10000001
} ],
"tenantid" : 10000001,
"use_in_groups_auto_attendant" : true,
"voicemail_forward_email" : "PI:EMAIL:<EMAIL>END_PI"
}
] },
"service" : "getgroups",
"timestamp" : "2013-11-19T23:08:13+0000",
"version" : "1.0"
} }`
)
) |
[
{
"context": "### ^\nBSD 3-Clause License\n\nCopyright (c) 2017, Stephan Jorek\nAll rights reserved.\n\nRedistribution and use in s",
"end": 61,
"score": 0.9998380541801453,
"start": 48,
"tag": "NAME",
"value": "Stephan Jorek"
}
] | src/Unordered/RuleMap.coffee | sjorek/goatee-rules.js | 0 | ### ^
BSD 3-Clause License
Copyright (c) 2017, Stephan Jorek
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
{
parse
} = require '../Rules'
{
trim
} = require '../Utility'
###
# # RuleMaps …
# -----------------
#
# … look like “identifier: expression; identifier2: expression2”. They
# provide a simplified implementation of:
# @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-ElementCSSInlineStyle
# @see http://www.w3.org/TR/1998/REC-html40-19980424/present/styles.html#h-14.2.2
###
###*
# -------------
# @class RuleMap
# @namespace GoateeRules.Unordered
###
class RuleMap
###*
# -------------
# @param {Object} [rules]
# @param {Object} [priority]
# @constructor
###
constructor: (@rules = {}, @priority = {}) ->
###*
# -------------
# adds a new rule to this instance
#
# @method add
# @param {String} key
# @param {mixed} value
# @param {Boolean} important
# @return {RuleMap}
###
add: (key, value, important) ->
id = @normalizeKey key
exists = @rules.hasOwnProperty(id)
return this unless important is true or \
exists is false or \
@priority.hasOwnProperty(id) is false
@rules[id] = @normalizeValue value
@priority[id] = true if important is true
this
###*
# -------------
# Call fn for each rule's key, value and priority and return this.
#
# @method map
# @param {Function} fn
# @return {Array}
###
each: (fn) ->
@map(fn)
@
###*
# -------------
# Call fn for each rule's key, value and priority and return the resulting
# Array.
#
# @method map
# @param {Function} fn
# @return {Array}
###
map: (fn) ->
fn key, value, @priority.hasOwnProperty(key) for own key, value of @rules
###*
# -------------
# Parses the given string and applies the resulting map to this map, taking
# priorities into consideration.
#
# @method apply
# @param {String} string
# @return {RuleMap}
###
apply: (string) ->
parse string, @
###*
# -------------
# Opposite of @project(map). Returns this map with all rules from given map
# applied to this map, taking my and their priorities into consideration.
#
# @method inject
# @param {RuleMap} map
# @return {RuleMap}
###
inject: (map) ->
map.project this
this
###*
# -------------
# Opposite of @inject(map). Returns the given map with all my rules applied
# to given map, taking their and my priorities into consideration.
#
# @method inject
# @param {RuleMap} map
# @return {RuleMap}
###
project: (map) ->
@each (key, value, priority) ->
map.add(key, value, priority)
this
###*
# -------------
# @method normalizeKey
# @param {String} string
# @return {String}
###
normalizeKey: (string) ->
trim string
###*
# -------------
# @method normalizeValue
# @param {String} string
# @return {String}
###
normalizeValue: (string) ->
trim string
###*
# -------------
# Return each rule's key, value and priority as Array of Arrays.
#
# @method flatten
# @param {Function} fn
# @return {Array}
###
flatten: (fn) ->
@map (key, value, priority) ->
[key, value, priority]
###*
# -------------
# Return a css-like representation of this maps' rules. It looks, like:
#
# identifier: value; key: expression=1+1; action: expr( … ; … );
#
# @method toString
# @return {String}
###
toString: ->
rules = @map (key, value, priority) ->
rule = "#{key}:#{value}"
rule += " !important" if priority is true
rule
rules.join ';'
module.exports = RuleMap
| 29887 | ### ^
BSD 3-Clause License
Copyright (c) 2017, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
{
parse
} = require '../Rules'
{
trim
} = require '../Utility'
###
# # RuleMaps …
# -----------------
#
# … look like “identifier: expression; identifier2: expression2”. They
# provide a simplified implementation of:
# @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-ElementCSSInlineStyle
# @see http://www.w3.org/TR/1998/REC-html40-19980424/present/styles.html#h-14.2.2
###
###*
# -------------
# @class RuleMap
# @namespace GoateeRules.Unordered
###
class RuleMap
###*
# -------------
# @param {Object} [rules]
# @param {Object} [priority]
# @constructor
###
constructor: (@rules = {}, @priority = {}) ->
###*
# -------------
# adds a new rule to this instance
#
# @method add
# @param {String} key
# @param {mixed} value
# @param {Boolean} important
# @return {RuleMap}
###
add: (key, value, important) ->
id = @normalizeKey key
exists = @rules.hasOwnProperty(id)
return this unless important is true or \
exists is false or \
@priority.hasOwnProperty(id) is false
@rules[id] = @normalizeValue value
@priority[id] = true if important is true
this
###*
# -------------
# Call fn for each rule's key, value and priority and return this.
#
# @method map
# @param {Function} fn
# @return {Array}
###
each: (fn) ->
@map(fn)
@
###*
# -------------
# Call fn for each rule's key, value and priority and return the resulting
# Array.
#
# @method map
# @param {Function} fn
# @return {Array}
###
map: (fn) ->
fn key, value, @priority.hasOwnProperty(key) for own key, value of @rules
###*
# -------------
# Parses the given string and applies the resulting map to this map, taking
# priorities into consideration.
#
# @method apply
# @param {String} string
# @return {RuleMap}
###
apply: (string) ->
parse string, @
###*
# -------------
# Opposite of @project(map). Returns this map with all rules from given map
# applied to this map, taking my and their priorities into consideration.
#
# @method inject
# @param {RuleMap} map
# @return {RuleMap}
###
inject: (map) ->
map.project this
this
###*
# -------------
# Opposite of @inject(map). Returns the given map with all my rules applied
# to given map, taking their and my priorities into consideration.
#
# @method inject
# @param {RuleMap} map
# @return {RuleMap}
###
project: (map) ->
@each (key, value, priority) ->
map.add(key, value, priority)
this
###*
# -------------
# @method normalizeKey
# @param {String} string
# @return {String}
###
normalizeKey: (string) ->
trim string
###*
# -------------
# @method normalizeValue
# @param {String} string
# @return {String}
###
normalizeValue: (string) ->
trim string
###*
# -------------
# Return each rule's key, value and priority as Array of Arrays.
#
# @method flatten
# @param {Function} fn
# @return {Array}
###
flatten: (fn) ->
@map (key, value, priority) ->
[key, value, priority]
###*
# -------------
# Return a css-like representation of this maps' rules. It looks, like:
#
# identifier: value; key: expression=1+1; action: expr( … ; … );
#
# @method toString
# @return {String}
###
toString: ->
rules = @map (key, value, priority) ->
rule = "#{key}:#{value}"
rule += " !important" if priority is true
rule
rules.join ';'
module.exports = RuleMap
| true | ### ^
BSD 3-Clause License
Copyright (c) 2017, PI:NAME:<NAME>END_PI
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
{
parse
} = require '../Rules'
{
trim
} = require '../Utility'
###
# # RuleMaps …
# -----------------
#
# … look like “identifier: expression; identifier2: expression2”. They
# provide a simplified implementation of:
# @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-ElementCSSInlineStyle
# @see http://www.w3.org/TR/1998/REC-html40-19980424/present/styles.html#h-14.2.2
###
###*
# -------------
# @class RuleMap
# @namespace GoateeRules.Unordered
###
class RuleMap
###*
# -------------
# @param {Object} [rules]
# @param {Object} [priority]
# @constructor
###
constructor: (@rules = {}, @priority = {}) ->
###*
# -------------
# adds a new rule to this instance
#
# @method add
# @param {String} key
# @param {mixed} value
# @param {Boolean} important
# @return {RuleMap}
###
add: (key, value, important) ->
id = @normalizeKey key
exists = @rules.hasOwnProperty(id)
return this unless important is true or \
exists is false or \
@priority.hasOwnProperty(id) is false
@rules[id] = @normalizeValue value
@priority[id] = true if important is true
this
###*
# -------------
# Call fn for each rule's key, value and priority and return this.
#
# @method map
# @param {Function} fn
# @return {Array}
###
each: (fn) ->
@map(fn)
@
###*
# -------------
# Call fn for each rule's key, value and priority and return the resulting
# Array.
#
# @method map
# @param {Function} fn
# @return {Array}
###
map: (fn) ->
fn key, value, @priority.hasOwnProperty(key) for own key, value of @rules
###*
# -------------
# Parses the given string and applies the resulting map to this map, taking
# priorities into consideration.
#
# @method apply
# @param {String} string
# @return {RuleMap}
###
apply: (string) ->
parse string, @
###*
# -------------
# Opposite of @project(map). Returns this map with all rules from given map
# applied to this map, taking my and their priorities into consideration.
#
# @method inject
# @param {RuleMap} map
# @return {RuleMap}
###
inject: (map) ->
map.project this
this
###*
# -------------
# Opposite of @inject(map). Returns the given map with all my rules applied
# to given map, taking their and my priorities into consideration.
#
# @method inject
# @param {RuleMap} map
# @return {RuleMap}
###
project: (map) ->
@each (key, value, priority) ->
map.add(key, value, priority)
this
###*
# -------------
# @method normalizeKey
# @param {String} string
# @return {String}
###
normalizeKey: (string) ->
trim string
###*
# -------------
# @method normalizeValue
# @param {String} string
# @return {String}
###
normalizeValue: (string) ->
trim string
###*
# -------------
# Return each rule's key, value and priority as Array of Arrays.
#
# @method flatten
# @param {Function} fn
# @return {Array}
###
flatten: (fn) ->
@map (key, value, priority) ->
[key, value, priority]
###*
# -------------
# Return a css-like representation of this maps' rules. It looks, like:
#
# identifier: value; key: expression=1+1; action: expr( … ; … );
#
# @method toString
# @return {String}
###
toString: ->
rules = @map (key, value, priority) ->
rule = "#{key}:#{value}"
rule += " !important" if priority is true
rule
rules.join ';'
module.exports = RuleMap
|
[
{
"context": "###\nCopyright 2016 Resin.io\n\nLicensed under the Apache License, Version 2.0 (",
"end": 27,
"score": 0.6181449890136719,
"start": 25,
"tag": "NAME",
"value": "io"
}
] | lib/operations.coffee | resin-io/resin-devices-operations | 2 | ###
Copyright 2016 Resin.io
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.
###
###*
# @module operations
###
EventEmitter = require('events').EventEmitter
Promise = require('bluebird')
rindle = require('rindle')
_ = require('lodash')
utils = require('./utils')
action = require('./action')
###*
# @summary Execute a set of operations over an image
# @function
# @public
#
# @description
# This function returns an `EventEmitter` object that emits the following events:
#
# - `state (Object state)`: When an operation is going to be executed. The state object contains the `operation` and the progress `percentage` (0-100).
# - `stdout (String data)`: When an operation prints to stdout.
# - `stderr (String data)`: When an operation prints to stderr.
# - `burn (String state)`: When the `burn` operation emits progress state.
# - `error (Error error)`: When an error happens.
# - `end`: When all the operations are completed successfully.
#
# @param {String} image - path to image
# @param {Object[]} operations - array of operations
# @param {Object} options - configuration options
#
# @returns {EventEmitter}
#
# @example
# execution = operations.execute 'foo/bar.img', [
# command: 'copy'
# from:
# partition:
# primary: 1
# path: '/bitstreams/parallella_e16_headless_gpiose_7010.bit.bin'
# to:
# partition:
# primary: 1
# path: '/parallella.bit.bin'
# when:
# coprocessorCore: '16'
# processorType: 'Z7010'
# ,
# command: 'copy'
# from:
# partition:
# primary: 1
# path: '/bistreams/parallella_e16_headless_gpiose_7020.bit.bin'
# to:
# partition:
# primary: 1
# path: '/parallella.bit.bin'
# when:
# coprocessorCore: '16'
# processorType: 'Z7020'
# ],
# coprocessorCore: '16'
# processorType: 'Z7010'
#
# execution.on('stdout', process.stdout.write)
# execution.on('stderr', process.stderr.write)
#
# execution.on 'state', (state) ->
# console.log(state.operation.command)
# console.log(state.percentage)
#
# execution.on 'error', (error) ->
# throw error
#
# execution.on 'end', ->
# console.log('Finished all operations')
###
exports.execute = (image, operations, options = {}) ->
options.os ?= utils.getOperatingSystem()
missingOptions = utils.getMissingOptions(operations, options)
if not _.isEmpty(missingOptions)
throw new Error("Missing options: #{missingOptions.join(', ')}")
emitter = new EventEmitter()
Promise.try ->
operations = utils.filterWhenMatches(operations, options)
promises = _.map operations, (operation) ->
return action.run(image, operation, options)
# There is an edge case where the event emitter instance
# emits the `end` event before the client is able to
# register a listener for it.
emitterOn = emitter.on
emitter.on = (event, callback) ->
if event is 'end' and emitter.ended
return callback()
emitterOn.apply(emitter, arguments)
Promise.delay(1).then ->
Promise.each promises, (promise, index) ->
state =
operation: operations[index]
percentage: action.getOperationProgress(index, operations)
emitter.emit('state', state)
promise().then (actionEvent) ->
# Pipe stdout/stderr events
if not actionEvent?
return
actionEvent.stdout?.on 'data', (data) ->
emitter.emit('stdout', data)
actionEvent.stderr?.on 'data', (data) ->
emitter.emit('stderr', data)
# Emit burn command progress state as `burn`
actionEvent.on 'progress', (state) ->
emitter.emit('burn', state)
return rindle.wait(actionEvent).spread (code) ->
# TODO: the number check is needed here because `rindle` is getting
# the `{ sourceChecksum }` response that is otherwise treated as an error code
# This hack is ugly and should be fixed in a better way.
if _.isNumber(code) and code isnt 0
throw new Error("Exited with error code: #{code}")
.then ->
emitter.emit('end')
# Mark the emitter as ended.
# Used to stub `emitter.on()` above.
emitter.ended = true
.catch (error) ->
emitter.emit('error', error)
return emitter
| 123537 | ###
Copyright 2016 Resin.<NAME>
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.
###
###*
# @module operations
###
EventEmitter = require('events').EventEmitter
Promise = require('bluebird')
rindle = require('rindle')
_ = require('lodash')
utils = require('./utils')
action = require('./action')
###*
# @summary Execute a set of operations over an image
# @function
# @public
#
# @description
# This function returns an `EventEmitter` object that emits the following events:
#
# - `state (Object state)`: When an operation is going to be executed. The state object contains the `operation` and the progress `percentage` (0-100).
# - `stdout (String data)`: When an operation prints to stdout.
# - `stderr (String data)`: When an operation prints to stderr.
# - `burn (String state)`: When the `burn` operation emits progress state.
# - `error (Error error)`: When an error happens.
# - `end`: When all the operations are completed successfully.
#
# @param {String} image - path to image
# @param {Object[]} operations - array of operations
# @param {Object} options - configuration options
#
# @returns {EventEmitter}
#
# @example
# execution = operations.execute 'foo/bar.img', [
# command: 'copy'
# from:
# partition:
# primary: 1
# path: '/bitstreams/parallella_e16_headless_gpiose_7010.bit.bin'
# to:
# partition:
# primary: 1
# path: '/parallella.bit.bin'
# when:
# coprocessorCore: '16'
# processorType: 'Z7010'
# ,
# command: 'copy'
# from:
# partition:
# primary: 1
# path: '/bistreams/parallella_e16_headless_gpiose_7020.bit.bin'
# to:
# partition:
# primary: 1
# path: '/parallella.bit.bin'
# when:
# coprocessorCore: '16'
# processorType: 'Z7020'
# ],
# coprocessorCore: '16'
# processorType: 'Z7010'
#
# execution.on('stdout', process.stdout.write)
# execution.on('stderr', process.stderr.write)
#
# execution.on 'state', (state) ->
# console.log(state.operation.command)
# console.log(state.percentage)
#
# execution.on 'error', (error) ->
# throw error
#
# execution.on 'end', ->
# console.log('Finished all operations')
###
exports.execute = (image, operations, options = {}) ->
options.os ?= utils.getOperatingSystem()
missingOptions = utils.getMissingOptions(operations, options)
if not _.isEmpty(missingOptions)
throw new Error("Missing options: #{missingOptions.join(', ')}")
emitter = new EventEmitter()
Promise.try ->
operations = utils.filterWhenMatches(operations, options)
promises = _.map operations, (operation) ->
return action.run(image, operation, options)
# There is an edge case where the event emitter instance
# emits the `end` event before the client is able to
# register a listener for it.
emitterOn = emitter.on
emitter.on = (event, callback) ->
if event is 'end' and emitter.ended
return callback()
emitterOn.apply(emitter, arguments)
Promise.delay(1).then ->
Promise.each promises, (promise, index) ->
state =
operation: operations[index]
percentage: action.getOperationProgress(index, operations)
emitter.emit('state', state)
promise().then (actionEvent) ->
# Pipe stdout/stderr events
if not actionEvent?
return
actionEvent.stdout?.on 'data', (data) ->
emitter.emit('stdout', data)
actionEvent.stderr?.on 'data', (data) ->
emitter.emit('stderr', data)
# Emit burn command progress state as `burn`
actionEvent.on 'progress', (state) ->
emitter.emit('burn', state)
return rindle.wait(actionEvent).spread (code) ->
# TODO: the number check is needed here because `rindle` is getting
# the `{ sourceChecksum }` response that is otherwise treated as an error code
# This hack is ugly and should be fixed in a better way.
if _.isNumber(code) and code isnt 0
throw new Error("Exited with error code: #{code}")
.then ->
emitter.emit('end')
# Mark the emitter as ended.
# Used to stub `emitter.on()` above.
emitter.ended = true
.catch (error) ->
emitter.emit('error', error)
return emitter
| true | ###
Copyright 2016 Resin.PI:NAME:<NAME>END_PI
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.
###
###*
# @module operations
###
EventEmitter = require('events').EventEmitter
Promise = require('bluebird')
rindle = require('rindle')
_ = require('lodash')
utils = require('./utils')
action = require('./action')
###*
# @summary Execute a set of operations over an image
# @function
# @public
#
# @description
# This function returns an `EventEmitter` object that emits the following events:
#
# - `state (Object state)`: When an operation is going to be executed. The state object contains the `operation` and the progress `percentage` (0-100).
# - `stdout (String data)`: When an operation prints to stdout.
# - `stderr (String data)`: When an operation prints to stderr.
# - `burn (String state)`: When the `burn` operation emits progress state.
# - `error (Error error)`: When an error happens.
# - `end`: When all the operations are completed successfully.
#
# @param {String} image - path to image
# @param {Object[]} operations - array of operations
# @param {Object} options - configuration options
#
# @returns {EventEmitter}
#
# @example
# execution = operations.execute 'foo/bar.img', [
# command: 'copy'
# from:
# partition:
# primary: 1
# path: '/bitstreams/parallella_e16_headless_gpiose_7010.bit.bin'
# to:
# partition:
# primary: 1
# path: '/parallella.bit.bin'
# when:
# coprocessorCore: '16'
# processorType: 'Z7010'
# ,
# command: 'copy'
# from:
# partition:
# primary: 1
# path: '/bistreams/parallella_e16_headless_gpiose_7020.bit.bin'
# to:
# partition:
# primary: 1
# path: '/parallella.bit.bin'
# when:
# coprocessorCore: '16'
# processorType: 'Z7020'
# ],
# coprocessorCore: '16'
# processorType: 'Z7010'
#
# execution.on('stdout', process.stdout.write)
# execution.on('stderr', process.stderr.write)
#
# execution.on 'state', (state) ->
# console.log(state.operation.command)
# console.log(state.percentage)
#
# execution.on 'error', (error) ->
# throw error
#
# execution.on 'end', ->
# console.log('Finished all operations')
###
exports.execute = (image, operations, options = {}) ->
options.os ?= utils.getOperatingSystem()
missingOptions = utils.getMissingOptions(operations, options)
if not _.isEmpty(missingOptions)
throw new Error("Missing options: #{missingOptions.join(', ')}")
emitter = new EventEmitter()
Promise.try ->
operations = utils.filterWhenMatches(operations, options)
promises = _.map operations, (operation) ->
return action.run(image, operation, options)
# There is an edge case where the event emitter instance
# emits the `end` event before the client is able to
# register a listener for it.
emitterOn = emitter.on
emitter.on = (event, callback) ->
if event is 'end' and emitter.ended
return callback()
emitterOn.apply(emitter, arguments)
Promise.delay(1).then ->
Promise.each promises, (promise, index) ->
state =
operation: operations[index]
percentage: action.getOperationProgress(index, operations)
emitter.emit('state', state)
promise().then (actionEvent) ->
# Pipe stdout/stderr events
if not actionEvent?
return
actionEvent.stdout?.on 'data', (data) ->
emitter.emit('stdout', data)
actionEvent.stderr?.on 'data', (data) ->
emitter.emit('stderr', data)
# Emit burn command progress state as `burn`
actionEvent.on 'progress', (state) ->
emitter.emit('burn', state)
return rindle.wait(actionEvent).spread (code) ->
# TODO: the number check is needed here because `rindle` is getting
# the `{ sourceChecksum }` response that is otherwise treated as an error code
# This hack is ugly and should be fixed in a better way.
if _.isNumber(code) and code isnt 0
throw new Error("Exited with error code: #{code}")
.then ->
emitter.emit('end')
# Mark the emitter as ended.
# Used to stub `emitter.on()` above.
emitter.ended = true
.catch (error) ->
emitter.emit('error', error)
return emitter
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998481273651123,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ",
"end": 60,
"score": 0.999929666519165,
"start": 44,
"tag": "EMAIL",
"value": "ts33kr@gmail.com"
}
] | library/applied/bower.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
bower = require "bower"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
moment = require "moment"
assert = require "assert"
colors = require "colors"
crypto = require "crypto"
nconf = require "nconf"
https = require "https"
path = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{rmdirSyncRecursive} = require "wrench"
{Barebones} = require "../membrane/skeleton"
# This abstract base class provides the dynamic Bower support for
# the services that inherit or compose this ABC. This implementation
# allows for each service to have its own, isolated tree of packages
# that will be dynamically installed via Bower package manager. The
# implementation provides convenient way of requiring frontend libs.
# Please refer to the implementation for details on the mechanics.
module.exports.BowerToolkit = class BowerToolkit extends Barebones
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# This class definition can be used to override the mechanisms
# that determine the location of the Bower collection directory
# of this service. That is, where all the Bower packages will be
# installed. Default is `undefined`, which will lead mechanism to
# use a separate directory for this service. The directory will
# have the name of the service internal, MD5 referential tagging.
@BOWER_DIRECTORY: undefined
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: bowerings: yes
# A hook that will be called prior to registering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
register: (kernel, router, next) ->
assert isf = _.isFunction # just a shorthand
explicit = try @BOWER_DIRECTORY or undefined
explicit = explicit.call this if isf explicit
assert isolate = "%s at %s".cyan # long paths
assert disposition = @constructor.disposition()
assert reference = disposition.reference or null
assert not _.isEmpty idc = explicit or reference
assert _.isObject(kernel), "got no kernel object"
assert _.isObject(router), "got no router object"
assert _.isFunction(next), "got no next function"
bowerings = @constructor.bowerings ?= new Array()
options = _.map(bowerings, (bowr) -> bowr.options)
options = _.merge Object.create(Object()), options...
directory = kernel.scope.managed "pub", "bower", idc
assert _.isString(directory), "error with Bower dir"
options.directory = bowerings.directory = directory
targets = _.map bowerings, (b) -> return b.target
running = "Configure Bower packages for %s service"
assert identify = @constructor.identify().underline
logger.info running.grey, identify.underline or no
logger.debug isolate, identify, directory.underline
return @installation kernel, targets, options, next
# This one is an internalized routine that gets preemptively
# called by the Bower configuration and installation sequence
# to see if the Bower installation directory has expired its
# TTL that is configured. If so, the system will run a Bower
# install command. If not, however, the system will silently
# skip it for this service/directory. If, however, directory
# does not exists - this method will not be interfering with.
staleInstallation: (kernel, targets, options, next) ->
expr = "Bower directory staled %s at %s".cyan
assert c = current = moment().toDate() # current
assert ident = @constructor.identify().underline
bowerings = @constructor.bowerings ?= new Array()
ndr = "could not find the Bower collector directory"
assert _.isArray(bowerings), "no intern bowerings"
assert _.isString(dir = bowerings.directory), ndr
return false unless stale = nconf.get "bower:stale"
return false unless fs.existsSync dir.toString()
assert not _.isEmpty stats = (try fs.statSync dir)
return false unless stats.isDirectory() is yes
assert _.isNumber(stale), "inval stale TTL (sec)"
assert _.isObject mtime = try moment stats.mtime
assert mtime.add "seconds", stale # expired time
logger.debug expr, mtime.fromNow().bold, ident
expired = mtime.isBefore() # directory expired?
return fs.utimesSync(dir, c, c) and no if expired
next(); return yes # skip install, not expired
# An internal routine that launches the actual Bower installer.
# It takes a series of pre calculated parameters to be able to
# perform the installation properly. Plese refer to the register
# hook implementation in this ABC service for more information.
# Also, refer to the method implementation for understanding.
installation: (kernel, targets, options, next) ->
assert install = bower.commands.install or 0
bowerings = @constructor.bowerings ?= Array()
return null if @staleInstallation arguments...
assert installer = install targets, {}, options
assert _.isObject(kernel), "got no kernel object"
assert _.isFunction(next), "got no next function"
kernel.domain.add installer if kernel.domain.add
assert removing = "Clense (rm) Bower collector at %s"
assert _.isString directory = bowerings.directory
fwd = (arg) => kernel.domain.emit "error", arg...
mark = => logger.warn removing.yellow, directory
destroy = => mark try rmdirSyncRecursive directory
installer.on "error", -> destroy(); fwd arguments
return installer.on "end", (installed) => do =>
message = "Getting Bower library %s@%s at %s"
assert bowerings.installed = installed or 0
fn = (argvector) -> next.call this, undefined
fn _.each _.values(installed or []), (packet) =>
assert meta = packet.pkgMeta or Object()
name = (try meta.name.underline) or null
version = (try meta.version.underline) or 0
where = @constructor.identify().underline
assert variable = [name, version, where]
logger.debug message.cyan, variable...
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an asynchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
assert list = bower.commands.list or null
bowerings = @constructor.bowerings ?= Array()
cached context if cached = try bowerings.cached
return next undefined if _.isFunction cached or 0
identify = try @constructor.identify().underline
assert options = directory: bowerings.directory
message = "Executing the Bower sequences in %s"
logger.debug message.yellow, identify.toString()
assert _.isString(symbol), "cannot found symbol"
assert _.isObject(context), "located no context"
assert _.isObject(request), "located no request"
assert _.isFunction(next), "got no next function"
esc = (reg) -> new RegExp RegExp.escape "#{reg}"
match = (k) -> (b) -> return esc(k).test b.target
sorter = (v, k) -> _.findIndex bowerings, match(k)
finder = (v, k) -> _.find bowerings, match(k)
list(paths: yes, options).on "end", (paths) =>
assert scope = [sorter, finder, paths]
bowerings.cached = @cachier scope...
bowerings.cached context; next()
# This complicated definition is used to produce and then install
# a method that is going to be cached and used for each request
# once the initial Bower package installation is done. Please do
# refer to the `prelude` implementation in this class for the info.
# Please, refer to the method implementation for an understanding.
cachier: (sorter, finder, paths) -> (context) ->
nsorter = -> fback sorter(arguments...), +999
fback = (vx, fx) -> if vx > 0 then vx else fx
assert sorted = try _.sortBy paths, nsorter
assert files = try _.flatten _.values sorted
locate = (fx) -> _.findKey paths, resides(fx)
resides = (f) -> (x) -> f is x or try f in x
assert _.isFunction(sorter), "no sorter func"
assert _.isFunction(finder), "no finder func"
assert _.isObject(context), "no contex object"
assert not _.isEmpty(paths), "no paths array"
for file in files then do (paths, file) ->
bowering = try finder null, locate(file)
entry = try bowering?.entry or undefined
assert formatted = try "#{file}/#{entry}"
context.scripts.push formatted if entry
return unless _.isEmpty entry?.toString()
ext = (fxt) -> path.extname(file) is fxt
context.scripts.push file if ext ".js"
context.sheets.push file if ext ".css"
# Install the specified packages via Bower into the specific
# location within the system that is figured out automatically.
# All packages installed via Bower will be served as the static
# assets, by using the `pub` env dir. The package installation
# is per service and automatically will be included in `prelude`.
# Refer to the rest of methods for slightly better understanding.
@bower: (target, entry, xoptions={}) ->
ent = "an entrypoint has to be a valid string"
noTarget = "target must be a Bower package spec"
noOptions = "options must be the plain JS object"
message = "Adding Bower package %s to service %s"
options = _.find(arguments, _.isPlainObject) or {}
assert previous = this.bowerings or new Array()
assert previous = try _.unique(previous) or null
return previous unless (try arguments.length) > 0
assert identify = id = this.identify().underline
assert _.isString(entry or null), ent if entry
assert _.isObject(options or null), noOptions
assert _.isString(target or null), noTarget
logger.silly message.cyan, target.bold, id
return this.bowerings = previous.concat
options: options or Object()
entry: entry or undefined
target: target.toString()
| 104863 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
bower = require "bower"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
moment = require "moment"
assert = require "assert"
colors = require "colors"
crypto = require "crypto"
nconf = require "nconf"
https = require "https"
path = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{rmdirSyncRecursive} = require "wrench"
{Barebones} = require "../membrane/skeleton"
# This abstract base class provides the dynamic Bower support for
# the services that inherit or compose this ABC. This implementation
# allows for each service to have its own, isolated tree of packages
# that will be dynamically installed via Bower package manager. The
# implementation provides convenient way of requiring frontend libs.
# Please refer to the implementation for details on the mechanics.
module.exports.BowerToolkit = class BowerToolkit extends Barebones
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# This class definition can be used to override the mechanisms
# that determine the location of the Bower collection directory
# of this service. That is, where all the Bower packages will be
# installed. Default is `undefined`, which will lead mechanism to
# use a separate directory for this service. The directory will
# have the name of the service internal, MD5 referential tagging.
@BOWER_DIRECTORY: undefined
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: bowerings: yes
# A hook that will be called prior to registering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
register: (kernel, router, next) ->
assert isf = _.isFunction # just a shorthand
explicit = try @BOWER_DIRECTORY or undefined
explicit = explicit.call this if isf explicit
assert isolate = "%s at %s".cyan # long paths
assert disposition = @constructor.disposition()
assert reference = disposition.reference or null
assert not _.isEmpty idc = explicit or reference
assert _.isObject(kernel), "got no kernel object"
assert _.isObject(router), "got no router object"
assert _.isFunction(next), "got no next function"
bowerings = @constructor.bowerings ?= new Array()
options = _.map(bowerings, (bowr) -> bowr.options)
options = _.merge Object.create(Object()), options...
directory = kernel.scope.managed "pub", "bower", idc
assert _.isString(directory), "error with Bower dir"
options.directory = bowerings.directory = directory
targets = _.map bowerings, (b) -> return b.target
running = "Configure Bower packages for %s service"
assert identify = @constructor.identify().underline
logger.info running.grey, identify.underline or no
logger.debug isolate, identify, directory.underline
return @installation kernel, targets, options, next
# This one is an internalized routine that gets preemptively
# called by the Bower configuration and installation sequence
# to see if the Bower installation directory has expired its
# TTL that is configured. If so, the system will run a Bower
# install command. If not, however, the system will silently
# skip it for this service/directory. If, however, directory
# does not exists - this method will not be interfering with.
staleInstallation: (kernel, targets, options, next) ->
expr = "Bower directory staled %s at %s".cyan
assert c = current = moment().toDate() # current
assert ident = @constructor.identify().underline
bowerings = @constructor.bowerings ?= new Array()
ndr = "could not find the Bower collector directory"
assert _.isArray(bowerings), "no intern bowerings"
assert _.isString(dir = bowerings.directory), ndr
return false unless stale = nconf.get "bower:stale"
return false unless fs.existsSync dir.toString()
assert not _.isEmpty stats = (try fs.statSync dir)
return false unless stats.isDirectory() is yes
assert _.isNumber(stale), "inval stale TTL (sec)"
assert _.isObject mtime = try moment stats.mtime
assert mtime.add "seconds", stale # expired time
logger.debug expr, mtime.fromNow().bold, ident
expired = mtime.isBefore() # directory expired?
return fs.utimesSync(dir, c, c) and no if expired
next(); return yes # skip install, not expired
# An internal routine that launches the actual Bower installer.
# It takes a series of pre calculated parameters to be able to
# perform the installation properly. Plese refer to the register
# hook implementation in this ABC service for more information.
# Also, refer to the method implementation for understanding.
installation: (kernel, targets, options, next) ->
assert install = bower.commands.install or 0
bowerings = @constructor.bowerings ?= Array()
return null if @staleInstallation arguments...
assert installer = install targets, {}, options
assert _.isObject(kernel), "got no kernel object"
assert _.isFunction(next), "got no next function"
kernel.domain.add installer if kernel.domain.add
assert removing = "Clense (rm) Bower collector at %s"
assert _.isString directory = bowerings.directory
fwd = (arg) => kernel.domain.emit "error", arg...
mark = => logger.warn removing.yellow, directory
destroy = => mark try rmdirSyncRecursive directory
installer.on "error", -> destroy(); fwd arguments
return installer.on "end", (installed) => do =>
message = "Getting Bower library %s@%s at %s"
assert bowerings.installed = installed or 0
fn = (argvector) -> next.call this, undefined
fn _.each _.values(installed or []), (packet) =>
assert meta = packet.pkgMeta or Object()
name = (try meta.name.underline) or null
version = (try meta.version.underline) or 0
where = @constructor.identify().underline
assert variable = [name, version, where]
logger.debug message.cyan, variable...
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an asynchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
assert list = bower.commands.list or null
bowerings = @constructor.bowerings ?= Array()
cached context if cached = try bowerings.cached
return next undefined if _.isFunction cached or 0
identify = try @constructor.identify().underline
assert options = directory: bowerings.directory
message = "Executing the Bower sequences in %s"
logger.debug message.yellow, identify.toString()
assert _.isString(symbol), "cannot found symbol"
assert _.isObject(context), "located no context"
assert _.isObject(request), "located no request"
assert _.isFunction(next), "got no next function"
esc = (reg) -> new RegExp RegExp.escape "#{reg}"
match = (k) -> (b) -> return esc(k).test b.target
sorter = (v, k) -> _.findIndex bowerings, match(k)
finder = (v, k) -> _.find bowerings, match(k)
list(paths: yes, options).on "end", (paths) =>
assert scope = [sorter, finder, paths]
bowerings.cached = @cachier scope...
bowerings.cached context; next()
# This complicated definition is used to produce and then install
# a method that is going to be cached and used for each request
# once the initial Bower package installation is done. Please do
# refer to the `prelude` implementation in this class for the info.
# Please, refer to the method implementation for an understanding.
cachier: (sorter, finder, paths) -> (context) ->
nsorter = -> fback sorter(arguments...), +999
fback = (vx, fx) -> if vx > 0 then vx else fx
assert sorted = try _.sortBy paths, nsorter
assert files = try _.flatten _.values sorted
locate = (fx) -> _.findKey paths, resides(fx)
resides = (f) -> (x) -> f is x or try f in x
assert _.isFunction(sorter), "no sorter func"
assert _.isFunction(finder), "no finder func"
assert _.isObject(context), "no contex object"
assert not _.isEmpty(paths), "no paths array"
for file in files then do (paths, file) ->
bowering = try finder null, locate(file)
entry = try bowering?.entry or undefined
assert formatted = try "#{file}/#{entry}"
context.scripts.push formatted if entry
return unless _.isEmpty entry?.toString()
ext = (fxt) -> path.extname(file) is fxt
context.scripts.push file if ext ".js"
context.sheets.push file if ext ".css"
# Install the specified packages via Bower into the specific
# location within the system that is figured out automatically.
# All packages installed via Bower will be served as the static
# assets, by using the `pub` env dir. The package installation
# is per service and automatically will be included in `prelude`.
# Refer to the rest of methods for slightly better understanding.
@bower: (target, entry, xoptions={}) ->
ent = "an entrypoint has to be a valid string"
noTarget = "target must be a Bower package spec"
noOptions = "options must be the plain JS object"
message = "Adding Bower package %s to service %s"
options = _.find(arguments, _.isPlainObject) or {}
assert previous = this.bowerings or new Array()
assert previous = try _.unique(previous) or null
return previous unless (try arguments.length) > 0
assert identify = id = this.identify().underline
assert _.isString(entry or null), ent if entry
assert _.isObject(options or null), noOptions
assert _.isString(target or null), noTarget
logger.silly message.cyan, target.bold, id
return this.bowerings = previous.concat
options: options or Object()
entry: entry or undefined
target: target.toString()
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
bower = require "bower"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
moment = require "moment"
assert = require "assert"
colors = require "colors"
crypto = require "crypto"
nconf = require "nconf"
https = require "https"
path = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{rmdirSyncRecursive} = require "wrench"
{Barebones} = require "../membrane/skeleton"
# This abstract base class provides the dynamic Bower support for
# the services that inherit or compose this ABC. This implementation
# allows for each service to have its own, isolated tree of packages
# that will be dynamically installed via Bower package manager. The
# implementation provides convenient way of requiring frontend libs.
# Please refer to the implementation for details on the mechanics.
module.exports.BowerToolkit = class BowerToolkit extends Barebones
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# This class definition can be used to override the mechanisms
# that determine the location of the Bower collection directory
# of this service. That is, where all the Bower packages will be
# installed. Default is `undefined`, which will lead mechanism to
# use a separate directory for this service. The directory will
# have the name of the service internal, MD5 referential tagging.
@BOWER_DIRECTORY: undefined
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: bowerings: yes
# A hook that will be called prior to registering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
register: (kernel, router, next) ->
assert isf = _.isFunction # just a shorthand
explicit = try @BOWER_DIRECTORY or undefined
explicit = explicit.call this if isf explicit
assert isolate = "%s at %s".cyan # long paths
assert disposition = @constructor.disposition()
assert reference = disposition.reference or null
assert not _.isEmpty idc = explicit or reference
assert _.isObject(kernel), "got no kernel object"
assert _.isObject(router), "got no router object"
assert _.isFunction(next), "got no next function"
bowerings = @constructor.bowerings ?= new Array()
options = _.map(bowerings, (bowr) -> bowr.options)
options = _.merge Object.create(Object()), options...
directory = kernel.scope.managed "pub", "bower", idc
assert _.isString(directory), "error with Bower dir"
options.directory = bowerings.directory = directory
targets = _.map bowerings, (b) -> return b.target
running = "Configure Bower packages for %s service"
assert identify = @constructor.identify().underline
logger.info running.grey, identify.underline or no
logger.debug isolate, identify, directory.underline
return @installation kernel, targets, options, next
# This one is an internalized routine that gets preemptively
# called by the Bower configuration and installation sequence
# to see if the Bower installation directory has expired its
# TTL that is configured. If so, the system will run a Bower
# install command. If not, however, the system will silently
# skip it for this service/directory. If, however, directory
# does not exists - this method will not be interfering with.
staleInstallation: (kernel, targets, options, next) ->
expr = "Bower directory staled %s at %s".cyan
assert c = current = moment().toDate() # current
assert ident = @constructor.identify().underline
bowerings = @constructor.bowerings ?= new Array()
ndr = "could not find the Bower collector directory"
assert _.isArray(bowerings), "no intern bowerings"
assert _.isString(dir = bowerings.directory), ndr
return false unless stale = nconf.get "bower:stale"
return false unless fs.existsSync dir.toString()
assert not _.isEmpty stats = (try fs.statSync dir)
return false unless stats.isDirectory() is yes
assert _.isNumber(stale), "inval stale TTL (sec)"
assert _.isObject mtime = try moment stats.mtime
assert mtime.add "seconds", stale # expired time
logger.debug expr, mtime.fromNow().bold, ident
expired = mtime.isBefore() # directory expired?
return fs.utimesSync(dir, c, c) and no if expired
next(); return yes # skip install, not expired
# An internal routine that launches the actual Bower installer.
# It takes a series of pre calculated parameters to be able to
# perform the installation properly. Plese refer to the register
# hook implementation in this ABC service for more information.
# Also, refer to the method implementation for understanding.
installation: (kernel, targets, options, next) ->
assert install = bower.commands.install or 0
bowerings = @constructor.bowerings ?= Array()
return null if @staleInstallation arguments...
assert installer = install targets, {}, options
assert _.isObject(kernel), "got no kernel object"
assert _.isFunction(next), "got no next function"
kernel.domain.add installer if kernel.domain.add
assert removing = "Clense (rm) Bower collector at %s"
assert _.isString directory = bowerings.directory
fwd = (arg) => kernel.domain.emit "error", arg...
mark = => logger.warn removing.yellow, directory
destroy = => mark try rmdirSyncRecursive directory
installer.on "error", -> destroy(); fwd arguments
return installer.on "end", (installed) => do =>
message = "Getting Bower library %s@%s at %s"
assert bowerings.installed = installed or 0
fn = (argvector) -> next.call this, undefined
fn _.each _.values(installed or []), (packet) =>
assert meta = packet.pkgMeta or Object()
name = (try meta.name.underline) or null
version = (try meta.version.underline) or 0
where = @constructor.identify().underline
assert variable = [name, version, where]
logger.debug message.cyan, variable...
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an asynchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
assert list = bower.commands.list or null
bowerings = @constructor.bowerings ?= Array()
cached context if cached = try bowerings.cached
return next undefined if _.isFunction cached or 0
identify = try @constructor.identify().underline
assert options = directory: bowerings.directory
message = "Executing the Bower sequences in %s"
logger.debug message.yellow, identify.toString()
assert _.isString(symbol), "cannot found symbol"
assert _.isObject(context), "located no context"
assert _.isObject(request), "located no request"
assert _.isFunction(next), "got no next function"
esc = (reg) -> new RegExp RegExp.escape "#{reg}"
match = (k) -> (b) -> return esc(k).test b.target
sorter = (v, k) -> _.findIndex bowerings, match(k)
finder = (v, k) -> _.find bowerings, match(k)
list(paths: yes, options).on "end", (paths) =>
assert scope = [sorter, finder, paths]
bowerings.cached = @cachier scope...
bowerings.cached context; next()
# This complicated definition is used to produce and then install
# a method that is going to be cached and used for each request
# once the initial Bower package installation is done. Please do
# refer to the `prelude` implementation in this class for the info.
# Please, refer to the method implementation for an understanding.
cachier: (sorter, finder, paths) -> (context) ->
nsorter = -> fback sorter(arguments...), +999
fback = (vx, fx) -> if vx > 0 then vx else fx
assert sorted = try _.sortBy paths, nsorter
assert files = try _.flatten _.values sorted
locate = (fx) -> _.findKey paths, resides(fx)
resides = (f) -> (x) -> f is x or try f in x
assert _.isFunction(sorter), "no sorter func"
assert _.isFunction(finder), "no finder func"
assert _.isObject(context), "no contex object"
assert not _.isEmpty(paths), "no paths array"
for file in files then do (paths, file) ->
bowering = try finder null, locate(file)
entry = try bowering?.entry or undefined
assert formatted = try "#{file}/#{entry}"
context.scripts.push formatted if entry
return unless _.isEmpty entry?.toString()
ext = (fxt) -> path.extname(file) is fxt
context.scripts.push file if ext ".js"
context.sheets.push file if ext ".css"
# Install the specified packages via Bower into the specific
# location within the system that is figured out automatically.
# All packages installed via Bower will be served as the static
# assets, by using the `pub` env dir. The package installation
# is per service and automatically will be included in `prelude`.
# Refer to the rest of methods for slightly better understanding.
@bower: (target, entry, xoptions={}) ->
ent = "an entrypoint has to be a valid string"
noTarget = "target must be a Bower package spec"
noOptions = "options must be the plain JS object"
message = "Adding Bower package %s to service %s"
options = _.find(arguments, _.isPlainObject) or {}
assert previous = this.bowerings or new Array()
assert previous = try _.unique(previous) or null
return previous unless (try arguments.length) > 0
assert identify = id = this.identify().underline
assert _.isString(entry or null), ent if entry
assert _.isObject(options or null), noOptions
assert _.isString(target or null), noTarget
logger.silly message.cyan, target.bold, id
return this.bowerings = previous.concat
options: options or Object()
entry: entry or undefined
target: target.toString()
|
[
{
"context": "data\n do (property, val) =>\n key = @concatFieldName scope, property\n input = @$fiel",
"end": 6136,
"score": 0.9751220941543579,
"start": 6129,
"tag": "KEY",
"value": "@concat"
}
] | source/joosy/form.coffee | alexshuhin/joosy | 0 | #
# AJAXifies form including file uploads and stuff. Built on top of jQuery.Form.
#
# Joosy.Form automatically cares of form validation highlights. It can
# read common server error responses and add .field_with_errors class to proper
# field.
#
# If you don't have resource associated with form (#fill), it will try to find fields
# by exact keywords from response. Otherwise it will search for resource_name[field].
#
# @example Joosy.Form usage
# form = new Joosy.Form, -> (response)
# console.log "Saved and got some: #{response}"
#
# form.progress = (percent) -> console.log "Uploaded by #{percent}%"
# form.fill @resource
#
# @include Joosy.Modules.Log
# @include Joosy.Modules.Events
# @concern Joosy.Modules.DOM
#
class Joosy.Form extends Joosy.Module
@concern Joosy.Modules.DOM
@include Joosy.Modules.Log
@include Joosy.Modules.Events
#
# Marks the CSS class to use to mark invalidated fields
#
invalidationClass: 'field_with_errors'
#
# List of mappings for fields of invalidated data which comes from server
#
# If you have something like {foo: 'bar', bar: 'baz'} coming from server
# substitutions = {foo: 'foo_id'} will change it to {foo_id: 'bar', bar: 'baz'}
#
substitutions: {}
#
# List of elements for internal usage
#
@mapElements
'fields': 'input,select,textarea'
#
# Makes one AJAX request with form data without binding
#
# @see #constructor
#
# @param [Element] form Instance of HTML form element
# @param [Hash] options Options
#
@submit: (form, options={}) ->
form = new @(form, options)
form.$container.submit()
form.unbind()
null
@attach: ->
new Joosy.Form arguments...
#
# During initialization replaces your basic form submit with AJAX request
#
# @note If method of form differs from POST or GET it will simulate it
# by adding hidden _method input. In this cases the method itself will be
# set to POST.
#
# @note For browsers having no support of HTML5 Forms it may do an iframe requests
# to handle file uploading.
#
# @param [jQuery] form Form element instance
# @param [Hash] options Options
#
# @option options [Function] before `(XHR) -> Bollean` to trigger right before submit.
# By default will run form invalidation cleanup. This behavior can be canceled
# by returning false from your own before callback. Both of callbacks will run if
# you return true.
#
# @option options [Function] success `(Object) -> null` triggers on 2xx HTTP code from server.
# Pases in the parsed JSON.
#
# @option options [Function] progress `(Float) -> null` runs periodically while form is uploading
#
# @option options [Function] error `(Object) -> Boolean` triggers if server responded with anything but 2xx.
# By default will run form invalidation routine. This behavior can be canceled
# by returning false from your own error callback. Both of callbacks will run if
# you return true.
#
# @option options [Joosy.Resources.Base] resource The resource to fill the form with
# @option options [String] resourceName The string to use as a resource name prefix for fields to match invalidation
# @option options [String] action Action URL for the form
# @option options [String] method HTTP method, for example PUT, that will passed in _method param
# @option options [Boolean] debounce Drop submit events while there is a pending submit request
#
constructor: (form, options={}) ->
if typeof(options) == 'function'
@success = options
else
@[key] = value for key, value of options
@$container = $(form)
return if @$container.length == 0
@__assignElements()
@__delegateEvents()
method = @$container.get(0).getAttribute('method')?.toLowerCase()
if method && ['get', 'post'].indexOf(method) == -1
@__markMethod method
@$container.attr 'method', 'POST'
@$container.ajaxForm
dataType: 'json'
beforeSend: =>
return false if @__debounce arguments...
@__before arguments...
@__pending_request = true
@debugAs this, 'beforeSend: pending_request = true'
true
success: =>
@__pending_request = false
@debugAs this, 'success: pending_request = false'
@__success arguments...
error: =>
@__pending_request = false
@debugAs this, 'error: pending_request = false'
@__error arguments...
xhr: =>
xhr = $.ajaxSettings.xhr()
if xhr.upload? && @progress
xhr.upload.onprogress = (event) =>
if event.lengthComputable
@progress (event.position / event.total * 100).round 2
xhr
if @resource?
@fill(@resource, options)
delete @resource
if @action?
@$container.attr 'action', @action
@$container.attr 'method', 'POST'
if @method?
@__markMethod @method
#
# Resets form submit behavior to default
#
unbind: ->
@$container.unbind('submit').find('input:submit,input:image,button:submit').unbind('click')
#
# Links current form with given resource and sets values of form inputs from with it.
# Form will use given resource while doing invalidation routine.
#
# @param [Resource] resource Resource to fill fields with
# @param [Hash] options Options
#
# @option options [Function] decorator `(Object) -> Object` decoration callback
# Pases in the parsed JSON.
#
# @option options [String] action Action URL for the form
#
fill: (resource, options) ->
resource = resource.build() if typeof(resource.build) == 'function'
@__resource = resource
if options?.decorator?
data = options.decorator resource.data
else
data = resource.data
filler = (data, scope) =>
return if data.__joosy_form_filler_lock
data.__joosy_form_filler_lock = true
for property, val of data
do (property, val) =>
key = @concatFieldName scope, property
input = @$fields().filter("[name='#{key}']:not(:file),[name='#{inflection.underscore(key)}']:not(:file),[name='#{inflection.camelize(key, true)}']:not(:file)")
if input.length > 0
if input.is ':checkbox'
input.prop 'checked', !!val
else if input.is ':radio'
input.filter("[value='#{val}']").prop 'checked', true
else
input.val val
if val instanceof Joosy.Resources.Array
for entity, i in val
filler entity.data, @concatFieldName(scope, "[#{property}_attributes][#{i}]")
else if val instanceof Joosy.Resources.REST
filler val.data, @concatFieldName(scope, "[#{property}_attributes]")
else if val?.constructor == Object || val instanceof Array
filler val, key
else
delete data.__joosy_form_filler_lock
filler data, resource.__entityName || options.resourceName
$('input[name=_method]', @$container).remove()
@__markMethod(options?.method || 'PUT') if resource.id()
url = options?.action || (if resource.id()? then resource.memberPath() else resource.collectionPath())
@$container.attr 'action', url
@$container.attr 'method', 'POST'
#
# Submit the HTML Form
#
submit: ->
@$container.submit()
#
# Serializes form into query string.
#
# @param [Boolean] skipMethod Determines if we should skip magical _method field
#
# @return [String]
#
serialize: (skipMethod=true) ->
data = @$container.serialize()
data = data.replace /\&?\_method\=put/i, '' if skipMethod
data
#
# Inner success callback.
#
__success: (response, status, xhr) ->
if xhr
@success? response
else if 200 <= response.status < 300
@success response.json
else
@__error response.json
#
# Inner before callback.
# By default will clean invalidation.
#
__before: (xhr, settings) ->
if !@before? || @before(arguments...) is true
@$fields().removeClass @invalidationClass
#
# Inner error callback.
# By default will trigger basic invalidation.
#
__error: (data) ->
errors = if data.responseText
try
data = jQuery.parseJSON(data.responseText)
catch error
{}
else
data
if !@error? || @error(errors) is true
errors = @__stringifyErrors(errors)
for field, notifications of errors
do (field, notifications) =>
input = @findField(field).addClass @invalidationClass
@notification? input, notifications
return errors
return false
#
# Aborts form submit if there is already another one pending XHR
#
__debounce: (xhr) ->
@debugAs this, "debounce: pending_request == #{@__pending_request}"
if @__pending_request && @debounce != false
if @debounce || Joosy.Form.debounceForms
xhr.abort()
@debugAs this, "debounce: xhr aborted"
return true
false
#
# Finds field by field name.
# This is not inlined since we want to override
# or monkeypatch it from time to time
#
# @param [String] field Name of field to find
#
findField: (field) ->
@$fields().filter("[name='#{field}']")
#
# Simulates REST methods by adding hidden _method input with real method
# while setting POST as the transport method.
#
# @param [String] method Real method to simulate
#
__markMethod: (method='PUT') ->
method = $('<input/>',
type: 'hidden'
name: '_method'
value: method
)
@$container.append method
#
# Prepares server response for default error handler
# Turns all possible response notations into form notation (foo[bar])
# Every direct field of incoming data will be decorated by @substitutions
#
# @example Flat validation result
# { field1: ['error'] } # input
# { field1: ['error'] } # if form was not associated with Resource by {#fill}
# { "fluffy[field1]": ['error']} # if form was associated with Resource (named fluffy)
#
# @example Complex validation result
# { foo: { bar: { baz: ['error'] } } } # input
# { "foo[bar][bar]": ['error'] } # output
#
# @param [Object] errors Data to prepare
#
# @return [Hash<String, Array>] Flat hash with field names in keys and arrays
# of errors in values
#
__stringifyErrors: (errors) ->
result = {}
errors = errors.errors if errors?.errors?.constructor == Object
for field, notifications of errors
do (field, notifications) =>
if @substitutions[field]?
field = @substitutions[field]
if notifications.constructor == Object || @isArrayOfObjects(notifications)
result[field+key] = value for key, value of @__foldInlineEntities(notifications)
else
if field.indexOf(".") != -1
splited = field.split '.'
field = splited.shift()
if @resourceName || @__resource
name = @resourceName || @__resource.__entityName
field = name + "[#{field}]"
field += "[#{f}]" for f in splited
else if @resourceName || @__resource
name = @resourceName || @__resource.__entityName
field = name + "[#{field}]"
result[field] = notifications
result
#
# Flattens complex inline structures into form notation
#
# @example Basic flattening
# data = foo: { bar: { baz: [] } }
# inner = @__foldInlineEntities(data.foo, 'foo')
#
# inner # { "foo[bar][baz]": [] }
#
# @param [Object] hash Structure to fold
# @param [String] scope Prefix for resulting scopes
# @param [Object] result Context of result for recursion
#
# @return [Hash]
#
__foldInlineEntities: (hash, scope="", result={}) ->
for key, value of hash
if value?.constructor == Object || @isArrayOfObjects(value)
@__foldInlineEntities(value, "#{scope}[#{key}]", result)
else
result["#{scope}[#{key}]"] = value
result
concatFieldName: (wrapper, name) ->
items = @splitFieldName(wrapper).concat @splitFieldName(name)
"#{items[0]}[#{items.slice(1).join('][')}]"
splitFieldName: (name) ->
items = name.split('][')
first = items[0].split('[')
if first.length == 2
if first[0].length == 0
items.splice 0, 1, first[1]
else
items.splice 0, 1, first[0], first[1]
items[items.length - 1] = items[items.length - 1].split(']')[0]
items
isArrayOfObjects: (array) ->
array instanceof Array && array.filter((elem) -> elem?.constructor != Object).length == 0
# AMD wrapper
if define?.amd?
define 'joosy/form', -> Joosy.Form
| 108513 | #
# AJAXifies form including file uploads and stuff. Built on top of jQuery.Form.
#
# Joosy.Form automatically cares of form validation highlights. It can
# read common server error responses and add .field_with_errors class to proper
# field.
#
# If you don't have resource associated with form (#fill), it will try to find fields
# by exact keywords from response. Otherwise it will search for resource_name[field].
#
# @example Joosy.Form usage
# form = new Joosy.Form, -> (response)
# console.log "Saved and got some: #{response}"
#
# form.progress = (percent) -> console.log "Uploaded by #{percent}%"
# form.fill @resource
#
# @include Joosy.Modules.Log
# @include Joosy.Modules.Events
# @concern Joosy.Modules.DOM
#
class Joosy.Form extends Joosy.Module
@concern Joosy.Modules.DOM
@include Joosy.Modules.Log
@include Joosy.Modules.Events
#
# Marks the CSS class to use to mark invalidated fields
#
invalidationClass: 'field_with_errors'
#
# List of mappings for fields of invalidated data which comes from server
#
# If you have something like {foo: 'bar', bar: 'baz'} coming from server
# substitutions = {foo: 'foo_id'} will change it to {foo_id: 'bar', bar: 'baz'}
#
substitutions: {}
#
# List of elements for internal usage
#
@mapElements
'fields': 'input,select,textarea'
#
# Makes one AJAX request with form data without binding
#
# @see #constructor
#
# @param [Element] form Instance of HTML form element
# @param [Hash] options Options
#
@submit: (form, options={}) ->
form = new @(form, options)
form.$container.submit()
form.unbind()
null
@attach: ->
new Joosy.Form arguments...
#
# During initialization replaces your basic form submit with AJAX request
#
# @note If method of form differs from POST or GET it will simulate it
# by adding hidden _method input. In this cases the method itself will be
# set to POST.
#
# @note For browsers having no support of HTML5 Forms it may do an iframe requests
# to handle file uploading.
#
# @param [jQuery] form Form element instance
# @param [Hash] options Options
#
# @option options [Function] before `(XHR) -> Bollean` to trigger right before submit.
# By default will run form invalidation cleanup. This behavior can be canceled
# by returning false from your own before callback. Both of callbacks will run if
# you return true.
#
# @option options [Function] success `(Object) -> null` triggers on 2xx HTTP code from server.
# Pases in the parsed JSON.
#
# @option options [Function] progress `(Float) -> null` runs periodically while form is uploading
#
# @option options [Function] error `(Object) -> Boolean` triggers if server responded with anything but 2xx.
# By default will run form invalidation routine. This behavior can be canceled
# by returning false from your own error callback. Both of callbacks will run if
# you return true.
#
# @option options [Joosy.Resources.Base] resource The resource to fill the form with
# @option options [String] resourceName The string to use as a resource name prefix for fields to match invalidation
# @option options [String] action Action URL for the form
# @option options [String] method HTTP method, for example PUT, that will passed in _method param
# @option options [Boolean] debounce Drop submit events while there is a pending submit request
#
constructor: (form, options={}) ->
if typeof(options) == 'function'
@success = options
else
@[key] = value for key, value of options
@$container = $(form)
return if @$container.length == 0
@__assignElements()
@__delegateEvents()
method = @$container.get(0).getAttribute('method')?.toLowerCase()
if method && ['get', 'post'].indexOf(method) == -1
@__markMethod method
@$container.attr 'method', 'POST'
@$container.ajaxForm
dataType: 'json'
beforeSend: =>
return false if @__debounce arguments...
@__before arguments...
@__pending_request = true
@debugAs this, 'beforeSend: pending_request = true'
true
success: =>
@__pending_request = false
@debugAs this, 'success: pending_request = false'
@__success arguments...
error: =>
@__pending_request = false
@debugAs this, 'error: pending_request = false'
@__error arguments...
xhr: =>
xhr = $.ajaxSettings.xhr()
if xhr.upload? && @progress
xhr.upload.onprogress = (event) =>
if event.lengthComputable
@progress (event.position / event.total * 100).round 2
xhr
if @resource?
@fill(@resource, options)
delete @resource
if @action?
@$container.attr 'action', @action
@$container.attr 'method', 'POST'
if @method?
@__markMethod @method
#
# Resets form submit behavior to default
#
unbind: ->
@$container.unbind('submit').find('input:submit,input:image,button:submit').unbind('click')
#
# Links current form with given resource and sets values of form inputs from with it.
# Form will use given resource while doing invalidation routine.
#
# @param [Resource] resource Resource to fill fields with
# @param [Hash] options Options
#
# @option options [Function] decorator `(Object) -> Object` decoration callback
# Pases in the parsed JSON.
#
# @option options [String] action Action URL for the form
#
fill: (resource, options) ->
resource = resource.build() if typeof(resource.build) == 'function'
@__resource = resource
if options?.decorator?
data = options.decorator resource.data
else
data = resource.data
filler = (data, scope) =>
return if data.__joosy_form_filler_lock
data.__joosy_form_filler_lock = true
for property, val of data
do (property, val) =>
key = <KEY>FieldName scope, property
input = @$fields().filter("[name='#{key}']:not(:file),[name='#{inflection.underscore(key)}']:not(:file),[name='#{inflection.camelize(key, true)}']:not(:file)")
if input.length > 0
if input.is ':checkbox'
input.prop 'checked', !!val
else if input.is ':radio'
input.filter("[value='#{val}']").prop 'checked', true
else
input.val val
if val instanceof Joosy.Resources.Array
for entity, i in val
filler entity.data, @concatFieldName(scope, "[#{property}_attributes][#{i}]")
else if val instanceof Joosy.Resources.REST
filler val.data, @concatFieldName(scope, "[#{property}_attributes]")
else if val?.constructor == Object || val instanceof Array
filler val, key
else
delete data.__joosy_form_filler_lock
filler data, resource.__entityName || options.resourceName
$('input[name=_method]', @$container).remove()
@__markMethod(options?.method || 'PUT') if resource.id()
url = options?.action || (if resource.id()? then resource.memberPath() else resource.collectionPath())
@$container.attr 'action', url
@$container.attr 'method', 'POST'
#
# Submit the HTML Form
#
submit: ->
@$container.submit()
#
# Serializes form into query string.
#
# @param [Boolean] skipMethod Determines if we should skip magical _method field
#
# @return [String]
#
serialize: (skipMethod=true) ->
data = @$container.serialize()
data = data.replace /\&?\_method\=put/i, '' if skipMethod
data
#
# Inner success callback.
#
__success: (response, status, xhr) ->
if xhr
@success? response
else if 200 <= response.status < 300
@success response.json
else
@__error response.json
#
# Inner before callback.
# By default will clean invalidation.
#
__before: (xhr, settings) ->
if !@before? || @before(arguments...) is true
@$fields().removeClass @invalidationClass
#
# Inner error callback.
# By default will trigger basic invalidation.
#
__error: (data) ->
errors = if data.responseText
try
data = jQuery.parseJSON(data.responseText)
catch error
{}
else
data
if !@error? || @error(errors) is true
errors = @__stringifyErrors(errors)
for field, notifications of errors
do (field, notifications) =>
input = @findField(field).addClass @invalidationClass
@notification? input, notifications
return errors
return false
#
# Aborts form submit if there is already another one pending XHR
#
__debounce: (xhr) ->
@debugAs this, "debounce: pending_request == #{@__pending_request}"
if @__pending_request && @debounce != false
if @debounce || Joosy.Form.debounceForms
xhr.abort()
@debugAs this, "debounce: xhr aborted"
return true
false
#
# Finds field by field name.
# This is not inlined since we want to override
# or monkeypatch it from time to time
#
# @param [String] field Name of field to find
#
findField: (field) ->
@$fields().filter("[name='#{field}']")
#
# Simulates REST methods by adding hidden _method input with real method
# while setting POST as the transport method.
#
# @param [String] method Real method to simulate
#
__markMethod: (method='PUT') ->
method = $('<input/>',
type: 'hidden'
name: '_method'
value: method
)
@$container.append method
#
# Prepares server response for default error handler
# Turns all possible response notations into form notation (foo[bar])
# Every direct field of incoming data will be decorated by @substitutions
#
# @example Flat validation result
# { field1: ['error'] } # input
# { field1: ['error'] } # if form was not associated with Resource by {#fill}
# { "fluffy[field1]": ['error']} # if form was associated with Resource (named fluffy)
#
# @example Complex validation result
# { foo: { bar: { baz: ['error'] } } } # input
# { "foo[bar][bar]": ['error'] } # output
#
# @param [Object] errors Data to prepare
#
# @return [Hash<String, Array>] Flat hash with field names in keys and arrays
# of errors in values
#
__stringifyErrors: (errors) ->
result = {}
errors = errors.errors if errors?.errors?.constructor == Object
for field, notifications of errors
do (field, notifications) =>
if @substitutions[field]?
field = @substitutions[field]
if notifications.constructor == Object || @isArrayOfObjects(notifications)
result[field+key] = value for key, value of @__foldInlineEntities(notifications)
else
if field.indexOf(".") != -1
splited = field.split '.'
field = splited.shift()
if @resourceName || @__resource
name = @resourceName || @__resource.__entityName
field = name + "[#{field}]"
field += "[#{f}]" for f in splited
else if @resourceName || @__resource
name = @resourceName || @__resource.__entityName
field = name + "[#{field}]"
result[field] = notifications
result
#
# Flattens complex inline structures into form notation
#
# @example Basic flattening
# data = foo: { bar: { baz: [] } }
# inner = @__foldInlineEntities(data.foo, 'foo')
#
# inner # { "foo[bar][baz]": [] }
#
# @param [Object] hash Structure to fold
# @param [String] scope Prefix for resulting scopes
# @param [Object] result Context of result for recursion
#
# @return [Hash]
#
__foldInlineEntities: (hash, scope="", result={}) ->
for key, value of hash
if value?.constructor == Object || @isArrayOfObjects(value)
@__foldInlineEntities(value, "#{scope}[#{key}]", result)
else
result["#{scope}[#{key}]"] = value
result
concatFieldName: (wrapper, name) ->
items = @splitFieldName(wrapper).concat @splitFieldName(name)
"#{items[0]}[#{items.slice(1).join('][')}]"
splitFieldName: (name) ->
items = name.split('][')
first = items[0].split('[')
if first.length == 2
if first[0].length == 0
items.splice 0, 1, first[1]
else
items.splice 0, 1, first[0], first[1]
items[items.length - 1] = items[items.length - 1].split(']')[0]
items
isArrayOfObjects: (array) ->
array instanceof Array && array.filter((elem) -> elem?.constructor != Object).length == 0
# AMD wrapper
if define?.amd?
define 'joosy/form', -> Joosy.Form
| true | #
# AJAXifies form including file uploads and stuff. Built on top of jQuery.Form.
#
# Joosy.Form automatically cares of form validation highlights. It can
# read common server error responses and add .field_with_errors class to proper
# field.
#
# If you don't have resource associated with form (#fill), it will try to find fields
# by exact keywords from response. Otherwise it will search for resource_name[field].
#
# @example Joosy.Form usage
# form = new Joosy.Form, -> (response)
# console.log "Saved and got some: #{response}"
#
# form.progress = (percent) -> console.log "Uploaded by #{percent}%"
# form.fill @resource
#
# @include Joosy.Modules.Log
# @include Joosy.Modules.Events
# @concern Joosy.Modules.DOM
#
class Joosy.Form extends Joosy.Module
@concern Joosy.Modules.DOM
@include Joosy.Modules.Log
@include Joosy.Modules.Events
#
# Marks the CSS class to use to mark invalidated fields
#
invalidationClass: 'field_with_errors'
#
# List of mappings for fields of invalidated data which comes from server
#
# If you have something like {foo: 'bar', bar: 'baz'} coming from server
# substitutions = {foo: 'foo_id'} will change it to {foo_id: 'bar', bar: 'baz'}
#
substitutions: {}
#
# List of elements for internal usage
#
@mapElements
'fields': 'input,select,textarea'
#
# Makes one AJAX request with form data without binding
#
# @see #constructor
#
# @param [Element] form Instance of HTML form element
# @param [Hash] options Options
#
@submit: (form, options={}) ->
form = new @(form, options)
form.$container.submit()
form.unbind()
null
@attach: ->
new Joosy.Form arguments...
#
# During initialization replaces your basic form submit with AJAX request
#
# @note If method of form differs from POST or GET it will simulate it
# by adding hidden _method input. In this cases the method itself will be
# set to POST.
#
# @note For browsers having no support of HTML5 Forms it may do an iframe requests
# to handle file uploading.
#
# @param [jQuery] form Form element instance
# @param [Hash] options Options
#
# @option options [Function] before `(XHR) -> Bollean` to trigger right before submit.
# By default will run form invalidation cleanup. This behavior can be canceled
# by returning false from your own before callback. Both of callbacks will run if
# you return true.
#
# @option options [Function] success `(Object) -> null` triggers on 2xx HTTP code from server.
# Pases in the parsed JSON.
#
# @option options [Function] progress `(Float) -> null` runs periodically while form is uploading
#
# @option options [Function] error `(Object) -> Boolean` triggers if server responded with anything but 2xx.
# By default will run form invalidation routine. This behavior can be canceled
# by returning false from your own error callback. Both of callbacks will run if
# you return true.
#
# @option options [Joosy.Resources.Base] resource The resource to fill the form with
# @option options [String] resourceName The string to use as a resource name prefix for fields to match invalidation
# @option options [String] action Action URL for the form
# @option options [String] method HTTP method, for example PUT, that will passed in _method param
# @option options [Boolean] debounce Drop submit events while there is a pending submit request
#
constructor: (form, options={}) ->
if typeof(options) == 'function'
@success = options
else
@[key] = value for key, value of options
@$container = $(form)
return if @$container.length == 0
@__assignElements()
@__delegateEvents()
method = @$container.get(0).getAttribute('method')?.toLowerCase()
if method && ['get', 'post'].indexOf(method) == -1
@__markMethod method
@$container.attr 'method', 'POST'
@$container.ajaxForm
dataType: 'json'
beforeSend: =>
return false if @__debounce arguments...
@__before arguments...
@__pending_request = true
@debugAs this, 'beforeSend: pending_request = true'
true
success: =>
@__pending_request = false
@debugAs this, 'success: pending_request = false'
@__success arguments...
error: =>
@__pending_request = false
@debugAs this, 'error: pending_request = false'
@__error arguments...
xhr: =>
xhr = $.ajaxSettings.xhr()
if xhr.upload? && @progress
xhr.upload.onprogress = (event) =>
if event.lengthComputable
@progress (event.position / event.total * 100).round 2
xhr
if @resource?
@fill(@resource, options)
delete @resource
if @action?
@$container.attr 'action', @action
@$container.attr 'method', 'POST'
if @method?
@__markMethod @method
#
# Resets form submit behavior to default
#
unbind: ->
@$container.unbind('submit').find('input:submit,input:image,button:submit').unbind('click')
#
# Links current form with given resource and sets values of form inputs from with it.
# Form will use given resource while doing invalidation routine.
#
# @param [Resource] resource Resource to fill fields with
# @param [Hash] options Options
#
# @option options [Function] decorator `(Object) -> Object` decoration callback
# Pases in the parsed JSON.
#
# @option options [String] action Action URL for the form
#
fill: (resource, options) ->
resource = resource.build() if typeof(resource.build) == 'function'
@__resource = resource
if options?.decorator?
data = options.decorator resource.data
else
data = resource.data
filler = (data, scope) =>
return if data.__joosy_form_filler_lock
data.__joosy_form_filler_lock = true
for property, val of data
do (property, val) =>
key = PI:KEY:<KEY>END_PIFieldName scope, property
input = @$fields().filter("[name='#{key}']:not(:file),[name='#{inflection.underscore(key)}']:not(:file),[name='#{inflection.camelize(key, true)}']:not(:file)")
if input.length > 0
if input.is ':checkbox'
input.prop 'checked', !!val
else if input.is ':radio'
input.filter("[value='#{val}']").prop 'checked', true
else
input.val val
if val instanceof Joosy.Resources.Array
for entity, i in val
filler entity.data, @concatFieldName(scope, "[#{property}_attributes][#{i}]")
else if val instanceof Joosy.Resources.REST
filler val.data, @concatFieldName(scope, "[#{property}_attributes]")
else if val?.constructor == Object || val instanceof Array
filler val, key
else
delete data.__joosy_form_filler_lock
filler data, resource.__entityName || options.resourceName
$('input[name=_method]', @$container).remove()
@__markMethod(options?.method || 'PUT') if resource.id()
url = options?.action || (if resource.id()? then resource.memberPath() else resource.collectionPath())
@$container.attr 'action', url
@$container.attr 'method', 'POST'
#
# Submit the HTML Form
#
submit: ->
@$container.submit()
#
# Serializes form into query string.
#
# @param [Boolean] skipMethod Determines if we should skip magical _method field
#
# @return [String]
#
serialize: (skipMethod=true) ->
data = @$container.serialize()
data = data.replace /\&?\_method\=put/i, '' if skipMethod
data
#
# Inner success callback.
#
__success: (response, status, xhr) ->
if xhr
@success? response
else if 200 <= response.status < 300
@success response.json
else
@__error response.json
#
# Inner before callback.
# By default will clean invalidation.
#
__before: (xhr, settings) ->
if !@before? || @before(arguments...) is true
@$fields().removeClass @invalidationClass
#
# Inner error callback.
# By default will trigger basic invalidation.
#
__error: (data) ->
errors = if data.responseText
try
data = jQuery.parseJSON(data.responseText)
catch error
{}
else
data
if !@error? || @error(errors) is true
errors = @__stringifyErrors(errors)
for field, notifications of errors
do (field, notifications) =>
input = @findField(field).addClass @invalidationClass
@notification? input, notifications
return errors
return false
#
# Aborts form submit if there is already another one pending XHR
#
__debounce: (xhr) ->
@debugAs this, "debounce: pending_request == #{@__pending_request}"
if @__pending_request && @debounce != false
if @debounce || Joosy.Form.debounceForms
xhr.abort()
@debugAs this, "debounce: xhr aborted"
return true
false
#
# Finds field by field name.
# This is not inlined since we want to override
# or monkeypatch it from time to time
#
# @param [String] field Name of field to find
#
findField: (field) ->
@$fields().filter("[name='#{field}']")
#
# Simulates REST methods by adding hidden _method input with real method
# while setting POST as the transport method.
#
# @param [String] method Real method to simulate
#
__markMethod: (method='PUT') ->
method = $('<input/>',
type: 'hidden'
name: '_method'
value: method
)
@$container.append method
#
# Prepares server response for default error handler
# Turns all possible response notations into form notation (foo[bar])
# Every direct field of incoming data will be decorated by @substitutions
#
# @example Flat validation result
# { field1: ['error'] } # input
# { field1: ['error'] } # if form was not associated with Resource by {#fill}
# { "fluffy[field1]": ['error']} # if form was associated with Resource (named fluffy)
#
# @example Complex validation result
# { foo: { bar: { baz: ['error'] } } } # input
# { "foo[bar][bar]": ['error'] } # output
#
# @param [Object] errors Data to prepare
#
# @return [Hash<String, Array>] Flat hash with field names in keys and arrays
# of errors in values
#
__stringifyErrors: (errors) ->
result = {}
errors = errors.errors if errors?.errors?.constructor == Object
for field, notifications of errors
do (field, notifications) =>
if @substitutions[field]?
field = @substitutions[field]
if notifications.constructor == Object || @isArrayOfObjects(notifications)
result[field+key] = value for key, value of @__foldInlineEntities(notifications)
else
if field.indexOf(".") != -1
splited = field.split '.'
field = splited.shift()
if @resourceName || @__resource
name = @resourceName || @__resource.__entityName
field = name + "[#{field}]"
field += "[#{f}]" for f in splited
else if @resourceName || @__resource
name = @resourceName || @__resource.__entityName
field = name + "[#{field}]"
result[field] = notifications
result
#
# Flattens complex inline structures into form notation
#
# @example Basic flattening
# data = foo: { bar: { baz: [] } }
# inner = @__foldInlineEntities(data.foo, 'foo')
#
# inner # { "foo[bar][baz]": [] }
#
# @param [Object] hash Structure to fold
# @param [String] scope Prefix for resulting scopes
# @param [Object] result Context of result for recursion
#
# @return [Hash]
#
__foldInlineEntities: (hash, scope="", result={}) ->
for key, value of hash
if value?.constructor == Object || @isArrayOfObjects(value)
@__foldInlineEntities(value, "#{scope}[#{key}]", result)
else
result["#{scope}[#{key}]"] = value
result
concatFieldName: (wrapper, name) ->
items = @splitFieldName(wrapper).concat @splitFieldName(name)
"#{items[0]}[#{items.slice(1).join('][')}]"
splitFieldName: (name) ->
items = name.split('][')
first = items[0].split('[')
if first.length == 2
if first[0].length == 0
items.splice 0, 1, first[1]
else
items.splice 0, 1, first[0], first[1]
items[items.length - 1] = items[items.length - 1].split(']')[0]
items
isArrayOfObjects: (array) ->
array instanceof Array && array.filter((elem) -> elem?.constructor != Object).length == 0
# AMD wrapper
if define?.amd?
define 'joosy/form', -> Joosy.Form
|
[
{
"context": "s _.startsWith header, 'x-meshblu-'\n key = _.camelCase( _.replace(header, \"x-meshblu-\", '' ))\n newM",
"end": 772,
"score": 0.773292064666748,
"start": 763,
"tag": "KEY",
"value": "camelCase"
},
{
"context": "lu-'\n key = _.camelCase( _.replace(header, \"x-meshblu-\", '' ))\n newMetadata[key] = value\n\n metada",
"end": 802,
"score": 0.5999751091003418,
"start": 795,
"tag": "KEY",
"value": "meshblu"
}
] | src/helpers/job-to-http.coffee | octoblu/meshblu-core-protocol-adapter-http-streaming | 1 | _ = require 'lodash'
MeshbluAuthParser = require '../helpers/meshblu-auth-parser'
class JobToHttp
constructor: () ->
@authParser = new MeshbluAuthParser
httpToJob: ({jobType, request, toUuid, data}) ->
data ?= request.body
userMetadata = @getMetadataFromHeaders request.headers
auth = @authParser.parse request
systemMetadata =
auth: auth
fromUuid: request.get('x-meshblu-as') ? auth.uuid
toUuid: toUuid
jobType: jobType
job =
metadata: _.extend userMetadata, systemMetadata
data: data
job
getMetadataFromHeaders: (headers) =>
_.transform headers, (newMetadata, value, header) =>
header = header.toLowerCase()
return unless _.startsWith header, 'x-meshblu-'
key = _.camelCase( _.replace(header, "x-meshblu-", '' ))
newMetadata[key] = value
metadataToHeaders: (metadata) =>
headers = {}
_.each metadata, (value, key) =>
header = "x-meshblu-#{_.kebabCase(key)}"
return _.set headers, header, value if _.isString value
return _.set headers, header, JSON.stringify value
headers
sendJobResponse: ({jobResponse, res}) ->
return res.sendStatus 500 unless jobResponse?
res.set 'Content-Type', 'application/json'
res.set @metadataToHeaders jobResponse.metadata
res.status jobResponse.metadata.code
res.send jobResponse.rawData
module.exports = JobToHttp
| 208185 | _ = require 'lodash'
MeshbluAuthParser = require '../helpers/meshblu-auth-parser'
class JobToHttp
constructor: () ->
@authParser = new MeshbluAuthParser
httpToJob: ({jobType, request, toUuid, data}) ->
data ?= request.body
userMetadata = @getMetadataFromHeaders request.headers
auth = @authParser.parse request
systemMetadata =
auth: auth
fromUuid: request.get('x-meshblu-as') ? auth.uuid
toUuid: toUuid
jobType: jobType
job =
metadata: _.extend userMetadata, systemMetadata
data: data
job
getMetadataFromHeaders: (headers) =>
_.transform headers, (newMetadata, value, header) =>
header = header.toLowerCase()
return unless _.startsWith header, 'x-meshblu-'
key = _.<KEY>( _.replace(header, "x-<KEY>-", '' ))
newMetadata[key] = value
metadataToHeaders: (metadata) =>
headers = {}
_.each metadata, (value, key) =>
header = "x-meshblu-#{_.kebabCase(key)}"
return _.set headers, header, value if _.isString value
return _.set headers, header, JSON.stringify value
headers
sendJobResponse: ({jobResponse, res}) ->
return res.sendStatus 500 unless jobResponse?
res.set 'Content-Type', 'application/json'
res.set @metadataToHeaders jobResponse.metadata
res.status jobResponse.metadata.code
res.send jobResponse.rawData
module.exports = JobToHttp
| true | _ = require 'lodash'
MeshbluAuthParser = require '../helpers/meshblu-auth-parser'
class JobToHttp
constructor: () ->
@authParser = new MeshbluAuthParser
httpToJob: ({jobType, request, toUuid, data}) ->
data ?= request.body
userMetadata = @getMetadataFromHeaders request.headers
auth = @authParser.parse request
systemMetadata =
auth: auth
fromUuid: request.get('x-meshblu-as') ? auth.uuid
toUuid: toUuid
jobType: jobType
job =
metadata: _.extend userMetadata, systemMetadata
data: data
job
getMetadataFromHeaders: (headers) =>
_.transform headers, (newMetadata, value, header) =>
header = header.toLowerCase()
return unless _.startsWith header, 'x-meshblu-'
key = _.PI:KEY:<KEY>END_PI( _.replace(header, "x-PI:KEY:<KEY>END_PI-", '' ))
newMetadata[key] = value
metadataToHeaders: (metadata) =>
headers = {}
_.each metadata, (value, key) =>
header = "x-meshblu-#{_.kebabCase(key)}"
return _.set headers, header, value if _.isString value
return _.set headers, header, JSON.stringify value
headers
sendJobResponse: ({jobResponse, res}) ->
return res.sendStatus 500 unless jobResponse?
res.set 'Content-Type', 'application/json'
res.set @metadataToHeaders jobResponse.metadata
res.status jobResponse.metadata.code
res.send jobResponse.rawData
module.exports = JobToHttp
|
[
{
"context": "165 lbs'\n nada: null\n\n model.set 'name', 'John'\n model.set 'age', 22\n model.set 'height', ",
"end": 1748,
"score": 0.9982359409332275,
"start": 1744,
"tag": "NAME",
"value": "John"
},
{
"context": "175 lbs'\n\n expected = 'falsetrue ' +\n '<p>John</p>' +\n '<p>22 - 6 ft 2 in - 165 lbs</p>'\n\n ",
"end": 1889,
"score": 0.9983810186386108,
"start": 1885,
"tag": "NAME",
"value": "John"
},
{
"context": "165 lbs'\n nada: null\n\n model.set 'name', 'John'\n model.set 'age', 22\n model.set 'height', ",
"end": 2795,
"score": 0.9973680377006531,
"start": 2791,
"tag": "NAME",
"value": "John"
},
{
"context": "<!--$$1--> <!--$2--><!--$$2-->' +\n '<p id=$3>John</p>' +\n '<p><!--$4-->22<!--$$4--> - <!--$5--",
"end": 3026,
"score": 0.9659698009490967,
"start": 3022,
"tag": "NAME",
"value": "John"
},
{
"context": "e', '{{unescaped name}} - stuff'\n ctx = name: 'Crème Brûlée'\n expect(view.get 'titl",
"end": 4324,
"score": 0.8231934309005737,
"start": 4315,
"tag": "NAME",
"value": "Crè"
},
{
"context": "scaped name}} - stuff'\n ctx = name: 'Crème Brûlée'\n expect(view.get 'title$s', ctx).t",
"end": 4336,
"score": 0.8909450769424438,
"start": 4325,
"tag": "NAME",
"value": "me Brû"
},
{
"context": "} - stuff'\n ctx = name: 'Crème Brûlée'\n expect(view.get 'title$s', ctx).to.eql 'Crèm",
"end": 4347,
"score": 0.9085712432861328,
"start": 4337,
"tag": "NAME",
"value": "lée"
},
{
"context": " type: 'home'\n people: [\n {name: 'fred', editable: true} \n {name: 'wilma', edi",
"end": 10096,
"score": 0.9997549057006836,
"start": 10092,
"tag": "NAME",
"value": "fred"
},
{
"context": "name: 'fred', editable: true} \n {name: 'wilma', editable: false}\n ]\n }, {\n t",
"end": 10140,
"score": 0.9997031688690186,
"start": 10135,
"tag": "NAME",
"value": "wilma"
},
{
"context": "e: 'neighbor'\n people: [\n {name: 'barney', editable: false}\n {name: 'betty', edi",
"end": 10248,
"score": 0.9997825622558594,
"start": 10242,
"tag": "NAME",
"value": "barney"
},
{
"context": "ame: 'barney', editable: false}\n {name: 'betty', editable: true}\n ]\n }\n ]\n\n v",
"end": 10291,
"score": 0.9997876286506653,
"start": 10286,
"tag": "NAME",
"value": "betty"
},
{
"context": "\n '<li>Type: home'\n '<input value=fred>'\n 'wilma'\n '</li>'\n '<li>",
"end": 10472,
"score": 0.9988862872123718,
"start": 10468,
"tag": "NAME",
"value": "fred"
},
{
"context": ": home'\n '<input value=fred>'\n 'wilma'\n '</li>'\n '<li>Type: neighbor'\n ",
"end": 10491,
"score": 0.9995936155319214,
"start": 10486,
"tag": "NAME",
"value": "wilma"
},
{
"context": " '</li>'\n '<li>Type: neighbor'\n 'barney'\n '<input value=betty>'\n '</li>'\n",
"end": 10555,
"score": 0.9997493028640747,
"start": 10549,
"tag": "NAME",
"value": "barney"
},
{
"context": " type: 'home'\n people: [\n {name: 'fred', editable: true} \n {name: 'wilma', edi",
"end": 11155,
"score": 0.9997613430023193,
"start": 11151,
"tag": "NAME",
"value": "fred"
},
{
"context": "name: 'fred', editable: true} \n {name: 'wilma', editable: false}\n ]\n }, {\n t",
"end": 11199,
"score": 0.9997057914733887,
"start": 11194,
"tag": "NAME",
"value": "wilma"
},
{
"context": "e: 'neighbor'\n people: [\n {name: 'barney', editable: false}\n {name: 'betty', edi",
"end": 11307,
"score": 0.9997700452804565,
"start": 11301,
"tag": "NAME",
"value": "barney"
},
{
"context": "ame: 'barney', editable: false}\n {name: 'betty', editable: true}\n ]\n }\n ]\n\n v",
"end": 11350,
"score": 0.9997265338897705,
"start": 11345,
"tag": "NAME",
"value": "betty"
},
{
"context": "\n '<li>Type: home'\n '<input value=fred>'\n 'wilma'\n '</li>'\n '<li>",
"end": 11531,
"score": 0.9952354431152344,
"start": 11527,
"tag": "NAME",
"value": "fred"
},
{
"context": ": home'\n '<input value=fred>'\n 'wilma'\n '</li>'\n '<li>Type: neighbor'\n ",
"end": 11550,
"score": 0.9993053674697876,
"start": 11545,
"tag": "NAME",
"value": "wilma"
},
{
"context": " '</li>'\n '<li>Type: neighbor'\n 'barney'\n '<input value=betty>'\n '</li>'\n",
"end": 11614,
"score": 0.9995027184486389,
"start": 11608,
"tag": "NAME",
"value": "barney"
},
{
"context": "', '<b>{{user.name}}</b>'\n ctx = user: {name: 'John'}\n\n expect(view.get 'test', ctx).to.equal '<b>",
"end": 12115,
"score": 0.9984667301177979,
"start": 12111,
"tag": "NAME",
"value": "John"
},
{
"context": "'}\n\n expect(view.get 'test', ctx).to.equal '<b>John</b>'\n\n it 'supports relative paths for ctx objec",
"end": 12169,
"score": 0.9732109308242798,
"start": 12165,
"tag": "NAME",
"value": "John"
},
{
"context": "r}}<b>{{.name}}</b>{{/}}'\n ctx = user: {name: 'John'}\n\n expect(view.get 'test', ctx).to.equal '<b>",
"end": 12318,
"score": 0.9992285370826721,
"start": 12314,
"tag": "NAME",
"value": "John"
},
{
"context": "'}\n\n expect(view.get 'test', ctx).to.equal '<b>John</b>'\n\n it 'supports Arrays containing non-object",
"end": 12372,
"score": 0.9978559613227844,
"start": 12368,
"tag": "NAME",
"value": "John"
}
] | test/View.mocha.coffee | TheMonkeys/derby | 0 | {expect, calls} = require 'racer/test/util'
{DetachedModel: Model, ResMock} = require './mocks'
View = require '../lib/View.server'
describe 'View.render', ->
it 'supports view.render with no defined views', ->
view = new View
res = new ResMock
res.onEnd = (html) ->
expect(html).to.match /^<!DOCTYPE html><meta charset=utf-8><title>.*<\/title><script>.*<\/script><script.*><\/script>$/
view.render res
describe 'View', ->
view = model = null
beforeEach (done) ->
view = new View
model = new Model
view._init model, false, done
it 'supports rendering a string literal view', ->
view.make 'test', """
<style>
body {
margin:
0
}
</style>
"""
# String views should have line breaks and leading whitespace removed
expect(view.get 'test').to.eql '<style>body {margin: 0}</style>'
it 'doctypes and conditional comments are maintained', ->
view.make 'test', """
<!DOCTYPE html>
<!-- This comment is removed -->
<title></title>
<!--[if gt IE 6]>
IE greater than 6
<![endif]-->
<!--[if !IE]> -->
Not IE
<!-- <![endif]-->
"""
expect(view.get 'test').to.eql '<!DOCTYPE html>' +
'<title></title>' +
'<!--[if gt IE 6]>\n' +
'IE greater than 6\n' +
'<![endif]-->' +
'<!--[if !IE]> -->Not IE<!-- <![endif]-->'
it 'supports substituting variables into text', ->
view.make 'test', '''
{{connected}}{{canConnect}} {{nada}}
<p>
{{name}}
</p>
<p>
{{age}} - {{height}} - {{weight}}
</p>
'''
ctx =
connected: false
weight: '165 lbs'
nada: null
model.set 'name', 'John'
model.set 'age', 22
model.set 'height', '6 ft 2 in'
model.set 'weight', '175 lbs'
expected = 'falsetrue ' +
'<p>John</p>' +
'<p>22 - 6 ft 2 in - 165 lbs</p>'
expect(view.get 'test', ctx).to.equal expected
it 'supports path interpolation', ->
view.make 'test', """
{{items[id]}}
{{#each ids}}
{{items[this]}}
{{/}}
{{#each others}}
{{items[.id]}}
{{/}}
"""
model.set 'id', 2
model.set 'ids', [2, 0]
ctx =
items:
0: 'red'
1: 'green'
2: 'blue'
others: [
{id: 1}
{id: 2}
]
expect(view.get 'test', ctx).to.equal 'blue' +
'blue' + 'red' +
'green' + 'blue'
it 'supports binding variables in text', ->
view.make 'test', '''
{connected}{canConnect} {nada}
<p>
{name}
</p>
<p>
{age} - {height} - {weight}
</p>
'''
ctx =
connected: false
weight: '165 lbs'
nada: null
model.set 'name', 'John'
model.set 'age', 22
model.set 'height', '6 ft 2 in'
model.set 'weight', '175 lbs'
expect(view.get 'test', ctx).to.equal '<!--$0-->false<!--$$0--><!--$1-->true<!--$$1--> <!--$2--><!--$$2-->' +
'<p id=$3>John</p>' +
'<p><!--$4-->22<!--$$4--> - <!--$5-->6 ft 2 in<!--$$5--> - <!--$6-->165 lbs<!--$$6--></p>'
it 'supports HTML escaping', ->
# Attribute values are escaped regardless of placeholder type
# Ampersands are escaped at the end of a replacement even when not
# required, because it is sometimes needed depending on the following item
template = '''<input value="{unescaped html}"> {html}x{unescaped html}'''
value = '<b id="hey">&Hi! & x& </b>&'
expected =
'<input id=$0 value="<b id="hey">&Hi! & x& </b>&"> ' +
'<!--$1--><b id="hey">&Hi! & x& </b>&<!--$$1-->x' +
'<!--$2--><b id="hey">&Hi! & x& </b>&<!--$$2-->'
view.make 'test1', template
expect(view.get 'test1', html: value).to.eql expected
view._idCount = 0
model.set 'html', value
expect(view.get 'test1').to.eql expected
view.make 'test2',
'<p a={{a}} b={{b}} c={{c}} d={{d}} e={{e}} f={{f}} g={{g}} h={{h}} i>'
expect(view.get 'test2',
{a: '"', b: "'", c: '<', d: '>', e: '=', f: ' ', g: '', h: null}
).to.eql '<p a=" b="\'" c="<" d=">" e="=" f=" " g="" h="" i>'
it 'supports HTML entity unescaping in string partials', ->
view.make 'title', '{{unescaped name}} - stuff'
ctx = name: 'Crème Brûlée'
expect(view.get 'title$s', ctx).to.eql 'Crème Brûlée - stuff'
it 'supports conditional blocks in text', ->
view.make 'literal',
'{{#if show}}Yep{{else}}Nope{{/}}{{#if show}} Yes!{{/}} {{#unless show}}No{{/}}'
view.make 'bound',
'{#if show}Yep{else}Nope{/}{#if show} Yes!{/} {#unless show}No{/}'
literalTruthy = 'Yep Yes! '
literalFalsey = 'Nope No'
modelTruthy = '<!--$0-->Yep<!--$$0--><!--$1--> Yes!<!--$$1--> <!--$2--><!--$$2-->'
modelFalsey = '<!--$0-->Nope<!--$$0--><!--$1--><!--$$1--> <!--$2-->No<!--$$2-->'
expect(view.get 'literal', show: true).to.eql literalTruthy
expect(view.get 'literal', show: 1).to.eql literalTruthy
expect(view.get 'literal', show: 'x').to.eql literalTruthy
expect(view.get 'literal', show: {}).to.eql literalTruthy
expect(view.get 'literal', show: [1]).to.eql literalTruthy
expect(view.get 'literal', show: false).to.eql literalFalsey
expect(view.get 'literal', show: undefined).to.eql literalFalsey
expect(view.get 'literal', show: null).to.eql literalFalsey
expect(view.get 'literal', show: 0).to.eql literalFalsey
expect(view.get 'literal', show: '').to.eql literalFalsey
expect(view.get 'literal', show: []).to.eql literalFalsey
expect(view.get 'literal').to.eql literalFalsey
# No parameter assumes it is a model path that is undefined
view._idCount = 0
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', true
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', 1
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', 'x'
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', {}
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', false
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', undefined
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', null
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', 0
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', ''
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', []
expect(view.get 'bound').to.eql modelFalsey
it 'supports else if conditionals', ->
view.make 'test', """
{{#if equal('red', value)}}
1
{{else if equal('red', value)}}
2
{{else if equal('green', value)}}
3
{{else}}
4
{{/}}
"""
expect(view.get 'test', value: 'red').to.equal '1'
expect(view.get 'test', value: 'green').to.equal '3'
expect(view.get 'test', value: 'blue').to.equal '4'
expect(view.get 'test').to.equal '4'
it 'supports unless then else conditionals', ->
view.make 'test', """
{{#unless value}}
1
{{else}}
2
{{/}}
"""
expect(view.get 'test', value: true).to.equal '2'
expect(view.get 'test', value: false).to.equal '1'
it 'supports lists in text', ->
template = """
<ul>
{{#each arr}}
<li>{{name}}
{{else}}
<li>Nothing to see
{{/}}
</ul>
"""
view.make 'test', template
expect(view.get 'test', arr: [])
.to.eql '<ul><li>Nothing to see</ul>'
view.make 'test', template
expect(view.get 'test', arr: [{name: 'stuff'}, {name: 'more'}])
.to.eql '<ul><li>stuff<li>more</ul>'
it 'supports nesting lists with relative paths', ->
template = """
<table>
<tbody>
{{#each table.rows}}
<tr>
{{#each .cells}}
<td><input value={{.text}}></td>
{{/}}
</tr>
{{/}}
</tbody>
</table>
"""
model.set 'table.rows', [
{cells: [{text: 'A'}, {text: 'B'}, {text: 'C'}]}
{cells: [{text: 1}, {text: 2}, {text: 3}]}
]
view.make 'test', template
expect(view.get 'test').to.equal [
'<table>'
'<tbody>'
'<tr>'
'<td><input value=A></td>'
'<td><input value=B></td>'
'<td><input value=C></td>'
'</tr>'
'<tr>'
'<td><input value=1></td>'
'<td><input value=2></td>'
'<td><input value=3></td>'
'</tr>'
'</tbody>'
'</table>'
].join('')
it 'supports nesting aliases to flat lists', ->
template = """
{{#each outer as :out}}
{{#each inner as :in}}
{{#each core as :core}}
[{{:out.name}} {{:in.name}} {{:core.name}} {{equal(:out.color, :in.color)}}]
{{/}}
{{/}}
{{/}}
"""
view.make 'test', template
compiled = view.get 'test',
outer: [{name: 'stuff', color: 'blue'}, {name: 'more', color: 'pink'}]
inner: [{name: '0', color: 'pink'}, {name: '1', color: 'blue'}]
core: [{name: '0'}, {name: '1'}]
expect(compiled).to.equal [
'[stuff 0 0 false]'
'[stuff 0 1 false]'
'[stuff 1 0 true]'
'[stuff 1 1 true]'
'[more 0 0 true]'
'[more 0 1 true]'
'[more 1 0 false]'
'[more 1 1 false]'
].join('')
it 'supports aliases from relative paths on nested lists', ->
template = """
<ul>
{{#each _room.street}}
<li>Type: {{.type}}
{{#each .people as :person}}
{{#if :person.editable}}
<input value={{:person.name}}>
{{else}}
{{:person.name}}
{{/}}
{{/}}
</li>
{{/}}
</ul>
"""
model.set '_room.street', [
{
type: 'home'
people: [
{name: 'fred', editable: true}
{name: 'wilma', editable: false}
]
}, {
type: 'neighbor'
people: [
{name: 'barney', editable: false}
{name: 'betty', editable: true}
]
}
]
view.make 'test', template
expect(view.get 'test').to.equal [
'<ul>'
'<li>Type: home'
'<input value=fred>'
'wilma'
'</li>'
'<li>Type: neighbor'
'barney'
'<input value=betty>'
'</li>'
'</ul>'
].join('')
it 'supports aliases from aliases on nested lists', ->
template = """
<ul>
{{#each _room.street as :street}}
<li>Type: {{:street.type}}
{{#each :street.people as :person}}
{{#if :person.editable}}
<input value={{:person.name}}>
{{else}}
{{:person.name}}
{{/}}
{{/}}
</li>
{{/}}
</ul>
"""
model.set '_room.street', [
{
type: 'home'
people: [
{name: 'fred', editable: true}
{name: 'wilma', editable: false}
]
}, {
type: 'neighbor'
people: [
{name: 'barney', editable: false}
{name: 'betty', editable: true}
]
}
]
view.make 'test', template
expect(view.get 'test').to.equal [
'<ul>'
'<li>Type: home'
'<input value=fred>'
'wilma'
'</li>'
'<li>Type: neighbor'
'barney'
'<input value=betty>'
'</li>'
'</ul>'
].join('')
it 'supports boolean attributes', ->
view.make 'test', '<input disabled={maybe}>'
expect(view.get 'test').to.equal '<input id=$0>'
expect(view.get 'test', maybe: false).to.equal '<input id=$1>'
expect(view.get 'test', maybe: true).to.equal '<input id=$2 disabled>'
it 'supports paths containing dots for ctx object items', ->
view.make 'test', '<b>{{user.name}}</b>'
ctx = user: {name: 'John'}
expect(view.get 'test', ctx).to.equal '<b>John</b>'
it 'supports relative paths for ctx object items', ->
view.make 'test', '{{#if user}}<b>{{.name}}</b>{{/}}'
ctx = user: {name: 'John'}
expect(view.get 'test', ctx).to.equal '<b>John</b>'
it 'supports Arrays containing non-objects from ctx', ->
view.make 'test1', '{{#each bools}}<b>{{this}}</b>{{/}}'
view.make 'test2', '{{#each bools as :value}}<b>{{:value}}</b>{{/}}'
ctx = bools: [true, false, true]
expect(view.get 'test1', ctx).to.equal '<b>true</b><b>false</b><b>true</b>'
expect(view.get 'test2', ctx).to.equal '<b>true</b><b>false</b><b>true</b>'
it 'supports view helper functions', ->
view.fn 'lower', (s) -> s.toLowerCase()
view.make 'test', '''{{lower('HI')}} {lower( "HI" )}'''
expect(view.get 'test').to.equal 'hi <!--$0-->hi<!--$$0-->'
view.fn 'sum', (a, b) -> a + b
view.make 'test', '{{sum(4, 9)}}'
expect(view.get 'test').to.equal '13'
view._idCount = 0
view.make 'test', '{equal(1, sum(-5, 6))}'
expect(view.get 'test').to.equal '<!--$0-->true<!--$$0-->'
view._idCount = 0
view.make 'test', '{unescaped equal(sum(-5, 6), 1)}'
expect(view.get 'test').to.equal '<!--$0-->true<!--$$0-->'
view.make 'test', '{{sum(4, count)}}'
expect(view.get 'test', {count: 7}).to.equal '11'
model.set 'count', 13
expect(view.get 'test').to.equal '17'
view._idCount = 0
view.make 'test', '''
<select>
{{#each items}}
<option selected="{{equal(this, current)}}">{{this}}
{{/}}
</select>
'''
expect(view.get 'test',
items: ['a', 'b', 'c']
current: 'c'
).to.equal '<select id=$0><option>a<option>b<option selected>c</select>'
view.fn 'positive', (num) -> num >= 0
view.make 'test', '''
{{#each nums as :num}}
{{#if positive(:num)}}
{{:num}},
{{/}}
{{/}}
'''
expect(view.get 'test', {nums: [-4, 8, 0, 2.3, -9]}).to.equal '8,0,2.3,'
it 'supports x-no-minify', ->
view.make 'test', '''
<script type="x-test" x-no-minify>
Some text
And a new line
</script>
'''
expect(view.get 'test').to.equal '''
<script type=x-test>
Some text
And a new line
</script>
''' | 207501 | {expect, calls} = require 'racer/test/util'
{DetachedModel: Model, ResMock} = require './mocks'
View = require '../lib/View.server'
describe 'View.render', ->
it 'supports view.render with no defined views', ->
view = new View
res = new ResMock
res.onEnd = (html) ->
expect(html).to.match /^<!DOCTYPE html><meta charset=utf-8><title>.*<\/title><script>.*<\/script><script.*><\/script>$/
view.render res
describe 'View', ->
view = model = null
beforeEach (done) ->
view = new View
model = new Model
view._init model, false, done
it 'supports rendering a string literal view', ->
view.make 'test', """
<style>
body {
margin:
0
}
</style>
"""
# String views should have line breaks and leading whitespace removed
expect(view.get 'test').to.eql '<style>body {margin: 0}</style>'
it 'doctypes and conditional comments are maintained', ->
view.make 'test', """
<!DOCTYPE html>
<!-- This comment is removed -->
<title></title>
<!--[if gt IE 6]>
IE greater than 6
<![endif]-->
<!--[if !IE]> -->
Not IE
<!-- <![endif]-->
"""
expect(view.get 'test').to.eql '<!DOCTYPE html>' +
'<title></title>' +
'<!--[if gt IE 6]>\n' +
'IE greater than 6\n' +
'<![endif]-->' +
'<!--[if !IE]> -->Not IE<!-- <![endif]-->'
it 'supports substituting variables into text', ->
view.make 'test', '''
{{connected}}{{canConnect}} {{nada}}
<p>
{{name}}
</p>
<p>
{{age}} - {{height}} - {{weight}}
</p>
'''
ctx =
connected: false
weight: '165 lbs'
nada: null
model.set 'name', '<NAME>'
model.set 'age', 22
model.set 'height', '6 ft 2 in'
model.set 'weight', '175 lbs'
expected = 'falsetrue ' +
'<p><NAME></p>' +
'<p>22 - 6 ft 2 in - 165 lbs</p>'
expect(view.get 'test', ctx).to.equal expected
it 'supports path interpolation', ->
view.make 'test', """
{{items[id]}}
{{#each ids}}
{{items[this]}}
{{/}}
{{#each others}}
{{items[.id]}}
{{/}}
"""
model.set 'id', 2
model.set 'ids', [2, 0]
ctx =
items:
0: 'red'
1: 'green'
2: 'blue'
others: [
{id: 1}
{id: 2}
]
expect(view.get 'test', ctx).to.equal 'blue' +
'blue' + 'red' +
'green' + 'blue'
it 'supports binding variables in text', ->
view.make 'test', '''
{connected}{canConnect} {nada}
<p>
{name}
</p>
<p>
{age} - {height} - {weight}
</p>
'''
ctx =
connected: false
weight: '165 lbs'
nada: null
model.set 'name', '<NAME>'
model.set 'age', 22
model.set 'height', '6 ft 2 in'
model.set 'weight', '175 lbs'
expect(view.get 'test', ctx).to.equal '<!--$0-->false<!--$$0--><!--$1-->true<!--$$1--> <!--$2--><!--$$2-->' +
'<p id=$3><NAME></p>' +
'<p><!--$4-->22<!--$$4--> - <!--$5-->6 ft 2 in<!--$$5--> - <!--$6-->165 lbs<!--$$6--></p>'
it 'supports HTML escaping', ->
# Attribute values are escaped regardless of placeholder type
# Ampersands are escaped at the end of a replacement even when not
# required, because it is sometimes needed depending on the following item
template = '''<input value="{unescaped html}"> {html}x{unescaped html}'''
value = '<b id="hey">&Hi! & x& </b>&'
expected =
'<input id=$0 value="<b id="hey">&Hi! & x& </b>&"> ' +
'<!--$1--><b id="hey">&Hi! & x& </b>&<!--$$1-->x' +
'<!--$2--><b id="hey">&Hi! & x& </b>&<!--$$2-->'
view.make 'test1', template
expect(view.get 'test1', html: value).to.eql expected
view._idCount = 0
model.set 'html', value
expect(view.get 'test1').to.eql expected
view.make 'test2',
'<p a={{a}} b={{b}} c={{c}} d={{d}} e={{e}} f={{f}} g={{g}} h={{h}} i>'
expect(view.get 'test2',
{a: '"', b: "'", c: '<', d: '>', e: '=', f: ' ', g: '', h: null}
).to.eql '<p a=" b="\'" c="<" d=">" e="=" f=" " g="" h="" i>'
it 'supports HTML entity unescaping in string partials', ->
view.make 'title', '{{unescaped name}} - stuff'
ctx = name: '<NAME>;<NAME>;<NAME>'
expect(view.get 'title$s', ctx).to.eql 'Crème Brûlée - stuff'
it 'supports conditional blocks in text', ->
view.make 'literal',
'{{#if show}}Yep{{else}}Nope{{/}}{{#if show}} Yes!{{/}} {{#unless show}}No{{/}}'
view.make 'bound',
'{#if show}Yep{else}Nope{/}{#if show} Yes!{/} {#unless show}No{/}'
literalTruthy = 'Yep Yes! '
literalFalsey = 'Nope No'
modelTruthy = '<!--$0-->Yep<!--$$0--><!--$1--> Yes!<!--$$1--> <!--$2--><!--$$2-->'
modelFalsey = '<!--$0-->Nope<!--$$0--><!--$1--><!--$$1--> <!--$2-->No<!--$$2-->'
expect(view.get 'literal', show: true).to.eql literalTruthy
expect(view.get 'literal', show: 1).to.eql literalTruthy
expect(view.get 'literal', show: 'x').to.eql literalTruthy
expect(view.get 'literal', show: {}).to.eql literalTruthy
expect(view.get 'literal', show: [1]).to.eql literalTruthy
expect(view.get 'literal', show: false).to.eql literalFalsey
expect(view.get 'literal', show: undefined).to.eql literalFalsey
expect(view.get 'literal', show: null).to.eql literalFalsey
expect(view.get 'literal', show: 0).to.eql literalFalsey
expect(view.get 'literal', show: '').to.eql literalFalsey
expect(view.get 'literal', show: []).to.eql literalFalsey
expect(view.get 'literal').to.eql literalFalsey
# No parameter assumes it is a model path that is undefined
view._idCount = 0
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', true
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', 1
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', 'x'
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', {}
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', false
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', undefined
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', null
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', 0
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', ''
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', []
expect(view.get 'bound').to.eql modelFalsey
it 'supports else if conditionals', ->
view.make 'test', """
{{#if equal('red', value)}}
1
{{else if equal('red', value)}}
2
{{else if equal('green', value)}}
3
{{else}}
4
{{/}}
"""
expect(view.get 'test', value: 'red').to.equal '1'
expect(view.get 'test', value: 'green').to.equal '3'
expect(view.get 'test', value: 'blue').to.equal '4'
expect(view.get 'test').to.equal '4'
it 'supports unless then else conditionals', ->
view.make 'test', """
{{#unless value}}
1
{{else}}
2
{{/}}
"""
expect(view.get 'test', value: true).to.equal '2'
expect(view.get 'test', value: false).to.equal '1'
it 'supports lists in text', ->
template = """
<ul>
{{#each arr}}
<li>{{name}}
{{else}}
<li>Nothing to see
{{/}}
</ul>
"""
view.make 'test', template
expect(view.get 'test', arr: [])
.to.eql '<ul><li>Nothing to see</ul>'
view.make 'test', template
expect(view.get 'test', arr: [{name: 'stuff'}, {name: 'more'}])
.to.eql '<ul><li>stuff<li>more</ul>'
it 'supports nesting lists with relative paths', ->
template = """
<table>
<tbody>
{{#each table.rows}}
<tr>
{{#each .cells}}
<td><input value={{.text}}></td>
{{/}}
</tr>
{{/}}
</tbody>
</table>
"""
model.set 'table.rows', [
{cells: [{text: 'A'}, {text: 'B'}, {text: 'C'}]}
{cells: [{text: 1}, {text: 2}, {text: 3}]}
]
view.make 'test', template
expect(view.get 'test').to.equal [
'<table>'
'<tbody>'
'<tr>'
'<td><input value=A></td>'
'<td><input value=B></td>'
'<td><input value=C></td>'
'</tr>'
'<tr>'
'<td><input value=1></td>'
'<td><input value=2></td>'
'<td><input value=3></td>'
'</tr>'
'</tbody>'
'</table>'
].join('')
it 'supports nesting aliases to flat lists', ->
template = """
{{#each outer as :out}}
{{#each inner as :in}}
{{#each core as :core}}
[{{:out.name}} {{:in.name}} {{:core.name}} {{equal(:out.color, :in.color)}}]
{{/}}
{{/}}
{{/}}
"""
view.make 'test', template
compiled = view.get 'test',
outer: [{name: 'stuff', color: 'blue'}, {name: 'more', color: 'pink'}]
inner: [{name: '0', color: 'pink'}, {name: '1', color: 'blue'}]
core: [{name: '0'}, {name: '1'}]
expect(compiled).to.equal [
'[stuff 0 0 false]'
'[stuff 0 1 false]'
'[stuff 1 0 true]'
'[stuff 1 1 true]'
'[more 0 0 true]'
'[more 0 1 true]'
'[more 1 0 false]'
'[more 1 1 false]'
].join('')
it 'supports aliases from relative paths on nested lists', ->
template = """
<ul>
{{#each _room.street}}
<li>Type: {{.type}}
{{#each .people as :person}}
{{#if :person.editable}}
<input value={{:person.name}}>
{{else}}
{{:person.name}}
{{/}}
{{/}}
</li>
{{/}}
</ul>
"""
model.set '_room.street', [
{
type: 'home'
people: [
{name: '<NAME>', editable: true}
{name: '<NAME>', editable: false}
]
}, {
type: 'neighbor'
people: [
{name: '<NAME>', editable: false}
{name: '<NAME>', editable: true}
]
}
]
view.make 'test', template
expect(view.get 'test').to.equal [
'<ul>'
'<li>Type: home'
'<input value=<NAME>>'
'<NAME>'
'</li>'
'<li>Type: neighbor'
'<NAME>'
'<input value=betty>'
'</li>'
'</ul>'
].join('')
it 'supports aliases from aliases on nested lists', ->
template = """
<ul>
{{#each _room.street as :street}}
<li>Type: {{:street.type}}
{{#each :street.people as :person}}
{{#if :person.editable}}
<input value={{:person.name}}>
{{else}}
{{:person.name}}
{{/}}
{{/}}
</li>
{{/}}
</ul>
"""
model.set '_room.street', [
{
type: 'home'
people: [
{name: '<NAME>', editable: true}
{name: '<NAME>', editable: false}
]
}, {
type: 'neighbor'
people: [
{name: '<NAME>', editable: false}
{name: '<NAME>', editable: true}
]
}
]
view.make 'test', template
expect(view.get 'test').to.equal [
'<ul>'
'<li>Type: home'
'<input value=<NAME>>'
'<NAME>'
'</li>'
'<li>Type: neighbor'
'<NAME>'
'<input value=betty>'
'</li>'
'</ul>'
].join('')
it 'supports boolean attributes', ->
view.make 'test', '<input disabled={maybe}>'
expect(view.get 'test').to.equal '<input id=$0>'
expect(view.get 'test', maybe: false).to.equal '<input id=$1>'
expect(view.get 'test', maybe: true).to.equal '<input id=$2 disabled>'
it 'supports paths containing dots for ctx object items', ->
view.make 'test', '<b>{{user.name}}</b>'
ctx = user: {name: '<NAME>'}
expect(view.get 'test', ctx).to.equal '<b><NAME></b>'
it 'supports relative paths for ctx object items', ->
view.make 'test', '{{#if user}}<b>{{.name}}</b>{{/}}'
ctx = user: {name: '<NAME>'}
expect(view.get 'test', ctx).to.equal '<b><NAME></b>'
it 'supports Arrays containing non-objects from ctx', ->
view.make 'test1', '{{#each bools}}<b>{{this}}</b>{{/}}'
view.make 'test2', '{{#each bools as :value}}<b>{{:value}}</b>{{/}}'
ctx = bools: [true, false, true]
expect(view.get 'test1', ctx).to.equal '<b>true</b><b>false</b><b>true</b>'
expect(view.get 'test2', ctx).to.equal '<b>true</b><b>false</b><b>true</b>'
it 'supports view helper functions', ->
view.fn 'lower', (s) -> s.toLowerCase()
view.make 'test', '''{{lower('HI')}} {lower( "HI" )}'''
expect(view.get 'test').to.equal 'hi <!--$0-->hi<!--$$0-->'
view.fn 'sum', (a, b) -> a + b
view.make 'test', '{{sum(4, 9)}}'
expect(view.get 'test').to.equal '13'
view._idCount = 0
view.make 'test', '{equal(1, sum(-5, 6))}'
expect(view.get 'test').to.equal '<!--$0-->true<!--$$0-->'
view._idCount = 0
view.make 'test', '{unescaped equal(sum(-5, 6), 1)}'
expect(view.get 'test').to.equal '<!--$0-->true<!--$$0-->'
view.make 'test', '{{sum(4, count)}}'
expect(view.get 'test', {count: 7}).to.equal '11'
model.set 'count', 13
expect(view.get 'test').to.equal '17'
view._idCount = 0
view.make 'test', '''
<select>
{{#each items}}
<option selected="{{equal(this, current)}}">{{this}}
{{/}}
</select>
'''
expect(view.get 'test',
items: ['a', 'b', 'c']
current: 'c'
).to.equal '<select id=$0><option>a<option>b<option selected>c</select>'
view.fn 'positive', (num) -> num >= 0
view.make 'test', '''
{{#each nums as :num}}
{{#if positive(:num)}}
{{:num}},
{{/}}
{{/}}
'''
expect(view.get 'test', {nums: [-4, 8, 0, 2.3, -9]}).to.equal '8,0,2.3,'
it 'supports x-no-minify', ->
view.make 'test', '''
<script type="x-test" x-no-minify>
Some text
And a new line
</script>
'''
expect(view.get 'test').to.equal '''
<script type=x-test>
Some text
And a new line
</script>
''' | true | {expect, calls} = require 'racer/test/util'
{DetachedModel: Model, ResMock} = require './mocks'
View = require '../lib/View.server'
describe 'View.render', ->
it 'supports view.render with no defined views', ->
view = new View
res = new ResMock
res.onEnd = (html) ->
expect(html).to.match /^<!DOCTYPE html><meta charset=utf-8><title>.*<\/title><script>.*<\/script><script.*><\/script>$/
view.render res
describe 'View', ->
view = model = null
beforeEach (done) ->
view = new View
model = new Model
view._init model, false, done
it 'supports rendering a string literal view', ->
view.make 'test', """
<style>
body {
margin:
0
}
</style>
"""
# String views should have line breaks and leading whitespace removed
expect(view.get 'test').to.eql '<style>body {margin: 0}</style>'
it 'doctypes and conditional comments are maintained', ->
view.make 'test', """
<!DOCTYPE html>
<!-- This comment is removed -->
<title></title>
<!--[if gt IE 6]>
IE greater than 6
<![endif]-->
<!--[if !IE]> -->
Not IE
<!-- <![endif]-->
"""
expect(view.get 'test').to.eql '<!DOCTYPE html>' +
'<title></title>' +
'<!--[if gt IE 6]>\n' +
'IE greater than 6\n' +
'<![endif]-->' +
'<!--[if !IE]> -->Not IE<!-- <![endif]-->'
it 'supports substituting variables into text', ->
view.make 'test', '''
{{connected}}{{canConnect}} {{nada}}
<p>
{{name}}
</p>
<p>
{{age}} - {{height}} - {{weight}}
</p>
'''
ctx =
connected: false
weight: '165 lbs'
nada: null
model.set 'name', 'PI:NAME:<NAME>END_PI'
model.set 'age', 22
model.set 'height', '6 ft 2 in'
model.set 'weight', '175 lbs'
expected = 'falsetrue ' +
'<p>PI:NAME:<NAME>END_PI</p>' +
'<p>22 - 6 ft 2 in - 165 lbs</p>'
expect(view.get 'test', ctx).to.equal expected
it 'supports path interpolation', ->
view.make 'test', """
{{items[id]}}
{{#each ids}}
{{items[this]}}
{{/}}
{{#each others}}
{{items[.id]}}
{{/}}
"""
model.set 'id', 2
model.set 'ids', [2, 0]
ctx =
items:
0: 'red'
1: 'green'
2: 'blue'
others: [
{id: 1}
{id: 2}
]
expect(view.get 'test', ctx).to.equal 'blue' +
'blue' + 'red' +
'green' + 'blue'
it 'supports binding variables in text', ->
view.make 'test', '''
{connected}{canConnect} {nada}
<p>
{name}
</p>
<p>
{age} - {height} - {weight}
</p>
'''
ctx =
connected: false
weight: '165 lbs'
nada: null
model.set 'name', 'PI:NAME:<NAME>END_PI'
model.set 'age', 22
model.set 'height', '6 ft 2 in'
model.set 'weight', '175 lbs'
expect(view.get 'test', ctx).to.equal '<!--$0-->false<!--$$0--><!--$1-->true<!--$$1--> <!--$2--><!--$$2-->' +
'<p id=$3>PI:NAME:<NAME>END_PI</p>' +
'<p><!--$4-->22<!--$$4--> - <!--$5-->6 ft 2 in<!--$$5--> - <!--$6-->165 lbs<!--$$6--></p>'
it 'supports HTML escaping', ->
# Attribute values are escaped regardless of placeholder type
# Ampersands are escaped at the end of a replacement even when not
# required, because it is sometimes needed depending on the following item
template = '''<input value="{unescaped html}"> {html}x{unescaped html}'''
value = '<b id="hey">&Hi! & x& </b>&'
expected =
'<input id=$0 value="<b id="hey">&Hi! & x& </b>&"> ' +
'<!--$1--><b id="hey">&Hi! & x& </b>&<!--$$1-->x' +
'<!--$2--><b id="hey">&Hi! & x& </b>&<!--$$2-->'
view.make 'test1', template
expect(view.get 'test1', html: value).to.eql expected
view._idCount = 0
model.set 'html', value
expect(view.get 'test1').to.eql expected
view.make 'test2',
'<p a={{a}} b={{b}} c={{c}} d={{d}} e={{e}} f={{f}} g={{g}} h={{h}} i>'
expect(view.get 'test2',
{a: '"', b: "'", c: '<', d: '>', e: '=', f: ' ', g: '', h: null}
).to.eql '<p a=" b="\'" c="<" d=">" e="=" f=" " g="" h="" i>'
it 'supports HTML entity unescaping in string partials', ->
view.make 'title', '{{unescaped name}} - stuff'
ctx = name: 'PI:NAME:<NAME>END_PI;PI:NAME:<NAME>END_PI;PI:NAME:<NAME>END_PI'
expect(view.get 'title$s', ctx).to.eql 'Crème Brûlée - stuff'
it 'supports conditional blocks in text', ->
view.make 'literal',
'{{#if show}}Yep{{else}}Nope{{/}}{{#if show}} Yes!{{/}} {{#unless show}}No{{/}}'
view.make 'bound',
'{#if show}Yep{else}Nope{/}{#if show} Yes!{/} {#unless show}No{/}'
literalTruthy = 'Yep Yes! '
literalFalsey = 'Nope No'
modelTruthy = '<!--$0-->Yep<!--$$0--><!--$1--> Yes!<!--$$1--> <!--$2--><!--$$2-->'
modelFalsey = '<!--$0-->Nope<!--$$0--><!--$1--><!--$$1--> <!--$2-->No<!--$$2-->'
expect(view.get 'literal', show: true).to.eql literalTruthy
expect(view.get 'literal', show: 1).to.eql literalTruthy
expect(view.get 'literal', show: 'x').to.eql literalTruthy
expect(view.get 'literal', show: {}).to.eql literalTruthy
expect(view.get 'literal', show: [1]).to.eql literalTruthy
expect(view.get 'literal', show: false).to.eql literalFalsey
expect(view.get 'literal', show: undefined).to.eql literalFalsey
expect(view.get 'literal', show: null).to.eql literalFalsey
expect(view.get 'literal', show: 0).to.eql literalFalsey
expect(view.get 'literal', show: '').to.eql literalFalsey
expect(view.get 'literal', show: []).to.eql literalFalsey
expect(view.get 'literal').to.eql literalFalsey
# No parameter assumes it is a model path that is undefined
view._idCount = 0
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', true
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', 1
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', 'x'
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', {}
expect(view.get 'bound').to.eql modelTruthy
view._idCount = 0
model.set 'show', false
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', undefined
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', null
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', 0
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', ''
expect(view.get 'bound').to.eql modelFalsey
view._idCount = 0
model.set 'show', []
expect(view.get 'bound').to.eql modelFalsey
it 'supports else if conditionals', ->
view.make 'test', """
{{#if equal('red', value)}}
1
{{else if equal('red', value)}}
2
{{else if equal('green', value)}}
3
{{else}}
4
{{/}}
"""
expect(view.get 'test', value: 'red').to.equal '1'
expect(view.get 'test', value: 'green').to.equal '3'
expect(view.get 'test', value: 'blue').to.equal '4'
expect(view.get 'test').to.equal '4'
it 'supports unless then else conditionals', ->
view.make 'test', """
{{#unless value}}
1
{{else}}
2
{{/}}
"""
expect(view.get 'test', value: true).to.equal '2'
expect(view.get 'test', value: false).to.equal '1'
it 'supports lists in text', ->
template = """
<ul>
{{#each arr}}
<li>{{name}}
{{else}}
<li>Nothing to see
{{/}}
</ul>
"""
view.make 'test', template
expect(view.get 'test', arr: [])
.to.eql '<ul><li>Nothing to see</ul>'
view.make 'test', template
expect(view.get 'test', arr: [{name: 'stuff'}, {name: 'more'}])
.to.eql '<ul><li>stuff<li>more</ul>'
it 'supports nesting lists with relative paths', ->
template = """
<table>
<tbody>
{{#each table.rows}}
<tr>
{{#each .cells}}
<td><input value={{.text}}></td>
{{/}}
</tr>
{{/}}
</tbody>
</table>
"""
model.set 'table.rows', [
{cells: [{text: 'A'}, {text: 'B'}, {text: 'C'}]}
{cells: [{text: 1}, {text: 2}, {text: 3}]}
]
view.make 'test', template
expect(view.get 'test').to.equal [
'<table>'
'<tbody>'
'<tr>'
'<td><input value=A></td>'
'<td><input value=B></td>'
'<td><input value=C></td>'
'</tr>'
'<tr>'
'<td><input value=1></td>'
'<td><input value=2></td>'
'<td><input value=3></td>'
'</tr>'
'</tbody>'
'</table>'
].join('')
it 'supports nesting aliases to flat lists', ->
template = """
{{#each outer as :out}}
{{#each inner as :in}}
{{#each core as :core}}
[{{:out.name}} {{:in.name}} {{:core.name}} {{equal(:out.color, :in.color)}}]
{{/}}
{{/}}
{{/}}
"""
view.make 'test', template
compiled = view.get 'test',
outer: [{name: 'stuff', color: 'blue'}, {name: 'more', color: 'pink'}]
inner: [{name: '0', color: 'pink'}, {name: '1', color: 'blue'}]
core: [{name: '0'}, {name: '1'}]
expect(compiled).to.equal [
'[stuff 0 0 false]'
'[stuff 0 1 false]'
'[stuff 1 0 true]'
'[stuff 1 1 true]'
'[more 0 0 true]'
'[more 0 1 true]'
'[more 1 0 false]'
'[more 1 1 false]'
].join('')
it 'supports aliases from relative paths on nested lists', ->
template = """
<ul>
{{#each _room.street}}
<li>Type: {{.type}}
{{#each .people as :person}}
{{#if :person.editable}}
<input value={{:person.name}}>
{{else}}
{{:person.name}}
{{/}}
{{/}}
</li>
{{/}}
</ul>
"""
model.set '_room.street', [
{
type: 'home'
people: [
{name: 'PI:NAME:<NAME>END_PI', editable: true}
{name: 'PI:NAME:<NAME>END_PI', editable: false}
]
}, {
type: 'neighbor'
people: [
{name: 'PI:NAME:<NAME>END_PI', editable: false}
{name: 'PI:NAME:<NAME>END_PI', editable: true}
]
}
]
view.make 'test', template
expect(view.get 'test').to.equal [
'<ul>'
'<li>Type: home'
'<input value=PI:NAME:<NAME>END_PI>'
'PI:NAME:<NAME>END_PI'
'</li>'
'<li>Type: neighbor'
'PI:NAME:<NAME>END_PI'
'<input value=betty>'
'</li>'
'</ul>'
].join('')
it 'supports aliases from aliases on nested lists', ->
template = """
<ul>
{{#each _room.street as :street}}
<li>Type: {{:street.type}}
{{#each :street.people as :person}}
{{#if :person.editable}}
<input value={{:person.name}}>
{{else}}
{{:person.name}}
{{/}}
{{/}}
</li>
{{/}}
</ul>
"""
model.set '_room.street', [
{
type: 'home'
people: [
{name: 'PI:NAME:<NAME>END_PI', editable: true}
{name: 'PI:NAME:<NAME>END_PI', editable: false}
]
}, {
type: 'neighbor'
people: [
{name: 'PI:NAME:<NAME>END_PI', editable: false}
{name: 'PI:NAME:<NAME>END_PI', editable: true}
]
}
]
view.make 'test', template
expect(view.get 'test').to.equal [
'<ul>'
'<li>Type: home'
'<input value=PI:NAME:<NAME>END_PI>'
'PI:NAME:<NAME>END_PI'
'</li>'
'<li>Type: neighbor'
'PI:NAME:<NAME>END_PI'
'<input value=betty>'
'</li>'
'</ul>'
].join('')
it 'supports boolean attributes', ->
view.make 'test', '<input disabled={maybe}>'
expect(view.get 'test').to.equal '<input id=$0>'
expect(view.get 'test', maybe: false).to.equal '<input id=$1>'
expect(view.get 'test', maybe: true).to.equal '<input id=$2 disabled>'
it 'supports paths containing dots for ctx object items', ->
view.make 'test', '<b>{{user.name}}</b>'
ctx = user: {name: 'PI:NAME:<NAME>END_PI'}
expect(view.get 'test', ctx).to.equal '<b>PI:NAME:<NAME>END_PI</b>'
it 'supports relative paths for ctx object items', ->
view.make 'test', '{{#if user}}<b>{{.name}}</b>{{/}}'
ctx = user: {name: 'PI:NAME:<NAME>END_PI'}
expect(view.get 'test', ctx).to.equal '<b>PI:NAME:<NAME>END_PI</b>'
it 'supports Arrays containing non-objects from ctx', ->
view.make 'test1', '{{#each bools}}<b>{{this}}</b>{{/}}'
view.make 'test2', '{{#each bools as :value}}<b>{{:value}}</b>{{/}}'
ctx = bools: [true, false, true]
expect(view.get 'test1', ctx).to.equal '<b>true</b><b>false</b><b>true</b>'
expect(view.get 'test2', ctx).to.equal '<b>true</b><b>false</b><b>true</b>'
it 'supports view helper functions', ->
view.fn 'lower', (s) -> s.toLowerCase()
view.make 'test', '''{{lower('HI')}} {lower( "HI" )}'''
expect(view.get 'test').to.equal 'hi <!--$0-->hi<!--$$0-->'
view.fn 'sum', (a, b) -> a + b
view.make 'test', '{{sum(4, 9)}}'
expect(view.get 'test').to.equal '13'
view._idCount = 0
view.make 'test', '{equal(1, sum(-5, 6))}'
expect(view.get 'test').to.equal '<!--$0-->true<!--$$0-->'
view._idCount = 0
view.make 'test', '{unescaped equal(sum(-5, 6), 1)}'
expect(view.get 'test').to.equal '<!--$0-->true<!--$$0-->'
view.make 'test', '{{sum(4, count)}}'
expect(view.get 'test', {count: 7}).to.equal '11'
model.set 'count', 13
expect(view.get 'test').to.equal '17'
view._idCount = 0
view.make 'test', '''
<select>
{{#each items}}
<option selected="{{equal(this, current)}}">{{this}}
{{/}}
</select>
'''
expect(view.get 'test',
items: ['a', 'b', 'c']
current: 'c'
).to.equal '<select id=$0><option>a<option>b<option selected>c</select>'
view.fn 'positive', (num) -> num >= 0
view.make 'test', '''
{{#each nums as :num}}
{{#if positive(:num)}}
{{:num}},
{{/}}
{{/}}
'''
expect(view.get 'test', {nums: [-4, 8, 0, 2.3, -9]}).to.equal '8,0,2.3,'
it 'supports x-no-minify', ->
view.make 'test', '''
<script type="x-test" x-no-minify>
Some text
And a new line
</script>
'''
expect(view.get 'test').to.equal '''
<script type=x-test>
Some text
And a new line
</script>
''' |
[
{
"context": " @game = new GamingAPI.Models.Game\n name: \"test\"\n deck: \"My test description\"\n original",
"end": 231,
"score": 0.9938648343086243,
"start": 227,
"tag": "NAME",
"value": "test"
}
] | spec/javascripts/games/models/game_spec.js.coffee | Mack0856/gaming_api | 0 | describe "GamingAPI.Models.Game", ->
beforeEach ->
@platforms = new GamingAPI.Collections.Platforms([{abbreviation: "XB1"}, {abbreviation: "PS4"}, {abbreviation: "PC"}])
@game = new GamingAPI.Models.Game
name: "test"
deck: "My test description"
original_release_date: "2015-01-01"
id: 1
platforms: @platforms
image:
medium_url: "my fake url"
describe "#getName", ->
it "returns the game name", ->
expect(@game.getName()).toEqual "test"
describe "#getReleaseDate", ->
it "returns the release date", ->
expect(@game.getReleaseDate()).toEqual new Date("2015-01-01")
describe "#getId", ->
it "returns the id", ->
expect(@game.getId()).toEqual 1
describe "#getDescription", ->
it "returns the description", ->
expect(@game.getDescription()).toEqual "My test description"
describe "#getPlatforms", ->
it "returns a platforms collection", ->
expect(this.game.getPlatforms().models[0].attributes.models[0].attributes.abbreviation).toEqual "XB1"
describe "#getImageUrl", ->
it "returns the image url", ->
expect(@game.getImageUrl()).toEqual "my fake url"
| 93437 | describe "GamingAPI.Models.Game", ->
beforeEach ->
@platforms = new GamingAPI.Collections.Platforms([{abbreviation: "XB1"}, {abbreviation: "PS4"}, {abbreviation: "PC"}])
@game = new GamingAPI.Models.Game
name: "<NAME>"
deck: "My test description"
original_release_date: "2015-01-01"
id: 1
platforms: @platforms
image:
medium_url: "my fake url"
describe "#getName", ->
it "returns the game name", ->
expect(@game.getName()).toEqual "test"
describe "#getReleaseDate", ->
it "returns the release date", ->
expect(@game.getReleaseDate()).toEqual new Date("2015-01-01")
describe "#getId", ->
it "returns the id", ->
expect(@game.getId()).toEqual 1
describe "#getDescription", ->
it "returns the description", ->
expect(@game.getDescription()).toEqual "My test description"
describe "#getPlatforms", ->
it "returns a platforms collection", ->
expect(this.game.getPlatforms().models[0].attributes.models[0].attributes.abbreviation).toEqual "XB1"
describe "#getImageUrl", ->
it "returns the image url", ->
expect(@game.getImageUrl()).toEqual "my fake url"
| true | describe "GamingAPI.Models.Game", ->
beforeEach ->
@platforms = new GamingAPI.Collections.Platforms([{abbreviation: "XB1"}, {abbreviation: "PS4"}, {abbreviation: "PC"}])
@game = new GamingAPI.Models.Game
name: "PI:NAME:<NAME>END_PI"
deck: "My test description"
original_release_date: "2015-01-01"
id: 1
platforms: @platforms
image:
medium_url: "my fake url"
describe "#getName", ->
it "returns the game name", ->
expect(@game.getName()).toEqual "test"
describe "#getReleaseDate", ->
it "returns the release date", ->
expect(@game.getReleaseDate()).toEqual new Date("2015-01-01")
describe "#getId", ->
it "returns the id", ->
expect(@game.getId()).toEqual 1
describe "#getDescription", ->
it "returns the description", ->
expect(@game.getDescription()).toEqual "My test description"
describe "#getPlatforms", ->
it "returns a platforms collection", ->
expect(this.game.getPlatforms().models[0].attributes.models[0].attributes.abbreviation).toEqual "XB1"
describe "#getImageUrl", ->
it "returns the image url", ->
expect(@game.getImageUrl()).toEqual "my fake url"
|
[
{
"context": "'use strict'\n# <kdb-connect srvUser=\"u\" srvPass=\"p\" target=\"h\" query=\"starting sequence\"/>\n(() ->\n ",
"end": 50,
"score": 0.9988549947738647,
"start": 49,
"tag": "PASSWORD",
"value": "p"
}
] | kdb-wc.coffee | quintanar401/kdb-wc | 60 | 'use strict'
# <kdb-connect srvUser="u" srvPass="p" target="h" query="starting sequence"/>
(() ->
try
new CustomEvent 'test'
catch
CE = (event, params) ->
params = params || bubbles: false, cancelable: false, detail: undefined
evt = document.createEvent 'CustomEvent'
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
return evt
CE.prototype = window.CustomEvent.prototype
window.CustomEvent = CE
)()
extractInfo = (v) ->
return v if typeof v is 'string'
txt = ''
if v.nodeName is 'SELECT'
if v.multiple
r = []
for e in v.options
if e.selected
r.push e.text
txt = r.join '\n'
else
txt = v.options[v.selectedIndex].text if v.selectedIndex>=0
else if v.nodeName is 'INPUT'
if v.type is 'checkbox'
txt = if v.checked then '1b' else '0b'
else if v.type is 'radio'
txt = v.form.querySelector("input[type='radio'][name='#{v.name}']:checked")?.value || ''
else
txt = v?.value || ''
else if v.nodeName is 'TEXTAREA'
txt = v.value
else if v.nodeName is 'KDB-EDITOR'
txt = v.kEditor.getValue()
else
txt = v.textContent
txt
mergeCfgs = (c1,c2) ->
for n,v of c1
continue if (v2 = c2[n]) is undefined
if typeof v2 is 'object' and typeof v is 'object' and !v2.length and !v.length
c1[n] = mergeCfgs v, v2
else
c1[n] = v2
for n,v of c2
continue if c1[n]
c1[n] = v
c1
copyCfg = (c) ->
cc = {}
for n,v of c
if typeof v is 'object' and !v.length
cc[n] = copyCfg v
else
cc[n] = v
cc
getConfig = (c) ->
return copyCfg (c.split(".").reduce ((x,y) -> return x[y]), window) if /^[\w\.]+$/.test c
try
cfg = JSON.parse c
catch err
console.log "kdb-wc: config parse exception"
return console.log err
keval = (s) ->
# .split(".").reduce ((x,y) -> return x[y]), window
try
eval s
catch err
null
jsonpRegistry = {}
class _KDBSrv extends HTMLElement
createdCallback: ->
@srvType = @attributes['k-srv-type']?.textContent || "http"
@target = @attributes['k-target']?.textContent || null
@wsSrv = if @srvType in ['http','https'] then location.host else (@attributes['k-srv-uri']?.textContent || location.host)
@srvUser = @attributes['k-srv-user']?.textContent || null
@srvPass = @attributes['k-srv-pass']?.textContent || null
@qPrefix = @attributes['k-prefix']?.textContent || ""
@debug = @attributes['debug']?.textContent || null
@rType = @attributes['k-return-type']?.textContent || "json"
@fixJson = @attributes['fix-json']?.textContent || null
@kFeed = (@attributes['k-feed']?.textContent || "false") is "true"
@kDeser = (@attributes['k-deserialize']?.textContent || "false") is "true"
@hidden = true
@ws = @wsReq = null
@wsQueue = []
@rType = 'json' if @srvType is 'jsonp'
@srvProto = if /^http.?\:/.test @wsSrv then '' else if @srvType is 'https' then 'https://' else 'http://'
console.log "kdb-srv inited: srvType:#{@srvType}, target:#{@target}, prefix:#{@qPrefix}, rType:#{@rType}, proto:#{@srvProto}, srv: #{@wsSrv}" if @debug
if @target
@target = (document.querySelector "[k-id='#{@target}']") || @target
runQuery: (q,cb) ->
(cb = (r,e) -> null) unless cb
return @sendHTTP q,cb if @srvType in ['http','xhttp','jsonp','https']
return @sendWS q,cb if @srvType in ['ws','wss']
console.error 'kdb-srv: unknown srv type: '+@srvType
sendWS: (qq,clb) ->
@wsQueue.push q:qq, cb:clb
if !@ws
@ws = new WebSocket("#{@srvType}://#{@wsSrv}/")
@ws.binaryType = 'arraybuffer'
@ws.onopen = =>
console.log "kdb-srv-ws: opened" if @debug
@processWSQueue()
@ws.onclose = =>
console.log "kdb-srv-ws: closed" if @debug
@ws = null
@sendWSRes null,'closed'
@ws.onerror = (e) =>
console.log "kdb-srv-ws: error #{e.data}" if @debug
@sendWSRes null,e.data
@ws.onmessage = (e) =>
console.log "kdb-srv-ws: msg" if @debug
try
res = if @rType is "json" and typeof e.data is 'string' then JSON.parse e.data else if typeof e.data is 'object' then deserialize(e.data) else e.data
catch error
console.error "kdb-srv-ws: exception in ws parse #{error}"
return @sendWSRes null, "result parse error: "+error.toString()
@sendWSRes res, null
return
@processWSQueue() if @ws.readyState is 1
sendWSRes: (r,e) ->
return unless req=@wsReq
@wsReq = null unless @kFeed
try
req.cb r,e
catch err
console.error "kdb-srv-ws: exception in callback"
console.log err
@processWSQueue()
processWSQueue: ->
return if @wsReq or @wsQueue.length is 0
@wsReq = @wsQueue.shift()
req = @wsReq.q
req = @qPrefix + req if typeof req is 'string' and @qPrefix
req = "%target=#{trg}%" + req if @target and trg=extractInfo @target
if @rType is 'q'
try
req = ' '+req if typeof req is 'string' and req[0] is '`' # compensate the strange behavior of serialize
req = serialize req
catch error
console.error "kdb-srv-ws: exception in ws send #{error}"
return @sendWSRes null,'send'
return @ws.send req if @ws and @ws.readyState is 1
@sendWS @wsReq.q,@wsReq.cb
@wsReq = null
sendHTTP: (q,cb) ->
if @fixJson
@fixJson = null
@qPrefix = (if @srvType is 'jsonp' then 'jsp?' else "jsn?enlist ") unless @qPrefix
query = ".h.tx[`jsn]:(.j.j');"
query = '.h.tx[`jsp]:{enlist "KDB.processJSONP(\'",string[x 0],"\',",(.j.j x 1),")"};' if @srvType is 'jsonp'
query += 'if[105=type .h.hp;.h.hp:(f:{ssr[x y;"\nConnection: close";{"\nAccess-Control-Allow-Origin: *\r",x}]})[.h.hp];.h.he:f .h.he;.h.hy:{[a;b;c;d]a[b c;d]}[f;.h.hy]];' if @srvType is "xhttp"
return @runQuery "{#{query};1}[]", (r,e) => @runQuery q, cb
@qPrefix = (if @srvType is 'jsonp' then 'jsp?' else "json?enlist ") if !@qPrefix and @rType is "json"
if @srvType is 'jsonp'
q = @qPrefix + "(`#{rid = 'id'+Date.now()};#{encodeURIComponent q})"
else
q = @qPrefix + encodeURIComponent q
q = q + "&target=" + trg if @target and trg=extractInfo @target
q = @srvProto + @wsSrv + '/' + q
console.log "kdb-srv sending request:"+q if @debug
return @sendJSONP rid, q, cb if @srvType is 'jsonp'
xhr = new XMLHttpRequest()
xhr.onerror = =>
console.log "kdb-srv error: "+xhr.statusText + " - " + xhr.responseText if @debug
cb null, xhr.statusText+": "+xhr.responseText
xhr.ontimeout = =>
console.log "kdb-srv timeout" if @debug
cb null, "timeout"
xhr.onload = =>
return xhr.onerror() unless xhr.status is 200
console.log "kdb-srv data: "+xhr.responseText.slice(0,50) if @debug
try
try
res = if @rType is "json" then JSON.parse xhr.responseText else if @rType is "xml" then xhr.responseXML else xhr.responseText
res = deserialize res[1] if @kDeser and res instanceof Array and res[0] is 'deserialize'
catch error
console.error "kdb-srv: exception in JSON.parse"
return cb null, "JSON.parse error: "+error.toString()
cb res, null
catch err
console.error "kdb-srv: HTTP callback exception"
console.log err
xhr.open 'GET', q, true, @srvUser, @srvPass
xhr.send()
sendJSONP: (rid,q,cb) ->
resOk = false
jsonpRegistry[rid] = (res) =>
console.log "kdb-srv(jsonp) data: " + res.toString().slice(0,50) if @debug
delete jsonpRegistry[rid]
resOk = true
try
cb res, null
catch error
console.error "kdb-srv: HTTP callback exception"
console.log error
script = document.createElement('script')
script.onload = script.onerror = =>
return if resOk
delete jsonpRegistry[rid]
console.log "kdb-srv(jsonp): error" if @debug
try
cb null, "url: "+q
catch error
console.error "kdb-srv: HTTP callback exception"
console.log error
script.src = q
document.body.appendChild script
class _KDBQuery extends HTMLElement
createdCallback: ->
@hidden = true
@setupQuery()
setupQuery: ->
prvExec = @exec
clearTimeout @ktimer if @ktimer
@ktimer = null
@iterationNumber = 0
@kID = @attributes['k-id']?.textContent || "undefined"
@query = @attributes['k-query']?.textContent || @textContent
@srv = @attributes['k-srv']?.textContent || ""
@exec = @attributes['k-execute-on']?.textContent.split(' ').filter((e)-> e.length > 0) || ["load"]
@debug = @attributes['debug']?.textContent || null
@escapeQ = @attributes['k-escape-q']?.textContent || ""
@kDispUpd = (@attributes['k-dispatch-update']?.textContent || "false") is "true"
@updObjs = @attributes['k-update-elements']?.textContent.split(' ').filter((e)-> e.length > 0) || []
@updErr = @attributes['k-on-error']?.textContent.split(' ').filter((e)-> e.length > 0) || []
@kInterval = @attributes['k-interval']?.textContent || "0"
@kInterval = if Number.parseInt then Number.parseInt @kInterval else Number @kInterval
@kDelay = @attributes['k-delay']?.textContent || "0"
@kDelay = if Number.parseInt then Number.parseInt @kDelay else Number @kDelay
@kQStatus = @attributes['k-status-var']?.textContent || null
@kQNum = 0
if @kFilter = @attributes['k-filter']?.textContent
@kFilter = keval @kFilter
@result = null
if 'load' in @exec and (!prvExec or !('load' in prvExec))
if document.readyState in ['complete','interactive']
setTimeout (=> @runQuery { src:"self", txt:"load"}), 100
else
document.addEventListener "DOMContentLoaded", (ev) => @runQuery src:"self", txt:"load"
for el in @exec when !(el in ['load','manual','timer'])
@addUpdater(v,el) if v = document.querySelector "[k-id='#{el}']"
@kRefs = @query.match(/\$(\w|\.)(\w|\.|\]|\[|\-)*\$/g)?.map (e) -> e.slice 1,e.length-1
@kMap = null
if 'timer' in @exec
setTimeout (=> @rerunQuery src:"self", txt:"timer"), if @kDelay then @kDelay else @kInterval
console.log "kdb-query inited: srv:#{@srv}, query:#{@query}, executeOn:#{@exec}, updateObs:#{@updObjs}, refs:#{@kRefs}, delay:#{@kDelay}, interval:#{@kInterval}" if @debug
rerunQuery: (args = {}) ->
args['pres'] = @result
@result = null
@runQuery args
runQuery: (args = {}) ->
args["i"] = @iterationNumber
return if @result isnt null
if typeof @srv is 'string'
@srv = if @srv is "" then document.getElementsByTagName("kdb-srv")?[0] else document.querySelector "[k-id='#{@srv}']"
console.log "kdb-query: executing query" if @debug
@kQNum += 1
@updateStatus()
@srv.runQuery @resolveRefs(@query, args), (r,e) =>
@kQNum -= 1
console.log "kdb-query: got response with status #{e}" if @debug
if e
@updateStatus()
@updObjWithRes o,document.querySelector("[k-id='#{o}']"),e for o in @updErr
else
r = (if typeof @kFilter is 'object' then @kFilter.filter r else @kFilter r) if @kFilter
@result = r
@updateStatus()
@updateObjects()
@sendEv()
setTimeout (=> @rerunQuery src:"self", txt:"timer"), @kInterval if @kInterval and 'timer' in @exec
@iterationNumber += 1
sendEv: -> @dispatchEvent @getEv() if @result isnt null
getEv: ->
new CustomEvent "newResult",
detail: if @kDispUpd then @result[""] else @result
bubbles: true
cancelable: true
onresult: (f) ->
@addEventListener 'newResult', f
f @getEv() if @result isnt null
setQueryParams: (o,c2) ->
return c2 unless attrs = o.attributes['k-attr']?.textContent
c1 = {}
c1[n] = o.attributes[n].textContent || "" for n in attrs.split(' ').filter((e)-> e.length > 0)
mergeCfgs c1,c2
addUpdater: (v,kid) ->
if v.nodeName is 'BUTTON'
v.addEventListener 'click', (ev) => @rerunQuery @setQueryParams v, src:'button', id: kid
else if v.nodeName is 'KDB-EDITOR'
v.onexec (ev) => @rerunQuery @setQueryParams v, src:'editor', id: kid, txt: ev.detail
else if v.nodeName is 'KDB-QUERY'
v.onresult (ev) => @rerunQuery @setQueryParams v, src:'query', id: kid, txt: ev.detail
else if v.nodeName in ['SELECT','TEXTAREA','INPUT']
v.addEventListener 'change', (ev) => @rerunQuery @setQueryParams v, src:v.nodeName, id: kid, txt: extractInfo v
else
v.addEventListener 'click', (ev) => @rerunQuery @setQueryParams v, src:v.nodeName, id: kid, txt: if (typeof ev.kdetail isnt "undefined" and ev.kdetail isnt null) then ev.kdetail else ev.target?.textContent
kdbUpd: (r,kid) -> @rerunQuery src:'query', id: kid, txt: r
updateStatus: ->
if @kQStatus
a = new Function "x",@kQStatus+" = x"
try
a(@kQNum)
catch
null
return
updateObjects: ->
@updateObj o,true,document.querySelector "[k-id='#{o}']" for o in @updObjs
if @kDispUpd
if typeof @result isnt 'object'
console.error "kdb-query: dictionary is expected with dispatch setting"
return console.log @result
@updateObj n,false,document.querySelector "[k-id='#{n}']" for n of @result when n
updateObj: (n,isUpd,o) ->
r = if @kDispUpd then @result[if isUpd then "" else n] else @result
return if r is undefined
@updObjWithRes n,o,r
updObjWithRes: (n,o,r) ->
if !o
a = new Function "x",n+" = x"
try
a(r)
catch
null
return
if o.kdbUpd
try
o.kdbUpd r, @kID
catch err
console.log "kdb-query:exception in kdbUpd"
console.log err
else if o.nodeName in ['SELECT','DATALIST']
prv = if o.nodeName is 'SELECT' and o.selectedIndex>=0 then o.options[o.selectedIndex].text else null
idx = -1
o.innerHTML = ''
for e,i in r
opt = document.createElement 'option'
opt.value = e.toString()
opt.text = e.toString()
idx = i if prv is opt.text
o.appendChild opt
o.selectedIndex = idx if idx>=0 and o.attributes['k-preserve']?.textContent
else if o.nodeName in ['KDB-CHART','KDB-TABLE','KDB-EDITOR'] # not inited
setTimeout (=> o.kdbUpd r,@kID),0
else
a = o.attributes['k-append']?.textContent || 'overwrite'
ty = o.attributes['k-content-type']?.textContent || 'text'
s = if o.textContent then '\n' else ''
if ty is 'text'
if a is 'top' then o.textContent = r.toString()+s+o.textContent else if a is 'bottom' then o.textContent += s+r.toString() else o.textContent = r.toString()
else
return o.innerHTML = r.toString() if a is 'overwrite'
if a is 'top' then o.insertAdjacentHTML 'afterBegin', r.toString()+s else o.insertAdjacentHTML 'beforeEnd', s+r.toString()
resolveRefs: (q,args)->
console.log args if @debug
return q unless @kRefs
if !@kMap
@kMap = {}
@kMap[e] = null for e in @kRefs
@kMap[e] = document.querySelector "[k-id='#{e}']" for e of @kMap
for n,v of @kMap
if !v
val = args[n]
val = keval n if val is null or val is undefined
txt = if val is null or val is undefined then n else val.toString()
else
txt = extractInfo v
q = q.replace (new RegExp "\\$#{n.replace /(\[|\])/g,"."}\\$", "g"), @escape txt
console.log "kdb-query: after resolve - #{q}" if @debug
q
escape: (s) -> if @escapeQ then s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\240/g," ").replace(/\n/g,"\\n") else s
class _KDBTable extends HTMLElement
createdCallback: ->
@srv = @attributes['k-srv']?.textContent || ""
@query = @attributes['k-query']?.textContent || @textContent
@kLib = @attributes['k-lib']?.textContent || 'table'
@debug = @attributes['debug']?.textContent || null
@escHtml = (@attributes['k-escape-html']?.textContent || 'true') == 'true'
@kConfig = @attributes['k-config']?.textContent
@kClass = @attributes['k-class']?.textContent || "kdb-table"
@kStyle = @attributes['k-style']?.textContent || ""
@kSearch = (@attributes['k-search']?.textContent || 'false') == 'true'
@inited = false
@initContainer()
console.log "kdb-table: srv: #{@srv}, query: #{@query}, lib:#{@kLib}" if @debug
initContainer: ->
if @kLib in ['jsgrid','datatables']
this.innerHTML = "" if @kCont
@kCont = document.createElement if @kLib is 'jsgrid' then 'div' else 'table'
cont = document.createElement 'div'
cont.className = @kClass
cont.style.cssText = @kStyle
@kCont.style.cssText = "width: 100%;" if @kLib is 'datatables'
cont.appendChild @kCont
this.appendChild cont
attachedCallback: ->
if !@inited
console.log "kdb-table: initing" if @debug
@inited = true
return if @query is ""
if /\w+/.test @query
@query = srv if srv = document.querySelector "[k-id='#{@query}']"
if typeof @query is 'string'
console.log "kdb-table: creating a query" if @debug
q = new KDB.KDBQuery()
q.setAttribute 'k-query', @query
q.setAttribute 'k-srv', @srv if @srv
q.setAttribute 'debug', @debug if @debug
q.setupQuery()
@query = q
return unless @query?.runQuery
@query.onresult (ev) => @onResult ev
console.log "kdb-table: init complete" if @debug
if @kLib in ['jsgrid','datatables'] and @kConfig
cfg = getConfig @kConfig
return unless cfg?.pageLoading or cfg?.serverSide
console.log "kdb-table: pageLoading/serverSide is set, forcing the first page" if @debug
@query.rerunQuery start: 0, size: 1, sortBy:"", sortOrder:"", data: null
onResult: (ev) ->
console.log "kdb-table: got event" if @debug
@updateTbl ev.detail
kdbUpd: (r,kID) ->
@query = document.querySelector "[k-id='#{kID}']"
@updateTbl r
updateTbl: (r) ->
console.log "kdb-table: data" if @debug
console.log r if @debug
return @updateJSGrid r if @kLib is 'jsgrid' and @kCfg?.pageLoading
return @updateDT r if @kLib is 'datatables' and @kCfg?.serverSide
return if (r.length || 0) is 0
return @updateJSGrid r if @kLib is 'jsgrid'
return @updateDT r if @kLib is 'datatables'
tbl = "<table class='#{@kClass}' style='#{@kStyle}'><tr>"
tbl += "<th>#{@escapeHtml c}</th>" for c of r[0]
tbl += "</tr>"
for e in r
tbl += "<tr>"
tbl += "<td>#{@escapeHtml d}</td>" for c,d of e
tbl += "</tr>"
tbl += "</table>"
@innerHTML = tbl
updateJSGrid: (r) ->
if @kCfg?.pageLoading
return @kPromise.resolve r
@kData = r
f = []
for n,v of r[0]
if typeof v is 'string'
f.push name:n, type: "text"
else if typeof v is 'number'
f.push name:n, type: "number"
else if typeof v is 'boolean'
f.push name:n, type: "checkbox"
else if v instanceof Date
f.push name:n, type: "text", subtype: 'date', itemTemplate: (v) -> v.toISOString()
else
f.push name:n, type: "text"
cfg =
width: '100%'
height: '100%'
filtering: @kSearch
sorting: true
paging: r.length>100
pageButtonCount: 5
pageSize: 50
fields: f
controller: loadData: (a) => @loadData a
cfg = mergeCfgs cfg, getConfig @kConfig if @kConfig
if cfg.pageLoading
cfg.paging = true
cfg.autoload = true
else
cfg.data = r
@kCfg = cfg
console.log "kdb-table: cfg" if @debug
console.log cfg if @debug
$(@kCont).jsGrid cfg
updateDT: (r) ->
if @kCfg?.serverSide and @kCB and r.draw?
if r.draw is @kDraw
@kCB r
@kCB = null
return
@initContainer() if @kCfg # reinit the container
c = []
for n,v of r[0]
c.push data: n, title: n
cfg =
columns: c
searching: @kSearch
scrollX: true
processing: true
cfg = mergeCfgs cfg, getConfig @kConfig if @kConfig
@kCfg = cfg
cfg.paging = r.length>100 or (cfg.serverSide || false) unless cfg.paging?
if cfg.serverSide
cfg.ajax = (d,cb,set) =>
@kCB = cb
@kDraw = d.draw
@query.rerunQuery data: JSON.stringify d
else
cfg.data = r
if @debug
console.log "kdb-table: cfg"
console.log cfg
$(@kCont).DataTable cfg
loadData: (f) ->
if f.pageIndex
@query.rerunQuery start: (f.pageIndex-1)*f.pageSize, size: f.pageSize, sortBy: f.sortField or "", sortOrder: f.sortOrder or 'asc'
@kPromise = $.Deferred()
return @kPromise
return @kData.filter (e) =>
r = true
for v in @kCfg.fields
if v.type is "text" and v.subtype is 'date'
r = r and (!f[v.name] or -1<e[v.name].toISOString().indexOf f[v.name])
else if v.type is "text"
r = r and (!f[v.name] or -1<e[v.name].indexOf f[v.name])
else if v.type is "number"
r = r and (!f[v.name] or 1>Math.abs e[v.name] - f[v.name])
else
r = r and (f[v.name] is undefined or e[v.name] is f[v.name])
r
escapeHtml: (s) ->
s = if s is null then "" else s.toString()
if @escHtml then s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>') else s
class _KDBChart extends HTMLElement
createdCallback: ->
@srv = @attributes['k-srv']?.textContent || ""
@query = @attributes['k-query']?.textContent || @textContent
@debug = @attributes['debug']?.textContent || null
@kFlow = (@attributes['k-flow']?.textContent || "false") is "true"
@kConfig = @attributes['k-config']?.textContent
kClass = @attributes['k-class']?.textContent || ""
kStyle = @attributes['k-style']?.textContent || ""
@kChType = @attributes['k-chart-type']?.textContent || "line"
@kTime = @attributes['k-time-col']?.textContent
@kData = @attributes['k-data-cols']?.textContent.split(' ').filter (el) -> el.length>0
@inited = false
@chart = null
@chSrc = ''
@kDygraph = /^dygraph/.test @kChType
@kChType = @kChType.match(/^dygraph-(.*)$/)?[1] || 'line' if @kDygraph
@kCont = document.createElement 'div'
@kCont.className = kClass
@kCont.style.cssText = kStyle
this.innerHTML = ''
this.appendChild @kCont
console.log "kdb-chart: query:#{@query}, type:#{@kChType}, cfg:#{@kConfig}" if @debug
attachedCallback: ->
if !@inited
console.log "kdb-chart: initing" if @debug
@inited = true
return if @query is ""
if /\w+/.test @query
@query = srv if srv = document.querySelector "[k-id='#{@query}']"
if typeof @query is 'string'
console.log "kdb-chart: creating a query" if @debug
q = new KDB.KDBQuery()
q.setAttribute 'k-query', @query
q.setAttribute 'k-srv', @srv if @srv
q.setAttribute 'debug', @debug if @debug
q.setupQuery()
@query = q
return unless @query?.runQuery
@query.onresult (ev) => @onResult ev
console.log "kdb-chart: init complete" if @debug
attributeChangedCallback: (a,o,n) ->
if a is "k-init"
@createdCallback()
@attachedCallback()
onResult: (ev) ->
console.log "kdb-chart: got event" if @debug
console.log ev.detail if @debug
@updateChart ev.detail
kdbUpd: (r) ->
console.log "kdb-chart: got update" if @debug
console.log r if @debug
@updateChart r
updateDyChart: (r) ->
if @chart and @kFlow
console.log "Flow update" if @debug
data = r if @chSrc is 'dy'
data = @convertDyAllTbl r if @chSrc is 'user'
data = (@convertDyTbl r,@dtCfg.time,@dtCfg.data)[1] if @chSrc is 'auto'
console.log data if @debug
@dyData = (@dyData.concat data).slice data.length
return @chart.updateOptions file: @dyData
if @kChType is 'use-config'
return unless @kConfig and typeof r is 'object'
return if r.length is 0
console.log "kdb-chart: will use provided cfg" if @debug
cfg = getConfig @kConfig
data = @convertDyAllTbl r
@chSrc = 'user'
else
if typeof r is 'object' and r.length is 2 and (r[0] instanceof Array or typeof r[0] is 'string') # raw config
console.log 'kdb-chart: raw config' if @debug
data = r[0]
cfg = r[1]
@chSrc = 'dy'
else
console.log "Will detect the user format" if @debug
return unless tm = @detectTime r[0]
console.log "Time is #{tm}" if @debug
dt = @detectData r[0]
console.log "Data is #{dt}" if @debug
@dtCfg = data: dt, time: tm
return if dt.length is 0
r = @convertDyTbl r,tm,dt
data = r[1]
cfg = labels: r[0]
@chSrc = 'auto'
if @kChType is 'merge-config'
console.log "kdb-chart: will merge cfgs" if @debug
cfg = mergeCfgs cfg, getConfig @kConfig
if typeof data is 'string'
cfg = mergeCfgs cfg,
xValueParser: (d) => @convDyTime d
axes:
x:
valueFormatter: Dygraph.dateString_
ticker: Dygraph.dateTicker
console.log "kdb-chart: cfg is" if @debug
console.log cfg if @debug
console.log data if @debug
@dyData = data if @kFlow
return @updateDyChartWithData data,cfg
updateDyChartWithData: (d,c) -> @chart = new Dygraph @kCont,d,c
updateChart: (r) ->
return @updateDyChart r if @kDygraph
if @chart and @kFlow
if @chSrc is 'c3'
return @updateFlowWithData r
tbl = r
cfg = {}
if r['data']
cfg.to = r.to if r.to
cfg.length = r.length if r.length
cfg.duration = r.duration if r.duration
tbl = r.data
cfg.rows = @convertAllTbl tbl if @chSrc is 'user'
cfg.rows = @convertTbl tbl,@dtCfg.time,@dtCfg.data if @chSrc is 'auto'
cfg.columns = ([n].concat v for n,v of tbl) if @chSrc is 'dict'
return @updateFlowWithData cfg
if @kChType is 'use-config'
return unless @kConfig and typeof r is 'object'
return if r.length is 0
console.log "kdb-chart: will use provided cfg" if @debug
cfg = getConfig @kConfig
cfg.data.rows = @convertAllTbl r
@chSrc = 'user'
else if typeof r is 'object' and r.data
console.log "C3 format detected" if @debug
console.log r if @debug
@chSrc = 'c3'
cfg = r
else if typeof r is 'object' and r.length>0
# detect format
console.log "Will detect the user format" if @debug
return unless tm = @detectTime r[0]
fmt = @detectTimeFmt r[0][tm]
xfmt = @detectTimeXFmt r, tm, fmt
console.log "Time is #{tm}, fmt is #{fmt}, xfmt is #{xfmt}" if @debug
dt = @detectData r[0]
console.log "Data is #{dt}" if @debug
@dtCfg = data: dt, time: tm
return if dt.length is 0
cfg =
data:
x: tm
rows: @convertTbl r,tm,dt
type: @kChType
xFormat: fmt
point:
show: false
axis:
x:
type: 'timeseries'
tick:
fit: true
format: xfmt
@chSrc = 'auto'
else if typeof r is 'object'
# pie
t = @attributes['k-chart-type']?.textContent || "pie"
d = ([n].concat v for n,v of r)
cfg =
data:
columns: d
type: t
@chSrc = 'dict'
if @kChType is 'merge-config'
console.log "kdb-chart: will merge cfgs" if @debug
cfg = mergeCfgs cfg, getConfig @kConfig
console.log "kdb-chart: cfg is" if @debug
console.log cfg if @debug
return @updateChartWithData cfg
updateChartWithData: (d) ->
d['bindto'] = @kCont
@chart = c3.generate d
updateFlowWithData: (d) -> @chart.flow d
convertTbl: (t,tm,dt) ->
cols = []
for n of t[0]
cols.push n if n is tm or n in dt
rows = [cols]
for rec in t
rows.push ((if n is tm then @convTime(rec[n]) else rec[n]) for n in cols)
rows
convertDyTbl: (t,tm,dt) ->
cols = [tm]
for n of t[0]
cols.push n if n in dt
rows = []
for rec in t
rows.push ((if n is tm then @convDyTime(rec[n]) else rec[n]) for n in cols)
[cols,rows]
convertAllTbl: (t) ->
t = [t] unless t.length
cols = []; fmts = []
for n,v of t[0]
cols.push n
fmts[n] = d3.time.format f if f = @detectTimeFmt v
rows = [cols]
for rec in t
rows.push ((if fmts[n] then (fmts[n].parse @convTime rec[n]) else rec[n]) for n in cols)
rows
convertDyAllTbl: (t) ->
t = [t] unless t.length
rows = []
cols = (n for n of t[0])
for rec in t
rows.push ((if i is 0 then @convDyTime(rec[n]) else rec[n]) for n,i in cols)
rows
detectData: (r) ->
return @kData if @kData
for n,v of r
return [n] if typeof v is 'number' or v instanceof Number
[]
detectTime: (r) ->
return @kTime if @kTime and r[@kTime]
t = null
for n,v of r
return n if v instanceof Date
return n if typeof v is 'string' and @detectTimeFmt v
t = n if !t and v instanceof Number
t
detectTimeFmt: (v) ->
return ((d) -> d) if v instanceof Date
return '%H:%M:%S.%L' if /^\d\d:\d\d:\d\d\.\d\d\d/.test v
return '%Y-%m-%dT%H:%M:%S.%L'if /^\d\d\d\d[-\.]\d\d[-\.]\d\d[DT]\d\d:\d\d:\d\d\.\d\d\d/.test v
return '%Y-%m-%d' if /^\d\d\d\d-\d\d-\d\d/.test v
return '%Y.%m.%d' if /^\d\d\d\d\.\d\d\.\d\d/.test v
return '%jT%H:%M:%S.%L' if /^\d+D\d\d:\d\d:\d\d\.\d\d\d/.test v
return '%H:%M:%S' if /^\d\d:\d\d:\d\d/.test v
return '%H:%M' if /^\d\d:\d\d/.test v
detectTimeXFmt: (r,tm,f) ->
return f if typeof f is 'string' and f.length<12
if typeof f is 'string'
fmt = d3.time.format f
f = (d) -> fmt.parse d
i = Math.abs (f @convTime r[r.length-1][tm])-(f @convTime r[0][tm])
return '%H:%M:%S.%L' if i < 86400000
'%Y.%m.%dT%H:%M'
convTime: (d) ->
return d unless typeof d is 'string' and d.length>=20
d = d.slice(0,-6) unless d[d.length-4] is "."
d = d.replace('.','-').replace('.','-') if d[4] is '.'
d.replace('D','T')
convDyTime: (d) ->
return d unless typeof d is 'string'
return Number d unless 0<=d.indexOf(':') or (d[4] is '.' and d[7] is '.') or d[4] is '-'
d = d.replace('.','-').replace('.','-') if d[4] is '.' # make date like 2010-10-10
d = d.replace('D','T') if 0<=d.indexOf "D" # change D to T
d = d.match(/^\d+T(.*)$/)[1] unless d[4] is '-' or d[2] is ':' # timespan - remove span completely
d = "2000-01-01T"+d if d[2] is ':'
new Date d
class _KDBEditor extends HTMLElement
createdCallback: ->
@query = @attributes['k-query']?.textContent
@debug = @attributes['debug']?.textContent || null
@kConfig = @attributes['k-config']?.textContent
kClass = "k-ace-editor "+(@attributes['k-class']?.textContent || "")
kStyle = @attributes['k-style']?.textContent || ""
@kEditor = null
@kCont = document.createElement 'pre'
@kCont.className = kClass
@kCont.style.cssText = kStyle
@kCont.textContent = this.textContent
@kMarkers = null
this.innerHTML = ''
this.appendChild @kCont
console.log "kdb-editor: query: #{@query}" if @debug
attachedCallback: ->
@kEditor = ace.edit @kCont
@query = srv if srv = document.querySelector "[k-id='#{@query}']"
@setCfg()
if @query?.runQuery
@query.onresult (ev) => @onResult ev
onResult: (ev) ->
console.log "kdb-editor: got event" if @debug
console.log ev.detail if @debug
@kdbUpd ev.detail
setCfg: ->
cfg =
theme: 'ace/theme/textmate'
mode: 'ace/mode/q'
readOnly: true
scrollPastEnd: false
fadeFoldWidgets: false
behavioursEnabled: true
useSoftTabs: true
animatedScroll: true
verticalScrollBar: false
horizontalScrollBar: false
highlightSelectedWord: true
showGutter: true
displayIndentGuides: false
showInvisibles: false
highlightActiveLine: true
selectionStyle: 'line' # line or text - how looks the selection decoration
wrap: 'off' # off 40 80 free (til end of box)
foldStyle: 'markbegin' # markbegin markbeginend manual
fontSize: 12
keybindings: 'ace' # ace emacs vim
showPrintMargin: true
useElasticTabstops: false
useIncrementalSearch: false
execLine: win: 'Ctrl-Return', mac: 'Command-Return'
execSelection: win: 'Ctrl-e', mac: 'Command-e'
cfg = mergeCfgs cfg, getConfig @kConfig if @kConfig
console.log "kdb-editor: config" if @debug
console.log cfg if @debug
@kCfg = cfg
@kEditor.setTheme cfg.theme
@kEditor.getSession().setMode cfg.mode
@kEditor.setReadOnly cfg.readOnly
@kEditor.setOption "scrollPastEnd", cfg.scrollPastEnd
@kEditor.setFadeFoldWidgets cfg.fadeFoldWidgets
@kEditor.setBehavioursEnabled cfg.behavioursEnabled
@kEditor.session.setUseSoftTabs cfg.useSoftTabs
@kEditor.setAnimatedScroll cfg.animatedScroll
@kEditor.setOption "vScrollBarAlwaysVisible", cfg.verticalScrollBar
@kEditor.setOption "hScrollBarAlwaysVisible", cfg.horizontalScrollBar
@kEditor.setHighlightSelectedWord cfg.highlightSelectedWord
@kEditor.renderer.setShowGutter cfg.showGutter
@kEditor.setDisplayIndentGuides cfg.displayIndentGuides
@kEditor.setShowInvisibles cfg.showInvisibles
@kEditor.setHighlightActiveLine cfg.highlightActiveLine
@kEditor.setOption "selectionStyle", cfg.selectionStyle
@kEditor.setOption "wrap", cfg.wrap
@kEditor.session.setFoldStyle cfg.foldStyle
@kEditor.setFontSize cfg.fontSize
@kEditor.setKeyboardHandler cfg.keybindings unless cfg.keybindings is 'ace'
@kEditor.renderer.setShowPrintMargin cfg.showPrintMargin
@kEditor.setOption "useElasticTabstops", cfg.useElasticTabstops if cfg.useElasticTabstops
@kEditor.setOption "useIncrementalSearch", cfg.useIncrementalSearch if cfg.useIncrementalSearch
@setCommands()
kdbUpd: (r) ->
if @debug
console.log "kdb-editor update"
console.log r
cfg = null
if typeof r is 'object' and !Array.isArray r
cfg = r
r = cfg.text
if typeof r is 'string' or Array.isArray r
a = @attributes['k-append']?.textContent || 'overwrite'
if a is 'overwrite'
@kEditor.setValue r, 0
if @kMarkers
@kEditor.getSession().removeMarker m for m in @kMarkers
@kMarkers = null
@kEditor.getSession().clearAnnotations()
@kEditor.getSession().clearBreakpoints()
else if a is 'top'
@kEditor.navigateFileStart()
@kEditor.insert r
else
@kEditor.navigateFileEnd()
@kEditor.navigateLineEnd()
@kEditor.insert r
@kEditor.navigateTo 0,0
if cfg
if cfg.row?
@kEditor.scrollToLine (cfg.row or 0), true, true, null
@kEditor.navigateTo (cfg.row or 0),(cfg.column or 0)
if cfg.markers?
(@kEditor.getSession().removeMarker m for m in @kMarkers) if @kMarkers
Range = ace.require('./range').Range
@kMarkers = (@kEditor.getSession().addMarker new Range(m.xy[0],m.xy[1],m.xy[2],m.xy[3]), m.class, m.type || "text", false for m in cfg.markers)
if cfg.annotations?
@kEditor.getSession().setAnnotations cfg.annotations
if cfg.breakpoints?
@kEditor.getSession().setBreakpoints cfg.breakpoints
setCommands: ->
@kEditor?.commands.addCommands [
(name: "execLine", bindKey: @kCfg.execLine, readOnly: true, exec: (e) => @execLine e)
name: "execSelection", bindKey: @kCfg.execSelection, readOnly: true, exec: (e) => @execSelection e
]
execLine: (e) ->
return unless l = @kEditor.getSession().getLine @kEditor.getCursorPosition().row
console.log "exec line: #{l}" if @debug
@sendEv l
execSelection: (e) ->
return unless s = @kEditor.getSelectedText()
console.log "exec select: #{s}" if @debug
@sendEv s
sendEv: (s) -> @dispatchEvent @getEv(s)
getEv: (s) ->
new CustomEvent "execText",
detail: s
bubbles: true
cancelable: true
onexec: (f) -> @addEventListener 'execText', f
window.KDB ?= {}
KDB.processJSONP = (id,res) ->
console.log "kdb-srv(JSONP): #{id}" + res if @debug
jsonpRegistry[id]?(res)
KDB.rerunQuery = (kID,args) -> document.querySelector("[k-id='#{kID}']")?.rerunQuery args
KDB.KDBChart = document.registerElement('kdb-chart', prototype: _KDBChart.prototype)
KDB.KDBSrv = document.registerElement('kdb-srv', prototype: _KDBSrv.prototype)
KDB.KDBQuery = document.registerElement('kdb-query', prototype: _KDBQuery.prototype)
KDB.KDBTable = document.registerElement('kdb-table', prototype: _KDBTable.prototype)
KDB.KDBEditor = document.registerElement('kdb-editor', prototype: _KDBEditor.prototype)
| 72238 | 'use strict'
# <kdb-connect srvUser="u" srvPass="<PASSWORD>" target="h" query="starting sequence"/>
(() ->
try
new CustomEvent 'test'
catch
CE = (event, params) ->
params = params || bubbles: false, cancelable: false, detail: undefined
evt = document.createEvent 'CustomEvent'
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
return evt
CE.prototype = window.CustomEvent.prototype
window.CustomEvent = CE
)()
extractInfo = (v) ->
return v if typeof v is 'string'
txt = ''
if v.nodeName is 'SELECT'
if v.multiple
r = []
for e in v.options
if e.selected
r.push e.text
txt = r.join '\n'
else
txt = v.options[v.selectedIndex].text if v.selectedIndex>=0
else if v.nodeName is 'INPUT'
if v.type is 'checkbox'
txt = if v.checked then '1b' else '0b'
else if v.type is 'radio'
txt = v.form.querySelector("input[type='radio'][name='#{v.name}']:checked")?.value || ''
else
txt = v?.value || ''
else if v.nodeName is 'TEXTAREA'
txt = v.value
else if v.nodeName is 'KDB-EDITOR'
txt = v.kEditor.getValue()
else
txt = v.textContent
txt
mergeCfgs = (c1,c2) ->
for n,v of c1
continue if (v2 = c2[n]) is undefined
if typeof v2 is 'object' and typeof v is 'object' and !v2.length and !v.length
c1[n] = mergeCfgs v, v2
else
c1[n] = v2
for n,v of c2
continue if c1[n]
c1[n] = v
c1
copyCfg = (c) ->
cc = {}
for n,v of c
if typeof v is 'object' and !v.length
cc[n] = copyCfg v
else
cc[n] = v
cc
getConfig = (c) ->
return copyCfg (c.split(".").reduce ((x,y) -> return x[y]), window) if /^[\w\.]+$/.test c
try
cfg = JSON.parse c
catch err
console.log "kdb-wc: config parse exception"
return console.log err
keval = (s) ->
# .split(".").reduce ((x,y) -> return x[y]), window
try
eval s
catch err
null
jsonpRegistry = {}
class _KDBSrv extends HTMLElement
createdCallback: ->
@srvType = @attributes['k-srv-type']?.textContent || "http"
@target = @attributes['k-target']?.textContent || null
@wsSrv = if @srvType in ['http','https'] then location.host else (@attributes['k-srv-uri']?.textContent || location.host)
@srvUser = @attributes['k-srv-user']?.textContent || null
@srvPass = @attributes['k-srv-pass']?.textContent || null
@qPrefix = @attributes['k-prefix']?.textContent || ""
@debug = @attributes['debug']?.textContent || null
@rType = @attributes['k-return-type']?.textContent || "json"
@fixJson = @attributes['fix-json']?.textContent || null
@kFeed = (@attributes['k-feed']?.textContent || "false") is "true"
@kDeser = (@attributes['k-deserialize']?.textContent || "false") is "true"
@hidden = true
@ws = @wsReq = null
@wsQueue = []
@rType = 'json' if @srvType is 'jsonp'
@srvProto = if /^http.?\:/.test @wsSrv then '' else if @srvType is 'https' then 'https://' else 'http://'
console.log "kdb-srv inited: srvType:#{@srvType}, target:#{@target}, prefix:#{@qPrefix}, rType:#{@rType}, proto:#{@srvProto}, srv: #{@wsSrv}" if @debug
if @target
@target = (document.querySelector "[k-id='#{@target}']") || @target
runQuery: (q,cb) ->
(cb = (r,e) -> null) unless cb
return @sendHTTP q,cb if @srvType in ['http','xhttp','jsonp','https']
return @sendWS q,cb if @srvType in ['ws','wss']
console.error 'kdb-srv: unknown srv type: '+@srvType
sendWS: (qq,clb) ->
@wsQueue.push q:qq, cb:clb
if !@ws
@ws = new WebSocket("#{@srvType}://#{@wsSrv}/")
@ws.binaryType = 'arraybuffer'
@ws.onopen = =>
console.log "kdb-srv-ws: opened" if @debug
@processWSQueue()
@ws.onclose = =>
console.log "kdb-srv-ws: closed" if @debug
@ws = null
@sendWSRes null,'closed'
@ws.onerror = (e) =>
console.log "kdb-srv-ws: error #{e.data}" if @debug
@sendWSRes null,e.data
@ws.onmessage = (e) =>
console.log "kdb-srv-ws: msg" if @debug
try
res = if @rType is "json" and typeof e.data is 'string' then JSON.parse e.data else if typeof e.data is 'object' then deserialize(e.data) else e.data
catch error
console.error "kdb-srv-ws: exception in ws parse #{error}"
return @sendWSRes null, "result parse error: "+error.toString()
@sendWSRes res, null
return
@processWSQueue() if @ws.readyState is 1
sendWSRes: (r,e) ->
return unless req=@wsReq
@wsReq = null unless @kFeed
try
req.cb r,e
catch err
console.error "kdb-srv-ws: exception in callback"
console.log err
@processWSQueue()
processWSQueue: ->
return if @wsReq or @wsQueue.length is 0
@wsReq = @wsQueue.shift()
req = @wsReq.q
req = @qPrefix + req if typeof req is 'string' and @qPrefix
req = "%target=#{trg}%" + req if @target and trg=extractInfo @target
if @rType is 'q'
try
req = ' '+req if typeof req is 'string' and req[0] is '`' # compensate the strange behavior of serialize
req = serialize req
catch error
console.error "kdb-srv-ws: exception in ws send #{error}"
return @sendWSRes null,'send'
return @ws.send req if @ws and @ws.readyState is 1
@sendWS @wsReq.q,@wsReq.cb
@wsReq = null
sendHTTP: (q,cb) ->
if @fixJson
@fixJson = null
@qPrefix = (if @srvType is 'jsonp' then 'jsp?' else "jsn?enlist ") unless @qPrefix
query = ".h.tx[`jsn]:(.j.j');"
query = '.h.tx[`jsp]:{enlist "KDB.processJSONP(\'",string[x 0],"\',",(.j.j x 1),")"};' if @srvType is 'jsonp'
query += 'if[105=type .h.hp;.h.hp:(f:{ssr[x y;"\nConnection: close";{"\nAccess-Control-Allow-Origin: *\r",x}]})[.h.hp];.h.he:f .h.he;.h.hy:{[a;b;c;d]a[b c;d]}[f;.h.hy]];' if @srvType is "xhttp"
return @runQuery "{#{query};1}[]", (r,e) => @runQuery q, cb
@qPrefix = (if @srvType is 'jsonp' then 'jsp?' else "json?enlist ") if !@qPrefix and @rType is "json"
if @srvType is 'jsonp'
q = @qPrefix + "(`#{rid = 'id'+Date.now()};#{encodeURIComponent q})"
else
q = @qPrefix + encodeURIComponent q
q = q + "&target=" + trg if @target and trg=extractInfo @target
q = @srvProto + @wsSrv + '/' + q
console.log "kdb-srv sending request:"+q if @debug
return @sendJSONP rid, q, cb if @srvType is 'jsonp'
xhr = new XMLHttpRequest()
xhr.onerror = =>
console.log "kdb-srv error: "+xhr.statusText + " - " + xhr.responseText if @debug
cb null, xhr.statusText+": "+xhr.responseText
xhr.ontimeout = =>
console.log "kdb-srv timeout" if @debug
cb null, "timeout"
xhr.onload = =>
return xhr.onerror() unless xhr.status is 200
console.log "kdb-srv data: "+xhr.responseText.slice(0,50) if @debug
try
try
res = if @rType is "json" then JSON.parse xhr.responseText else if @rType is "xml" then xhr.responseXML else xhr.responseText
res = deserialize res[1] if @kDeser and res instanceof Array and res[0] is 'deserialize'
catch error
console.error "kdb-srv: exception in JSON.parse"
return cb null, "JSON.parse error: "+error.toString()
cb res, null
catch err
console.error "kdb-srv: HTTP callback exception"
console.log err
xhr.open 'GET', q, true, @srvUser, @srvPass
xhr.send()
sendJSONP: (rid,q,cb) ->
resOk = false
jsonpRegistry[rid] = (res) =>
console.log "kdb-srv(jsonp) data: " + res.toString().slice(0,50) if @debug
delete jsonpRegistry[rid]
resOk = true
try
cb res, null
catch error
console.error "kdb-srv: HTTP callback exception"
console.log error
script = document.createElement('script')
script.onload = script.onerror = =>
return if resOk
delete jsonpRegistry[rid]
console.log "kdb-srv(jsonp): error" if @debug
try
cb null, "url: "+q
catch error
console.error "kdb-srv: HTTP callback exception"
console.log error
script.src = q
document.body.appendChild script
class _KDBQuery extends HTMLElement
createdCallback: ->
@hidden = true
@setupQuery()
setupQuery: ->
prvExec = @exec
clearTimeout @ktimer if @ktimer
@ktimer = null
@iterationNumber = 0
@kID = @attributes['k-id']?.textContent || "undefined"
@query = @attributes['k-query']?.textContent || @textContent
@srv = @attributes['k-srv']?.textContent || ""
@exec = @attributes['k-execute-on']?.textContent.split(' ').filter((e)-> e.length > 0) || ["load"]
@debug = @attributes['debug']?.textContent || null
@escapeQ = @attributes['k-escape-q']?.textContent || ""
@kDispUpd = (@attributes['k-dispatch-update']?.textContent || "false") is "true"
@updObjs = @attributes['k-update-elements']?.textContent.split(' ').filter((e)-> e.length > 0) || []
@updErr = @attributes['k-on-error']?.textContent.split(' ').filter((e)-> e.length > 0) || []
@kInterval = @attributes['k-interval']?.textContent || "0"
@kInterval = if Number.parseInt then Number.parseInt @kInterval else Number @kInterval
@kDelay = @attributes['k-delay']?.textContent || "0"
@kDelay = if Number.parseInt then Number.parseInt @kDelay else Number @kDelay
@kQStatus = @attributes['k-status-var']?.textContent || null
@kQNum = 0
if @kFilter = @attributes['k-filter']?.textContent
@kFilter = keval @kFilter
@result = null
if 'load' in @exec and (!prvExec or !('load' in prvExec))
if document.readyState in ['complete','interactive']
setTimeout (=> @runQuery { src:"self", txt:"load"}), 100
else
document.addEventListener "DOMContentLoaded", (ev) => @runQuery src:"self", txt:"load"
for el in @exec when !(el in ['load','manual','timer'])
@addUpdater(v,el) if v = document.querySelector "[k-id='#{el}']"
@kRefs = @query.match(/\$(\w|\.)(\w|\.|\]|\[|\-)*\$/g)?.map (e) -> e.slice 1,e.length-1
@kMap = null
if 'timer' in @exec
setTimeout (=> @rerunQuery src:"self", txt:"timer"), if @kDelay then @kDelay else @kInterval
console.log "kdb-query inited: srv:#{@srv}, query:#{@query}, executeOn:#{@exec}, updateObs:#{@updObjs}, refs:#{@kRefs}, delay:#{@kDelay}, interval:#{@kInterval}" if @debug
rerunQuery: (args = {}) ->
args['pres'] = @result
@result = null
@runQuery args
runQuery: (args = {}) ->
args["i"] = @iterationNumber
return if @result isnt null
if typeof @srv is 'string'
@srv = if @srv is "" then document.getElementsByTagName("kdb-srv")?[0] else document.querySelector "[k-id='#{@srv}']"
console.log "kdb-query: executing query" if @debug
@kQNum += 1
@updateStatus()
@srv.runQuery @resolveRefs(@query, args), (r,e) =>
@kQNum -= 1
console.log "kdb-query: got response with status #{e}" if @debug
if e
@updateStatus()
@updObjWithRes o,document.querySelector("[k-id='#{o}']"),e for o in @updErr
else
r = (if typeof @kFilter is 'object' then @kFilter.filter r else @kFilter r) if @kFilter
@result = r
@updateStatus()
@updateObjects()
@sendEv()
setTimeout (=> @rerunQuery src:"self", txt:"timer"), @kInterval if @kInterval and 'timer' in @exec
@iterationNumber += 1
sendEv: -> @dispatchEvent @getEv() if @result isnt null
getEv: ->
new CustomEvent "newResult",
detail: if @kDispUpd then @result[""] else @result
bubbles: true
cancelable: true
onresult: (f) ->
@addEventListener 'newResult', f
f @getEv() if @result isnt null
setQueryParams: (o,c2) ->
return c2 unless attrs = o.attributes['k-attr']?.textContent
c1 = {}
c1[n] = o.attributes[n].textContent || "" for n in attrs.split(' ').filter((e)-> e.length > 0)
mergeCfgs c1,c2
addUpdater: (v,kid) ->
if v.nodeName is 'BUTTON'
v.addEventListener 'click', (ev) => @rerunQuery @setQueryParams v, src:'button', id: kid
else if v.nodeName is 'KDB-EDITOR'
v.onexec (ev) => @rerunQuery @setQueryParams v, src:'editor', id: kid, txt: ev.detail
else if v.nodeName is 'KDB-QUERY'
v.onresult (ev) => @rerunQuery @setQueryParams v, src:'query', id: kid, txt: ev.detail
else if v.nodeName in ['SELECT','TEXTAREA','INPUT']
v.addEventListener 'change', (ev) => @rerunQuery @setQueryParams v, src:v.nodeName, id: kid, txt: extractInfo v
else
v.addEventListener 'click', (ev) => @rerunQuery @setQueryParams v, src:v.nodeName, id: kid, txt: if (typeof ev.kdetail isnt "undefined" and ev.kdetail isnt null) then ev.kdetail else ev.target?.textContent
kdbUpd: (r,kid) -> @rerunQuery src:'query', id: kid, txt: r
updateStatus: ->
if @kQStatus
a = new Function "x",@kQStatus+" = x"
try
a(@kQNum)
catch
null
return
updateObjects: ->
@updateObj o,true,document.querySelector "[k-id='#{o}']" for o in @updObjs
if @kDispUpd
if typeof @result isnt 'object'
console.error "kdb-query: dictionary is expected with dispatch setting"
return console.log @result
@updateObj n,false,document.querySelector "[k-id='#{n}']" for n of @result when n
updateObj: (n,isUpd,o) ->
r = if @kDispUpd then @result[if isUpd then "" else n] else @result
return if r is undefined
@updObjWithRes n,o,r
updObjWithRes: (n,o,r) ->
if !o
a = new Function "x",n+" = x"
try
a(r)
catch
null
return
if o.kdbUpd
try
o.kdbUpd r, @kID
catch err
console.log "kdb-query:exception in kdbUpd"
console.log err
else if o.nodeName in ['SELECT','DATALIST']
prv = if o.nodeName is 'SELECT' and o.selectedIndex>=0 then o.options[o.selectedIndex].text else null
idx = -1
o.innerHTML = ''
for e,i in r
opt = document.createElement 'option'
opt.value = e.toString()
opt.text = e.toString()
idx = i if prv is opt.text
o.appendChild opt
o.selectedIndex = idx if idx>=0 and o.attributes['k-preserve']?.textContent
else if o.nodeName in ['KDB-CHART','KDB-TABLE','KDB-EDITOR'] # not inited
setTimeout (=> o.kdbUpd r,@kID),0
else
a = o.attributes['k-append']?.textContent || 'overwrite'
ty = o.attributes['k-content-type']?.textContent || 'text'
s = if o.textContent then '\n' else ''
if ty is 'text'
if a is 'top' then o.textContent = r.toString()+s+o.textContent else if a is 'bottom' then o.textContent += s+r.toString() else o.textContent = r.toString()
else
return o.innerHTML = r.toString() if a is 'overwrite'
if a is 'top' then o.insertAdjacentHTML 'afterBegin', r.toString()+s else o.insertAdjacentHTML 'beforeEnd', s+r.toString()
resolveRefs: (q,args)->
console.log args if @debug
return q unless @kRefs
if !@kMap
@kMap = {}
@kMap[e] = null for e in @kRefs
@kMap[e] = document.querySelector "[k-id='#{e}']" for e of @kMap
for n,v of @kMap
if !v
val = args[n]
val = keval n if val is null or val is undefined
txt = if val is null or val is undefined then n else val.toString()
else
txt = extractInfo v
q = q.replace (new RegExp "\\$#{n.replace /(\[|\])/g,"."}\\$", "g"), @escape txt
console.log "kdb-query: after resolve - #{q}" if @debug
q
escape: (s) -> if @escapeQ then s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\240/g," ").replace(/\n/g,"\\n") else s
class _KDBTable extends HTMLElement
createdCallback: ->
@srv = @attributes['k-srv']?.textContent || ""
@query = @attributes['k-query']?.textContent || @textContent
@kLib = @attributes['k-lib']?.textContent || 'table'
@debug = @attributes['debug']?.textContent || null
@escHtml = (@attributes['k-escape-html']?.textContent || 'true') == 'true'
@kConfig = @attributes['k-config']?.textContent
@kClass = @attributes['k-class']?.textContent || "kdb-table"
@kStyle = @attributes['k-style']?.textContent || ""
@kSearch = (@attributes['k-search']?.textContent || 'false') == 'true'
@inited = false
@initContainer()
console.log "kdb-table: srv: #{@srv}, query: #{@query}, lib:#{@kLib}" if @debug
initContainer: ->
if @kLib in ['jsgrid','datatables']
this.innerHTML = "" if @kCont
@kCont = document.createElement if @kLib is 'jsgrid' then 'div' else 'table'
cont = document.createElement 'div'
cont.className = @kClass
cont.style.cssText = @kStyle
@kCont.style.cssText = "width: 100%;" if @kLib is 'datatables'
cont.appendChild @kCont
this.appendChild cont
attachedCallback: ->
if !@inited
console.log "kdb-table: initing" if @debug
@inited = true
return if @query is ""
if /\w+/.test @query
@query = srv if srv = document.querySelector "[k-id='#{@query}']"
if typeof @query is 'string'
console.log "kdb-table: creating a query" if @debug
q = new KDB.KDBQuery()
q.setAttribute 'k-query', @query
q.setAttribute 'k-srv', @srv if @srv
q.setAttribute 'debug', @debug if @debug
q.setupQuery()
@query = q
return unless @query?.runQuery
@query.onresult (ev) => @onResult ev
console.log "kdb-table: init complete" if @debug
if @kLib in ['jsgrid','datatables'] and @kConfig
cfg = getConfig @kConfig
return unless cfg?.pageLoading or cfg?.serverSide
console.log "kdb-table: pageLoading/serverSide is set, forcing the first page" if @debug
@query.rerunQuery start: 0, size: 1, sortBy:"", sortOrder:"", data: null
onResult: (ev) ->
console.log "kdb-table: got event" if @debug
@updateTbl ev.detail
kdbUpd: (r,kID) ->
@query = document.querySelector "[k-id='#{kID}']"
@updateTbl r
updateTbl: (r) ->
console.log "kdb-table: data" if @debug
console.log r if @debug
return @updateJSGrid r if @kLib is 'jsgrid' and @kCfg?.pageLoading
return @updateDT r if @kLib is 'datatables' and @kCfg?.serverSide
return if (r.length || 0) is 0
return @updateJSGrid r if @kLib is 'jsgrid'
return @updateDT r if @kLib is 'datatables'
tbl = "<table class='#{@kClass}' style='#{@kStyle}'><tr>"
tbl += "<th>#{@escapeHtml c}</th>" for c of r[0]
tbl += "</tr>"
for e in r
tbl += "<tr>"
tbl += "<td>#{@escapeHtml d}</td>" for c,d of e
tbl += "</tr>"
tbl += "</table>"
@innerHTML = tbl
updateJSGrid: (r) ->
if @kCfg?.pageLoading
return @kPromise.resolve r
@kData = r
f = []
for n,v of r[0]
if typeof v is 'string'
f.push name:n, type: "text"
else if typeof v is 'number'
f.push name:n, type: "number"
else if typeof v is 'boolean'
f.push name:n, type: "checkbox"
else if v instanceof Date
f.push name:n, type: "text", subtype: 'date', itemTemplate: (v) -> v.toISOString()
else
f.push name:n, type: "text"
cfg =
width: '100%'
height: '100%'
filtering: @kSearch
sorting: true
paging: r.length>100
pageButtonCount: 5
pageSize: 50
fields: f
controller: loadData: (a) => @loadData a
cfg = mergeCfgs cfg, getConfig @kConfig if @kConfig
if cfg.pageLoading
cfg.paging = true
cfg.autoload = true
else
cfg.data = r
@kCfg = cfg
console.log "kdb-table: cfg" if @debug
console.log cfg if @debug
$(@kCont).jsGrid cfg
updateDT: (r) ->
if @kCfg?.serverSide and @kCB and r.draw?
if r.draw is @kDraw
@kCB r
@kCB = null
return
@initContainer() if @kCfg # reinit the container
c = []
for n,v of r[0]
c.push data: n, title: n
cfg =
columns: c
searching: @kSearch
scrollX: true
processing: true
cfg = mergeCfgs cfg, getConfig @kConfig if @kConfig
@kCfg = cfg
cfg.paging = r.length>100 or (cfg.serverSide || false) unless cfg.paging?
if cfg.serverSide
cfg.ajax = (d,cb,set) =>
@kCB = cb
@kDraw = d.draw
@query.rerunQuery data: JSON.stringify d
else
cfg.data = r
if @debug
console.log "kdb-table: cfg"
console.log cfg
$(@kCont).DataTable cfg
loadData: (f) ->
if f.pageIndex
@query.rerunQuery start: (f.pageIndex-1)*f.pageSize, size: f.pageSize, sortBy: f.sortField or "", sortOrder: f.sortOrder or 'asc'
@kPromise = $.Deferred()
return @kPromise
return @kData.filter (e) =>
r = true
for v in @kCfg.fields
if v.type is "text" and v.subtype is 'date'
r = r and (!f[v.name] or -1<e[v.name].toISOString().indexOf f[v.name])
else if v.type is "text"
r = r and (!f[v.name] or -1<e[v.name].indexOf f[v.name])
else if v.type is "number"
r = r and (!f[v.name] or 1>Math.abs e[v.name] - f[v.name])
else
r = r and (f[v.name] is undefined or e[v.name] is f[v.name])
r
escapeHtml: (s) ->
s = if s is null then "" else s.toString()
if @escHtml then s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>') else s
class _KDBChart extends HTMLElement
createdCallback: ->
@srv = @attributes['k-srv']?.textContent || ""
@query = @attributes['k-query']?.textContent || @textContent
@debug = @attributes['debug']?.textContent || null
@kFlow = (@attributes['k-flow']?.textContent || "false") is "true"
@kConfig = @attributes['k-config']?.textContent
kClass = @attributes['k-class']?.textContent || ""
kStyle = @attributes['k-style']?.textContent || ""
@kChType = @attributes['k-chart-type']?.textContent || "line"
@kTime = @attributes['k-time-col']?.textContent
@kData = @attributes['k-data-cols']?.textContent.split(' ').filter (el) -> el.length>0
@inited = false
@chart = null
@chSrc = ''
@kDygraph = /^dygraph/.test @kChType
@kChType = @kChType.match(/^dygraph-(.*)$/)?[1] || 'line' if @kDygraph
@kCont = document.createElement 'div'
@kCont.className = kClass
@kCont.style.cssText = kStyle
this.innerHTML = ''
this.appendChild @kCont
console.log "kdb-chart: query:#{@query}, type:#{@kChType}, cfg:#{@kConfig}" if @debug
attachedCallback: ->
if !@inited
console.log "kdb-chart: initing" if @debug
@inited = true
return if @query is ""
if /\w+/.test @query
@query = srv if srv = document.querySelector "[k-id='#{@query}']"
if typeof @query is 'string'
console.log "kdb-chart: creating a query" if @debug
q = new KDB.KDBQuery()
q.setAttribute 'k-query', @query
q.setAttribute 'k-srv', @srv if @srv
q.setAttribute 'debug', @debug if @debug
q.setupQuery()
@query = q
return unless @query?.runQuery
@query.onresult (ev) => @onResult ev
console.log "kdb-chart: init complete" if @debug
attributeChangedCallback: (a,o,n) ->
if a is "k-init"
@createdCallback()
@attachedCallback()
onResult: (ev) ->
console.log "kdb-chart: got event" if @debug
console.log ev.detail if @debug
@updateChart ev.detail
kdbUpd: (r) ->
console.log "kdb-chart: got update" if @debug
console.log r if @debug
@updateChart r
updateDyChart: (r) ->
if @chart and @kFlow
console.log "Flow update" if @debug
data = r if @chSrc is 'dy'
data = @convertDyAllTbl r if @chSrc is 'user'
data = (@convertDyTbl r,@dtCfg.time,@dtCfg.data)[1] if @chSrc is 'auto'
console.log data if @debug
@dyData = (@dyData.concat data).slice data.length
return @chart.updateOptions file: @dyData
if @kChType is 'use-config'
return unless @kConfig and typeof r is 'object'
return if r.length is 0
console.log "kdb-chart: will use provided cfg" if @debug
cfg = getConfig @kConfig
data = @convertDyAllTbl r
@chSrc = 'user'
else
if typeof r is 'object' and r.length is 2 and (r[0] instanceof Array or typeof r[0] is 'string') # raw config
console.log 'kdb-chart: raw config' if @debug
data = r[0]
cfg = r[1]
@chSrc = 'dy'
else
console.log "Will detect the user format" if @debug
return unless tm = @detectTime r[0]
console.log "Time is #{tm}" if @debug
dt = @detectData r[0]
console.log "Data is #{dt}" if @debug
@dtCfg = data: dt, time: tm
return if dt.length is 0
r = @convertDyTbl r,tm,dt
data = r[1]
cfg = labels: r[0]
@chSrc = 'auto'
if @kChType is 'merge-config'
console.log "kdb-chart: will merge cfgs" if @debug
cfg = mergeCfgs cfg, getConfig @kConfig
if typeof data is 'string'
cfg = mergeCfgs cfg,
xValueParser: (d) => @convDyTime d
axes:
x:
valueFormatter: Dygraph.dateString_
ticker: Dygraph.dateTicker
console.log "kdb-chart: cfg is" if @debug
console.log cfg if @debug
console.log data if @debug
@dyData = data if @kFlow
return @updateDyChartWithData data,cfg
updateDyChartWithData: (d,c) -> @chart = new Dygraph @kCont,d,c
updateChart: (r) ->
return @updateDyChart r if @kDygraph
if @chart and @kFlow
if @chSrc is 'c3'
return @updateFlowWithData r
tbl = r
cfg = {}
if r['data']
cfg.to = r.to if r.to
cfg.length = r.length if r.length
cfg.duration = r.duration if r.duration
tbl = r.data
cfg.rows = @convertAllTbl tbl if @chSrc is 'user'
cfg.rows = @convertTbl tbl,@dtCfg.time,@dtCfg.data if @chSrc is 'auto'
cfg.columns = ([n].concat v for n,v of tbl) if @chSrc is 'dict'
return @updateFlowWithData cfg
if @kChType is 'use-config'
return unless @kConfig and typeof r is 'object'
return if r.length is 0
console.log "kdb-chart: will use provided cfg" if @debug
cfg = getConfig @kConfig
cfg.data.rows = @convertAllTbl r
@chSrc = 'user'
else if typeof r is 'object' and r.data
console.log "C3 format detected" if @debug
console.log r if @debug
@chSrc = 'c3'
cfg = r
else if typeof r is 'object' and r.length>0
# detect format
console.log "Will detect the user format" if @debug
return unless tm = @detectTime r[0]
fmt = @detectTimeFmt r[0][tm]
xfmt = @detectTimeXFmt r, tm, fmt
console.log "Time is #{tm}, fmt is #{fmt}, xfmt is #{xfmt}" if @debug
dt = @detectData r[0]
console.log "Data is #{dt}" if @debug
@dtCfg = data: dt, time: tm
return if dt.length is 0
cfg =
data:
x: tm
rows: @convertTbl r,tm,dt
type: @kChType
xFormat: fmt
point:
show: false
axis:
x:
type: 'timeseries'
tick:
fit: true
format: xfmt
@chSrc = 'auto'
else if typeof r is 'object'
# pie
t = @attributes['k-chart-type']?.textContent || "pie"
d = ([n].concat v for n,v of r)
cfg =
data:
columns: d
type: t
@chSrc = 'dict'
if @kChType is 'merge-config'
console.log "kdb-chart: will merge cfgs" if @debug
cfg = mergeCfgs cfg, getConfig @kConfig
console.log "kdb-chart: cfg is" if @debug
console.log cfg if @debug
return @updateChartWithData cfg
updateChartWithData: (d) ->
d['bindto'] = @kCont
@chart = c3.generate d
updateFlowWithData: (d) -> @chart.flow d
convertTbl: (t,tm,dt) ->
cols = []
for n of t[0]
cols.push n if n is tm or n in dt
rows = [cols]
for rec in t
rows.push ((if n is tm then @convTime(rec[n]) else rec[n]) for n in cols)
rows
convertDyTbl: (t,tm,dt) ->
cols = [tm]
for n of t[0]
cols.push n if n in dt
rows = []
for rec in t
rows.push ((if n is tm then @convDyTime(rec[n]) else rec[n]) for n in cols)
[cols,rows]
convertAllTbl: (t) ->
t = [t] unless t.length
cols = []; fmts = []
for n,v of t[0]
cols.push n
fmts[n] = d3.time.format f if f = @detectTimeFmt v
rows = [cols]
for rec in t
rows.push ((if fmts[n] then (fmts[n].parse @convTime rec[n]) else rec[n]) for n in cols)
rows
convertDyAllTbl: (t) ->
t = [t] unless t.length
rows = []
cols = (n for n of t[0])
for rec in t
rows.push ((if i is 0 then @convDyTime(rec[n]) else rec[n]) for n,i in cols)
rows
detectData: (r) ->
return @kData if @kData
for n,v of r
return [n] if typeof v is 'number' or v instanceof Number
[]
detectTime: (r) ->
return @kTime if @kTime and r[@kTime]
t = null
for n,v of r
return n if v instanceof Date
return n if typeof v is 'string' and @detectTimeFmt v
t = n if !t and v instanceof Number
t
detectTimeFmt: (v) ->
return ((d) -> d) if v instanceof Date
return '%H:%M:%S.%L' if /^\d\d:\d\d:\d\d\.\d\d\d/.test v
return '%Y-%m-%dT%H:%M:%S.%L'if /^\d\d\d\d[-\.]\d\d[-\.]\d\d[DT]\d\d:\d\d:\d\d\.\d\d\d/.test v
return '%Y-%m-%d' if /^\d\d\d\d-\d\d-\d\d/.test v
return '%Y.%m.%d' if /^\d\d\d\d\.\d\d\.\d\d/.test v
return '%jT%H:%M:%S.%L' if /^\d+D\d\d:\d\d:\d\d\.\d\d\d/.test v
return '%H:%M:%S' if /^\d\d:\d\d:\d\d/.test v
return '%H:%M' if /^\d\d:\d\d/.test v
detectTimeXFmt: (r,tm,f) ->
return f if typeof f is 'string' and f.length<12
if typeof f is 'string'
fmt = d3.time.format f
f = (d) -> fmt.parse d
i = Math.abs (f @convTime r[r.length-1][tm])-(f @convTime r[0][tm])
return '%H:%M:%S.%L' if i < 86400000
'%Y.%m.%dT%H:%M'
convTime: (d) ->
return d unless typeof d is 'string' and d.length>=20
d = d.slice(0,-6) unless d[d.length-4] is "."
d = d.replace('.','-').replace('.','-') if d[4] is '.'
d.replace('D','T')
convDyTime: (d) ->
return d unless typeof d is 'string'
return Number d unless 0<=d.indexOf(':') or (d[4] is '.' and d[7] is '.') or d[4] is '-'
d = d.replace('.','-').replace('.','-') if d[4] is '.' # make date like 2010-10-10
d = d.replace('D','T') if 0<=d.indexOf "D" # change D to T
d = d.match(/^\d+T(.*)$/)[1] unless d[4] is '-' or d[2] is ':' # timespan - remove span completely
d = "2000-01-01T"+d if d[2] is ':'
new Date d
class _KDBEditor extends HTMLElement
createdCallback: ->
@query = @attributes['k-query']?.textContent
@debug = @attributes['debug']?.textContent || null
@kConfig = @attributes['k-config']?.textContent
kClass = "k-ace-editor "+(@attributes['k-class']?.textContent || "")
kStyle = @attributes['k-style']?.textContent || ""
@kEditor = null
@kCont = document.createElement 'pre'
@kCont.className = kClass
@kCont.style.cssText = kStyle
@kCont.textContent = this.textContent
@kMarkers = null
this.innerHTML = ''
this.appendChild @kCont
console.log "kdb-editor: query: #{@query}" if @debug
attachedCallback: ->
@kEditor = ace.edit @kCont
@query = srv if srv = document.querySelector "[k-id='#{@query}']"
@setCfg()
if @query?.runQuery
@query.onresult (ev) => @onResult ev
onResult: (ev) ->
console.log "kdb-editor: got event" if @debug
console.log ev.detail if @debug
@kdbUpd ev.detail
setCfg: ->
cfg =
theme: 'ace/theme/textmate'
mode: 'ace/mode/q'
readOnly: true
scrollPastEnd: false
fadeFoldWidgets: false
behavioursEnabled: true
useSoftTabs: true
animatedScroll: true
verticalScrollBar: false
horizontalScrollBar: false
highlightSelectedWord: true
showGutter: true
displayIndentGuides: false
showInvisibles: false
highlightActiveLine: true
selectionStyle: 'line' # line or text - how looks the selection decoration
wrap: 'off' # off 40 80 free (til end of box)
foldStyle: 'markbegin' # markbegin markbeginend manual
fontSize: 12
keybindings: 'ace' # ace emacs vim
showPrintMargin: true
useElasticTabstops: false
useIncrementalSearch: false
execLine: win: 'Ctrl-Return', mac: 'Command-Return'
execSelection: win: 'Ctrl-e', mac: 'Command-e'
cfg = mergeCfgs cfg, getConfig @kConfig if @kConfig
console.log "kdb-editor: config" if @debug
console.log cfg if @debug
@kCfg = cfg
@kEditor.setTheme cfg.theme
@kEditor.getSession().setMode cfg.mode
@kEditor.setReadOnly cfg.readOnly
@kEditor.setOption "scrollPastEnd", cfg.scrollPastEnd
@kEditor.setFadeFoldWidgets cfg.fadeFoldWidgets
@kEditor.setBehavioursEnabled cfg.behavioursEnabled
@kEditor.session.setUseSoftTabs cfg.useSoftTabs
@kEditor.setAnimatedScroll cfg.animatedScroll
@kEditor.setOption "vScrollBarAlwaysVisible", cfg.verticalScrollBar
@kEditor.setOption "hScrollBarAlwaysVisible", cfg.horizontalScrollBar
@kEditor.setHighlightSelectedWord cfg.highlightSelectedWord
@kEditor.renderer.setShowGutter cfg.showGutter
@kEditor.setDisplayIndentGuides cfg.displayIndentGuides
@kEditor.setShowInvisibles cfg.showInvisibles
@kEditor.setHighlightActiveLine cfg.highlightActiveLine
@kEditor.setOption "selectionStyle", cfg.selectionStyle
@kEditor.setOption "wrap", cfg.wrap
@kEditor.session.setFoldStyle cfg.foldStyle
@kEditor.setFontSize cfg.fontSize
@kEditor.setKeyboardHandler cfg.keybindings unless cfg.keybindings is 'ace'
@kEditor.renderer.setShowPrintMargin cfg.showPrintMargin
@kEditor.setOption "useElasticTabstops", cfg.useElasticTabstops if cfg.useElasticTabstops
@kEditor.setOption "useIncrementalSearch", cfg.useIncrementalSearch if cfg.useIncrementalSearch
@setCommands()
kdbUpd: (r) ->
if @debug
console.log "kdb-editor update"
console.log r
cfg = null
if typeof r is 'object' and !Array.isArray r
cfg = r
r = cfg.text
if typeof r is 'string' or Array.isArray r
a = @attributes['k-append']?.textContent || 'overwrite'
if a is 'overwrite'
@kEditor.setValue r, 0
if @kMarkers
@kEditor.getSession().removeMarker m for m in @kMarkers
@kMarkers = null
@kEditor.getSession().clearAnnotations()
@kEditor.getSession().clearBreakpoints()
else if a is 'top'
@kEditor.navigateFileStart()
@kEditor.insert r
else
@kEditor.navigateFileEnd()
@kEditor.navigateLineEnd()
@kEditor.insert r
@kEditor.navigateTo 0,0
if cfg
if cfg.row?
@kEditor.scrollToLine (cfg.row or 0), true, true, null
@kEditor.navigateTo (cfg.row or 0),(cfg.column or 0)
if cfg.markers?
(@kEditor.getSession().removeMarker m for m in @kMarkers) if @kMarkers
Range = ace.require('./range').Range
@kMarkers = (@kEditor.getSession().addMarker new Range(m.xy[0],m.xy[1],m.xy[2],m.xy[3]), m.class, m.type || "text", false for m in cfg.markers)
if cfg.annotations?
@kEditor.getSession().setAnnotations cfg.annotations
if cfg.breakpoints?
@kEditor.getSession().setBreakpoints cfg.breakpoints
setCommands: ->
@kEditor?.commands.addCommands [
(name: "execLine", bindKey: @kCfg.execLine, readOnly: true, exec: (e) => @execLine e)
name: "execSelection", bindKey: @kCfg.execSelection, readOnly: true, exec: (e) => @execSelection e
]
execLine: (e) ->
return unless l = @kEditor.getSession().getLine @kEditor.getCursorPosition().row
console.log "exec line: #{l}" if @debug
@sendEv l
execSelection: (e) ->
return unless s = @kEditor.getSelectedText()
console.log "exec select: #{s}" if @debug
@sendEv s
sendEv: (s) -> @dispatchEvent @getEv(s)
getEv: (s) ->
new CustomEvent "execText",
detail: s
bubbles: true
cancelable: true
onexec: (f) -> @addEventListener 'execText', f
window.KDB ?= {}
KDB.processJSONP = (id,res) ->
console.log "kdb-srv(JSONP): #{id}" + res if @debug
jsonpRegistry[id]?(res)
KDB.rerunQuery = (kID,args) -> document.querySelector("[k-id='#{kID}']")?.rerunQuery args
KDB.KDBChart = document.registerElement('kdb-chart', prototype: _KDBChart.prototype)
KDB.KDBSrv = document.registerElement('kdb-srv', prototype: _KDBSrv.prototype)
KDB.KDBQuery = document.registerElement('kdb-query', prototype: _KDBQuery.prototype)
KDB.KDBTable = document.registerElement('kdb-table', prototype: _KDBTable.prototype)
KDB.KDBEditor = document.registerElement('kdb-editor', prototype: _KDBEditor.prototype)
| true | 'use strict'
# <kdb-connect srvUser="u" srvPass="PI:PASSWORD:<PASSWORD>END_PI" target="h" query="starting sequence"/>
(() ->
try
new CustomEvent 'test'
catch
CE = (event, params) ->
params = params || bubbles: false, cancelable: false, detail: undefined
evt = document.createEvent 'CustomEvent'
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
return evt
CE.prototype = window.CustomEvent.prototype
window.CustomEvent = CE
)()
extractInfo = (v) ->
return v if typeof v is 'string'
txt = ''
if v.nodeName is 'SELECT'
if v.multiple
r = []
for e in v.options
if e.selected
r.push e.text
txt = r.join '\n'
else
txt = v.options[v.selectedIndex].text if v.selectedIndex>=0
else if v.nodeName is 'INPUT'
if v.type is 'checkbox'
txt = if v.checked then '1b' else '0b'
else if v.type is 'radio'
txt = v.form.querySelector("input[type='radio'][name='#{v.name}']:checked")?.value || ''
else
txt = v?.value || ''
else if v.nodeName is 'TEXTAREA'
txt = v.value
else if v.nodeName is 'KDB-EDITOR'
txt = v.kEditor.getValue()
else
txt = v.textContent
txt
mergeCfgs = (c1,c2) ->
for n,v of c1
continue if (v2 = c2[n]) is undefined
if typeof v2 is 'object' and typeof v is 'object' and !v2.length and !v.length
c1[n] = mergeCfgs v, v2
else
c1[n] = v2
for n,v of c2
continue if c1[n]
c1[n] = v
c1
copyCfg = (c) ->
cc = {}
for n,v of c
if typeof v is 'object' and !v.length
cc[n] = copyCfg v
else
cc[n] = v
cc
getConfig = (c) ->
return copyCfg (c.split(".").reduce ((x,y) -> return x[y]), window) if /^[\w\.]+$/.test c
try
cfg = JSON.parse c
catch err
console.log "kdb-wc: config parse exception"
return console.log err
keval = (s) ->
# .split(".").reduce ((x,y) -> return x[y]), window
try
eval s
catch err
null
jsonpRegistry = {}
class _KDBSrv extends HTMLElement
createdCallback: ->
@srvType = @attributes['k-srv-type']?.textContent || "http"
@target = @attributes['k-target']?.textContent || null
@wsSrv = if @srvType in ['http','https'] then location.host else (@attributes['k-srv-uri']?.textContent || location.host)
@srvUser = @attributes['k-srv-user']?.textContent || null
@srvPass = @attributes['k-srv-pass']?.textContent || null
@qPrefix = @attributes['k-prefix']?.textContent || ""
@debug = @attributes['debug']?.textContent || null
@rType = @attributes['k-return-type']?.textContent || "json"
@fixJson = @attributes['fix-json']?.textContent || null
@kFeed = (@attributes['k-feed']?.textContent || "false") is "true"
@kDeser = (@attributes['k-deserialize']?.textContent || "false") is "true"
@hidden = true
@ws = @wsReq = null
@wsQueue = []
@rType = 'json' if @srvType is 'jsonp'
@srvProto = if /^http.?\:/.test @wsSrv then '' else if @srvType is 'https' then 'https://' else 'http://'
console.log "kdb-srv inited: srvType:#{@srvType}, target:#{@target}, prefix:#{@qPrefix}, rType:#{@rType}, proto:#{@srvProto}, srv: #{@wsSrv}" if @debug
if @target
@target = (document.querySelector "[k-id='#{@target}']") || @target
runQuery: (q,cb) ->
(cb = (r,e) -> null) unless cb
return @sendHTTP q,cb if @srvType in ['http','xhttp','jsonp','https']
return @sendWS q,cb if @srvType in ['ws','wss']
console.error 'kdb-srv: unknown srv type: '+@srvType
sendWS: (qq,clb) ->
@wsQueue.push q:qq, cb:clb
if !@ws
@ws = new WebSocket("#{@srvType}://#{@wsSrv}/")
@ws.binaryType = 'arraybuffer'
@ws.onopen = =>
console.log "kdb-srv-ws: opened" if @debug
@processWSQueue()
@ws.onclose = =>
console.log "kdb-srv-ws: closed" if @debug
@ws = null
@sendWSRes null,'closed'
@ws.onerror = (e) =>
console.log "kdb-srv-ws: error #{e.data}" if @debug
@sendWSRes null,e.data
@ws.onmessage = (e) =>
console.log "kdb-srv-ws: msg" if @debug
try
res = if @rType is "json" and typeof e.data is 'string' then JSON.parse e.data else if typeof e.data is 'object' then deserialize(e.data) else e.data
catch error
console.error "kdb-srv-ws: exception in ws parse #{error}"
return @sendWSRes null, "result parse error: "+error.toString()
@sendWSRes res, null
return
@processWSQueue() if @ws.readyState is 1
sendWSRes: (r,e) ->
return unless req=@wsReq
@wsReq = null unless @kFeed
try
req.cb r,e
catch err
console.error "kdb-srv-ws: exception in callback"
console.log err
@processWSQueue()
processWSQueue: ->
return if @wsReq or @wsQueue.length is 0
@wsReq = @wsQueue.shift()
req = @wsReq.q
req = @qPrefix + req if typeof req is 'string' and @qPrefix
req = "%target=#{trg}%" + req if @target and trg=extractInfo @target
if @rType is 'q'
try
req = ' '+req if typeof req is 'string' and req[0] is '`' # compensate the strange behavior of serialize
req = serialize req
catch error
console.error "kdb-srv-ws: exception in ws send #{error}"
return @sendWSRes null,'send'
return @ws.send req if @ws and @ws.readyState is 1
@sendWS @wsReq.q,@wsReq.cb
@wsReq = null
sendHTTP: (q,cb) ->
if @fixJson
@fixJson = null
@qPrefix = (if @srvType is 'jsonp' then 'jsp?' else "jsn?enlist ") unless @qPrefix
query = ".h.tx[`jsn]:(.j.j');"
query = '.h.tx[`jsp]:{enlist "KDB.processJSONP(\'",string[x 0],"\',",(.j.j x 1),")"};' if @srvType is 'jsonp'
query += 'if[105=type .h.hp;.h.hp:(f:{ssr[x y;"\nConnection: close";{"\nAccess-Control-Allow-Origin: *\r",x}]})[.h.hp];.h.he:f .h.he;.h.hy:{[a;b;c;d]a[b c;d]}[f;.h.hy]];' if @srvType is "xhttp"
return @runQuery "{#{query};1}[]", (r,e) => @runQuery q, cb
@qPrefix = (if @srvType is 'jsonp' then 'jsp?' else "json?enlist ") if !@qPrefix and @rType is "json"
if @srvType is 'jsonp'
q = @qPrefix + "(`#{rid = 'id'+Date.now()};#{encodeURIComponent q})"
else
q = @qPrefix + encodeURIComponent q
q = q + "&target=" + trg if @target and trg=extractInfo @target
q = @srvProto + @wsSrv + '/' + q
console.log "kdb-srv sending request:"+q if @debug
return @sendJSONP rid, q, cb if @srvType is 'jsonp'
xhr = new XMLHttpRequest()
xhr.onerror = =>
console.log "kdb-srv error: "+xhr.statusText + " - " + xhr.responseText if @debug
cb null, xhr.statusText+": "+xhr.responseText
xhr.ontimeout = =>
console.log "kdb-srv timeout" if @debug
cb null, "timeout"
xhr.onload = =>
return xhr.onerror() unless xhr.status is 200
console.log "kdb-srv data: "+xhr.responseText.slice(0,50) if @debug
try
try
res = if @rType is "json" then JSON.parse xhr.responseText else if @rType is "xml" then xhr.responseXML else xhr.responseText
res = deserialize res[1] if @kDeser and res instanceof Array and res[0] is 'deserialize'
catch error
console.error "kdb-srv: exception in JSON.parse"
return cb null, "JSON.parse error: "+error.toString()
cb res, null
catch err
console.error "kdb-srv: HTTP callback exception"
console.log err
xhr.open 'GET', q, true, @srvUser, @srvPass
xhr.send()
sendJSONP: (rid,q,cb) ->
resOk = false
jsonpRegistry[rid] = (res) =>
console.log "kdb-srv(jsonp) data: " + res.toString().slice(0,50) if @debug
delete jsonpRegistry[rid]
resOk = true
try
cb res, null
catch error
console.error "kdb-srv: HTTP callback exception"
console.log error
script = document.createElement('script')
script.onload = script.onerror = =>
return if resOk
delete jsonpRegistry[rid]
console.log "kdb-srv(jsonp): error" if @debug
try
cb null, "url: "+q
catch error
console.error "kdb-srv: HTTP callback exception"
console.log error
script.src = q
document.body.appendChild script
class _KDBQuery extends HTMLElement
createdCallback: ->
@hidden = true
@setupQuery()
setupQuery: ->
prvExec = @exec
clearTimeout @ktimer if @ktimer
@ktimer = null
@iterationNumber = 0
@kID = @attributes['k-id']?.textContent || "undefined"
@query = @attributes['k-query']?.textContent || @textContent
@srv = @attributes['k-srv']?.textContent || ""
@exec = @attributes['k-execute-on']?.textContent.split(' ').filter((e)-> e.length > 0) || ["load"]
@debug = @attributes['debug']?.textContent || null
@escapeQ = @attributes['k-escape-q']?.textContent || ""
@kDispUpd = (@attributes['k-dispatch-update']?.textContent || "false") is "true"
@updObjs = @attributes['k-update-elements']?.textContent.split(' ').filter((e)-> e.length > 0) || []
@updErr = @attributes['k-on-error']?.textContent.split(' ').filter((e)-> e.length > 0) || []
@kInterval = @attributes['k-interval']?.textContent || "0"
@kInterval = if Number.parseInt then Number.parseInt @kInterval else Number @kInterval
@kDelay = @attributes['k-delay']?.textContent || "0"
@kDelay = if Number.parseInt then Number.parseInt @kDelay else Number @kDelay
@kQStatus = @attributes['k-status-var']?.textContent || null
@kQNum = 0
if @kFilter = @attributes['k-filter']?.textContent
@kFilter = keval @kFilter
@result = null
if 'load' in @exec and (!prvExec or !('load' in prvExec))
if document.readyState in ['complete','interactive']
setTimeout (=> @runQuery { src:"self", txt:"load"}), 100
else
document.addEventListener "DOMContentLoaded", (ev) => @runQuery src:"self", txt:"load"
for el in @exec when !(el in ['load','manual','timer'])
@addUpdater(v,el) if v = document.querySelector "[k-id='#{el}']"
@kRefs = @query.match(/\$(\w|\.)(\w|\.|\]|\[|\-)*\$/g)?.map (e) -> e.slice 1,e.length-1
@kMap = null
if 'timer' in @exec
setTimeout (=> @rerunQuery src:"self", txt:"timer"), if @kDelay then @kDelay else @kInterval
console.log "kdb-query inited: srv:#{@srv}, query:#{@query}, executeOn:#{@exec}, updateObs:#{@updObjs}, refs:#{@kRefs}, delay:#{@kDelay}, interval:#{@kInterval}" if @debug
rerunQuery: (args = {}) ->
args['pres'] = @result
@result = null
@runQuery args
runQuery: (args = {}) ->
args["i"] = @iterationNumber
return if @result isnt null
if typeof @srv is 'string'
@srv = if @srv is "" then document.getElementsByTagName("kdb-srv")?[0] else document.querySelector "[k-id='#{@srv}']"
console.log "kdb-query: executing query" if @debug
@kQNum += 1
@updateStatus()
@srv.runQuery @resolveRefs(@query, args), (r,e) =>
@kQNum -= 1
console.log "kdb-query: got response with status #{e}" if @debug
if e
@updateStatus()
@updObjWithRes o,document.querySelector("[k-id='#{o}']"),e for o in @updErr
else
r = (if typeof @kFilter is 'object' then @kFilter.filter r else @kFilter r) if @kFilter
@result = r
@updateStatus()
@updateObjects()
@sendEv()
setTimeout (=> @rerunQuery src:"self", txt:"timer"), @kInterval if @kInterval and 'timer' in @exec
@iterationNumber += 1
sendEv: -> @dispatchEvent @getEv() if @result isnt null
getEv: ->
new CustomEvent "newResult",
detail: if @kDispUpd then @result[""] else @result
bubbles: true
cancelable: true
onresult: (f) ->
@addEventListener 'newResult', f
f @getEv() if @result isnt null
setQueryParams: (o,c2) ->
return c2 unless attrs = o.attributes['k-attr']?.textContent
c1 = {}
c1[n] = o.attributes[n].textContent || "" for n in attrs.split(' ').filter((e)-> e.length > 0)
mergeCfgs c1,c2
addUpdater: (v,kid) ->
if v.nodeName is 'BUTTON'
v.addEventListener 'click', (ev) => @rerunQuery @setQueryParams v, src:'button', id: kid
else if v.nodeName is 'KDB-EDITOR'
v.onexec (ev) => @rerunQuery @setQueryParams v, src:'editor', id: kid, txt: ev.detail
else if v.nodeName is 'KDB-QUERY'
v.onresult (ev) => @rerunQuery @setQueryParams v, src:'query', id: kid, txt: ev.detail
else if v.nodeName in ['SELECT','TEXTAREA','INPUT']
v.addEventListener 'change', (ev) => @rerunQuery @setQueryParams v, src:v.nodeName, id: kid, txt: extractInfo v
else
v.addEventListener 'click', (ev) => @rerunQuery @setQueryParams v, src:v.nodeName, id: kid, txt: if (typeof ev.kdetail isnt "undefined" and ev.kdetail isnt null) then ev.kdetail else ev.target?.textContent
kdbUpd: (r,kid) -> @rerunQuery src:'query', id: kid, txt: r
updateStatus: ->
if @kQStatus
a = new Function "x",@kQStatus+" = x"
try
a(@kQNum)
catch
null
return
updateObjects: ->
@updateObj o,true,document.querySelector "[k-id='#{o}']" for o in @updObjs
if @kDispUpd
if typeof @result isnt 'object'
console.error "kdb-query: dictionary is expected with dispatch setting"
return console.log @result
@updateObj n,false,document.querySelector "[k-id='#{n}']" for n of @result when n
updateObj: (n,isUpd,o) ->
r = if @kDispUpd then @result[if isUpd then "" else n] else @result
return if r is undefined
@updObjWithRes n,o,r
updObjWithRes: (n,o,r) ->
if !o
a = new Function "x",n+" = x"
try
a(r)
catch
null
return
if o.kdbUpd
try
o.kdbUpd r, @kID
catch err
console.log "kdb-query:exception in kdbUpd"
console.log err
else if o.nodeName in ['SELECT','DATALIST']
prv = if o.nodeName is 'SELECT' and o.selectedIndex>=0 then o.options[o.selectedIndex].text else null
idx = -1
o.innerHTML = ''
for e,i in r
opt = document.createElement 'option'
opt.value = e.toString()
opt.text = e.toString()
idx = i if prv is opt.text
o.appendChild opt
o.selectedIndex = idx if idx>=0 and o.attributes['k-preserve']?.textContent
else if o.nodeName in ['KDB-CHART','KDB-TABLE','KDB-EDITOR'] # not inited
setTimeout (=> o.kdbUpd r,@kID),0
else
a = o.attributes['k-append']?.textContent || 'overwrite'
ty = o.attributes['k-content-type']?.textContent || 'text'
s = if o.textContent then '\n' else ''
if ty is 'text'
if a is 'top' then o.textContent = r.toString()+s+o.textContent else if a is 'bottom' then o.textContent += s+r.toString() else o.textContent = r.toString()
else
return o.innerHTML = r.toString() if a is 'overwrite'
if a is 'top' then o.insertAdjacentHTML 'afterBegin', r.toString()+s else o.insertAdjacentHTML 'beforeEnd', s+r.toString()
resolveRefs: (q,args)->
console.log args if @debug
return q unless @kRefs
if !@kMap
@kMap = {}
@kMap[e] = null for e in @kRefs
@kMap[e] = document.querySelector "[k-id='#{e}']" for e of @kMap
for n,v of @kMap
if !v
val = args[n]
val = keval n if val is null or val is undefined
txt = if val is null or val is undefined then n else val.toString()
else
txt = extractInfo v
q = q.replace (new RegExp "\\$#{n.replace /(\[|\])/g,"."}\\$", "g"), @escape txt
console.log "kdb-query: after resolve - #{q}" if @debug
q
escape: (s) -> if @escapeQ then s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\240/g," ").replace(/\n/g,"\\n") else s
class _KDBTable extends HTMLElement
createdCallback: ->
@srv = @attributes['k-srv']?.textContent || ""
@query = @attributes['k-query']?.textContent || @textContent
@kLib = @attributes['k-lib']?.textContent || 'table'
@debug = @attributes['debug']?.textContent || null
@escHtml = (@attributes['k-escape-html']?.textContent || 'true') == 'true'
@kConfig = @attributes['k-config']?.textContent
@kClass = @attributes['k-class']?.textContent || "kdb-table"
@kStyle = @attributes['k-style']?.textContent || ""
@kSearch = (@attributes['k-search']?.textContent || 'false') == 'true'
@inited = false
@initContainer()
console.log "kdb-table: srv: #{@srv}, query: #{@query}, lib:#{@kLib}" if @debug
initContainer: ->
if @kLib in ['jsgrid','datatables']
this.innerHTML = "" if @kCont
@kCont = document.createElement if @kLib is 'jsgrid' then 'div' else 'table'
cont = document.createElement 'div'
cont.className = @kClass
cont.style.cssText = @kStyle
@kCont.style.cssText = "width: 100%;" if @kLib is 'datatables'
cont.appendChild @kCont
this.appendChild cont
attachedCallback: ->
if !@inited
console.log "kdb-table: initing" if @debug
@inited = true
return if @query is ""
if /\w+/.test @query
@query = srv if srv = document.querySelector "[k-id='#{@query}']"
if typeof @query is 'string'
console.log "kdb-table: creating a query" if @debug
q = new KDB.KDBQuery()
q.setAttribute 'k-query', @query
q.setAttribute 'k-srv', @srv if @srv
q.setAttribute 'debug', @debug if @debug
q.setupQuery()
@query = q
return unless @query?.runQuery
@query.onresult (ev) => @onResult ev
console.log "kdb-table: init complete" if @debug
if @kLib in ['jsgrid','datatables'] and @kConfig
cfg = getConfig @kConfig
return unless cfg?.pageLoading or cfg?.serverSide
console.log "kdb-table: pageLoading/serverSide is set, forcing the first page" if @debug
@query.rerunQuery start: 0, size: 1, sortBy:"", sortOrder:"", data: null
onResult: (ev) ->
console.log "kdb-table: got event" if @debug
@updateTbl ev.detail
kdbUpd: (r,kID) ->
@query = document.querySelector "[k-id='#{kID}']"
@updateTbl r
updateTbl: (r) ->
console.log "kdb-table: data" if @debug
console.log r if @debug
return @updateJSGrid r if @kLib is 'jsgrid' and @kCfg?.pageLoading
return @updateDT r if @kLib is 'datatables' and @kCfg?.serverSide
return if (r.length || 0) is 0
return @updateJSGrid r if @kLib is 'jsgrid'
return @updateDT r if @kLib is 'datatables'
tbl = "<table class='#{@kClass}' style='#{@kStyle}'><tr>"
tbl += "<th>#{@escapeHtml c}</th>" for c of r[0]
tbl += "</tr>"
for e in r
tbl += "<tr>"
tbl += "<td>#{@escapeHtml d}</td>" for c,d of e
tbl += "</tr>"
tbl += "</table>"
@innerHTML = tbl
updateJSGrid: (r) ->
if @kCfg?.pageLoading
return @kPromise.resolve r
@kData = r
f = []
for n,v of r[0]
if typeof v is 'string'
f.push name:n, type: "text"
else if typeof v is 'number'
f.push name:n, type: "number"
else if typeof v is 'boolean'
f.push name:n, type: "checkbox"
else if v instanceof Date
f.push name:n, type: "text", subtype: 'date', itemTemplate: (v) -> v.toISOString()
else
f.push name:n, type: "text"
cfg =
width: '100%'
height: '100%'
filtering: @kSearch
sorting: true
paging: r.length>100
pageButtonCount: 5
pageSize: 50
fields: f
controller: loadData: (a) => @loadData a
cfg = mergeCfgs cfg, getConfig @kConfig if @kConfig
if cfg.pageLoading
cfg.paging = true
cfg.autoload = true
else
cfg.data = r
@kCfg = cfg
console.log "kdb-table: cfg" if @debug
console.log cfg if @debug
$(@kCont).jsGrid cfg
updateDT: (r) ->
if @kCfg?.serverSide and @kCB and r.draw?
if r.draw is @kDraw
@kCB r
@kCB = null
return
@initContainer() if @kCfg # reinit the container
c = []
for n,v of r[0]
c.push data: n, title: n
cfg =
columns: c
searching: @kSearch
scrollX: true
processing: true
cfg = mergeCfgs cfg, getConfig @kConfig if @kConfig
@kCfg = cfg
cfg.paging = r.length>100 or (cfg.serverSide || false) unless cfg.paging?
if cfg.serverSide
cfg.ajax = (d,cb,set) =>
@kCB = cb
@kDraw = d.draw
@query.rerunQuery data: JSON.stringify d
else
cfg.data = r
if @debug
console.log "kdb-table: cfg"
console.log cfg
$(@kCont).DataTable cfg
loadData: (f) ->
if f.pageIndex
@query.rerunQuery start: (f.pageIndex-1)*f.pageSize, size: f.pageSize, sortBy: f.sortField or "", sortOrder: f.sortOrder or 'asc'
@kPromise = $.Deferred()
return @kPromise
return @kData.filter (e) =>
r = true
for v in @kCfg.fields
if v.type is "text" and v.subtype is 'date'
r = r and (!f[v.name] or -1<e[v.name].toISOString().indexOf f[v.name])
else if v.type is "text"
r = r and (!f[v.name] or -1<e[v.name].indexOf f[v.name])
else if v.type is "number"
r = r and (!f[v.name] or 1>Math.abs e[v.name] - f[v.name])
else
r = r and (f[v.name] is undefined or e[v.name] is f[v.name])
r
escapeHtml: (s) ->
s = if s is null then "" else s.toString()
if @escHtml then s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>') else s
class _KDBChart extends HTMLElement
createdCallback: ->
@srv = @attributes['k-srv']?.textContent || ""
@query = @attributes['k-query']?.textContent || @textContent
@debug = @attributes['debug']?.textContent || null
@kFlow = (@attributes['k-flow']?.textContent || "false") is "true"
@kConfig = @attributes['k-config']?.textContent
kClass = @attributes['k-class']?.textContent || ""
kStyle = @attributes['k-style']?.textContent || ""
@kChType = @attributes['k-chart-type']?.textContent || "line"
@kTime = @attributes['k-time-col']?.textContent
@kData = @attributes['k-data-cols']?.textContent.split(' ').filter (el) -> el.length>0
@inited = false
@chart = null
@chSrc = ''
@kDygraph = /^dygraph/.test @kChType
@kChType = @kChType.match(/^dygraph-(.*)$/)?[1] || 'line' if @kDygraph
@kCont = document.createElement 'div'
@kCont.className = kClass
@kCont.style.cssText = kStyle
this.innerHTML = ''
this.appendChild @kCont
console.log "kdb-chart: query:#{@query}, type:#{@kChType}, cfg:#{@kConfig}" if @debug
attachedCallback: ->
if !@inited
console.log "kdb-chart: initing" if @debug
@inited = true
return if @query is ""
if /\w+/.test @query
@query = srv if srv = document.querySelector "[k-id='#{@query}']"
if typeof @query is 'string'
console.log "kdb-chart: creating a query" if @debug
q = new KDB.KDBQuery()
q.setAttribute 'k-query', @query
q.setAttribute 'k-srv', @srv if @srv
q.setAttribute 'debug', @debug if @debug
q.setupQuery()
@query = q
return unless @query?.runQuery
@query.onresult (ev) => @onResult ev
console.log "kdb-chart: init complete" if @debug
attributeChangedCallback: (a,o,n) ->
if a is "k-init"
@createdCallback()
@attachedCallback()
onResult: (ev) ->
console.log "kdb-chart: got event" if @debug
console.log ev.detail if @debug
@updateChart ev.detail
kdbUpd: (r) ->
console.log "kdb-chart: got update" if @debug
console.log r if @debug
@updateChart r
updateDyChart: (r) ->
if @chart and @kFlow
console.log "Flow update" if @debug
data = r if @chSrc is 'dy'
data = @convertDyAllTbl r if @chSrc is 'user'
data = (@convertDyTbl r,@dtCfg.time,@dtCfg.data)[1] if @chSrc is 'auto'
console.log data if @debug
@dyData = (@dyData.concat data).slice data.length
return @chart.updateOptions file: @dyData
if @kChType is 'use-config'
return unless @kConfig and typeof r is 'object'
return if r.length is 0
console.log "kdb-chart: will use provided cfg" if @debug
cfg = getConfig @kConfig
data = @convertDyAllTbl r
@chSrc = 'user'
else
if typeof r is 'object' and r.length is 2 and (r[0] instanceof Array or typeof r[0] is 'string') # raw config
console.log 'kdb-chart: raw config' if @debug
data = r[0]
cfg = r[1]
@chSrc = 'dy'
else
console.log "Will detect the user format" if @debug
return unless tm = @detectTime r[0]
console.log "Time is #{tm}" if @debug
dt = @detectData r[0]
console.log "Data is #{dt}" if @debug
@dtCfg = data: dt, time: tm
return if dt.length is 0
r = @convertDyTbl r,tm,dt
data = r[1]
cfg = labels: r[0]
@chSrc = 'auto'
if @kChType is 'merge-config'
console.log "kdb-chart: will merge cfgs" if @debug
cfg = mergeCfgs cfg, getConfig @kConfig
if typeof data is 'string'
cfg = mergeCfgs cfg,
xValueParser: (d) => @convDyTime d
axes:
x:
valueFormatter: Dygraph.dateString_
ticker: Dygraph.dateTicker
console.log "kdb-chart: cfg is" if @debug
console.log cfg if @debug
console.log data if @debug
@dyData = data if @kFlow
return @updateDyChartWithData data,cfg
updateDyChartWithData: (d,c) -> @chart = new Dygraph @kCont,d,c
updateChart: (r) ->
return @updateDyChart r if @kDygraph
if @chart and @kFlow
if @chSrc is 'c3'
return @updateFlowWithData r
tbl = r
cfg = {}
if r['data']
cfg.to = r.to if r.to
cfg.length = r.length if r.length
cfg.duration = r.duration if r.duration
tbl = r.data
cfg.rows = @convertAllTbl tbl if @chSrc is 'user'
cfg.rows = @convertTbl tbl,@dtCfg.time,@dtCfg.data if @chSrc is 'auto'
cfg.columns = ([n].concat v for n,v of tbl) if @chSrc is 'dict'
return @updateFlowWithData cfg
if @kChType is 'use-config'
return unless @kConfig and typeof r is 'object'
return if r.length is 0
console.log "kdb-chart: will use provided cfg" if @debug
cfg = getConfig @kConfig
cfg.data.rows = @convertAllTbl r
@chSrc = 'user'
else if typeof r is 'object' and r.data
console.log "C3 format detected" if @debug
console.log r if @debug
@chSrc = 'c3'
cfg = r
else if typeof r is 'object' and r.length>0
# detect format
console.log "Will detect the user format" if @debug
return unless tm = @detectTime r[0]
fmt = @detectTimeFmt r[0][tm]
xfmt = @detectTimeXFmt r, tm, fmt
console.log "Time is #{tm}, fmt is #{fmt}, xfmt is #{xfmt}" if @debug
dt = @detectData r[0]
console.log "Data is #{dt}" if @debug
@dtCfg = data: dt, time: tm
return if dt.length is 0
cfg =
data:
x: tm
rows: @convertTbl r,tm,dt
type: @kChType
xFormat: fmt
point:
show: false
axis:
x:
type: 'timeseries'
tick:
fit: true
format: xfmt
@chSrc = 'auto'
else if typeof r is 'object'
# pie
t = @attributes['k-chart-type']?.textContent || "pie"
d = ([n].concat v for n,v of r)
cfg =
data:
columns: d
type: t
@chSrc = 'dict'
if @kChType is 'merge-config'
console.log "kdb-chart: will merge cfgs" if @debug
cfg = mergeCfgs cfg, getConfig @kConfig
console.log "kdb-chart: cfg is" if @debug
console.log cfg if @debug
return @updateChartWithData cfg
updateChartWithData: (d) ->
d['bindto'] = @kCont
@chart = c3.generate d
updateFlowWithData: (d) -> @chart.flow d
convertTbl: (t,tm,dt) ->
cols = []
for n of t[0]
cols.push n if n is tm or n in dt
rows = [cols]
for rec in t
rows.push ((if n is tm then @convTime(rec[n]) else rec[n]) for n in cols)
rows
convertDyTbl: (t,tm,dt) ->
cols = [tm]
for n of t[0]
cols.push n if n in dt
rows = []
for rec in t
rows.push ((if n is tm then @convDyTime(rec[n]) else rec[n]) for n in cols)
[cols,rows]
convertAllTbl: (t) ->
t = [t] unless t.length
cols = []; fmts = []
for n,v of t[0]
cols.push n
fmts[n] = d3.time.format f if f = @detectTimeFmt v
rows = [cols]
for rec in t
rows.push ((if fmts[n] then (fmts[n].parse @convTime rec[n]) else rec[n]) for n in cols)
rows
convertDyAllTbl: (t) ->
t = [t] unless t.length
rows = []
cols = (n for n of t[0])
for rec in t
rows.push ((if i is 0 then @convDyTime(rec[n]) else rec[n]) for n,i in cols)
rows
detectData: (r) ->
return @kData if @kData
for n,v of r
return [n] if typeof v is 'number' or v instanceof Number
[]
detectTime: (r) ->
return @kTime if @kTime and r[@kTime]
t = null
for n,v of r
return n if v instanceof Date
return n if typeof v is 'string' and @detectTimeFmt v
t = n if !t and v instanceof Number
t
detectTimeFmt: (v) ->
return ((d) -> d) if v instanceof Date
return '%H:%M:%S.%L' if /^\d\d:\d\d:\d\d\.\d\d\d/.test v
return '%Y-%m-%dT%H:%M:%S.%L'if /^\d\d\d\d[-\.]\d\d[-\.]\d\d[DT]\d\d:\d\d:\d\d\.\d\d\d/.test v
return '%Y-%m-%d' if /^\d\d\d\d-\d\d-\d\d/.test v
return '%Y.%m.%d' if /^\d\d\d\d\.\d\d\.\d\d/.test v
return '%jT%H:%M:%S.%L' if /^\d+D\d\d:\d\d:\d\d\.\d\d\d/.test v
return '%H:%M:%S' if /^\d\d:\d\d:\d\d/.test v
return '%H:%M' if /^\d\d:\d\d/.test v
detectTimeXFmt: (r,tm,f) ->
return f if typeof f is 'string' and f.length<12
if typeof f is 'string'
fmt = d3.time.format f
f = (d) -> fmt.parse d
i = Math.abs (f @convTime r[r.length-1][tm])-(f @convTime r[0][tm])
return '%H:%M:%S.%L' if i < 86400000
'%Y.%m.%dT%H:%M'
convTime: (d) ->
return d unless typeof d is 'string' and d.length>=20
d = d.slice(0,-6) unless d[d.length-4] is "."
d = d.replace('.','-').replace('.','-') if d[4] is '.'
d.replace('D','T')
convDyTime: (d) ->
return d unless typeof d is 'string'
return Number d unless 0<=d.indexOf(':') or (d[4] is '.' and d[7] is '.') or d[4] is '-'
d = d.replace('.','-').replace('.','-') if d[4] is '.' # make date like 2010-10-10
d = d.replace('D','T') if 0<=d.indexOf "D" # change D to T
d = d.match(/^\d+T(.*)$/)[1] unless d[4] is '-' or d[2] is ':' # timespan - remove span completely
d = "2000-01-01T"+d if d[2] is ':'
new Date d
class _KDBEditor extends HTMLElement
createdCallback: ->
@query = @attributes['k-query']?.textContent
@debug = @attributes['debug']?.textContent || null
@kConfig = @attributes['k-config']?.textContent
kClass = "k-ace-editor "+(@attributes['k-class']?.textContent || "")
kStyle = @attributes['k-style']?.textContent || ""
@kEditor = null
@kCont = document.createElement 'pre'
@kCont.className = kClass
@kCont.style.cssText = kStyle
@kCont.textContent = this.textContent
@kMarkers = null
this.innerHTML = ''
this.appendChild @kCont
console.log "kdb-editor: query: #{@query}" if @debug
attachedCallback: ->
@kEditor = ace.edit @kCont
@query = srv if srv = document.querySelector "[k-id='#{@query}']"
@setCfg()
if @query?.runQuery
@query.onresult (ev) => @onResult ev
onResult: (ev) ->
console.log "kdb-editor: got event" if @debug
console.log ev.detail if @debug
@kdbUpd ev.detail
setCfg: ->
cfg =
theme: 'ace/theme/textmate'
mode: 'ace/mode/q'
readOnly: true
scrollPastEnd: false
fadeFoldWidgets: false
behavioursEnabled: true
useSoftTabs: true
animatedScroll: true
verticalScrollBar: false
horizontalScrollBar: false
highlightSelectedWord: true
showGutter: true
displayIndentGuides: false
showInvisibles: false
highlightActiveLine: true
selectionStyle: 'line' # line or text - how looks the selection decoration
wrap: 'off' # off 40 80 free (til end of box)
foldStyle: 'markbegin' # markbegin markbeginend manual
fontSize: 12
keybindings: 'ace' # ace emacs vim
showPrintMargin: true
useElasticTabstops: false
useIncrementalSearch: false
execLine: win: 'Ctrl-Return', mac: 'Command-Return'
execSelection: win: 'Ctrl-e', mac: 'Command-e'
cfg = mergeCfgs cfg, getConfig @kConfig if @kConfig
console.log "kdb-editor: config" if @debug
console.log cfg if @debug
@kCfg = cfg
@kEditor.setTheme cfg.theme
@kEditor.getSession().setMode cfg.mode
@kEditor.setReadOnly cfg.readOnly
@kEditor.setOption "scrollPastEnd", cfg.scrollPastEnd
@kEditor.setFadeFoldWidgets cfg.fadeFoldWidgets
@kEditor.setBehavioursEnabled cfg.behavioursEnabled
@kEditor.session.setUseSoftTabs cfg.useSoftTabs
@kEditor.setAnimatedScroll cfg.animatedScroll
@kEditor.setOption "vScrollBarAlwaysVisible", cfg.verticalScrollBar
@kEditor.setOption "hScrollBarAlwaysVisible", cfg.horizontalScrollBar
@kEditor.setHighlightSelectedWord cfg.highlightSelectedWord
@kEditor.renderer.setShowGutter cfg.showGutter
@kEditor.setDisplayIndentGuides cfg.displayIndentGuides
@kEditor.setShowInvisibles cfg.showInvisibles
@kEditor.setHighlightActiveLine cfg.highlightActiveLine
@kEditor.setOption "selectionStyle", cfg.selectionStyle
@kEditor.setOption "wrap", cfg.wrap
@kEditor.session.setFoldStyle cfg.foldStyle
@kEditor.setFontSize cfg.fontSize
@kEditor.setKeyboardHandler cfg.keybindings unless cfg.keybindings is 'ace'
@kEditor.renderer.setShowPrintMargin cfg.showPrintMargin
@kEditor.setOption "useElasticTabstops", cfg.useElasticTabstops if cfg.useElasticTabstops
@kEditor.setOption "useIncrementalSearch", cfg.useIncrementalSearch if cfg.useIncrementalSearch
@setCommands()
kdbUpd: (r) ->
if @debug
console.log "kdb-editor update"
console.log r
cfg = null
if typeof r is 'object' and !Array.isArray r
cfg = r
r = cfg.text
if typeof r is 'string' or Array.isArray r
a = @attributes['k-append']?.textContent || 'overwrite'
if a is 'overwrite'
@kEditor.setValue r, 0
if @kMarkers
@kEditor.getSession().removeMarker m for m in @kMarkers
@kMarkers = null
@kEditor.getSession().clearAnnotations()
@kEditor.getSession().clearBreakpoints()
else if a is 'top'
@kEditor.navigateFileStart()
@kEditor.insert r
else
@kEditor.navigateFileEnd()
@kEditor.navigateLineEnd()
@kEditor.insert r
@kEditor.navigateTo 0,0
if cfg
if cfg.row?
@kEditor.scrollToLine (cfg.row or 0), true, true, null
@kEditor.navigateTo (cfg.row or 0),(cfg.column or 0)
if cfg.markers?
(@kEditor.getSession().removeMarker m for m in @kMarkers) if @kMarkers
Range = ace.require('./range').Range
@kMarkers = (@kEditor.getSession().addMarker new Range(m.xy[0],m.xy[1],m.xy[2],m.xy[3]), m.class, m.type || "text", false for m in cfg.markers)
if cfg.annotations?
@kEditor.getSession().setAnnotations cfg.annotations
if cfg.breakpoints?
@kEditor.getSession().setBreakpoints cfg.breakpoints
setCommands: ->
@kEditor?.commands.addCommands [
(name: "execLine", bindKey: @kCfg.execLine, readOnly: true, exec: (e) => @execLine e)
name: "execSelection", bindKey: @kCfg.execSelection, readOnly: true, exec: (e) => @execSelection e
]
execLine: (e) ->
return unless l = @kEditor.getSession().getLine @kEditor.getCursorPosition().row
console.log "exec line: #{l}" if @debug
@sendEv l
execSelection: (e) ->
return unless s = @kEditor.getSelectedText()
console.log "exec select: #{s}" if @debug
@sendEv s
sendEv: (s) -> @dispatchEvent @getEv(s)
getEv: (s) ->
new CustomEvent "execText",
detail: s
bubbles: true
cancelable: true
onexec: (f) -> @addEventListener 'execText', f
window.KDB ?= {}
KDB.processJSONP = (id,res) ->
console.log "kdb-srv(JSONP): #{id}" + res if @debug
jsonpRegistry[id]?(res)
KDB.rerunQuery = (kID,args) -> document.querySelector("[k-id='#{kID}']")?.rerunQuery args
KDB.KDBChart = document.registerElement('kdb-chart', prototype: _KDBChart.prototype)
KDB.KDBSrv = document.registerElement('kdb-srv', prototype: _KDBSrv.prototype)
KDB.KDBQuery = document.registerElement('kdb-query', prototype: _KDBQuery.prototype)
KDB.KDBTable = document.registerElement('kdb-table', prototype: _KDBTable.prototype)
KDB.KDBEditor = document.registerElement('kdb-editor', prototype: _KDBEditor.prototype)
|
[
{
"context": " @artwork.artists = [ fabricate('artist', name: 'Andy Warhol') ]\n benv.render resolve(__dirname, '../temp",
"end": 728,
"score": 0.9998831748962402,
"start": 717,
"tag": "NAME",
"value": "Andy Warhol"
},
{
"context": " @artwork.artists = [ fabricate('artist', name: 'Andy Warhol') ]\n @artwork.auction = {\n is_closed:",
"end": 2960,
"score": 0.9998641014099121,
"start": 2949,
"tag": "NAME",
"value": "Andy Warhol"
}
] | src/mobile/apps/artwork/components/image/test/view.coffee | kanaabe/force | 0 | _ = require 'underscore'
benv = require 'benv'
Backbone = require 'backbone'
sinon = require 'sinon'
rewire = require 'rewire'
CurrentUser = require '../../../../../models/current_user'
{ fabricate, fabricate2 } = require 'antigravity'
{ resolve } = require 'path'
describe 'ArtworkImageView', ->
before (done) ->
benv.setup =>
benv.expose
$: benv.require 'jquery'
Element: window.Element
Backbone.$ = $
done()
after ->
benv.teardown()
afterEach ->
Backbone.sync.restore()
describe 'favoriting an artwork', ->
beforeEach (done) ->
@artwork = fabricate('artwork', { image: url: '/image.png' } )
@artwork.artists = [ fabricate('artist', name: 'Andy Warhol') ]
benv.render resolve(__dirname, '../templates/index.jade'), {
artwork: @artwork
sd: ARTWORK: @artwork
asset: (->)
}, =>
ArtworkImageView = rewire '../view.coffee'
ArtworkImageView.__set__ 'ShareView', sinon.stub()
ArtworkImageView.__set__ 'Flickity', sinon.stub()
sinon.stub Backbone, 'sync'
@view = new ArtworkImageView
artwork: @artwork
el: $('.artwork-image-module')
done()
describe '#renderSave without a user', ->
it 'is in unsaved state', ->
@view.renderSave()
@view.$('.artwork-header-module__favorite-button').data('state').should.equal 'unsaved'
@view.$('.artwork-header-module__favorite-button').data('action').should.equal 'save'
it 'adds link to signup page', ->
@view.renderSave()
@view.$('.artwork-header-module__favorite-button').attr('href').should.containEql "/sign_up?action=artwork-save"
describe '#saveArtwork', ->
beforeEach ->
@e = new $.Event('click')
@spy = sinon.spy(CurrentUser.prototype, 'saveArtwork')
afterEach ->
CurrentUser.prototype.saveArtwork.restore()
describe 'with a user', ->
beforeEach ->
@view.user = new CurrentUser fabricate 'user'
@view.user.initializeDefaultArtworkCollection()
@view.$('.artwork-header-module__favorite-button').attr('data-action', 'save')
@view.savedArtwork(@e)
it 'saves the artwork', ->
@view.renderSave()
@spy.calledOnce.should.be.ok()
it 'toggles button state', ->
_.last(Backbone.sync.args)[2].success { id: 'saved-masterpiece' }
@view.$('.artwork-header-module__favorite-button').attr('data-action').should.equal 'remove'
@view.$('.artwork-header-module__favorite-button').attr('data-state').should.equal 'saved'
describe 'without a user', ->
it 'does nothing', ->
@spy.called.should.not.be.ok()
describe 'watching an artwork in auction', ->
beforeEach (done) ->
@artwork = fabricate('artwork', { image: url: '/image.png' } )
@artwork.artists = [ fabricate('artist', name: 'Andy Warhol') ]
@artwork.auction = {
is_closed: false
}
benv.render resolve(__dirname, '../templates/index.jade'), {
artwork: @artwork
sd: ARTWORK: @artwork
asset: (->)
}, =>
ArtworkImageView = rewire '../view.coffee'
ArtworkImageView.__set__ 'ShareView', sinon.stub()
ArtworkImageView.__set__ 'Flickity', sinon.stub()
sinon.stub Backbone, 'sync'
@view = new ArtworkImageView
artwork: @artwork
el: $('.artwork-image-module')
done()
describe '#renderSave without a user', ->
it 'is in unsaved state', ->
@view.renderSave()
@view.$('.artwork-header-module__watch-button').data('state').should.equal 'unsaved'
@view.$('.artwork-header-module__watch-button').data('action').should.equal 'save'
it 'adds link to signup page', ->
@view.renderSave()
@view.$('.artwork-header-module__watch-button').attr('href').should.containEql "/sign_up?action=artwork-save"
describe '#watchArtwork', ->
beforeEach ->
@e = new $.Event('click')
@spy = sinon.spy(CurrentUser.prototype, 'saveArtwork')
afterEach ->
CurrentUser.prototype.saveArtwork.restore()
describe 'with a user', ->
beforeEach ->
@view.user = new CurrentUser fabricate 'user'
@view.user.initializeDefaultArtworkCollection()
@view.$('.artwork-header-module__watch-button').attr('data-action', 'save')
@view.watchArtwork(@e)
it 'saves the artwork', ->
@view.renderSave()
@spy.calledOnce.should.be.ok()
it 'toggles button state', ->
_.last(Backbone.sync.args)[2].success { id: 'saved-masterpiece' }
@view.$('.artwork-header-module__watch-button').attr('data-action').should.equal 'remove'
@view.$('.artwork-header-module__watch-button').attr('data-state').should.equal 'saved'
describe 'without a user', ->
it 'does nothing', ->
@spy.called.should.not.be.ok()
| 126859 | _ = require 'underscore'
benv = require 'benv'
Backbone = require 'backbone'
sinon = require 'sinon'
rewire = require 'rewire'
CurrentUser = require '../../../../../models/current_user'
{ fabricate, fabricate2 } = require 'antigravity'
{ resolve } = require 'path'
describe 'ArtworkImageView', ->
before (done) ->
benv.setup =>
benv.expose
$: benv.require 'jquery'
Element: window.Element
Backbone.$ = $
done()
after ->
benv.teardown()
afterEach ->
Backbone.sync.restore()
describe 'favoriting an artwork', ->
beforeEach (done) ->
@artwork = fabricate('artwork', { image: url: '/image.png' } )
@artwork.artists = [ fabricate('artist', name: '<NAME>') ]
benv.render resolve(__dirname, '../templates/index.jade'), {
artwork: @artwork
sd: ARTWORK: @artwork
asset: (->)
}, =>
ArtworkImageView = rewire '../view.coffee'
ArtworkImageView.__set__ 'ShareView', sinon.stub()
ArtworkImageView.__set__ 'Flickity', sinon.stub()
sinon.stub Backbone, 'sync'
@view = new ArtworkImageView
artwork: @artwork
el: $('.artwork-image-module')
done()
describe '#renderSave without a user', ->
it 'is in unsaved state', ->
@view.renderSave()
@view.$('.artwork-header-module__favorite-button').data('state').should.equal 'unsaved'
@view.$('.artwork-header-module__favorite-button').data('action').should.equal 'save'
it 'adds link to signup page', ->
@view.renderSave()
@view.$('.artwork-header-module__favorite-button').attr('href').should.containEql "/sign_up?action=artwork-save"
describe '#saveArtwork', ->
beforeEach ->
@e = new $.Event('click')
@spy = sinon.spy(CurrentUser.prototype, 'saveArtwork')
afterEach ->
CurrentUser.prototype.saveArtwork.restore()
describe 'with a user', ->
beforeEach ->
@view.user = new CurrentUser fabricate 'user'
@view.user.initializeDefaultArtworkCollection()
@view.$('.artwork-header-module__favorite-button').attr('data-action', 'save')
@view.savedArtwork(@e)
it 'saves the artwork', ->
@view.renderSave()
@spy.calledOnce.should.be.ok()
it 'toggles button state', ->
_.last(Backbone.sync.args)[2].success { id: 'saved-masterpiece' }
@view.$('.artwork-header-module__favorite-button').attr('data-action').should.equal 'remove'
@view.$('.artwork-header-module__favorite-button').attr('data-state').should.equal 'saved'
describe 'without a user', ->
it 'does nothing', ->
@spy.called.should.not.be.ok()
describe 'watching an artwork in auction', ->
beforeEach (done) ->
@artwork = fabricate('artwork', { image: url: '/image.png' } )
@artwork.artists = [ fabricate('artist', name: '<NAME>') ]
@artwork.auction = {
is_closed: false
}
benv.render resolve(__dirname, '../templates/index.jade'), {
artwork: @artwork
sd: ARTWORK: @artwork
asset: (->)
}, =>
ArtworkImageView = rewire '../view.coffee'
ArtworkImageView.__set__ 'ShareView', sinon.stub()
ArtworkImageView.__set__ 'Flickity', sinon.stub()
sinon.stub Backbone, 'sync'
@view = new ArtworkImageView
artwork: @artwork
el: $('.artwork-image-module')
done()
describe '#renderSave without a user', ->
it 'is in unsaved state', ->
@view.renderSave()
@view.$('.artwork-header-module__watch-button').data('state').should.equal 'unsaved'
@view.$('.artwork-header-module__watch-button').data('action').should.equal 'save'
it 'adds link to signup page', ->
@view.renderSave()
@view.$('.artwork-header-module__watch-button').attr('href').should.containEql "/sign_up?action=artwork-save"
describe '#watchArtwork', ->
beforeEach ->
@e = new $.Event('click')
@spy = sinon.spy(CurrentUser.prototype, 'saveArtwork')
afterEach ->
CurrentUser.prototype.saveArtwork.restore()
describe 'with a user', ->
beforeEach ->
@view.user = new CurrentUser fabricate 'user'
@view.user.initializeDefaultArtworkCollection()
@view.$('.artwork-header-module__watch-button').attr('data-action', 'save')
@view.watchArtwork(@e)
it 'saves the artwork', ->
@view.renderSave()
@spy.calledOnce.should.be.ok()
it 'toggles button state', ->
_.last(Backbone.sync.args)[2].success { id: 'saved-masterpiece' }
@view.$('.artwork-header-module__watch-button').attr('data-action').should.equal 'remove'
@view.$('.artwork-header-module__watch-button').attr('data-state').should.equal 'saved'
describe 'without a user', ->
it 'does nothing', ->
@spy.called.should.not.be.ok()
| true | _ = require 'underscore'
benv = require 'benv'
Backbone = require 'backbone'
sinon = require 'sinon'
rewire = require 'rewire'
CurrentUser = require '../../../../../models/current_user'
{ fabricate, fabricate2 } = require 'antigravity'
{ resolve } = require 'path'
describe 'ArtworkImageView', ->
before (done) ->
benv.setup =>
benv.expose
$: benv.require 'jquery'
Element: window.Element
Backbone.$ = $
done()
after ->
benv.teardown()
afterEach ->
Backbone.sync.restore()
describe 'favoriting an artwork', ->
beforeEach (done) ->
@artwork = fabricate('artwork', { image: url: '/image.png' } )
@artwork.artists = [ fabricate('artist', name: 'PI:NAME:<NAME>END_PI') ]
benv.render resolve(__dirname, '../templates/index.jade'), {
artwork: @artwork
sd: ARTWORK: @artwork
asset: (->)
}, =>
ArtworkImageView = rewire '../view.coffee'
ArtworkImageView.__set__ 'ShareView', sinon.stub()
ArtworkImageView.__set__ 'Flickity', sinon.stub()
sinon.stub Backbone, 'sync'
@view = new ArtworkImageView
artwork: @artwork
el: $('.artwork-image-module')
done()
describe '#renderSave without a user', ->
it 'is in unsaved state', ->
@view.renderSave()
@view.$('.artwork-header-module__favorite-button').data('state').should.equal 'unsaved'
@view.$('.artwork-header-module__favorite-button').data('action').should.equal 'save'
it 'adds link to signup page', ->
@view.renderSave()
@view.$('.artwork-header-module__favorite-button').attr('href').should.containEql "/sign_up?action=artwork-save"
describe '#saveArtwork', ->
beforeEach ->
@e = new $.Event('click')
@spy = sinon.spy(CurrentUser.prototype, 'saveArtwork')
afterEach ->
CurrentUser.prototype.saveArtwork.restore()
describe 'with a user', ->
beforeEach ->
@view.user = new CurrentUser fabricate 'user'
@view.user.initializeDefaultArtworkCollection()
@view.$('.artwork-header-module__favorite-button').attr('data-action', 'save')
@view.savedArtwork(@e)
it 'saves the artwork', ->
@view.renderSave()
@spy.calledOnce.should.be.ok()
it 'toggles button state', ->
_.last(Backbone.sync.args)[2].success { id: 'saved-masterpiece' }
@view.$('.artwork-header-module__favorite-button').attr('data-action').should.equal 'remove'
@view.$('.artwork-header-module__favorite-button').attr('data-state').should.equal 'saved'
describe 'without a user', ->
it 'does nothing', ->
@spy.called.should.not.be.ok()
describe 'watching an artwork in auction', ->
beforeEach (done) ->
@artwork = fabricate('artwork', { image: url: '/image.png' } )
@artwork.artists = [ fabricate('artist', name: 'PI:NAME:<NAME>END_PI') ]
@artwork.auction = {
is_closed: false
}
benv.render resolve(__dirname, '../templates/index.jade'), {
artwork: @artwork
sd: ARTWORK: @artwork
asset: (->)
}, =>
ArtworkImageView = rewire '../view.coffee'
ArtworkImageView.__set__ 'ShareView', sinon.stub()
ArtworkImageView.__set__ 'Flickity', sinon.stub()
sinon.stub Backbone, 'sync'
@view = new ArtworkImageView
artwork: @artwork
el: $('.artwork-image-module')
done()
describe '#renderSave without a user', ->
it 'is in unsaved state', ->
@view.renderSave()
@view.$('.artwork-header-module__watch-button').data('state').should.equal 'unsaved'
@view.$('.artwork-header-module__watch-button').data('action').should.equal 'save'
it 'adds link to signup page', ->
@view.renderSave()
@view.$('.artwork-header-module__watch-button').attr('href').should.containEql "/sign_up?action=artwork-save"
describe '#watchArtwork', ->
beforeEach ->
@e = new $.Event('click')
@spy = sinon.spy(CurrentUser.prototype, 'saveArtwork')
afterEach ->
CurrentUser.prototype.saveArtwork.restore()
describe 'with a user', ->
beforeEach ->
@view.user = new CurrentUser fabricate 'user'
@view.user.initializeDefaultArtworkCollection()
@view.$('.artwork-header-module__watch-button').attr('data-action', 'save')
@view.watchArtwork(@e)
it 'saves the artwork', ->
@view.renderSave()
@spy.calledOnce.should.be.ok()
it 'toggles button state', ->
_.last(Backbone.sync.args)[2].success { id: 'saved-masterpiece' }
@view.$('.artwork-header-module__watch-button').attr('data-action').should.equal 'remove'
@view.$('.artwork-header-module__watch-button').attr('data-state').should.equal 'saved'
describe 'without a user', ->
it 'does nothing', ->
@spy.called.should.not.be.ok()
|
[
{
"context": "= params.email\n passField.value = params.passw\n form.submit()\n , params\n\n g",
"end": 1834,
"score": 0.932617723941803,
"start": 1829,
"tag": "PASSWORD",
"value": "passw"
}
] | lib/vkAuth.coffee | Wenqer/node-vk-music-sync | 1 | https = require 'https'
phantom = require 'phantom'
colors = require 'colors'
code = null
params = null
getToken = (callback) ->
options =
host: 'oauth.vk.com'
port: 443
path: "/access_token?client_id=#{params.appID}" +
"&client_secret=#{params.appSecret}" +
"&code=#{code}"
https.get options, (res) ->
response = new String
res.setEncoding 'utf8'
res.on 'data', (chunk) -> response += chunk
res.on 'end', ->
json = JSON.parse response
if json.access_token
console.log "Auth successed!".green
callback json.access_token
else
throw json.error
getPermissions = (callback) ->
phantom.create (ph) ->
ph.createPage (page) ->
page.set 'onUrlChanged', (url) ->
console.log "URL changed by script: ".grey , url.underline
page.set 'onLoadFinished', (success) ->
if success is 'fail' then callback null
console.log "Load status ".grey , success
page.set 'onNavigationRequested', (url) ->
console.log "URL changed: ".grey , url.underline
match = url.match /#code=(.*)/
if match
code = match[1]
ph.exit()
callback()
# Fix page.evaluate for pass variables inside sandbox
evaluate = (page, func) ->
args = [].slice.call arguments, 2
fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}"
page.evaluate fn
# Login into vk.com
page.open "https://vk.com", (status) ->
evaluate page, (params) ->
form = document.getElementById 'quick_login_form'
emailField = document.getElementById 'quick_email'
passField = document.getElementById 'quick_pass'
emailField.value = params.email
passField.value = params.passw
form.submit()
, params
getCode = ->
url = "https://oauth.vk.com" +
"/authorize/?client_id=#{params.appID}" +
"&scope=audio" +
"&response_type=code"
page.open url, (status) ->
page.evaluate ->
btn = document.getElementById 'install_allow'
btn.click()
# Try to get code
setTimeout getCode, 4000
module.exports = (options) ->
initialize: (callback) ->
params = options
getPermissions (status) ->
if status is null then callback null
getToken (token) ->
callback token
| 188644 | https = require 'https'
phantom = require 'phantom'
colors = require 'colors'
code = null
params = null
getToken = (callback) ->
options =
host: 'oauth.vk.com'
port: 443
path: "/access_token?client_id=#{params.appID}" +
"&client_secret=#{params.appSecret}" +
"&code=#{code}"
https.get options, (res) ->
response = new String
res.setEncoding 'utf8'
res.on 'data', (chunk) -> response += chunk
res.on 'end', ->
json = JSON.parse response
if json.access_token
console.log "Auth successed!".green
callback json.access_token
else
throw json.error
getPermissions = (callback) ->
phantom.create (ph) ->
ph.createPage (page) ->
page.set 'onUrlChanged', (url) ->
console.log "URL changed by script: ".grey , url.underline
page.set 'onLoadFinished', (success) ->
if success is 'fail' then callback null
console.log "Load status ".grey , success
page.set 'onNavigationRequested', (url) ->
console.log "URL changed: ".grey , url.underline
match = url.match /#code=(.*)/
if match
code = match[1]
ph.exit()
callback()
# Fix page.evaluate for pass variables inside sandbox
evaluate = (page, func) ->
args = [].slice.call arguments, 2
fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}"
page.evaluate fn
# Login into vk.com
page.open "https://vk.com", (status) ->
evaluate page, (params) ->
form = document.getElementById 'quick_login_form'
emailField = document.getElementById 'quick_email'
passField = document.getElementById 'quick_pass'
emailField.value = params.email
passField.value = params.<PASSWORD>
form.submit()
, params
getCode = ->
url = "https://oauth.vk.com" +
"/authorize/?client_id=#{params.appID}" +
"&scope=audio" +
"&response_type=code"
page.open url, (status) ->
page.evaluate ->
btn = document.getElementById 'install_allow'
btn.click()
# Try to get code
setTimeout getCode, 4000
module.exports = (options) ->
initialize: (callback) ->
params = options
getPermissions (status) ->
if status is null then callback null
getToken (token) ->
callback token
| true | https = require 'https'
phantom = require 'phantom'
colors = require 'colors'
code = null
params = null
getToken = (callback) ->
options =
host: 'oauth.vk.com'
port: 443
path: "/access_token?client_id=#{params.appID}" +
"&client_secret=#{params.appSecret}" +
"&code=#{code}"
https.get options, (res) ->
response = new String
res.setEncoding 'utf8'
res.on 'data', (chunk) -> response += chunk
res.on 'end', ->
json = JSON.parse response
if json.access_token
console.log "Auth successed!".green
callback json.access_token
else
throw json.error
getPermissions = (callback) ->
phantom.create (ph) ->
ph.createPage (page) ->
page.set 'onUrlChanged', (url) ->
console.log "URL changed by script: ".grey , url.underline
page.set 'onLoadFinished', (success) ->
if success is 'fail' then callback null
console.log "Load status ".grey , success
page.set 'onNavigationRequested', (url) ->
console.log "URL changed: ".grey , url.underline
match = url.match /#code=(.*)/
if match
code = match[1]
ph.exit()
callback()
# Fix page.evaluate for pass variables inside sandbox
evaluate = (page, func) ->
args = [].slice.call arguments, 2
fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}"
page.evaluate fn
# Login into vk.com
page.open "https://vk.com", (status) ->
evaluate page, (params) ->
form = document.getElementById 'quick_login_form'
emailField = document.getElementById 'quick_email'
passField = document.getElementById 'quick_pass'
emailField.value = params.email
passField.value = params.PI:PASSWORD:<PASSWORD>END_PI
form.submit()
, params
getCode = ->
url = "https://oauth.vk.com" +
"/authorize/?client_id=#{params.appID}" +
"&scope=audio" +
"&response_type=code"
page.open url, (status) ->
page.evaluate ->
btn = document.getElementById 'install_allow'
btn.click()
# Try to get code
setTimeout getCode, 4000
module.exports = (options) ->
initialize: (callback) ->
params = options
getPermissions (status) ->
if status is null then callback null
getToken (token) ->
callback token
|
[
{
"context": "hostname = settings.hostname or settings.host or '127.0.0.1'\n u.port = settings.port or 8529\n u.auth = \"#{s",
"end": 522,
"score": 0.9526199698448181,
"start": 513,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "###\n_isReservedKey = (key) ->\n key in ['_key', '_id', '_rev', '_from', '_to']\n\nclass Sequence\n const",
"end": 1428,
"score": 0.7030313611030579,
"start": 1426,
"tag": "KEY",
"value": "id"
},
{
"context": "ReservedKey = (key) ->\n key in ['_key', '_id', '_rev', '_from', '_to']\n\nclass Sequence\n constructor: ",
"end": 1436,
"score": 0.6119635105133057,
"start": 1433,
"tag": "KEY",
"value": "rev"
},
{
"context": "Key = (key) ->\n key in ['_key', '_id', '_rev', '_from', '_to']\n\nclass Sequence\n constructor: (start) -",
"end": 1445,
"score": 0.5522744655609131,
"start": 1441,
"tag": "KEY",
"value": "from"
},
{
"context": " dataI._key = idValue\n\n aql = qb.upsert({_key: '@id'}).insert('@dataI').update('@data').in('@@collect",
"end": 11781,
"score": 0.8350245952606201,
"start": 11777,
"tag": "KEY",
"value": "'@id"
}
] | src/arangodb.coffee | mrbatista/loopback-connector-arangodb | 15 | # node modules
# Module dependencies
arangojs = require 'arangojs'
qb = require 'aqb'
url = require 'url'
merge = require 'extend'
async = require 'async'
_ = require 'underscore'
Connector = require('loopback-connector').Connector
debug = require('debug') 'loopback:connector:arango'
###
Generate the arangodb URL from the options
###
exports.generateArangoDBURL = generateArangoDBURL = (settings) ->
u = {}
u.protocol = settings.protocol or 'http:'
u.hostname = settings.hostname or settings.host or '127.0.0.1'
u.port = settings.port or 8529
u.auth = "#{settings.username}:#{settings.password}" if settings.username and settings.password
settings.databaseName = settings.database or settings.db or '_system'
return url.format u
###
Check if field should be included
@param {Object} fields
@param {String} fieldName
@returns {Boolean}
@private
###
_fieldIncluded = (fields, fieldName) ->
if not fields then return true
if Array.isArray fields
return fields.indexOf fieldName >= 0
if fields[fieldName]
# Included
return true
if fieldName in fields and !fields[fieldName]
# Excluded
return false
for f in fields
return !fields[f]; # If the fields has exclusion
return true
###
Verify if a field is a reserved arangoDB key
@param {String} key The name of key to verify
@returns {Boolean}
@private
###
_isReservedKey = (key) ->
key in ['_key', '_id', '_rev', '_from', '_to']
class Sequence
constructor: (start) ->
@nextVal = start or 0
next: () ->
return @nextVal++;
###
Initialize the ArangoDB connector for the given data source
@param {DataSource} dataSource The data source instance
@param {Function} [callback] The callback function
###
exports.initialize = initializeDataSource = (dataSource, callback) ->
return if not arangojs
s = dataSource.settings
s.url = s.url or generateArangoDBURL s
dataSource.connector = new ArangoDBConnector s, dataSource
dataSource.connector.connect callback if callback?
###
Loopback ArangoDB Connector
@extend Connector
###
class ArangoDBConnector extends Connector
returnVariable = 'result'
@collection = 'collection'
@edgeCollection = 'edgeCollection'
@returnVariable = 'result'
###
The constructor for ArangoDB connector
@param {Object} settings The settings object
@param {DataSource} dataSource The data source instance
@constructor
###
constructor: (settings, dataSource) ->
super 'arangodb', settings
# debug
@debug = dataSource.settings.debug or debug.enabled
# link to datasource
@dataSource = dataSource
# Arango Query Builder
# TODO MAJOR rename to aqb
@qb = qb
###
Connect to ArangoDB
@param {Function} [callback] The callback function
@callback callback
@param {Error} err The error object
@param {Db} db The arangoDB object
###
connect: (callback) ->
debug "ArangoDB connection is called with settings: #{JSON.stringify @settings}" if @debug
if not @db
@db = arangojs @settings
@api = @db.route '/_api'
process.nextTick () =>
callback null, @db if callback
###
Get the types of this connector
@return {Array<String>} The types of connector
###
getTypes: () ->
return ['db', 'nosql', 'arangodb']
###
The default Id type
@return {String} The type of id value
###
getDefaultIdType: () ->
return String
###
Get the model class for a certain model name
@param {String} model The model name to lookup
@return {Object} The model class of this model
###
getModelClass: (model) ->
return @_models[model]
###
Get the collection name for a certain model name
@param {String} model The model name to lookup
@return {Object} The collection name for this model
###
getCollectionName: (model) ->
modelClass = @getModelClass model
if modelClass.settings and modelClass.settings.arangodb
model = modelClass.settings.arangodb.collection or model
return model
###
Coerce the id value
###
coerceId: (model, id) ->
return id if not id?
idValue = id;
idName = @idName model
# Type conversion for id
idProp = @getPropertyDefinition model, idName
if idProp && typeof idProp.type is 'function'
if not (idValue instanceof idProp.type)
idValue = idProp.type id
# Reset to id
if idProp.type is Number and isNaN id then idValue = id
return idValue;
###
Set value of specific field into data object
@param data {Object} The data object
@param field {String} The name of field to set
@param value {Any} The value to set
###
_setFieldValue: (data, field, value) ->
if data then data[field] = value;
###
Verify if the collection is an edge collection
@param model [String] The model name to lookup
@return [Boolean] Return true if collection is edge false otherwise
###
_isEdge: (model) ->
modelClass = @getModelClass model
settings = modelClass.settings
return settings and settings.arangodb and settings.arangodb.edge || false
###
###
_getNameOfProperty: (model, p) ->
props = @getModelClass(model).properties
for key, prop of props
if prop[p] then return key else continue
return false
###
Get if the model has _id field
@param {String} model The model name to lookup
@return {String|Boolean} Return name of _id or false if model not has _id field
###
_fullIdName: (model) ->
@_getNameOfProperty model, '_id'
###
Get if the model has _from field
@param {String} model The model name to lookup
@return {String|Boolean} Return name of _from or false if model not has _from field
###
_fromName: (model) ->
@_getNameOfProperty model, '_from'
###
Get if the model has _to field
@param {String} model The model name to lookup
@return {String|Boolean} Return name of _to or false if model not has _to field
###
_toName: (model) ->
@_getNameOfProperty model, '_to'
###
Access a ArangoDB collection by model name
@param {String} model The model name
@return {*}
###
getCollection: (model) ->
if not @db then throw new Error('ArangoDB connection is not established')
collection = ArangoDBConnector.collection
if @_isEdge model then collection = ArangoDBConnector.edgeCollection
return @db[collection] @getCollectionName model
###
Converts the retrieved data from the database to JSON, based on the properties of a given model
@param {String} model The model name to look up the properties
@param {Object} [data] The data from DB
@return {Object} The converted data as an JSON Object
###
fromDatabase: (model, data) ->
return null if not data?
props = @getModelClass(model).properties
for key, val of props
#Buffer type
if data[key]? and val? and val.type is Buffer
data[key] = new Buffer(data[key])
# Date
if data[key]? and val? and val.type is Date
data[key] = new Date data[key]
# GeoPoint
if data[key]? and val? and val.type and val.type.name is 'GeoPoint'
console.warn('GeoPoint is not supported by connector');
return data
###
Execute a ArangoDB command
###
execute: (model, command) ->
#Get the parameters for the given command
args = [].slice.call(arguments, 2);
#The last argument must be a callback function
callback = args[args.length - 1];
context =
req:
command: command
params: args
@notifyObserversAround 'execute', context, (context, done) =>
debug 'ArangoDB: model=%s command=%s', model, command, args if @debug
args[args.length - 1] = (err, result) ->
if err
debug('Error: ', err);
if err.code
err.statusCode = err.code
err.response? delete err.response
else
context.res = result;
debug('Result: ', result)
done(err, result);
if command is 'query'
query = context.req.params[0]
bindVars = context.req.params[1]
if @debug
if typeof query.toAQL is 'function'
q = query.toAQL()
else
q = query
debug "query: #{q} bindVars: #{JSON.stringify bindVars}"
@db.query.apply @db, args
else
collection = @getCollection model
collection[command].apply collection, args
, callback
###
Get the version of the ArangoDB
@param callback [Function] The callback function
@callback callback
@param {Error} err The error object
@param {String} version The arangoDB version
###
getVersion: (callback) ->
if @version?
callback null, @version
else
@api.get 'version', (err, result) =>
callback err if err
@version = result.body
callback null, @version
###
Create a new model instance for the given data
@param {String} model The model name
@param {Object} data The data to create
@param {Object} options The data to create
@param callback [Function] The callback function
###
create: (model, data, options, callback) ->
debug "create model #{model} with data: #{JSON.stringify data}" if @debug
idValue = @getIdValue model, data
idName = @idName model
if !idValue? or typeof idValue is 'undefined'
delete data[idName]
else
id = @getDefaultIdType() idValue
data._key = id
if idName isnt '_key' then delete data[idName]
# Check and delete full id name if present
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
isEdge = @_isEdge model
fromName = null
toName = null
if isEdge
fromName = @_fromName model
data._from = data[fromName]
if fromName isnt '_from'
data._from = data[fromName]
delete data[fromName]
toName = @_toName model
if toName isnt '_to'
data._to = data[toName]
delete data[toName]
@execute model, 'save', data, (err, result) =>
if err
# Change message error to pass junit test
if err.errorNum is 1210 then err.message = '/duplicate/i'
return callback(err)
# Save _key and _id value
idValue = @coerceId model, result._key
delete data._key
data[idName] = idValue;
if isEdge
if fromName isnt '_from' then data[fromName] = data._from
if toName isnt '_to' then data[toName] = data._to
if fullIdName
data[fullIdName] = result._id
delete result._id
callback err, idValue
###
Update if the model instance exists with the same id or create a new instance
@param model [String] The model name
@param data [Object] The model instance data
@param options [Object] The options
@param callback [Function] The callback function, called with a (possible) error object and updated or created object
###
updateOrCreate: (model, data, options, callback) ->
debug "updateOrCreate for Model #{model} with data: #{JSON.stringify data}" if @debug
idValue = @getIdValue(model, data)
idName = @idName(model)
idValue = @getDefaultIdType() idValue if typeof idValue is 'number'
delete data[idName]
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
isEdge = @_isEdge model
fromName = null
toName = null
if isEdge
fromName = @_fromName model
if fromName isnt '_from'
data._from = data[fromName]
delete data[fromName]
toName = @_toName model
if toName isnt '_to'
data._to = data[toName]
delete data[toName]
dataI = _.clone(data)
dataI._key = idValue
aql = qb.upsert({_key: '@id'}).insert('@dataI').update('@data').in('@@collection').let('isNewInstance',
qb.ref('OLD').then(false).else(true)).return({doc: 'NEW', isNewInstance: 'isNewInstance'});
bindVars =
'@collection': @getCollectionName model
id: idValue
dataI: dataI
data: data
@execute model, 'query', aql, bindVars, (err, result) =>
if result and result._result[0]
newDoc = result._result[0].doc
# Delete revision
delete newDoc._rev
if fullIdName
data[fullIdName] = newDoc._id
if fullIdName isnt '_id' then delete newDoc._id
else
delete newDoc._id
if isEdge
if fromName isnt '_from' then data[fromName] = data._from
if toName isnt '_to' then data[toName] = data._to
isNewInstance = { isNewInstance: result._result[0].isNewInstance }
@setIdValue(model, data, newDoc._key)
@setIdValue(model, newDoc, newDoc._key)
if idName isnt '_key' then delete newDoc._key
callback err, newDoc, isNewInstance
###
Save the model instance for the given data
@param model [String] The model name
@param data [Object] The updated data to save or create
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and the number of affected objects
###
save: @::updateOrCreate
###
Check if a model instance exists by id
@param model [String] The model name
@param id [String] The id value
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and an boolean value if the specified object existed (true) or not (false)
###
exists: (model, id, options, callback) ->
debug "exists for #{model} with id: #{id}" if @debug
@find model, id, options, (err, result) ->
return callback err if err
callback null, result.length > 0
###
Find a model instance by id
@param model [String] model The model name
@param id [String] id The id value
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and the found object
###
find: (model, id, options, callback) ->
debug "find for #{model} with id: #{id}" if @debug
command = 'document'
if @_isEdge model then command = 'edge'
@execute model, command, id, (err, result) ->
return callback err if err
callback null, result
###
Extracts where relevant information from the filter for a certain model
@param [String] model The model name
@param [Object] filter The filter object, also containing the where conditions
@param [Sequence] sequence The sequence instance used to generate random bind vars
@return return [Object]
@option return aqlArray [Array] The issued conditions as an array of AQL query builder objects
@option return bindVars [Object] The variables, bound in the conditions
@option return geoObject [Object] An query builder object containing possible parameters for a geo query
###
_buildWhere: (model, where, sequence) ->
debug "Evaluating where object #{JSON.stringify where} for Model #{model}" if @debug
if !where? or typeof where isnt 'object'
return
# array holding the filter
aqlArray = []
# the object holding the assignments of conditional values to temporary variables
bindVars = {}
geoExpr = {}
# index for condition parameter binding
sequence = sequence or new Sequence
# helper function to fill bindVars with the upcoming temporary variables that the where sentence will generate
assignNewQueryVariable = (value) ->
partName = 'param_' + sequence.next()
bindVars[partName] = value
return '@' + partName
idName = @idName model
fullIdName = @_fullIdName model
fromName = @_fromName model
toName = @_toName model
###
the where object comes in two flavors
- where[prop] = value: this is short for "prop" equals "value"
- where[prop][op] = value: this is the long version and stands for "prop" "op" "value"
###
for condProp, condValue of where
do() =>
# special treatment for 'and', 'or' and 'nor' operator, since there value is an array of conditions
if condProp in ['and', 'or', 'nor']
# 'and', 'or' and 'nor' have multiple conditions so we run buildWhere recursively on their array to
if Array.isArray condValue
aql = qb
# condValue is an array of conditions so get the conditions from it via a recursive buildWhere call
for c, a of condValue
cond = @_buildWhere model, a, sequence
aql = aql[condProp] cond.aqlArray[0]
bindVars = merge true, bindVars, cond.bindVars
aqlArray.push aql
aql = null
return
# correct if the conditionProperty falsely references to 'id'
if condProp is idName
condProp = '_key'
if typeof condValue is 'number' then condValue = String(condValue)
if condProp is fullIdName
condProp = '_id'
if condProp is fromName
condProp = '_from'
if condProp is toName
condProp = '_to'
# special case: if condValue is a Object (instead of a string or number) we have a conditionOperator
if condValue and condValue.constructor.name is 'Object'
# condition operator is the only keys value, the new condition value is shifted one level deeper and can be a object with keys and values
options = condValue.options
condOp = Object.keys(condValue)[0]
condValue = condValue[condOp]
if condOp
# If the value is not an array, fall back to regular fields
switch
when condOp in ['lte', 'lt']
tempAql = qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
# https://docs.arangodb.com/2.8/Aql/Basics.html#type-and-value-order
if condValue isnt null
tempAql = tempAql.and qb['neq'] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(null)}"
aqlArray.push(tempAql)
when condOp in ['gte', 'gt']
# https://docs.arangodb.com/2.8/Aql/Basics.html#type-and-value-order
if condValue is null
if condOp is 'gte' then condOp = 'lte'
if condOp is 'gt' then condOp = 'lt'
aqlArray.push qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(null)}"
else
aqlArray.push qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
when condOp in ['eq', 'neq']
aqlArray.push qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
# range comparison
when condOp is 'between'
tempAql = qb.gte "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue[0])}"
tempAql = tempAql.and qb.lte "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue[1])}"
aqlArray.push(tempAql)
# string comparison
when condOp is 'like'
if options is 'i' then options = true else options = false
aqlArray.push qb.fn('LIKE') "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}", options
when condOp is 'nlike'
if options is 'i' then options = true else options = false
aqlArray.push qb.not qb.fn('LIKE') "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}", options
# array comparison
when condOp is 'nin'
if _isReservedKey condProp
condValue = (value.toString() for value in condValue)
aqlArray.push qb.not qb.in "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
when condOp is 'inq'
if _isReservedKey condProp
condValue = (value.toString() for value in condValue)
aqlArray.push qb.in "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
# geo comparison (extra object)
when condOp is 'near'
# 'near' does not create a condition in the filter part, it returnes the lat/long pair
# the query will be done from the querying method itself
[lat, long] = condValue.split(',')
collection = @getCollectionName model
if where.limit?
geoExpr = qb.NEAR collection, lat, long, where.limit
else
geoExpr = qb.NEAR collection, lat, long
# if we don't have a matching operator or no operator at all (condOp = false) print warning
else
console.warn 'No matching operator for : ', condOp
else
aqlArray.push qb.eq "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
return {
aqlArray: aqlArray
bindVars: bindVars
geoExpr: geoExpr
}
###
Find matching model instances by the filter
@param [String] model The model name
@param [Object] filter The filter
@param options [Object]
@param [Function] callback Callback with (possible) error object or list of objects
###
all: (model, filter, options, callback) ->
debug "all for #{model} with filter #{JSON.stringify filter}" if @debug
idName = @idName model
fullIdName = @_fullIdName model
fromName = @_fromName model
toName = @_toName model
bindVars =
'@collection': @getCollectionName model
aql = qb.for(returnVariable).in('@@collection')
if filter.where
where = @_buildWhere(model, filter.where)
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
if filter.order
if typeof filter.order is 'string' then filter.order = filter.order.split(',')
for order in filter.order
m = order.match(/\s+(A|DE)SC$/)
field = order.replace(/\s+(A|DE)SC$/, '').trim()
if field in [idName, fullIdName, fromName, toName]
switch field
when idName then field = '_key'
when fullIdName then field = '_id'
when fromName then field = '_from'
when toName then field = '_to'
if m and m[1] is 'DE'
aql = aql.sort(returnVariable + '.' + field, 'DESC')
else
aql = aql.sort(returnVariable + '.' + field, 'ASC')
else if not @settings.disableDefaultSortByKey
aql = aql.sort(returnVariable + '._key')
if filter.limit
aql = aql.limit(filter.skip, filter.limit)
fields = _.clone(filter.fields)
if fields
indexId = fields.indexOf(idName)
if indexId isnt -1
fields[indexId] = '_key'
indexFullId = fields.indexOf(fullIdName)
if indexFullId isnt -1
fields[indexFullId] = '_id'
indexFromName = fields.indexOf(fromName)
if indexFromName isnt -1
fields[indexFromName] = '_from'
indexToName = fields.indexOf(toName)
if indexToName isnt -1
fields[indexToName] = '_to'
fields = ( '"' + field + '"' for field in fields)
aql = aql.return(qb.fn('KEEP') returnVariable, fields)
else
aql = aql.return((qb.fn('UNSET') returnVariable, ['"_rev"']))
@execute model, 'query', aql, bindVars, (err, cursor) =>
return callback err if err
cursorToArray = (r) =>
if _fieldIncluded filter.fields, idName
@setIdValue model, r, r._key
# Don't pass back _key if the fields is set
if idName isnt '_key' then delete r._key;
if fullIdName
if _fieldIncluded filter.fields, fullIdName
@_setFieldValue r, fullIdName, r._id
if fullIdName isnt '_id' and idName isnt '_id' then delete r._id
else
if idName isnt '_id' then delete r._id
if @_isEdge model
if _fieldIncluded filter.fields, fromName
@_setFieldValue r, fromName, r._from
if fromName isnt '_from' then delete r._from
if _fieldIncluded filter.fields, toName
@_setFieldValue r, toName, r._to
if toName isnt '_to' then delete r._to
r = @fromDatabase(model, r)
cursor.map cursorToArray, (err, result) =>
return callback err if err
# filter include
if filter.include?
@_models[model].model.include result, filter.include, options, callback
else
callback null, result
###
Delete a model instance by id
@param model [String] model The model name
@param id [String] id The id value
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and the number of affected objects
###
destroy: (model, id, options, callback) ->
debug "delete for #{model} with id #{id}" if @debug
@execute model, 'remove', id, (err, result) ->
# Set error to null if API response is `document not found`
if err and err.errorNum is 1202 then err = null
callback and callback err, {count: if result and !result.error then 1 else 0}
###
Delete all instances for the given model
@param [String] model The model name
@param [Object] [where] The filter for where
@param options [Object]
@param [Function] callback Callback with (possible) error object or the number of affected objects
###
destroyAll: (model, where, options, callback) ->
debug "destroyAll for #{model} with where #{JSON.stringify where}" if @debug
if !callback && typeof where is 'function'
callback = where
where = undefined
collection = @getCollectionName model
bindVars =
'@collection': collection
aql = qb.for(returnVariable).in('@@collection')
if !_.isEmpty(where)
where = @_buildWhere model, where
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
aql = aql.remove(returnVariable).in('@@collection')
@execute model, 'query', aql, bindVars, (err, result) ->
if callback
return callback err if err
callback null, {count: result.extra.stats.writesExecuted}
###
Count the number of instances for the given model
@param [String] model The model name
@param [Function] callback Callback with (possible) error object or the number of affected objects
@param [Object] where The filter for where
###
count: (model, where, options, callback) ->
debug "count for #{model} with where #{JSON.stringify where}" if @debug
collection = @getCollectionName model
bindVars =
'@collection': collection
aql = qb.for(returnVariable).in('@@collection')
if !_.isEmpty(where)
where = @_buildWhere model, where
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
aql = aql.collectWithCountInto(returnVariable).return(returnVariable)
@execute model, 'query', aql, bindVars, (err, result) ->
return callback err if err
callback null, result._result[0]
###
Update properties for the model instance data
@param [String] model The model name
@param [String] id The models id
@param [Object] data The model data
@param [Object] options
@param [Function] callback Callback with (possible) error object or the updated object
###
updateAttributes: (model, id, data, options, callback) ->
debug "updateAttributes for #{model} with id #{id} and data #{JSON.stringify data}" if @debug
id = @getDefaultIdType() id
idName = @idName(model)
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
isEdge = @_isEdge model
fromName = null
toName = null
if isEdge
fromName = @_fromName model
delete data[fromName]
toName = @_toName model
delete data[toName]
@execute model, 'update', id, data, options, (err, result) =>
if result
delete result['_rev']
if idName isnt '_key' then delete result._key;
@setIdValue(model, result, id);
if fullIdName
fullIdValue = result._id
delete result._id
result[fullIdName] = fullIdValue;
if isEdge
result[fromName] = data._from
result[toName] = data._to
callback and callback err, result
###
Update matching instance
@param [String] model The model name
@param [Object] where The search criteria
@param [Object] data The property/value pairs to be updated
@param [Object] options
@param [Function] callback Callback with (possible) error object or the number of affected objects
###
update: (model, where, data, options, callback) ->
debug "updateAll for #{model} with where #{JSON.stringify where} and data #{JSON.stringify data}" if @debug
collection = @getCollectionName model
bindVars =
'@collection': collection
data: data
aql = qb.for(returnVariable).in('@@collection')
if where
where = @_buildWhere(model, where)
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
aql = aql.update(returnVariable).with('@data').in('@@collection')
# _id, _key _from and _to are are immutable once set and cannot be updated
idName = @idName(model)
delete data[idName]
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
if @_isEdge model
fromName = @_fromName model
delete data[fromName]
toName = @_toName model
delete data[toName]
@execute model, 'query', aql, bindVars, (err, result) ->
return callback err if err
callback null, {count: result.extra.stats.writesExecuted}
###
Update all matching instances
###
updateAll: @::update
###
Perform autoupdate for the given models. It basically calls ensureIndex
@param [String[]] [models] A model name or an array of model names. If not present, apply to all models
@param [Function] [cb] The callback function
###
autoupdate: (models, cb) ->
if @db
debug 'autoupdate for model %s', models if @debug
if (not cb) and (typeof models is 'function')
cb = models
models = undefined
# First argument is a model name
models = [models] if typeof models is 'string'
models = models or Object.keys @_models
async.each( models, ((model, modelCallback) =>
indexes = @_models[model].settings.indexes or []
indexList = []
index = {}
options = {}
if typeof indexes is 'object'
for indexName, index of indexes
if index.keys
# the index object has keys
options = index.options or {}
options.name = options.name or indexName
index.options = options
else
options =
name: indexName
index =
keys: index
options: options
indexList.push index
else if Array.isArray indexes
indexList = indexList.concat indexes
for propIdx, property of @_models[model].properties
if property.index
index = {}
index[propIdx] = 1
if typeof property.index is 'object'
# If there is a arangodb key for the index, use it
if typeof property.index.arangodb is 'object'
options = property.index.arangodb
index[propIdx] = options.kind or 1
# Backwards compatibility for former type of indexes
options.unique = true if property.index.uniqe is true
else
# If there isn't an properties[p].index.mongodb object, we read the properties from properties[p].index
options = property.index
options.background = true if options.background is undefined
# If properties[p].index isn't an object we hardcode the background option and check for properties[p].unique
else
options =
background: true
options.unique = true if property.unique
indexList.push {keys: index, options: options}
debug 'create indexes' if @debug
async.each( indexList, ((index, indexCallback) =>
debug 'createIndex: %s', index if @debug
collection = @getCollection model
collection.createIndex(index.fields || index.keys, index.options, indexCallback);
), modelCallback )
), cb)
else
@dataSource.once 'connected', () -> @autoupdate models, cb
###
Perform automigrate for the given models. It drops the corresponding collections and calls ensureIndex
@param [String[]] [models] A model name or an array of model names. If not present, apply to all models
@param [Function] [cb] The callback function
###
automigrate: (models, cb) ->
if @db
debug "automigrate for model #{models}" if @debug
if (not cb) and (typeof models is 'function')
cb = models
models = undefined
# First argument is a model name
models = [models] if typeof models is 'string'
models = models || Object.keys @_models
async.eachSeries(models, ((model, modelCallback) =>
collectionName = @getCollectionName model
debug 'drop collection %s for model %s', collectionName, model
collection = @getCollection model
collection.drop (err) =>
if err
if err.response.body?
err = err.response.body
# For errors other than 'collection not found'
isCollectionNotFound = err.error is true and err.errorNum is 1203 and
(err.errorMessage is 'unknown collection \'' + model + '\'' or err.errorMessage is 'collection not found')
return modelCallback err if not isCollectionNotFound
# Recreate the collection
debug 'create collection %s for model %s', collectionName, model
collection.create modelCallback
), ((err) =>
return cb and cb err
@autoupdate models, cb
))
else
@dataSource.once 'connected', () -> @automigrate models cb
exports.ArangoDBConnector = ArangoDBConnector
| 191981 | # node modules
# Module dependencies
arangojs = require 'arangojs'
qb = require 'aqb'
url = require 'url'
merge = require 'extend'
async = require 'async'
_ = require 'underscore'
Connector = require('loopback-connector').Connector
debug = require('debug') 'loopback:connector:arango'
###
Generate the arangodb URL from the options
###
exports.generateArangoDBURL = generateArangoDBURL = (settings) ->
u = {}
u.protocol = settings.protocol or 'http:'
u.hostname = settings.hostname or settings.host or '127.0.0.1'
u.port = settings.port or 8529
u.auth = "#{settings.username}:#{settings.password}" if settings.username and settings.password
settings.databaseName = settings.database or settings.db or '_system'
return url.format u
###
Check if field should be included
@param {Object} fields
@param {String} fieldName
@returns {Boolean}
@private
###
_fieldIncluded = (fields, fieldName) ->
if not fields then return true
if Array.isArray fields
return fields.indexOf fieldName >= 0
if fields[fieldName]
# Included
return true
if fieldName in fields and !fields[fieldName]
# Excluded
return false
for f in fields
return !fields[f]; # If the fields has exclusion
return true
###
Verify if a field is a reserved arangoDB key
@param {String} key The name of key to verify
@returns {Boolean}
@private
###
_isReservedKey = (key) ->
key in ['_key', '_<KEY>', '_<KEY>', '_<KEY>', '_to']
class Sequence
constructor: (start) ->
@nextVal = start or 0
next: () ->
return @nextVal++;
###
Initialize the ArangoDB connector for the given data source
@param {DataSource} dataSource The data source instance
@param {Function} [callback] The callback function
###
exports.initialize = initializeDataSource = (dataSource, callback) ->
return if not arangojs
s = dataSource.settings
s.url = s.url or generateArangoDBURL s
dataSource.connector = new ArangoDBConnector s, dataSource
dataSource.connector.connect callback if callback?
###
Loopback ArangoDB Connector
@extend Connector
###
class ArangoDBConnector extends Connector
returnVariable = 'result'
@collection = 'collection'
@edgeCollection = 'edgeCollection'
@returnVariable = 'result'
###
The constructor for ArangoDB connector
@param {Object} settings The settings object
@param {DataSource} dataSource The data source instance
@constructor
###
constructor: (settings, dataSource) ->
super 'arangodb', settings
# debug
@debug = dataSource.settings.debug or debug.enabled
# link to datasource
@dataSource = dataSource
# Arango Query Builder
# TODO MAJOR rename to aqb
@qb = qb
###
Connect to ArangoDB
@param {Function} [callback] The callback function
@callback callback
@param {Error} err The error object
@param {Db} db The arangoDB object
###
connect: (callback) ->
debug "ArangoDB connection is called with settings: #{JSON.stringify @settings}" if @debug
if not @db
@db = arangojs @settings
@api = @db.route '/_api'
process.nextTick () =>
callback null, @db if callback
###
Get the types of this connector
@return {Array<String>} The types of connector
###
getTypes: () ->
return ['db', 'nosql', 'arangodb']
###
The default Id type
@return {String} The type of id value
###
getDefaultIdType: () ->
return String
###
Get the model class for a certain model name
@param {String} model The model name to lookup
@return {Object} The model class of this model
###
getModelClass: (model) ->
return @_models[model]
###
Get the collection name for a certain model name
@param {String} model The model name to lookup
@return {Object} The collection name for this model
###
getCollectionName: (model) ->
modelClass = @getModelClass model
if modelClass.settings and modelClass.settings.arangodb
model = modelClass.settings.arangodb.collection or model
return model
###
Coerce the id value
###
coerceId: (model, id) ->
return id if not id?
idValue = id;
idName = @idName model
# Type conversion for id
idProp = @getPropertyDefinition model, idName
if idProp && typeof idProp.type is 'function'
if not (idValue instanceof idProp.type)
idValue = idProp.type id
# Reset to id
if idProp.type is Number and isNaN id then idValue = id
return idValue;
###
Set value of specific field into data object
@param data {Object} The data object
@param field {String} The name of field to set
@param value {Any} The value to set
###
_setFieldValue: (data, field, value) ->
if data then data[field] = value;
###
Verify if the collection is an edge collection
@param model [String] The model name to lookup
@return [Boolean] Return true if collection is edge false otherwise
###
_isEdge: (model) ->
modelClass = @getModelClass model
settings = modelClass.settings
return settings and settings.arangodb and settings.arangodb.edge || false
###
###
_getNameOfProperty: (model, p) ->
props = @getModelClass(model).properties
for key, prop of props
if prop[p] then return key else continue
return false
###
Get if the model has _id field
@param {String} model The model name to lookup
@return {String|Boolean} Return name of _id or false if model not has _id field
###
_fullIdName: (model) ->
@_getNameOfProperty model, '_id'
###
Get if the model has _from field
@param {String} model The model name to lookup
@return {String|Boolean} Return name of _from or false if model not has _from field
###
_fromName: (model) ->
@_getNameOfProperty model, '_from'
###
Get if the model has _to field
@param {String} model The model name to lookup
@return {String|Boolean} Return name of _to or false if model not has _to field
###
_toName: (model) ->
@_getNameOfProperty model, '_to'
###
Access a ArangoDB collection by model name
@param {String} model The model name
@return {*}
###
getCollection: (model) ->
if not @db then throw new Error('ArangoDB connection is not established')
collection = ArangoDBConnector.collection
if @_isEdge model then collection = ArangoDBConnector.edgeCollection
return @db[collection] @getCollectionName model
###
Converts the retrieved data from the database to JSON, based on the properties of a given model
@param {String} model The model name to look up the properties
@param {Object} [data] The data from DB
@return {Object} The converted data as an JSON Object
###
fromDatabase: (model, data) ->
return null if not data?
props = @getModelClass(model).properties
for key, val of props
#Buffer type
if data[key]? and val? and val.type is Buffer
data[key] = new Buffer(data[key])
# Date
if data[key]? and val? and val.type is Date
data[key] = new Date data[key]
# GeoPoint
if data[key]? and val? and val.type and val.type.name is 'GeoPoint'
console.warn('GeoPoint is not supported by connector');
return data
###
Execute a ArangoDB command
###
execute: (model, command) ->
#Get the parameters for the given command
args = [].slice.call(arguments, 2);
#The last argument must be a callback function
callback = args[args.length - 1];
context =
req:
command: command
params: args
@notifyObserversAround 'execute', context, (context, done) =>
debug 'ArangoDB: model=%s command=%s', model, command, args if @debug
args[args.length - 1] = (err, result) ->
if err
debug('Error: ', err);
if err.code
err.statusCode = err.code
err.response? delete err.response
else
context.res = result;
debug('Result: ', result)
done(err, result);
if command is 'query'
query = context.req.params[0]
bindVars = context.req.params[1]
if @debug
if typeof query.toAQL is 'function'
q = query.toAQL()
else
q = query
debug "query: #{q} bindVars: #{JSON.stringify bindVars}"
@db.query.apply @db, args
else
collection = @getCollection model
collection[command].apply collection, args
, callback
###
Get the version of the ArangoDB
@param callback [Function] The callback function
@callback callback
@param {Error} err The error object
@param {String} version The arangoDB version
###
getVersion: (callback) ->
if @version?
callback null, @version
else
@api.get 'version', (err, result) =>
callback err if err
@version = result.body
callback null, @version
###
Create a new model instance for the given data
@param {String} model The model name
@param {Object} data The data to create
@param {Object} options The data to create
@param callback [Function] The callback function
###
create: (model, data, options, callback) ->
debug "create model #{model} with data: #{JSON.stringify data}" if @debug
idValue = @getIdValue model, data
idName = @idName model
if !idValue? or typeof idValue is 'undefined'
delete data[idName]
else
id = @getDefaultIdType() idValue
data._key = id
if idName isnt '_key' then delete data[idName]
# Check and delete full id name if present
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
isEdge = @_isEdge model
fromName = null
toName = null
if isEdge
fromName = @_fromName model
data._from = data[fromName]
if fromName isnt '_from'
data._from = data[fromName]
delete data[fromName]
toName = @_toName model
if toName isnt '_to'
data._to = data[toName]
delete data[toName]
@execute model, 'save', data, (err, result) =>
if err
# Change message error to pass junit test
if err.errorNum is 1210 then err.message = '/duplicate/i'
return callback(err)
# Save _key and _id value
idValue = @coerceId model, result._key
delete data._key
data[idName] = idValue;
if isEdge
if fromName isnt '_from' then data[fromName] = data._from
if toName isnt '_to' then data[toName] = data._to
if fullIdName
data[fullIdName] = result._id
delete result._id
callback err, idValue
###
Update if the model instance exists with the same id or create a new instance
@param model [String] The model name
@param data [Object] The model instance data
@param options [Object] The options
@param callback [Function] The callback function, called with a (possible) error object and updated or created object
###
updateOrCreate: (model, data, options, callback) ->
debug "updateOrCreate for Model #{model} with data: #{JSON.stringify data}" if @debug
idValue = @getIdValue(model, data)
idName = @idName(model)
idValue = @getDefaultIdType() idValue if typeof idValue is 'number'
delete data[idName]
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
isEdge = @_isEdge model
fromName = null
toName = null
if isEdge
fromName = @_fromName model
if fromName isnt '_from'
data._from = data[fromName]
delete data[fromName]
toName = @_toName model
if toName isnt '_to'
data._to = data[toName]
delete data[toName]
dataI = _.clone(data)
dataI._key = idValue
aql = qb.upsert({_key: <KEY>'}).insert('@dataI').update('@data').in('@@collection').let('isNewInstance',
qb.ref('OLD').then(false).else(true)).return({doc: 'NEW', isNewInstance: 'isNewInstance'});
bindVars =
'@collection': @getCollectionName model
id: idValue
dataI: dataI
data: data
@execute model, 'query', aql, bindVars, (err, result) =>
if result and result._result[0]
newDoc = result._result[0].doc
# Delete revision
delete newDoc._rev
if fullIdName
data[fullIdName] = newDoc._id
if fullIdName isnt '_id' then delete newDoc._id
else
delete newDoc._id
if isEdge
if fromName isnt '_from' then data[fromName] = data._from
if toName isnt '_to' then data[toName] = data._to
isNewInstance = { isNewInstance: result._result[0].isNewInstance }
@setIdValue(model, data, newDoc._key)
@setIdValue(model, newDoc, newDoc._key)
if idName isnt '_key' then delete newDoc._key
callback err, newDoc, isNewInstance
###
Save the model instance for the given data
@param model [String] The model name
@param data [Object] The updated data to save or create
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and the number of affected objects
###
save: @::updateOrCreate
###
Check if a model instance exists by id
@param model [String] The model name
@param id [String] The id value
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and an boolean value if the specified object existed (true) or not (false)
###
exists: (model, id, options, callback) ->
debug "exists for #{model} with id: #{id}" if @debug
@find model, id, options, (err, result) ->
return callback err if err
callback null, result.length > 0
###
Find a model instance by id
@param model [String] model The model name
@param id [String] id The id value
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and the found object
###
find: (model, id, options, callback) ->
debug "find for #{model} with id: #{id}" if @debug
command = 'document'
if @_isEdge model then command = 'edge'
@execute model, command, id, (err, result) ->
return callback err if err
callback null, result
###
Extracts where relevant information from the filter for a certain model
@param [String] model The model name
@param [Object] filter The filter object, also containing the where conditions
@param [Sequence] sequence The sequence instance used to generate random bind vars
@return return [Object]
@option return aqlArray [Array] The issued conditions as an array of AQL query builder objects
@option return bindVars [Object] The variables, bound in the conditions
@option return geoObject [Object] An query builder object containing possible parameters for a geo query
###
_buildWhere: (model, where, sequence) ->
debug "Evaluating where object #{JSON.stringify where} for Model #{model}" if @debug
if !where? or typeof where isnt 'object'
return
# array holding the filter
aqlArray = []
# the object holding the assignments of conditional values to temporary variables
bindVars = {}
geoExpr = {}
# index for condition parameter binding
sequence = sequence or new Sequence
# helper function to fill bindVars with the upcoming temporary variables that the where sentence will generate
assignNewQueryVariable = (value) ->
partName = 'param_' + sequence.next()
bindVars[partName] = value
return '@' + partName
idName = @idName model
fullIdName = @_fullIdName model
fromName = @_fromName model
toName = @_toName model
###
the where object comes in two flavors
- where[prop] = value: this is short for "prop" equals "value"
- where[prop][op] = value: this is the long version and stands for "prop" "op" "value"
###
for condProp, condValue of where
do() =>
# special treatment for 'and', 'or' and 'nor' operator, since there value is an array of conditions
if condProp in ['and', 'or', 'nor']
# 'and', 'or' and 'nor' have multiple conditions so we run buildWhere recursively on their array to
if Array.isArray condValue
aql = qb
# condValue is an array of conditions so get the conditions from it via a recursive buildWhere call
for c, a of condValue
cond = @_buildWhere model, a, sequence
aql = aql[condProp] cond.aqlArray[0]
bindVars = merge true, bindVars, cond.bindVars
aqlArray.push aql
aql = null
return
# correct if the conditionProperty falsely references to 'id'
if condProp is idName
condProp = '_key'
if typeof condValue is 'number' then condValue = String(condValue)
if condProp is fullIdName
condProp = '_id'
if condProp is fromName
condProp = '_from'
if condProp is toName
condProp = '_to'
# special case: if condValue is a Object (instead of a string or number) we have a conditionOperator
if condValue and condValue.constructor.name is 'Object'
# condition operator is the only keys value, the new condition value is shifted one level deeper and can be a object with keys and values
options = condValue.options
condOp = Object.keys(condValue)[0]
condValue = condValue[condOp]
if condOp
# If the value is not an array, fall back to regular fields
switch
when condOp in ['lte', 'lt']
tempAql = qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
# https://docs.arangodb.com/2.8/Aql/Basics.html#type-and-value-order
if condValue isnt null
tempAql = tempAql.and qb['neq'] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(null)}"
aqlArray.push(tempAql)
when condOp in ['gte', 'gt']
# https://docs.arangodb.com/2.8/Aql/Basics.html#type-and-value-order
if condValue is null
if condOp is 'gte' then condOp = 'lte'
if condOp is 'gt' then condOp = 'lt'
aqlArray.push qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(null)}"
else
aqlArray.push qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
when condOp in ['eq', 'neq']
aqlArray.push qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
# range comparison
when condOp is 'between'
tempAql = qb.gte "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue[0])}"
tempAql = tempAql.and qb.lte "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue[1])}"
aqlArray.push(tempAql)
# string comparison
when condOp is 'like'
if options is 'i' then options = true else options = false
aqlArray.push qb.fn('LIKE') "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}", options
when condOp is 'nlike'
if options is 'i' then options = true else options = false
aqlArray.push qb.not qb.fn('LIKE') "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}", options
# array comparison
when condOp is 'nin'
if _isReservedKey condProp
condValue = (value.toString() for value in condValue)
aqlArray.push qb.not qb.in "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
when condOp is 'inq'
if _isReservedKey condProp
condValue = (value.toString() for value in condValue)
aqlArray.push qb.in "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
# geo comparison (extra object)
when condOp is 'near'
# 'near' does not create a condition in the filter part, it returnes the lat/long pair
# the query will be done from the querying method itself
[lat, long] = condValue.split(',')
collection = @getCollectionName model
if where.limit?
geoExpr = qb.NEAR collection, lat, long, where.limit
else
geoExpr = qb.NEAR collection, lat, long
# if we don't have a matching operator or no operator at all (condOp = false) print warning
else
console.warn 'No matching operator for : ', condOp
else
aqlArray.push qb.eq "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
return {
aqlArray: aqlArray
bindVars: bindVars
geoExpr: geoExpr
}
###
Find matching model instances by the filter
@param [String] model The model name
@param [Object] filter The filter
@param options [Object]
@param [Function] callback Callback with (possible) error object or list of objects
###
all: (model, filter, options, callback) ->
debug "all for #{model} with filter #{JSON.stringify filter}" if @debug
idName = @idName model
fullIdName = @_fullIdName model
fromName = @_fromName model
toName = @_toName model
bindVars =
'@collection': @getCollectionName model
aql = qb.for(returnVariable).in('@@collection')
if filter.where
where = @_buildWhere(model, filter.where)
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
if filter.order
if typeof filter.order is 'string' then filter.order = filter.order.split(',')
for order in filter.order
m = order.match(/\s+(A|DE)SC$/)
field = order.replace(/\s+(A|DE)SC$/, '').trim()
if field in [idName, fullIdName, fromName, toName]
switch field
when idName then field = '_key'
when fullIdName then field = '_id'
when fromName then field = '_from'
when toName then field = '_to'
if m and m[1] is 'DE'
aql = aql.sort(returnVariable + '.' + field, 'DESC')
else
aql = aql.sort(returnVariable + '.' + field, 'ASC')
else if not @settings.disableDefaultSortByKey
aql = aql.sort(returnVariable + '._key')
if filter.limit
aql = aql.limit(filter.skip, filter.limit)
fields = _.clone(filter.fields)
if fields
indexId = fields.indexOf(idName)
if indexId isnt -1
fields[indexId] = '_key'
indexFullId = fields.indexOf(fullIdName)
if indexFullId isnt -1
fields[indexFullId] = '_id'
indexFromName = fields.indexOf(fromName)
if indexFromName isnt -1
fields[indexFromName] = '_from'
indexToName = fields.indexOf(toName)
if indexToName isnt -1
fields[indexToName] = '_to'
fields = ( '"' + field + '"' for field in fields)
aql = aql.return(qb.fn('KEEP') returnVariable, fields)
else
aql = aql.return((qb.fn('UNSET') returnVariable, ['"_rev"']))
@execute model, 'query', aql, bindVars, (err, cursor) =>
return callback err if err
cursorToArray = (r) =>
if _fieldIncluded filter.fields, idName
@setIdValue model, r, r._key
# Don't pass back _key if the fields is set
if idName isnt '_key' then delete r._key;
if fullIdName
if _fieldIncluded filter.fields, fullIdName
@_setFieldValue r, fullIdName, r._id
if fullIdName isnt '_id' and idName isnt '_id' then delete r._id
else
if idName isnt '_id' then delete r._id
if @_isEdge model
if _fieldIncluded filter.fields, fromName
@_setFieldValue r, fromName, r._from
if fromName isnt '_from' then delete r._from
if _fieldIncluded filter.fields, toName
@_setFieldValue r, toName, r._to
if toName isnt '_to' then delete r._to
r = @fromDatabase(model, r)
cursor.map cursorToArray, (err, result) =>
return callback err if err
# filter include
if filter.include?
@_models[model].model.include result, filter.include, options, callback
else
callback null, result
###
Delete a model instance by id
@param model [String] model The model name
@param id [String] id The id value
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and the number of affected objects
###
destroy: (model, id, options, callback) ->
debug "delete for #{model} with id #{id}" if @debug
@execute model, 'remove', id, (err, result) ->
# Set error to null if API response is `document not found`
if err and err.errorNum is 1202 then err = null
callback and callback err, {count: if result and !result.error then 1 else 0}
###
Delete all instances for the given model
@param [String] model The model name
@param [Object] [where] The filter for where
@param options [Object]
@param [Function] callback Callback with (possible) error object or the number of affected objects
###
destroyAll: (model, where, options, callback) ->
debug "destroyAll for #{model} with where #{JSON.stringify where}" if @debug
if !callback && typeof where is 'function'
callback = where
where = undefined
collection = @getCollectionName model
bindVars =
'@collection': collection
aql = qb.for(returnVariable).in('@@collection')
if !_.isEmpty(where)
where = @_buildWhere model, where
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
aql = aql.remove(returnVariable).in('@@collection')
@execute model, 'query', aql, bindVars, (err, result) ->
if callback
return callback err if err
callback null, {count: result.extra.stats.writesExecuted}
###
Count the number of instances for the given model
@param [String] model The model name
@param [Function] callback Callback with (possible) error object or the number of affected objects
@param [Object] where The filter for where
###
count: (model, where, options, callback) ->
debug "count for #{model} with where #{JSON.stringify where}" if @debug
collection = @getCollectionName model
bindVars =
'@collection': collection
aql = qb.for(returnVariable).in('@@collection')
if !_.isEmpty(where)
where = @_buildWhere model, where
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
aql = aql.collectWithCountInto(returnVariable).return(returnVariable)
@execute model, 'query', aql, bindVars, (err, result) ->
return callback err if err
callback null, result._result[0]
###
Update properties for the model instance data
@param [String] model The model name
@param [String] id The models id
@param [Object] data The model data
@param [Object] options
@param [Function] callback Callback with (possible) error object or the updated object
###
updateAttributes: (model, id, data, options, callback) ->
debug "updateAttributes for #{model} with id #{id} and data #{JSON.stringify data}" if @debug
id = @getDefaultIdType() id
idName = @idName(model)
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
isEdge = @_isEdge model
fromName = null
toName = null
if isEdge
fromName = @_fromName model
delete data[fromName]
toName = @_toName model
delete data[toName]
@execute model, 'update', id, data, options, (err, result) =>
if result
delete result['_rev']
if idName isnt '_key' then delete result._key;
@setIdValue(model, result, id);
if fullIdName
fullIdValue = result._id
delete result._id
result[fullIdName] = fullIdValue;
if isEdge
result[fromName] = data._from
result[toName] = data._to
callback and callback err, result
###
Update matching instance
@param [String] model The model name
@param [Object] where The search criteria
@param [Object] data The property/value pairs to be updated
@param [Object] options
@param [Function] callback Callback with (possible) error object or the number of affected objects
###
update: (model, where, data, options, callback) ->
debug "updateAll for #{model} with where #{JSON.stringify where} and data #{JSON.stringify data}" if @debug
collection = @getCollectionName model
bindVars =
'@collection': collection
data: data
aql = qb.for(returnVariable).in('@@collection')
if where
where = @_buildWhere(model, where)
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
aql = aql.update(returnVariable).with('@data').in('@@collection')
# _id, _key _from and _to are are immutable once set and cannot be updated
idName = @idName(model)
delete data[idName]
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
if @_isEdge model
fromName = @_fromName model
delete data[fromName]
toName = @_toName model
delete data[toName]
@execute model, 'query', aql, bindVars, (err, result) ->
return callback err if err
callback null, {count: result.extra.stats.writesExecuted}
###
Update all matching instances
###
updateAll: @::update
###
Perform autoupdate for the given models. It basically calls ensureIndex
@param [String[]] [models] A model name or an array of model names. If not present, apply to all models
@param [Function] [cb] The callback function
###
autoupdate: (models, cb) ->
if @db
debug 'autoupdate for model %s', models if @debug
if (not cb) and (typeof models is 'function')
cb = models
models = undefined
# First argument is a model name
models = [models] if typeof models is 'string'
models = models or Object.keys @_models
async.each( models, ((model, modelCallback) =>
indexes = @_models[model].settings.indexes or []
indexList = []
index = {}
options = {}
if typeof indexes is 'object'
for indexName, index of indexes
if index.keys
# the index object has keys
options = index.options or {}
options.name = options.name or indexName
index.options = options
else
options =
name: indexName
index =
keys: index
options: options
indexList.push index
else if Array.isArray indexes
indexList = indexList.concat indexes
for propIdx, property of @_models[model].properties
if property.index
index = {}
index[propIdx] = 1
if typeof property.index is 'object'
# If there is a arangodb key for the index, use it
if typeof property.index.arangodb is 'object'
options = property.index.arangodb
index[propIdx] = options.kind or 1
# Backwards compatibility for former type of indexes
options.unique = true if property.index.uniqe is true
else
# If there isn't an properties[p].index.mongodb object, we read the properties from properties[p].index
options = property.index
options.background = true if options.background is undefined
# If properties[p].index isn't an object we hardcode the background option and check for properties[p].unique
else
options =
background: true
options.unique = true if property.unique
indexList.push {keys: index, options: options}
debug 'create indexes' if @debug
async.each( indexList, ((index, indexCallback) =>
debug 'createIndex: %s', index if @debug
collection = @getCollection model
collection.createIndex(index.fields || index.keys, index.options, indexCallback);
), modelCallback )
), cb)
else
@dataSource.once 'connected', () -> @autoupdate models, cb
###
Perform automigrate for the given models. It drops the corresponding collections and calls ensureIndex
@param [String[]] [models] A model name or an array of model names. If not present, apply to all models
@param [Function] [cb] The callback function
###
automigrate: (models, cb) ->
if @db
debug "automigrate for model #{models}" if @debug
if (not cb) and (typeof models is 'function')
cb = models
models = undefined
# First argument is a model name
models = [models] if typeof models is 'string'
models = models || Object.keys @_models
async.eachSeries(models, ((model, modelCallback) =>
collectionName = @getCollectionName model
debug 'drop collection %s for model %s', collectionName, model
collection = @getCollection model
collection.drop (err) =>
if err
if err.response.body?
err = err.response.body
# For errors other than 'collection not found'
isCollectionNotFound = err.error is true and err.errorNum is 1203 and
(err.errorMessage is 'unknown collection \'' + model + '\'' or err.errorMessage is 'collection not found')
return modelCallback err if not isCollectionNotFound
# Recreate the collection
debug 'create collection %s for model %s', collectionName, model
collection.create modelCallback
), ((err) =>
return cb and cb err
@autoupdate models, cb
))
else
@dataSource.once 'connected', () -> @automigrate models cb
exports.ArangoDBConnector = ArangoDBConnector
| true | # node modules
# Module dependencies
arangojs = require 'arangojs'
qb = require 'aqb'
url = require 'url'
merge = require 'extend'
async = require 'async'
_ = require 'underscore'
Connector = require('loopback-connector').Connector
debug = require('debug') 'loopback:connector:arango'
###
Generate the arangodb URL from the options
###
exports.generateArangoDBURL = generateArangoDBURL = (settings) ->
u = {}
u.protocol = settings.protocol or 'http:'
u.hostname = settings.hostname or settings.host or '127.0.0.1'
u.port = settings.port or 8529
u.auth = "#{settings.username}:#{settings.password}" if settings.username and settings.password
settings.databaseName = settings.database or settings.db or '_system'
return url.format u
###
Check if field should be included
@param {Object} fields
@param {String} fieldName
@returns {Boolean}
@private
###
_fieldIncluded = (fields, fieldName) ->
if not fields then return true
if Array.isArray fields
return fields.indexOf fieldName >= 0
if fields[fieldName]
# Included
return true
if fieldName in fields and !fields[fieldName]
# Excluded
return false
for f in fields
return !fields[f]; # If the fields has exclusion
return true
###
Verify if a field is a reserved arangoDB key
@param {String} key The name of key to verify
@returns {Boolean}
@private
###
_isReservedKey = (key) ->
key in ['_key', '_PI:KEY:<KEY>END_PI', '_PI:KEY:<KEY>END_PI', '_PI:KEY:<KEY>END_PI', '_to']
class Sequence
constructor: (start) ->
@nextVal = start or 0
next: () ->
return @nextVal++;
###
Initialize the ArangoDB connector for the given data source
@param {DataSource} dataSource The data source instance
@param {Function} [callback] The callback function
###
exports.initialize = initializeDataSource = (dataSource, callback) ->
return if not arangojs
s = dataSource.settings
s.url = s.url or generateArangoDBURL s
dataSource.connector = new ArangoDBConnector s, dataSource
dataSource.connector.connect callback if callback?
###
Loopback ArangoDB Connector
@extend Connector
###
class ArangoDBConnector extends Connector
returnVariable = 'result'
@collection = 'collection'
@edgeCollection = 'edgeCollection'
@returnVariable = 'result'
###
The constructor for ArangoDB connector
@param {Object} settings The settings object
@param {DataSource} dataSource The data source instance
@constructor
###
constructor: (settings, dataSource) ->
super 'arangodb', settings
# debug
@debug = dataSource.settings.debug or debug.enabled
# link to datasource
@dataSource = dataSource
# Arango Query Builder
# TODO MAJOR rename to aqb
@qb = qb
###
Connect to ArangoDB
@param {Function} [callback] The callback function
@callback callback
@param {Error} err The error object
@param {Db} db The arangoDB object
###
connect: (callback) ->
debug "ArangoDB connection is called with settings: #{JSON.stringify @settings}" if @debug
if not @db
@db = arangojs @settings
@api = @db.route '/_api'
process.nextTick () =>
callback null, @db if callback
###
Get the types of this connector
@return {Array<String>} The types of connector
###
getTypes: () ->
return ['db', 'nosql', 'arangodb']
###
The default Id type
@return {String} The type of id value
###
getDefaultIdType: () ->
return String
###
Get the model class for a certain model name
@param {String} model The model name to lookup
@return {Object} The model class of this model
###
getModelClass: (model) ->
return @_models[model]
###
Get the collection name for a certain model name
@param {String} model The model name to lookup
@return {Object} The collection name for this model
###
getCollectionName: (model) ->
modelClass = @getModelClass model
if modelClass.settings and modelClass.settings.arangodb
model = modelClass.settings.arangodb.collection or model
return model
###
Coerce the id value
###
coerceId: (model, id) ->
return id if not id?
idValue = id;
idName = @idName model
# Type conversion for id
idProp = @getPropertyDefinition model, idName
if idProp && typeof idProp.type is 'function'
if not (idValue instanceof idProp.type)
idValue = idProp.type id
# Reset to id
if idProp.type is Number and isNaN id then idValue = id
return idValue;
###
Set value of specific field into data object
@param data {Object} The data object
@param field {String} The name of field to set
@param value {Any} The value to set
###
_setFieldValue: (data, field, value) ->
if data then data[field] = value;
###
Verify if the collection is an edge collection
@param model [String] The model name to lookup
@return [Boolean] Return true if collection is edge false otherwise
###
_isEdge: (model) ->
modelClass = @getModelClass model
settings = modelClass.settings
return settings and settings.arangodb and settings.arangodb.edge || false
###
###
_getNameOfProperty: (model, p) ->
props = @getModelClass(model).properties
for key, prop of props
if prop[p] then return key else continue
return false
###
Get if the model has _id field
@param {String} model The model name to lookup
@return {String|Boolean} Return name of _id or false if model not has _id field
###
_fullIdName: (model) ->
@_getNameOfProperty model, '_id'
###
Get if the model has _from field
@param {String} model The model name to lookup
@return {String|Boolean} Return name of _from or false if model not has _from field
###
_fromName: (model) ->
@_getNameOfProperty model, '_from'
###
Get if the model has _to field
@param {String} model The model name to lookup
@return {String|Boolean} Return name of _to or false if model not has _to field
###
_toName: (model) ->
@_getNameOfProperty model, '_to'
###
Access a ArangoDB collection by model name
@param {String} model The model name
@return {*}
###
getCollection: (model) ->
if not @db then throw new Error('ArangoDB connection is not established')
collection = ArangoDBConnector.collection
if @_isEdge model then collection = ArangoDBConnector.edgeCollection
return @db[collection] @getCollectionName model
###
Converts the retrieved data from the database to JSON, based on the properties of a given model
@param {String} model The model name to look up the properties
@param {Object} [data] The data from DB
@return {Object} The converted data as an JSON Object
###
fromDatabase: (model, data) ->
return null if not data?
props = @getModelClass(model).properties
for key, val of props
#Buffer type
if data[key]? and val? and val.type is Buffer
data[key] = new Buffer(data[key])
# Date
if data[key]? and val? and val.type is Date
data[key] = new Date data[key]
# GeoPoint
if data[key]? and val? and val.type and val.type.name is 'GeoPoint'
console.warn('GeoPoint is not supported by connector');
return data
###
Execute a ArangoDB command
###
execute: (model, command) ->
#Get the parameters for the given command
args = [].slice.call(arguments, 2);
#The last argument must be a callback function
callback = args[args.length - 1];
context =
req:
command: command
params: args
@notifyObserversAround 'execute', context, (context, done) =>
debug 'ArangoDB: model=%s command=%s', model, command, args if @debug
args[args.length - 1] = (err, result) ->
if err
debug('Error: ', err);
if err.code
err.statusCode = err.code
err.response? delete err.response
else
context.res = result;
debug('Result: ', result)
done(err, result);
if command is 'query'
query = context.req.params[0]
bindVars = context.req.params[1]
if @debug
if typeof query.toAQL is 'function'
q = query.toAQL()
else
q = query
debug "query: #{q} bindVars: #{JSON.stringify bindVars}"
@db.query.apply @db, args
else
collection = @getCollection model
collection[command].apply collection, args
, callback
###
Get the version of the ArangoDB
@param callback [Function] The callback function
@callback callback
@param {Error} err The error object
@param {String} version The arangoDB version
###
getVersion: (callback) ->
if @version?
callback null, @version
else
@api.get 'version', (err, result) =>
callback err if err
@version = result.body
callback null, @version
###
Create a new model instance for the given data
@param {String} model The model name
@param {Object} data The data to create
@param {Object} options The data to create
@param callback [Function] The callback function
###
create: (model, data, options, callback) ->
debug "create model #{model} with data: #{JSON.stringify data}" if @debug
idValue = @getIdValue model, data
idName = @idName model
if !idValue? or typeof idValue is 'undefined'
delete data[idName]
else
id = @getDefaultIdType() idValue
data._key = id
if idName isnt '_key' then delete data[idName]
# Check and delete full id name if present
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
isEdge = @_isEdge model
fromName = null
toName = null
if isEdge
fromName = @_fromName model
data._from = data[fromName]
if fromName isnt '_from'
data._from = data[fromName]
delete data[fromName]
toName = @_toName model
if toName isnt '_to'
data._to = data[toName]
delete data[toName]
@execute model, 'save', data, (err, result) =>
if err
# Change message error to pass junit test
if err.errorNum is 1210 then err.message = '/duplicate/i'
return callback(err)
# Save _key and _id value
idValue = @coerceId model, result._key
delete data._key
data[idName] = idValue;
if isEdge
if fromName isnt '_from' then data[fromName] = data._from
if toName isnt '_to' then data[toName] = data._to
if fullIdName
data[fullIdName] = result._id
delete result._id
callback err, idValue
###
Update if the model instance exists with the same id or create a new instance
@param model [String] The model name
@param data [Object] The model instance data
@param options [Object] The options
@param callback [Function] The callback function, called with a (possible) error object and updated or created object
###
updateOrCreate: (model, data, options, callback) ->
debug "updateOrCreate for Model #{model} with data: #{JSON.stringify data}" if @debug
idValue = @getIdValue(model, data)
idName = @idName(model)
idValue = @getDefaultIdType() idValue if typeof idValue is 'number'
delete data[idName]
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
isEdge = @_isEdge model
fromName = null
toName = null
if isEdge
fromName = @_fromName model
if fromName isnt '_from'
data._from = data[fromName]
delete data[fromName]
toName = @_toName model
if toName isnt '_to'
data._to = data[toName]
delete data[toName]
dataI = _.clone(data)
dataI._key = idValue
aql = qb.upsert({_key: PI:KEY:<KEY>END_PI'}).insert('@dataI').update('@data').in('@@collection').let('isNewInstance',
qb.ref('OLD').then(false).else(true)).return({doc: 'NEW', isNewInstance: 'isNewInstance'});
bindVars =
'@collection': @getCollectionName model
id: idValue
dataI: dataI
data: data
@execute model, 'query', aql, bindVars, (err, result) =>
if result and result._result[0]
newDoc = result._result[0].doc
# Delete revision
delete newDoc._rev
if fullIdName
data[fullIdName] = newDoc._id
if fullIdName isnt '_id' then delete newDoc._id
else
delete newDoc._id
if isEdge
if fromName isnt '_from' then data[fromName] = data._from
if toName isnt '_to' then data[toName] = data._to
isNewInstance = { isNewInstance: result._result[0].isNewInstance }
@setIdValue(model, data, newDoc._key)
@setIdValue(model, newDoc, newDoc._key)
if idName isnt '_key' then delete newDoc._key
callback err, newDoc, isNewInstance
###
Save the model instance for the given data
@param model [String] The model name
@param data [Object] The updated data to save or create
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and the number of affected objects
###
save: @::updateOrCreate
###
Check if a model instance exists by id
@param model [String] The model name
@param id [String] The id value
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and an boolean value if the specified object existed (true) or not (false)
###
exists: (model, id, options, callback) ->
debug "exists for #{model} with id: #{id}" if @debug
@find model, id, options, (err, result) ->
return callback err if err
callback null, result.length > 0
###
Find a model instance by id
@param model [String] model The model name
@param id [String] id The id value
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and the found object
###
find: (model, id, options, callback) ->
debug "find for #{model} with id: #{id}" if @debug
command = 'document'
if @_isEdge model then command = 'edge'
@execute model, command, id, (err, result) ->
return callback err if err
callback null, result
###
Extracts where relevant information from the filter for a certain model
@param [String] model The model name
@param [Object] filter The filter object, also containing the where conditions
@param [Sequence] sequence The sequence instance used to generate random bind vars
@return return [Object]
@option return aqlArray [Array] The issued conditions as an array of AQL query builder objects
@option return bindVars [Object] The variables, bound in the conditions
@option return geoObject [Object] An query builder object containing possible parameters for a geo query
###
_buildWhere: (model, where, sequence) ->
debug "Evaluating where object #{JSON.stringify where} for Model #{model}" if @debug
if !where? or typeof where isnt 'object'
return
# array holding the filter
aqlArray = []
# the object holding the assignments of conditional values to temporary variables
bindVars = {}
geoExpr = {}
# index for condition parameter binding
sequence = sequence or new Sequence
# helper function to fill bindVars with the upcoming temporary variables that the where sentence will generate
assignNewQueryVariable = (value) ->
partName = 'param_' + sequence.next()
bindVars[partName] = value
return '@' + partName
idName = @idName model
fullIdName = @_fullIdName model
fromName = @_fromName model
toName = @_toName model
###
the where object comes in two flavors
- where[prop] = value: this is short for "prop" equals "value"
- where[prop][op] = value: this is the long version and stands for "prop" "op" "value"
###
for condProp, condValue of where
do() =>
# special treatment for 'and', 'or' and 'nor' operator, since there value is an array of conditions
if condProp in ['and', 'or', 'nor']
# 'and', 'or' and 'nor' have multiple conditions so we run buildWhere recursively on their array to
if Array.isArray condValue
aql = qb
# condValue is an array of conditions so get the conditions from it via a recursive buildWhere call
for c, a of condValue
cond = @_buildWhere model, a, sequence
aql = aql[condProp] cond.aqlArray[0]
bindVars = merge true, bindVars, cond.bindVars
aqlArray.push aql
aql = null
return
# correct if the conditionProperty falsely references to 'id'
if condProp is idName
condProp = '_key'
if typeof condValue is 'number' then condValue = String(condValue)
if condProp is fullIdName
condProp = '_id'
if condProp is fromName
condProp = '_from'
if condProp is toName
condProp = '_to'
# special case: if condValue is a Object (instead of a string or number) we have a conditionOperator
if condValue and condValue.constructor.name is 'Object'
# condition operator is the only keys value, the new condition value is shifted one level deeper and can be a object with keys and values
options = condValue.options
condOp = Object.keys(condValue)[0]
condValue = condValue[condOp]
if condOp
# If the value is not an array, fall back to regular fields
switch
when condOp in ['lte', 'lt']
tempAql = qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
# https://docs.arangodb.com/2.8/Aql/Basics.html#type-and-value-order
if condValue isnt null
tempAql = tempAql.and qb['neq'] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(null)}"
aqlArray.push(tempAql)
when condOp in ['gte', 'gt']
# https://docs.arangodb.com/2.8/Aql/Basics.html#type-and-value-order
if condValue is null
if condOp is 'gte' then condOp = 'lte'
if condOp is 'gt' then condOp = 'lt'
aqlArray.push qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(null)}"
else
aqlArray.push qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
when condOp in ['eq', 'neq']
aqlArray.push qb[condOp] "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
# range comparison
when condOp is 'between'
tempAql = qb.gte "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue[0])}"
tempAql = tempAql.and qb.lte "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue[1])}"
aqlArray.push(tempAql)
# string comparison
when condOp is 'like'
if options is 'i' then options = true else options = false
aqlArray.push qb.fn('LIKE') "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}", options
when condOp is 'nlike'
if options is 'i' then options = true else options = false
aqlArray.push qb.not qb.fn('LIKE') "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}", options
# array comparison
when condOp is 'nin'
if _isReservedKey condProp
condValue = (value.toString() for value in condValue)
aqlArray.push qb.not qb.in "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
when condOp is 'inq'
if _isReservedKey condProp
condValue = (value.toString() for value in condValue)
aqlArray.push qb.in "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
# geo comparison (extra object)
when condOp is 'near'
# 'near' does not create a condition in the filter part, it returnes the lat/long pair
# the query will be done from the querying method itself
[lat, long] = condValue.split(',')
collection = @getCollectionName model
if where.limit?
geoExpr = qb.NEAR collection, lat, long, where.limit
else
geoExpr = qb.NEAR collection, lat, long
# if we don't have a matching operator or no operator at all (condOp = false) print warning
else
console.warn 'No matching operator for : ', condOp
else
aqlArray.push qb.eq "#{returnVariable}.#{condProp}", "#{assignNewQueryVariable(condValue)}"
return {
aqlArray: aqlArray
bindVars: bindVars
geoExpr: geoExpr
}
###
Find matching model instances by the filter
@param [String] model The model name
@param [Object] filter The filter
@param options [Object]
@param [Function] callback Callback with (possible) error object or list of objects
###
all: (model, filter, options, callback) ->
debug "all for #{model} with filter #{JSON.stringify filter}" if @debug
idName = @idName model
fullIdName = @_fullIdName model
fromName = @_fromName model
toName = @_toName model
bindVars =
'@collection': @getCollectionName model
aql = qb.for(returnVariable).in('@@collection')
if filter.where
where = @_buildWhere(model, filter.where)
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
if filter.order
if typeof filter.order is 'string' then filter.order = filter.order.split(',')
for order in filter.order
m = order.match(/\s+(A|DE)SC$/)
field = order.replace(/\s+(A|DE)SC$/, '').trim()
if field in [idName, fullIdName, fromName, toName]
switch field
when idName then field = '_key'
when fullIdName then field = '_id'
when fromName then field = '_from'
when toName then field = '_to'
if m and m[1] is 'DE'
aql = aql.sort(returnVariable + '.' + field, 'DESC')
else
aql = aql.sort(returnVariable + '.' + field, 'ASC')
else if not @settings.disableDefaultSortByKey
aql = aql.sort(returnVariable + '._key')
if filter.limit
aql = aql.limit(filter.skip, filter.limit)
fields = _.clone(filter.fields)
if fields
indexId = fields.indexOf(idName)
if indexId isnt -1
fields[indexId] = '_key'
indexFullId = fields.indexOf(fullIdName)
if indexFullId isnt -1
fields[indexFullId] = '_id'
indexFromName = fields.indexOf(fromName)
if indexFromName isnt -1
fields[indexFromName] = '_from'
indexToName = fields.indexOf(toName)
if indexToName isnt -1
fields[indexToName] = '_to'
fields = ( '"' + field + '"' for field in fields)
aql = aql.return(qb.fn('KEEP') returnVariable, fields)
else
aql = aql.return((qb.fn('UNSET') returnVariable, ['"_rev"']))
@execute model, 'query', aql, bindVars, (err, cursor) =>
return callback err if err
cursorToArray = (r) =>
if _fieldIncluded filter.fields, idName
@setIdValue model, r, r._key
# Don't pass back _key if the fields is set
if idName isnt '_key' then delete r._key;
if fullIdName
if _fieldIncluded filter.fields, fullIdName
@_setFieldValue r, fullIdName, r._id
if fullIdName isnt '_id' and idName isnt '_id' then delete r._id
else
if idName isnt '_id' then delete r._id
if @_isEdge model
if _fieldIncluded filter.fields, fromName
@_setFieldValue r, fromName, r._from
if fromName isnt '_from' then delete r._from
if _fieldIncluded filter.fields, toName
@_setFieldValue r, toName, r._to
if toName isnt '_to' then delete r._to
r = @fromDatabase(model, r)
cursor.map cursorToArray, (err, result) =>
return callback err if err
# filter include
if filter.include?
@_models[model].model.include result, filter.include, options, callback
else
callback null, result
###
Delete a model instance by id
@param model [String] model The model name
@param id [String] id The id value
@param options [Object]
@param callback [Function] The callback function, called with a (possible) error object and the number of affected objects
###
destroy: (model, id, options, callback) ->
debug "delete for #{model} with id #{id}" if @debug
@execute model, 'remove', id, (err, result) ->
# Set error to null if API response is `document not found`
if err and err.errorNum is 1202 then err = null
callback and callback err, {count: if result and !result.error then 1 else 0}
###
Delete all instances for the given model
@param [String] model The model name
@param [Object] [where] The filter for where
@param options [Object]
@param [Function] callback Callback with (possible) error object or the number of affected objects
###
destroyAll: (model, where, options, callback) ->
debug "destroyAll for #{model} with where #{JSON.stringify where}" if @debug
if !callback && typeof where is 'function'
callback = where
where = undefined
collection = @getCollectionName model
bindVars =
'@collection': collection
aql = qb.for(returnVariable).in('@@collection')
if !_.isEmpty(where)
where = @_buildWhere model, where
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
aql = aql.remove(returnVariable).in('@@collection')
@execute model, 'query', aql, bindVars, (err, result) ->
if callback
return callback err if err
callback null, {count: result.extra.stats.writesExecuted}
###
Count the number of instances for the given model
@param [String] model The model name
@param [Function] callback Callback with (possible) error object or the number of affected objects
@param [Object] where The filter for where
###
count: (model, where, options, callback) ->
debug "count for #{model} with where #{JSON.stringify where}" if @debug
collection = @getCollectionName model
bindVars =
'@collection': collection
aql = qb.for(returnVariable).in('@@collection')
if !_.isEmpty(where)
where = @_buildWhere model, where
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
aql = aql.collectWithCountInto(returnVariable).return(returnVariable)
@execute model, 'query', aql, bindVars, (err, result) ->
return callback err if err
callback null, result._result[0]
###
Update properties for the model instance data
@param [String] model The model name
@param [String] id The models id
@param [Object] data The model data
@param [Object] options
@param [Function] callback Callback with (possible) error object or the updated object
###
updateAttributes: (model, id, data, options, callback) ->
debug "updateAttributes for #{model} with id #{id} and data #{JSON.stringify data}" if @debug
id = @getDefaultIdType() id
idName = @idName(model)
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
isEdge = @_isEdge model
fromName = null
toName = null
if isEdge
fromName = @_fromName model
delete data[fromName]
toName = @_toName model
delete data[toName]
@execute model, 'update', id, data, options, (err, result) =>
if result
delete result['_rev']
if idName isnt '_key' then delete result._key;
@setIdValue(model, result, id);
if fullIdName
fullIdValue = result._id
delete result._id
result[fullIdName] = fullIdValue;
if isEdge
result[fromName] = data._from
result[toName] = data._to
callback and callback err, result
###
Update matching instance
@param [String] model The model name
@param [Object] where The search criteria
@param [Object] data The property/value pairs to be updated
@param [Object] options
@param [Function] callback Callback with (possible) error object or the number of affected objects
###
update: (model, where, data, options, callback) ->
debug "updateAll for #{model} with where #{JSON.stringify where} and data #{JSON.stringify data}" if @debug
collection = @getCollectionName model
bindVars =
'@collection': collection
data: data
aql = qb.for(returnVariable).in('@@collection')
if where
where = @_buildWhere(model, where)
for w in where.aqlArray
aql = aql.filter(w)
merge true, bindVars, where.bindVars
aql = aql.update(returnVariable).with('@data').in('@@collection')
# _id, _key _from and _to are are immutable once set and cannot be updated
idName = @idName(model)
delete data[idName]
fullIdName = @_fullIdName model
if fullIdName then delete data[fullIdName]
if @_isEdge model
fromName = @_fromName model
delete data[fromName]
toName = @_toName model
delete data[toName]
@execute model, 'query', aql, bindVars, (err, result) ->
return callback err if err
callback null, {count: result.extra.stats.writesExecuted}
###
Update all matching instances
###
updateAll: @::update
###
Perform autoupdate for the given models. It basically calls ensureIndex
@param [String[]] [models] A model name or an array of model names. If not present, apply to all models
@param [Function] [cb] The callback function
###
autoupdate: (models, cb) ->
if @db
debug 'autoupdate for model %s', models if @debug
if (not cb) and (typeof models is 'function')
cb = models
models = undefined
# First argument is a model name
models = [models] if typeof models is 'string'
models = models or Object.keys @_models
async.each( models, ((model, modelCallback) =>
indexes = @_models[model].settings.indexes or []
indexList = []
index = {}
options = {}
if typeof indexes is 'object'
for indexName, index of indexes
if index.keys
# the index object has keys
options = index.options or {}
options.name = options.name or indexName
index.options = options
else
options =
name: indexName
index =
keys: index
options: options
indexList.push index
else if Array.isArray indexes
indexList = indexList.concat indexes
for propIdx, property of @_models[model].properties
if property.index
index = {}
index[propIdx] = 1
if typeof property.index is 'object'
# If there is a arangodb key for the index, use it
if typeof property.index.arangodb is 'object'
options = property.index.arangodb
index[propIdx] = options.kind or 1
# Backwards compatibility for former type of indexes
options.unique = true if property.index.uniqe is true
else
# If there isn't an properties[p].index.mongodb object, we read the properties from properties[p].index
options = property.index
options.background = true if options.background is undefined
# If properties[p].index isn't an object we hardcode the background option and check for properties[p].unique
else
options =
background: true
options.unique = true if property.unique
indexList.push {keys: index, options: options}
debug 'create indexes' if @debug
async.each( indexList, ((index, indexCallback) =>
debug 'createIndex: %s', index if @debug
collection = @getCollection model
collection.createIndex(index.fields || index.keys, index.options, indexCallback);
), modelCallback )
), cb)
else
@dataSource.once 'connected', () -> @autoupdate models, cb
###
Perform automigrate for the given models. It drops the corresponding collections and calls ensureIndex
@param [String[]] [models] A model name or an array of model names. If not present, apply to all models
@param [Function] [cb] The callback function
###
automigrate: (models, cb) ->
if @db
debug "automigrate for model #{models}" if @debug
if (not cb) and (typeof models is 'function')
cb = models
models = undefined
# First argument is a model name
models = [models] if typeof models is 'string'
models = models || Object.keys @_models
async.eachSeries(models, ((model, modelCallback) =>
collectionName = @getCollectionName model
debug 'drop collection %s for model %s', collectionName, model
collection = @getCollection model
collection.drop (err) =>
if err
if err.response.body?
err = err.response.body
# For errors other than 'collection not found'
isCollectionNotFound = err.error is true and err.errorNum is 1203 and
(err.errorMessage is 'unknown collection \'' + model + '\'' or err.errorMessage is 'collection not found')
return modelCallback err if not isCollectionNotFound
# Recreate the collection
debug 'create collection %s for model %s', collectionName, model
collection.create modelCallback
), ((err) =>
return cb and cb err
@autoupdate models, cb
))
else
@dataSource.once 'connected', () -> @automigrate models cb
exports.ArangoDBConnector = ArangoDBConnector
|
[
{
"context": "###\nCopyright 2016 Resin.io\n\nLicensed under the Apache License, Version 2.0 (",
"end": 27,
"score": 0.5482524633407593,
"start": 25,
"tag": "NAME",
"value": "io"
}
] | lib/discoverable.coffee | balena-io-modules/resin-discoverable-services | 3 | ###
Copyright 2016 Resin.io
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.
###
Promise = require('bluebird')
fs = Promise.promisifyAll(require('fs'))
os = require('os')
ip = require('ip')
bonjour = require('bonjour')
_ = require('lodash')
# In priority order:
browserBackends = [
require('./backends/avahi')
require('./backends/native')
]
# Set the memoize cache as a Map so we can clear it should the service
# registry change.
_.memoize.Cache = Map
registryPath = "#{__dirname}/../services"
# List of published services. The bonjourInstance is initially uncreated, and
# is created either by the publishing of a service, or by finding a service.
# It *must* be cleaned up and destroyed before exiting a process to ensure
# bound sockets are removed.
publishInstance = null
###
# @summary Scans the registry path hierarchy to determine service types.
# @function
# @private
###
retrieveServices = ->
foundPaths = []
scanDirectory = (parentPath, localPath) ->
# Scan for directory names,
foundDirectories = []
fs.readdirAsync(parentPath)
.then (paths) ->
Promise.map paths, (path) ->
fs.statAsync("#{parentPath}/#{path}")
.then (stat) ->
if stat.isDirectory()
foundDirectories.push(path)
.then ->
if foundDirectories.length is 0
foundPaths.push(localPath)
else
# Prepend our path onto it
Promise.map foundDirectories, (path) ->
# Scan each of these
scanDirectory("#{parentPath}/#{path}", "#{localPath}/#{path}")
scanDirectory(registryPath, '')
.then ->
services = []
# Only depths of 2 or 3 levels are valid (subtype/type/protocol).
# Any incorrect depths are ignored, as we would prefer to retrieve the
# services if at all possible
Promise.map foundPaths, (path) ->
components = _.split(path, '/')
components.shift()
# Ignore any non-valid service structure
if (components.length >= 2 or components.length <= 3)
service = ''
tags = []
if components.length is 3
service = "_#{components[0]}._sub."
components.shift()
service += "_#{components[0]}._#{components[1]}"
fs.readFileAsync("#{registryPath}#{path}/tags.json", { encoding: 'utf8' })
.then (data) ->
json = JSON.parse(data)
if (not _.isArray(json))
throw new Error()
tags = json
.catch (err) ->
# If the tag file didn't exist, we silently fail.
if err.code isnt 'ENOENT'
throw new Error("tags.json for #{service} service defintion is incorrect")
.then ->
services.push({ service: service, tags: tags })
.return(services)
# Set the services function as a memoized one.
registryServices = _.memoize(retrieveServices)
###
# @summary Determines if a service is valid.
# @function
# @private
###
findValidService = (serviceIdentifier, knownServices) ->
_.find knownServices, ({ service, tags }) ->
serviceIdentifier in [ service, tags... ]
###
# @summary Retrieves information for a given services string.
# @function
# @private
###
determineServiceInfo = (service) ->
info = {}
types = service.service.match(/^(_(.*)\._sub\.)?_(.*)\._(.*)$/)
if not types[1]? and not types[2]?
info.subtypes = []
else
info.subtypes = [ types[2] ]
# We only try and find a service if the type is valid
if types[3]? and types[4]?
info.type = types[3]
info.protocol = types[4]
return info
###
# @summary Ensures valid network interfaces exist
# @function
# @private
###
hasValidInterfaces = ->
# We can continue so long as we have one interface, and that interface is not loopback.
_.some os.networkInterfaces(), (value) ->
_.some(value, internal: false)
###
# @summary Determine if a specified interface address for MDNS binding is a loopback interface
# @function
# @private
###
isLoopbackInterface = (address) ->
if ip.isV4Format(address)
family = 'IPv4'
else if ip.isV6Format(address)
family = 'IPv6'
else
return null
# Correctly format any IPv6 addresses so we find them.
foundIntf = _.find os.networkInterfaces(), (intfInfo) ->
_.find(intfInfo, address: address)
if not foundIntf? or not (validFamily = _.find(foundIntf, family: family)?.internal)?
return null
return validFamily
###
# @summary Sets the path which will be examined for service definitions.
# @function
# @public
#
# @description
# Should no parameter be passed, or this method not called, then the default
# path is the 'services' directory that exists within the module's directory
# hierarchy.
#
# @param {String} path - New path to use as the service registry.
#
# @example
# discoverableServices.setRegistryPath("/home/heds/discoverable_services")
###
exports.setRegistryPath = (path) ->
if not path?
path = "#{__dirname}/../services"
if not _.isString(path)
throw new Error('path parameter must be a path string')
registryPath = path
registryServices.cache.clear()
###
# @summary Enumerates all currently registered services available for discovery.
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted.
#
# @param {Function} callback - callback (error, services)
#
# @example
# discoverableServices.enumerateServices (error, services) ->
# throw error if error?
# # services is an array of service objects holding type/subtype and any tagnames associated with them
# console.log(services)
###
exports.enumerateServices = (callback) ->
registryServices()
.asCallback(callback)
###
# @summary Listens for all locally published services, returning information on them after a period of time.
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted. Should the timeout value be missing
# then a default timeout of 2000ms is used.
#
# @param {Array} services - A string array of service identifiers or tags
# @param {Number} timeout - A timeout in milliseconds before results are returned. Defaults to 2000ms
# @param {Function} callback - callback (error, services)
#
# @example
# discoverableServices.findServices([ '_resin-device._sub._ssh._tcp' ], 5000, (error, services) ->
# throw error if error?
# # services is an array of every service that conformed to the specified search parameters
# console.log(services)
###
exports.findServices = Promise.method (services, timeout, callback) ->
# Check parameters.
if not timeout?
timeout = 2000
else
if not _.isNumber(timeout)
throw new Error('timeout parameter must be a number value in milliseconds')
if not _.isArray(services)
throw new Error('services parameter must be an array of service name strings')
# Perform the bonjour service lookup and return any results after the timeout period
# Do this on all available, valid NICS.
nics = os.networkInterfaces()
findInstances = []
_.each nics, (nic) ->
_.each nic, (addr) ->
if (addr.family == 'IPv4') and (addr.internal == false)
findInstances.push(bonjour({ interface: addr.address }))
createBrowser = (serviceIdentifier, subtypes, type, protocol) ->
new Promise (resolve) ->
foundServices = []
browsers = []
_.each findInstances, (findInstance) ->
browsers.push findInstance.find { type: type, subtypes: subtypes, protocol: protocol }, (service) ->
# Because we spin up a new search for each subtype, we don't
# need to update records here. Any valid service is unique.
service.service = serviceIdentifier
foundServices.push(service)
setTimeout( ->
_.each browsers, (browser) ->
browser.stop()
resolve(_.uniqBy(foundServices, (service) -> service.fqdn))
, timeout)
# Get the list of registered services.
registryServices()
.then (validServices) ->
serviceBrowsers = []
services.forEach (service) ->
if (registeredService = findValidService(service, validServices))?
serviceDetails = determineServiceInfo(registeredService)
if serviceDetails.type? and serviceDetails.protocol?
# Build a browser, set a timeout and resolve once that
# timeout has finished
serviceBrowsers.push(createBrowser registeredService.service,
serviceDetails.subtypes, serviceDetails.type, serviceDetails.protocol
)
Promise.all serviceBrowsers
.then (services) ->
services = _.flatten(services)
_.remove(services, (entry) -> entry == null)
return services
.finally ->
_.each findInstances, (instance) ->
instance.destroy()
.asCallback(callback)
getServiceBrowser = (timeout) ->
Promise.filter browserBackends, (backend) ->
backend.isAvailable()
.then (availableBackends) ->
if availableBackends.length == 0
throw new Error('No backends available for service discovery')
return availableBackends[0].get(timeout)
###
# @summary Publishes all available services
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted.
# Note that it is vital that any published services are unpublished during exit of the process using `unpublishServices()`.
# Should an `mdnsInterface` property be set in the `services` object and pertain to a loopback device, then loopback for multicast will automatically be enabled.
#
# @param {Array} services - An object array of service details. Each service object is comprised of:
# @param {String} services.identifier - A string of the service identifier or an associated tag
# @param {String} services.name - A string of the service name to advertise as
# @param {String} services.host - A specific hostname that will be used as the host (useful for proxying or psuedo-hosting). Defaults to current host name should none be given
# @param {Number} services.port - The port on which the service will be advertised
# @param {Object} options - An options object for passing publishing options:
# @param {String} options.mdnsInterface - The IPv4 or IPv6 address of a current valid interface with which to bind the MDNS service to (if unset, first available interface).
#
# @example
# discoverableServices.publishServices([ { service: '_resin-device._sub._ssh._tcp', host: 'server1.local', port: 9999 } ])
###
exports.publishServices = Promise.method (services, options, callback) ->
if not _.isArray(services)
throw new Error('services parameter must be an array of service objects')
# If we have a specific interface to bind multicast to, we need to determine if loopback
# should be set (if we can't find the address, we bail)
if not options?.mdnsInterface? and not hasValidInterfaces()
throw new Error('At least one non-loopback interface must be present to bind to')
else if options?.mdnsInterface?
loopbackInterface = isLoopbackInterface(options.mdnsInterface)
if not loopbackInterface?
throw new Error('The specified MDNS interface address is not valid')
# Get the list of registered services.
registryServices()
.then (validServices) ->
services.forEach (service) ->
if service.identifier? and service.name? and (registeredService = findValidService(service.identifier, validServices))?
serviceDetails = determineServiceInfo(registeredService)
if serviceDetails.type? and serviceDetails.protocol? and service.port?
if !publishInstance?
bonjourOpts = {}
if options?.mdnsInterface?
bonjourOpts.interface = options.mdnsInterface
bonjourOpts.loopback = loopbackInterface
publishInstance = bonjour(bonjourOpts)
publishDetails =
name: service.name
port: service.port
type: serviceDetails.type
subtypes: serviceDetails.subtypes
protocol: serviceDetails.protocol
if service.host? then publishDetails.host = service.host
publishInstance.publish(publishDetails)
.asCallback(callback)
###
# @summary Unpublishes all available services
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted.
# This function must be called before process exit to ensure used sockets are destroyed.
#
# @example
# discoverableServices.unpublishServices()
###
exports.unpublishServices = (callback) ->
return Promise.resolve().asCallback(callback) if not publishInstance?
publishInstance.unpublishAll ->
publishInstance.destroy()
publishInstance = null
return Promise.resolve().asCallback(callback)
| 223506 | ###
Copyright 2016 Resin.<NAME>
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.
###
Promise = require('bluebird')
fs = Promise.promisifyAll(require('fs'))
os = require('os')
ip = require('ip')
bonjour = require('bonjour')
_ = require('lodash')
# In priority order:
browserBackends = [
require('./backends/avahi')
require('./backends/native')
]
# Set the memoize cache as a Map so we can clear it should the service
# registry change.
_.memoize.Cache = Map
registryPath = "#{__dirname}/../services"
# List of published services. The bonjourInstance is initially uncreated, and
# is created either by the publishing of a service, or by finding a service.
# It *must* be cleaned up and destroyed before exiting a process to ensure
# bound sockets are removed.
publishInstance = null
###
# @summary Scans the registry path hierarchy to determine service types.
# @function
# @private
###
retrieveServices = ->
foundPaths = []
scanDirectory = (parentPath, localPath) ->
# Scan for directory names,
foundDirectories = []
fs.readdirAsync(parentPath)
.then (paths) ->
Promise.map paths, (path) ->
fs.statAsync("#{parentPath}/#{path}")
.then (stat) ->
if stat.isDirectory()
foundDirectories.push(path)
.then ->
if foundDirectories.length is 0
foundPaths.push(localPath)
else
# Prepend our path onto it
Promise.map foundDirectories, (path) ->
# Scan each of these
scanDirectory("#{parentPath}/#{path}", "#{localPath}/#{path}")
scanDirectory(registryPath, '')
.then ->
services = []
# Only depths of 2 or 3 levels are valid (subtype/type/protocol).
# Any incorrect depths are ignored, as we would prefer to retrieve the
# services if at all possible
Promise.map foundPaths, (path) ->
components = _.split(path, '/')
components.shift()
# Ignore any non-valid service structure
if (components.length >= 2 or components.length <= 3)
service = ''
tags = []
if components.length is 3
service = "_#{components[0]}._sub."
components.shift()
service += "_#{components[0]}._#{components[1]}"
fs.readFileAsync("#{registryPath}#{path}/tags.json", { encoding: 'utf8' })
.then (data) ->
json = JSON.parse(data)
if (not _.isArray(json))
throw new Error()
tags = json
.catch (err) ->
# If the tag file didn't exist, we silently fail.
if err.code isnt 'ENOENT'
throw new Error("tags.json for #{service} service defintion is incorrect")
.then ->
services.push({ service: service, tags: tags })
.return(services)
# Set the services function as a memoized one.
registryServices = _.memoize(retrieveServices)
###
# @summary Determines if a service is valid.
# @function
# @private
###
findValidService = (serviceIdentifier, knownServices) ->
_.find knownServices, ({ service, tags }) ->
serviceIdentifier in [ service, tags... ]
###
# @summary Retrieves information for a given services string.
# @function
# @private
###
determineServiceInfo = (service) ->
info = {}
types = service.service.match(/^(_(.*)\._sub\.)?_(.*)\._(.*)$/)
if not types[1]? and not types[2]?
info.subtypes = []
else
info.subtypes = [ types[2] ]
# We only try and find a service if the type is valid
if types[3]? and types[4]?
info.type = types[3]
info.protocol = types[4]
return info
###
# @summary Ensures valid network interfaces exist
# @function
# @private
###
hasValidInterfaces = ->
# We can continue so long as we have one interface, and that interface is not loopback.
_.some os.networkInterfaces(), (value) ->
_.some(value, internal: false)
###
# @summary Determine if a specified interface address for MDNS binding is a loopback interface
# @function
# @private
###
isLoopbackInterface = (address) ->
if ip.isV4Format(address)
family = 'IPv4'
else if ip.isV6Format(address)
family = 'IPv6'
else
return null
# Correctly format any IPv6 addresses so we find them.
foundIntf = _.find os.networkInterfaces(), (intfInfo) ->
_.find(intfInfo, address: address)
if not foundIntf? or not (validFamily = _.find(foundIntf, family: family)?.internal)?
return null
return validFamily
###
# @summary Sets the path which will be examined for service definitions.
# @function
# @public
#
# @description
# Should no parameter be passed, or this method not called, then the default
# path is the 'services' directory that exists within the module's directory
# hierarchy.
#
# @param {String} path - New path to use as the service registry.
#
# @example
# discoverableServices.setRegistryPath("/home/heds/discoverable_services")
###
exports.setRegistryPath = (path) ->
if not path?
path = "#{__dirname}/../services"
if not _.isString(path)
throw new Error('path parameter must be a path string')
registryPath = path
registryServices.cache.clear()
###
# @summary Enumerates all currently registered services available for discovery.
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted.
#
# @param {Function} callback - callback (error, services)
#
# @example
# discoverableServices.enumerateServices (error, services) ->
# throw error if error?
# # services is an array of service objects holding type/subtype and any tagnames associated with them
# console.log(services)
###
exports.enumerateServices = (callback) ->
registryServices()
.asCallback(callback)
###
# @summary Listens for all locally published services, returning information on them after a period of time.
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted. Should the timeout value be missing
# then a default timeout of 2000ms is used.
#
# @param {Array} services - A string array of service identifiers or tags
# @param {Number} timeout - A timeout in milliseconds before results are returned. Defaults to 2000ms
# @param {Function} callback - callback (error, services)
#
# @example
# discoverableServices.findServices([ '_resin-device._sub._ssh._tcp' ], 5000, (error, services) ->
# throw error if error?
# # services is an array of every service that conformed to the specified search parameters
# console.log(services)
###
exports.findServices = Promise.method (services, timeout, callback) ->
# Check parameters.
if not timeout?
timeout = 2000
else
if not _.isNumber(timeout)
throw new Error('timeout parameter must be a number value in milliseconds')
if not _.isArray(services)
throw new Error('services parameter must be an array of service name strings')
# Perform the bonjour service lookup and return any results after the timeout period
# Do this on all available, valid NICS.
nics = os.networkInterfaces()
findInstances = []
_.each nics, (nic) ->
_.each nic, (addr) ->
if (addr.family == 'IPv4') and (addr.internal == false)
findInstances.push(bonjour({ interface: addr.address }))
createBrowser = (serviceIdentifier, subtypes, type, protocol) ->
new Promise (resolve) ->
foundServices = []
browsers = []
_.each findInstances, (findInstance) ->
browsers.push findInstance.find { type: type, subtypes: subtypes, protocol: protocol }, (service) ->
# Because we spin up a new search for each subtype, we don't
# need to update records here. Any valid service is unique.
service.service = serviceIdentifier
foundServices.push(service)
setTimeout( ->
_.each browsers, (browser) ->
browser.stop()
resolve(_.uniqBy(foundServices, (service) -> service.fqdn))
, timeout)
# Get the list of registered services.
registryServices()
.then (validServices) ->
serviceBrowsers = []
services.forEach (service) ->
if (registeredService = findValidService(service, validServices))?
serviceDetails = determineServiceInfo(registeredService)
if serviceDetails.type? and serviceDetails.protocol?
# Build a browser, set a timeout and resolve once that
# timeout has finished
serviceBrowsers.push(createBrowser registeredService.service,
serviceDetails.subtypes, serviceDetails.type, serviceDetails.protocol
)
Promise.all serviceBrowsers
.then (services) ->
services = _.flatten(services)
_.remove(services, (entry) -> entry == null)
return services
.finally ->
_.each findInstances, (instance) ->
instance.destroy()
.asCallback(callback)
getServiceBrowser = (timeout) ->
Promise.filter browserBackends, (backend) ->
backend.isAvailable()
.then (availableBackends) ->
if availableBackends.length == 0
throw new Error('No backends available for service discovery')
return availableBackends[0].get(timeout)
###
# @summary Publishes all available services
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted.
# Note that it is vital that any published services are unpublished during exit of the process using `unpublishServices()`.
# Should an `mdnsInterface` property be set in the `services` object and pertain to a loopback device, then loopback for multicast will automatically be enabled.
#
# @param {Array} services - An object array of service details. Each service object is comprised of:
# @param {String} services.identifier - A string of the service identifier or an associated tag
# @param {String} services.name - A string of the service name to advertise as
# @param {String} services.host - A specific hostname that will be used as the host (useful for proxying or psuedo-hosting). Defaults to current host name should none be given
# @param {Number} services.port - The port on which the service will be advertised
# @param {Object} options - An options object for passing publishing options:
# @param {String} options.mdnsInterface - The IPv4 or IPv6 address of a current valid interface with which to bind the MDNS service to (if unset, first available interface).
#
# @example
# discoverableServices.publishServices([ { service: '_resin-device._sub._ssh._tcp', host: 'server1.local', port: 9999 } ])
###
exports.publishServices = Promise.method (services, options, callback) ->
if not _.isArray(services)
throw new Error('services parameter must be an array of service objects')
# If we have a specific interface to bind multicast to, we need to determine if loopback
# should be set (if we can't find the address, we bail)
if not options?.mdnsInterface? and not hasValidInterfaces()
throw new Error('At least one non-loopback interface must be present to bind to')
else if options?.mdnsInterface?
loopbackInterface = isLoopbackInterface(options.mdnsInterface)
if not loopbackInterface?
throw new Error('The specified MDNS interface address is not valid')
# Get the list of registered services.
registryServices()
.then (validServices) ->
services.forEach (service) ->
if service.identifier? and service.name? and (registeredService = findValidService(service.identifier, validServices))?
serviceDetails = determineServiceInfo(registeredService)
if serviceDetails.type? and serviceDetails.protocol? and service.port?
if !publishInstance?
bonjourOpts = {}
if options?.mdnsInterface?
bonjourOpts.interface = options.mdnsInterface
bonjourOpts.loopback = loopbackInterface
publishInstance = bonjour(bonjourOpts)
publishDetails =
name: service.name
port: service.port
type: serviceDetails.type
subtypes: serviceDetails.subtypes
protocol: serviceDetails.protocol
if service.host? then publishDetails.host = service.host
publishInstance.publish(publishDetails)
.asCallback(callback)
###
# @summary Unpublishes all available services
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted.
# This function must be called before process exit to ensure used sockets are destroyed.
#
# @example
# discoverableServices.unpublishServices()
###
exports.unpublishServices = (callback) ->
return Promise.resolve().asCallback(callback) if not publishInstance?
publishInstance.unpublishAll ->
publishInstance.destroy()
publishInstance = null
return Promise.resolve().asCallback(callback)
| true | ###
Copyright 2016 Resin.PI:NAME:<NAME>END_PI
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.
###
Promise = require('bluebird')
fs = Promise.promisifyAll(require('fs'))
os = require('os')
ip = require('ip')
bonjour = require('bonjour')
_ = require('lodash')
# In priority order:
browserBackends = [
require('./backends/avahi')
require('./backends/native')
]
# Set the memoize cache as a Map so we can clear it should the service
# registry change.
_.memoize.Cache = Map
registryPath = "#{__dirname}/../services"
# List of published services. The bonjourInstance is initially uncreated, and
# is created either by the publishing of a service, or by finding a service.
# It *must* be cleaned up and destroyed before exiting a process to ensure
# bound sockets are removed.
publishInstance = null
###
# @summary Scans the registry path hierarchy to determine service types.
# @function
# @private
###
retrieveServices = ->
foundPaths = []
scanDirectory = (parentPath, localPath) ->
# Scan for directory names,
foundDirectories = []
fs.readdirAsync(parentPath)
.then (paths) ->
Promise.map paths, (path) ->
fs.statAsync("#{parentPath}/#{path}")
.then (stat) ->
if stat.isDirectory()
foundDirectories.push(path)
.then ->
if foundDirectories.length is 0
foundPaths.push(localPath)
else
# Prepend our path onto it
Promise.map foundDirectories, (path) ->
# Scan each of these
scanDirectory("#{parentPath}/#{path}", "#{localPath}/#{path}")
scanDirectory(registryPath, '')
.then ->
services = []
# Only depths of 2 or 3 levels are valid (subtype/type/protocol).
# Any incorrect depths are ignored, as we would prefer to retrieve the
# services if at all possible
Promise.map foundPaths, (path) ->
components = _.split(path, '/')
components.shift()
# Ignore any non-valid service structure
if (components.length >= 2 or components.length <= 3)
service = ''
tags = []
if components.length is 3
service = "_#{components[0]}._sub."
components.shift()
service += "_#{components[0]}._#{components[1]}"
fs.readFileAsync("#{registryPath}#{path}/tags.json", { encoding: 'utf8' })
.then (data) ->
json = JSON.parse(data)
if (not _.isArray(json))
throw new Error()
tags = json
.catch (err) ->
# If the tag file didn't exist, we silently fail.
if err.code isnt 'ENOENT'
throw new Error("tags.json for #{service} service defintion is incorrect")
.then ->
services.push({ service: service, tags: tags })
.return(services)
# Set the services function as a memoized one.
registryServices = _.memoize(retrieveServices)
###
# @summary Determines if a service is valid.
# @function
# @private
###
findValidService = (serviceIdentifier, knownServices) ->
_.find knownServices, ({ service, tags }) ->
serviceIdentifier in [ service, tags... ]
###
# @summary Retrieves information for a given services string.
# @function
# @private
###
determineServiceInfo = (service) ->
info = {}
types = service.service.match(/^(_(.*)\._sub\.)?_(.*)\._(.*)$/)
if not types[1]? and not types[2]?
info.subtypes = []
else
info.subtypes = [ types[2] ]
# We only try and find a service if the type is valid
if types[3]? and types[4]?
info.type = types[3]
info.protocol = types[4]
return info
###
# @summary Ensures valid network interfaces exist
# @function
# @private
###
hasValidInterfaces = ->
# We can continue so long as we have one interface, and that interface is not loopback.
_.some os.networkInterfaces(), (value) ->
_.some(value, internal: false)
###
# @summary Determine if a specified interface address for MDNS binding is a loopback interface
# @function
# @private
###
isLoopbackInterface = (address) ->
if ip.isV4Format(address)
family = 'IPv4'
else if ip.isV6Format(address)
family = 'IPv6'
else
return null
# Correctly format any IPv6 addresses so we find them.
foundIntf = _.find os.networkInterfaces(), (intfInfo) ->
_.find(intfInfo, address: address)
if not foundIntf? or not (validFamily = _.find(foundIntf, family: family)?.internal)?
return null
return validFamily
###
# @summary Sets the path which will be examined for service definitions.
# @function
# @public
#
# @description
# Should no parameter be passed, or this method not called, then the default
# path is the 'services' directory that exists within the module's directory
# hierarchy.
#
# @param {String} path - New path to use as the service registry.
#
# @example
# discoverableServices.setRegistryPath("/home/heds/discoverable_services")
###
exports.setRegistryPath = (path) ->
if not path?
path = "#{__dirname}/../services"
if not _.isString(path)
throw new Error('path parameter must be a path string')
registryPath = path
registryServices.cache.clear()
###
# @summary Enumerates all currently registered services available for discovery.
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted.
#
# @param {Function} callback - callback (error, services)
#
# @example
# discoverableServices.enumerateServices (error, services) ->
# throw error if error?
# # services is an array of service objects holding type/subtype and any tagnames associated with them
# console.log(services)
###
exports.enumerateServices = (callback) ->
registryServices()
.asCallback(callback)
###
# @summary Listens for all locally published services, returning information on them after a period of time.
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted. Should the timeout value be missing
# then a default timeout of 2000ms is used.
#
# @param {Array} services - A string array of service identifiers or tags
# @param {Number} timeout - A timeout in milliseconds before results are returned. Defaults to 2000ms
# @param {Function} callback - callback (error, services)
#
# @example
# discoverableServices.findServices([ '_resin-device._sub._ssh._tcp' ], 5000, (error, services) ->
# throw error if error?
# # services is an array of every service that conformed to the specified search parameters
# console.log(services)
###
exports.findServices = Promise.method (services, timeout, callback) ->
# Check parameters.
if not timeout?
timeout = 2000
else
if not _.isNumber(timeout)
throw new Error('timeout parameter must be a number value in milliseconds')
if not _.isArray(services)
throw new Error('services parameter must be an array of service name strings')
# Perform the bonjour service lookup and return any results after the timeout period
# Do this on all available, valid NICS.
nics = os.networkInterfaces()
findInstances = []
_.each nics, (nic) ->
_.each nic, (addr) ->
if (addr.family == 'IPv4') and (addr.internal == false)
findInstances.push(bonjour({ interface: addr.address }))
createBrowser = (serviceIdentifier, subtypes, type, protocol) ->
new Promise (resolve) ->
foundServices = []
browsers = []
_.each findInstances, (findInstance) ->
browsers.push findInstance.find { type: type, subtypes: subtypes, protocol: protocol }, (service) ->
# Because we spin up a new search for each subtype, we don't
# need to update records here. Any valid service is unique.
service.service = serviceIdentifier
foundServices.push(service)
setTimeout( ->
_.each browsers, (browser) ->
browser.stop()
resolve(_.uniqBy(foundServices, (service) -> service.fqdn))
, timeout)
# Get the list of registered services.
registryServices()
.then (validServices) ->
serviceBrowsers = []
services.forEach (service) ->
if (registeredService = findValidService(service, validServices))?
serviceDetails = determineServiceInfo(registeredService)
if serviceDetails.type? and serviceDetails.protocol?
# Build a browser, set a timeout and resolve once that
# timeout has finished
serviceBrowsers.push(createBrowser registeredService.service,
serviceDetails.subtypes, serviceDetails.type, serviceDetails.protocol
)
Promise.all serviceBrowsers
.then (services) ->
services = _.flatten(services)
_.remove(services, (entry) -> entry == null)
return services
.finally ->
_.each findInstances, (instance) ->
instance.destroy()
.asCallback(callback)
getServiceBrowser = (timeout) ->
Promise.filter browserBackends, (backend) ->
backend.isAvailable()
.then (availableBackends) ->
if availableBackends.length == 0
throw new Error('No backends available for service discovery')
return availableBackends[0].get(timeout)
###
# @summary Publishes all available services
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted.
# Note that it is vital that any published services are unpublished during exit of the process using `unpublishServices()`.
# Should an `mdnsInterface` property be set in the `services` object and pertain to a loopback device, then loopback for multicast will automatically be enabled.
#
# @param {Array} services - An object array of service details. Each service object is comprised of:
# @param {String} services.identifier - A string of the service identifier or an associated tag
# @param {String} services.name - A string of the service name to advertise as
# @param {String} services.host - A specific hostname that will be used as the host (useful for proxying or psuedo-hosting). Defaults to current host name should none be given
# @param {Number} services.port - The port on which the service will be advertised
# @param {Object} options - An options object for passing publishing options:
# @param {String} options.mdnsInterface - The IPv4 or IPv6 address of a current valid interface with which to bind the MDNS service to (if unset, first available interface).
#
# @example
# discoverableServices.publishServices([ { service: '_resin-device._sub._ssh._tcp', host: 'server1.local', port: 9999 } ])
###
exports.publishServices = Promise.method (services, options, callback) ->
if not _.isArray(services)
throw new Error('services parameter must be an array of service objects')
# If we have a specific interface to bind multicast to, we need to determine if loopback
# should be set (if we can't find the address, we bail)
if not options?.mdnsInterface? and not hasValidInterfaces()
throw new Error('At least one non-loopback interface must be present to bind to')
else if options?.mdnsInterface?
loopbackInterface = isLoopbackInterface(options.mdnsInterface)
if not loopbackInterface?
throw new Error('The specified MDNS interface address is not valid')
# Get the list of registered services.
registryServices()
.then (validServices) ->
services.forEach (service) ->
if service.identifier? and service.name? and (registeredService = findValidService(service.identifier, validServices))?
serviceDetails = determineServiceInfo(registeredService)
if serviceDetails.type? and serviceDetails.protocol? and service.port?
if !publishInstance?
bonjourOpts = {}
if options?.mdnsInterface?
bonjourOpts.interface = options.mdnsInterface
bonjourOpts.loopback = loopbackInterface
publishInstance = bonjour(bonjourOpts)
publishDetails =
name: service.name
port: service.port
type: serviceDetails.type
subtypes: serviceDetails.subtypes
protocol: serviceDetails.protocol
if service.host? then publishDetails.host = service.host
publishInstance.publish(publishDetails)
.asCallback(callback)
###
# @summary Unpublishes all available services
# @function
# @public
#
# @description
# This function allows promise style if the callback is omitted.
# This function must be called before process exit to ensure used sockets are destroyed.
#
# @example
# discoverableServices.unpublishServices()
###
exports.unpublishServices = (callback) ->
return Promise.resolve().asCallback(callback) if not publishInstance?
publishInstance.unpublishAll ->
publishInstance.destroy()
publishInstance = null
return Promise.resolve().asCallback(callback)
|
[
{
"context": ".parameters).to.be.eql(\n\t\t\t\tdatabase:\n\t\t\t\t\thost: '127.0.0.1'\n\t\t\t\t\tdatabase: 'db'\n\t\t\t\t\tuser: 'root'\n\t\t\t\t\tpassw",
"end": 4273,
"score": 0.9997056126594543,
"start": 4264,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "\tdatabase: 'db'\n\t\t\t\t\tuser: 'root'\n\t\t\t\t\tpassword: 'qwerty'\n\t\t\t)\n\n\t\tit 'should load data from different envi",
"end": 4335,
"score": 0.9993457794189453,
"start": 4329,
"tag": "PASSWORD",
"value": "qwerty"
},
{
"context": ".parameters).to.be.eql(\n\t\t\t\tdatabase:\n\t\t\t\t\thost: '127.0.0.1'\n\t\t\t\t\tdatabase: 'db'\n\t\t\t\t\tuser: 'root'\n\t\t\t\t\tpassw",
"end": 4591,
"score": 0.999710738658905,
"start": 4582,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "\tdatabase: 'db'\n\t\t\t\t\tuser: 'root'\n\t\t\t\t\tpassword: 'toor'\n\t\t\t)\n\n\t\tit 'should load data from local environm",
"end": 4651,
"score": 0.9993668794631958,
"start": 4647,
"tag": "PASSWORD",
"value": "toor"
},
{
"context": "ameters).to.be.eql(\n\t\t\t\tdatabase:\n\t\t\t\t\tpassword: 'toor'\n\t\t\t)\n\n\tdescribe '#addConfig()', ->\n\n\t\tit 'should",
"end": 4927,
"score": 0.9993428587913513,
"start": 4923,
"tag": "PASSWORD",
"value": "toor"
},
{
"context": "ameters).to.be.eql(\n\t\t\t\tdatabase:\n\t\t\t\t\tpassword: 'qwerty'\n\t\t\t\t\thost: '127.0.0.1'\n\t\t\t\t\tdatabase: 'db'\n\t\t\t\t\t",
"end": 5294,
"score": 0.9993177652359009,
"start": 5288,
"tag": "PASSWORD",
"value": "qwerty"
},
{
"context": "\t\t\t\tdatabase:\n\t\t\t\t\tpassword: 'qwerty'\n\t\t\t\t\thost: '127.0.0.1'\n\t\t\t\t\tdatabase: 'db'\n\t\t\t\t\tuser: 'root'\n\t\t\t)",
"end": 5317,
"score": 0.9997351765632629,
"start": 5308,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | test/node/src/EasyConfiguration.coffee | sakren/node-easy-configuration | 1 | expect = require('chai').expect
path = require 'path'
EasyConfiguration = require '../../../lib/EasyConfiguration'
Extension = require '../../../lib/Extension'
dir = path.normalize(__dirname + '/../../data')
configuration = null
describe 'EasyConfiguration', ->
beforeEach( ->
configuration = new EasyConfiguration("#{dir}/config.json")
)
describe '#constructor()', ->
it 'should load configuration with relative path', ->
configuration = new EasyConfiguration('../../data/config.json')
configuration.load()
expect(configuration.parameters).to.be.an.instanceof(Object)
describe '#load()', ->
it 'should return loaded configuration without parameters', ->
expect(configuration.load()).to.be.eql({})
it 'should throw an error with information about circular reference', ->
configuration = new EasyConfiguration("#{dir}/circular.json")
expect( -> configuration.load()).to.throw(Error, 'Found circular reference in parameters first, second, third, other.inner.fourth.')
describe '#addSection()', ->
it 'should return instance of newly registered section', ->
expect(configuration.addSection('newSection')).to.be.an.instanceof(Extension)
it 'should throw exception if section with reserved name is trying to register', ->
expect( ->
configuration.addSection('includes')
configuration.addSection('parameters')
).to.throw(Error)
describe '#getParameter()', ->
beforeEach( ->
configuration.load()
)
it 'should throw an error for unknown parameter', ->
expect( -> configuration.getParameter('unknown')).to.throw(Error, 'Parameter unknown is not defined.')
it 'should return parameter', ->
expect(configuration.getParameter('base')).to.be.equal('./www')
it 'should return parameter from not first depth', ->
expect(configuration.getParameter('paths.cdn')).to.be.equal('./cdn/data')
it 'should return parameter pointing to other parameter', ->
expect(configuration.getParameter('paths.lang')).to.be.equal('./www/lang')
expect(configuration.getParameter('paths.translator')).to.be.equal('./www/lang/translator.js')
it 'should return parameter pointing to other parameter from included file', ->
expect(configuration.getParameter('paths.videos')).to.be.equal('./www/videos')
it 'should return object of parameters', ->
expect(configuration.getParameter('paths')).to.be.eql(
cdn: './cdn/data'
lang: './www/lang'
translator: './www/lang/translator.js'
images: './www/images'
videos: './www/videos'
)
it 'should not expand parameters list in configuration', ->
expect(configuration.getParameter('pathsToCaching')).to.be.equal('%cached%')
describe 'sections', ->
it 'should throw an error for unknown section', ->
configuration = new EasyConfiguration("#{dir}/unknownSection")
expect( -> configuration.load()).to.throw(Error, 'Found section unknown but there is no coresponding extension.')
it 'should load data of section', ->
configuration = new EasyConfiguration("#{dir}/advanced")
configuration.addSection('application')
expect(configuration.load()).to.be.eql(
application:
path: './www'
data: [
'./cdn/data'
'./www/lang'
'./www/lang/translator.js'
'./www/images'
'./www/videos'
]
)
it 'should load data from section with defaults', ->
configuration = new EasyConfiguration("#{dir}/advanced")
section = configuration.addSection('application')
section.loadConfiguration = ->
config = @getConfig(
data: []
run: true
favicon: null
cache: '%base%/temp/cache'
)
for _path, i in config.data
config.data[i] =
path: _path
return config
expect(configuration.load()).to.be.eql(
application:
path: './www'
data: [
{path: './cdn/data'}
{path: './www/lang'}
{path: './www/lang/translator.js'}
{path: './www/images'}
{path: './www/videos'}
]
run: true
favicon: null
cache: './www/temp/cache'
)
describe 'environments', ->
it 'should load data from base environment section', ->
configuration = new EasyConfiguration("#{dir}/environments")
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
host: '127.0.0.1'
database: 'db'
user: 'root'
password: 'qwerty'
)
it 'should load data from different environment section', ->
configuration = new EasyConfiguration("#{dir}/environments", 'development')
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
host: '127.0.0.1'
database: 'db'
user: 'root'
password: 'toor'
)
it 'should load data from local environment section without common section', ->
configuration = new EasyConfiguration("#{dir}/environmentsNoCommon", 'local')
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
password: 'toor'
)
describe '#addConfig()', ->
it 'should add more config files', ->
configuration = new EasyConfiguration
configuration.addConfig('../../data/environmentsNoCommon', 'local')
configuration.addConfig('../../data/environments', 'production')
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
password: 'qwerty'
host: '127.0.0.1'
database: 'db'
user: 'root'
) | 50850 | expect = require('chai').expect
path = require 'path'
EasyConfiguration = require '../../../lib/EasyConfiguration'
Extension = require '../../../lib/Extension'
dir = path.normalize(__dirname + '/../../data')
configuration = null
describe 'EasyConfiguration', ->
beforeEach( ->
configuration = new EasyConfiguration("#{dir}/config.json")
)
describe '#constructor()', ->
it 'should load configuration with relative path', ->
configuration = new EasyConfiguration('../../data/config.json')
configuration.load()
expect(configuration.parameters).to.be.an.instanceof(Object)
describe '#load()', ->
it 'should return loaded configuration without parameters', ->
expect(configuration.load()).to.be.eql({})
it 'should throw an error with information about circular reference', ->
configuration = new EasyConfiguration("#{dir}/circular.json")
expect( -> configuration.load()).to.throw(Error, 'Found circular reference in parameters first, second, third, other.inner.fourth.')
describe '#addSection()', ->
it 'should return instance of newly registered section', ->
expect(configuration.addSection('newSection')).to.be.an.instanceof(Extension)
it 'should throw exception if section with reserved name is trying to register', ->
expect( ->
configuration.addSection('includes')
configuration.addSection('parameters')
).to.throw(Error)
describe '#getParameter()', ->
beforeEach( ->
configuration.load()
)
it 'should throw an error for unknown parameter', ->
expect( -> configuration.getParameter('unknown')).to.throw(Error, 'Parameter unknown is not defined.')
it 'should return parameter', ->
expect(configuration.getParameter('base')).to.be.equal('./www')
it 'should return parameter from not first depth', ->
expect(configuration.getParameter('paths.cdn')).to.be.equal('./cdn/data')
it 'should return parameter pointing to other parameter', ->
expect(configuration.getParameter('paths.lang')).to.be.equal('./www/lang')
expect(configuration.getParameter('paths.translator')).to.be.equal('./www/lang/translator.js')
it 'should return parameter pointing to other parameter from included file', ->
expect(configuration.getParameter('paths.videos')).to.be.equal('./www/videos')
it 'should return object of parameters', ->
expect(configuration.getParameter('paths')).to.be.eql(
cdn: './cdn/data'
lang: './www/lang'
translator: './www/lang/translator.js'
images: './www/images'
videos: './www/videos'
)
it 'should not expand parameters list in configuration', ->
expect(configuration.getParameter('pathsToCaching')).to.be.equal('%cached%')
describe 'sections', ->
it 'should throw an error for unknown section', ->
configuration = new EasyConfiguration("#{dir}/unknownSection")
expect( -> configuration.load()).to.throw(Error, 'Found section unknown but there is no coresponding extension.')
it 'should load data of section', ->
configuration = new EasyConfiguration("#{dir}/advanced")
configuration.addSection('application')
expect(configuration.load()).to.be.eql(
application:
path: './www'
data: [
'./cdn/data'
'./www/lang'
'./www/lang/translator.js'
'./www/images'
'./www/videos'
]
)
it 'should load data from section with defaults', ->
configuration = new EasyConfiguration("#{dir}/advanced")
section = configuration.addSection('application')
section.loadConfiguration = ->
config = @getConfig(
data: []
run: true
favicon: null
cache: '%base%/temp/cache'
)
for _path, i in config.data
config.data[i] =
path: _path
return config
expect(configuration.load()).to.be.eql(
application:
path: './www'
data: [
{path: './cdn/data'}
{path: './www/lang'}
{path: './www/lang/translator.js'}
{path: './www/images'}
{path: './www/videos'}
]
run: true
favicon: null
cache: './www/temp/cache'
)
describe 'environments', ->
it 'should load data from base environment section', ->
configuration = new EasyConfiguration("#{dir}/environments")
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
host: '127.0.0.1'
database: 'db'
user: 'root'
password: '<PASSWORD>'
)
it 'should load data from different environment section', ->
configuration = new EasyConfiguration("#{dir}/environments", 'development')
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
host: '127.0.0.1'
database: 'db'
user: 'root'
password: '<PASSWORD>'
)
it 'should load data from local environment section without common section', ->
configuration = new EasyConfiguration("#{dir}/environmentsNoCommon", 'local')
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
password: '<PASSWORD>'
)
describe '#addConfig()', ->
it 'should add more config files', ->
configuration = new EasyConfiguration
configuration.addConfig('../../data/environmentsNoCommon', 'local')
configuration.addConfig('../../data/environments', 'production')
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
password: '<PASSWORD>'
host: '127.0.0.1'
database: 'db'
user: 'root'
) | true | expect = require('chai').expect
path = require 'path'
EasyConfiguration = require '../../../lib/EasyConfiguration'
Extension = require '../../../lib/Extension'
dir = path.normalize(__dirname + '/../../data')
configuration = null
describe 'EasyConfiguration', ->
beforeEach( ->
configuration = new EasyConfiguration("#{dir}/config.json")
)
describe '#constructor()', ->
it 'should load configuration with relative path', ->
configuration = new EasyConfiguration('../../data/config.json')
configuration.load()
expect(configuration.parameters).to.be.an.instanceof(Object)
describe '#load()', ->
it 'should return loaded configuration without parameters', ->
expect(configuration.load()).to.be.eql({})
it 'should throw an error with information about circular reference', ->
configuration = new EasyConfiguration("#{dir}/circular.json")
expect( -> configuration.load()).to.throw(Error, 'Found circular reference in parameters first, second, third, other.inner.fourth.')
describe '#addSection()', ->
it 'should return instance of newly registered section', ->
expect(configuration.addSection('newSection')).to.be.an.instanceof(Extension)
it 'should throw exception if section with reserved name is trying to register', ->
expect( ->
configuration.addSection('includes')
configuration.addSection('parameters')
).to.throw(Error)
describe '#getParameter()', ->
beforeEach( ->
configuration.load()
)
it 'should throw an error for unknown parameter', ->
expect( -> configuration.getParameter('unknown')).to.throw(Error, 'Parameter unknown is not defined.')
it 'should return parameter', ->
expect(configuration.getParameter('base')).to.be.equal('./www')
it 'should return parameter from not first depth', ->
expect(configuration.getParameter('paths.cdn')).to.be.equal('./cdn/data')
it 'should return parameter pointing to other parameter', ->
expect(configuration.getParameter('paths.lang')).to.be.equal('./www/lang')
expect(configuration.getParameter('paths.translator')).to.be.equal('./www/lang/translator.js')
it 'should return parameter pointing to other parameter from included file', ->
expect(configuration.getParameter('paths.videos')).to.be.equal('./www/videos')
it 'should return object of parameters', ->
expect(configuration.getParameter('paths')).to.be.eql(
cdn: './cdn/data'
lang: './www/lang'
translator: './www/lang/translator.js'
images: './www/images'
videos: './www/videos'
)
it 'should not expand parameters list in configuration', ->
expect(configuration.getParameter('pathsToCaching')).to.be.equal('%cached%')
describe 'sections', ->
it 'should throw an error for unknown section', ->
configuration = new EasyConfiguration("#{dir}/unknownSection")
expect( -> configuration.load()).to.throw(Error, 'Found section unknown but there is no coresponding extension.')
it 'should load data of section', ->
configuration = new EasyConfiguration("#{dir}/advanced")
configuration.addSection('application')
expect(configuration.load()).to.be.eql(
application:
path: './www'
data: [
'./cdn/data'
'./www/lang'
'./www/lang/translator.js'
'./www/images'
'./www/videos'
]
)
it 'should load data from section with defaults', ->
configuration = new EasyConfiguration("#{dir}/advanced")
section = configuration.addSection('application')
section.loadConfiguration = ->
config = @getConfig(
data: []
run: true
favicon: null
cache: '%base%/temp/cache'
)
for _path, i in config.data
config.data[i] =
path: _path
return config
expect(configuration.load()).to.be.eql(
application:
path: './www'
data: [
{path: './cdn/data'}
{path: './www/lang'}
{path: './www/lang/translator.js'}
{path: './www/images'}
{path: './www/videos'}
]
run: true
favicon: null
cache: './www/temp/cache'
)
describe 'environments', ->
it 'should load data from base environment section', ->
configuration = new EasyConfiguration("#{dir}/environments")
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
host: '127.0.0.1'
database: 'db'
user: 'root'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
)
it 'should load data from different environment section', ->
configuration = new EasyConfiguration("#{dir}/environments", 'development')
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
host: '127.0.0.1'
database: 'db'
user: 'root'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
)
it 'should load data from local environment section without common section', ->
configuration = new EasyConfiguration("#{dir}/environmentsNoCommon", 'local')
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
password: 'PI:PASSWORD:<PASSWORD>END_PI'
)
describe '#addConfig()', ->
it 'should add more config files', ->
configuration = new EasyConfiguration
configuration.addConfig('../../data/environmentsNoCommon', 'local')
configuration.addConfig('../../data/environments', 'production')
configuration.load()
expect(configuration.parameters).to.be.eql(
database:
password: 'PI:PASSWORD:<PASSWORD>END_PI'
host: '127.0.0.1'
database: 'db'
user: 'root'
) |
[
{
"context": " #\n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) #\n# ",
"end": 914,
"score": 0.9997715950012207,
"start": 904,
"tag": "NAME",
"value": "Mark Masse"
}
] | wrmldoc/js/app/views/_base/View.coffee | wrml/wrml | 47 | ###############################################################################
# #
# WRML - Web Resource Modeling Language #
# __ __ ______ __ __ __ #
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ #
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ #
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ #
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ #
# #
# http://www.wrml.org #
# #
# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) #
# #
# 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. #
# #
###############################################################################
# CoffeeScript
@Wrmldoc.module "Views", (Views, App, Backbone, Marionette, $, _) ->
_remove = Marionette.View::remove
_.extend Marionette.View::,
addOpacityWrapper: (init = true) ->
@$el.toggleWrapper
className: "opacity"
, init
setInstancePropertiesFor: (args...) ->
for key, val of _.pick(@options, args...)
@[key] = val
remove: (args...) ->
console.log "removing", @
if @model?.isDestroyed?()
wrapper = @$el.toggleWrapper
className: "opacity"
backgroundColor: "red"
wrapper.fadeOut 400, ->
$(@).remove()
@$el.fadeOut 400, =>
_remove.apply @, args
else
_remove.apply @, args
templateHelpers: ->
linkTo: (name, url, options = {}) ->
_.defaults options,
external: false
url = "#" + url unless options.external
"<a href='#{url}'>#{@escape(name)}</a>" | 66490 | ###############################################################################
# #
# WRML - Web Resource Modeling Language #
# __ __ ______ __ __ __ #
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ #
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ #
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ #
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ #
# #
# http://www.wrml.org #
# #
# Copyright 2011 - 2013 <NAME> (OSS project WRML.org) #
# #
# 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. #
# #
###############################################################################
# CoffeeScript
@Wrmldoc.module "Views", (Views, App, Backbone, Marionette, $, _) ->
_remove = Marionette.View::remove
_.extend Marionette.View::,
addOpacityWrapper: (init = true) ->
@$el.toggleWrapper
className: "opacity"
, init
setInstancePropertiesFor: (args...) ->
for key, val of _.pick(@options, args...)
@[key] = val
remove: (args...) ->
console.log "removing", @
if @model?.isDestroyed?()
wrapper = @$el.toggleWrapper
className: "opacity"
backgroundColor: "red"
wrapper.fadeOut 400, ->
$(@).remove()
@$el.fadeOut 400, =>
_remove.apply @, args
else
_remove.apply @, args
templateHelpers: ->
linkTo: (name, url, options = {}) ->
_.defaults options,
external: false
url = "#" + url unless options.external
"<a href='#{url}'>#{@escape(name)}</a>" | true | ###############################################################################
# #
# WRML - Web Resource Modeling Language #
# __ __ ______ __ __ __ #
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ #
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ #
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ #
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ #
# #
# http://www.wrml.org #
# #
# Copyright 2011 - 2013 PI:NAME:<NAME>END_PI (OSS project WRML.org) #
# #
# 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. #
# #
###############################################################################
# CoffeeScript
@Wrmldoc.module "Views", (Views, App, Backbone, Marionette, $, _) ->
_remove = Marionette.View::remove
_.extend Marionette.View::,
addOpacityWrapper: (init = true) ->
@$el.toggleWrapper
className: "opacity"
, init
setInstancePropertiesFor: (args...) ->
for key, val of _.pick(@options, args...)
@[key] = val
remove: (args...) ->
console.log "removing", @
if @model?.isDestroyed?()
wrapper = @$el.toggleWrapper
className: "opacity"
backgroundColor: "red"
wrapper.fadeOut 400, ->
$(@).remove()
@$el.fadeOut 400, =>
_remove.apply @, args
else
_remove.apply @, args
templateHelpers: ->
linkTo: (name, url, options = {}) ->
_.defaults options,
external: false
url = "#" + url unless options.external
"<a href='#{url}'>#{@escape(name)}</a>" |
[
{
"context": "allback) ->\n teamsHelpers.inviteUser browser, 'admin'\n browser.pause 3000, callback\n\n\n sendNewMemb",
"end": 7539,
"score": 0.5988506078720093,
"start": 7534,
"tag": "USERNAME",
"value": "admin"
},
{
"context": " teamsHelpers.newInviteFromResendModal browser, 'admin'\n browser.pause 1000, callback\n\n\n #Member can",
"end": 8009,
"score": 0.9797101020812988,
"start": 8004,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "sswordSelector\n .setValue passwordSelector, '1234'\n .click confirmButton\n .waitForElement",
"end": 9753,
"score": 0.9985374808311462,
"start": 9749,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": "passwordSelector\n .setValue passwordSelector, targetUser1.password\n .click confirmButton\n .assert.urlConta",
"end": 10125,
"score": 0.9242256283760071,
"start": 10105,
"tag": "PASSWORD",
"value": "targetUser1.password"
}
] | client/test/lib/helpers/myteamhelpers.coffee | ezgikaysi/koding | 1 | utils = require '../utils/utils.js'
helpers = require '../helpers/helpers.js'
teamsHelpers = require '../helpers/teamshelpers.js'
myTeamLink = "#{helpers.getUrl(yes)}/Home/my-team"
sectionSelector = '.HomeAppView--section.team-settings'
buttonSelector = "#{sectionSelector} .uploadInputWrapper .HomeAppView--button.custom-link-view"
uploadLogoButton = "#{buttonSelector}.primary"
removeLogoButton = "#{buttonSelector}.remove"
teamNameSelector = "#{sectionSelector} .half input[type=text]"
saveChangesButton = '.HomeAppView--section .HomeAppView--button.fr'
kodingLogo = "#{sectionSelector} .HomeAppView--uploadLogo img"
defaultLogoPath = "#{helpers.getUrl(yes)}/a/images/logos/sidebar_footer_logo.svg"
localImage = "#{__dirname}/upload.png"
localImage = require('path').resolve(localImage)
teamLogo = "#{sectionSelector} .kdinput.file"
successMessage = 'Team settings has been successfully updated.'
executeCommand = "document.querySelector('.teamLogo').setAttribute('src', 'some_path');"
teammateSection = '.kdcustomscrollview.HomeAppView--scroller.my-team'
teammateSectionSelector = '.HomeAppView--section.teammates'
checkboxSelector = '.HomeAppView--section.send-invites .invite-inputs .kdcustomcheckbox'
adminTextSelector = '.HomeAppView--section.send-invites .information .invite-labels label:last-child span:last-child'
sendInvitesButton = '.HomeAppView--section.send-invites .custom-link-view.HomeAppView--button.primary.fr'
welcomeView = '.WelcomeStacksView'
leaveTeamButton = '.HomeAppView--button'
passwordSelector = 'input[name=password]'
forgotPasswordButton = '.kdbutton.solid.light-gray'
confirmButton = 'button[type=submit]'
notification = '.kdnotification.main'
index = ''
indexOfTargetUser1 = ''
indexOfTargetUser2 = ''
indexOfTargetUser3 = ''
invitations = ''
module.exports =
editTeamName: (browser, host, callback) ->
browser
.url myTeamLink
.pause 3000
.waitForElementVisible sectionSelector, 20000
.click saveChangesButton
.waitForElementNotPresent '.kdnotification', 5000
.clearValue teamNameSelector
.setValue teamNameSelector, host.teamSlug + 'new'
.click saveChangesButton
teamsHelpers.assertConfirmation browser, successMessage
browser
.clearValue teamNameSelector
.setValue teamNameSelector, host.teamSlug
.click saveChangesButton
teamsHelpers.assertConfirmation browser, successMessage
browser.pause 1000, callback
inviteAndJoinToTeam: (browser, host, callback) ->
{ invitations, index } = utils.getInvitationData()
index = if index is 0 then 1 else index
indexOfTargetUser1 = if 1 % index isnt 0 then 1 else 2
indexOfTargetUser2 = if 3 % index isnt 0 then 3 else 4
indexOfTargetUser3 = if 5 % index isnt 0 then 5 else 6
teamsHelpers.inviteUsers browser, invitations, (res) ->
teamsHelpers.acceptAndJoinInvitation host, browser, invitations[indexOfTargetUser1], (res) ->
teamsHelpers.acceptAndJoinInvitation host, browser, invitations[indexOfTargetUser2], (res) ->
teamsHelpers.acceptAndJoinInvitation host, browser, invitations[indexOfTargetUser3], (res) ->
browser.pause 1000, callback
seeTeammatesList: (browser, callback) ->
browser
.url myTeamLink
.pause 2000
.scrollToElement "#{teammateSectionSelector} .ListView"
.waitForElementVisible teammateSection, 20000
.waitForElementVisible teammateSectionSelector, 20000
.assert.containsText selector(indexOfTargetUser1 + 1), 'Member'
.assert.containsText selector(indexOfTargetUser2 + 1), 'Member'
.assert.containsText selector(indexOfTargetUser3 + 1), 'Member'
.pause 1000, callback
changeMemberRole: (browser, host, callback) ->
invitations[indexOfTargetUser1].accepted = 'Member'
invitations[indexOfTargetUser2].accepted = 'Admin'
invitations[indexOfTargetUser3].accepted = 'Member'
invitations[index].accepted = 'Owner'
lastPendingInvitationIndex = 0
invitations.forEach (invitation, i) ->
unless invitation.accepted
lastPendingInvitationIndex = i
browser
.url myTeamLink
.waitForElementVisible sectionSelector, 20000
.scrollToElement "#{teammateSectionSelector} .ListView"
.waitForElementVisible selector(1), 20000
.click selector(1), ->
teamsHelpers.checkTeammates browser, invitations[0], nthItem(1), nthItem(2), selector(1), no, ->
browser.waitForElementVisible selector(1), 20000
browser.click selector(2), ->
teamsHelpers.checkTeammates browser, invitations[1], nthItem(1), nthItem(2), selector(2), no, ->
browser.click selector(indexOfTargetUser2 + 1), ->
browser
.pause 1000
.click nthItem(2)
.pause 1000
.waitForElementVisible selector(indexOfTargetUser2 + 1), 20000
.assert.containsText selector(indexOfTargetUser2 + 1), 'Admin'
browser.expect.element(selector(index + 1)).text.to.contain 'Owner'
browser.click selector(lastPendingInvitationIndex + 1), ->
browser.waitForElementVisible selector(lastPendingInvitationIndex + 1), 20000
teamsHelpers.checkTeammates browser, invitations[lastPendingInvitationIndex], nthItem(1), nthItem(2), selector(lastPendingInvitationIndex + 1), yes, ->
teamsHelpers.logoutTeam browser, (res) ->
teamsHelpers.loginToTeam browser, invitations[lastPendingInvitationIndex], yes, ->
browser.assert.containsText notification, 'Unknown user name'
teamsHelpers.loginToTeam browser, host , no, ->
browser
.waitForElementVisible welcomeView, 20000
.url myTeamLink
.waitForElementVisible sectionSelector, 20000, callback
uploadCSV: (browser, callback) ->
browser
.url myTeamLink
.waitForElementVisible sectionSelector, 20000
.scrollToElement '.HomeAppView--section.send-invites'
teamsHelpers.uploadCSV browser
browser.pause 1000, callback
sendAlreadyMemberInvite: (browser, callback) ->
teamsHelpers.fillInviteInputByIndex browser, 2, invitations[indexOfTargetUser1].email
browser
.waitForElementVisible sendInvitesButton, 5000
.click sendInvitesButton
teamsHelpers.acceptConfirmModal browser
teamsHelpers.assertConfirmation browser, "Invitation is sent to #{invitations[indexOfTargetUser1].email}"
browser.pause 3000, callback
sendAlreadyAdminInvite: (browser, callback) ->
teamsHelpers.fillInviteInputByIndex browser, 1, invitations[indexOfTargetUser2].email
browser
.waitForElementVisible sendInvitesButton, 5000
.click sendInvitesButton
teamsHelpers.acceptConfirmModal browser
teamsHelpers.assertConfirmation browser, "Invitation is sent to #{invitations[indexOfTargetUser2].email}"
browser.pause 3000, callback
sendInviteToPendingMember: (browser, callback) ->
teamsHelpers.inviteUser browser, 'member', invitations[indexOfTargetUser1 + 1]
browser.pause 3000
teamsHelpers.inviteUser browser, 'admin', invitations[indexOfTargetUser2 + 1]
browser.pause 3000, callback
sendNewAdminInvite: (browser, callback) ->
teamsHelpers.inviteUser browser, 'admin'
browser.pause 3000, callback
sendNewMemberInvite: (browser, callback) ->
teamsHelpers.inviteUser browser, 'member'
browser.pause 3000, callback
sendInviteAll: (browser, callback) ->
teamsHelpers.inviteAll browser
browser.pause 3000, callback
sendNewInviteFromResendModal: (browser, callback) ->
teamsHelpers.newInviteFromResendModal browser, 'member'
browser.pause 3000
teamsHelpers.newInviteFromResendModal browser, 'admin'
browser.pause 1000, callback
#Member can not change team name and team logo
changeTeamName: (browser, callback) ->
targetUser1 = invitations[1]
teamsHelpers.logoutTeam browser, (res) ->
teamsHelpers.loginToTeam browser, targetUser1 , no, ->
browser
.waitForElementVisible welcomeView, 20000
.url myTeamLink
.waitForElementVisible sectionSelector, 20000
.waitForElementNotPresent checkboxSelector, 20000
.expect.element(adminTextSelector).text.to.not.contain 'Admin'
browser
.scrollToElement "#{teammateSectionSelector} .ListView"
.waitForElementVisible teammateSection, 20000
.waitForElementVisible teammateSectionSelector, 20000
.pause 5000
.click selector(1)
.waitForElementNotPresent nthItem(1), 20000
.scrollToElement sectionSelector
.waitForElementNotPresent removeLogoButton, 20000
.waitForElementNotPresent uploadLogoButton, 20000
.waitForElementNotPresent '.HomeAppView--button .custom-link-view .fr .hidden', 20000
.assert.attributeEquals teamNameSelector, 'disabled', 'true'
.pause 1000, callback
leaveTeam: (browser, callback) ->
targetUser1 = invitations[1]
browser
.waitForElementVisible leaveTeamButton, 20000
.click leaveTeamButton
.waitForElementVisible '.kdmodal.kddraggable', 5000
.click forgotPasswordButton
.waitForElementVisible '.kdnotification', 5000
.assert.containsText '.kdnotification.main', 'Check your email'
.pause 5000
.click leaveTeamButton
.waitForElementVisible '.kdmodal.kddraggable', 5000
.clearValue passwordSelector
.setValue passwordSelector, '1234'
.click confirmButton
.waitForElementVisible '.kdnotification', 20000
.assert.containsText '.kdnotification.main', 'Current password cannot be confirmed'
.pause 5000
.click leaveTeamButton
.waitForElementVisible '.kdmodal.kddraggable', 5000
.clearValue passwordSelector
.setValue passwordSelector, targetUser1.password
.click confirmButton
.assert.urlContains helpers.getUrl(yes)
.pause 1000, callback
selector = (index) ->
".HomeApp-Teammate--ListItem:nth-of-type(#{index}) .dropdown "
nthItem = (index) ->
".ButtonWithMenuItemsList li:nth-of-type(#{index})"
| 154754 | utils = require '../utils/utils.js'
helpers = require '../helpers/helpers.js'
teamsHelpers = require '../helpers/teamshelpers.js'
myTeamLink = "#{helpers.getUrl(yes)}/Home/my-team"
sectionSelector = '.HomeAppView--section.team-settings'
buttonSelector = "#{sectionSelector} .uploadInputWrapper .HomeAppView--button.custom-link-view"
uploadLogoButton = "#{buttonSelector}.primary"
removeLogoButton = "#{buttonSelector}.remove"
teamNameSelector = "#{sectionSelector} .half input[type=text]"
saveChangesButton = '.HomeAppView--section .HomeAppView--button.fr'
kodingLogo = "#{sectionSelector} .HomeAppView--uploadLogo img"
defaultLogoPath = "#{helpers.getUrl(yes)}/a/images/logos/sidebar_footer_logo.svg"
localImage = "#{__dirname}/upload.png"
localImage = require('path').resolve(localImage)
teamLogo = "#{sectionSelector} .kdinput.file"
successMessage = 'Team settings has been successfully updated.'
executeCommand = "document.querySelector('.teamLogo').setAttribute('src', 'some_path');"
teammateSection = '.kdcustomscrollview.HomeAppView--scroller.my-team'
teammateSectionSelector = '.HomeAppView--section.teammates'
checkboxSelector = '.HomeAppView--section.send-invites .invite-inputs .kdcustomcheckbox'
adminTextSelector = '.HomeAppView--section.send-invites .information .invite-labels label:last-child span:last-child'
sendInvitesButton = '.HomeAppView--section.send-invites .custom-link-view.HomeAppView--button.primary.fr'
welcomeView = '.WelcomeStacksView'
leaveTeamButton = '.HomeAppView--button'
passwordSelector = 'input[name=password]'
forgotPasswordButton = '.kdbutton.solid.light-gray'
confirmButton = 'button[type=submit]'
notification = '.kdnotification.main'
index = ''
indexOfTargetUser1 = ''
indexOfTargetUser2 = ''
indexOfTargetUser3 = ''
invitations = ''
module.exports =
editTeamName: (browser, host, callback) ->
browser
.url myTeamLink
.pause 3000
.waitForElementVisible sectionSelector, 20000
.click saveChangesButton
.waitForElementNotPresent '.kdnotification', 5000
.clearValue teamNameSelector
.setValue teamNameSelector, host.teamSlug + 'new'
.click saveChangesButton
teamsHelpers.assertConfirmation browser, successMessage
browser
.clearValue teamNameSelector
.setValue teamNameSelector, host.teamSlug
.click saveChangesButton
teamsHelpers.assertConfirmation browser, successMessage
browser.pause 1000, callback
inviteAndJoinToTeam: (browser, host, callback) ->
{ invitations, index } = utils.getInvitationData()
index = if index is 0 then 1 else index
indexOfTargetUser1 = if 1 % index isnt 0 then 1 else 2
indexOfTargetUser2 = if 3 % index isnt 0 then 3 else 4
indexOfTargetUser3 = if 5 % index isnt 0 then 5 else 6
teamsHelpers.inviteUsers browser, invitations, (res) ->
teamsHelpers.acceptAndJoinInvitation host, browser, invitations[indexOfTargetUser1], (res) ->
teamsHelpers.acceptAndJoinInvitation host, browser, invitations[indexOfTargetUser2], (res) ->
teamsHelpers.acceptAndJoinInvitation host, browser, invitations[indexOfTargetUser3], (res) ->
browser.pause 1000, callback
seeTeammatesList: (browser, callback) ->
browser
.url myTeamLink
.pause 2000
.scrollToElement "#{teammateSectionSelector} .ListView"
.waitForElementVisible teammateSection, 20000
.waitForElementVisible teammateSectionSelector, 20000
.assert.containsText selector(indexOfTargetUser1 + 1), 'Member'
.assert.containsText selector(indexOfTargetUser2 + 1), 'Member'
.assert.containsText selector(indexOfTargetUser3 + 1), 'Member'
.pause 1000, callback
changeMemberRole: (browser, host, callback) ->
invitations[indexOfTargetUser1].accepted = 'Member'
invitations[indexOfTargetUser2].accepted = 'Admin'
invitations[indexOfTargetUser3].accepted = 'Member'
invitations[index].accepted = 'Owner'
lastPendingInvitationIndex = 0
invitations.forEach (invitation, i) ->
unless invitation.accepted
lastPendingInvitationIndex = i
browser
.url myTeamLink
.waitForElementVisible sectionSelector, 20000
.scrollToElement "#{teammateSectionSelector} .ListView"
.waitForElementVisible selector(1), 20000
.click selector(1), ->
teamsHelpers.checkTeammates browser, invitations[0], nthItem(1), nthItem(2), selector(1), no, ->
browser.waitForElementVisible selector(1), 20000
browser.click selector(2), ->
teamsHelpers.checkTeammates browser, invitations[1], nthItem(1), nthItem(2), selector(2), no, ->
browser.click selector(indexOfTargetUser2 + 1), ->
browser
.pause 1000
.click nthItem(2)
.pause 1000
.waitForElementVisible selector(indexOfTargetUser2 + 1), 20000
.assert.containsText selector(indexOfTargetUser2 + 1), 'Admin'
browser.expect.element(selector(index + 1)).text.to.contain 'Owner'
browser.click selector(lastPendingInvitationIndex + 1), ->
browser.waitForElementVisible selector(lastPendingInvitationIndex + 1), 20000
teamsHelpers.checkTeammates browser, invitations[lastPendingInvitationIndex], nthItem(1), nthItem(2), selector(lastPendingInvitationIndex + 1), yes, ->
teamsHelpers.logoutTeam browser, (res) ->
teamsHelpers.loginToTeam browser, invitations[lastPendingInvitationIndex], yes, ->
browser.assert.containsText notification, 'Unknown user name'
teamsHelpers.loginToTeam browser, host , no, ->
browser
.waitForElementVisible welcomeView, 20000
.url myTeamLink
.waitForElementVisible sectionSelector, 20000, callback
uploadCSV: (browser, callback) ->
browser
.url myTeamLink
.waitForElementVisible sectionSelector, 20000
.scrollToElement '.HomeAppView--section.send-invites'
teamsHelpers.uploadCSV browser
browser.pause 1000, callback
sendAlreadyMemberInvite: (browser, callback) ->
teamsHelpers.fillInviteInputByIndex browser, 2, invitations[indexOfTargetUser1].email
browser
.waitForElementVisible sendInvitesButton, 5000
.click sendInvitesButton
teamsHelpers.acceptConfirmModal browser
teamsHelpers.assertConfirmation browser, "Invitation is sent to #{invitations[indexOfTargetUser1].email}"
browser.pause 3000, callback
sendAlreadyAdminInvite: (browser, callback) ->
teamsHelpers.fillInviteInputByIndex browser, 1, invitations[indexOfTargetUser2].email
browser
.waitForElementVisible sendInvitesButton, 5000
.click sendInvitesButton
teamsHelpers.acceptConfirmModal browser
teamsHelpers.assertConfirmation browser, "Invitation is sent to #{invitations[indexOfTargetUser2].email}"
browser.pause 3000, callback
sendInviteToPendingMember: (browser, callback) ->
teamsHelpers.inviteUser browser, 'member', invitations[indexOfTargetUser1 + 1]
browser.pause 3000
teamsHelpers.inviteUser browser, 'admin', invitations[indexOfTargetUser2 + 1]
browser.pause 3000, callback
sendNewAdminInvite: (browser, callback) ->
teamsHelpers.inviteUser browser, 'admin'
browser.pause 3000, callback
sendNewMemberInvite: (browser, callback) ->
teamsHelpers.inviteUser browser, 'member'
browser.pause 3000, callback
sendInviteAll: (browser, callback) ->
teamsHelpers.inviteAll browser
browser.pause 3000, callback
sendNewInviteFromResendModal: (browser, callback) ->
teamsHelpers.newInviteFromResendModal browser, 'member'
browser.pause 3000
teamsHelpers.newInviteFromResendModal browser, 'admin'
browser.pause 1000, callback
#Member can not change team name and team logo
changeTeamName: (browser, callback) ->
targetUser1 = invitations[1]
teamsHelpers.logoutTeam browser, (res) ->
teamsHelpers.loginToTeam browser, targetUser1 , no, ->
browser
.waitForElementVisible welcomeView, 20000
.url myTeamLink
.waitForElementVisible sectionSelector, 20000
.waitForElementNotPresent checkboxSelector, 20000
.expect.element(adminTextSelector).text.to.not.contain 'Admin'
browser
.scrollToElement "#{teammateSectionSelector} .ListView"
.waitForElementVisible teammateSection, 20000
.waitForElementVisible teammateSectionSelector, 20000
.pause 5000
.click selector(1)
.waitForElementNotPresent nthItem(1), 20000
.scrollToElement sectionSelector
.waitForElementNotPresent removeLogoButton, 20000
.waitForElementNotPresent uploadLogoButton, 20000
.waitForElementNotPresent '.HomeAppView--button .custom-link-view .fr .hidden', 20000
.assert.attributeEquals teamNameSelector, 'disabled', 'true'
.pause 1000, callback
leaveTeam: (browser, callback) ->
targetUser1 = invitations[1]
browser
.waitForElementVisible leaveTeamButton, 20000
.click leaveTeamButton
.waitForElementVisible '.kdmodal.kddraggable', 5000
.click forgotPasswordButton
.waitForElementVisible '.kdnotification', 5000
.assert.containsText '.kdnotification.main', 'Check your email'
.pause 5000
.click leaveTeamButton
.waitForElementVisible '.kdmodal.kddraggable', 5000
.clearValue passwordSelector
.setValue passwordSelector, '<PASSWORD>'
.click confirmButton
.waitForElementVisible '.kdnotification', 20000
.assert.containsText '.kdnotification.main', 'Current password cannot be confirmed'
.pause 5000
.click leaveTeamButton
.waitForElementVisible '.kdmodal.kddraggable', 5000
.clearValue passwordSelector
.setValue passwordSelector, <PASSWORD>
.click confirmButton
.assert.urlContains helpers.getUrl(yes)
.pause 1000, callback
selector = (index) ->
".HomeApp-Teammate--ListItem:nth-of-type(#{index}) .dropdown "
nthItem = (index) ->
".ButtonWithMenuItemsList li:nth-of-type(#{index})"
| true | utils = require '../utils/utils.js'
helpers = require '../helpers/helpers.js'
teamsHelpers = require '../helpers/teamshelpers.js'
myTeamLink = "#{helpers.getUrl(yes)}/Home/my-team"
sectionSelector = '.HomeAppView--section.team-settings'
buttonSelector = "#{sectionSelector} .uploadInputWrapper .HomeAppView--button.custom-link-view"
uploadLogoButton = "#{buttonSelector}.primary"
removeLogoButton = "#{buttonSelector}.remove"
teamNameSelector = "#{sectionSelector} .half input[type=text]"
saveChangesButton = '.HomeAppView--section .HomeAppView--button.fr'
kodingLogo = "#{sectionSelector} .HomeAppView--uploadLogo img"
defaultLogoPath = "#{helpers.getUrl(yes)}/a/images/logos/sidebar_footer_logo.svg"
localImage = "#{__dirname}/upload.png"
localImage = require('path').resolve(localImage)
teamLogo = "#{sectionSelector} .kdinput.file"
successMessage = 'Team settings has been successfully updated.'
executeCommand = "document.querySelector('.teamLogo').setAttribute('src', 'some_path');"
teammateSection = '.kdcustomscrollview.HomeAppView--scroller.my-team'
teammateSectionSelector = '.HomeAppView--section.teammates'
checkboxSelector = '.HomeAppView--section.send-invites .invite-inputs .kdcustomcheckbox'
adminTextSelector = '.HomeAppView--section.send-invites .information .invite-labels label:last-child span:last-child'
sendInvitesButton = '.HomeAppView--section.send-invites .custom-link-view.HomeAppView--button.primary.fr'
welcomeView = '.WelcomeStacksView'
leaveTeamButton = '.HomeAppView--button'
passwordSelector = 'input[name=password]'
forgotPasswordButton = '.kdbutton.solid.light-gray'
confirmButton = 'button[type=submit]'
notification = '.kdnotification.main'
index = ''
indexOfTargetUser1 = ''
indexOfTargetUser2 = ''
indexOfTargetUser3 = ''
invitations = ''
module.exports =
editTeamName: (browser, host, callback) ->
browser
.url myTeamLink
.pause 3000
.waitForElementVisible sectionSelector, 20000
.click saveChangesButton
.waitForElementNotPresent '.kdnotification', 5000
.clearValue teamNameSelector
.setValue teamNameSelector, host.teamSlug + 'new'
.click saveChangesButton
teamsHelpers.assertConfirmation browser, successMessage
browser
.clearValue teamNameSelector
.setValue teamNameSelector, host.teamSlug
.click saveChangesButton
teamsHelpers.assertConfirmation browser, successMessage
browser.pause 1000, callback
inviteAndJoinToTeam: (browser, host, callback) ->
{ invitations, index } = utils.getInvitationData()
index = if index is 0 then 1 else index
indexOfTargetUser1 = if 1 % index isnt 0 then 1 else 2
indexOfTargetUser2 = if 3 % index isnt 0 then 3 else 4
indexOfTargetUser3 = if 5 % index isnt 0 then 5 else 6
teamsHelpers.inviteUsers browser, invitations, (res) ->
teamsHelpers.acceptAndJoinInvitation host, browser, invitations[indexOfTargetUser1], (res) ->
teamsHelpers.acceptAndJoinInvitation host, browser, invitations[indexOfTargetUser2], (res) ->
teamsHelpers.acceptAndJoinInvitation host, browser, invitations[indexOfTargetUser3], (res) ->
browser.pause 1000, callback
seeTeammatesList: (browser, callback) ->
browser
.url myTeamLink
.pause 2000
.scrollToElement "#{teammateSectionSelector} .ListView"
.waitForElementVisible teammateSection, 20000
.waitForElementVisible teammateSectionSelector, 20000
.assert.containsText selector(indexOfTargetUser1 + 1), 'Member'
.assert.containsText selector(indexOfTargetUser2 + 1), 'Member'
.assert.containsText selector(indexOfTargetUser3 + 1), 'Member'
.pause 1000, callback
changeMemberRole: (browser, host, callback) ->
invitations[indexOfTargetUser1].accepted = 'Member'
invitations[indexOfTargetUser2].accepted = 'Admin'
invitations[indexOfTargetUser3].accepted = 'Member'
invitations[index].accepted = 'Owner'
lastPendingInvitationIndex = 0
invitations.forEach (invitation, i) ->
unless invitation.accepted
lastPendingInvitationIndex = i
browser
.url myTeamLink
.waitForElementVisible sectionSelector, 20000
.scrollToElement "#{teammateSectionSelector} .ListView"
.waitForElementVisible selector(1), 20000
.click selector(1), ->
teamsHelpers.checkTeammates browser, invitations[0], nthItem(1), nthItem(2), selector(1), no, ->
browser.waitForElementVisible selector(1), 20000
browser.click selector(2), ->
teamsHelpers.checkTeammates browser, invitations[1], nthItem(1), nthItem(2), selector(2), no, ->
browser.click selector(indexOfTargetUser2 + 1), ->
browser
.pause 1000
.click nthItem(2)
.pause 1000
.waitForElementVisible selector(indexOfTargetUser2 + 1), 20000
.assert.containsText selector(indexOfTargetUser2 + 1), 'Admin'
browser.expect.element(selector(index + 1)).text.to.contain 'Owner'
browser.click selector(lastPendingInvitationIndex + 1), ->
browser.waitForElementVisible selector(lastPendingInvitationIndex + 1), 20000
teamsHelpers.checkTeammates browser, invitations[lastPendingInvitationIndex], nthItem(1), nthItem(2), selector(lastPendingInvitationIndex + 1), yes, ->
teamsHelpers.logoutTeam browser, (res) ->
teamsHelpers.loginToTeam browser, invitations[lastPendingInvitationIndex], yes, ->
browser.assert.containsText notification, 'Unknown user name'
teamsHelpers.loginToTeam browser, host , no, ->
browser
.waitForElementVisible welcomeView, 20000
.url myTeamLink
.waitForElementVisible sectionSelector, 20000, callback
uploadCSV: (browser, callback) ->
browser
.url myTeamLink
.waitForElementVisible sectionSelector, 20000
.scrollToElement '.HomeAppView--section.send-invites'
teamsHelpers.uploadCSV browser
browser.pause 1000, callback
sendAlreadyMemberInvite: (browser, callback) ->
teamsHelpers.fillInviteInputByIndex browser, 2, invitations[indexOfTargetUser1].email
browser
.waitForElementVisible sendInvitesButton, 5000
.click sendInvitesButton
teamsHelpers.acceptConfirmModal browser
teamsHelpers.assertConfirmation browser, "Invitation is sent to #{invitations[indexOfTargetUser1].email}"
browser.pause 3000, callback
sendAlreadyAdminInvite: (browser, callback) ->
teamsHelpers.fillInviteInputByIndex browser, 1, invitations[indexOfTargetUser2].email
browser
.waitForElementVisible sendInvitesButton, 5000
.click sendInvitesButton
teamsHelpers.acceptConfirmModal browser
teamsHelpers.assertConfirmation browser, "Invitation is sent to #{invitations[indexOfTargetUser2].email}"
browser.pause 3000, callback
sendInviteToPendingMember: (browser, callback) ->
teamsHelpers.inviteUser browser, 'member', invitations[indexOfTargetUser1 + 1]
browser.pause 3000
teamsHelpers.inviteUser browser, 'admin', invitations[indexOfTargetUser2 + 1]
browser.pause 3000, callback
sendNewAdminInvite: (browser, callback) ->
teamsHelpers.inviteUser browser, 'admin'
browser.pause 3000, callback
sendNewMemberInvite: (browser, callback) ->
teamsHelpers.inviteUser browser, 'member'
browser.pause 3000, callback
sendInviteAll: (browser, callback) ->
teamsHelpers.inviteAll browser
browser.pause 3000, callback
sendNewInviteFromResendModal: (browser, callback) ->
teamsHelpers.newInviteFromResendModal browser, 'member'
browser.pause 3000
teamsHelpers.newInviteFromResendModal browser, 'admin'
browser.pause 1000, callback
#Member can not change team name and team logo
changeTeamName: (browser, callback) ->
targetUser1 = invitations[1]
teamsHelpers.logoutTeam browser, (res) ->
teamsHelpers.loginToTeam browser, targetUser1 , no, ->
browser
.waitForElementVisible welcomeView, 20000
.url myTeamLink
.waitForElementVisible sectionSelector, 20000
.waitForElementNotPresent checkboxSelector, 20000
.expect.element(adminTextSelector).text.to.not.contain 'Admin'
browser
.scrollToElement "#{teammateSectionSelector} .ListView"
.waitForElementVisible teammateSection, 20000
.waitForElementVisible teammateSectionSelector, 20000
.pause 5000
.click selector(1)
.waitForElementNotPresent nthItem(1), 20000
.scrollToElement sectionSelector
.waitForElementNotPresent removeLogoButton, 20000
.waitForElementNotPresent uploadLogoButton, 20000
.waitForElementNotPresent '.HomeAppView--button .custom-link-view .fr .hidden', 20000
.assert.attributeEquals teamNameSelector, 'disabled', 'true'
.pause 1000, callback
leaveTeam: (browser, callback) ->
targetUser1 = invitations[1]
browser
.waitForElementVisible leaveTeamButton, 20000
.click leaveTeamButton
.waitForElementVisible '.kdmodal.kddraggable', 5000
.click forgotPasswordButton
.waitForElementVisible '.kdnotification', 5000
.assert.containsText '.kdnotification.main', 'Check your email'
.pause 5000
.click leaveTeamButton
.waitForElementVisible '.kdmodal.kddraggable', 5000
.clearValue passwordSelector
.setValue passwordSelector, 'PI:PASSWORD:<PASSWORD>END_PI'
.click confirmButton
.waitForElementVisible '.kdnotification', 20000
.assert.containsText '.kdnotification.main', 'Current password cannot be confirmed'
.pause 5000
.click leaveTeamButton
.waitForElementVisible '.kdmodal.kddraggable', 5000
.clearValue passwordSelector
.setValue passwordSelector, PI:PASSWORD:<PASSWORD>END_PI
.click confirmButton
.assert.urlContains helpers.getUrl(yes)
.pause 1000, callback
selector = (index) ->
".HomeApp-Teammate--ListItem:nth-of-type(#{index}) .dropdown "
nthItem = (index) ->
".ButtonWithMenuItemsList li:nth-of-type(#{index})"
|
[
{
"context": "@getAvatarUrlFromUsername = (username) ->\n\tkey = \"avatar_random_#{username}\"\n\tunless Session.get(key)?\n\t\trandom = Math.floor((",
"end": 76,
"score": 0.9974696040153503,
"start": 50,
"tag": "KEY",
"value": "avatar_random_#{username}\""
},
{
"context": "\n\n@updateAvatarOfUsername = (username) ->\n\tkey = \"avatar_random_#{username}\"\n\tSession.set key, Math.round(Math.random() * 1000",
"end": 878,
"score": 0.969382107257843,
"start": 852,
"tag": "KEY",
"value": "avatar_random_#{username}\""
}
] | client/lib/avatar.coffee | akio46/Stitch | 0 | @getAvatarUrlFromUsername = (username) ->
key = "avatar_random_#{username}"
unless Session.get(key)?
random = Math.floor((Math.random() * 500) + 1)
Session.set(key, random)
avatarRandom = Session.get(key)
if not username?
return
if Meteor.isCordova
path = Meteor.absoluteUrl()
else
path = '/'
return "#{path}avatar/#{username}.jpg?_dc=#{avatarRandom}"
Blaze.registerHelper 'avatarUrlFromUsername', getAvatarUrlFromUsername
@getAvatarAsPng = (username, cb) ->
image = new Image
image.src = getAvatarUrlFromUsername(username)
image.onload = ->
canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
context = canvas.getContext('2d')
context.drawImage(image, 0, 0)
cb canvas.toDataURL('image/png')
image.onerror = ->
cb ''
@updateAvatarOfUsername = (username) ->
key = "avatar_random_#{username}"
Session.set key, Math.round(Math.random() * 1000)
for key, room of RoomManager.openedRooms
url = getAvatarUrlFromUsername username
$(room.dom).find(".message[data-username='#{username}'] .avatar-image").css('background-image', "url(#{url})");
return true
| 132197 | @getAvatarUrlFromUsername = (username) ->
key = "<KEY>
unless Session.get(key)?
random = Math.floor((Math.random() * 500) + 1)
Session.set(key, random)
avatarRandom = Session.get(key)
if not username?
return
if Meteor.isCordova
path = Meteor.absoluteUrl()
else
path = '/'
return "#{path}avatar/#{username}.jpg?_dc=#{avatarRandom}"
Blaze.registerHelper 'avatarUrlFromUsername', getAvatarUrlFromUsername
@getAvatarAsPng = (username, cb) ->
image = new Image
image.src = getAvatarUrlFromUsername(username)
image.onload = ->
canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
context = canvas.getContext('2d')
context.drawImage(image, 0, 0)
cb canvas.toDataURL('image/png')
image.onerror = ->
cb ''
@updateAvatarOfUsername = (username) ->
key = "<KEY>
Session.set key, Math.round(Math.random() * 1000)
for key, room of RoomManager.openedRooms
url = getAvatarUrlFromUsername username
$(room.dom).find(".message[data-username='#{username}'] .avatar-image").css('background-image', "url(#{url})");
return true
| true | @getAvatarUrlFromUsername = (username) ->
key = "PI:KEY:<KEY>END_PI
unless Session.get(key)?
random = Math.floor((Math.random() * 500) + 1)
Session.set(key, random)
avatarRandom = Session.get(key)
if not username?
return
if Meteor.isCordova
path = Meteor.absoluteUrl()
else
path = '/'
return "#{path}avatar/#{username}.jpg?_dc=#{avatarRandom}"
Blaze.registerHelper 'avatarUrlFromUsername', getAvatarUrlFromUsername
@getAvatarAsPng = (username, cb) ->
image = new Image
image.src = getAvatarUrlFromUsername(username)
image.onload = ->
canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
context = canvas.getContext('2d')
context.drawImage(image, 0, 0)
cb canvas.toDataURL('image/png')
image.onerror = ->
cb ''
@updateAvatarOfUsername = (username) ->
key = "PI:KEY:<KEY>END_PI
Session.set key, Math.round(Math.random() * 1000)
for key, room of RoomManager.openedRooms
url = getAvatarUrlFromUsername username
$(room.dom).find(".message[data-username='#{username}'] .avatar-image").css('background-image', "url(#{url})");
return true
|
[
{
"context": "om, automatically generated\n# Generator created by Renato \"Hii\" Garcia\n'.source.pwn, .source.inc':\n 'sqrtN':",
"end": 74,
"score": 0.9899902939796448,
"start": 68,
"tag": "NAME",
"value": "Renato"
},
{
"context": "atically generated\n# Generator created by Renato \"Hii\" Garcia\n'.source.pwn, .source.inc':\n 'sqrtN':\n ",
"end": 79,
"score": 0.9868386387825012,
"start": 76,
"tag": "NAME",
"value": "Hii"
},
{
"context": "ally generated\n# Generator created by Renato \"Hii\" Garcia\n'.source.pwn, .source.inc':\n 'sqrtN':\n 'prefi",
"end": 87,
"score": 0.9907976984977722,
"start": 81,
"tag": "NAME",
"value": "Garcia"
}
] | snippets/3DTryg.cson | Wuzi/language-pawn | 4 | # Snippets for Atom, automatically generated
# Generator created by Renato "Hii" Garcia
'.source.pwn, .source.inc':
'sqrtN':
'prefix': 'sqrtN'
'body': 'sqrtN(${1:Float:value}, ${2:Float:exponent})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'abs':
'prefix': 'abs'
'body': 'abs(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'fabs':
'prefix': 'fabs'
'body': 'fabs(${1:Float:value})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'power':
'prefix': 'power'
'body': 'power(${1:value}, ${2:Float:exponent})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ctg':
'prefix': 'ctg'
'body': 'ctg(${1:Float:value}, ${2:anglemode:mode=radian})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'secans':
'prefix': 'secans'
'body': 'secans(${1:Float:value}, ${2:anglemode:mode=radian})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'cosecans':
'prefix': 'cosecans'
'body': 'cosecans(${1:Float:value}, ${2:anglemode:mode=radian})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsEven':
'prefix': 'IsEven'
'body': 'IsEven(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'RandomFloat':
'prefix': 'RandomFloat'
'body': 'RandomFloat(${1:Float:min}, ${2:Float:max}, ${3:accuracy = 4})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'single_clock':
'prefix': 'single_clock'
'body': 'single_clock(${1:max}, ${2:id})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'even_clock':
'prefix': 'even_clock'
'body': 'even_clock(${1:max}, ${2:id})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'uneven_clock':
'prefix': 'uneven_clock'
'body': 'uneven_clock(${1:max}, ${2:id})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTZ':
'prefix': 'NLTZ'
'body': 'NLTZ(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTZ':
'prefix': 'NMTZ'
'body': 'NMTZ(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTZF':
'prefix': 'NLTZF'
'body': 'NLTZF(${1:Float:value})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTZF':
'prefix': 'NMTZF'
'body': 'NMTZF(${1:Float:value})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTV':
'prefix': 'NLTV'
'body': 'NLTV(${1:value}, ${2:min})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTV':
'prefix': 'NMTV'
'body': 'NMTV(${1:value}, ${2:max})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTVF':
'prefix': 'NLTVF'
'body': 'NLTVF(${1:Float:value}, ${2:Float:min})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTVF':
'prefix': 'NMTVF'
'body': 'NMTVF(${1:Float:value}, ${2:Float:max})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CompRotation':
'prefix': 'CompRotation'
'body': 'CompRotation(${1:rotation}, ${2:&crotation=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'DeCompRotation':
'prefix': 'DeCompRotation'
'body': 'DeCompRotation(${1:rotation}, ${2:&crotation=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CompRotationFloat':
'prefix': 'CompRotationFloat'
'body': 'CompRotationFloat(${1:Float:rotation}, ${2:&Float:crotation=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'DeCompRotationFloat':
'prefix': 'DeCompRotationFloat'
'body': 'DeCompRotationFloat(${1:Float:rotation}, ${2:&Float:crotation=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsRotationTest':
'prefix': 'IsRotationTest'
'body': 'IsRotationTest(${1:Float:rotation}, ${2:Float:r_min}, ${3:Float:r_max})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetRotationMatrixEuler':
'prefix': 'Tryg3D_GetRotationMatrixEuler'
'body': 'Tryg3D_GetRotationMatrixEuler(${1:Float:matrix[][]}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz}, ${5:T3D:eulermode:mode=T3D:euler_default})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_MatrixRotate':
'prefix': 'Tryg3D_MatrixRotate'
'body': 'Tryg3D_MatrixRotate(${1:Float:matrix[][]}, ${2:Float:oX}, ${3:Float:oY}, ${4:Float:oZ}, ${5:&Float:x}, ${6:&Float:y}, ${7:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GivePlayerDamage':
'prefix': 'Tryg3D_GivePlayerDamage'
'body': 'Tryg3D_GivePlayerDamage(${1:targetid}, ${2:Float:damage}, ${3:playerid}, ${4:weaponid}, ${5:bool:force_spawn=true}, ${6:bool:deathmsg=true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetWeaponDamage':
'prefix': 'Tryg3D_GetWeaponDamage'
'body': 'Tryg3D_GetWeaponDamage(${1:weaponid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_SwapInt':
'prefix': 'Tryg3D_SwapInt'
'body': 'Tryg3D_SwapInt(${1:variable1}, ${2:variable2})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountPlayers':
'prefix': 'CountPlayers'
'body': 'CountPlayers(${1:bool:isplayer=true}, ${2:bool:isnpc=true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountActors':
'prefix': 'CountActors'
'body': 'CountActors()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'RecoilFloat':
'prefix': 'RecoilFloat'
'body': 'RecoilFloat(${1:Float:value}, ${2:Float:recoil})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'RecoilVector':
'prefix': 'RecoilVector'
'body': 'RecoilVector(${1:&Float:vx}, ${2:&Float:vy}, ${3:&Float:vz}, ${4:Float:sx}, ${5:Float:sy}, ${6:Float:sz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftDegreeToRadian':
'prefix': 'ShiftDegreeToRadian'
'body': 'ShiftDegreeToRadian(${1:Float:deg})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftDegreeToRadianEx':
'prefix': 'ShiftDegreeToRadianEx'
'body': 'ShiftDegreeToRadianEx(${1:Float:deg})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftDegreeToGrades':
'prefix': 'ShiftDegreeToGrades'
'body': 'ShiftDegreeToGrades(${1:Float:deg})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRadianToDegree':
'prefix': 'ShiftRadianToDegree'
'body': 'ShiftRadianToDegree(${1:Float:rad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRadianToDegreeEx':
'prefix': 'ShiftRadianToDegreeEx'
'body': 'ShiftRadianToDegreeEx(${1:Float:rad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRadianToGrades':
'prefix': 'ShiftRadianToGrades'
'body': 'ShiftRadianToGrades(${1:Float:rad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftGradesToDegree':
'prefix': 'ShiftGradesToDegree'
'body': 'ShiftGradesToDegree(${1:Float:grad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftGradesToRadian':
'prefix': 'ShiftGradesToRadian'
'body': 'ShiftGradesToRadian(${1:Float:grad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomHit':
'prefix': 'GetRandomHit'
'body': 'GetRandomHit(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:range}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPoints1D':
'prefix': 'GetDistanceBetweenPoints1D'
'body': 'GetDistanceBetweenPoints1D(${1:Float:x1}, ${2:Float:x2})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPoints2D':
'prefix': 'GetDistanceBetweenPoints2D'
'body': 'GetDistanceBetweenPoints2D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:x2}, ${4:Float:y2})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPoints3D':
'prefix': 'GetDistanceBetweenPoints3D'
'body': 'GetDistanceBetweenPoints3D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:z1}, ${4:Float:x2}, ${5:Float:y2}, ${6:Float:z2})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFront2D':
'prefix': 'GetPointInFront2D'
'body': 'GetPointInFront2D(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFront3D':
'prefix': 'GetPointInFront3D'
'body': 'GetPointInFront3D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:Float:radius}, ${7:&Float:tx}, ${8:&Float:ty}, ${9:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfPlayer':
'prefix': 'GetPointInFrontOfPlayer'
'body': 'GetPointInFrontOfPlayer(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera2D':
'prefix': 'GetPointInFrontOfCamera2D'
'body': 'GetPointInFrontOfCamera2D(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera3D':
'prefix': 'GetPointInFrontOfCamera3D'
'body': 'GetPointInFrontOfCamera3D(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRotationFor2Point2D':
'prefix': 'GetRotationFor2Point2D'
'body': 'GetRotationFor2Point2D(${1:Float:x}, ${2:Float:y}, ${3:Float:tx}, ${4:Float:ty}, ${5:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRotationFor2Point3D':
'prefix': 'GetRotationFor2Point3D'
'body': 'GetRotationFor2Point3D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:&Float:rx}, ${8:&Float:rz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ConvertMTARaceRotation':
'prefix': 'ConvertMTARaceRotation'
'body': 'ConvertMTARaceRotation(${1:Float:rotation1}, ${2:Float:rotation2}, ${3:Float:rotation3}, ${4:&Float:rx}, ${5:&Float:ry}, ${6:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ConvertToMTARaceRotation':
'prefix': 'ConvertToMTARaceRotation'
'body': 'ConvertToMTARaceRotation(${1:Float:rx}, ${2:Float:ry}, ${3:Float:rz}, ${4:&Float:rotation1}, ${5:&Float:rotation2}, ${6:&Float:rotation3})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetMoveTime':
'prefix': 'GetMoveTime'
'body': 'GetMoveTime(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:Float:speed}, ${8:&rtime=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetSpeedForMoveTime':
'prefix': 'GetSpeedForMoveTime'
'body': 'GetSpeedForMoveTime(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:&Float:speed}, ${8:rtime})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleRotation':
'prefix': 'GetVehicleRotation'
'body': 'GetVehicleRotation(${1:vehicleid}, ${2:&Float:rx}, ${3:&Float:ry}, ${4:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle2D':
'prefix': 'GetPointInFrontOfVehicle2D'
'body': 'GetPointInFrontOfVehicle2D(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle3D':
'prefix': 'GetPointInFrontOfVehicle3D'
'body': 'GetPointInFrontOfVehicle3D(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCameraRotation':
'prefix': 'GetPlayerCameraRotation'
'body': 'GetPlayerCameraRotation(${1:playerid}, ${2:&Float:rx}, ${3:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerCameraRotation':
'prefix': 'SetPlayerCameraRotation'
'body': 'SetPlayerCameraRotation(${1:playerid}, ${2:Float:rx}, ${3:Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCameraZAngle':
'prefix': 'GetPlayerCameraZAngle'
'body': 'GetPlayerCameraZAngle(${1:playerid}, ${2:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerCameraZAngle':
'prefix': 'SetPlayerCameraZAngle'
'body': 'SetPlayerCameraZAngle(${1:playerid}, ${2:Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point2D':
'prefix': 'GetPointFor2Point2D'
'body': 'GetPointFor2Point2D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:x2}, ${4:Float:y2}, ${5:Float:percent_size}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point3D':
'prefix': 'GetPointFor2Point3D'
'body': 'GetPointFor2Point3D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:z1}, ${4:Float:x2}, ${5:Float:y2}, ${6:Float:z2}, ${7:Float:percent_size}, ${8:&Float:tx}, ${9:&Float:ty}, ${10:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point2DEx':
'prefix': 'GetPointFor2Point2DEx'
'body': 'GetPointFor2Point2DEx(${1:Float:x1}, ${2:Float:y1}, ${3:Float:x2}, ${4:Float:y2}, ${5:Float:distance}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point3DEx':
'prefix': 'GetPointFor2Point3DEx'
'body': 'GetPointFor2Point3DEx(${1:Float:x1}, ${2:Float:y1}, ${3:Float:z1}, ${4:Float:x2}, ${5:Float:y2}, ${6:Float:z2}, ${7:Float:distance}, ${8:&Float:tx}, ${9:&Float:ty}, ${10:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftVectorToRotation':
'prefix': 'ShiftVectorToRotation'
'body': 'ShiftVectorToRotation(${1:Float:vx}, ${2:Float:vy}, ${3:Float:vz}, ${4:&Float:rx}, ${5:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRotationToVector':
'prefix': 'ShiftRotationToVector'
'body': 'ShiftRotationToVector(${1:Float:rx}, ${2:Float:rz}, ${3:&Float:vx}, ${4:&Float:vy}, ${5:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnClock':
'prefix': 'GetRandomPointOnClock'
'body': 'GetRandomPointOnClock(${1:Float:x}, ${2:Float:y}, ${3:Float:radius}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:trz}, ${7:Float:rz = INVALID_ROTATION})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCircle':
'prefix': 'GetRandomPointInCircle'
'body': 'GetRandomPointInCircle(${1:Float:x}, ${2:Float:y}, ${3:Float:radius}, ${4:&Float:tx}, ${5:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCylinderEx':
'prefix': 'GetRandomPointInCylinderEx'
'body': 'GetRandomPointInCylinderEx(${1:Float:x}, ${2:Float:y}, ${3:Float:minz}, ${4:Float:maxz}, ${5:Float:radius}, ${6:&Float:tx}, ${7:&Float:ty}, ${8:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInSphere':
'prefix': 'GetRandomPointInSphere'
'body': 'GetRandomPointInSphere(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInRectangle':
'prefix': 'GetRandomPointInRectangle'
'body': 'GetRandomPointInRectangle(${1:Float:minx}, ${2:Float:miny}, ${3:Float:maxx}, ${4:Float:maxy}, ${5:&Float:tx}, ${6:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCube':
'prefix': 'GetRandomPointInCube'
'body': 'GetRandomPointInCube(${1:Float:minx}, ${2:Float:miny}, ${3:Float:minz}, ${4:Float:maxx}, ${5:Float:maxy}, ${6:Float:maxz}, ${7:&Float:tx}, ${8:&Float:ty}, ${9:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCircularSector':
'prefix': 'GetRandomPointInCircularSector'
'body': 'GetRandomPointInCircularSector(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:Float:view_angle}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnCircle':
'prefix': 'GetRandomPointOnCircle'
'body': 'GetRandomPointOnCircle(${1:Float:x}, ${2:Float:y}, ${3:Float:radius}, ${4:&Float:tx}, ${5:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnSphere':
'prefix': 'GetRandomPointOnSphere'
'body': 'GetRandomPointOnSphere(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnCircularSector':
'prefix': 'GetRandomPointOnCircularSector'
'body': 'GetRandomPointOnCircularSector(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:Float:view_angle}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointBetween2Points2D':
'prefix': 'IsPointBetween2Points2D'
'body': 'IsPointBetween2Points2D(${1:Float:px}, ${2:Float:py}, ${3:Float:xA}, ${4:Float:yA}, ${5:Float:xB}, ${6:Float:yB})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointBetween2Points3D':
'prefix': 'IsPointBetween2Points3D'
'body': 'IsPointBetween2Points3D(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:xA}, ${5:Float:yA}, ${6:Float:zA}, ${7:Float:xB}, ${8:Float:yB}, ${9:Float:zB})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointNearly2Points2D':
'prefix': 'IsPointNearly2Points2D'
'body': 'IsPointNearly2Points2D(${1:Float:px}, ${2:Float:py}, ${3:Float:xA}, ${4:Float:yA}, ${5:Float:xB}, ${6:Float:yB}, ${7:Float:maxdist})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointNearly2Points3D':
'prefix': 'IsPointNearly2Points3D'
'body': 'IsPointNearly2Points3D(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:xA}, ${5:Float:yA}, ${6:Float:zA}, ${7:Float:xB}, ${8:Float:yB}, ${9:Float:zB}, ${10:Float:maxdist})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCircle':
'prefix': 'IsPointInCircle'
'body': 'IsPointInCircle(${1:Float:px}, ${2:Float:py}, ${3:Float:x}, ${4:Float:y}, ${5:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCylinder':
'prefix': 'IsPointInCylinder'
'body': 'IsPointInCylinder(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:xA}, ${5:Float:yA}, ${6:Float:zA}, ${7:Float:xB}, ${8:Float:yB}, ${9:Float:zB}, ${10:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCylinderEx':
'prefix': 'IsPointInCylinderEx'
'body': 'IsPointInCylinderEx(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:minz}, ${7:Float:maxz}, ${8:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInSphere':
'prefix': 'IsPointInSphere'
'body': 'IsPointInSphere(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInRectangle':
'prefix': 'IsPointInRectangle'
'body': 'IsPointInRectangle(${1:Float:x}, ${2:Float:y}, ${3:Float:minx}, ${4:Float:miny}, ${5:Float:maxx}, ${6:Float:maxy})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCube':
'prefix': 'IsPointInCube'
'body': 'IsPointInCube(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:minx}, ${5:Float:miny}, ${6:Float:minz}, ${7:Float:maxx}, ${8:Float:maxy}, ${9:Float:maxz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInPolygon':
'prefix': 'IsPointInPolygon'
'body': 'IsPointInPolygon(${1:Float:x}, ${2:Float:y}, ${3:Float:points[]}, ${4:maxpoints = sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCircularSector':
'prefix': 'IsPointInCircularSector'
'body': 'IsPointInCircularSector(${1:Float:px}, ${2:Float:py}, ${3:Float:x}, ${4:Float:y}, ${5:Float:rz}, ${6:Float:radius}, ${7:Float:view_angle})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInSphericalSector':
'prefix': 'IsPointInSphericalSector'
'body': 'IsPointInSphericalSector(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:Float:rx}, ${8:Float:rz}, ${9:Float:radius}, ${10:Float:vrx}, ${11:Float:vrz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCircle':
'prefix': 'IsPlayerInCircle'
'body': 'IsPlayerInCircle(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCylinder':
'prefix': 'IsPlayerInCylinder'
'body': 'IsPlayerInCylinder(${1:playerid}, ${2:Float:xA}, ${3:Float:yA}, ${4:Float:zA}, ${5:Float:xB}, ${6:Float:yB}, ${7:Float:zB}, ${8:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCylinderEx':
'prefix': 'IsPlayerInCylinderEx'
'body': 'IsPlayerInCylinderEx(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:minz}, ${5:Float:maxz}, ${6:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInSphere':
'prefix': 'IsPlayerInSphere'
'body': 'IsPlayerInSphere(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInRectangle':
'prefix': 'IsPlayerInRectangle'
'body': 'IsPlayerInRectangle(${1:playerid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:maxx}, ${5:Float:maxy})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCube':
'prefix': 'IsPlayerInCube'
'body': 'IsPlayerInCube(${1:playerid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:minz}, ${5:Float:maxx}, ${6:Float:maxy}, ${7:Float:maxz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInPolygon':
'prefix': 'IsPlayerInPolygon'
'body': 'IsPlayerInPolygon(${1:playerid}, ${2:Float:points[]}, ${3:maxpoints = sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCircularSector':
'prefix': 'IsPlayerInCircularSector'
'body': 'IsPlayerInCircularSector(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:rz}, ${5:Float:radius}, ${6:Float:view_angle})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInSphericalSector':
'prefix': 'IsPlayerInSphericalSector'
'body': 'IsPlayerInSphericalSector(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:radius}, ${8:Float:vrx}, ${9:Float:vrz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsProbable':
'prefix': 'IsProbable'
'body': 'IsProbable(${1:chance})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CalculatePercent':
'prefix': 'CalculatePercent'
'body': 'CalculatePercent(${1:Float:value}, ${2:Float:maxvalue})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerTargetAngle':
'prefix': 'GetPlayerTargetAngle'
'body': 'GetPlayerTargetAngle(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerTargetAngle':
'prefix': 'SetPlayerTargetAngle'
'body': 'SetPlayerTargetAngle(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerTargetPlayerAngle':
'prefix': 'GetPlayerTargetPlayerAngle'
'body': 'GetPlayerTargetPlayerAngle(${1:playerid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerTargetPlayerAngle':
'prefix': 'SetPlayerTargetPlayerAngle'
'body': 'SetPlayerTargetPlayerAngle(${1:playerid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleSpeed':
'prefix': 'GetVehicleSpeed'
'body': 'GetVehicleSpeed(${1:vehicleid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerSpeed':
'prefix': 'GetPlayerSpeed'
'body': 'GetPlayerSpeed(${1:playerid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CreateDynamicExplosion':
'prefix': 'CreateDynamicExplosion'
'body': 'CreateDynamicExplosion(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:type}, ${5:Float:radius}, ${6:worldid=-1}, ${7:interiorid=-1}, ${8:playerid=-1}, ${9:Float:distance=200.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleFlags':
'prefix': 'GetVehicleFlags'
'body': 'GetVehicleFlags(${1:vehicleid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleFlagsByModel':
'prefix': 'GetVehicleFlagsByModel'
'body': 'GetVehicleFlagsByModel(${1:modelid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleFlag':
'prefix': 'IsVehicleFlag'
'body': 'IsVehicleFlag(${1:value}, ${2:flag})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerOrientationPos':
'prefix': 'GetPlayerOrientationPos'
'body': 'GetPlayerOrientationPos(${1:playerid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz}, ${7:isactor=false})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleOrientationPos':
'prefix': 'GetVehicleOrientationPos'
'body': 'GetVehicleOrientationPos(${1:vehicleid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectOrientationPos':
'prefix': 'GetObjectOrientationPos'
'body': 'GetObjectOrientationPos(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetWeaponShotPos':
'prefix': 'GetWeaponShotPos'
'body': 'GetWeaponShotPos(${1:playerid}, ${2:hittype}, ${3:&Float:fx}, ${4:&Float:fy}, ${5:&Float:fz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetActorDistanceFromPoint':
'prefix': 'GetActorDistanceFromPoint'
'body': 'GetActorDistanceFromPoint(${1:actorid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectDistanceFromPoint':
'prefix': 'GetObjectDistanceFromPoint'
'body': 'GetObjectDistanceFromPoint(${1:objectid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPlayers':
'prefix': 'GetDistanceBetweenPlayers'
'body': 'GetDistanceBetweenPlayers(${1:playerid_a}, ${2:playerid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenVehicles':
'prefix': 'GetDistanceBetweenVehicles'
'body': 'GetDistanceBetweenVehicles(${1:vehicleid_a}, ${2:vehicleid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenObjects':
'prefix': 'GetDistanceBetweenObjects'
'body': 'GetDistanceBetweenObjects(${1:objectid_a}, ${2:objectid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerActorDistance':
'prefix': 'GetPlayerActorDistance'
'body': 'GetPlayerActorDistance(${1:playerid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerVehicleDistance':
'prefix': 'GetPlayerVehicleDistance'
'body': 'GetPlayerVehicleDistance(${1:playerid}, ${2:vehicleid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerObjectDistance':
'prefix': 'GetPlayerObjectDistance'
'body': 'GetPlayerObjectDistance(${1:playerid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerLookAtPlayer':
'prefix': 'SetPlayerLookAtPlayer'
'body': 'SetPlayerLookAtPlayer(${1:playerid}, ${2:targetid}, ${3:cut = CAMERA_CUT})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCameraLookAt':
'prefix': 'GetPlayerCameraLookAt'
'body': 'GetPlayerCameraLookAt(${1:playerid}, ${2:&Float:x}, ${3:&Float:y}, ${4:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerLookAtSky':
'prefix': 'IsPlayerLookAtSky'
'body': 'IsPlayerLookAtSky(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleUpVector':
'prefix': 'GetVehicleUpVector'
'body': 'GetVehicleUpVector(${1:vehicleid}, ${2:&Float:vx}, ${3:&Float:vy}, ${4:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleUpPos':
'prefix': 'GetVehicleUpPos'
'body': 'GetVehicleUpPos(${1:vehicleid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleDownPos':
'prefix': 'GetVehicleDownPos'
'body': 'GetVehicleDownPos(${1:vehicleid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectRotationQuat':
'prefix': 'GetObjectRotationQuat'
'body': 'GetObjectRotationQuat(${1:objectid}, ${2:&Float:qw}, ${3:&Float:qx}, ${4:&Float:qy}, ${5:&Float:qz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectUpVector':
'prefix': 'GetObjectUpVector'
'body': 'GetObjectUpVector(${1:objectid}, ${2:&Float:vx}, ${3:&Float:vy}, ${4:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectUpPos':
'prefix': 'GetObjectUpPos'
'body': 'GetObjectUpPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectDownPos':
'prefix': 'GetObjectDownPos'
'body': 'GetObjectDownPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetQuatUpVector':
'prefix': 'GetQuatUpVector'
'body': 'GetQuatUpVector(${1:Float:qw}, ${2:Float:qx}, ${3:Float:qy}, ${4:Float:qz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetQuatFromRot':
'prefix': 'GetQuatFromRot'
'body': 'GetQuatFromRot(${1:Float:rx}, ${2:Float:ry}, ${3:Float:rz}, ${4:&Float:qw}, ${5:&Float:qx}, ${6:&Float:qy}, ${7:&Float:qz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLineSize2D':
'prefix': 'GetLineSize2D'
'body': 'GetLineSize2D(${1:Float:points[][]}, ${2:maxpoints=sizeof(points})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLineSize3D':
'prefix': 'GetLineSize3D'
'body': 'GetLineSize3D(${1:Float:points[][]}, ${2:maxpoints=sizeof(points})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointToPointVector':
'prefix': 'GetPointToPointVector'
'body': 'GetPointToPointVector(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:&Float:vx}, ${8:&Float:vy}, ${9:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerToPointVector':
'prefix': 'GetPlayerToPointVector'
'body': 'GetPlayerToPointVector(${1:playerid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectToPointVector':
'prefix': 'GetObjectToPointVector'
'body': 'GetObjectToPointVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleToPointVector':
'prefix': 'GetVehicleToPointVector'
'body': 'GetVehicleToPointVector(${1:vehicleid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleInRangeOfPoint':
'prefix': 'IsVehicleInRangeOfPoint'
'body': 'IsVehicleInRangeOfPoint(${1:vehicleid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorInRangeOfPoint':
'prefix': 'IsActorInRangeOfPoint'
'body': 'IsActorInRangeOfPoint(${1:actorid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectInRangeOfPoint':
'prefix': 'IsObjectInRangeOfPoint'
'body': 'IsObjectInRangeOfPoint(${1:objectid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftLineRotation':
'prefix': 'ShiftLineRotation'
'body': 'ShiftLineRotation(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:Float:rx}, ${8:Float:ry}, ${9:Float:rz}, ${10:&Float:nX}, ${11:&Float:nY}, ${12:&Float:nZ})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftLineRotationVector':
'prefix': 'ShiftLineRotationVector'
'body': 'ShiftLineRotationVector(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:Float:rx}, ${8:Float:ry}, ${9:Float:rz}, ${10:&Float:nX}, ${11:&Float:nY}, ${12:&Float:nZ})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerRotatedVector':
'prefix': 'GetPlayerRotatedVector'
'body': 'GetPlayerRotatedVector(${1:playerid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectRotatedVector':
'prefix': 'GetObjectRotatedVector'
'body': 'GetObjectRotatedVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleRotatedVector':
'prefix': 'GetVehicleRotatedVector'
'body': 'GetVehicleRotatedVector(${1:vehicleid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsFloor2D':
'prefix': 'GetArcPointsFloor2D'
'body': 'GetArcPointsFloor2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsCellar2D':
'prefix': 'GetArcPointsCellar2D'
'body': 'GetArcPointsCellar2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsStarboard2D':
'prefix': 'GetArcPointsStarboard2D'
'body': 'GetArcPointsStarboard2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsLarboard2D':
'prefix': 'GetArcPointsLarboard2D'
'body': 'GetArcPointsLarboard2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInSphericalSectorEx':
'prefix': 'IsPointInSphericalSectorEx'
'body': 'IsPointInSphericalSectorEx(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:Float:rx}, ${8:Float:rz}, ${9:Float:radius}, ${10:Float:vrx}, ${11:Float:vrz}, ${12:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerOnPlayerScreen':
'prefix': 'IsPlayerOnPlayerScreen'
'body': 'IsPlayerOnPlayerScreen(${1:playerid}, ${2:targetid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleOnPlayerScreen':
'prefix': 'IsVehicleOnPlayerScreen'
'body': 'IsVehicleOnPlayerScreen(${1:playerid}, ${2:vehicleid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectOnPlayerScreen':
'prefix': 'IsObjectOnPlayerScreen'
'body': 'IsObjectOnPlayerScreen(${1:playerid}, ${2:objectid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorOnPlayerScreen':
'prefix': 'IsActorOnPlayerScreen'
'body': 'IsActorOnPlayerScreen(${1:playerid}, ${2:actorid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerOnFakeScreen':
'prefix': 'IsPlayerOnFakeScreen'
'body': 'IsPlayerOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:targetid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleOnFakeScreen':
'prefix': 'IsVehicleOnFakeScreen'
'body': 'IsVehicleOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:vehicleid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectOnFakeScreen':
'prefix': 'IsObjectOnFakeScreen'
'body': 'IsObjectOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:objectid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorOnFakeScreen':
'prefix': 'IsActorOnFakeScreen'
'body': 'IsActorOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:actorid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerSkydiving':
'prefix': 'IsPlayerSkydiving'
'body': 'IsPlayerSkydiving(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerUsingParachute':
'prefix': 'IsPlayerUsingParachute'
'body': 'IsPlayerUsingParachute(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerAiming':
'prefix': 'IsPlayerAiming'
'body': 'IsPlayerAiming(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerStay':
'prefix': 'IsPlayerStay'
'body': 'IsPlayerStay(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerRunning':
'prefix': 'IsPlayerRunning'
'body': 'IsPlayerRunning(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerSwim':
'prefix': 'IsPlayerSwim'
'body': 'IsPlayerSwim(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerJump':
'prefix': 'IsPlayerJump'
'body': 'IsPlayerJump(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerParaFall':
'prefix': 'IsPlayerParaFall'
'body': 'IsPlayerParaFall(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerParaGlide':
'prefix': 'IsPlayerParaGlide'
'body': 'IsPlayerParaGlide(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerFall':
'prefix': 'IsPlayerFall'
'body': 'IsPlayerFall(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Get3DTrygModules':
'prefix': 'Get3DTrygModules'
'body': 'Get3DTrygModules(${1:&modules_count=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsTryg3DModuleLoaded':
'prefix': 'IsTryg3DModuleLoaded'
'body': 'IsTryg3DModuleLoaded(${1:Tryg3DModule:moduleid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Get3DTrygEfficiency':
'prefix': 'Get3DTrygEfficiency'
'body': 'Get3DTrygEfficiency(${1:bool:use_colandreas=false})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Get3DTrygErrorCount':
'prefix': 'Get3DTrygErrorCount'
'body': 'Get3DTrygErrorCount()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Reset3DTrygErrorCount':
'prefix': 'Reset3DTrygErrorCount'
'body': 'Reset3DTrygErrorCount()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_SetStreamDistance':
'prefix': 'Tryg3D_SetStreamDistance'
'body': 'Tryg3D_SetStreamDistance(${1:Float:streamdistance})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetStreamDistance':
'prefix': 'Tryg3D_GetStreamDistance'
'body': 'Tryg3D_GetStreamDistance()'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetTryg3DActiveCount':
'prefix': 'GetTryg3DActiveCount'
'body': 'GetTryg3DActiveCount()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftPositionToOrion':
'prefix': 'ShiftPositionToOrion'
'body': 'ShiftPositionToOrion(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:&Float:orion}, ${5:&Float:lon}, ${6:&Float:lat})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftOrionToPosition':
'prefix': 'ShiftOrionToPosition'
'body': 'ShiftOrionToPosition(${1:Float:orion}, ${2:Float:lon}, ${3:Float:lat}, ${4:&Float:x}, ${5:&Float:y}, ${6:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'randomex':
'prefix': 'randomex'
'body': 'randomex(${1:min}, ${2:max})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_KeyPressed':
'prefix': 'Tryg3D_KeyPressed'
'body': 'Tryg3D_KeyPressed(${1:key})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_KeyReleased':
'prefix': 'Tryg3D_KeyReleased'
'body': 'Tryg3D_KeyReleased(${1:key})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_KeyHolding':
'prefix': 'Tryg3D_KeyHolding'
'body': 'Tryg3D_KeyHolding(${1:key})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetSAMIncludeVersion':
'prefix': 'GetSAMIncludeVersion'
'body': 'GetSAMIncludeVersion(${1:value}, ${2:name[]}, ${3:maxdest = sizeof(name})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'DisableADMLogging':
'prefix': 'DisableADMLogging'
'body': 'DisableADMLogging(${1:bool:disable})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SecToTimeDay':
'prefix': 'SecToTimeDay'
'body': 'SecToTimeDay(${1:second})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MSToTimeDay':
'prefix': 'MSToTimeDay'
'body': 'MSToTimeDay(${1:millisecond})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SecToTime':
'prefix': 'SecToTime'
'body': 'SecToTime(${1:second})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MSToTime':
'prefix': 'MSToTime'
'body': 'MSToTime(${1:millisecond})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SecToTimeMini':
'prefix': 'SecToTimeMini'
'body': 'SecToTimeMini(${1:second})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MSToTimeMini':
'prefix': 'MSToTimeMini'
'body': 'MSToTimeMini(${1:millisecond})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectOrientationPos':
'prefix': 'GetDynamicObjectOrientationPos'
'body': 'GetDynamicObjectOrientationPos(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenDynamicObject':
'prefix': 'GetDistanceBetweenDynamicObject'
'body': 'GetDistanceBetweenDynamicObject(${1:objectid_a}, ${2:objectid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerDynamicObjectDistance':
'prefix': 'GetPlayerDynamicObjectDistance'
'body': 'GetPlayerDynamicObjectDistance(${1:playerid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectRotationQuat':
'prefix': 'GetDynamicObjectRotationQuat'
'body': 'GetDynamicObjectRotationQuat(${1:objectid}, ${2:&Float:qw}, ${3:&Float:qx}, ${4:&Float:qy}, ${5:&Float:qz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectUpVector':
'prefix': 'GetDynamicObjectUpVector'
'body': 'GetDynamicObjectUpVector(${1:objectid}, ${2:&Float:vx}, ${3:&Float:vy}, ${4:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectUpPos':
'prefix': 'GetDynamicObjectUpPos'
'body': 'GetDynamicObjectUpPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectDownPos':
'prefix': 'GetDynamicObjectDownPos'
'body': 'GetDynamicObjectDownPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectToPointVector':
'prefix': 'GetDynamicObjectToPointVector'
'body': 'GetDynamicObjectToPointVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectDistFromPoint':
'prefix': 'GetDynamicObjectDistFromPoint'
'body': 'GetDynamicObjectDistFromPoint(${1:objectid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectInRangeOfPoint':
'prefix': 'IsDynamicObjectInRangeOfPoint'
'body': 'IsDynamicObjectInRangeOfPoint(${1:objectid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerAbsolutePosition':
'prefix': 'SetPlayerAbsolutePosition'
'body': 'SetPlayerAbsolutePosition(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:angle}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:compensatedtime = -1})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerAbsolutePositionVeh':
'prefix': 'SetPlayerAbsolutePositionVeh'
'body': 'SetPlayerAbsolutePositionVeh(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:angle}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:compensatedtime = -1})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectRotatedVector':
'prefix': 'GetDynamicObjectRotatedVector'
'body': 'GetDynamicObjectRotatedVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectOnPlayerScreen':
'prefix': 'IsDynamicObjectOnPlayerScreen'
'body': 'IsDynamicObjectOnPlayerScreen(${1:playerid}, ${2:objectid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectOnFakeScreen':
'prefix': 'IsDynamicObjectOnFakeScreen'
'body': 'IsDynamicObjectOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:objectid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicActorDistFromPoint':
'prefix': 'GetDynamicActorDistFromPoint'
'body': 'GetDynamicActorDistFromPoint(${1:actorid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerDynamicActorDistance':
'prefix': 'GetPlayerDynamicActorDistance'
'body': 'GetPlayerDynamicActorDistance(${1:playerid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorInRangeOfPoint':
'prefix': 'IsDynamicActorInRangeOfPoint'
'body': 'IsDynamicActorInRangeOfPoint(${1:actorid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicActorOrientationPos':
'prefix': 'GetDynamicActorOrientationPos'
'body': 'GetDynamicActorOrientationPos(${1:actorid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorOnPlayerScreen':
'prefix': 'IsDynamicActorOnPlayerScreen'
'body': 'IsDynamicActorOnPlayerScreen(${1:playerid}, ${2:actorid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorOnFakeScreen':
'prefix': 'IsDynamicActorOnFakeScreen'
'body': 'IsDynamicActorOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:actorid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_IsValidStreamer':
'prefix': 'Tryg3D_IsValidStreamer'
'body': 'Tryg3D_IsValidStreamer(${1:version})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetStreamerVersionName':
'prefix': 'Tryg3D_GetStreamerVersionName'
'body': 'Tryg3D_GetStreamerVersionName(${1:name[]}, ${2:value = TRYG3D_GET_STREAMER_VERSION}, ${3:maxdest = sizeof(name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_CheckStreamerVersion':
'prefix': 'Tryg3D_CheckStreamerVersion'
'body': 'Tryg3D_CheckStreamerVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectOrientPosCol':
'prefix': 'GetDynamicObjectOrientPosCol'
'body': 'GetDynamicObjectOrientPosCol(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectCollisionFlags':
'prefix': 'GetDynamicObjectCollisionFlags'
'body': 'GetDynamicObjectCollisionFlags(${1:objectid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicActorOrientPosCol':
'prefix': 'GetDynamicActorOrientPosCol'
'body': 'GetDynamicActorOrientPosCol(${1:actorid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetNPCAbsolutePosition':
'prefix': 'SetNPCAbsolutePosition'
'body': 'SetNPCAbsolutePosition(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:angle}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:compensatedtime = -1})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCDynamicActorDistance':
'prefix': 'GetNPCDynamicActorDistance'
'body': 'GetNPCDynamicActorDistance(${1:npcid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MapAndreasFindZ':
'prefix': 'MapAndreasFindZ'
'body': 'MapAndreasFindZ(${1:Float:x}, ${2:Float:y}, ${3:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetGroundRotation':
'prefix': 'GetGroundRotation'
'body': 'GetGroundRotation(${1:Float:x}, ${2:Float:y}, ${3:Float:size}, ${4:&Float:rx}, ${5:&Float:ry})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOnGround':
'prefix': 'GetPointInFrontOnGround'
'body': 'GetPointInFrontOnGround(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:&Float:tx}, ${7:&Float:ty}, ${8:&Float:tz}, ${9:Float:max_distance})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInWaterFrontOfPlayer':
'prefix': 'IsPointInWaterFrontOfPlayer'
'body': 'IsPointInWaterFrontOfPlayer(${1:playerid}, ${2:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInWater':
'prefix': 'IsPointInWater'
'body': 'IsPointInWater(${1:Float:x}, ${2:Float:y}, ${3:Float:z=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsMapAndreasInit':
'prefix': 'IsMapAndreasInit'
'body': 'IsMapAndreasInit()'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SafeMapAndreasInit':
'prefix': 'SafeMapAndreasInit'
'body': 'SafeMapAndreasInit(${1:mode = MAP_ANDREAS_MODE_FULL}, ${2:name[]=\"\"}, ${3:len=sizeof(name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MovePointCol':
'prefix': 'MovePointCol'
'body': 'MovePointCol(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MovePointColCutLine':
'prefix': 'MovePointColCutLine'
'body': 'MovePointColCutLine(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:Float:cut_size=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MovePointColCutLineEx':
'prefix': 'MovePointColCutLineEx'
'body': 'MovePointColCutLineEx(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:Float:cut_size=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFront3DCol':
'prefix': 'GetPointInFront3DCol'
'body': 'GetPointInFront3DCol(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:Float:radius}, ${7:&Float:tx}, ${8:&Float:ty}, ${9:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfPlayerCol':
'prefix': 'GetPointInFrontOfPlayerCol'
'body': 'GetPointInFrontOfPlayerCol(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera2DCol':
'prefix': 'GetPointInFrontOfCamera2DCol'
'body': 'GetPointInFrontOfCamera2DCol(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera3DCol':
'prefix': 'GetPointInFrontOfCamera3DCol'
'body': 'GetPointInFrontOfCamera3DCol(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle2DCol':
'prefix': 'GetPointInFrontOfVehicle2DCol'
'body': 'GetPointInFrontOfVehicle2DCol(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle3DCol':
'prefix': 'GetPointInFrontOfVehicle3DCol'
'body': 'GetPointInFrontOfVehicle3DCol(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointCollisionFlags':
'prefix': 'GetPointCollisionFlags'
'body': 'GetPointCollisionFlags(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:interiorid=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCollisionFlags':
'prefix': 'GetPlayerCollisionFlags'
'body': 'GetPlayerCollisionFlags(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleCollisionFlags':
'prefix': 'GetVehicleCollisionFlags'
'body': 'GetVehicleCollisionFlags(${1:vehicleid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectCollisionFlags':
'prefix': 'GetObjectCollisionFlags'
'body': 'GetObjectCollisionFlags(${1:objectid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsCollisionFlag':
'prefix': 'IsCollisionFlag'
'body': 'IsCollisionFlag(${1:value}, ${2:flag})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'UndergroundFindZ':
'prefix': 'UndergroundFindZ'
'body': 'UndergroundFindZ(${1:Float:x}, ${2:Float:y}, ${3:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'InteriorFindZ':
'prefix': 'InteriorFindZ'
'body': 'InteriorFindZ(${1:Float:px}, ${2:Float:py}, ${3:Float:pz=1000.0}, ${4:Float:size=2.0}, ${5:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInUnderwater':
'prefix': 'IsPointInUnderwater'
'body': 'IsPointInUnderwater(${1:Float:x}, ${2:Float:y}, ${3:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInUnderground':
'prefix': 'IsPointInUnderground'
'body': 'IsPointInUnderground(${1:Float:x}, ${2:Float:y}, ${3:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInAir':
'prefix': 'IsPointInAir'
'body': 'IsPointInAir(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:bool:interior=false}, ${5:Float:max_distance=2.2})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInGround':
'prefix': 'IsPointInGround'
'body': 'IsPointInGround(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:bool:interior=false}, ${5:Float:max_distance=2.2})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ColAndreasFindZ':
'prefix': 'ColAndreasFindZ'
'body': 'ColAndreasFindZ(${1:Float:x}, ${2:Float:y}, ${3:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerOrientationPosCol':
'prefix': 'GetPlayerOrientationPosCol'
'body': 'GetPlayerOrientationPosCol(${1:playerid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz}, ${7:isactor=false})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleOrientationPosCol':
'prefix': 'GetVehicleOrientationPosCol'
'body': 'GetVehicleOrientationPosCol(${1:vehicleid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectOrientationPosCol':
'prefix': 'GetObjectOrientationPosCol'
'body': 'GetObjectOrientationPosCol(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenPlayersIsWall':
'prefix': 'IsBetweenPlayersIsWall'
'body': 'IsBetweenPlayersIsWall(${1:playerid}, ${2:targetid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenPlayerToPointIsWall':
'prefix': 'IsBetweenPlayerToPointIsWall'
'body': 'IsBetweenPlayerToPointIsWall(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInWallForPoint':
'prefix': 'GetPointInWallForPoint'
'body': 'GetPointInWallForPoint(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz}, ${8:Float:sector=90.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsColAndreasInit':
'prefix': 'IsColAndreasInit'
'body': 'IsColAndreasInit()'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SafeColAndreasInit':
'prefix': 'SafeColAndreasInit'
'body': 'SafeColAndreasInit()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetColAndreasVersion':
'prefix': 'GetColAndreasVersion'
'body': 'GetColAndreasVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetValidColAndreasVersion':
'prefix': 'GetValidColAndreasVersion'
'body': 'GetValidColAndreasVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsValidColAndreas':
'prefix': 'IsValidColAndreas'
'body': 'IsValidColAndreas(${1:version})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetColAndreasVersionName':
'prefix': 'GetColAndreasVersionName'
'body': 'GetColAndreasVersionName(${1:name[]}, ${2:value = GET_COLANDREAS_VERSION}, ${3:maxdest = sizeof(name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CheckColAndreasVersion':
'prefix': 'CheckColAndreasVersion'
'body': 'CheckColAndreasVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'OnColAndreasRemoveBuilding':
'prefix': 'OnColAndreasRemoveBuilding'
'body': 'OnColAndreasRemoveBuilding()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerHydraReactorRX':
'prefix': 'GetPlayerHydraReactorRX'
'body': 'GetPlayerHydraReactorRX(${1:playerid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerHydraReactorBoost':
'prefix': 'IsPlayerHydraReactorBoost'
'body': 'IsPlayerHydraReactorBoost(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerRotation':
'prefix': 'GetPlayerRotation'
'body': 'GetPlayerRotation(${1:playerid}, ${2:&Float:rx}, ${3:&Float:ry}, ${4:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountTextDraw':
'prefix': 'CountTextDraw'
'body': 'CountTextDraw()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountPlayerTextDraw':
'prefix': 'CountPlayerTextDraw'
'body': 'CountPlayerTextDraw(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountVisibleTextDraw':
'prefix': 'CountVisibleTextDraw'
'body': 'CountVisibleTextDraw(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountVisiblePlayerTextDraw':
'prefix': 'CountVisiblePlayerTextDraw'
'body': 'CountVisiblePlayerTextDraw(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'UpdatePlayerTimeline':
'prefix': 'UpdatePlayerTimeline'
'body': 'UpdatePlayerTimeline(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerTimeline':
'prefix': 'GetPlayerTimeline'
'body': 'GetPlayerTimeline(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerTimeline':
'prefix': 'SetPlayerTimeline'
'body': 'SetPlayerTimeline(${1:playerid}, ${2:timeline})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerPos4D':
'prefix': 'GetPlayerPos4D'
'body': 'GetPlayerPos4D(${1:playerid}, ${2:&Float:x}, ${3:&Float:y}, ${4:&Float:z}, ${5:&timeline})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerPos4D':
'prefix': 'SetPlayerPos4D'
'body': 'SetPlayerPos4D(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:timeline=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CreateDynamicExplosion4D':
'prefix': 'CreateDynamicExplosion4D'
'body': 'CreateDynamicExplosion4D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:type}, ${5:Float:radius}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:timeline = -1}, ${9:playerid = -1}, ${10:Float:distance = 200.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCircle':
'prefix': 'IsNPCInCircle'
'body': 'IsNPCInCircle(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCylinder':
'prefix': 'IsNPCInCylinder'
'body': 'IsNPCInCylinder(${1:npcid}, ${2:Float:xA}, ${3:Float:yA}, ${4:Float:zA}, ${5:Float:xB}, ${6:Float:yB}, ${7:Float:zB}, ${8:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCylinderEx':
'prefix': 'IsNPCInCylinderEx'
'body': 'IsNPCInCylinderEx(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:minz}, ${5:Float:maxz}, ${6:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInSphere':
'prefix': 'IsNPCInSphere'
'body': 'IsNPCInSphere(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInRectangle':
'prefix': 'IsNPCInRectangle'
'body': 'IsNPCInRectangle(${1:npcid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:maxx}, ${5:Float:maxy})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCube':
'prefix': 'IsNPCInCube'
'body': 'IsNPCInCube(${1:npcid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:minz}, ${5:Float:maxx}, ${6:Float:maxy}, ${7:Float:maxz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInPolygon':
'prefix': 'IsNPCInPolygon'
'body': 'IsNPCInPolygon(${1:npcid}, ${2:Float:points[]}, ${3:maxpoints = sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCircularSector':
'prefix': 'IsNPCInCircularSector'
'body': 'IsNPCInCircularSector(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:rz}, ${5:Float:radius}, ${6:Float:view_angle})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInSphericalSector':
'prefix': 'IsNPCInSphericalSector'
'body': 'IsNPCInSphericalSector(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:radius}, ${8:Float:vrx}, ${9:Float:vrz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfNPC':
'prefix': 'GetPointInFrontOfNPC'
'body': 'GetPointInFrontOfNPC(${1:npcid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCOrientationPos':
'prefix': 'GetNPCOrientationPos'
'body': 'GetNPCOrientationPos(${1:npcid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCDistanceFromPoint':
'prefix': 'GetNPCDistanceFromPoint'
'body': 'GetNPCDistanceFromPoint(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInRangeOfPoint':
'prefix': 'IsNPCInRangeOfPoint'
'body': 'IsNPCInRangeOfPoint(${1:npcid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenNPCs':
'prefix': 'GetDistanceBetweenNPCs'
'body': 'GetDistanceBetweenNPCs(${1:npcid_a}, ${2:npcid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCSpeed':
'prefix': 'GetNPCSpeed'
'body': 'GetNPCSpeed(${1:npcid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCTargetAngle':
'prefix': 'GetNPCTargetAngle'
'body': 'GetNPCTargetAngle(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetNPCTargetAngle':
'prefix': 'SetNPCTargetAngle'
'body': 'SetNPCTargetAngle(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCTargetNPCAngle':
'prefix': 'GetNPCTargetNPCAngle'
'body': 'GetNPCTargetNPCAngle(${1:npcid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetNPCTargetNPCAngle':
'prefix': 'SetNPCTargetNPCAngle'
'body': 'SetNPCTargetNPCAngle(${1:npcid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCActorDistance':
'prefix': 'GetNPCActorDistance'
'body': 'GetNPCActorDistance(${1:npcid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCVehicleDistance':
'prefix': 'GetNPCVehicleDistance'
'body': 'GetNPCVehicleDistance(${1:npcid}, ${2:vehicleid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCObjectDistance':
'prefix': 'GetNPCObjectDistance'
'body': 'GetNPCObjectDistance(${1:npcid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCToPointVector':
'prefix': 'GetNPCToPointVector'
'body': 'GetNPCToPointVector(${1:npcid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_SetVehicleRotation':
'prefix': 'FCNPC_SetVehicleRotation'
'body': 'FCNPC_SetVehicleRotation(${1:npcid}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_SetVehicleTargetRotation':
'prefix': 'FCNPC_SetVehicleTargetRotation'
'body': 'FCNPC_SetVehicleTargetRotation(${1:npcid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:Float:ry=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCRotatedVector':
'prefix': 'GetNPCRotatedVector'
'body': 'GetNPCRotatedVector(${1:npcid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToAir':
'prefix': 'FCNPC_GoToAir'
'body': 'FCNPC_GoToAir(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:type = MOVE_TYPE_AUTO}, ${6:Float:speed = MOVE_SPEED_AUTO})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfNPCCol':
'prefix': 'GetPointInFrontOfNPCCol'
'body': 'GetPointInFrontOfNPCCol(${1:npcid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCCollisionFlags':
'prefix': 'GetNPCCollisionFlags'
'body': 'GetNPCCollisionFlags(${1:npcid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenNPCsIsWall':
'prefix': 'IsBetweenNPCsIsWall'
'body': 'IsBetweenNPCsIsWall(${1:npcid}, ${2:targetid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenNPCToPointIsWall':
'prefix': 'IsBetweenNPCToPointIsWall'
'body': 'IsBetweenNPCToPointIsWall(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCOrientationPosCol':
'prefix': 'GetNPCOrientationPosCol'
'body': 'GetNPCOrientationPosCol(${1:npcid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToCol':
'prefix': 'FCNPC_GoToCol'
'body': 'FCNPC_GoToCol(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:type = MOVE_TYPE_AUTO}, ${6:Float:speed = MOVE_SPEED_AUTO}, ${7:bool:UseMapAndreas = false}, ${8:Float:cut_size = 0.0}, ${9:bool:setangle = true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToPlayerCol':
'prefix': 'FCNPC_GoToPlayerCol'
'body': 'FCNPC_GoToPlayerCol(${1:npcid}, ${2:playerid}, ${3:type = MOVE_TYPE_AUTO}, ${4:Float:speed = MOVE_SPEED_AUTO}, ${5:bool:UseMapAndreas = false}, ${6:Float:cut_size = 0.0}, ${7:bool:setangle = true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToPlayerOnGroundCol':
'prefix': 'FCNPC_GoToPlayerOnGroundCol'
'body': 'FCNPC_GoToPlayerOnGroundCol(${1:npcid}, ${2:playerid}, ${3:type = MOVE_TYPE_AUTO}, ${4:Float:speed = MOVE_SPEED_AUTO}, ${5:bool:UseMapAndreas = false}, ${6:Float:cut_size = 1.0}, ${7:Float:climbing = 2.0}, ${8:bool:setangle = true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToAirCol':
'prefix': 'FCNPC_GoToAirCol'
'body': 'FCNPC_GoToAirCol(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:type = MOVE_TYPE_AUTO}, ${6:Float:speed = MOVE_SPEED_AUTO}, ${7:Float:cut_size = 0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInWaterFrontOfNPC':
'prefix': 'IsPointInWaterFrontOfNPC'
'body': 'IsPointInWaterFrontOfNPC(${1:npcid}, ${2:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCDynamicObjectDistance':
'prefix': 'GetNPCDynamicObjectDistance'
'body': 'GetNPCDynamicObjectDistance(${1:npcid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCreate':
'prefix': 'StreamCreate'
'body': 'StreamCreate(${1:variable})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetStreamType':
'prefix': 'GetStreamType'
'body': 'GetStreamType(${1:Stream:StreamData[Stream3D]})'
'leftLabel': 'StreamType'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ConvertAreaToStream':
'prefix': 'ConvertAreaToStream'
'body': 'ConvertAreaToStream(${1:areaid})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCircle':
'prefix': 'StreamCircle'
'body': 'StreamCircle(${1:Float:x}, ${2:Float:y}, ${3:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCylinder':
'prefix': 'StreamCylinder'
'body': 'StreamCylinder(${1:Float:xA}, ${2:Float:yA}, ${3:Float:zA}, ${4:Float:xB}, ${5:Float:yB}, ${6:Float:zB}, ${7:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCylinderEx':
'prefix': 'StreamCylinderEx'
'body': 'StreamCylinderEx(${1:Float:x}, ${2:Float:y}, ${3:Float:minz}, ${4:Float:maxz}, ${5:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamSphere':
'prefix': 'StreamSphere'
'body': 'StreamSphere(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamRectangle':
'prefix': 'StreamRectangle'
'body': 'StreamRectangle(${1:Float:minx}, ${2:Float:miny}, ${3:Float:maxx}, ${4:Float:maxy})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCube':
'prefix': 'StreamCube'
'body': 'StreamCube(${1:Float:minx}, ${2:Float:miny}, ${3:Float:minz}, ${4:Float:maxx}, ${5:Float:maxy}, ${6:Float:maxz})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCircularSector':
'prefix': 'StreamCircularSector'
'body': 'StreamCircularSector(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:Float:view_angle})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamSphericalSector':
'prefix': 'StreamSphericalSector'
'body': 'StreamSphericalSector(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:Float:radius}, ${7:Float:vrx}, ${8:Float:vrz})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsValidStream':
'prefix': 'IsValidStream'
'body': 'IsValidStream(${1:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInStream':
'prefix': 'IsPointInStream'
'body': 'IsPointInStream(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInStream':
'prefix': 'IsPlayerInStream'
'body': 'IsPlayerInStream(${1:playerid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectInStream':
'prefix': 'IsObjectInStream'
'body': 'IsObjectInStream(${1:objectid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorInStream':
'prefix': 'IsActorInStream'
'body': 'IsActorInStream(${1:actorid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInStream':
'prefix': 'IsNPCInStream'
'body': 'IsNPCInStream(${1:npcid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectInStream':
'prefix': 'IsDynamicObjectInStream'
'body': 'IsDynamicObjectInStream(${1:objectid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorInStream':
'prefix': 'IsDynamicActorInStream'
'body': 'IsDynamicActorInStream(${1:actorid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Line3DCreate':
'prefix': 'Line3DCreate'
'body': 'Line3DCreate(${1:variable}, ${2:max_points})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLine3DValue':
'prefix': 'GetLine3DValue'
'body': 'GetLine3DValue(${1:variable}, ${2:pointid}, ${3:name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetLine3DValue':
'prefix': 'SetLine3DValue'
'body': 'SetLine3DValue(${1:variable}, ${2:pointid}, ${3:name}, ${4:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLine3DPointPos':
'prefix': 'GetLine3DPointPos'
'body': 'GetLine3DPointPos(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetLine3DPointPos':
'prefix': 'SetLine3DPointPos'
'body': 'SetLine3DPointPos(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLine3DPointRot':
'prefix': 'GetLine3DPointRot'
'body': 'GetLine3DPointRot(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:&Float:rx}, ${4:&Float:ry}, ${5:&Float:rz}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetLine3DPointRot':
'prefix': 'SetLine3DPointRot'
'body': 'SetLine3DPointRot(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:Float:rx}, ${4:Float:ry}, ${5:Float:rz}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountLine3DPoints':
'prefix': 'CountLine3DPoints'
'body': 'CountLine3DPoints(${1:Line3D:LineData[][LinePoint3D]}, ${2:max_points = sizeof(LineData})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'AddPointToLine3D':
'prefix': 'AddPointToLine3D'
'body': 'AddPointToLine3D(${1:Line3D:LineData[][LinePoint3D]}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx=INVALID_ROTATION}, ${6:Float:ry=INVALID_ROTATION}, ${7:Float:rz=INVALID_ROTATION}, ${8:max_points = sizeof(LineData})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetXYZInFrontOfVehicle':
'prefix': 'GetXYZInFrontOfVehicle'
'body': 'GetXYZInFrontOfVehicle(${1:vehicleid}, ${2:Float:distance}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomClockPos':
'prefix': 'GetRandomClockPos'
'body': 'GetRandomClockPos(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz}, ${8:&Float:trz}, ${9:Float:rz = INVALID_ROTATION})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
| 166874 | # Snippets for Atom, automatically generated
# Generator created by <NAME> "<NAME>" <NAME>
'.source.pwn, .source.inc':
'sqrtN':
'prefix': 'sqrtN'
'body': 'sqrtN(${1:Float:value}, ${2:Float:exponent})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'abs':
'prefix': 'abs'
'body': 'abs(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'fabs':
'prefix': 'fabs'
'body': 'fabs(${1:Float:value})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'power':
'prefix': 'power'
'body': 'power(${1:value}, ${2:Float:exponent})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ctg':
'prefix': 'ctg'
'body': 'ctg(${1:Float:value}, ${2:anglemode:mode=radian})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'secans':
'prefix': 'secans'
'body': 'secans(${1:Float:value}, ${2:anglemode:mode=radian})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'cosecans':
'prefix': 'cosecans'
'body': 'cosecans(${1:Float:value}, ${2:anglemode:mode=radian})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsEven':
'prefix': 'IsEven'
'body': 'IsEven(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'RandomFloat':
'prefix': 'RandomFloat'
'body': 'RandomFloat(${1:Float:min}, ${2:Float:max}, ${3:accuracy = 4})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'single_clock':
'prefix': 'single_clock'
'body': 'single_clock(${1:max}, ${2:id})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'even_clock':
'prefix': 'even_clock'
'body': 'even_clock(${1:max}, ${2:id})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'uneven_clock':
'prefix': 'uneven_clock'
'body': 'uneven_clock(${1:max}, ${2:id})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTZ':
'prefix': 'NLTZ'
'body': 'NLTZ(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTZ':
'prefix': 'NMTZ'
'body': 'NMTZ(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTZF':
'prefix': 'NLTZF'
'body': 'NLTZF(${1:Float:value})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTZF':
'prefix': 'NMTZF'
'body': 'NMTZF(${1:Float:value})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTV':
'prefix': 'NLTV'
'body': 'NLTV(${1:value}, ${2:min})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTV':
'prefix': 'NMTV'
'body': 'NMTV(${1:value}, ${2:max})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTVF':
'prefix': 'NLTVF'
'body': 'NLTVF(${1:Float:value}, ${2:Float:min})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTVF':
'prefix': 'NMTVF'
'body': 'NMTVF(${1:Float:value}, ${2:Float:max})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CompRotation':
'prefix': 'CompRotation'
'body': 'CompRotation(${1:rotation}, ${2:&crotation=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'DeCompRotation':
'prefix': 'DeCompRotation'
'body': 'DeCompRotation(${1:rotation}, ${2:&crotation=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CompRotationFloat':
'prefix': 'CompRotationFloat'
'body': 'CompRotationFloat(${1:Float:rotation}, ${2:&Float:crotation=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'DeCompRotationFloat':
'prefix': 'DeCompRotationFloat'
'body': 'DeCompRotationFloat(${1:Float:rotation}, ${2:&Float:crotation=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsRotationTest':
'prefix': 'IsRotationTest'
'body': 'IsRotationTest(${1:Float:rotation}, ${2:Float:r_min}, ${3:Float:r_max})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetRotationMatrixEuler':
'prefix': 'Tryg3D_GetRotationMatrixEuler'
'body': 'Tryg3D_GetRotationMatrixEuler(${1:Float:matrix[][]}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz}, ${5:T3D:eulermode:mode=T3D:euler_default})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_MatrixRotate':
'prefix': 'Tryg3D_MatrixRotate'
'body': 'Tryg3D_MatrixRotate(${1:Float:matrix[][]}, ${2:Float:oX}, ${3:Float:oY}, ${4:Float:oZ}, ${5:&Float:x}, ${6:&Float:y}, ${7:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GivePlayerDamage':
'prefix': 'Tryg3D_GivePlayerDamage'
'body': 'Tryg3D_GivePlayerDamage(${1:targetid}, ${2:Float:damage}, ${3:playerid}, ${4:weaponid}, ${5:bool:force_spawn=true}, ${6:bool:deathmsg=true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetWeaponDamage':
'prefix': 'Tryg3D_GetWeaponDamage'
'body': 'Tryg3D_GetWeaponDamage(${1:weaponid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_SwapInt':
'prefix': 'Tryg3D_SwapInt'
'body': 'Tryg3D_SwapInt(${1:variable1}, ${2:variable2})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountPlayers':
'prefix': 'CountPlayers'
'body': 'CountPlayers(${1:bool:isplayer=true}, ${2:bool:isnpc=true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountActors':
'prefix': 'CountActors'
'body': 'CountActors()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'RecoilFloat':
'prefix': 'RecoilFloat'
'body': 'RecoilFloat(${1:Float:value}, ${2:Float:recoil})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'RecoilVector':
'prefix': 'RecoilVector'
'body': 'RecoilVector(${1:&Float:vx}, ${2:&Float:vy}, ${3:&Float:vz}, ${4:Float:sx}, ${5:Float:sy}, ${6:Float:sz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftDegreeToRadian':
'prefix': 'ShiftDegreeToRadian'
'body': 'ShiftDegreeToRadian(${1:Float:deg})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftDegreeToRadianEx':
'prefix': 'ShiftDegreeToRadianEx'
'body': 'ShiftDegreeToRadianEx(${1:Float:deg})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftDegreeToGrades':
'prefix': 'ShiftDegreeToGrades'
'body': 'ShiftDegreeToGrades(${1:Float:deg})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRadianToDegree':
'prefix': 'ShiftRadianToDegree'
'body': 'ShiftRadianToDegree(${1:Float:rad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRadianToDegreeEx':
'prefix': 'ShiftRadianToDegreeEx'
'body': 'ShiftRadianToDegreeEx(${1:Float:rad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRadianToGrades':
'prefix': 'ShiftRadianToGrades'
'body': 'ShiftRadianToGrades(${1:Float:rad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftGradesToDegree':
'prefix': 'ShiftGradesToDegree'
'body': 'ShiftGradesToDegree(${1:Float:grad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftGradesToRadian':
'prefix': 'ShiftGradesToRadian'
'body': 'ShiftGradesToRadian(${1:Float:grad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomHit':
'prefix': 'GetRandomHit'
'body': 'GetRandomHit(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:range}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPoints1D':
'prefix': 'GetDistanceBetweenPoints1D'
'body': 'GetDistanceBetweenPoints1D(${1:Float:x1}, ${2:Float:x2})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPoints2D':
'prefix': 'GetDistanceBetweenPoints2D'
'body': 'GetDistanceBetweenPoints2D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:x2}, ${4:Float:y2})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPoints3D':
'prefix': 'GetDistanceBetweenPoints3D'
'body': 'GetDistanceBetweenPoints3D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:z1}, ${4:Float:x2}, ${5:Float:y2}, ${6:Float:z2})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFront2D':
'prefix': 'GetPointInFront2D'
'body': 'GetPointInFront2D(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFront3D':
'prefix': 'GetPointInFront3D'
'body': 'GetPointInFront3D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:Float:radius}, ${7:&Float:tx}, ${8:&Float:ty}, ${9:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfPlayer':
'prefix': 'GetPointInFrontOfPlayer'
'body': 'GetPointInFrontOfPlayer(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera2D':
'prefix': 'GetPointInFrontOfCamera2D'
'body': 'GetPointInFrontOfCamera2D(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera3D':
'prefix': 'GetPointInFrontOfCamera3D'
'body': 'GetPointInFrontOfCamera3D(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRotationFor2Point2D':
'prefix': 'GetRotationFor2Point2D'
'body': 'GetRotationFor2Point2D(${1:Float:x}, ${2:Float:y}, ${3:Float:tx}, ${4:Float:ty}, ${5:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRotationFor2Point3D':
'prefix': 'GetRotationFor2Point3D'
'body': 'GetRotationFor2Point3D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:&Float:rx}, ${8:&Float:rz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ConvertMTARaceRotation':
'prefix': 'ConvertMTARaceRotation'
'body': 'ConvertMTARaceRotation(${1:Float:rotation1}, ${2:Float:rotation2}, ${3:Float:rotation3}, ${4:&Float:rx}, ${5:&Float:ry}, ${6:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ConvertToMTARaceRotation':
'prefix': 'ConvertToMTARaceRotation'
'body': 'ConvertToMTARaceRotation(${1:Float:rx}, ${2:Float:ry}, ${3:Float:rz}, ${4:&Float:rotation1}, ${5:&Float:rotation2}, ${6:&Float:rotation3})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetMoveTime':
'prefix': 'GetMoveTime'
'body': 'GetMoveTime(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:Float:speed}, ${8:&rtime=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetSpeedForMoveTime':
'prefix': 'GetSpeedForMoveTime'
'body': 'GetSpeedForMoveTime(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:&Float:speed}, ${8:rtime})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleRotation':
'prefix': 'GetVehicleRotation'
'body': 'GetVehicleRotation(${1:vehicleid}, ${2:&Float:rx}, ${3:&Float:ry}, ${4:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle2D':
'prefix': 'GetPointInFrontOfVehicle2D'
'body': 'GetPointInFrontOfVehicle2D(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle3D':
'prefix': 'GetPointInFrontOfVehicle3D'
'body': 'GetPointInFrontOfVehicle3D(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCameraRotation':
'prefix': 'GetPlayerCameraRotation'
'body': 'GetPlayerCameraRotation(${1:playerid}, ${2:&Float:rx}, ${3:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerCameraRotation':
'prefix': 'SetPlayerCameraRotation'
'body': 'SetPlayerCameraRotation(${1:playerid}, ${2:Float:rx}, ${3:Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCameraZAngle':
'prefix': 'GetPlayerCameraZAngle'
'body': 'GetPlayerCameraZAngle(${1:playerid}, ${2:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerCameraZAngle':
'prefix': 'SetPlayerCameraZAngle'
'body': 'SetPlayerCameraZAngle(${1:playerid}, ${2:Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point2D':
'prefix': 'GetPointFor2Point2D'
'body': 'GetPointFor2Point2D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:x2}, ${4:Float:y2}, ${5:Float:percent_size}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point3D':
'prefix': 'GetPointFor2Point3D'
'body': 'GetPointFor2Point3D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:z1}, ${4:Float:x2}, ${5:Float:y2}, ${6:Float:z2}, ${7:Float:percent_size}, ${8:&Float:tx}, ${9:&Float:ty}, ${10:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point2DEx':
'prefix': 'GetPointFor2Point2DEx'
'body': 'GetPointFor2Point2DEx(${1:Float:x1}, ${2:Float:y1}, ${3:Float:x2}, ${4:Float:y2}, ${5:Float:distance}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point3DEx':
'prefix': 'GetPointFor2Point3DEx'
'body': 'GetPointFor2Point3DEx(${1:Float:x1}, ${2:Float:y1}, ${3:Float:z1}, ${4:Float:x2}, ${5:Float:y2}, ${6:Float:z2}, ${7:Float:distance}, ${8:&Float:tx}, ${9:&Float:ty}, ${10:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftVectorToRotation':
'prefix': 'ShiftVectorToRotation'
'body': 'ShiftVectorToRotation(${1:Float:vx}, ${2:Float:vy}, ${3:Float:vz}, ${4:&Float:rx}, ${5:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRotationToVector':
'prefix': 'ShiftRotationToVector'
'body': 'ShiftRotationToVector(${1:Float:rx}, ${2:Float:rz}, ${3:&Float:vx}, ${4:&Float:vy}, ${5:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnClock':
'prefix': 'GetRandomPointOnClock'
'body': 'GetRandomPointOnClock(${1:Float:x}, ${2:Float:y}, ${3:Float:radius}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:trz}, ${7:Float:rz = INVALID_ROTATION})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCircle':
'prefix': 'GetRandomPointInCircle'
'body': 'GetRandomPointInCircle(${1:Float:x}, ${2:Float:y}, ${3:Float:radius}, ${4:&Float:tx}, ${5:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCylinderEx':
'prefix': 'GetRandomPointInCylinderEx'
'body': 'GetRandomPointInCylinderEx(${1:Float:x}, ${2:Float:y}, ${3:Float:minz}, ${4:Float:maxz}, ${5:Float:radius}, ${6:&Float:tx}, ${7:&Float:ty}, ${8:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInSphere':
'prefix': 'GetRandomPointInSphere'
'body': 'GetRandomPointInSphere(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInRectangle':
'prefix': 'GetRandomPointInRectangle'
'body': 'GetRandomPointInRectangle(${1:Float:minx}, ${2:Float:miny}, ${3:Float:maxx}, ${4:Float:maxy}, ${5:&Float:tx}, ${6:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCube':
'prefix': 'GetRandomPointInCube'
'body': 'GetRandomPointInCube(${1:Float:minx}, ${2:Float:miny}, ${3:Float:minz}, ${4:Float:maxx}, ${5:Float:maxy}, ${6:Float:maxz}, ${7:&Float:tx}, ${8:&Float:ty}, ${9:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCircularSector':
'prefix': 'GetRandomPointInCircularSector'
'body': 'GetRandomPointInCircularSector(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:Float:view_angle}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnCircle':
'prefix': 'GetRandomPointOnCircle'
'body': 'GetRandomPointOnCircle(${1:Float:x}, ${2:Float:y}, ${3:Float:radius}, ${4:&Float:tx}, ${5:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnSphere':
'prefix': 'GetRandomPointOnSphere'
'body': 'GetRandomPointOnSphere(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnCircularSector':
'prefix': 'GetRandomPointOnCircularSector'
'body': 'GetRandomPointOnCircularSector(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:Float:view_angle}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointBetween2Points2D':
'prefix': 'IsPointBetween2Points2D'
'body': 'IsPointBetween2Points2D(${1:Float:px}, ${2:Float:py}, ${3:Float:xA}, ${4:Float:yA}, ${5:Float:xB}, ${6:Float:yB})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointBetween2Points3D':
'prefix': 'IsPointBetween2Points3D'
'body': 'IsPointBetween2Points3D(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:xA}, ${5:Float:yA}, ${6:Float:zA}, ${7:Float:xB}, ${8:Float:yB}, ${9:Float:zB})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointNearly2Points2D':
'prefix': 'IsPointNearly2Points2D'
'body': 'IsPointNearly2Points2D(${1:Float:px}, ${2:Float:py}, ${3:Float:xA}, ${4:Float:yA}, ${5:Float:xB}, ${6:Float:yB}, ${7:Float:maxdist})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointNearly2Points3D':
'prefix': 'IsPointNearly2Points3D'
'body': 'IsPointNearly2Points3D(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:xA}, ${5:Float:yA}, ${6:Float:zA}, ${7:Float:xB}, ${8:Float:yB}, ${9:Float:zB}, ${10:Float:maxdist})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCircle':
'prefix': 'IsPointInCircle'
'body': 'IsPointInCircle(${1:Float:px}, ${2:Float:py}, ${3:Float:x}, ${4:Float:y}, ${5:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCylinder':
'prefix': 'IsPointInCylinder'
'body': 'IsPointInCylinder(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:xA}, ${5:Float:yA}, ${6:Float:zA}, ${7:Float:xB}, ${8:Float:yB}, ${9:Float:zB}, ${10:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCylinderEx':
'prefix': 'IsPointInCylinderEx'
'body': 'IsPointInCylinderEx(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:minz}, ${7:Float:maxz}, ${8:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInSphere':
'prefix': 'IsPointInSphere'
'body': 'IsPointInSphere(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInRectangle':
'prefix': 'IsPointInRectangle'
'body': 'IsPointInRectangle(${1:Float:x}, ${2:Float:y}, ${3:Float:minx}, ${4:Float:miny}, ${5:Float:maxx}, ${6:Float:maxy})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCube':
'prefix': 'IsPointInCube'
'body': 'IsPointInCube(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:minx}, ${5:Float:miny}, ${6:Float:minz}, ${7:Float:maxx}, ${8:Float:maxy}, ${9:Float:maxz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInPolygon':
'prefix': 'IsPointInPolygon'
'body': 'IsPointInPolygon(${1:Float:x}, ${2:Float:y}, ${3:Float:points[]}, ${4:maxpoints = sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCircularSector':
'prefix': 'IsPointInCircularSector'
'body': 'IsPointInCircularSector(${1:Float:px}, ${2:Float:py}, ${3:Float:x}, ${4:Float:y}, ${5:Float:rz}, ${6:Float:radius}, ${7:Float:view_angle})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInSphericalSector':
'prefix': 'IsPointInSphericalSector'
'body': 'IsPointInSphericalSector(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:Float:rx}, ${8:Float:rz}, ${9:Float:radius}, ${10:Float:vrx}, ${11:Float:vrz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCircle':
'prefix': 'IsPlayerInCircle'
'body': 'IsPlayerInCircle(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCylinder':
'prefix': 'IsPlayerInCylinder'
'body': 'IsPlayerInCylinder(${1:playerid}, ${2:Float:xA}, ${3:Float:yA}, ${4:Float:zA}, ${5:Float:xB}, ${6:Float:yB}, ${7:Float:zB}, ${8:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCylinderEx':
'prefix': 'IsPlayerInCylinderEx'
'body': 'IsPlayerInCylinderEx(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:minz}, ${5:Float:maxz}, ${6:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInSphere':
'prefix': 'IsPlayerInSphere'
'body': 'IsPlayerInSphere(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInRectangle':
'prefix': 'IsPlayerInRectangle'
'body': 'IsPlayerInRectangle(${1:playerid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:maxx}, ${5:Float:maxy})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCube':
'prefix': 'IsPlayerInCube'
'body': 'IsPlayerInCube(${1:playerid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:minz}, ${5:Float:maxx}, ${6:Float:maxy}, ${7:Float:maxz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInPolygon':
'prefix': 'IsPlayerInPolygon'
'body': 'IsPlayerInPolygon(${1:playerid}, ${2:Float:points[]}, ${3:maxpoints = sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCircularSector':
'prefix': 'IsPlayerInCircularSector'
'body': 'IsPlayerInCircularSector(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:rz}, ${5:Float:radius}, ${6:Float:view_angle})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInSphericalSector':
'prefix': 'IsPlayerInSphericalSector'
'body': 'IsPlayerInSphericalSector(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:radius}, ${8:Float:vrx}, ${9:Float:vrz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsProbable':
'prefix': 'IsProbable'
'body': 'IsProbable(${1:chance})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CalculatePercent':
'prefix': 'CalculatePercent'
'body': 'CalculatePercent(${1:Float:value}, ${2:Float:maxvalue})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerTargetAngle':
'prefix': 'GetPlayerTargetAngle'
'body': 'GetPlayerTargetAngle(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerTargetAngle':
'prefix': 'SetPlayerTargetAngle'
'body': 'SetPlayerTargetAngle(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerTargetPlayerAngle':
'prefix': 'GetPlayerTargetPlayerAngle'
'body': 'GetPlayerTargetPlayerAngle(${1:playerid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerTargetPlayerAngle':
'prefix': 'SetPlayerTargetPlayerAngle'
'body': 'SetPlayerTargetPlayerAngle(${1:playerid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleSpeed':
'prefix': 'GetVehicleSpeed'
'body': 'GetVehicleSpeed(${1:vehicleid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerSpeed':
'prefix': 'GetPlayerSpeed'
'body': 'GetPlayerSpeed(${1:playerid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CreateDynamicExplosion':
'prefix': 'CreateDynamicExplosion'
'body': 'CreateDynamicExplosion(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:type}, ${5:Float:radius}, ${6:worldid=-1}, ${7:interiorid=-1}, ${8:playerid=-1}, ${9:Float:distance=200.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleFlags':
'prefix': 'GetVehicleFlags'
'body': 'GetVehicleFlags(${1:vehicleid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleFlagsByModel':
'prefix': 'GetVehicleFlagsByModel'
'body': 'GetVehicleFlagsByModel(${1:modelid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleFlag':
'prefix': 'IsVehicleFlag'
'body': 'IsVehicleFlag(${1:value}, ${2:flag})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerOrientationPos':
'prefix': 'GetPlayerOrientationPos'
'body': 'GetPlayerOrientationPos(${1:playerid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz}, ${7:isactor=false})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleOrientationPos':
'prefix': 'GetVehicleOrientationPos'
'body': 'GetVehicleOrientationPos(${1:vehicleid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectOrientationPos':
'prefix': 'GetObjectOrientationPos'
'body': 'GetObjectOrientationPos(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetWeaponShotPos':
'prefix': 'GetWeaponShotPos'
'body': 'GetWeaponShotPos(${1:playerid}, ${2:hittype}, ${3:&Float:fx}, ${4:&Float:fy}, ${5:&Float:fz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetActorDistanceFromPoint':
'prefix': 'GetActorDistanceFromPoint'
'body': 'GetActorDistanceFromPoint(${1:actorid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectDistanceFromPoint':
'prefix': 'GetObjectDistanceFromPoint'
'body': 'GetObjectDistanceFromPoint(${1:objectid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPlayers':
'prefix': 'GetDistanceBetweenPlayers'
'body': 'GetDistanceBetweenPlayers(${1:playerid_a}, ${2:playerid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenVehicles':
'prefix': 'GetDistanceBetweenVehicles'
'body': 'GetDistanceBetweenVehicles(${1:vehicleid_a}, ${2:vehicleid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenObjects':
'prefix': 'GetDistanceBetweenObjects'
'body': 'GetDistanceBetweenObjects(${1:objectid_a}, ${2:objectid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerActorDistance':
'prefix': 'GetPlayerActorDistance'
'body': 'GetPlayerActorDistance(${1:playerid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerVehicleDistance':
'prefix': 'GetPlayerVehicleDistance'
'body': 'GetPlayerVehicleDistance(${1:playerid}, ${2:vehicleid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerObjectDistance':
'prefix': 'GetPlayerObjectDistance'
'body': 'GetPlayerObjectDistance(${1:playerid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerLookAtPlayer':
'prefix': 'SetPlayerLookAtPlayer'
'body': 'SetPlayerLookAtPlayer(${1:playerid}, ${2:targetid}, ${3:cut = CAMERA_CUT})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCameraLookAt':
'prefix': 'GetPlayerCameraLookAt'
'body': 'GetPlayerCameraLookAt(${1:playerid}, ${2:&Float:x}, ${3:&Float:y}, ${4:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerLookAtSky':
'prefix': 'IsPlayerLookAtSky'
'body': 'IsPlayerLookAtSky(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleUpVector':
'prefix': 'GetVehicleUpVector'
'body': 'GetVehicleUpVector(${1:vehicleid}, ${2:&Float:vx}, ${3:&Float:vy}, ${4:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleUpPos':
'prefix': 'GetVehicleUpPos'
'body': 'GetVehicleUpPos(${1:vehicleid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleDownPos':
'prefix': 'GetVehicleDownPos'
'body': 'GetVehicleDownPos(${1:vehicleid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectRotationQuat':
'prefix': 'GetObjectRotationQuat'
'body': 'GetObjectRotationQuat(${1:objectid}, ${2:&Float:qw}, ${3:&Float:qx}, ${4:&Float:qy}, ${5:&Float:qz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectUpVector':
'prefix': 'GetObjectUpVector'
'body': 'GetObjectUpVector(${1:objectid}, ${2:&Float:vx}, ${3:&Float:vy}, ${4:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectUpPos':
'prefix': 'GetObjectUpPos'
'body': 'GetObjectUpPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectDownPos':
'prefix': 'GetObjectDownPos'
'body': 'GetObjectDownPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetQuatUpVector':
'prefix': 'GetQuatUpVector'
'body': 'GetQuatUpVector(${1:Float:qw}, ${2:Float:qx}, ${3:Float:qy}, ${4:Float:qz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetQuatFromRot':
'prefix': 'GetQuatFromRot'
'body': 'GetQuatFromRot(${1:Float:rx}, ${2:Float:ry}, ${3:Float:rz}, ${4:&Float:qw}, ${5:&Float:qx}, ${6:&Float:qy}, ${7:&Float:qz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLineSize2D':
'prefix': 'GetLineSize2D'
'body': 'GetLineSize2D(${1:Float:points[][]}, ${2:maxpoints=sizeof(points})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLineSize3D':
'prefix': 'GetLineSize3D'
'body': 'GetLineSize3D(${1:Float:points[][]}, ${2:maxpoints=sizeof(points})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointToPointVector':
'prefix': 'GetPointToPointVector'
'body': 'GetPointToPointVector(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:&Float:vx}, ${8:&Float:vy}, ${9:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerToPointVector':
'prefix': 'GetPlayerToPointVector'
'body': 'GetPlayerToPointVector(${1:playerid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectToPointVector':
'prefix': 'GetObjectToPointVector'
'body': 'GetObjectToPointVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleToPointVector':
'prefix': 'GetVehicleToPointVector'
'body': 'GetVehicleToPointVector(${1:vehicleid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleInRangeOfPoint':
'prefix': 'IsVehicleInRangeOfPoint'
'body': 'IsVehicleInRangeOfPoint(${1:vehicleid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorInRangeOfPoint':
'prefix': 'IsActorInRangeOfPoint'
'body': 'IsActorInRangeOfPoint(${1:actorid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectInRangeOfPoint':
'prefix': 'IsObjectInRangeOfPoint'
'body': 'IsObjectInRangeOfPoint(${1:objectid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftLineRotation':
'prefix': 'ShiftLineRotation'
'body': 'ShiftLineRotation(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:Float:rx}, ${8:Float:ry}, ${9:Float:rz}, ${10:&Float:nX}, ${11:&Float:nY}, ${12:&Float:nZ})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftLineRotationVector':
'prefix': 'ShiftLineRotationVector'
'body': 'ShiftLineRotationVector(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:Float:rx}, ${8:Float:ry}, ${9:Float:rz}, ${10:&Float:nX}, ${11:&Float:nY}, ${12:&Float:nZ})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerRotatedVector':
'prefix': 'GetPlayerRotatedVector'
'body': 'GetPlayerRotatedVector(${1:playerid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectRotatedVector':
'prefix': 'GetObjectRotatedVector'
'body': 'GetObjectRotatedVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleRotatedVector':
'prefix': 'GetVehicleRotatedVector'
'body': 'GetVehicleRotatedVector(${1:vehicleid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsFloor2D':
'prefix': 'GetArcPointsFloor2D'
'body': 'GetArcPointsFloor2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsCellar2D':
'prefix': 'GetArcPointsCellar2D'
'body': 'GetArcPointsCellar2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsStarboard2D':
'prefix': 'GetArcPointsStarboard2D'
'body': 'GetArcPointsStarboard2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsLarboard2D':
'prefix': 'GetArcPointsLarboard2D'
'body': 'GetArcPointsLarboard2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInSphericalSectorEx':
'prefix': 'IsPointInSphericalSectorEx'
'body': 'IsPointInSphericalSectorEx(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:Float:rx}, ${8:Float:rz}, ${9:Float:radius}, ${10:Float:vrx}, ${11:Float:vrz}, ${12:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerOnPlayerScreen':
'prefix': 'IsPlayerOnPlayerScreen'
'body': 'IsPlayerOnPlayerScreen(${1:playerid}, ${2:targetid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleOnPlayerScreen':
'prefix': 'IsVehicleOnPlayerScreen'
'body': 'IsVehicleOnPlayerScreen(${1:playerid}, ${2:vehicleid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectOnPlayerScreen':
'prefix': 'IsObjectOnPlayerScreen'
'body': 'IsObjectOnPlayerScreen(${1:playerid}, ${2:objectid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorOnPlayerScreen':
'prefix': 'IsActorOnPlayerScreen'
'body': 'IsActorOnPlayerScreen(${1:playerid}, ${2:actorid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerOnFakeScreen':
'prefix': 'IsPlayerOnFakeScreen'
'body': 'IsPlayerOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:targetid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleOnFakeScreen':
'prefix': 'IsVehicleOnFakeScreen'
'body': 'IsVehicleOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:vehicleid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectOnFakeScreen':
'prefix': 'IsObjectOnFakeScreen'
'body': 'IsObjectOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:objectid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorOnFakeScreen':
'prefix': 'IsActorOnFakeScreen'
'body': 'IsActorOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:actorid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerSkydiving':
'prefix': 'IsPlayerSkydiving'
'body': 'IsPlayerSkydiving(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerUsingParachute':
'prefix': 'IsPlayerUsingParachute'
'body': 'IsPlayerUsingParachute(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerAiming':
'prefix': 'IsPlayerAiming'
'body': 'IsPlayerAiming(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerStay':
'prefix': 'IsPlayerStay'
'body': 'IsPlayerStay(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerRunning':
'prefix': 'IsPlayerRunning'
'body': 'IsPlayerRunning(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerSwim':
'prefix': 'IsPlayerSwim'
'body': 'IsPlayerSwim(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerJump':
'prefix': 'IsPlayerJump'
'body': 'IsPlayerJump(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerParaFall':
'prefix': 'IsPlayerParaFall'
'body': 'IsPlayerParaFall(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerParaGlide':
'prefix': 'IsPlayerParaGlide'
'body': 'IsPlayerParaGlide(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerFall':
'prefix': 'IsPlayerFall'
'body': 'IsPlayerFall(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Get3DTrygModules':
'prefix': 'Get3DTrygModules'
'body': 'Get3DTrygModules(${1:&modules_count=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsTryg3DModuleLoaded':
'prefix': 'IsTryg3DModuleLoaded'
'body': 'IsTryg3DModuleLoaded(${1:Tryg3DModule:moduleid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Get3DTrygEfficiency':
'prefix': 'Get3DTrygEfficiency'
'body': 'Get3DTrygEfficiency(${1:bool:use_colandreas=false})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Get3DTrygErrorCount':
'prefix': 'Get3DTrygErrorCount'
'body': 'Get3DTrygErrorCount()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Reset3DTrygErrorCount':
'prefix': 'Reset3DTrygErrorCount'
'body': 'Reset3DTrygErrorCount()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_SetStreamDistance':
'prefix': 'Tryg3D_SetStreamDistance'
'body': 'Tryg3D_SetStreamDistance(${1:Float:streamdistance})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetStreamDistance':
'prefix': 'Tryg3D_GetStreamDistance'
'body': 'Tryg3D_GetStreamDistance()'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetTryg3DActiveCount':
'prefix': 'GetTryg3DActiveCount'
'body': 'GetTryg3DActiveCount()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftPositionToOrion':
'prefix': 'ShiftPositionToOrion'
'body': 'ShiftPositionToOrion(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:&Float:orion}, ${5:&Float:lon}, ${6:&Float:lat})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftOrionToPosition':
'prefix': 'ShiftOrionToPosition'
'body': 'ShiftOrionToPosition(${1:Float:orion}, ${2:Float:lon}, ${3:Float:lat}, ${4:&Float:x}, ${5:&Float:y}, ${6:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'randomex':
'prefix': 'randomex'
'body': 'randomex(${1:min}, ${2:max})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_KeyPressed':
'prefix': 'Tryg3D_KeyPressed'
'body': 'Tryg3D_KeyPressed(${1:key})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_KeyReleased':
'prefix': 'Tryg3D_KeyReleased'
'body': 'Tryg3D_KeyReleased(${1:key})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_KeyHolding':
'prefix': 'Tryg3D_KeyHolding'
'body': 'Tryg3D_KeyHolding(${1:key})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetSAMIncludeVersion':
'prefix': 'GetSAMIncludeVersion'
'body': 'GetSAMIncludeVersion(${1:value}, ${2:name[]}, ${3:maxdest = sizeof(name})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'DisableADMLogging':
'prefix': 'DisableADMLogging'
'body': 'DisableADMLogging(${1:bool:disable})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SecToTimeDay':
'prefix': 'SecToTimeDay'
'body': 'SecToTimeDay(${1:second})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MSToTimeDay':
'prefix': 'MSToTimeDay'
'body': 'MSToTimeDay(${1:millisecond})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SecToTime':
'prefix': 'SecToTime'
'body': 'SecToTime(${1:second})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MSToTime':
'prefix': 'MSToTime'
'body': 'MSToTime(${1:millisecond})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SecToTimeMini':
'prefix': 'SecToTimeMini'
'body': 'SecToTimeMini(${1:second})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MSToTimeMini':
'prefix': 'MSToTimeMini'
'body': 'MSToTimeMini(${1:millisecond})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectOrientationPos':
'prefix': 'GetDynamicObjectOrientationPos'
'body': 'GetDynamicObjectOrientationPos(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenDynamicObject':
'prefix': 'GetDistanceBetweenDynamicObject'
'body': 'GetDistanceBetweenDynamicObject(${1:objectid_a}, ${2:objectid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerDynamicObjectDistance':
'prefix': 'GetPlayerDynamicObjectDistance'
'body': 'GetPlayerDynamicObjectDistance(${1:playerid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectRotationQuat':
'prefix': 'GetDynamicObjectRotationQuat'
'body': 'GetDynamicObjectRotationQuat(${1:objectid}, ${2:&Float:qw}, ${3:&Float:qx}, ${4:&Float:qy}, ${5:&Float:qz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectUpVector':
'prefix': 'GetDynamicObjectUpVector'
'body': 'GetDynamicObjectUpVector(${1:objectid}, ${2:&Float:vx}, ${3:&Float:vy}, ${4:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectUpPos':
'prefix': 'GetDynamicObjectUpPos'
'body': 'GetDynamicObjectUpPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectDownPos':
'prefix': 'GetDynamicObjectDownPos'
'body': 'GetDynamicObjectDownPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectToPointVector':
'prefix': 'GetDynamicObjectToPointVector'
'body': 'GetDynamicObjectToPointVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectDistFromPoint':
'prefix': 'GetDynamicObjectDistFromPoint'
'body': 'GetDynamicObjectDistFromPoint(${1:objectid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectInRangeOfPoint':
'prefix': 'IsDynamicObjectInRangeOfPoint'
'body': 'IsDynamicObjectInRangeOfPoint(${1:objectid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerAbsolutePosition':
'prefix': 'SetPlayerAbsolutePosition'
'body': 'SetPlayerAbsolutePosition(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:angle}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:compensatedtime = -1})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerAbsolutePositionVeh':
'prefix': 'SetPlayerAbsolutePositionVeh'
'body': 'SetPlayerAbsolutePositionVeh(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:angle}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:compensatedtime = -1})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectRotatedVector':
'prefix': 'GetDynamicObjectRotatedVector'
'body': 'GetDynamicObjectRotatedVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectOnPlayerScreen':
'prefix': 'IsDynamicObjectOnPlayerScreen'
'body': 'IsDynamicObjectOnPlayerScreen(${1:playerid}, ${2:objectid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectOnFakeScreen':
'prefix': 'IsDynamicObjectOnFakeScreen'
'body': 'IsDynamicObjectOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:objectid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicActorDistFromPoint':
'prefix': 'GetDynamicActorDistFromPoint'
'body': 'GetDynamicActorDistFromPoint(${1:actorid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerDynamicActorDistance':
'prefix': 'GetPlayerDynamicActorDistance'
'body': 'GetPlayerDynamicActorDistance(${1:playerid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorInRangeOfPoint':
'prefix': 'IsDynamicActorInRangeOfPoint'
'body': 'IsDynamicActorInRangeOfPoint(${1:actorid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicActorOrientationPos':
'prefix': 'GetDynamicActorOrientationPos'
'body': 'GetDynamicActorOrientationPos(${1:actorid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorOnPlayerScreen':
'prefix': 'IsDynamicActorOnPlayerScreen'
'body': 'IsDynamicActorOnPlayerScreen(${1:playerid}, ${2:actorid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorOnFakeScreen':
'prefix': 'IsDynamicActorOnFakeScreen'
'body': 'IsDynamicActorOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:actorid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_IsValidStreamer':
'prefix': 'Tryg3D_IsValidStreamer'
'body': 'Tryg3D_IsValidStreamer(${1:version})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetStreamerVersionName':
'prefix': 'Tryg3D_GetStreamerVersionName'
'body': 'Tryg3D_GetStreamerVersionName(${1:name[]}, ${2:value = TRYG3D_GET_STREAMER_VERSION}, ${3:maxdest = sizeof(name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_CheckStreamerVersion':
'prefix': 'Tryg3D_CheckStreamerVersion'
'body': 'Tryg3D_CheckStreamerVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectOrientPosCol':
'prefix': 'GetDynamicObjectOrientPosCol'
'body': 'GetDynamicObjectOrientPosCol(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectCollisionFlags':
'prefix': 'GetDynamicObjectCollisionFlags'
'body': 'GetDynamicObjectCollisionFlags(${1:objectid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicActorOrientPosCol':
'prefix': 'GetDynamicActorOrientPosCol'
'body': 'GetDynamicActorOrientPosCol(${1:actorid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetNPCAbsolutePosition':
'prefix': 'SetNPCAbsolutePosition'
'body': 'SetNPCAbsolutePosition(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:angle}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:compensatedtime = -1})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCDynamicActorDistance':
'prefix': 'GetNPCDynamicActorDistance'
'body': 'GetNPCDynamicActorDistance(${1:npcid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MapAndreasFindZ':
'prefix': 'MapAndreasFindZ'
'body': 'MapAndreasFindZ(${1:Float:x}, ${2:Float:y}, ${3:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetGroundRotation':
'prefix': 'GetGroundRotation'
'body': 'GetGroundRotation(${1:Float:x}, ${2:Float:y}, ${3:Float:size}, ${4:&Float:rx}, ${5:&Float:ry})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOnGround':
'prefix': 'GetPointInFrontOnGround'
'body': 'GetPointInFrontOnGround(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:&Float:tx}, ${7:&Float:ty}, ${8:&Float:tz}, ${9:Float:max_distance})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInWaterFrontOfPlayer':
'prefix': 'IsPointInWaterFrontOfPlayer'
'body': 'IsPointInWaterFrontOfPlayer(${1:playerid}, ${2:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInWater':
'prefix': 'IsPointInWater'
'body': 'IsPointInWater(${1:Float:x}, ${2:Float:y}, ${3:Float:z=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsMapAndreasInit':
'prefix': 'IsMapAndreasInit'
'body': 'IsMapAndreasInit()'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SafeMapAndreasInit':
'prefix': 'SafeMapAndreasInit'
'body': 'SafeMapAndreasInit(${1:mode = MAP_ANDREAS_MODE_FULL}, ${2:name[]=\"\"}, ${3:len=sizeof(name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MovePointCol':
'prefix': 'MovePointCol'
'body': 'MovePointCol(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MovePointColCutLine':
'prefix': 'MovePointColCutLine'
'body': 'MovePointColCutLine(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:Float:cut_size=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MovePointColCutLineEx':
'prefix': 'MovePointColCutLineEx'
'body': 'MovePointColCutLineEx(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:Float:cut_size=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFront3DCol':
'prefix': 'GetPointInFront3DCol'
'body': 'GetPointInFront3DCol(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:Float:radius}, ${7:&Float:tx}, ${8:&Float:ty}, ${9:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfPlayerCol':
'prefix': 'GetPointInFrontOfPlayerCol'
'body': 'GetPointInFrontOfPlayerCol(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera2DCol':
'prefix': 'GetPointInFrontOfCamera2DCol'
'body': 'GetPointInFrontOfCamera2DCol(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera3DCol':
'prefix': 'GetPointInFrontOfCamera3DCol'
'body': 'GetPointInFrontOfCamera3DCol(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle2DCol':
'prefix': 'GetPointInFrontOfVehicle2DCol'
'body': 'GetPointInFrontOfVehicle2DCol(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle3DCol':
'prefix': 'GetPointInFrontOfVehicle3DCol'
'body': 'GetPointInFrontOfVehicle3DCol(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointCollisionFlags':
'prefix': 'GetPointCollisionFlags'
'body': 'GetPointCollisionFlags(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:interiorid=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCollisionFlags':
'prefix': 'GetPlayerCollisionFlags'
'body': 'GetPlayerCollisionFlags(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleCollisionFlags':
'prefix': 'GetVehicleCollisionFlags'
'body': 'GetVehicleCollisionFlags(${1:vehicleid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectCollisionFlags':
'prefix': 'GetObjectCollisionFlags'
'body': 'GetObjectCollisionFlags(${1:objectid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsCollisionFlag':
'prefix': 'IsCollisionFlag'
'body': 'IsCollisionFlag(${1:value}, ${2:flag})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'UndergroundFindZ':
'prefix': 'UndergroundFindZ'
'body': 'UndergroundFindZ(${1:Float:x}, ${2:Float:y}, ${3:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'InteriorFindZ':
'prefix': 'InteriorFindZ'
'body': 'InteriorFindZ(${1:Float:px}, ${2:Float:py}, ${3:Float:pz=1000.0}, ${4:Float:size=2.0}, ${5:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInUnderwater':
'prefix': 'IsPointInUnderwater'
'body': 'IsPointInUnderwater(${1:Float:x}, ${2:Float:y}, ${3:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInUnderground':
'prefix': 'IsPointInUnderground'
'body': 'IsPointInUnderground(${1:Float:x}, ${2:Float:y}, ${3:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInAir':
'prefix': 'IsPointInAir'
'body': 'IsPointInAir(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:bool:interior=false}, ${5:Float:max_distance=2.2})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInGround':
'prefix': 'IsPointInGround'
'body': 'IsPointInGround(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:bool:interior=false}, ${5:Float:max_distance=2.2})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ColAndreasFindZ':
'prefix': 'ColAndreasFindZ'
'body': 'ColAndreasFindZ(${1:Float:x}, ${2:Float:y}, ${3:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerOrientationPosCol':
'prefix': 'GetPlayerOrientationPosCol'
'body': 'GetPlayerOrientationPosCol(${1:playerid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz}, ${7:isactor=false})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleOrientationPosCol':
'prefix': 'GetVehicleOrientationPosCol'
'body': 'GetVehicleOrientationPosCol(${1:vehicleid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectOrientationPosCol':
'prefix': 'GetObjectOrientationPosCol'
'body': 'GetObjectOrientationPosCol(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenPlayersIsWall':
'prefix': 'IsBetweenPlayersIsWall'
'body': 'IsBetweenPlayersIsWall(${1:playerid}, ${2:targetid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenPlayerToPointIsWall':
'prefix': 'IsBetweenPlayerToPointIsWall'
'body': 'IsBetweenPlayerToPointIsWall(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInWallForPoint':
'prefix': 'GetPointInWallForPoint'
'body': 'GetPointInWallForPoint(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz}, ${8:Float:sector=90.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsColAndreasInit':
'prefix': 'IsColAndreasInit'
'body': 'IsColAndreasInit()'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SafeColAndreasInit':
'prefix': 'SafeColAndreasInit'
'body': 'SafeColAndreasInit()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetColAndreasVersion':
'prefix': 'GetColAndreasVersion'
'body': 'GetColAndreasVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetValidColAndreasVersion':
'prefix': 'GetValidColAndreasVersion'
'body': 'GetValidColAndreasVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsValidColAndreas':
'prefix': 'IsValidColAndreas'
'body': 'IsValidColAndreas(${1:version})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetColAndreasVersionName':
'prefix': 'GetColAndreasVersionName'
'body': 'GetColAndreasVersionName(${1:name[]}, ${2:value = GET_COLANDREAS_VERSION}, ${3:maxdest = sizeof(name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CheckColAndreasVersion':
'prefix': 'CheckColAndreasVersion'
'body': 'CheckColAndreasVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'OnColAndreasRemoveBuilding':
'prefix': 'OnColAndreasRemoveBuilding'
'body': 'OnColAndreasRemoveBuilding()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerHydraReactorRX':
'prefix': 'GetPlayerHydraReactorRX'
'body': 'GetPlayerHydraReactorRX(${1:playerid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerHydraReactorBoost':
'prefix': 'IsPlayerHydraReactorBoost'
'body': 'IsPlayerHydraReactorBoost(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerRotation':
'prefix': 'GetPlayerRotation'
'body': 'GetPlayerRotation(${1:playerid}, ${2:&Float:rx}, ${3:&Float:ry}, ${4:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountTextDraw':
'prefix': 'CountTextDraw'
'body': 'CountTextDraw()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountPlayerTextDraw':
'prefix': 'CountPlayerTextDraw'
'body': 'CountPlayerTextDraw(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountVisibleTextDraw':
'prefix': 'CountVisibleTextDraw'
'body': 'CountVisibleTextDraw(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountVisiblePlayerTextDraw':
'prefix': 'CountVisiblePlayerTextDraw'
'body': 'CountVisiblePlayerTextDraw(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'UpdatePlayerTimeline':
'prefix': 'UpdatePlayerTimeline'
'body': 'UpdatePlayerTimeline(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerTimeline':
'prefix': 'GetPlayerTimeline'
'body': 'GetPlayerTimeline(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerTimeline':
'prefix': 'SetPlayerTimeline'
'body': 'SetPlayerTimeline(${1:playerid}, ${2:timeline})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerPos4D':
'prefix': 'GetPlayerPos4D'
'body': 'GetPlayerPos4D(${1:playerid}, ${2:&Float:x}, ${3:&Float:y}, ${4:&Float:z}, ${5:&timeline})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerPos4D':
'prefix': 'SetPlayerPos4D'
'body': 'SetPlayerPos4D(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:timeline=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CreateDynamicExplosion4D':
'prefix': 'CreateDynamicExplosion4D'
'body': 'CreateDynamicExplosion4D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:type}, ${5:Float:radius}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:timeline = -1}, ${9:playerid = -1}, ${10:Float:distance = 200.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCircle':
'prefix': 'IsNPCInCircle'
'body': 'IsNPCInCircle(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCylinder':
'prefix': 'IsNPCInCylinder'
'body': 'IsNPCInCylinder(${1:npcid}, ${2:Float:xA}, ${3:Float:yA}, ${4:Float:zA}, ${5:Float:xB}, ${6:Float:yB}, ${7:Float:zB}, ${8:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCylinderEx':
'prefix': 'IsNPCInCylinderEx'
'body': 'IsNPCInCylinderEx(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:minz}, ${5:Float:maxz}, ${6:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInSphere':
'prefix': 'IsNPCInSphere'
'body': 'IsNPCInSphere(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInRectangle':
'prefix': 'IsNPCInRectangle'
'body': 'IsNPCInRectangle(${1:npcid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:maxx}, ${5:Float:maxy})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCube':
'prefix': 'IsNPCInCube'
'body': 'IsNPCInCube(${1:npcid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:minz}, ${5:Float:maxx}, ${6:Float:maxy}, ${7:Float:maxz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInPolygon':
'prefix': 'IsNPCInPolygon'
'body': 'IsNPCInPolygon(${1:npcid}, ${2:Float:points[]}, ${3:maxpoints = sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCircularSector':
'prefix': 'IsNPCInCircularSector'
'body': 'IsNPCInCircularSector(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:rz}, ${5:Float:radius}, ${6:Float:view_angle})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInSphericalSector':
'prefix': 'IsNPCInSphericalSector'
'body': 'IsNPCInSphericalSector(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:radius}, ${8:Float:vrx}, ${9:Float:vrz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfNPC':
'prefix': 'GetPointInFrontOfNPC'
'body': 'GetPointInFrontOfNPC(${1:npcid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCOrientationPos':
'prefix': 'GetNPCOrientationPos'
'body': 'GetNPCOrientationPos(${1:npcid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCDistanceFromPoint':
'prefix': 'GetNPCDistanceFromPoint'
'body': 'GetNPCDistanceFromPoint(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInRangeOfPoint':
'prefix': 'IsNPCInRangeOfPoint'
'body': 'IsNPCInRangeOfPoint(${1:npcid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenNPCs':
'prefix': 'GetDistanceBetweenNPCs'
'body': 'GetDistanceBetweenNPCs(${1:npcid_a}, ${2:npcid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCSpeed':
'prefix': 'GetNPCSpeed'
'body': 'GetNPCSpeed(${1:npcid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCTargetAngle':
'prefix': 'GetNPCTargetAngle'
'body': 'GetNPCTargetAngle(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetNPCTargetAngle':
'prefix': 'SetNPCTargetAngle'
'body': 'SetNPCTargetAngle(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCTargetNPCAngle':
'prefix': 'GetNPCTargetNPCAngle'
'body': 'GetNPCTargetNPCAngle(${1:npcid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetNPCTargetNPCAngle':
'prefix': 'SetNPCTargetNPCAngle'
'body': 'SetNPCTargetNPCAngle(${1:npcid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCActorDistance':
'prefix': 'GetNPCActorDistance'
'body': 'GetNPCActorDistance(${1:npcid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCVehicleDistance':
'prefix': 'GetNPCVehicleDistance'
'body': 'GetNPCVehicleDistance(${1:npcid}, ${2:vehicleid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCObjectDistance':
'prefix': 'GetNPCObjectDistance'
'body': 'GetNPCObjectDistance(${1:npcid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCToPointVector':
'prefix': 'GetNPCToPointVector'
'body': 'GetNPCToPointVector(${1:npcid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_SetVehicleRotation':
'prefix': 'FCNPC_SetVehicleRotation'
'body': 'FCNPC_SetVehicleRotation(${1:npcid}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_SetVehicleTargetRotation':
'prefix': 'FCNPC_SetVehicleTargetRotation'
'body': 'FCNPC_SetVehicleTargetRotation(${1:npcid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:Float:ry=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCRotatedVector':
'prefix': 'GetNPCRotatedVector'
'body': 'GetNPCRotatedVector(${1:npcid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToAir':
'prefix': 'FCNPC_GoToAir'
'body': 'FCNPC_GoToAir(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:type = MOVE_TYPE_AUTO}, ${6:Float:speed = MOVE_SPEED_AUTO})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfNPCCol':
'prefix': 'GetPointInFrontOfNPCCol'
'body': 'GetPointInFrontOfNPCCol(${1:npcid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCCollisionFlags':
'prefix': 'GetNPCCollisionFlags'
'body': 'GetNPCCollisionFlags(${1:npcid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenNPCsIsWall':
'prefix': 'IsBetweenNPCsIsWall'
'body': 'IsBetweenNPCsIsWall(${1:npcid}, ${2:targetid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenNPCToPointIsWall':
'prefix': 'IsBetweenNPCToPointIsWall'
'body': 'IsBetweenNPCToPointIsWall(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCOrientationPosCol':
'prefix': 'GetNPCOrientationPosCol'
'body': 'GetNPCOrientationPosCol(${1:npcid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToCol':
'prefix': 'FCNPC_GoToCol'
'body': 'FCNPC_GoToCol(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:type = MOVE_TYPE_AUTO}, ${6:Float:speed = MOVE_SPEED_AUTO}, ${7:bool:UseMapAndreas = false}, ${8:Float:cut_size = 0.0}, ${9:bool:setangle = true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToPlayerCol':
'prefix': 'FCNPC_GoToPlayerCol'
'body': 'FCNPC_GoToPlayerCol(${1:npcid}, ${2:playerid}, ${3:type = MOVE_TYPE_AUTO}, ${4:Float:speed = MOVE_SPEED_AUTO}, ${5:bool:UseMapAndreas = false}, ${6:Float:cut_size = 0.0}, ${7:bool:setangle = true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToPlayerOnGroundCol':
'prefix': 'FCNPC_GoToPlayerOnGroundCol'
'body': 'FCNPC_GoToPlayerOnGroundCol(${1:npcid}, ${2:playerid}, ${3:type = MOVE_TYPE_AUTO}, ${4:Float:speed = MOVE_SPEED_AUTO}, ${5:bool:UseMapAndreas = false}, ${6:Float:cut_size = 1.0}, ${7:Float:climbing = 2.0}, ${8:bool:setangle = true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToAirCol':
'prefix': 'FCNPC_GoToAirCol'
'body': 'FCNPC_GoToAirCol(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:type = MOVE_TYPE_AUTO}, ${6:Float:speed = MOVE_SPEED_AUTO}, ${7:Float:cut_size = 0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInWaterFrontOfNPC':
'prefix': 'IsPointInWaterFrontOfNPC'
'body': 'IsPointInWaterFrontOfNPC(${1:npcid}, ${2:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCDynamicObjectDistance':
'prefix': 'GetNPCDynamicObjectDistance'
'body': 'GetNPCDynamicObjectDistance(${1:npcid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCreate':
'prefix': 'StreamCreate'
'body': 'StreamCreate(${1:variable})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetStreamType':
'prefix': 'GetStreamType'
'body': 'GetStreamType(${1:Stream:StreamData[Stream3D]})'
'leftLabel': 'StreamType'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ConvertAreaToStream':
'prefix': 'ConvertAreaToStream'
'body': 'ConvertAreaToStream(${1:areaid})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCircle':
'prefix': 'StreamCircle'
'body': 'StreamCircle(${1:Float:x}, ${2:Float:y}, ${3:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCylinder':
'prefix': 'StreamCylinder'
'body': 'StreamCylinder(${1:Float:xA}, ${2:Float:yA}, ${3:Float:zA}, ${4:Float:xB}, ${5:Float:yB}, ${6:Float:zB}, ${7:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCylinderEx':
'prefix': 'StreamCylinderEx'
'body': 'StreamCylinderEx(${1:Float:x}, ${2:Float:y}, ${3:Float:minz}, ${4:Float:maxz}, ${5:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamSphere':
'prefix': 'StreamSphere'
'body': 'StreamSphere(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamRectangle':
'prefix': 'StreamRectangle'
'body': 'StreamRectangle(${1:Float:minx}, ${2:Float:miny}, ${3:Float:maxx}, ${4:Float:maxy})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCube':
'prefix': 'StreamCube'
'body': 'StreamCube(${1:Float:minx}, ${2:Float:miny}, ${3:Float:minz}, ${4:Float:maxx}, ${5:Float:maxy}, ${6:Float:maxz})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCircularSector':
'prefix': 'StreamCircularSector'
'body': 'StreamCircularSector(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:Float:view_angle})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamSphericalSector':
'prefix': 'StreamSphericalSector'
'body': 'StreamSphericalSector(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:Float:radius}, ${7:Float:vrx}, ${8:Float:vrz})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsValidStream':
'prefix': 'IsValidStream'
'body': 'IsValidStream(${1:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInStream':
'prefix': 'IsPointInStream'
'body': 'IsPointInStream(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInStream':
'prefix': 'IsPlayerInStream'
'body': 'IsPlayerInStream(${1:playerid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectInStream':
'prefix': 'IsObjectInStream'
'body': 'IsObjectInStream(${1:objectid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorInStream':
'prefix': 'IsActorInStream'
'body': 'IsActorInStream(${1:actorid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInStream':
'prefix': 'IsNPCInStream'
'body': 'IsNPCInStream(${1:npcid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectInStream':
'prefix': 'IsDynamicObjectInStream'
'body': 'IsDynamicObjectInStream(${1:objectid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorInStream':
'prefix': 'IsDynamicActorInStream'
'body': 'IsDynamicActorInStream(${1:actorid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Line3DCreate':
'prefix': 'Line3DCreate'
'body': 'Line3DCreate(${1:variable}, ${2:max_points})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLine3DValue':
'prefix': 'GetLine3DValue'
'body': 'GetLine3DValue(${1:variable}, ${2:pointid}, ${3:name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetLine3DValue':
'prefix': 'SetLine3DValue'
'body': 'SetLine3DValue(${1:variable}, ${2:pointid}, ${3:name}, ${4:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLine3DPointPos':
'prefix': 'GetLine3DPointPos'
'body': 'GetLine3DPointPos(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetLine3DPointPos':
'prefix': 'SetLine3DPointPos'
'body': 'SetLine3DPointPos(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLine3DPointRot':
'prefix': 'GetLine3DPointRot'
'body': 'GetLine3DPointRot(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:&Float:rx}, ${4:&Float:ry}, ${5:&Float:rz}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetLine3DPointRot':
'prefix': 'SetLine3DPointRot'
'body': 'SetLine3DPointRot(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:Float:rx}, ${4:Float:ry}, ${5:Float:rz}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountLine3DPoints':
'prefix': 'CountLine3DPoints'
'body': 'CountLine3DPoints(${1:Line3D:LineData[][LinePoint3D]}, ${2:max_points = sizeof(LineData})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'AddPointToLine3D':
'prefix': 'AddPointToLine3D'
'body': 'AddPointToLine3D(${1:Line3D:LineData[][LinePoint3D]}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx=INVALID_ROTATION}, ${6:Float:ry=INVALID_ROTATION}, ${7:Float:rz=INVALID_ROTATION}, ${8:max_points = sizeof(LineData})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetXYZInFrontOfVehicle':
'prefix': 'GetXYZInFrontOfVehicle'
'body': 'GetXYZInFrontOfVehicle(${1:vehicleid}, ${2:Float:distance}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomClockPos':
'prefix': 'GetRandomClockPos'
'body': 'GetRandomClockPos(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz}, ${8:&Float:trz}, ${9:Float:rz = INVALID_ROTATION})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
| true | # Snippets for Atom, automatically generated
# Generator created by PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI
'.source.pwn, .source.inc':
'sqrtN':
'prefix': 'sqrtN'
'body': 'sqrtN(${1:Float:value}, ${2:Float:exponent})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'abs':
'prefix': 'abs'
'body': 'abs(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'fabs':
'prefix': 'fabs'
'body': 'fabs(${1:Float:value})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'power':
'prefix': 'power'
'body': 'power(${1:value}, ${2:Float:exponent})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ctg':
'prefix': 'ctg'
'body': 'ctg(${1:Float:value}, ${2:anglemode:mode=radian})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'secans':
'prefix': 'secans'
'body': 'secans(${1:Float:value}, ${2:anglemode:mode=radian})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'cosecans':
'prefix': 'cosecans'
'body': 'cosecans(${1:Float:value}, ${2:anglemode:mode=radian})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsEven':
'prefix': 'IsEven'
'body': 'IsEven(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'RandomFloat':
'prefix': 'RandomFloat'
'body': 'RandomFloat(${1:Float:min}, ${2:Float:max}, ${3:accuracy = 4})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'single_clock':
'prefix': 'single_clock'
'body': 'single_clock(${1:max}, ${2:id})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'even_clock':
'prefix': 'even_clock'
'body': 'even_clock(${1:max}, ${2:id})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'uneven_clock':
'prefix': 'uneven_clock'
'body': 'uneven_clock(${1:max}, ${2:id})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTZ':
'prefix': 'NLTZ'
'body': 'NLTZ(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTZ':
'prefix': 'NMTZ'
'body': 'NMTZ(${1:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTZF':
'prefix': 'NLTZF'
'body': 'NLTZF(${1:Float:value})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTZF':
'prefix': 'NMTZF'
'body': 'NMTZF(${1:Float:value})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTV':
'prefix': 'NLTV'
'body': 'NLTV(${1:value}, ${2:min})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTV':
'prefix': 'NMTV'
'body': 'NMTV(${1:value}, ${2:max})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NLTVF':
'prefix': 'NLTVF'
'body': 'NLTVF(${1:Float:value}, ${2:Float:min})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'NMTVF':
'prefix': 'NMTVF'
'body': 'NMTVF(${1:Float:value}, ${2:Float:max})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CompRotation':
'prefix': 'CompRotation'
'body': 'CompRotation(${1:rotation}, ${2:&crotation=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'DeCompRotation':
'prefix': 'DeCompRotation'
'body': 'DeCompRotation(${1:rotation}, ${2:&crotation=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CompRotationFloat':
'prefix': 'CompRotationFloat'
'body': 'CompRotationFloat(${1:Float:rotation}, ${2:&Float:crotation=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'DeCompRotationFloat':
'prefix': 'DeCompRotationFloat'
'body': 'DeCompRotationFloat(${1:Float:rotation}, ${2:&Float:crotation=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsRotationTest':
'prefix': 'IsRotationTest'
'body': 'IsRotationTest(${1:Float:rotation}, ${2:Float:r_min}, ${3:Float:r_max})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetRotationMatrixEuler':
'prefix': 'Tryg3D_GetRotationMatrixEuler'
'body': 'Tryg3D_GetRotationMatrixEuler(${1:Float:matrix[][]}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz}, ${5:T3D:eulermode:mode=T3D:euler_default})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_MatrixRotate':
'prefix': 'Tryg3D_MatrixRotate'
'body': 'Tryg3D_MatrixRotate(${1:Float:matrix[][]}, ${2:Float:oX}, ${3:Float:oY}, ${4:Float:oZ}, ${5:&Float:x}, ${6:&Float:y}, ${7:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GivePlayerDamage':
'prefix': 'Tryg3D_GivePlayerDamage'
'body': 'Tryg3D_GivePlayerDamage(${1:targetid}, ${2:Float:damage}, ${3:playerid}, ${4:weaponid}, ${5:bool:force_spawn=true}, ${6:bool:deathmsg=true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetWeaponDamage':
'prefix': 'Tryg3D_GetWeaponDamage'
'body': 'Tryg3D_GetWeaponDamage(${1:weaponid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_SwapInt':
'prefix': 'Tryg3D_SwapInt'
'body': 'Tryg3D_SwapInt(${1:variable1}, ${2:variable2})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountPlayers':
'prefix': 'CountPlayers'
'body': 'CountPlayers(${1:bool:isplayer=true}, ${2:bool:isnpc=true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountActors':
'prefix': 'CountActors'
'body': 'CountActors()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'RecoilFloat':
'prefix': 'RecoilFloat'
'body': 'RecoilFloat(${1:Float:value}, ${2:Float:recoil})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'RecoilVector':
'prefix': 'RecoilVector'
'body': 'RecoilVector(${1:&Float:vx}, ${2:&Float:vy}, ${3:&Float:vz}, ${4:Float:sx}, ${5:Float:sy}, ${6:Float:sz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftDegreeToRadian':
'prefix': 'ShiftDegreeToRadian'
'body': 'ShiftDegreeToRadian(${1:Float:deg})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftDegreeToRadianEx':
'prefix': 'ShiftDegreeToRadianEx'
'body': 'ShiftDegreeToRadianEx(${1:Float:deg})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftDegreeToGrades':
'prefix': 'ShiftDegreeToGrades'
'body': 'ShiftDegreeToGrades(${1:Float:deg})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRadianToDegree':
'prefix': 'ShiftRadianToDegree'
'body': 'ShiftRadianToDegree(${1:Float:rad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRadianToDegreeEx':
'prefix': 'ShiftRadianToDegreeEx'
'body': 'ShiftRadianToDegreeEx(${1:Float:rad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRadianToGrades':
'prefix': 'ShiftRadianToGrades'
'body': 'ShiftRadianToGrades(${1:Float:rad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftGradesToDegree':
'prefix': 'ShiftGradesToDegree'
'body': 'ShiftGradesToDegree(${1:Float:grad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftGradesToRadian':
'prefix': 'ShiftGradesToRadian'
'body': 'ShiftGradesToRadian(${1:Float:grad})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomHit':
'prefix': 'GetRandomHit'
'body': 'GetRandomHit(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:range}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPoints1D':
'prefix': 'GetDistanceBetweenPoints1D'
'body': 'GetDistanceBetweenPoints1D(${1:Float:x1}, ${2:Float:x2})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPoints2D':
'prefix': 'GetDistanceBetweenPoints2D'
'body': 'GetDistanceBetweenPoints2D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:x2}, ${4:Float:y2})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPoints3D':
'prefix': 'GetDistanceBetweenPoints3D'
'body': 'GetDistanceBetweenPoints3D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:z1}, ${4:Float:x2}, ${5:Float:y2}, ${6:Float:z2})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFront2D':
'prefix': 'GetPointInFront2D'
'body': 'GetPointInFront2D(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFront3D':
'prefix': 'GetPointInFront3D'
'body': 'GetPointInFront3D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:Float:radius}, ${7:&Float:tx}, ${8:&Float:ty}, ${9:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfPlayer':
'prefix': 'GetPointInFrontOfPlayer'
'body': 'GetPointInFrontOfPlayer(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera2D':
'prefix': 'GetPointInFrontOfCamera2D'
'body': 'GetPointInFrontOfCamera2D(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera3D':
'prefix': 'GetPointInFrontOfCamera3D'
'body': 'GetPointInFrontOfCamera3D(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRotationFor2Point2D':
'prefix': 'GetRotationFor2Point2D'
'body': 'GetRotationFor2Point2D(${1:Float:x}, ${2:Float:y}, ${3:Float:tx}, ${4:Float:ty}, ${5:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRotationFor2Point3D':
'prefix': 'GetRotationFor2Point3D'
'body': 'GetRotationFor2Point3D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:&Float:rx}, ${8:&Float:rz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ConvertMTARaceRotation':
'prefix': 'ConvertMTARaceRotation'
'body': 'ConvertMTARaceRotation(${1:Float:rotation1}, ${2:Float:rotation2}, ${3:Float:rotation3}, ${4:&Float:rx}, ${5:&Float:ry}, ${6:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ConvertToMTARaceRotation':
'prefix': 'ConvertToMTARaceRotation'
'body': 'ConvertToMTARaceRotation(${1:Float:rx}, ${2:Float:ry}, ${3:Float:rz}, ${4:&Float:rotation1}, ${5:&Float:rotation2}, ${6:&Float:rotation3})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetMoveTime':
'prefix': 'GetMoveTime'
'body': 'GetMoveTime(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:Float:speed}, ${8:&rtime=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetSpeedForMoveTime':
'prefix': 'GetSpeedForMoveTime'
'body': 'GetSpeedForMoveTime(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:&Float:speed}, ${8:rtime})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleRotation':
'prefix': 'GetVehicleRotation'
'body': 'GetVehicleRotation(${1:vehicleid}, ${2:&Float:rx}, ${3:&Float:ry}, ${4:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle2D':
'prefix': 'GetPointInFrontOfVehicle2D'
'body': 'GetPointInFrontOfVehicle2D(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle3D':
'prefix': 'GetPointInFrontOfVehicle3D'
'body': 'GetPointInFrontOfVehicle3D(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCameraRotation':
'prefix': 'GetPlayerCameraRotation'
'body': 'GetPlayerCameraRotation(${1:playerid}, ${2:&Float:rx}, ${3:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerCameraRotation':
'prefix': 'SetPlayerCameraRotation'
'body': 'SetPlayerCameraRotation(${1:playerid}, ${2:Float:rx}, ${3:Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCameraZAngle':
'prefix': 'GetPlayerCameraZAngle'
'body': 'GetPlayerCameraZAngle(${1:playerid}, ${2:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerCameraZAngle':
'prefix': 'SetPlayerCameraZAngle'
'body': 'SetPlayerCameraZAngle(${1:playerid}, ${2:Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point2D':
'prefix': 'GetPointFor2Point2D'
'body': 'GetPointFor2Point2D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:x2}, ${4:Float:y2}, ${5:Float:percent_size}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point3D':
'prefix': 'GetPointFor2Point3D'
'body': 'GetPointFor2Point3D(${1:Float:x1}, ${2:Float:y1}, ${3:Float:z1}, ${4:Float:x2}, ${5:Float:y2}, ${6:Float:z2}, ${7:Float:percent_size}, ${8:&Float:tx}, ${9:&Float:ty}, ${10:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point2DEx':
'prefix': 'GetPointFor2Point2DEx'
'body': 'GetPointFor2Point2DEx(${1:Float:x1}, ${2:Float:y1}, ${3:Float:x2}, ${4:Float:y2}, ${5:Float:distance}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointFor2Point3DEx':
'prefix': 'GetPointFor2Point3DEx'
'body': 'GetPointFor2Point3DEx(${1:Float:x1}, ${2:Float:y1}, ${3:Float:z1}, ${4:Float:x2}, ${5:Float:y2}, ${6:Float:z2}, ${7:Float:distance}, ${8:&Float:tx}, ${9:&Float:ty}, ${10:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftVectorToRotation':
'prefix': 'ShiftVectorToRotation'
'body': 'ShiftVectorToRotation(${1:Float:vx}, ${2:Float:vy}, ${3:Float:vz}, ${4:&Float:rx}, ${5:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftRotationToVector':
'prefix': 'ShiftRotationToVector'
'body': 'ShiftRotationToVector(${1:Float:rx}, ${2:Float:rz}, ${3:&Float:vx}, ${4:&Float:vy}, ${5:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnClock':
'prefix': 'GetRandomPointOnClock'
'body': 'GetRandomPointOnClock(${1:Float:x}, ${2:Float:y}, ${3:Float:radius}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:trz}, ${7:Float:rz = INVALID_ROTATION})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCircle':
'prefix': 'GetRandomPointInCircle'
'body': 'GetRandomPointInCircle(${1:Float:x}, ${2:Float:y}, ${3:Float:radius}, ${4:&Float:tx}, ${5:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCylinderEx':
'prefix': 'GetRandomPointInCylinderEx'
'body': 'GetRandomPointInCylinderEx(${1:Float:x}, ${2:Float:y}, ${3:Float:minz}, ${4:Float:maxz}, ${5:Float:radius}, ${6:&Float:tx}, ${7:&Float:ty}, ${8:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInSphere':
'prefix': 'GetRandomPointInSphere'
'body': 'GetRandomPointInSphere(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInRectangle':
'prefix': 'GetRandomPointInRectangle'
'body': 'GetRandomPointInRectangle(${1:Float:minx}, ${2:Float:miny}, ${3:Float:maxx}, ${4:Float:maxy}, ${5:&Float:tx}, ${6:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCube':
'prefix': 'GetRandomPointInCube'
'body': 'GetRandomPointInCube(${1:Float:minx}, ${2:Float:miny}, ${3:Float:minz}, ${4:Float:maxx}, ${5:Float:maxy}, ${6:Float:maxz}, ${7:&Float:tx}, ${8:&Float:ty}, ${9:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointInCircularSector':
'prefix': 'GetRandomPointInCircularSector'
'body': 'GetRandomPointInCircularSector(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:Float:view_angle}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnCircle':
'prefix': 'GetRandomPointOnCircle'
'body': 'GetRandomPointOnCircle(${1:Float:x}, ${2:Float:y}, ${3:Float:radius}, ${4:&Float:tx}, ${5:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnSphere':
'prefix': 'GetRandomPointOnSphere'
'body': 'GetRandomPointOnSphere(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomPointOnCircularSector':
'prefix': 'GetRandomPointOnCircularSector'
'body': 'GetRandomPointOnCircularSector(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:Float:view_angle}, ${6:&Float:tx}, ${7:&Float:ty})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointBetween2Points2D':
'prefix': 'IsPointBetween2Points2D'
'body': 'IsPointBetween2Points2D(${1:Float:px}, ${2:Float:py}, ${3:Float:xA}, ${4:Float:yA}, ${5:Float:xB}, ${6:Float:yB})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointBetween2Points3D':
'prefix': 'IsPointBetween2Points3D'
'body': 'IsPointBetween2Points3D(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:xA}, ${5:Float:yA}, ${6:Float:zA}, ${7:Float:xB}, ${8:Float:yB}, ${9:Float:zB})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointNearly2Points2D':
'prefix': 'IsPointNearly2Points2D'
'body': 'IsPointNearly2Points2D(${1:Float:px}, ${2:Float:py}, ${3:Float:xA}, ${4:Float:yA}, ${5:Float:xB}, ${6:Float:yB}, ${7:Float:maxdist})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointNearly2Points3D':
'prefix': 'IsPointNearly2Points3D'
'body': 'IsPointNearly2Points3D(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:xA}, ${5:Float:yA}, ${6:Float:zA}, ${7:Float:xB}, ${8:Float:yB}, ${9:Float:zB}, ${10:Float:maxdist})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCircle':
'prefix': 'IsPointInCircle'
'body': 'IsPointInCircle(${1:Float:px}, ${2:Float:py}, ${3:Float:x}, ${4:Float:y}, ${5:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCylinder':
'prefix': 'IsPointInCylinder'
'body': 'IsPointInCylinder(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:xA}, ${5:Float:yA}, ${6:Float:zA}, ${7:Float:xB}, ${8:Float:yB}, ${9:Float:zB}, ${10:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCylinderEx':
'prefix': 'IsPointInCylinderEx'
'body': 'IsPointInCylinderEx(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:minz}, ${7:Float:maxz}, ${8:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInSphere':
'prefix': 'IsPointInSphere'
'body': 'IsPointInSphere(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInRectangle':
'prefix': 'IsPointInRectangle'
'body': 'IsPointInRectangle(${1:Float:x}, ${2:Float:y}, ${3:Float:minx}, ${4:Float:miny}, ${5:Float:maxx}, ${6:Float:maxy})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCube':
'prefix': 'IsPointInCube'
'body': 'IsPointInCube(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:minx}, ${5:Float:miny}, ${6:Float:minz}, ${7:Float:maxx}, ${8:Float:maxy}, ${9:Float:maxz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInPolygon':
'prefix': 'IsPointInPolygon'
'body': 'IsPointInPolygon(${1:Float:x}, ${2:Float:y}, ${3:Float:points[]}, ${4:maxpoints = sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInCircularSector':
'prefix': 'IsPointInCircularSector'
'body': 'IsPointInCircularSector(${1:Float:px}, ${2:Float:py}, ${3:Float:x}, ${4:Float:y}, ${5:Float:rz}, ${6:Float:radius}, ${7:Float:view_angle})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInSphericalSector':
'prefix': 'IsPointInSphericalSector'
'body': 'IsPointInSphericalSector(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:Float:rx}, ${8:Float:rz}, ${9:Float:radius}, ${10:Float:vrx}, ${11:Float:vrz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCircle':
'prefix': 'IsPlayerInCircle'
'body': 'IsPlayerInCircle(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCylinder':
'prefix': 'IsPlayerInCylinder'
'body': 'IsPlayerInCylinder(${1:playerid}, ${2:Float:xA}, ${3:Float:yA}, ${4:Float:zA}, ${5:Float:xB}, ${6:Float:yB}, ${7:Float:zB}, ${8:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCylinderEx':
'prefix': 'IsPlayerInCylinderEx'
'body': 'IsPlayerInCylinderEx(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:minz}, ${5:Float:maxz}, ${6:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInSphere':
'prefix': 'IsPlayerInSphere'
'body': 'IsPlayerInSphere(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInRectangle':
'prefix': 'IsPlayerInRectangle'
'body': 'IsPlayerInRectangle(${1:playerid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:maxx}, ${5:Float:maxy})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCube':
'prefix': 'IsPlayerInCube'
'body': 'IsPlayerInCube(${1:playerid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:minz}, ${5:Float:maxx}, ${6:Float:maxy}, ${7:Float:maxz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInPolygon':
'prefix': 'IsPlayerInPolygon'
'body': 'IsPlayerInPolygon(${1:playerid}, ${2:Float:points[]}, ${3:maxpoints = sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInCircularSector':
'prefix': 'IsPlayerInCircularSector'
'body': 'IsPlayerInCircularSector(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:rz}, ${5:Float:radius}, ${6:Float:view_angle})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInSphericalSector':
'prefix': 'IsPlayerInSphericalSector'
'body': 'IsPlayerInSphericalSector(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:radius}, ${8:Float:vrx}, ${9:Float:vrz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsProbable':
'prefix': 'IsProbable'
'body': 'IsProbable(${1:chance})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CalculatePercent':
'prefix': 'CalculatePercent'
'body': 'CalculatePercent(${1:Float:value}, ${2:Float:maxvalue})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerTargetAngle':
'prefix': 'GetPlayerTargetAngle'
'body': 'GetPlayerTargetAngle(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerTargetAngle':
'prefix': 'SetPlayerTargetAngle'
'body': 'SetPlayerTargetAngle(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerTargetPlayerAngle':
'prefix': 'GetPlayerTargetPlayerAngle'
'body': 'GetPlayerTargetPlayerAngle(${1:playerid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerTargetPlayerAngle':
'prefix': 'SetPlayerTargetPlayerAngle'
'body': 'SetPlayerTargetPlayerAngle(${1:playerid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleSpeed':
'prefix': 'GetVehicleSpeed'
'body': 'GetVehicleSpeed(${1:vehicleid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerSpeed':
'prefix': 'GetPlayerSpeed'
'body': 'GetPlayerSpeed(${1:playerid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CreateDynamicExplosion':
'prefix': 'CreateDynamicExplosion'
'body': 'CreateDynamicExplosion(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:type}, ${5:Float:radius}, ${6:worldid=-1}, ${7:interiorid=-1}, ${8:playerid=-1}, ${9:Float:distance=200.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleFlags':
'prefix': 'GetVehicleFlags'
'body': 'GetVehicleFlags(${1:vehicleid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleFlagsByModel':
'prefix': 'GetVehicleFlagsByModel'
'body': 'GetVehicleFlagsByModel(${1:modelid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleFlag':
'prefix': 'IsVehicleFlag'
'body': 'IsVehicleFlag(${1:value}, ${2:flag})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerOrientationPos':
'prefix': 'GetPlayerOrientationPos'
'body': 'GetPlayerOrientationPos(${1:playerid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz}, ${7:isactor=false})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleOrientationPos':
'prefix': 'GetVehicleOrientationPos'
'body': 'GetVehicleOrientationPos(${1:vehicleid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectOrientationPos':
'prefix': 'GetObjectOrientationPos'
'body': 'GetObjectOrientationPos(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetWeaponShotPos':
'prefix': 'GetWeaponShotPos'
'body': 'GetWeaponShotPos(${1:playerid}, ${2:hittype}, ${3:&Float:fx}, ${4:&Float:fy}, ${5:&Float:fz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetActorDistanceFromPoint':
'prefix': 'GetActorDistanceFromPoint'
'body': 'GetActorDistanceFromPoint(${1:actorid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectDistanceFromPoint':
'prefix': 'GetObjectDistanceFromPoint'
'body': 'GetObjectDistanceFromPoint(${1:objectid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenPlayers':
'prefix': 'GetDistanceBetweenPlayers'
'body': 'GetDistanceBetweenPlayers(${1:playerid_a}, ${2:playerid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenVehicles':
'prefix': 'GetDistanceBetweenVehicles'
'body': 'GetDistanceBetweenVehicles(${1:vehicleid_a}, ${2:vehicleid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenObjects':
'prefix': 'GetDistanceBetweenObjects'
'body': 'GetDistanceBetweenObjects(${1:objectid_a}, ${2:objectid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerActorDistance':
'prefix': 'GetPlayerActorDistance'
'body': 'GetPlayerActorDistance(${1:playerid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerVehicleDistance':
'prefix': 'GetPlayerVehicleDistance'
'body': 'GetPlayerVehicleDistance(${1:playerid}, ${2:vehicleid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerObjectDistance':
'prefix': 'GetPlayerObjectDistance'
'body': 'GetPlayerObjectDistance(${1:playerid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerLookAtPlayer':
'prefix': 'SetPlayerLookAtPlayer'
'body': 'SetPlayerLookAtPlayer(${1:playerid}, ${2:targetid}, ${3:cut = CAMERA_CUT})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCameraLookAt':
'prefix': 'GetPlayerCameraLookAt'
'body': 'GetPlayerCameraLookAt(${1:playerid}, ${2:&Float:x}, ${3:&Float:y}, ${4:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerLookAtSky':
'prefix': 'IsPlayerLookAtSky'
'body': 'IsPlayerLookAtSky(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleUpVector':
'prefix': 'GetVehicleUpVector'
'body': 'GetVehicleUpVector(${1:vehicleid}, ${2:&Float:vx}, ${3:&Float:vy}, ${4:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleUpPos':
'prefix': 'GetVehicleUpPos'
'body': 'GetVehicleUpPos(${1:vehicleid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleDownPos':
'prefix': 'GetVehicleDownPos'
'body': 'GetVehicleDownPos(${1:vehicleid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectRotationQuat':
'prefix': 'GetObjectRotationQuat'
'body': 'GetObjectRotationQuat(${1:objectid}, ${2:&Float:qw}, ${3:&Float:qx}, ${4:&Float:qy}, ${5:&Float:qz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectUpVector':
'prefix': 'GetObjectUpVector'
'body': 'GetObjectUpVector(${1:objectid}, ${2:&Float:vx}, ${3:&Float:vy}, ${4:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectUpPos':
'prefix': 'GetObjectUpPos'
'body': 'GetObjectUpPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectDownPos':
'prefix': 'GetObjectDownPos'
'body': 'GetObjectDownPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetQuatUpVector':
'prefix': 'GetQuatUpVector'
'body': 'GetQuatUpVector(${1:Float:qw}, ${2:Float:qx}, ${3:Float:qy}, ${4:Float:qz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetQuatFromRot':
'prefix': 'GetQuatFromRot'
'body': 'GetQuatFromRot(${1:Float:rx}, ${2:Float:ry}, ${3:Float:rz}, ${4:&Float:qw}, ${5:&Float:qx}, ${6:&Float:qy}, ${7:&Float:qz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLineSize2D':
'prefix': 'GetLineSize2D'
'body': 'GetLineSize2D(${1:Float:points[][]}, ${2:maxpoints=sizeof(points})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLineSize3D':
'prefix': 'GetLineSize3D'
'body': 'GetLineSize3D(${1:Float:points[][]}, ${2:maxpoints=sizeof(points})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointToPointVector':
'prefix': 'GetPointToPointVector'
'body': 'GetPointToPointVector(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:tz}, ${7:&Float:vx}, ${8:&Float:vy}, ${9:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerToPointVector':
'prefix': 'GetPlayerToPointVector'
'body': 'GetPlayerToPointVector(${1:playerid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectToPointVector':
'prefix': 'GetObjectToPointVector'
'body': 'GetObjectToPointVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleToPointVector':
'prefix': 'GetVehicleToPointVector'
'body': 'GetVehicleToPointVector(${1:vehicleid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleInRangeOfPoint':
'prefix': 'IsVehicleInRangeOfPoint'
'body': 'IsVehicleInRangeOfPoint(${1:vehicleid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorInRangeOfPoint':
'prefix': 'IsActorInRangeOfPoint'
'body': 'IsActorInRangeOfPoint(${1:actorid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectInRangeOfPoint':
'prefix': 'IsObjectInRangeOfPoint'
'body': 'IsObjectInRangeOfPoint(${1:objectid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftLineRotation':
'prefix': 'ShiftLineRotation'
'body': 'ShiftLineRotation(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:Float:rx}, ${8:Float:ry}, ${9:Float:rz}, ${10:&Float:nX}, ${11:&Float:nY}, ${12:&Float:nZ})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftLineRotationVector':
'prefix': 'ShiftLineRotationVector'
'body': 'ShiftLineRotationVector(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:Float:rx}, ${8:Float:ry}, ${9:Float:rz}, ${10:&Float:nX}, ${11:&Float:nY}, ${12:&Float:nZ})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerRotatedVector':
'prefix': 'GetPlayerRotatedVector'
'body': 'GetPlayerRotatedVector(${1:playerid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectRotatedVector':
'prefix': 'GetObjectRotatedVector'
'body': 'GetObjectRotatedVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleRotatedVector':
'prefix': 'GetVehicleRotatedVector'
'body': 'GetVehicleRotatedVector(${1:vehicleid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsFloor2D':
'prefix': 'GetArcPointsFloor2D'
'body': 'GetArcPointsFloor2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsCellar2D':
'prefix': 'GetArcPointsCellar2D'
'body': 'GetArcPointsCellar2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsStarboard2D':
'prefix': 'GetArcPointsStarboard2D'
'body': 'GetArcPointsStarboard2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetArcPointsLarboard2D':
'prefix': 'GetArcPointsLarboard2D'
'body': 'GetArcPointsLarboard2D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:tx}, ${5:Float:ty}, ${6:Float:spread}, ${7:Float:points[][]}, ${8:max_points=sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInSphericalSectorEx':
'prefix': 'IsPointInSphericalSectorEx'
'body': 'IsPointInSphericalSectorEx(${1:Float:px}, ${2:Float:py}, ${3:Float:pz}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:Float:rx}, ${8:Float:rz}, ${9:Float:radius}, ${10:Float:vrx}, ${11:Float:vrz}, ${12:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerOnPlayerScreen':
'prefix': 'IsPlayerOnPlayerScreen'
'body': 'IsPlayerOnPlayerScreen(${1:playerid}, ${2:targetid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleOnPlayerScreen':
'prefix': 'IsVehicleOnPlayerScreen'
'body': 'IsVehicleOnPlayerScreen(${1:playerid}, ${2:vehicleid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectOnPlayerScreen':
'prefix': 'IsObjectOnPlayerScreen'
'body': 'IsObjectOnPlayerScreen(${1:playerid}, ${2:objectid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorOnPlayerScreen':
'prefix': 'IsActorOnPlayerScreen'
'body': 'IsActorOnPlayerScreen(${1:playerid}, ${2:actorid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerOnFakeScreen':
'prefix': 'IsPlayerOnFakeScreen'
'body': 'IsPlayerOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:targetid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsVehicleOnFakeScreen':
'prefix': 'IsVehicleOnFakeScreen'
'body': 'IsVehicleOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:vehicleid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectOnFakeScreen':
'prefix': 'IsObjectOnFakeScreen'
'body': 'IsObjectOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:objectid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorOnFakeScreen':
'prefix': 'IsActorOnFakeScreen'
'body': 'IsActorOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:actorid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerSkydiving':
'prefix': 'IsPlayerSkydiving'
'body': 'IsPlayerSkydiving(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerUsingParachute':
'prefix': 'IsPlayerUsingParachute'
'body': 'IsPlayerUsingParachute(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerAiming':
'prefix': 'IsPlayerAiming'
'body': 'IsPlayerAiming(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerStay':
'prefix': 'IsPlayerStay'
'body': 'IsPlayerStay(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerRunning':
'prefix': 'IsPlayerRunning'
'body': 'IsPlayerRunning(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerSwim':
'prefix': 'IsPlayerSwim'
'body': 'IsPlayerSwim(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerJump':
'prefix': 'IsPlayerJump'
'body': 'IsPlayerJump(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerParaFall':
'prefix': 'IsPlayerParaFall'
'body': 'IsPlayerParaFall(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerParaGlide':
'prefix': 'IsPlayerParaGlide'
'body': 'IsPlayerParaGlide(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerFall':
'prefix': 'IsPlayerFall'
'body': 'IsPlayerFall(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Get3DTrygModules':
'prefix': 'Get3DTrygModules'
'body': 'Get3DTrygModules(${1:&modules_count=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsTryg3DModuleLoaded':
'prefix': 'IsTryg3DModuleLoaded'
'body': 'IsTryg3DModuleLoaded(${1:Tryg3DModule:moduleid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Get3DTrygEfficiency':
'prefix': 'Get3DTrygEfficiency'
'body': 'Get3DTrygEfficiency(${1:bool:use_colandreas=false})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Get3DTrygErrorCount':
'prefix': 'Get3DTrygErrorCount'
'body': 'Get3DTrygErrorCount()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Reset3DTrygErrorCount':
'prefix': 'Reset3DTrygErrorCount'
'body': 'Reset3DTrygErrorCount()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_SetStreamDistance':
'prefix': 'Tryg3D_SetStreamDistance'
'body': 'Tryg3D_SetStreamDistance(${1:Float:streamdistance})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetStreamDistance':
'prefix': 'Tryg3D_GetStreamDistance'
'body': 'Tryg3D_GetStreamDistance()'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetTryg3DActiveCount':
'prefix': 'GetTryg3DActiveCount'
'body': 'GetTryg3DActiveCount()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftPositionToOrion':
'prefix': 'ShiftPositionToOrion'
'body': 'ShiftPositionToOrion(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:&Float:orion}, ${5:&Float:lon}, ${6:&Float:lat})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ShiftOrionToPosition':
'prefix': 'ShiftOrionToPosition'
'body': 'ShiftOrionToPosition(${1:Float:orion}, ${2:Float:lon}, ${3:Float:lat}, ${4:&Float:x}, ${5:&Float:y}, ${6:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'randomex':
'prefix': 'randomex'
'body': 'randomex(${1:min}, ${2:max})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_KeyPressed':
'prefix': 'Tryg3D_KeyPressed'
'body': 'Tryg3D_KeyPressed(${1:key})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_KeyReleased':
'prefix': 'Tryg3D_KeyReleased'
'body': 'Tryg3D_KeyReleased(${1:key})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_KeyHolding':
'prefix': 'Tryg3D_KeyHolding'
'body': 'Tryg3D_KeyHolding(${1:key})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetSAMIncludeVersion':
'prefix': 'GetSAMIncludeVersion'
'body': 'GetSAMIncludeVersion(${1:value}, ${2:name[]}, ${3:maxdest = sizeof(name})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'DisableADMLogging':
'prefix': 'DisableADMLogging'
'body': 'DisableADMLogging(${1:bool:disable})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SecToTimeDay':
'prefix': 'SecToTimeDay'
'body': 'SecToTimeDay(${1:second})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MSToTimeDay':
'prefix': 'MSToTimeDay'
'body': 'MSToTimeDay(${1:millisecond})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SecToTime':
'prefix': 'SecToTime'
'body': 'SecToTime(${1:second})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MSToTime':
'prefix': 'MSToTime'
'body': 'MSToTime(${1:millisecond})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SecToTimeMini':
'prefix': 'SecToTimeMini'
'body': 'SecToTimeMini(${1:second})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MSToTimeMini':
'prefix': 'MSToTimeMini'
'body': 'MSToTimeMini(${1:millisecond})'
'leftLabel': 'T3D'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectOrientationPos':
'prefix': 'GetDynamicObjectOrientationPos'
'body': 'GetDynamicObjectOrientationPos(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenDynamicObject':
'prefix': 'GetDistanceBetweenDynamicObject'
'body': 'GetDistanceBetweenDynamicObject(${1:objectid_a}, ${2:objectid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerDynamicObjectDistance':
'prefix': 'GetPlayerDynamicObjectDistance'
'body': 'GetPlayerDynamicObjectDistance(${1:playerid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectRotationQuat':
'prefix': 'GetDynamicObjectRotationQuat'
'body': 'GetDynamicObjectRotationQuat(${1:objectid}, ${2:&Float:qw}, ${3:&Float:qx}, ${4:&Float:qy}, ${5:&Float:qz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectUpVector':
'prefix': 'GetDynamicObjectUpVector'
'body': 'GetDynamicObjectUpVector(${1:objectid}, ${2:&Float:vx}, ${3:&Float:vy}, ${4:&Float:vz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectUpPos':
'prefix': 'GetDynamicObjectUpPos'
'body': 'GetDynamicObjectUpPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectDownPos':
'prefix': 'GetDynamicObjectDownPos'
'body': 'GetDynamicObjectDownPos(${1:objectid}, ${2:Float:radius}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectToPointVector':
'prefix': 'GetDynamicObjectToPointVector'
'body': 'GetDynamicObjectToPointVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectDistFromPoint':
'prefix': 'GetDynamicObjectDistFromPoint'
'body': 'GetDynamicObjectDistFromPoint(${1:objectid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectInRangeOfPoint':
'prefix': 'IsDynamicObjectInRangeOfPoint'
'body': 'IsDynamicObjectInRangeOfPoint(${1:objectid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerAbsolutePosition':
'prefix': 'SetPlayerAbsolutePosition'
'body': 'SetPlayerAbsolutePosition(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:angle}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:compensatedtime = -1})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerAbsolutePositionVeh':
'prefix': 'SetPlayerAbsolutePositionVeh'
'body': 'SetPlayerAbsolutePositionVeh(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:angle}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:compensatedtime = -1})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectRotatedVector':
'prefix': 'GetDynamicObjectRotatedVector'
'body': 'GetDynamicObjectRotatedVector(${1:objectid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectOnPlayerScreen':
'prefix': 'IsDynamicObjectOnPlayerScreen'
'body': 'IsDynamicObjectOnPlayerScreen(${1:playerid}, ${2:objectid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectOnFakeScreen':
'prefix': 'IsDynamicObjectOnFakeScreen'
'body': 'IsDynamicObjectOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:objectid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicActorDistFromPoint':
'prefix': 'GetDynamicActorDistFromPoint'
'body': 'GetDynamicActorDistFromPoint(${1:actorid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerDynamicActorDistance':
'prefix': 'GetPlayerDynamicActorDistance'
'body': 'GetPlayerDynamicActorDistance(${1:playerid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorInRangeOfPoint':
'prefix': 'IsDynamicActorInRangeOfPoint'
'body': 'IsDynamicActorInRangeOfPoint(${1:actorid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicActorOrientationPos':
'prefix': 'GetDynamicActorOrientationPos'
'body': 'GetDynamicActorOrientationPos(${1:actorid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorOnPlayerScreen':
'prefix': 'IsDynamicActorOnPlayerScreen'
'body': 'IsDynamicActorOnPlayerScreen(${1:playerid}, ${2:actorid}, ${3:Float:rx=INVALID_ROTATION}, ${4:Float:rz=INVALID_ROTATION}, ${5:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${6:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${7:bool:testLOS=true}, ${8:bool:testVW=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorOnFakeScreen':
'prefix': 'IsDynamicActorOnFakeScreen'
'body': 'IsDynamicActorOnFakeScreen(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:actorid}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:vrx=VERTICAL_CAMERA_RADIUS}, ${8:Float:vrz=HORIZONTAL_CAMERA_RADIUS}, ${9:bool:testLOS=true})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_IsValidStreamer':
'prefix': 'Tryg3D_IsValidStreamer'
'body': 'Tryg3D_IsValidStreamer(${1:version})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_GetStreamerVersionName':
'prefix': 'Tryg3D_GetStreamerVersionName'
'body': 'Tryg3D_GetStreamerVersionName(${1:name[]}, ${2:value = TRYG3D_GET_STREAMER_VERSION}, ${3:maxdest = sizeof(name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Tryg3D_CheckStreamerVersion':
'prefix': 'Tryg3D_CheckStreamerVersion'
'body': 'Tryg3D_CheckStreamerVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectOrientPosCol':
'prefix': 'GetDynamicObjectOrientPosCol'
'body': 'GetDynamicObjectOrientPosCol(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicObjectCollisionFlags':
'prefix': 'GetDynamicObjectCollisionFlags'
'body': 'GetDynamicObjectCollisionFlags(${1:objectid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDynamicActorOrientPosCol':
'prefix': 'GetDynamicActorOrientPosCol'
'body': 'GetDynamicActorOrientPosCol(${1:actorid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetNPCAbsolutePosition':
'prefix': 'SetNPCAbsolutePosition'
'body': 'SetNPCAbsolutePosition(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:angle}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:compensatedtime = -1})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCDynamicActorDistance':
'prefix': 'GetNPCDynamicActorDistance'
'body': 'GetNPCDynamicActorDistance(${1:npcid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MapAndreasFindZ':
'prefix': 'MapAndreasFindZ'
'body': 'MapAndreasFindZ(${1:Float:x}, ${2:Float:y}, ${3:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetGroundRotation':
'prefix': 'GetGroundRotation'
'body': 'GetGroundRotation(${1:Float:x}, ${2:Float:y}, ${3:Float:size}, ${4:&Float:rx}, ${5:&Float:ry})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOnGround':
'prefix': 'GetPointInFrontOnGround'
'body': 'GetPointInFrontOnGround(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:&Float:tx}, ${7:&Float:ty}, ${8:&Float:tz}, ${9:Float:max_distance})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInWaterFrontOfPlayer':
'prefix': 'IsPointInWaterFrontOfPlayer'
'body': 'IsPointInWaterFrontOfPlayer(${1:playerid}, ${2:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInWater':
'prefix': 'IsPointInWater'
'body': 'IsPointInWater(${1:Float:x}, ${2:Float:y}, ${3:Float:z=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsMapAndreasInit':
'prefix': 'IsMapAndreasInit'
'body': 'IsMapAndreasInit()'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SafeMapAndreasInit':
'prefix': 'SafeMapAndreasInit'
'body': 'SafeMapAndreasInit(${1:mode = MAP_ANDREAS_MODE_FULL}, ${2:name[]=\"\"}, ${3:len=sizeof(name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MovePointCol':
'prefix': 'MovePointCol'
'body': 'MovePointCol(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MovePointColCutLine':
'prefix': 'MovePointColCutLine'
'body': 'MovePointColCutLine(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:Float:cut_size=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'MovePointColCutLineEx':
'prefix': 'MovePointColCutLineEx'
'body': 'MovePointColCutLineEx(${1:Float:sX}, ${2:Float:sY}, ${3:Float:sZ}, ${4:Float:eX}, ${5:Float:eY}, ${6:Float:eZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:Float:cut_size=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFront3DCol':
'prefix': 'GetPointInFront3DCol'
'body': 'GetPointInFront3DCol(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:Float:radius}, ${7:&Float:tx}, ${8:&Float:ty}, ${9:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfPlayerCol':
'prefix': 'GetPointInFrontOfPlayerCol'
'body': 'GetPointInFrontOfPlayerCol(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera2DCol':
'prefix': 'GetPointInFrontOfCamera2DCol'
'body': 'GetPointInFrontOfCamera2DCol(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfCamera3DCol':
'prefix': 'GetPointInFrontOfCamera3DCol'
'body': 'GetPointInFrontOfCamera3DCol(${1:playerid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle2DCol':
'prefix': 'GetPointInFrontOfVehicle2DCol'
'body': 'GetPointInFrontOfVehicle2DCol(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfVehicle3DCol':
'prefix': 'GetPointInFrontOfVehicle3DCol'
'body': 'GetPointInFrontOfVehicle3DCol(${1:vehicleid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:&Float:tz}, ${5:Float:radius}, ${6:&Float:rx=0.0}, ${7:&Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointCollisionFlags':
'prefix': 'GetPointCollisionFlags'
'body': 'GetPointCollisionFlags(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:interiorid=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerCollisionFlags':
'prefix': 'GetPlayerCollisionFlags'
'body': 'GetPlayerCollisionFlags(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleCollisionFlags':
'prefix': 'GetVehicleCollisionFlags'
'body': 'GetVehicleCollisionFlags(${1:vehicleid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectCollisionFlags':
'prefix': 'GetObjectCollisionFlags'
'body': 'GetObjectCollisionFlags(${1:objectid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsCollisionFlag':
'prefix': 'IsCollisionFlag'
'body': 'IsCollisionFlag(${1:value}, ${2:flag})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'UndergroundFindZ':
'prefix': 'UndergroundFindZ'
'body': 'UndergroundFindZ(${1:Float:x}, ${2:Float:y}, ${3:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'InteriorFindZ':
'prefix': 'InteriorFindZ'
'body': 'InteriorFindZ(${1:Float:px}, ${2:Float:py}, ${3:Float:pz=1000.0}, ${4:Float:size=2.0}, ${5:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInUnderwater':
'prefix': 'IsPointInUnderwater'
'body': 'IsPointInUnderwater(${1:Float:x}, ${2:Float:y}, ${3:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInUnderground':
'prefix': 'IsPointInUnderground'
'body': 'IsPointInUnderground(${1:Float:x}, ${2:Float:y}, ${3:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInAir':
'prefix': 'IsPointInAir'
'body': 'IsPointInAir(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:bool:interior=false}, ${5:Float:max_distance=2.2})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInGround':
'prefix': 'IsPointInGround'
'body': 'IsPointInGround(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:bool:interior=false}, ${5:Float:max_distance=2.2})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ColAndreasFindZ':
'prefix': 'ColAndreasFindZ'
'body': 'ColAndreasFindZ(${1:Float:x}, ${2:Float:y}, ${3:&Float:z=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerOrientationPosCol':
'prefix': 'GetPlayerOrientationPosCol'
'body': 'GetPlayerOrientationPosCol(${1:playerid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz}, ${7:isactor=false})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetVehicleOrientationPosCol':
'prefix': 'GetVehicleOrientationPosCol'
'body': 'GetVehicleOrientationPosCol(${1:vehicleid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetObjectOrientationPosCol':
'prefix': 'GetObjectOrientationPosCol'
'body': 'GetObjectOrientationPosCol(${1:objectid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenPlayersIsWall':
'prefix': 'IsBetweenPlayersIsWall'
'body': 'IsBetweenPlayersIsWall(${1:playerid}, ${2:targetid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenPlayerToPointIsWall':
'prefix': 'IsBetweenPlayerToPointIsWall'
'body': 'IsBetweenPlayerToPointIsWall(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInWallForPoint':
'prefix': 'GetPointInWallForPoint'
'body': 'GetPointInWallForPoint(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz}, ${8:Float:sector=90.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsColAndreasInit':
'prefix': 'IsColAndreasInit'
'body': 'IsColAndreasInit()'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SafeColAndreasInit':
'prefix': 'SafeColAndreasInit'
'body': 'SafeColAndreasInit()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetColAndreasVersion':
'prefix': 'GetColAndreasVersion'
'body': 'GetColAndreasVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetValidColAndreasVersion':
'prefix': 'GetValidColAndreasVersion'
'body': 'GetValidColAndreasVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsValidColAndreas':
'prefix': 'IsValidColAndreas'
'body': 'IsValidColAndreas(${1:version})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetColAndreasVersionName':
'prefix': 'GetColAndreasVersionName'
'body': 'GetColAndreasVersionName(${1:name[]}, ${2:value = GET_COLANDREAS_VERSION}, ${3:maxdest = sizeof(name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CheckColAndreasVersion':
'prefix': 'CheckColAndreasVersion'
'body': 'CheckColAndreasVersion()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'OnColAndreasRemoveBuilding':
'prefix': 'OnColAndreasRemoveBuilding'
'body': 'OnColAndreasRemoveBuilding()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerHydraReactorRX':
'prefix': 'GetPlayerHydraReactorRX'
'body': 'GetPlayerHydraReactorRX(${1:playerid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerHydraReactorBoost':
'prefix': 'IsPlayerHydraReactorBoost'
'body': 'IsPlayerHydraReactorBoost(${1:playerid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerRotation':
'prefix': 'GetPlayerRotation'
'body': 'GetPlayerRotation(${1:playerid}, ${2:&Float:rx}, ${3:&Float:ry}, ${4:&Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountTextDraw':
'prefix': 'CountTextDraw'
'body': 'CountTextDraw()'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountPlayerTextDraw':
'prefix': 'CountPlayerTextDraw'
'body': 'CountPlayerTextDraw(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountVisibleTextDraw':
'prefix': 'CountVisibleTextDraw'
'body': 'CountVisibleTextDraw(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountVisiblePlayerTextDraw':
'prefix': 'CountVisiblePlayerTextDraw'
'body': 'CountVisiblePlayerTextDraw(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'UpdatePlayerTimeline':
'prefix': 'UpdatePlayerTimeline'
'body': 'UpdatePlayerTimeline(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerTimeline':
'prefix': 'GetPlayerTimeline'
'body': 'GetPlayerTimeline(${1:playerid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerTimeline':
'prefix': 'SetPlayerTimeline'
'body': 'SetPlayerTimeline(${1:playerid}, ${2:timeline})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPlayerPos4D':
'prefix': 'GetPlayerPos4D'
'body': 'GetPlayerPos4D(${1:playerid}, ${2:&Float:x}, ${3:&Float:y}, ${4:&Float:z}, ${5:&timeline})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetPlayerPos4D':
'prefix': 'SetPlayerPos4D'
'body': 'SetPlayerPos4D(${1:playerid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:timeline=0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CreateDynamicExplosion4D':
'prefix': 'CreateDynamicExplosion4D'
'body': 'CreateDynamicExplosion4D(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:type}, ${5:Float:radius}, ${6:worldid = -1}, ${7:interiorid = -1}, ${8:timeline = -1}, ${9:playerid = -1}, ${10:Float:distance = 200.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCircle':
'prefix': 'IsNPCInCircle'
'body': 'IsNPCInCircle(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCylinder':
'prefix': 'IsNPCInCylinder'
'body': 'IsNPCInCylinder(${1:npcid}, ${2:Float:xA}, ${3:Float:yA}, ${4:Float:zA}, ${5:Float:xB}, ${6:Float:yB}, ${7:Float:zB}, ${8:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCylinderEx':
'prefix': 'IsNPCInCylinderEx'
'body': 'IsNPCInCylinderEx(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:minz}, ${5:Float:maxz}, ${6:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInSphere':
'prefix': 'IsNPCInSphere'
'body': 'IsNPCInSphere(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInRectangle':
'prefix': 'IsNPCInRectangle'
'body': 'IsNPCInRectangle(${1:npcid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:maxx}, ${5:Float:maxy})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCube':
'prefix': 'IsNPCInCube'
'body': 'IsNPCInCube(${1:npcid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:minz}, ${5:Float:maxx}, ${6:Float:maxy}, ${7:Float:maxz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInPolygon':
'prefix': 'IsNPCInPolygon'
'body': 'IsNPCInPolygon(${1:npcid}, ${2:Float:points[]}, ${3:maxpoints = sizeof(points})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInCircularSector':
'prefix': 'IsNPCInCircularSector'
'body': 'IsNPCInCircularSector(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:rz}, ${5:Float:radius}, ${6:Float:view_angle})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInSphericalSector':
'prefix': 'IsNPCInSphericalSector'
'body': 'IsNPCInSphericalSector(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:rz}, ${7:Float:radius}, ${8:Float:vrx}, ${9:Float:vrz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfNPC':
'prefix': 'GetPointInFrontOfNPC'
'body': 'GetPointInFrontOfNPC(${1:npcid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCOrientationPos':
'prefix': 'GetNPCOrientationPos'
'body': 'GetNPCOrientationPos(${1:npcid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCDistanceFromPoint':
'prefix': 'GetNPCDistanceFromPoint'
'body': 'GetNPCDistanceFromPoint(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInRangeOfPoint':
'prefix': 'IsNPCInRangeOfPoint'
'body': 'IsNPCInRangeOfPoint(${1:npcid}, ${2:Float:range}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetDistanceBetweenNPCs':
'prefix': 'GetDistanceBetweenNPCs'
'body': 'GetDistanceBetweenNPCs(${1:npcid_a}, ${2:npcid_b})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCSpeed':
'prefix': 'GetNPCSpeed'
'body': 'GetNPCSpeed(${1:npcid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCTargetAngle':
'prefix': 'GetNPCTargetAngle'
'body': 'GetNPCTargetAngle(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetNPCTargetAngle':
'prefix': 'SetNPCTargetAngle'
'body': 'SetNPCTargetAngle(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCTargetNPCAngle':
'prefix': 'GetNPCTargetNPCAngle'
'body': 'GetNPCTargetNPCAngle(${1:npcid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetNPCTargetNPCAngle':
'prefix': 'SetNPCTargetNPCAngle'
'body': 'SetNPCTargetNPCAngle(${1:npcid}, ${2:targetid}, ${3:&Float:rz=0.0})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCActorDistance':
'prefix': 'GetNPCActorDistance'
'body': 'GetNPCActorDistance(${1:npcid}, ${2:actorid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCVehicleDistance':
'prefix': 'GetNPCVehicleDistance'
'body': 'GetNPCVehicleDistance(${1:npcid}, ${2:vehicleid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCObjectDistance':
'prefix': 'GetNPCObjectDistance'
'body': 'GetNPCObjectDistance(${1:npcid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCToPointVector':
'prefix': 'GetNPCToPointVector'
'body': 'GetNPCToPointVector(${1:npcid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_SetVehicleRotation':
'prefix': 'FCNPC_SetVehicleRotation'
'body': 'FCNPC_SetVehicleRotation(${1:npcid}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_SetVehicleTargetRotation':
'prefix': 'FCNPC_SetVehicleTargetRotation'
'body': 'FCNPC_SetVehicleTargetRotation(${1:npcid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:Float:ry=0.0})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCRotatedVector':
'prefix': 'GetNPCRotatedVector'
'body': 'GetNPCRotatedVector(${1:npcid}, ${2:Float:tx}, ${3:Float:ty}, ${4:Float:tz}, ${5:&Float:vx}, ${6:&Float:vy}, ${7:&Float:vz}, ${8:bool:return_vector=true}, ${9:Float:rx=0.0}, ${10:Float:ry=0.0}, ${11:Float:rz=0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToAir':
'prefix': 'FCNPC_GoToAir'
'body': 'FCNPC_GoToAir(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:type = MOVE_TYPE_AUTO}, ${6:Float:speed = MOVE_SPEED_AUTO})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetPointInFrontOfNPCCol':
'prefix': 'GetPointInFrontOfNPCCol'
'body': 'GetPointInFrontOfNPCCol(${1:npcid}, ${2:&Float:tx}, ${3:&Float:ty}, ${4:Float:radius})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCCollisionFlags':
'prefix': 'GetNPCCollisionFlags'
'body': 'GetNPCCollisionFlags(${1:npcid})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenNPCsIsWall':
'prefix': 'IsBetweenNPCsIsWall'
'body': 'IsBetweenNPCsIsWall(${1:npcid}, ${2:targetid})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsBetweenNPCToPointIsWall':
'prefix': 'IsBetweenNPCToPointIsWall'
'body': 'IsBetweenNPCToPointIsWall(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCOrientationPosCol':
'prefix': 'GetNPCOrientationPosCol'
'body': 'GetNPCOrientationPosCol(${1:npcid}, ${2:element_orientation:orientation}, ${3:Float:distance}, ${4:&Float:tx}, ${5:&Float:ty}, ${6:&Float:tz})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToCol':
'prefix': 'FCNPC_GoToCol'
'body': 'FCNPC_GoToCol(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:type = MOVE_TYPE_AUTO}, ${6:Float:speed = MOVE_SPEED_AUTO}, ${7:bool:UseMapAndreas = false}, ${8:Float:cut_size = 0.0}, ${9:bool:setangle = true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToPlayerCol':
'prefix': 'FCNPC_GoToPlayerCol'
'body': 'FCNPC_GoToPlayerCol(${1:npcid}, ${2:playerid}, ${3:type = MOVE_TYPE_AUTO}, ${4:Float:speed = MOVE_SPEED_AUTO}, ${5:bool:UseMapAndreas = false}, ${6:Float:cut_size = 0.0}, ${7:bool:setangle = true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToPlayerOnGroundCol':
'prefix': 'FCNPC_GoToPlayerOnGroundCol'
'body': 'FCNPC_GoToPlayerOnGroundCol(${1:npcid}, ${2:playerid}, ${3:type = MOVE_TYPE_AUTO}, ${4:Float:speed = MOVE_SPEED_AUTO}, ${5:bool:UseMapAndreas = false}, ${6:Float:cut_size = 1.0}, ${7:Float:climbing = 2.0}, ${8:bool:setangle = true})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'FCNPC_GoToAirCol':
'prefix': 'FCNPC_GoToAirCol'
'body': 'FCNPC_GoToAirCol(${1:npcid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:type = MOVE_TYPE_AUTO}, ${6:Float:speed = MOVE_SPEED_AUTO}, ${7:Float:cut_size = 0.0})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInWaterFrontOfNPC':
'prefix': 'IsPointInWaterFrontOfNPC'
'body': 'IsPointInWaterFrontOfNPC(${1:npcid}, ${2:Float:radius})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetNPCDynamicObjectDistance':
'prefix': 'GetNPCDynamicObjectDistance'
'body': 'GetNPCDynamicObjectDistance(${1:npcid}, ${2:objectid})'
'leftLabel': 'Float'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCreate':
'prefix': 'StreamCreate'
'body': 'StreamCreate(${1:variable})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetStreamType':
'prefix': 'GetStreamType'
'body': 'GetStreamType(${1:Stream:StreamData[Stream3D]})'
'leftLabel': 'StreamType'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'ConvertAreaToStream':
'prefix': 'ConvertAreaToStream'
'body': 'ConvertAreaToStream(${1:areaid})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCircle':
'prefix': 'StreamCircle'
'body': 'StreamCircle(${1:Float:x}, ${2:Float:y}, ${3:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCylinder':
'prefix': 'StreamCylinder'
'body': 'StreamCylinder(${1:Float:xA}, ${2:Float:yA}, ${3:Float:zA}, ${4:Float:xB}, ${5:Float:yB}, ${6:Float:zB}, ${7:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCylinderEx':
'prefix': 'StreamCylinderEx'
'body': 'StreamCylinderEx(${1:Float:x}, ${2:Float:y}, ${3:Float:minz}, ${4:Float:maxz}, ${5:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamSphere':
'prefix': 'StreamSphere'
'body': 'StreamSphere(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamRectangle':
'prefix': 'StreamRectangle'
'body': 'StreamRectangle(${1:Float:minx}, ${2:Float:miny}, ${3:Float:maxx}, ${4:Float:maxy})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCube':
'prefix': 'StreamCube'
'body': 'StreamCube(${1:Float:minx}, ${2:Float:miny}, ${3:Float:minz}, ${4:Float:maxx}, ${5:Float:maxy}, ${6:Float:maxz})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamCircularSector':
'prefix': 'StreamCircularSector'
'body': 'StreamCircularSector(${1:Float:x}, ${2:Float:y}, ${3:Float:rz}, ${4:Float:radius}, ${5:Float:view_angle})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'StreamSphericalSector':
'prefix': 'StreamSphericalSector'
'body': 'StreamSphericalSector(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:rx}, ${5:Float:rz}, ${6:Float:radius}, ${7:Float:vrx}, ${8:Float:vrz})'
'leftLabel': 'Stream'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsValidStream':
'prefix': 'IsValidStream'
'body': 'IsValidStream(${1:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPointInStream':
'prefix': 'IsPointInStream'
'body': 'IsPointInStream(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsPlayerInStream':
'prefix': 'IsPlayerInStream'
'body': 'IsPlayerInStream(${1:playerid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsObjectInStream':
'prefix': 'IsObjectInStream'
'body': 'IsObjectInStream(${1:objectid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsActorInStream':
'prefix': 'IsActorInStream'
'body': 'IsActorInStream(${1:actorid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsNPCInStream':
'prefix': 'IsNPCInStream'
'body': 'IsNPCInStream(${1:npcid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicObjectInStream':
'prefix': 'IsDynamicObjectInStream'
'body': 'IsDynamicObjectInStream(${1:objectid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'IsDynamicActorInStream':
'prefix': 'IsDynamicActorInStream'
'body': 'IsDynamicActorInStream(${1:actorid}, ${2:Stream:StreamData[Stream3D]})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'Line3DCreate':
'prefix': 'Line3DCreate'
'body': 'Line3DCreate(${1:variable}, ${2:max_points})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLine3DValue':
'prefix': 'GetLine3DValue'
'body': 'GetLine3DValue(${1:variable}, ${2:pointid}, ${3:name})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetLine3DValue':
'prefix': 'SetLine3DValue'
'body': 'SetLine3DValue(${1:variable}, ${2:pointid}, ${3:name}, ${4:value})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLine3DPointPos':
'prefix': 'GetLine3DPointPos'
'body': 'GetLine3DPointPos(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetLine3DPointPos':
'prefix': 'SetLine3DPointPos'
'body': 'SetLine3DPointPos(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:Float:x}, ${4:Float:y}, ${5:Float:z}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetLine3DPointRot':
'prefix': 'GetLine3DPointRot'
'body': 'GetLine3DPointRot(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:&Float:rx}, ${4:&Float:ry}, ${5:&Float:rz}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'SetLine3DPointRot':
'prefix': 'SetLine3DPointRot'
'body': 'SetLine3DPointRot(${1:Line3D:LineData[][LinePoint3D]}, ${2:pointid}, ${3:Float:rx}, ${4:Float:ry}, ${5:Float:rz}, ${6:max_points = sizeof(LineData})'
'leftLabel': 'bool'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'CountLine3DPoints':
'prefix': 'CountLine3DPoints'
'body': 'CountLine3DPoints(${1:Line3D:LineData[][LinePoint3D]}, ${2:max_points = sizeof(LineData})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'AddPointToLine3D':
'prefix': 'AddPointToLine3D'
'body': 'AddPointToLine3D(${1:Line3D:LineData[][LinePoint3D]}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx=INVALID_ROTATION}, ${6:Float:ry=INVALID_ROTATION}, ${7:Float:rz=INVALID_ROTATION}, ${8:max_points = sizeof(LineData})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetXYZInFrontOfVehicle':
'prefix': 'GetXYZInFrontOfVehicle'
'body': 'GetXYZInFrontOfVehicle(${1:vehicleid}, ${2:Float:distance}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
'GetRandomClockPos':
'prefix': 'GetRandomClockPos'
'body': 'GetRandomClockPos(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:radius}, ${5:&Float:tx}, ${6:&Float:ty}, ${7:&Float:tz}, ${8:&Float:trz}, ${9:Float:rz = INVALID_ROTATION})'
'description': 'Function from: 3DTryg'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=591010'
|
[
{
"context": "ssification.annotations\n annotation._key ?= Math.random()\n isPriorAnnotation = annotation isnt @pr",
"end": 307,
"score": 0.9693989753723145,
"start": 296,
"tag": "KEY",
"value": "Math.random"
},
{
"context": ", m in annotation.value\n mark._key ?= Math.random()\n toolDescription = taskDescription",
"end": 676,
"score": 0.969667911529541,
"start": 665,
"tag": "KEY",
"value": "Math.random"
}
] | app/classifier/tasks/drawing/all-marks-display.cjsx | Crentist/Panoptes-frontend-spanish | 1 | React = require 'react'
module.exports = React.createClass
displayName: 'AllMarksDisplay'
getDetailsTooltipProps: ->
workflow: null
classification: null
annotation: null
render: ->
<g>
{for annotation in @props.classification.annotations
annotation._key ?= Math.random()
isPriorAnnotation = annotation isnt @props.annotation
taskDescription = @props.workflow.tasks[annotation.task]
if taskDescription.type is 'drawing'
<g key={annotation._key} className="marks-for-annotation" data-disabled={isPriorAnnotation or null}>
{for mark, m in annotation.value
mark._key ?= Math.random()
toolDescription = taskDescription.tools[mark.tool]
toolEnv =
containerRect: @state.sizeRect
scale: @getScale()
disabled: isPriorAnnotation
selected: mark is @state.selectedMark
getEventOffset: @getEventOffset
ref: 'selectedTool' if mark is @state.selectedMark
toolProps =
mark: mark
color: toolDescription.color
toolMethods =
onChange: @updateAnnotations
onSelect: @selectMark.bind this, annotation, mark
onDestroy: @destroyMark.bind this, annotation, mark
ToolComponent = drawingTools[toolDescription.type]
<ToolComponent key={mark._key} {...toolProps} {...toolEnv} {...toolMethods} />}
</g>}
</g>
| 178322 | React = require 'react'
module.exports = React.createClass
displayName: 'AllMarksDisplay'
getDetailsTooltipProps: ->
workflow: null
classification: null
annotation: null
render: ->
<g>
{for annotation in @props.classification.annotations
annotation._key ?= <KEY>()
isPriorAnnotation = annotation isnt @props.annotation
taskDescription = @props.workflow.tasks[annotation.task]
if taskDescription.type is 'drawing'
<g key={annotation._key} className="marks-for-annotation" data-disabled={isPriorAnnotation or null}>
{for mark, m in annotation.value
mark._key ?= <KEY>()
toolDescription = taskDescription.tools[mark.tool]
toolEnv =
containerRect: @state.sizeRect
scale: @getScale()
disabled: isPriorAnnotation
selected: mark is @state.selectedMark
getEventOffset: @getEventOffset
ref: 'selectedTool' if mark is @state.selectedMark
toolProps =
mark: mark
color: toolDescription.color
toolMethods =
onChange: @updateAnnotations
onSelect: @selectMark.bind this, annotation, mark
onDestroy: @destroyMark.bind this, annotation, mark
ToolComponent = drawingTools[toolDescription.type]
<ToolComponent key={mark._key} {...toolProps} {...toolEnv} {...toolMethods} />}
</g>}
</g>
| true | React = require 'react'
module.exports = React.createClass
displayName: 'AllMarksDisplay'
getDetailsTooltipProps: ->
workflow: null
classification: null
annotation: null
render: ->
<g>
{for annotation in @props.classification.annotations
annotation._key ?= PI:KEY:<KEY>END_PI()
isPriorAnnotation = annotation isnt @props.annotation
taskDescription = @props.workflow.tasks[annotation.task]
if taskDescription.type is 'drawing'
<g key={annotation._key} className="marks-for-annotation" data-disabled={isPriorAnnotation or null}>
{for mark, m in annotation.value
mark._key ?= PI:KEY:<KEY>END_PI()
toolDescription = taskDescription.tools[mark.tool]
toolEnv =
containerRect: @state.sizeRect
scale: @getScale()
disabled: isPriorAnnotation
selected: mark is @state.selectedMark
getEventOffset: @getEventOffset
ref: 'selectedTool' if mark is @state.selectedMark
toolProps =
mark: mark
color: toolDescription.color
toolMethods =
onChange: @updateAnnotations
onSelect: @selectMark.bind this, annotation, mark
onDestroy: @destroyMark.bind this, annotation, mark
ToolComponent = drawingTools[toolDescription.type]
<ToolComponent key={mark._key} {...toolProps} {...toolEnv} {...toolMethods} />}
</g>}
</g>
|
[
{
"context": "###*\n *\n * Dialog\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{Component} ",
"end": 35,
"score": 0.9995741844177246,
"start": 29,
"tag": "USERNAME",
"value": "vfasky"
},
{
"context": "###*\n *\n * Dialog\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{Component} = require 'mcore'\n",
"end": 53,
"score": 0.9999217391014099,
"start": 37,
"tag": "EMAIL",
"value": "vfasky@gmail.com"
}
] | src/coffee/dialog.coffee | vfasky/mcore-weui | 0 | ###*
*
* Dialog
* @author vfasky <vfasky@gmail.com>
###
'use strict'
{Component} = require 'mcore'
_dialog = null
class Dialog extends Component
constructor: (@el = document.body, @virtualEl = null)->
super @el, @virtualEl
init: ->
@render require('../tpl/dialog.html'),
type: 'alert'
show: false
show: (content, @callback, title = '提示信息', type = 'alert')->
@set 'title', title
@set 'type', type
@set 'content', content
@set 'show', true
this
isShow: -> @get('show')
close: (event, el, isOk)->
isOk = isOk == true and true or false
@set 'show', false, => @callback isOk
Dialog.alert = (content, callback, title)->
_dialog = new Dialog() if !_dialog
callback or= ->
return false if _dialog.isShow()
_dialog.show content, callback, title
Dialog.confirm = (content, callback, title = '请确认')->
_dialog = new Dialog() if !_dialog
callback or= ->
return false if _dialog.isShow()
_dialog.show content, callback, title, 'confirm'
module.exports = Dialog
| 33807 | ###*
*
* Dialog
* @author vfasky <<EMAIL>>
###
'use strict'
{Component} = require 'mcore'
_dialog = null
class Dialog extends Component
constructor: (@el = document.body, @virtualEl = null)->
super @el, @virtualEl
init: ->
@render require('../tpl/dialog.html'),
type: 'alert'
show: false
show: (content, @callback, title = '提示信息', type = 'alert')->
@set 'title', title
@set 'type', type
@set 'content', content
@set 'show', true
this
isShow: -> @get('show')
close: (event, el, isOk)->
isOk = isOk == true and true or false
@set 'show', false, => @callback isOk
Dialog.alert = (content, callback, title)->
_dialog = new Dialog() if !_dialog
callback or= ->
return false if _dialog.isShow()
_dialog.show content, callback, title
Dialog.confirm = (content, callback, title = '请确认')->
_dialog = new Dialog() if !_dialog
callback or= ->
return false if _dialog.isShow()
_dialog.show content, callback, title, 'confirm'
module.exports = Dialog
| true | ###*
*
* Dialog
* @author vfasky <PI:EMAIL:<EMAIL>END_PI>
###
'use strict'
{Component} = require 'mcore'
_dialog = null
class Dialog extends Component
constructor: (@el = document.body, @virtualEl = null)->
super @el, @virtualEl
init: ->
@render require('../tpl/dialog.html'),
type: 'alert'
show: false
show: (content, @callback, title = '提示信息', type = 'alert')->
@set 'title', title
@set 'type', type
@set 'content', content
@set 'show', true
this
isShow: -> @get('show')
close: (event, el, isOk)->
isOk = isOk == true and true or false
@set 'show', false, => @callback isOk
Dialog.alert = (content, callback, title)->
_dialog = new Dialog() if !_dialog
callback or= ->
return false if _dialog.isShow()
_dialog.show content, callback, title
Dialog.confirm = (content, callback, title = '请确认')->
_dialog = new Dialog() if !_dialog
callback or= ->
return false if _dialog.isShow()
_dialog.show content, callback, title, 'confirm'
module.exports = Dialog
|
[
{
"context": " \"addressRegion\"\n \"addressStreetAddress\"\n \"cardholderName\"\n \"company\"\n \"email\"\n \"fax\"\n \"firstNa",
"end": 319,
"score": 0.8745542168617249,
"start": 305,
"tag": "USERNAME",
"value": "cardholderName"
},
{
"context": "derName\"\n \"company\"\n \"email\"\n \"fax\"\n \"firstName\"\n \"id\"\n \"lastName\"\n \"paymentMethodToken\"",
"end": 371,
"score": 0.9895076751708984,
"start": 362,
"tag": "NAME",
"value": "firstName"
},
{
"context": " \"email\"\n \"fax\"\n \"firstName\"\n \"id\"\n \"lastName\"\n \"paymentMethodToken\"\n \"paypalAccountEmail",
"end": 395,
"score": 0.9962960481643677,
"start": 387,
"tag": "NAME",
"value": "lastName"
}
] | src/braintree/customer_search.coffee | StreamCo/braintree_node | 0 | {AdvancedSearch} = require('./advanced_search')
class CustomerSearch extends AdvancedSearch
@textFields(
"addressCountryName"
"addressExtendedAddress"
"addressFirstName"
"addressLastName"
"addressLocality"
"addressPostalCode"
"addressRegion"
"addressStreetAddress"
"cardholderName"
"company"
"email"
"fax"
"firstName"
"id"
"lastName"
"paymentMethodToken"
"paypalAccountEmail"
"phone"
"website"
)
@equalityFields "creditCardExpirationDate"
@partialMatchFields "creditCardNumber"
@multipleValueField "ids"
@rangeFields "createdAt"
exports.CustomerSearch = CustomerSearch
| 130728 | {AdvancedSearch} = require('./advanced_search')
class CustomerSearch extends AdvancedSearch
@textFields(
"addressCountryName"
"addressExtendedAddress"
"addressFirstName"
"addressLastName"
"addressLocality"
"addressPostalCode"
"addressRegion"
"addressStreetAddress"
"cardholderName"
"company"
"email"
"fax"
"<NAME>"
"id"
"<NAME>"
"paymentMethodToken"
"paypalAccountEmail"
"phone"
"website"
)
@equalityFields "creditCardExpirationDate"
@partialMatchFields "creditCardNumber"
@multipleValueField "ids"
@rangeFields "createdAt"
exports.CustomerSearch = CustomerSearch
| true | {AdvancedSearch} = require('./advanced_search')
class CustomerSearch extends AdvancedSearch
@textFields(
"addressCountryName"
"addressExtendedAddress"
"addressFirstName"
"addressLastName"
"addressLocality"
"addressPostalCode"
"addressRegion"
"addressStreetAddress"
"cardholderName"
"company"
"email"
"fax"
"PI:NAME:<NAME>END_PI"
"id"
"PI:NAME:<NAME>END_PI"
"paymentMethodToken"
"paypalAccountEmail"
"phone"
"website"
)
@equalityFields "creditCardExpirationDate"
@partialMatchFields "creditCardNumber"
@multipleValueField "ids"
@rangeFields "createdAt"
exports.CustomerSearch = CustomerSearch
|
[
{
"context": " type: 'primitive'\n name: name\n # doc: @commentLines[@lineM",
"end": 8242,
"score": 0.8250947594642639,
"start": 8238,
"tag": "NAME",
"value": "name"
},
{
"context": "\n ret =\n type: 'import'\n # doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]\n range: ",
"end": 11336,
"score": 0.7574100494384766,
"start": 11310,
"tag": "USERNAME",
"value": "@commentLines[@lineMapping"
},
{
"context": " ret\n\n else\n type: 'function'\n # doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]\n range: [ ",
"end": 11853,
"score": 0.8315317630767822,
"start": 11827,
"tag": "USERNAME",
"value": "@commentLines[@lineMapping"
}
] | src/metadata.coffee | abe33/biscotto | 2 | fs = require 'fs'
path = require 'path'
_ = require 'underscore'
builtins = require 'builtins'
module.exports = class Metadata
constructor: (@dependencies, @parser) ->
generate: (@root) ->
@defs = {} # Local variable definitions
@exports = {}
@bindingTypes = {}
@modules = {}
@classes = @parser.classes
@files = @parser.files
@root.traverseChildren no, (exp) => @visit(exp) # `no` means Stop at scope boundaries
visit: (exp) ->
@["visit#{exp.constructor.name}"](exp)
eval: (exp) ->
@["eval#{exp.constructor.name}"](exp)
visitComment: (exp) ->
# Skip the 1st comment which is added by biscotto
return if exp.comment is '~Private~'
visitClass: (exp) ->
return unless exp.variable?
@defs[exp.variable.base.value] = @evalClass(exp)
no # Do not traverse into the class methods
visitAssign: (exp) ->
variable = @eval(exp.variable)
value = @eval(exp.value)
baseName = exp.variable.base.value
switch baseName
when 'module'
return if exp.variable.properties.length is 0 # Ignore `module = ...` (atom/src/browser/main.coffee)
unless exp.variable.properties?[0]?.name?.value is 'exports'
throw new Error 'BUG: Does not support module.somthingOtherThanExports'
baseName = 'exports'
firstProp = exp.variable.properties[1]
when 'exports'
firstProp = exp.variable.properties[0]
switch baseName
when 'exports'
# Handle 3 cases:
#
# - `exports.foo = SomeClass`
# - `exports.foo = 42`
# - `exports = bar`
if firstProp
if value.base? && @defs[value.base.value]
# case `exports.foo = SomeClass`
@exports[firstProp.name.value] = @defs[value.base.value]
else
# case `exports.foo = 42`
unless firstProp.name.value == value.name
@defs[firstProp.name.value] =
name: firstProp.name.value
bindingType: 'exportsProperty'
type: value.type
range: [ [exp.variable.base.locationData.first_line, exp.variable.base.locationData.first_column], [exp.variable.base.locationData.last_line, exp.variable.base.locationData.last_column ] ]
@exports[firstProp.name.value] =
startLineNumber: exp.variable.base.locationData.first_line
else
# case `exports = bar`
@exports = {_default: value}
switch value.type
when 'class'
@bindingTypes[value.name] = "exports"
# case left-hand-side is anything other than `exports...`
else
# Handle 4 common cases:
#
# X = ...
# {X} = ...
# {X:Y} = ...
# X.y = ...
switch exp.variable.base.constructor.name
when 'Literal'
# Something we dont care about is on the right side of the `=`.
# This could be some garbage like an if statement.
return unless value.range
# case _.str = ...
if exp.variable.properties.length > 0
nameWithPeriods = [exp.variable.base.value].concat(_.map(exp.variable.properties, (prop) -> prop.name.value)).join(".")
@defs[nameWithPeriods] = _.extend name: nameWithPeriods, value
else # case X = ...
@defs[exp.variable.base.value] = _.extend name: exp.variable.base.value, value
# satisfies the case of npm module requires (like Grim in our tests)
if @defs[exp.variable.base.value].type == "import"
key = @defs[exp.variable.base.value].path || @defs[exp.variable.base.value].module
if _.isUndefined @modules[key]
@modules[key] = []
@modules[key].push { name: @defs[exp.variable.base.value].name, range: @defs[exp.variable.base.value].range }
switch @defs[exp.variable.base.value].type
when 'function'
doc = null
# fetch method from file
_.each @files, (file) =>
file.methods = _.filter file.methods, (method) =>
if @defs[exp.variable.base.value].name == method.name
doc = method.doc
return true
return false
@defs[exp.variable.base.value].doc = doc
when 'Obj'
for key in exp.variable.base.objects
switch key.constructor.name
when 'Value'
# case {X} = ...
@defs[key.base.value] = _.extend {}, value,
name: key.base.value
exportsProperty: key.base.value
range: [ [key.base.locationData.first_line, key.base.locationData.first_column], [key.base.locationData.last_line, key.base.locationData.last_column ] ]
# Store the name of the exported property to the module name
if @defs[key.base.value].type == "import" # I *think* this will always be true
if _.isUndefined @modules[@defs[key.base.value].path]
@modules[@defs[key.base.value].path] = []
@modules[@defs[key.base.value].path].push {name: @defs[key.base.value].name, range: @defs[key.base.value].range}
when 'Assign'
# case {X:Y} = ...
@defs[key.value.base.value] = _.extend {}, value,
name: key.value.base.value
exportsProperty: key.variable.base.value
return no # Do not continue visiting X
else throw new Error "BUG: Unsupported require Obj structure: #{key.constructor.name}"
else throw new Error "BUG: Unsupported require structure: #{variable.base.constructor.name}"
visitCode: (exp) ->
visitValue: (exp) ->
visitCall: (exp) ->
visitLiteral: (exp) ->
visitObj: (exp) ->
visitAccess: (exp) ->
visitBlock: (exp) ->
evalComment: (exp) ->
type: 'comment'
doc: exp.comment
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
evalClass: (exp) ->
className = exp.variable.base.value
classProperties = []
prototypeProperties = []
classNode = _.find(@classes, (clazz) -> clazz.getFullName() == className)
for subExp in exp.body.expressions
switch subExp.constructor.name
# case Prototype-level methods (this.foo = (foo) -> ...)
when 'Assign'
value = @eval(subExp.value)
@defs["#{className}.#{value.name}"] = value
classProperties.push(value)
when 'Value'
# case Prototype-level properties (@foo: "foo")
for prototypeExp in subExp.base.properties
switch prototypeExp.constructor.name
when 'Comment'
value = @eval(prototypeExp)
@defs["#{value.range[0][0]}_line_comment"] = value
else
isClassLevel = prototypeExp.variable.this
if isClassLevel
name = prototypeExp.variable.properties[0].name.value
else
name = prototypeExp.variable.base.value
value = @eval(prototypeExp.value)
if value.constructor?.name is 'Value'
lookedUpVar = @defs[value.base.value]
if lookedUpVar
if lookedUpVar.type is 'import'
value =
name: name
# doc: @commentLines[@lineMapping[value.locationData.first_line] - 1]
range: [ [value.locationData.first_line, value.locationData.first_column], [value.locationData.last_line, value.locationData.last_column ] ]
reference: lookedUpVar
else
value = _.extend name: name, lookedUpVar
else
# Assigning a simple var
value =
type: 'primitive'
name: name
# doc: @commentLines[@lineMapping[value.locationData.first_line] - 1]
range: [ [value.locationData.first_line, value.locationData.first_column], [value.locationData.last_line, value.locationData.last_column ] ]
else
value = _.extend name: name, value
# TODO: `value = @eval(prototypeExp.value)` is messing this up
# interferes also with evalValue
if isClassLevel
value.name = name
value.bindingType = "classProperty"
@defs["#{className}.#{name}"] = value
classProperties.push(value)
if reference = @applyReference(prototypeExp)
@defs["#{className}.#{name}"].reference =
position: reference.range[0]
else
value.name = name
value.bindingType = "prototypeProperty"
@defs["#{className}::#{name}"] = value
prototypeProperties.push(value)
if reference = @applyReference(prototypeExp)
@defs["#{className}::#{name}"].reference =
position: reference.range[0]
# apply the reference (if one exists)
if value.type == "function"
# find the matching method from the parsed files
func = _.find classNode?.getMethods(), (method) -> method.name == value.name
value.doc = func?.doc.comment
true
type: 'class'
name: className
bindingType: @bindingTypes[className] unless _.isUndefined @bindingTypes[className]
classProperties: classProperties
prototypeProperties: prototypeProperties
doc: classNode?.doc.comment
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
evalCode: (exp) ->
bindingType: 'variable'
type: 'function'
paramNames: _.map exp.params, (param) -> param.name.value
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
doc: null
evalValue: (exp) ->
if exp.base
type: 'primitive'
name: exp.base?.value
# doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
else
throw new Error 'BUG? Not sure how to evaluate this value if it does not have .base'
evalCall: (exp) ->
# The only interesting call is `require('foo')`
if exp.variable.base.value is 'require'
moduleName = exp.args[0].base.value
moduleName = moduleName.substring(1, moduleName.length - 1)
# For npm modules include the version number
ver = @dependencies[moduleName]
moduleName = "#{moduleName}@#{ver}" if ver
ret =
type: 'import'
# doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
bindingType: 'variable'
if /^\./.test(moduleName)
# Local module
ret.path = moduleName
else
ret.module = moduleName
# Tag builtin NodeJS modules
ret.builtin = true if builtins.indexOf(moduleName) >= 0
ret
else
type: 'function'
# doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
evalError: (str, exp) ->
throw new Error "BUG: Not implemented yet: #{str}. Line #{exp.locationData.first_line}"
evalAssign: (exp) -> @eval(exp.value) # Support x = y = z
evalLiteral: (exp) -> @evalError 'evalLiteral', exp
evalObj: (exp) -> @evalError 'evalObj', exp
evalAccess: (exp) -> @evalError 'evalAccess', exp
evalUnknown: (exp) -> exp
evalIf: -> @evalUnknown(arguments)
visitIf: ->
visitOp: ->
visitArr: ->
visitNull: ->
visitBool: ->
visitIndex: ->
visitParens: ->
evalOp: (exp) -> exp
applyReference: (prototypeExp) ->
for module, references of @modules
for reference in references
# non-npm module case (local file ref)
if prototypeExp.value.base?.value
ref = prototypeExp.value.base.value
else
ref = prototypeExp.value.base
if reference.name == ref
return reference
| 75989 | fs = require 'fs'
path = require 'path'
_ = require 'underscore'
builtins = require 'builtins'
module.exports = class Metadata
constructor: (@dependencies, @parser) ->
generate: (@root) ->
@defs = {} # Local variable definitions
@exports = {}
@bindingTypes = {}
@modules = {}
@classes = @parser.classes
@files = @parser.files
@root.traverseChildren no, (exp) => @visit(exp) # `no` means Stop at scope boundaries
visit: (exp) ->
@["visit#{exp.constructor.name}"](exp)
eval: (exp) ->
@["eval#{exp.constructor.name}"](exp)
visitComment: (exp) ->
# Skip the 1st comment which is added by biscotto
return if exp.comment is '~Private~'
visitClass: (exp) ->
return unless exp.variable?
@defs[exp.variable.base.value] = @evalClass(exp)
no # Do not traverse into the class methods
visitAssign: (exp) ->
variable = @eval(exp.variable)
value = @eval(exp.value)
baseName = exp.variable.base.value
switch baseName
when 'module'
return if exp.variable.properties.length is 0 # Ignore `module = ...` (atom/src/browser/main.coffee)
unless exp.variable.properties?[0]?.name?.value is 'exports'
throw new Error 'BUG: Does not support module.somthingOtherThanExports'
baseName = 'exports'
firstProp = exp.variable.properties[1]
when 'exports'
firstProp = exp.variable.properties[0]
switch baseName
when 'exports'
# Handle 3 cases:
#
# - `exports.foo = SomeClass`
# - `exports.foo = 42`
# - `exports = bar`
if firstProp
if value.base? && @defs[value.base.value]
# case `exports.foo = SomeClass`
@exports[firstProp.name.value] = @defs[value.base.value]
else
# case `exports.foo = 42`
unless firstProp.name.value == value.name
@defs[firstProp.name.value] =
name: firstProp.name.value
bindingType: 'exportsProperty'
type: value.type
range: [ [exp.variable.base.locationData.first_line, exp.variable.base.locationData.first_column], [exp.variable.base.locationData.last_line, exp.variable.base.locationData.last_column ] ]
@exports[firstProp.name.value] =
startLineNumber: exp.variable.base.locationData.first_line
else
# case `exports = bar`
@exports = {_default: value}
switch value.type
when 'class'
@bindingTypes[value.name] = "exports"
# case left-hand-side is anything other than `exports...`
else
# Handle 4 common cases:
#
# X = ...
# {X} = ...
# {X:Y} = ...
# X.y = ...
switch exp.variable.base.constructor.name
when 'Literal'
# Something we dont care about is on the right side of the `=`.
# This could be some garbage like an if statement.
return unless value.range
# case _.str = ...
if exp.variable.properties.length > 0
nameWithPeriods = [exp.variable.base.value].concat(_.map(exp.variable.properties, (prop) -> prop.name.value)).join(".")
@defs[nameWithPeriods] = _.extend name: nameWithPeriods, value
else # case X = ...
@defs[exp.variable.base.value] = _.extend name: exp.variable.base.value, value
# satisfies the case of npm module requires (like Grim in our tests)
if @defs[exp.variable.base.value].type == "import"
key = @defs[exp.variable.base.value].path || @defs[exp.variable.base.value].module
if _.isUndefined @modules[key]
@modules[key] = []
@modules[key].push { name: @defs[exp.variable.base.value].name, range: @defs[exp.variable.base.value].range }
switch @defs[exp.variable.base.value].type
when 'function'
doc = null
# fetch method from file
_.each @files, (file) =>
file.methods = _.filter file.methods, (method) =>
if @defs[exp.variable.base.value].name == method.name
doc = method.doc
return true
return false
@defs[exp.variable.base.value].doc = doc
when 'Obj'
for key in exp.variable.base.objects
switch key.constructor.name
when 'Value'
# case {X} = ...
@defs[key.base.value] = _.extend {}, value,
name: key.base.value
exportsProperty: key.base.value
range: [ [key.base.locationData.first_line, key.base.locationData.first_column], [key.base.locationData.last_line, key.base.locationData.last_column ] ]
# Store the name of the exported property to the module name
if @defs[key.base.value].type == "import" # I *think* this will always be true
if _.isUndefined @modules[@defs[key.base.value].path]
@modules[@defs[key.base.value].path] = []
@modules[@defs[key.base.value].path].push {name: @defs[key.base.value].name, range: @defs[key.base.value].range}
when 'Assign'
# case {X:Y} = ...
@defs[key.value.base.value] = _.extend {}, value,
name: key.value.base.value
exportsProperty: key.variable.base.value
return no # Do not continue visiting X
else throw new Error "BUG: Unsupported require Obj structure: #{key.constructor.name}"
else throw new Error "BUG: Unsupported require structure: #{variable.base.constructor.name}"
visitCode: (exp) ->
visitValue: (exp) ->
visitCall: (exp) ->
visitLiteral: (exp) ->
visitObj: (exp) ->
visitAccess: (exp) ->
visitBlock: (exp) ->
evalComment: (exp) ->
type: 'comment'
doc: exp.comment
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
evalClass: (exp) ->
className = exp.variable.base.value
classProperties = []
prototypeProperties = []
classNode = _.find(@classes, (clazz) -> clazz.getFullName() == className)
for subExp in exp.body.expressions
switch subExp.constructor.name
# case Prototype-level methods (this.foo = (foo) -> ...)
when 'Assign'
value = @eval(subExp.value)
@defs["#{className}.#{value.name}"] = value
classProperties.push(value)
when 'Value'
# case Prototype-level properties (@foo: "foo")
for prototypeExp in subExp.base.properties
switch prototypeExp.constructor.name
when 'Comment'
value = @eval(prototypeExp)
@defs["#{value.range[0][0]}_line_comment"] = value
else
isClassLevel = prototypeExp.variable.this
if isClassLevel
name = prototypeExp.variable.properties[0].name.value
else
name = prototypeExp.variable.base.value
value = @eval(prototypeExp.value)
if value.constructor?.name is 'Value'
lookedUpVar = @defs[value.base.value]
if lookedUpVar
if lookedUpVar.type is 'import'
value =
name: name
# doc: @commentLines[@lineMapping[value.locationData.first_line] - 1]
range: [ [value.locationData.first_line, value.locationData.first_column], [value.locationData.last_line, value.locationData.last_column ] ]
reference: lookedUpVar
else
value = _.extend name: name, lookedUpVar
else
# Assigning a simple var
value =
type: 'primitive'
name: <NAME>
# doc: @commentLines[@lineMapping[value.locationData.first_line] - 1]
range: [ [value.locationData.first_line, value.locationData.first_column], [value.locationData.last_line, value.locationData.last_column ] ]
else
value = _.extend name: name, value
# TODO: `value = @eval(prototypeExp.value)` is messing this up
# interferes also with evalValue
if isClassLevel
value.name = name
value.bindingType = "classProperty"
@defs["#{className}.#{name}"] = value
classProperties.push(value)
if reference = @applyReference(prototypeExp)
@defs["#{className}.#{name}"].reference =
position: reference.range[0]
else
value.name = name
value.bindingType = "prototypeProperty"
@defs["#{className}::#{name}"] = value
prototypeProperties.push(value)
if reference = @applyReference(prototypeExp)
@defs["#{className}::#{name}"].reference =
position: reference.range[0]
# apply the reference (if one exists)
if value.type == "function"
# find the matching method from the parsed files
func = _.find classNode?.getMethods(), (method) -> method.name == value.name
value.doc = func?.doc.comment
true
type: 'class'
name: className
bindingType: @bindingTypes[className] unless _.isUndefined @bindingTypes[className]
classProperties: classProperties
prototypeProperties: prototypeProperties
doc: classNode?.doc.comment
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
evalCode: (exp) ->
bindingType: 'variable'
type: 'function'
paramNames: _.map exp.params, (param) -> param.name.value
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
doc: null
evalValue: (exp) ->
if exp.base
type: 'primitive'
name: exp.base?.value
# doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
else
throw new Error 'BUG? Not sure how to evaluate this value if it does not have .base'
evalCall: (exp) ->
# The only interesting call is `require('foo')`
if exp.variable.base.value is 'require'
moduleName = exp.args[0].base.value
moduleName = moduleName.substring(1, moduleName.length - 1)
# For npm modules include the version number
ver = @dependencies[moduleName]
moduleName = "#{moduleName}@#{ver}" if ver
ret =
type: 'import'
# doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
bindingType: 'variable'
if /^\./.test(moduleName)
# Local module
ret.path = moduleName
else
ret.module = moduleName
# Tag builtin NodeJS modules
ret.builtin = true if builtins.indexOf(moduleName) >= 0
ret
else
type: 'function'
# doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
evalError: (str, exp) ->
throw new Error "BUG: Not implemented yet: #{str}. Line #{exp.locationData.first_line}"
evalAssign: (exp) -> @eval(exp.value) # Support x = y = z
evalLiteral: (exp) -> @evalError 'evalLiteral', exp
evalObj: (exp) -> @evalError 'evalObj', exp
evalAccess: (exp) -> @evalError 'evalAccess', exp
evalUnknown: (exp) -> exp
evalIf: -> @evalUnknown(arguments)
visitIf: ->
visitOp: ->
visitArr: ->
visitNull: ->
visitBool: ->
visitIndex: ->
visitParens: ->
evalOp: (exp) -> exp
applyReference: (prototypeExp) ->
for module, references of @modules
for reference in references
# non-npm module case (local file ref)
if prototypeExp.value.base?.value
ref = prototypeExp.value.base.value
else
ref = prototypeExp.value.base
if reference.name == ref
return reference
| true | fs = require 'fs'
path = require 'path'
_ = require 'underscore'
builtins = require 'builtins'
module.exports = class Metadata
constructor: (@dependencies, @parser) ->
generate: (@root) ->
@defs = {} # Local variable definitions
@exports = {}
@bindingTypes = {}
@modules = {}
@classes = @parser.classes
@files = @parser.files
@root.traverseChildren no, (exp) => @visit(exp) # `no` means Stop at scope boundaries
visit: (exp) ->
@["visit#{exp.constructor.name}"](exp)
eval: (exp) ->
@["eval#{exp.constructor.name}"](exp)
visitComment: (exp) ->
# Skip the 1st comment which is added by biscotto
return if exp.comment is '~Private~'
visitClass: (exp) ->
return unless exp.variable?
@defs[exp.variable.base.value] = @evalClass(exp)
no # Do not traverse into the class methods
visitAssign: (exp) ->
variable = @eval(exp.variable)
value = @eval(exp.value)
baseName = exp.variable.base.value
switch baseName
when 'module'
return if exp.variable.properties.length is 0 # Ignore `module = ...` (atom/src/browser/main.coffee)
unless exp.variable.properties?[0]?.name?.value is 'exports'
throw new Error 'BUG: Does not support module.somthingOtherThanExports'
baseName = 'exports'
firstProp = exp.variable.properties[1]
when 'exports'
firstProp = exp.variable.properties[0]
switch baseName
when 'exports'
# Handle 3 cases:
#
# - `exports.foo = SomeClass`
# - `exports.foo = 42`
# - `exports = bar`
if firstProp
if value.base? && @defs[value.base.value]
# case `exports.foo = SomeClass`
@exports[firstProp.name.value] = @defs[value.base.value]
else
# case `exports.foo = 42`
unless firstProp.name.value == value.name
@defs[firstProp.name.value] =
name: firstProp.name.value
bindingType: 'exportsProperty'
type: value.type
range: [ [exp.variable.base.locationData.first_line, exp.variable.base.locationData.first_column], [exp.variable.base.locationData.last_line, exp.variable.base.locationData.last_column ] ]
@exports[firstProp.name.value] =
startLineNumber: exp.variable.base.locationData.first_line
else
# case `exports = bar`
@exports = {_default: value}
switch value.type
when 'class'
@bindingTypes[value.name] = "exports"
# case left-hand-side is anything other than `exports...`
else
# Handle 4 common cases:
#
# X = ...
# {X} = ...
# {X:Y} = ...
# X.y = ...
switch exp.variable.base.constructor.name
when 'Literal'
# Something we dont care about is on the right side of the `=`.
# This could be some garbage like an if statement.
return unless value.range
# case _.str = ...
if exp.variable.properties.length > 0
nameWithPeriods = [exp.variable.base.value].concat(_.map(exp.variable.properties, (prop) -> prop.name.value)).join(".")
@defs[nameWithPeriods] = _.extend name: nameWithPeriods, value
else # case X = ...
@defs[exp.variable.base.value] = _.extend name: exp.variable.base.value, value
# satisfies the case of npm module requires (like Grim in our tests)
if @defs[exp.variable.base.value].type == "import"
key = @defs[exp.variable.base.value].path || @defs[exp.variable.base.value].module
if _.isUndefined @modules[key]
@modules[key] = []
@modules[key].push { name: @defs[exp.variable.base.value].name, range: @defs[exp.variable.base.value].range }
switch @defs[exp.variable.base.value].type
when 'function'
doc = null
# fetch method from file
_.each @files, (file) =>
file.methods = _.filter file.methods, (method) =>
if @defs[exp.variable.base.value].name == method.name
doc = method.doc
return true
return false
@defs[exp.variable.base.value].doc = doc
when 'Obj'
for key in exp.variable.base.objects
switch key.constructor.name
when 'Value'
# case {X} = ...
@defs[key.base.value] = _.extend {}, value,
name: key.base.value
exportsProperty: key.base.value
range: [ [key.base.locationData.first_line, key.base.locationData.first_column], [key.base.locationData.last_line, key.base.locationData.last_column ] ]
# Store the name of the exported property to the module name
if @defs[key.base.value].type == "import" # I *think* this will always be true
if _.isUndefined @modules[@defs[key.base.value].path]
@modules[@defs[key.base.value].path] = []
@modules[@defs[key.base.value].path].push {name: @defs[key.base.value].name, range: @defs[key.base.value].range}
when 'Assign'
# case {X:Y} = ...
@defs[key.value.base.value] = _.extend {}, value,
name: key.value.base.value
exportsProperty: key.variable.base.value
return no # Do not continue visiting X
else throw new Error "BUG: Unsupported require Obj structure: #{key.constructor.name}"
else throw new Error "BUG: Unsupported require structure: #{variable.base.constructor.name}"
visitCode: (exp) ->
visitValue: (exp) ->
visitCall: (exp) ->
visitLiteral: (exp) ->
visitObj: (exp) ->
visitAccess: (exp) ->
visitBlock: (exp) ->
evalComment: (exp) ->
type: 'comment'
doc: exp.comment
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
evalClass: (exp) ->
className = exp.variable.base.value
classProperties = []
prototypeProperties = []
classNode = _.find(@classes, (clazz) -> clazz.getFullName() == className)
for subExp in exp.body.expressions
switch subExp.constructor.name
# case Prototype-level methods (this.foo = (foo) -> ...)
when 'Assign'
value = @eval(subExp.value)
@defs["#{className}.#{value.name}"] = value
classProperties.push(value)
when 'Value'
# case Prototype-level properties (@foo: "foo")
for prototypeExp in subExp.base.properties
switch prototypeExp.constructor.name
when 'Comment'
value = @eval(prototypeExp)
@defs["#{value.range[0][0]}_line_comment"] = value
else
isClassLevel = prototypeExp.variable.this
if isClassLevel
name = prototypeExp.variable.properties[0].name.value
else
name = prototypeExp.variable.base.value
value = @eval(prototypeExp.value)
if value.constructor?.name is 'Value'
lookedUpVar = @defs[value.base.value]
if lookedUpVar
if lookedUpVar.type is 'import'
value =
name: name
# doc: @commentLines[@lineMapping[value.locationData.first_line] - 1]
range: [ [value.locationData.first_line, value.locationData.first_column], [value.locationData.last_line, value.locationData.last_column ] ]
reference: lookedUpVar
else
value = _.extend name: name, lookedUpVar
else
# Assigning a simple var
value =
type: 'primitive'
name: PI:NAME:<NAME>END_PI
# doc: @commentLines[@lineMapping[value.locationData.first_line] - 1]
range: [ [value.locationData.first_line, value.locationData.first_column], [value.locationData.last_line, value.locationData.last_column ] ]
else
value = _.extend name: name, value
# TODO: `value = @eval(prototypeExp.value)` is messing this up
# interferes also with evalValue
if isClassLevel
value.name = name
value.bindingType = "classProperty"
@defs["#{className}.#{name}"] = value
classProperties.push(value)
if reference = @applyReference(prototypeExp)
@defs["#{className}.#{name}"].reference =
position: reference.range[0]
else
value.name = name
value.bindingType = "prototypeProperty"
@defs["#{className}::#{name}"] = value
prototypeProperties.push(value)
if reference = @applyReference(prototypeExp)
@defs["#{className}::#{name}"].reference =
position: reference.range[0]
# apply the reference (if one exists)
if value.type == "function"
# find the matching method from the parsed files
func = _.find classNode?.getMethods(), (method) -> method.name == value.name
value.doc = func?.doc.comment
true
type: 'class'
name: className
bindingType: @bindingTypes[className] unless _.isUndefined @bindingTypes[className]
classProperties: classProperties
prototypeProperties: prototypeProperties
doc: classNode?.doc.comment
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
evalCode: (exp) ->
bindingType: 'variable'
type: 'function'
paramNames: _.map exp.params, (param) -> param.name.value
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
doc: null
evalValue: (exp) ->
if exp.base
type: 'primitive'
name: exp.base?.value
# doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
else
throw new Error 'BUG? Not sure how to evaluate this value if it does not have .base'
evalCall: (exp) ->
# The only interesting call is `require('foo')`
if exp.variable.base.value is 'require'
moduleName = exp.args[0].base.value
moduleName = moduleName.substring(1, moduleName.length - 1)
# For npm modules include the version number
ver = @dependencies[moduleName]
moduleName = "#{moduleName}@#{ver}" if ver
ret =
type: 'import'
# doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
bindingType: 'variable'
if /^\./.test(moduleName)
# Local module
ret.path = moduleName
else
ret.module = moduleName
# Tag builtin NodeJS modules
ret.builtin = true if builtins.indexOf(moduleName) >= 0
ret
else
type: 'function'
# doc: @commentLines[@lineMapping[exp.locationData.first_line] - 1]
range: [ [exp.locationData.first_line, exp.locationData.first_column], [exp.locationData.last_line, exp.locationData.last_column ] ]
evalError: (str, exp) ->
throw new Error "BUG: Not implemented yet: #{str}. Line #{exp.locationData.first_line}"
evalAssign: (exp) -> @eval(exp.value) # Support x = y = z
evalLiteral: (exp) -> @evalError 'evalLiteral', exp
evalObj: (exp) -> @evalError 'evalObj', exp
evalAccess: (exp) -> @evalError 'evalAccess', exp
evalUnknown: (exp) -> exp
evalIf: -> @evalUnknown(arguments)
visitIf: ->
visitOp: ->
visitArr: ->
visitNull: ->
visitBool: ->
visitIndex: ->
visitParens: ->
evalOp: (exp) -> exp
applyReference: (prototypeExp) ->
for module, references of @modules
for reference in references
# non-npm module case (local file ref)
if prototypeExp.value.base?.value
ref = prototypeExp.value.base.value
else
ref = prototypeExp.value.base
if reference.name == ref
return reference
|
[
{
"context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ",
"end": 194,
"score": 0.9999222159385681,
"start": 178,
"tag": "EMAIL",
"value": "info@chaibio.com"
}
] | frontend/javascripts/app/controllers/user_settings_ctrl.js.coffee | MakerButt/chaipcr | 1 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>
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.
###
window.ChaiBioTech.ngApp
.controller 'UserSettingsCtrl', [
'$scope'
'$window'
'$uibModal'
'User'
($scope, $window, $uibModal, User) ->
angular.element('body').addClass 'modal-form'
$scope.$on '$destroy', ->
angular.element('body').removeClass 'modal-form'
$scope.settings =
option: 'A'
checkbox: true
$scope.goHome = ->
$window.location = '#home'
fetchUsers = ->
User.fetch().then (users) ->
$scope.users = users
$scope.currentUser = User.currentUser()
User.getCurrent().then (data) ->
$scope.loggedInUser = data.data.user
console.log $scope.loggedInUser
$scope.user = {}
fetchUsers()
$scope.changeUser = (index)->
$scope.selectedUser = $scope.users[index].user;
User.selectedUSer = $scope.users[index].user;
console.log "clciked", $scope.selectedUser
$scope.addUser = ->
user = angular.copy $scope.user
user.role = if $scope.user.role then 'admin' else 'default'
User.save(user)
.then ->
$scope.user = {}
fetchUsers()
$scope.modal.close()
.catch (data) ->
data.user.role = if data.user.role is 'default' then false else true
$scope.user.errors = data.user.errors
$scope.removeUser = (id) ->
if $window.confirm 'Are you sure?'
User.remove(id).then fetchUsers
$scope.openAddUserModal = ->
$scope.modal = $uibModal.open
scope: $scope
templateUrl: 'app/views/user/modal-add-user.html'
]
| 17923 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>>
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.
###
window.ChaiBioTech.ngApp
.controller 'UserSettingsCtrl', [
'$scope'
'$window'
'$uibModal'
'User'
($scope, $window, $uibModal, User) ->
angular.element('body').addClass 'modal-form'
$scope.$on '$destroy', ->
angular.element('body').removeClass 'modal-form'
$scope.settings =
option: 'A'
checkbox: true
$scope.goHome = ->
$window.location = '#home'
fetchUsers = ->
User.fetch().then (users) ->
$scope.users = users
$scope.currentUser = User.currentUser()
User.getCurrent().then (data) ->
$scope.loggedInUser = data.data.user
console.log $scope.loggedInUser
$scope.user = {}
fetchUsers()
$scope.changeUser = (index)->
$scope.selectedUser = $scope.users[index].user;
User.selectedUSer = $scope.users[index].user;
console.log "clciked", $scope.selectedUser
$scope.addUser = ->
user = angular.copy $scope.user
user.role = if $scope.user.role then 'admin' else 'default'
User.save(user)
.then ->
$scope.user = {}
fetchUsers()
$scope.modal.close()
.catch (data) ->
data.user.role = if data.user.role is 'default' then false else true
$scope.user.errors = data.user.errors
$scope.removeUser = (id) ->
if $window.confirm 'Are you sure?'
User.remove(id).then fetchUsers
$scope.openAddUserModal = ->
$scope.modal = $uibModal.open
scope: $scope
templateUrl: 'app/views/user/modal-add-user.html'
]
| true | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>END_PI>
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.
###
window.ChaiBioTech.ngApp
.controller 'UserSettingsCtrl', [
'$scope'
'$window'
'$uibModal'
'User'
($scope, $window, $uibModal, User) ->
angular.element('body').addClass 'modal-form'
$scope.$on '$destroy', ->
angular.element('body').removeClass 'modal-form'
$scope.settings =
option: 'A'
checkbox: true
$scope.goHome = ->
$window.location = '#home'
fetchUsers = ->
User.fetch().then (users) ->
$scope.users = users
$scope.currentUser = User.currentUser()
User.getCurrent().then (data) ->
$scope.loggedInUser = data.data.user
console.log $scope.loggedInUser
$scope.user = {}
fetchUsers()
$scope.changeUser = (index)->
$scope.selectedUser = $scope.users[index].user;
User.selectedUSer = $scope.users[index].user;
console.log "clciked", $scope.selectedUser
$scope.addUser = ->
user = angular.copy $scope.user
user.role = if $scope.user.role then 'admin' else 'default'
User.save(user)
.then ->
$scope.user = {}
fetchUsers()
$scope.modal.close()
.catch (data) ->
data.user.role = if data.user.role is 'default' then false else true
$scope.user.errors = data.user.errors
$scope.removeUser = (id) ->
if $window.confirm 'Are you sure?'
User.remove(id).then fetchUsers
$scope.openAddUserModal = ->
$scope.modal = $uibModal.open
scope: $scope
templateUrl: 'app/views/user/modal-add-user.html'
]
|
[
{
"context": "ode used by Kaylee.\n#\n# :copyright: (c) 2012 by Zaur Nasibov.\n# :license: MIT, see LICENSE for more details",
"end": 200,
"score": 0.9998767375946045,
"start": 188,
"tag": "NAME",
"value": "Zaur Nasibov"
}
] | kaylee/client/klutil.coffee | BasicWolf/archived-kaylee | 2 | ###
# klutil.coffee
# ~~~~~~~~~~~~~
#
# This file is a part of Kaylee client-side module.
# It contains the util and shared code used by Kaylee.
#
# :copyright: (c) 2012 by Zaur Nasibov.
# :license: MIT, see LICENSE for more details.
###
kl.util = util = {}
util.is_function = (obj) ->
return typeof(obj) == 'function'
util.ends_with = (str, suffix) ->
return str.indexOf(suffix, str.length - suffix.length) != -1
kl.Event = class Event
constructor : (handler = null) ->
@handlers = []
@handlers.push(handler) if handler?
return
trigger : (args...) =>
for c in @handlers
c(args...)
return
bind : (handler) =>
@handlers.push(handler)
return
unbind : (handler) =>
@handlers[t..t] = [] if (t = @handlers.indexOf(handler)) > -1
return
# currently (01.12.2012) a hack, hopefully will be fixed in newer
# versions of CoffeeScript
kl.KayleeError = class KayleeError extends Error then constructor: -> super
util.after = (timeout, f) ->
setTimeout(f, timeout)
util.every = (period, f) ->
setInterval(f, period) | 88146 | ###
# klutil.coffee
# ~~~~~~~~~~~~~
#
# This file is a part of Kaylee client-side module.
# It contains the util and shared code used by Kaylee.
#
# :copyright: (c) 2012 by <NAME>.
# :license: MIT, see LICENSE for more details.
###
kl.util = util = {}
util.is_function = (obj) ->
return typeof(obj) == 'function'
util.ends_with = (str, suffix) ->
return str.indexOf(suffix, str.length - suffix.length) != -1
kl.Event = class Event
constructor : (handler = null) ->
@handlers = []
@handlers.push(handler) if handler?
return
trigger : (args...) =>
for c in @handlers
c(args...)
return
bind : (handler) =>
@handlers.push(handler)
return
unbind : (handler) =>
@handlers[t..t] = [] if (t = @handlers.indexOf(handler)) > -1
return
# currently (01.12.2012) a hack, hopefully will be fixed in newer
# versions of CoffeeScript
kl.KayleeError = class KayleeError extends Error then constructor: -> super
util.after = (timeout, f) ->
setTimeout(f, timeout)
util.every = (period, f) ->
setInterval(f, period) | true | ###
# klutil.coffee
# ~~~~~~~~~~~~~
#
# This file is a part of Kaylee client-side module.
# It contains the util and shared code used by Kaylee.
#
# :copyright: (c) 2012 by PI:NAME:<NAME>END_PI.
# :license: MIT, see LICENSE for more details.
###
kl.util = util = {}
util.is_function = (obj) ->
return typeof(obj) == 'function'
util.ends_with = (str, suffix) ->
return str.indexOf(suffix, str.length - suffix.length) != -1
kl.Event = class Event
constructor : (handler = null) ->
@handlers = []
@handlers.push(handler) if handler?
return
trigger : (args...) =>
for c in @handlers
c(args...)
return
bind : (handler) =>
@handlers.push(handler)
return
unbind : (handler) =>
@handlers[t..t] = [] if (t = @handlers.indexOf(handler)) > -1
return
# currently (01.12.2012) a hack, hopefully will be fixed in newer
# versions of CoffeeScript
kl.KayleeError = class KayleeError extends Error then constructor: -> super
util.after = (timeout, f) ->
setTimeout(f, timeout)
util.every = (period, f) ->
setInterval(f, period) |
[
{
"context": "ileoverview Tests for no-backticks rule.\n# @author Julian Rosse\n###\n'use strict'\n\n#------------------------------",
"end": 72,
"score": 0.9998306035995483,
"start": 60,
"tag": "NAME",
"value": "Julian Rosse"
}
] | src/tests/rules/no-backticks.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-backticks rule.
# @author Julian Rosse
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-backticks'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
error = type: 'PassthroughLiteral'
ruleTester.run 'no-backticks', rule,
valid: [
'foo = ->'
# eslint-disable-next-line coffee/no-template-curly-in-string
'''
"a#{b}`c`"
'''
'''
'`a`'
'''
'''
<div>{### comment ###}</div>
'''
]
invalid: [
code: '`a`'
errors: [error]
,
code: 'foo = `a`'
errors: [error]
,
code: '''
class A
`get b() {}`
'''
errors: [error]
]
| 98091 | ###*
# @fileoverview Tests for no-backticks rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-backticks'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
error = type: 'PassthroughLiteral'
ruleTester.run 'no-backticks', rule,
valid: [
'foo = ->'
# eslint-disable-next-line coffee/no-template-curly-in-string
'''
"a#{b}`c`"
'''
'''
'`a`'
'''
'''
<div>{### comment ###}</div>
'''
]
invalid: [
code: '`a`'
errors: [error]
,
code: 'foo = `a`'
errors: [error]
,
code: '''
class A
`get b() {}`
'''
errors: [error]
]
| true | ###*
# @fileoverview Tests for no-backticks rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-backticks'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
error = type: 'PassthroughLiteral'
ruleTester.run 'no-backticks', rule,
valid: [
'foo = ->'
# eslint-disable-next-line coffee/no-template-curly-in-string
'''
"a#{b}`c`"
'''
'''
'`a`'
'''
'''
<div>{### comment ###}</div>
'''
]
invalid: [
code: '`a`'
errors: [error]
,
code: 'foo = `a`'
errors: [error]
,
code: '''
class A
`get b() {}`
'''
errors: [error]
]
|
[
{
"context": "module for J-SENS protocol\n# Originally written by Denis Shirokov\n# Contributors: Ivan Orlov, Alexey Mikhaylishin, ",
"end": 90,
"score": 0.9998689889907837,
"start": 76,
"tag": "NAME",
"value": "Denis Shirokov"
},
{
"context": "iginally written by Denis Shirokov\n# Contributors: Ivan Orlov, Alexey Mikhaylishin, Konstantin Moskalenko\n# See",
"end": 117,
"score": 0.9998611211776733,
"start": 107,
"tag": "NAME",
"value": "Ivan Orlov"
},
{
"context": "tten by Denis Shirokov\n# Contributors: Ivan Orlov, Alexey Mikhaylishin, Konstantin Moskalenko\n# See https://github.com/b",
"end": 138,
"score": 0.9998636245727539,
"start": 119,
"tag": "NAME",
"value": "Alexey Mikhaylishin"
},
{
"context": "v\n# Contributors: Ivan Orlov, Alexey Mikhaylishin, Konstantin Moskalenko\n# See https://github.com/bzikst/J-SENS for detail",
"end": 161,
"score": 0.9998577833175659,
"start": 140,
"tag": "NAME",
"value": "Konstantin Moskalenko"
},
{
"context": "n, Konstantin Moskalenko\n# See https://github.com/bzikst/J-SENS for details\n#\n\nrequire 'coffee-script'\n\n# ",
"end": 193,
"score": 0.8652006983757019,
"start": 187,
"tag": "USERNAME",
"value": "bzikst"
}
] | client/DeviceManager.coffee | bzikst/J-SENS | 0 | # Device manager example module for J-SENS protocol
# Originally written by Denis Shirokov
# Contributors: Ivan Orlov, Alexey Mikhaylishin, Konstantin Moskalenko
# See https://github.com/bzikst/J-SENS for details
#
require 'coffee-script'
# Внешние модули
#
dgram = require 'dgram'
http = require 'http'
querystring = require 'querystring'
crypto = require 'crypto'
fs = require 'fs'
path = require 'path'
# Ошибки устройств
#
class DeviceError extends Error
constructor: (code, error)->
@code = code
@error = error
# Отправить комманду на устройство
#
sndCmd = (host, port, params, timeout, cb)->
sendData = JSON.stringify params
options =
method: 'POST', host: host, port: port,
headers:
'Content-Type': 'application/json'
'Content-Length': Buffer.byteLength(sendData)
Logger.debug """
На адрес #{host}:#{port} отправленны данные
#{sendData}
"""
# установить обработчик полученных данных
req = http.request options, (res)->
data = ''
res.on 'data', (chunk)-> data += chunk
res.on 'end', ()->
Logger.debug "Данные с контроллера #{data}"
try
jsonData = JSON.parse data
cb.done? jsonData
catch error
Logger.debug('Ошибка parse error', error)
Logger.debug('Parse data', data)
cb.fail? DeviceError 'parseerror', error
# определить максимальное время запроса
req.setTimeout timeout, ()->
cb.fail? DeviceError 'timeout'
req.abort()
# обработать ошибку
req.on 'error', (error)->
Logger.debug('Ошибка request error', error)
cb.fail? DeviceError 'noresponse', error
# сделать запрос
req.write sendData
req.end()
# Логгер
#
debug = global.debug;
Logger =
debug: ->
if debug
console.log('Logger debug >>>')
console.log.apply(console, arguments)
console.log('Logger ---\n')
info: ->
console.log('Logger info >>>')
console.log.apply(console, arguments)
console.log('Logger ---\n')
CONFIG =
# файл с обновлением
UPDATE_FILE: './update.data'
# файл с описанием обновления
UPDATE_INFO: './update.json'
# Утсройство
#
class Device
constructor: (host, port, uid)->
@verification = null
@version = null
@protocol = null
@host = host
@port = port
@uid = crypto
.createHash('md5')
.update(uid)
.digest('hex')
@haveupdate = no
@lastUpdate = Date.now() # время последнего обновления
@id = crypto
.createHash('md5')
.update(host + ':' + port)
.digest('hex')
toString: ->
"""
Устройство #{@uid}
id: #{@id}
хост: #{@host}:#{@port}
требует обновления: #{@haveupdate}
подлинность: #{@verification}
"""
toJSON: ->
{
id: @id
uid: @uid
verification: @verification
haveupdate: @haveupdate
protocol: @protocol
version: @version
}
# получить статус устройства
#
getStatus: (deviceManager)->
sndCmd @host, @port, {cmd: 'get-status'}, DeviceManager._DEV_TIMEOUT,
done: (res) =>
# если ответ положительный, статус изменени, то оповестить клиенты
if res.status? and DeviceManager.RES_SUCCESS is res.status.code
if res.data?.verification isnt @verification
@verification = res.data.verification
deviceManager.change(@id, 'status')
Logger.debug('Получен ответ об на get-status, статус изменился')
else
Logger.debug('Получен ответ об на get-status, статус остался прежнем')
else
Logger.info('Неверный ответ на get-status от устройства:\n', @toString(), 'ответ:', res)
fail: (err) =>
Logger.info('Не получен ответ на get-status, устройство', @toString(), ' будет удалено')
deviceManager.remove(@id, 'noresponse')
# получить информацию об устройстве
#
getInfo: (deviceManager)->
Logger.debug('getInfo', @)
sndCmd @host, @port, {cmd: 'get-info'}, DeviceManager._DEV_TIMEOUT,
done: (res) =>
if res.status? and DeviceManager.RES_SUCCESS is res.status.code
@verification = res.data?.verification
@version = res.data?.version
@protocol = res.data?.protocol
# проверить обновление
if @checkUpdate(deviceManager.updateInfo) is 'critical'
@haveupdate = yes
@sendUpdate deviceManager,
done: =>
deviceManager.remove(@id, 'updating')
fail: (err)=>
Logger.debug('При отправки update на ', @toString(), 'произошла ошибка', err)
else if @checkUpdate(deviceManager.updateInfo) is 'normal'
@haveupdate = yes
deviceManager.add(@id, 'new')
else
deviceManager.add(@id, 'new')
else
Logger.info('Неверный ответ на get-info от устройства:', @toString(), 'ответ:', res)
fail: (err) =>
Logger.info('Не получен ответ на get-info, устройство', @toString(), ' будет удалено')
deviceManager.remove(@id, 'noresponse')
# проверить, требуется ли обновление
#
checkUpdate: (updateInfo)->
unless updateInfo? then return 'noupdate'
min = Number(updateInfo.version.min)
max = Number(updateInfo.version.max)
cv = Number(@version)
console.log(min, cv, max)
# проверить версию
if min <= cv < max
if 'critical' is updateInfo.priority
return 'critical'
else
return 'normal'
else
return 'noupdate'
# отправить обновления на устройство
#
sendUpdate: (deviceManager, cb)->
fs.readFile CONFIG.UPDATE_FILE, (err, data)=>
unless err?
sndCmd @host, @port, {cmd: 'update', params: {name: deviceManager.updateInfo.name, data: data.toString('base64')}}, DeviceManager._DEV_TIMEOUT,
done: (res) =>
if res.status? and DeviceManager.RES_SUCCESS is res.status.code
Logger.debug('Получен ответ на update, устройство', @toString(),'будет обновленно')
deviceManager.remove(@id, 'updating')
cb.done?(res)
else
Logger.info('Неверный ответ на update от устройства:', @toString(), 'ответ:', res)
cb.fail?(err)
fail: (err) =>
Logger.info('Не получен ответ на update, устройство', @toString(), ' будет удалено')
deviceManager.remove(@id, 'noresponse')
cb.fail?(err)
else
cb.fail?(Error())
# пробросить комманду
#
proxyCommand: (deviceManager, params, cb)->
# перехватить команду на обновление
if 'update' is params.cmd
if @checkUpdate(deviceManager.updateInfo) in ['critical', 'normal']
@sendUpdate deviceManager,
done: (res)=>
cb.done?(res)
fail: (err)=>
cb.fail?(err)
else
Logger.info('Получен запрос на обновления, но обновлений нет, для:', @toString())
cb.fail?(Error())
else
sndCmd @host, @port, params, DeviceManager._DEV_TIMEOUT, cb
# Менеджер устройств
#
# Сообщения клиенту
# update [devices] - отправить подключенному клиенту массив устройств
# change device - отправить клиенту обновленное утсройство
# remove id msg - отправить клиенту сообщение об удалении устройства id и поясняющее сообщение msg
#
_instance = null
class DeviceManager
@_HELO_MSG: /[a-z0-9_-]+_v[a-z0-9.-]_p[0-9]+]/
@_DEV_HTTP_PORT : 8080
@_DEV_UDP_PORT : 3000 # udp порт
@_DEV_UPD_TIME : 1000 # ms таймоут после которого мы просим обновить устройство
@_DEV_REF_TIME : 10000 # ms таймоут после которого мы принудительно обновляем устройство, и если оно не подтверждено удаляем его
@_DEV_TIMEOUT : 5000 # ms таймоут после которого считается что устройство не доступно
udpSct : null
sockets : null # client socket connection
devices : null # devices hash table
hTimer : null
updateInfo : null
@RES_SUCCESS : 'success'
@Instance: ()->
unless _instance?
_instance = new DeviceManager
return _instance
constructor: ()->
@sockets = []
@devices = {}
@readUpdateInfo()
@start()
# прочитать файл обновлений
#
readUpdateInfo: ->
fs.readFile CONFIG.UPDATE_INFO, {flag: 'r'}, (err, data)=>
unless err?
try
updateInfo = JSON.parse(data.toString())
if updateInfo.version?.min? and updateInfo.version?.max?
@updateInfo = updateInfo
Logger.debug('Файл с обновлениями прочитан')
else
Logger.info('Неверный формат файла с обновлениями:', data.toString(), updateInfo)
catch err
Logger.info('Неверный формат файла с обновлениями(json parse error):', data.toString(), err)
else
Logger.info('Ошибка чтения файла с обновлениями:', CONFIG.UPDATE_INFO)
Logger.debug(err)
# старт менеджера устройств
#
start: =>
@udpSct = dgram.createSocket 'udp4'
@udpSct.on 'listening', @udpOnListening
@udpSct.on 'message', @udpOnMessage
@udpSct.bind DeviceManager._DEV_UDP_PORT
@hTimer = setInterval @forceUpdate, DeviceManager._DEV_REF_TIME
# стоп менеджера устройств
#
stop: () ->
@udpSct.close()
@devices = null
@sockets.length = 0
clearInterval @hTimer
# добавить подключенный клиент
#
connect: (socket)->
@sockets.push socket
# отдать клиенту информацию об устройствах
socket.emit 'update', @toJSON()
socket.emit 'disconnect', ()=>
@disconnect socket
# удалить отключенный клиент
#
disconnect: (socket)->
index = @sockets.indexOf socket
@sockets.splice index, 1
# обработать сообщение
#
udpOnMessage: (buff, rinfo)=>
msg = buff.toString()
Logger.debug "server got #{msg} from #{rinfo.address}:#{rinfo.port}"
# нужна проверка
if DeviceManager._HELO_MSG.test msg
# новое подключенное устройство
host = rinfo.address
port = DeviceManager._DEV_HTTP_PORT
@tryUpdate host, port, msg
# обрботать событие началот прослушивания порта udp
#
udpOnListening: ()=>
addr = @udpSct.address()
Logger.info "UDP Server listening on #{addr.address}:#{addr.port}"
# обновить по событию таймера
#
forceUpdate: =>
time = Date.now()
for id, device of @devices
timeout = time - device.lastUpdate
if timeout > DeviceManager._DEV_UPD_TIME
device.lastUpdate = Date.now()
device.getStatus(@)
# обновить по событию от устройства
#
tryUpdate: (host, port, uid)->
id = crypto
.createHash('md5')
.update(host + ':' + port)
.digest('hex')
time = Date.now()
device = @devices[id]
unless device?
# устройства нет в списке
@devices[id] = new Device(host, port, uid)
@devices[id].getInfo(@)
else
# устройство есть в списке
timeout = time - device.lastUpdate
if timeout > DeviceManager._DEV_UPD_TIME
device.lastUpdate = Date.now()
device.getStatus(@)
# оповестить об изменение информации об устройстве
#
change: (id, msg)->
device = @devices[id]
if device?
jsonDevice = device.toJSON()
@sockets.forEach (socket)=>
socket.emit 'change', jsonDevice, msg
# оповестить об удаление устройства
#
remove: (id, msg)->
delete @devices[id]
@sockets.forEach (socket)=>
socket.emit 'remove', id, msg
# оповестить об удаление устройства
#
add: (id, msg)->
device = @devices[id]
if device?
jsonDevice = device.toJSON()
@sockets.forEach (socket)=>
socket.emit 'add', id, jsonDevice, msg
toJSON: ->
data = []
for id, device of @devices
item = JSON.parse JSON.stringify device.toJSON()
data.push item
return data
# передать команду на устройство
#
proxyCmd: (id, params, cb)->
device = @devices[id]
if device?
device.proxyCommand(@, params, cb)
else
@remove(id, 'notfound')
cb.fail?(Error('not found'))
module.exports = DeviceManager
| 116924 | # Device manager example module for J-SENS protocol
# Originally written by <NAME>
# Contributors: <NAME>, <NAME>, <NAME>
# See https://github.com/bzikst/J-SENS for details
#
require 'coffee-script'
# Внешние модули
#
dgram = require 'dgram'
http = require 'http'
querystring = require 'querystring'
crypto = require 'crypto'
fs = require 'fs'
path = require 'path'
# Ошибки устройств
#
class DeviceError extends Error
constructor: (code, error)->
@code = code
@error = error
# Отправить комманду на устройство
#
sndCmd = (host, port, params, timeout, cb)->
sendData = JSON.stringify params
options =
method: 'POST', host: host, port: port,
headers:
'Content-Type': 'application/json'
'Content-Length': Buffer.byteLength(sendData)
Logger.debug """
На адрес #{host}:#{port} отправленны данные
#{sendData}
"""
# установить обработчик полученных данных
req = http.request options, (res)->
data = ''
res.on 'data', (chunk)-> data += chunk
res.on 'end', ()->
Logger.debug "Данные с контроллера #{data}"
try
jsonData = JSON.parse data
cb.done? jsonData
catch error
Logger.debug('Ошибка parse error', error)
Logger.debug('Parse data', data)
cb.fail? DeviceError 'parseerror', error
# определить максимальное время запроса
req.setTimeout timeout, ()->
cb.fail? DeviceError 'timeout'
req.abort()
# обработать ошибку
req.on 'error', (error)->
Logger.debug('Ошибка request error', error)
cb.fail? DeviceError 'noresponse', error
# сделать запрос
req.write sendData
req.end()
# Логгер
#
debug = global.debug;
Logger =
debug: ->
if debug
console.log('Logger debug >>>')
console.log.apply(console, arguments)
console.log('Logger ---\n')
info: ->
console.log('Logger info >>>')
console.log.apply(console, arguments)
console.log('Logger ---\n')
CONFIG =
# файл с обновлением
UPDATE_FILE: './update.data'
# файл с описанием обновления
UPDATE_INFO: './update.json'
# Утсройство
#
class Device
constructor: (host, port, uid)->
@verification = null
@version = null
@protocol = null
@host = host
@port = port
@uid = crypto
.createHash('md5')
.update(uid)
.digest('hex')
@haveupdate = no
@lastUpdate = Date.now() # время последнего обновления
@id = crypto
.createHash('md5')
.update(host + ':' + port)
.digest('hex')
toString: ->
"""
Устройство #{@uid}
id: #{@id}
хост: #{@host}:#{@port}
требует обновления: #{@haveupdate}
подлинность: #{@verification}
"""
toJSON: ->
{
id: @id
uid: @uid
verification: @verification
haveupdate: @haveupdate
protocol: @protocol
version: @version
}
# получить статус устройства
#
getStatus: (deviceManager)->
sndCmd @host, @port, {cmd: 'get-status'}, DeviceManager._DEV_TIMEOUT,
done: (res) =>
# если ответ положительный, статус изменени, то оповестить клиенты
if res.status? and DeviceManager.RES_SUCCESS is res.status.code
if res.data?.verification isnt @verification
@verification = res.data.verification
deviceManager.change(@id, 'status')
Logger.debug('Получен ответ об на get-status, статус изменился')
else
Logger.debug('Получен ответ об на get-status, статус остался прежнем')
else
Logger.info('Неверный ответ на get-status от устройства:\n', @toString(), 'ответ:', res)
fail: (err) =>
Logger.info('Не получен ответ на get-status, устройство', @toString(), ' будет удалено')
deviceManager.remove(@id, 'noresponse')
# получить информацию об устройстве
#
getInfo: (deviceManager)->
Logger.debug('getInfo', @)
sndCmd @host, @port, {cmd: 'get-info'}, DeviceManager._DEV_TIMEOUT,
done: (res) =>
if res.status? and DeviceManager.RES_SUCCESS is res.status.code
@verification = res.data?.verification
@version = res.data?.version
@protocol = res.data?.protocol
# проверить обновление
if @checkUpdate(deviceManager.updateInfo) is 'critical'
@haveupdate = yes
@sendUpdate deviceManager,
done: =>
deviceManager.remove(@id, 'updating')
fail: (err)=>
Logger.debug('При отправки update на ', @toString(), 'произошла ошибка', err)
else if @checkUpdate(deviceManager.updateInfo) is 'normal'
@haveupdate = yes
deviceManager.add(@id, 'new')
else
deviceManager.add(@id, 'new')
else
Logger.info('Неверный ответ на get-info от устройства:', @toString(), 'ответ:', res)
fail: (err) =>
Logger.info('Не получен ответ на get-info, устройство', @toString(), ' будет удалено')
deviceManager.remove(@id, 'noresponse')
# проверить, требуется ли обновление
#
checkUpdate: (updateInfo)->
unless updateInfo? then return 'noupdate'
min = Number(updateInfo.version.min)
max = Number(updateInfo.version.max)
cv = Number(@version)
console.log(min, cv, max)
# проверить версию
if min <= cv < max
if 'critical' is updateInfo.priority
return 'critical'
else
return 'normal'
else
return 'noupdate'
# отправить обновления на устройство
#
sendUpdate: (deviceManager, cb)->
fs.readFile CONFIG.UPDATE_FILE, (err, data)=>
unless err?
sndCmd @host, @port, {cmd: 'update', params: {name: deviceManager.updateInfo.name, data: data.toString('base64')}}, DeviceManager._DEV_TIMEOUT,
done: (res) =>
if res.status? and DeviceManager.RES_SUCCESS is res.status.code
Logger.debug('Получен ответ на update, устройство', @toString(),'будет обновленно')
deviceManager.remove(@id, 'updating')
cb.done?(res)
else
Logger.info('Неверный ответ на update от устройства:', @toString(), 'ответ:', res)
cb.fail?(err)
fail: (err) =>
Logger.info('Не получен ответ на update, устройство', @toString(), ' будет удалено')
deviceManager.remove(@id, 'noresponse')
cb.fail?(err)
else
cb.fail?(Error())
# пробросить комманду
#
proxyCommand: (deviceManager, params, cb)->
# перехватить команду на обновление
if 'update' is params.cmd
if @checkUpdate(deviceManager.updateInfo) in ['critical', 'normal']
@sendUpdate deviceManager,
done: (res)=>
cb.done?(res)
fail: (err)=>
cb.fail?(err)
else
Logger.info('Получен запрос на обновления, но обновлений нет, для:', @toString())
cb.fail?(Error())
else
sndCmd @host, @port, params, DeviceManager._DEV_TIMEOUT, cb
# Менеджер устройств
#
# Сообщения клиенту
# update [devices] - отправить подключенному клиенту массив устройств
# change device - отправить клиенту обновленное утсройство
# remove id msg - отправить клиенту сообщение об удалении устройства id и поясняющее сообщение msg
#
_instance = null
class DeviceManager
@_HELO_MSG: /[a-z0-9_-]+_v[a-z0-9.-]_p[0-9]+]/
@_DEV_HTTP_PORT : 8080
@_DEV_UDP_PORT : 3000 # udp порт
@_DEV_UPD_TIME : 1000 # ms таймоут после которого мы просим обновить устройство
@_DEV_REF_TIME : 10000 # ms таймоут после которого мы принудительно обновляем устройство, и если оно не подтверждено удаляем его
@_DEV_TIMEOUT : 5000 # ms таймоут после которого считается что устройство не доступно
udpSct : null
sockets : null # client socket connection
devices : null # devices hash table
hTimer : null
updateInfo : null
@RES_SUCCESS : 'success'
@Instance: ()->
unless _instance?
_instance = new DeviceManager
return _instance
constructor: ()->
@sockets = []
@devices = {}
@readUpdateInfo()
@start()
# прочитать файл обновлений
#
readUpdateInfo: ->
fs.readFile CONFIG.UPDATE_INFO, {flag: 'r'}, (err, data)=>
unless err?
try
updateInfo = JSON.parse(data.toString())
if updateInfo.version?.min? and updateInfo.version?.max?
@updateInfo = updateInfo
Logger.debug('Файл с обновлениями прочитан')
else
Logger.info('Неверный формат файла с обновлениями:', data.toString(), updateInfo)
catch err
Logger.info('Неверный формат файла с обновлениями(json parse error):', data.toString(), err)
else
Logger.info('Ошибка чтения файла с обновлениями:', CONFIG.UPDATE_INFO)
Logger.debug(err)
# старт менеджера устройств
#
start: =>
@udpSct = dgram.createSocket 'udp4'
@udpSct.on 'listening', @udpOnListening
@udpSct.on 'message', @udpOnMessage
@udpSct.bind DeviceManager._DEV_UDP_PORT
@hTimer = setInterval @forceUpdate, DeviceManager._DEV_REF_TIME
# стоп менеджера устройств
#
stop: () ->
@udpSct.close()
@devices = null
@sockets.length = 0
clearInterval @hTimer
# добавить подключенный клиент
#
connect: (socket)->
@sockets.push socket
# отдать клиенту информацию об устройствах
socket.emit 'update', @toJSON()
socket.emit 'disconnect', ()=>
@disconnect socket
# удалить отключенный клиент
#
disconnect: (socket)->
index = @sockets.indexOf socket
@sockets.splice index, 1
# обработать сообщение
#
udpOnMessage: (buff, rinfo)=>
msg = buff.toString()
Logger.debug "server got #{msg} from #{rinfo.address}:#{rinfo.port}"
# нужна проверка
if DeviceManager._HELO_MSG.test msg
# новое подключенное устройство
host = rinfo.address
port = DeviceManager._DEV_HTTP_PORT
@tryUpdate host, port, msg
# обрботать событие началот прослушивания порта udp
#
udpOnListening: ()=>
addr = @udpSct.address()
Logger.info "UDP Server listening on #{addr.address}:#{addr.port}"
# обновить по событию таймера
#
forceUpdate: =>
time = Date.now()
for id, device of @devices
timeout = time - device.lastUpdate
if timeout > DeviceManager._DEV_UPD_TIME
device.lastUpdate = Date.now()
device.getStatus(@)
# обновить по событию от устройства
#
tryUpdate: (host, port, uid)->
id = crypto
.createHash('md5')
.update(host + ':' + port)
.digest('hex')
time = Date.now()
device = @devices[id]
unless device?
# устройства нет в списке
@devices[id] = new Device(host, port, uid)
@devices[id].getInfo(@)
else
# устройство есть в списке
timeout = time - device.lastUpdate
if timeout > DeviceManager._DEV_UPD_TIME
device.lastUpdate = Date.now()
device.getStatus(@)
# оповестить об изменение информации об устройстве
#
change: (id, msg)->
device = @devices[id]
if device?
jsonDevice = device.toJSON()
@sockets.forEach (socket)=>
socket.emit 'change', jsonDevice, msg
# оповестить об удаление устройства
#
remove: (id, msg)->
delete @devices[id]
@sockets.forEach (socket)=>
socket.emit 'remove', id, msg
# оповестить об удаление устройства
#
add: (id, msg)->
device = @devices[id]
if device?
jsonDevice = device.toJSON()
@sockets.forEach (socket)=>
socket.emit 'add', id, jsonDevice, msg
toJSON: ->
data = []
for id, device of @devices
item = JSON.parse JSON.stringify device.toJSON()
data.push item
return data
# передать команду на устройство
#
proxyCmd: (id, params, cb)->
device = @devices[id]
if device?
device.proxyCommand(@, params, cb)
else
@remove(id, 'notfound')
cb.fail?(Error('not found'))
module.exports = DeviceManager
| true | # Device manager example module for J-SENS protocol
# Originally written by PI:NAME:<NAME>END_PI
# Contributors: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
# See https://github.com/bzikst/J-SENS for details
#
require 'coffee-script'
# Внешние модули
#
dgram = require 'dgram'
http = require 'http'
querystring = require 'querystring'
crypto = require 'crypto'
fs = require 'fs'
path = require 'path'
# Ошибки устройств
#
class DeviceError extends Error
constructor: (code, error)->
@code = code
@error = error
# Отправить комманду на устройство
#
sndCmd = (host, port, params, timeout, cb)->
sendData = JSON.stringify params
options =
method: 'POST', host: host, port: port,
headers:
'Content-Type': 'application/json'
'Content-Length': Buffer.byteLength(sendData)
Logger.debug """
На адрес #{host}:#{port} отправленны данные
#{sendData}
"""
# установить обработчик полученных данных
req = http.request options, (res)->
data = ''
res.on 'data', (chunk)-> data += chunk
res.on 'end', ()->
Logger.debug "Данные с контроллера #{data}"
try
jsonData = JSON.parse data
cb.done? jsonData
catch error
Logger.debug('Ошибка parse error', error)
Logger.debug('Parse data', data)
cb.fail? DeviceError 'parseerror', error
# определить максимальное время запроса
req.setTimeout timeout, ()->
cb.fail? DeviceError 'timeout'
req.abort()
# обработать ошибку
req.on 'error', (error)->
Logger.debug('Ошибка request error', error)
cb.fail? DeviceError 'noresponse', error
# сделать запрос
req.write sendData
req.end()
# Логгер
#
debug = global.debug;
Logger =
debug: ->
if debug
console.log('Logger debug >>>')
console.log.apply(console, arguments)
console.log('Logger ---\n')
info: ->
console.log('Logger info >>>')
console.log.apply(console, arguments)
console.log('Logger ---\n')
CONFIG =
# файл с обновлением
UPDATE_FILE: './update.data'
# файл с описанием обновления
UPDATE_INFO: './update.json'
# Утсройство
#
class Device
constructor: (host, port, uid)->
@verification = null
@version = null
@protocol = null
@host = host
@port = port
@uid = crypto
.createHash('md5')
.update(uid)
.digest('hex')
@haveupdate = no
@lastUpdate = Date.now() # время последнего обновления
@id = crypto
.createHash('md5')
.update(host + ':' + port)
.digest('hex')
toString: ->
"""
Устройство #{@uid}
id: #{@id}
хост: #{@host}:#{@port}
требует обновления: #{@haveupdate}
подлинность: #{@verification}
"""
toJSON: ->
{
id: @id
uid: @uid
verification: @verification
haveupdate: @haveupdate
protocol: @protocol
version: @version
}
# получить статус устройства
#
getStatus: (deviceManager)->
sndCmd @host, @port, {cmd: 'get-status'}, DeviceManager._DEV_TIMEOUT,
done: (res) =>
# если ответ положительный, статус изменени, то оповестить клиенты
if res.status? and DeviceManager.RES_SUCCESS is res.status.code
if res.data?.verification isnt @verification
@verification = res.data.verification
deviceManager.change(@id, 'status')
Logger.debug('Получен ответ об на get-status, статус изменился')
else
Logger.debug('Получен ответ об на get-status, статус остался прежнем')
else
Logger.info('Неверный ответ на get-status от устройства:\n', @toString(), 'ответ:', res)
fail: (err) =>
Logger.info('Не получен ответ на get-status, устройство', @toString(), ' будет удалено')
deviceManager.remove(@id, 'noresponse')
# получить информацию об устройстве
#
getInfo: (deviceManager)->
Logger.debug('getInfo', @)
sndCmd @host, @port, {cmd: 'get-info'}, DeviceManager._DEV_TIMEOUT,
done: (res) =>
if res.status? and DeviceManager.RES_SUCCESS is res.status.code
@verification = res.data?.verification
@version = res.data?.version
@protocol = res.data?.protocol
# проверить обновление
if @checkUpdate(deviceManager.updateInfo) is 'critical'
@haveupdate = yes
@sendUpdate deviceManager,
done: =>
deviceManager.remove(@id, 'updating')
fail: (err)=>
Logger.debug('При отправки update на ', @toString(), 'произошла ошибка', err)
else if @checkUpdate(deviceManager.updateInfo) is 'normal'
@haveupdate = yes
deviceManager.add(@id, 'new')
else
deviceManager.add(@id, 'new')
else
Logger.info('Неверный ответ на get-info от устройства:', @toString(), 'ответ:', res)
fail: (err) =>
Logger.info('Не получен ответ на get-info, устройство', @toString(), ' будет удалено')
deviceManager.remove(@id, 'noresponse')
# проверить, требуется ли обновление
#
checkUpdate: (updateInfo)->
unless updateInfo? then return 'noupdate'
min = Number(updateInfo.version.min)
max = Number(updateInfo.version.max)
cv = Number(@version)
console.log(min, cv, max)
# проверить версию
if min <= cv < max
if 'critical' is updateInfo.priority
return 'critical'
else
return 'normal'
else
return 'noupdate'
# отправить обновления на устройство
#
sendUpdate: (deviceManager, cb)->
fs.readFile CONFIG.UPDATE_FILE, (err, data)=>
unless err?
sndCmd @host, @port, {cmd: 'update', params: {name: deviceManager.updateInfo.name, data: data.toString('base64')}}, DeviceManager._DEV_TIMEOUT,
done: (res) =>
if res.status? and DeviceManager.RES_SUCCESS is res.status.code
Logger.debug('Получен ответ на update, устройство', @toString(),'будет обновленно')
deviceManager.remove(@id, 'updating')
cb.done?(res)
else
Logger.info('Неверный ответ на update от устройства:', @toString(), 'ответ:', res)
cb.fail?(err)
fail: (err) =>
Logger.info('Не получен ответ на update, устройство', @toString(), ' будет удалено')
deviceManager.remove(@id, 'noresponse')
cb.fail?(err)
else
cb.fail?(Error())
# пробросить комманду
#
proxyCommand: (deviceManager, params, cb)->
# перехватить команду на обновление
if 'update' is params.cmd
if @checkUpdate(deviceManager.updateInfo) in ['critical', 'normal']
@sendUpdate deviceManager,
done: (res)=>
cb.done?(res)
fail: (err)=>
cb.fail?(err)
else
Logger.info('Получен запрос на обновления, но обновлений нет, для:', @toString())
cb.fail?(Error())
else
sndCmd @host, @port, params, DeviceManager._DEV_TIMEOUT, cb
# Менеджер устройств
#
# Сообщения клиенту
# update [devices] - отправить подключенному клиенту массив устройств
# change device - отправить клиенту обновленное утсройство
# remove id msg - отправить клиенту сообщение об удалении устройства id и поясняющее сообщение msg
#
_instance = null
class DeviceManager
@_HELO_MSG: /[a-z0-9_-]+_v[a-z0-9.-]_p[0-9]+]/
@_DEV_HTTP_PORT : 8080
@_DEV_UDP_PORT : 3000 # udp порт
@_DEV_UPD_TIME : 1000 # ms таймоут после которого мы просим обновить устройство
@_DEV_REF_TIME : 10000 # ms таймоут после которого мы принудительно обновляем устройство, и если оно не подтверждено удаляем его
@_DEV_TIMEOUT : 5000 # ms таймоут после которого считается что устройство не доступно
udpSct : null
sockets : null # client socket connection
devices : null # devices hash table
hTimer : null
updateInfo : null
@RES_SUCCESS : 'success'
@Instance: ()->
unless _instance?
_instance = new DeviceManager
return _instance
constructor: ()->
@sockets = []
@devices = {}
@readUpdateInfo()
@start()
# прочитать файл обновлений
#
readUpdateInfo: ->
fs.readFile CONFIG.UPDATE_INFO, {flag: 'r'}, (err, data)=>
unless err?
try
updateInfo = JSON.parse(data.toString())
if updateInfo.version?.min? and updateInfo.version?.max?
@updateInfo = updateInfo
Logger.debug('Файл с обновлениями прочитан')
else
Logger.info('Неверный формат файла с обновлениями:', data.toString(), updateInfo)
catch err
Logger.info('Неверный формат файла с обновлениями(json parse error):', data.toString(), err)
else
Logger.info('Ошибка чтения файла с обновлениями:', CONFIG.UPDATE_INFO)
Logger.debug(err)
# старт менеджера устройств
#
start: =>
@udpSct = dgram.createSocket 'udp4'
@udpSct.on 'listening', @udpOnListening
@udpSct.on 'message', @udpOnMessage
@udpSct.bind DeviceManager._DEV_UDP_PORT
@hTimer = setInterval @forceUpdate, DeviceManager._DEV_REF_TIME
# стоп менеджера устройств
#
stop: () ->
@udpSct.close()
@devices = null
@sockets.length = 0
clearInterval @hTimer
# добавить подключенный клиент
#
connect: (socket)->
@sockets.push socket
# отдать клиенту информацию об устройствах
socket.emit 'update', @toJSON()
socket.emit 'disconnect', ()=>
@disconnect socket
# удалить отключенный клиент
#
disconnect: (socket)->
index = @sockets.indexOf socket
@sockets.splice index, 1
# обработать сообщение
#
udpOnMessage: (buff, rinfo)=>
msg = buff.toString()
Logger.debug "server got #{msg} from #{rinfo.address}:#{rinfo.port}"
# нужна проверка
if DeviceManager._HELO_MSG.test msg
# новое подключенное устройство
host = rinfo.address
port = DeviceManager._DEV_HTTP_PORT
@tryUpdate host, port, msg
# обрботать событие началот прослушивания порта udp
#
udpOnListening: ()=>
addr = @udpSct.address()
Logger.info "UDP Server listening on #{addr.address}:#{addr.port}"
# обновить по событию таймера
#
forceUpdate: =>
time = Date.now()
for id, device of @devices
timeout = time - device.lastUpdate
if timeout > DeviceManager._DEV_UPD_TIME
device.lastUpdate = Date.now()
device.getStatus(@)
# обновить по событию от устройства
#
tryUpdate: (host, port, uid)->
id = crypto
.createHash('md5')
.update(host + ':' + port)
.digest('hex')
time = Date.now()
device = @devices[id]
unless device?
# устройства нет в списке
@devices[id] = new Device(host, port, uid)
@devices[id].getInfo(@)
else
# устройство есть в списке
timeout = time - device.lastUpdate
if timeout > DeviceManager._DEV_UPD_TIME
device.lastUpdate = Date.now()
device.getStatus(@)
# оповестить об изменение информации об устройстве
#
change: (id, msg)->
device = @devices[id]
if device?
jsonDevice = device.toJSON()
@sockets.forEach (socket)=>
socket.emit 'change', jsonDevice, msg
# оповестить об удаление устройства
#
remove: (id, msg)->
delete @devices[id]
@sockets.forEach (socket)=>
socket.emit 'remove', id, msg
# оповестить об удаление устройства
#
add: (id, msg)->
device = @devices[id]
if device?
jsonDevice = device.toJSON()
@sockets.forEach (socket)=>
socket.emit 'add', id, jsonDevice, msg
toJSON: ->
data = []
for id, device of @devices
item = JSON.parse JSON.stringify device.toJSON()
data.push item
return data
# передать команду на устройство
#
proxyCmd: (id, params, cb)->
device = @devices[id]
if device?
device.proxyCommand(@, params, cb)
else
@remove(id, 'notfound')
cb.fail?(Error('not found'))
module.exports = DeviceManager
|
[
{
"context": "ulate width of text from DOM element or string. By Phil Freo <http://philfreo.com>\n\t# This works but doesn't d",
"end": 2781,
"score": 0.9998528361320496,
"start": 2772,
"tag": "NAME",
"value": "Phil Freo"
}
] | www/js/calendar-tile.coffee | robdobsn/HomeTabletLocalApp | 0 | class App.CalendarTile extends App.Tile
constructor: (@app, tileDef, @calDayIndex) ->
super tileDef
@shortDayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
@calLineCount = 0; @calCharCount = 0; @calMaxLineLen = 0
@secsBetweenCalendarRefreshes = 60
return
handleAction: (action) ->
if action is "next"
if @calDayIndex < @app.calendarManager.getCalNumDays()
@calDayIndex++
else if action is "prev"
if @calDayIndex > 0
@calDayIndex--
@updateCalendar()
return
addToDoc: () ->
super()
@setRefreshInterval(@secsBetweenCalendarRefreshes, @updateCalendar, true)
return
updateCalendar: () ->
calData = @app.calendarManager.getCalData()
@showCalendar(calData)
showCalendar: (jsonData) ->
if not ("calEvents" of jsonData)
return
newHtml = ""
# Calendar boxes can be for each of the next few days so see which date this one is for
reqDate = new Date()
reqDate.setDate(reqDate.getDate()+@calDayIndex);
reqDateStr = @toZeroPadStr(reqDate.getFullYear(), 4) +
@toZeroPadStr(reqDate.getMonth()+1, 2) +
@toZeroPadStr(reqDate.getDate(), 2)
calTitle = ""
if @calDayIndex is 0
calTitle = "Today "
calTitle += @shortDayNames[reqDate.getDay()]
calTitle += " " + @toZeroPadStr(reqDate.getDate(), 2) + "/" +
@toZeroPadStr(reqDate.getMonth()+1, 2) + "/" +
@toZeroPadStr(reqDate.getFullYear(), 4)
# Format the text to go into the calendar and keep stats on it for font sizing
@calLineCount = 0; @calCharCount = 0; @calMaxLineLen = 0
for event in jsonData["calEvents"]
if event["eventDate"] is reqDateStr
@calLineCount += 1
newLine = """
<span class="sqCalEventStart">#{event["eventTime"]}</span>
<span class="sqCalEventDur"> (#{@formatDurationStr(event["duration"])}) </span>
<span class="sqCalEventSummary">#{event["summary"]}</span>
"""
newHtml += """
<li class="sqCalEvent">
#{newLine}
</li>
"""
@calCharCount += newLine.length
@calMaxLineLen = if @calMaxLineLen < newLine.length then newLine.length else @calMaxLineLen
# Check for non-busy day
if newHtml is ""
newHtml = "Nothing doing"
# Place the calendar text
@contents.html """
<div class="sqCalTitle" style="font-size:26px;font-weight:bold;color:white;">#{calTitle}</div>
<ul class="sqCalEvents">
#{newHtml}
</ul>
"""
# Calculate optimal font size
@recalculateFontScaling()
return
# Utility function for leading zeroes
toZeroPadStr: (value, digits) ->
s = "0000" + value
return s.substr(s.length-digits)
# Override reposition to handle font scaling
reposition: (posX, posY, sizeX, sizeY) ->
super(posX, posY, sizeX, sizeY)
@recalculateFontScaling()
return
# Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com>
# This works but doesn't do what I want - which is to calculate the actual width of text
# including overflowed text in a box of fixed width - what it does is removes the box width
# restriction and calculates the overall width of the text at the given font size - useful
# in some situations but not what I need
calcTextWidth: (text, fontSize, boxWidth) ->
@fakeEl = $("<span>").hide().appendTo(document.body) unless @fakeEl?
@fakeEl.text(text).css("font-size", fontSize)
return @fakeEl.width()
findOptimumFontSize: (optHeight, docElem, initScale, maxFontScale) ->
availSize = (if optHeight then @sizeY else @sizeX) * 0.9
calText = @getElement(docElem)
# console.log @calcTextWidth(calText.text(), calText.css("font-size"))
textSize = if optHeight then calText.height() else @calcTextWidth(calText.text(), calText.css("font-size"))
if not textSize? then return 1.0
fontScale = if optHeight then availSize / textSize else initScale
fontScale = if fontScale > maxFontScale then maxFontScale else fontScale
@setContentFontScaling(fontScale)
sizeInc = 1.0
# Iterate through possible sizes in a kind of binary tree search
for i in [0..6]
calText = @getElement(docElem)
textSize = if optHeight then calText.height() else @calcTextWidth(calText.text(), calText.css("font-size"))
if not textSize? then return fontScale
if textSize > availSize
fontScale = fontScale * (1 - (sizeInc/2))
@setContentFontScaling(fontScale)
else if textSize < (availSize * 0.75) and fontScale < maxFontScale
fontScale = fontScale * (1 + sizeInc)
@setContentFontScaling(fontScale)
else
break
sizeInc *= 0.5
return fontScale
# Provide a different font scaling based on the amount of text in the calendar box
recalculateFontScaling: () ->
if not @sizeX? or not @sizeY? or (@calLineCount is 0) then return
fontScale = @findOptimumFontSize(true, ".sqCalEvents", 1.0, 2.2)
#fontScale = @findOptimumFontSize(false, ".sqCalEvents", yScale)
@setContentFontScaling(fontScale)
return
setContentFontScaling: (contentFontScaling) ->
css =
"font-size": (100 * contentFontScaling) + "%"
$(".sqCalEvents").css(css)
return
formatDurationStr: (val) ->
dur = val.split(":")
days = parseInt(dur[0])
hrs = parseInt(dur[1])
mins = parseInt(dur[2])
outStr = ""
if days is 0 and hrs isnt 0 and mins is 30
outStr = (hrs+0.5) + "h"
else
outStr = if days is 0 then "" else (days + "d")
outStr += if hrs is 0 then "" else (hrs + "h")
outStr += if mins is 0 then "" else (mins + "m")
return outStr
| 81331 | class App.CalendarTile extends App.Tile
constructor: (@app, tileDef, @calDayIndex) ->
super tileDef
@shortDayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
@calLineCount = 0; @calCharCount = 0; @calMaxLineLen = 0
@secsBetweenCalendarRefreshes = 60
return
handleAction: (action) ->
if action is "next"
if @calDayIndex < @app.calendarManager.getCalNumDays()
@calDayIndex++
else if action is "prev"
if @calDayIndex > 0
@calDayIndex--
@updateCalendar()
return
addToDoc: () ->
super()
@setRefreshInterval(@secsBetweenCalendarRefreshes, @updateCalendar, true)
return
updateCalendar: () ->
calData = @app.calendarManager.getCalData()
@showCalendar(calData)
showCalendar: (jsonData) ->
if not ("calEvents" of jsonData)
return
newHtml = ""
# Calendar boxes can be for each of the next few days so see which date this one is for
reqDate = new Date()
reqDate.setDate(reqDate.getDate()+@calDayIndex);
reqDateStr = @toZeroPadStr(reqDate.getFullYear(), 4) +
@toZeroPadStr(reqDate.getMonth()+1, 2) +
@toZeroPadStr(reqDate.getDate(), 2)
calTitle = ""
if @calDayIndex is 0
calTitle = "Today "
calTitle += @shortDayNames[reqDate.getDay()]
calTitle += " " + @toZeroPadStr(reqDate.getDate(), 2) + "/" +
@toZeroPadStr(reqDate.getMonth()+1, 2) + "/" +
@toZeroPadStr(reqDate.getFullYear(), 4)
# Format the text to go into the calendar and keep stats on it for font sizing
@calLineCount = 0; @calCharCount = 0; @calMaxLineLen = 0
for event in jsonData["calEvents"]
if event["eventDate"] is reqDateStr
@calLineCount += 1
newLine = """
<span class="sqCalEventStart">#{event["eventTime"]}</span>
<span class="sqCalEventDur"> (#{@formatDurationStr(event["duration"])}) </span>
<span class="sqCalEventSummary">#{event["summary"]}</span>
"""
newHtml += """
<li class="sqCalEvent">
#{newLine}
</li>
"""
@calCharCount += newLine.length
@calMaxLineLen = if @calMaxLineLen < newLine.length then newLine.length else @calMaxLineLen
# Check for non-busy day
if newHtml is ""
newHtml = "Nothing doing"
# Place the calendar text
@contents.html """
<div class="sqCalTitle" style="font-size:26px;font-weight:bold;color:white;">#{calTitle}</div>
<ul class="sqCalEvents">
#{newHtml}
</ul>
"""
# Calculate optimal font size
@recalculateFontScaling()
return
# Utility function for leading zeroes
toZeroPadStr: (value, digits) ->
s = "0000" + value
return s.substr(s.length-digits)
# Override reposition to handle font scaling
reposition: (posX, posY, sizeX, sizeY) ->
super(posX, posY, sizeX, sizeY)
@recalculateFontScaling()
return
# Calculate width of text from DOM element or string. By <NAME> <http://philfreo.com>
# This works but doesn't do what I want - which is to calculate the actual width of text
# including overflowed text in a box of fixed width - what it does is removes the box width
# restriction and calculates the overall width of the text at the given font size - useful
# in some situations but not what I need
calcTextWidth: (text, fontSize, boxWidth) ->
@fakeEl = $("<span>").hide().appendTo(document.body) unless @fakeEl?
@fakeEl.text(text).css("font-size", fontSize)
return @fakeEl.width()
findOptimumFontSize: (optHeight, docElem, initScale, maxFontScale) ->
availSize = (if optHeight then @sizeY else @sizeX) * 0.9
calText = @getElement(docElem)
# console.log @calcTextWidth(calText.text(), calText.css("font-size"))
textSize = if optHeight then calText.height() else @calcTextWidth(calText.text(), calText.css("font-size"))
if not textSize? then return 1.0
fontScale = if optHeight then availSize / textSize else initScale
fontScale = if fontScale > maxFontScale then maxFontScale else fontScale
@setContentFontScaling(fontScale)
sizeInc = 1.0
# Iterate through possible sizes in a kind of binary tree search
for i in [0..6]
calText = @getElement(docElem)
textSize = if optHeight then calText.height() else @calcTextWidth(calText.text(), calText.css("font-size"))
if not textSize? then return fontScale
if textSize > availSize
fontScale = fontScale * (1 - (sizeInc/2))
@setContentFontScaling(fontScale)
else if textSize < (availSize * 0.75) and fontScale < maxFontScale
fontScale = fontScale * (1 + sizeInc)
@setContentFontScaling(fontScale)
else
break
sizeInc *= 0.5
return fontScale
# Provide a different font scaling based on the amount of text in the calendar box
recalculateFontScaling: () ->
if not @sizeX? or not @sizeY? or (@calLineCount is 0) then return
fontScale = @findOptimumFontSize(true, ".sqCalEvents", 1.0, 2.2)
#fontScale = @findOptimumFontSize(false, ".sqCalEvents", yScale)
@setContentFontScaling(fontScale)
return
setContentFontScaling: (contentFontScaling) ->
css =
"font-size": (100 * contentFontScaling) + "%"
$(".sqCalEvents").css(css)
return
formatDurationStr: (val) ->
dur = val.split(":")
days = parseInt(dur[0])
hrs = parseInt(dur[1])
mins = parseInt(dur[2])
outStr = ""
if days is 0 and hrs isnt 0 and mins is 30
outStr = (hrs+0.5) + "h"
else
outStr = if days is 0 then "" else (days + "d")
outStr += if hrs is 0 then "" else (hrs + "h")
outStr += if mins is 0 then "" else (mins + "m")
return outStr
| true | class App.CalendarTile extends App.Tile
constructor: (@app, tileDef, @calDayIndex) ->
super tileDef
@shortDayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
@calLineCount = 0; @calCharCount = 0; @calMaxLineLen = 0
@secsBetweenCalendarRefreshes = 60
return
handleAction: (action) ->
if action is "next"
if @calDayIndex < @app.calendarManager.getCalNumDays()
@calDayIndex++
else if action is "prev"
if @calDayIndex > 0
@calDayIndex--
@updateCalendar()
return
addToDoc: () ->
super()
@setRefreshInterval(@secsBetweenCalendarRefreshes, @updateCalendar, true)
return
updateCalendar: () ->
calData = @app.calendarManager.getCalData()
@showCalendar(calData)
showCalendar: (jsonData) ->
if not ("calEvents" of jsonData)
return
newHtml = ""
# Calendar boxes can be for each of the next few days so see which date this one is for
reqDate = new Date()
reqDate.setDate(reqDate.getDate()+@calDayIndex);
reqDateStr = @toZeroPadStr(reqDate.getFullYear(), 4) +
@toZeroPadStr(reqDate.getMonth()+1, 2) +
@toZeroPadStr(reqDate.getDate(), 2)
calTitle = ""
if @calDayIndex is 0
calTitle = "Today "
calTitle += @shortDayNames[reqDate.getDay()]
calTitle += " " + @toZeroPadStr(reqDate.getDate(), 2) + "/" +
@toZeroPadStr(reqDate.getMonth()+1, 2) + "/" +
@toZeroPadStr(reqDate.getFullYear(), 4)
# Format the text to go into the calendar and keep stats on it for font sizing
@calLineCount = 0; @calCharCount = 0; @calMaxLineLen = 0
for event in jsonData["calEvents"]
if event["eventDate"] is reqDateStr
@calLineCount += 1
newLine = """
<span class="sqCalEventStart">#{event["eventTime"]}</span>
<span class="sqCalEventDur"> (#{@formatDurationStr(event["duration"])}) </span>
<span class="sqCalEventSummary">#{event["summary"]}</span>
"""
newHtml += """
<li class="sqCalEvent">
#{newLine}
</li>
"""
@calCharCount += newLine.length
@calMaxLineLen = if @calMaxLineLen < newLine.length then newLine.length else @calMaxLineLen
# Check for non-busy day
if newHtml is ""
newHtml = "Nothing doing"
# Place the calendar text
@contents.html """
<div class="sqCalTitle" style="font-size:26px;font-weight:bold;color:white;">#{calTitle}</div>
<ul class="sqCalEvents">
#{newHtml}
</ul>
"""
# Calculate optimal font size
@recalculateFontScaling()
return
# Utility function for leading zeroes
toZeroPadStr: (value, digits) ->
s = "0000" + value
return s.substr(s.length-digits)
# Override reposition to handle font scaling
reposition: (posX, posY, sizeX, sizeY) ->
super(posX, posY, sizeX, sizeY)
@recalculateFontScaling()
return
# Calculate width of text from DOM element or string. By PI:NAME:<NAME>END_PI <http://philfreo.com>
# This works but doesn't do what I want - which is to calculate the actual width of text
# including overflowed text in a box of fixed width - what it does is removes the box width
# restriction and calculates the overall width of the text at the given font size - useful
# in some situations but not what I need
calcTextWidth: (text, fontSize, boxWidth) ->
@fakeEl = $("<span>").hide().appendTo(document.body) unless @fakeEl?
@fakeEl.text(text).css("font-size", fontSize)
return @fakeEl.width()
findOptimumFontSize: (optHeight, docElem, initScale, maxFontScale) ->
availSize = (if optHeight then @sizeY else @sizeX) * 0.9
calText = @getElement(docElem)
# console.log @calcTextWidth(calText.text(), calText.css("font-size"))
textSize = if optHeight then calText.height() else @calcTextWidth(calText.text(), calText.css("font-size"))
if not textSize? then return 1.0
fontScale = if optHeight then availSize / textSize else initScale
fontScale = if fontScale > maxFontScale then maxFontScale else fontScale
@setContentFontScaling(fontScale)
sizeInc = 1.0
# Iterate through possible sizes in a kind of binary tree search
for i in [0..6]
calText = @getElement(docElem)
textSize = if optHeight then calText.height() else @calcTextWidth(calText.text(), calText.css("font-size"))
if not textSize? then return fontScale
if textSize > availSize
fontScale = fontScale * (1 - (sizeInc/2))
@setContentFontScaling(fontScale)
else if textSize < (availSize * 0.75) and fontScale < maxFontScale
fontScale = fontScale * (1 + sizeInc)
@setContentFontScaling(fontScale)
else
break
sizeInc *= 0.5
return fontScale
# Provide a different font scaling based on the amount of text in the calendar box
recalculateFontScaling: () ->
if not @sizeX? or not @sizeY? or (@calLineCount is 0) then return
fontScale = @findOptimumFontSize(true, ".sqCalEvents", 1.0, 2.2)
#fontScale = @findOptimumFontSize(false, ".sqCalEvents", yScale)
@setContentFontScaling(fontScale)
return
setContentFontScaling: (contentFontScaling) ->
css =
"font-size": (100 * contentFontScaling) + "%"
$(".sqCalEvents").css(css)
return
formatDurationStr: (val) ->
dur = val.split(":")
days = parseInt(dur[0])
hrs = parseInt(dur[1])
mins = parseInt(dur[2])
outStr = ""
if days is 0 and hrs isnt 0 and mins is 30
outStr = (hrs+0.5) + "h"
else
outStr = if days is 0 then "" else (days + "d")
outStr += if hrs is 0 then "" else (hrs + "h")
outStr += if mins is 0 then "" else (mins + "m")
return outStr
|
[
{
"context": "quotes = {\n Gates: '''<!-- --><b><!-- Comments are ignored --><q da",
"end": 20,
"score": 0.6732059121131897,
"start": 15,
"tag": "NAME",
"value": "Gates"
},
{
"context": "href=\"#\"><img src=\"bill-gates.jpg\"></a></q>'''\n Kernighan: ''' <q>\n Everyone knows that debugging ",
"end": 235,
"score": 0.7622063755989075,
"start": 228,
"tag": "NAME",
"value": "Kernigh"
},
{
"context": " you ever <b>debug</b> it?</span>\n </q> '''\n Ritchie: '''\nI can't recall any difficulty in making the ",
"end": 504,
"score": 0.7787113189697266,
"start": 497,
"tag": "NAME",
"value": "Ritchie"
}
] | src/spec/html-string-spec.coffee | anthonyjb/HTMLString | 24 | quotes = {
Gates: '''<!-- --><b><!-- Comments are ignored --><q data-example>We all</q></b><q data-example> need people who will give us feedback. That's how we improve. <a href="#"><img src="bill-gates.jpg"></a></q>'''
Kernighan: ''' <q>
Everyone knows that debugging is twice as hard as writing a program in
the first place. So if you're as clever as you can be when you write
it, <span class="question">how will you ever <b>debug</b> it?</span>
</q> '''
Ritchie: '''
I can't recall any difficulty in making the C language definition completely
open - any discussion on the matter tended to mention languages whose
inventors tried to keep tight control, and consequent ill fate.'''
Turing: '''
<q id="turings-quote">Machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency.</i></q>
'''
Wozniak: '''
all the best people in life seem to like LINUX.
'''
WozniakNamespaced: '''
all the best people in life seem to like <ns:tag ns:attr="foo">LINUX</ns:tag>.
'''
WozniakWhitespace: '''
all the best people in life seem to like LINUX.
'''
AmbiguousAmpersand: '''
& &<a href="/foo?bar=1&zee=2&omm=3&end">amp</a> &foo && && &end
'''
}
describe 'HTMLString.String()', () ->
it 'should parse and render text (no HTML)', () ->
string = new HTMLString.String(quotes.Wozniak)
expect(string.text()).toBe quotes.Wozniak
it 'should parse and render text (no HTML with whitespace preserved)', () ->
string = new HTMLString.String(quotes.WozniakWhitespace, true)
expect(string.text()).toBe quotes.WozniakWhitespace
it 'should parse and render a string (HTML)', () ->
string = new HTMLString.String(quotes.Turing)
expect(string.html()).toBe quotes.Turing
# Check names spaced tags are supported
string = new HTMLString.String(quotes.WozniakNamespaced)
expect(string.html()).toBe quotes.WozniakNamespaced
it 'should parse and render a string (HTML with ambiguous ampersands)', () ->
string = new HTMLString.String(quotes.AmbiguousAmpersand)
expect(string.html()).toBe quotes.AmbiguousAmpersand
console.log string.html()
describe 'HTMLString.String.isWhitespace()', () ->
it 'should return true if a string consists entirely of whitespace \
characters', () ->
string = new HTMLString.String(" <br>")
expect(string.isWhitespace()).toBe true
it 'should return false if a string contains any non-whitespace \
character', () ->
string = new HTMLString.String(" a <br>")
expect(string.isWhitespace()).toBe false
describe 'HTMLString.String.length()', () ->
it 'should return the length of a string', () ->
string = new HTMLString.String(quotes.Turing)
expect(string.length()).toBe 52
describe 'HTMLString.String.preserveWhitespace()', () ->
it 'should return the true if whitespace is reserved for the string', () ->
# Not preserved
string = new HTMLString.String(quotes.Turing)
expect(string.preserveWhitespace()).toBe false
# Preserved
string = new HTMLString.String(quotes.Turing, true)
expect(string.preserveWhitespace()).toBe true
describe 'HTMLString.String.capitalize()', () ->
it 'should capitalize the first character of a string', () ->
string = new HTMLString.String(quotes.Wozniak)
newString = string.capitalize()
expect(newString.charAt(0).c()).toBe 'A'
describe 'HTMLString.String.charAt()', () ->
it 'should return a character from a string at the specified index', () ->
string = new HTMLString.String(quotes.Turing)
expect(string.charAt(18).c()).toBe 'y'
describe 'HTMLString.String.concat()', () ->
it 'should combine 2 or more strings and return a new string', () ->
stringA = new HTMLString.String(quotes.Turing)
stringB = new HTMLString.String(quotes.Wozniak)
newString = stringA.concat(stringB)
expect(newString.html()).toBe '''<q id="turings-quote">Machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency.all the best people in life seem to like LINUX.</i></q>'''
describe 'HTMLString.String.contain()', () ->
it 'should return true if a string contains a substring', () ->
string = new HTMLString.String(quotes.Turing)
substring = new HTMLString.String('<q id="turings-quote">take me</q>')
expect(string.contains('take me')).toBe true
expect(string.contains(substring)).toBe true
describe 'HTMLString.String.endswith()', () ->
it 'should return true if a string ends with a substring.`', () ->
string = new HTMLString.String(quotes.Turing)
substring = new HTMLString.String(
'<q id="turings-quote"><i>great frequency.</i></q>'
)
expect(
string.endsWith(
"great#{ HTMLString.String.decode(' ') }frequency."
)
).toBe true
expect(string.endsWith(substring)).toBe true
describe 'HTMLString.String.format()', () ->
it 'should format a selection of characters in a string (add tags)', () ->
string = new HTMLString.String(quotes.Ritchie)
string = string.format(0, -1, new HTMLString.Tag('q'))
string = string.format(
19,
29,
new HTMLString.Tag('a', {href: 'http://www.getme.co.uk'}),
new HTMLString.Tag('b')
)
expect(string.html()).toBe """
<q>I can't recall any <a href="http://www.getme.co.uk"><b>difficulty</b></a> in making the C language definition completely open - any discussion on the matter tended to mention languages whose inventors tried to keep tight control, and consequent ill fate.</q>
""".trim()
describe 'HTMLString.String.hasTags()', () ->
it 'should return true if the string has and characters formatted with the \
specifed tags', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
expect(
string.hasTags(
new HTMLString.Tag('q'),
'b'
)
).toBe true
expect(string.hasTags(new HTMLString.Tag('q')), true).toBe true
describe 'HTMLString.String.indexOf()', () ->
it 'should return the first position of an substring in another string, \
or -1 if there is no match', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
substring = new HTMLString.String('<q>debugging</q>')
expect(string.indexOf('debugging')).toBe 20
expect(string.indexOf(substring)).toBe 20
expect(string.indexOf(substring, 30)).toBe -1
describe 'HTMLString.String.insert()', () ->
it 'should insert a string into another string and return a new \
string', () ->
stringA = new HTMLString.String(quotes.Kernighan).trim()
stringB = new HTMLString.String(quotes.Turing)
# Inherit formatting
newString = stringA.insert(9, stringB)
newString = newString.insert(9 + stringB.length(), ' - new string inserted - ')
expect(newString.html()).toBe '''<q>Everyone <q id="turings-quote">Machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency. - new string inserted - </i></q>knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, <span class="question">how will you ever <b>debug</b> it?</span></q>'''
# Do not inherit formatting
newString = stringA.insert(9, ' - insert unformatted string - ', false)
expect(newString.html()).toBe '''<q>Everyone </q> - insert unformatted string - <q>knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, <span class="question">how will you ever <b>debug</b> it?</span></q>'''
describe 'HTMLString.String.lastIndexOf()', () ->
it 'should return the last position of an substring in another string, \
or -1 if there is no match', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
substring = new HTMLString.String('<q>debugging</q>')
expect(string.lastIndexOf('debugging')).toBe 142
expect(string.lastIndexOf(substring)).toBe 142
expect(string.lastIndexOf(substring, 30)).toBe -1
describe 'HTMLString.String.optimize()', () ->
it 'should optimize the string (in place) so that tags are restacked in \
order of longest running', () ->
string = new HTMLString.String(quotes.Gates)
string.optimize()
expect(string.html()).toBe '''<q data-example><b>We all</b> need people who will give us feedback. That's how we improve. <a href="#"><img src="bill-gates.jpg"></a></q>'''
describe 'HTMLString.String.slice()', () ->
it 'should extract a section of a string and return a new string', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
newString = string.slice(10, 19)
expect(newString.html()).toBe '''<q>nows that</q>'''
describe 'HTMLString.String.split()', () ->
it 'should split a string by the separator and return a list of \
sub-strings', () ->
string = new HTMLString.String(' ', true)
substrings = string.split(' ')
expect(substrings.length).toBe 2
expect(substrings[0].length()).toBe 0
expect(substrings[1].length()).toBe 0
string = new HTMLString.String(quotes.Kernighan).trim()
substrings = string.split('a')
expect(substrings.length).toBe 11
substrings = string.split('@@')
expect(substrings.length).toBe 1
substrings = string.split(
new HTMLString.String(
'<q><span class="question"><b>e</b></span></q>'
)
)
expect(substrings.length).toBe 2
describe 'HTMLString.String.startsWith()', () ->
it 'should return true if a string starts with a substring.`', () ->
string = new HTMLString.String(quotes.Turing)
substring = new HTMLString.String(
'<q id="turings-quote">Machines take</q>'
)
expect(string.startsWith("Machines take")).toBe true
expect(string.startsWith(substring)).toBe true
describe 'HTMLString.String.substr()', () ->
it 'should return a subset of a string from an offset for a specified \
length`', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
newString = string.substr(10, 9)
expect(newString.html()).toBe '''<q>nows that</q>'''
describe 'HTMLString.String.substring()', () ->
it 'should return a subset of a string between 2 indexes`', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
newString = string.substring(10, 19)
expect(newString.html()).toBe '''<q>nows that</q>'''
describe 'HTMLString.String.toLowerCase()', () ->
it 'should return a copy of a string converted to lower case.`', () ->
string = new HTMLString.String(quotes.Turing)
newString = string.toLowerCase()
expect(newString.html()).toBe '''<q id="turings-quote">machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency.</i></q>'''
describe 'HTMLString.String.toUpperCase()', () ->
it 'should return a copy of a string converted to upper case.`', () ->
string = new HTMLString.String(quotes.Turing)
newString = string.toUpperCase()
expect(newString.html()).toBe '''<q id="turings-quote">MACHINES TAKE ME BY <br> <span class="suprised">SURPRISE</span> WITH <i>GREAT FREQUENCY.</i></q>'''
describe 'HTMLString.String.trim()', () ->
it 'should return a copy of a string converted with whitespaces trimmed \
from both ends.`', () ->
string = new HTMLString.String(quotes.Kernighan)
newString = string.trim()
expect(newString.characters[0].isWhitespace()).toBe false
expect(
newString.characters[newString.length() - 1].isWhitespace()
).toBe false
describe 'HTMLString.String.trimLeft()', () ->
it 'should return a copy of a string converted with whitespaces trimmed \
from the left.`', () ->
string = new HTMLString.String(quotes.Kernighan)
newString = string.trimLeft()
expect(newString.characters[0].isWhitespace()).toBe false
expect(
newString.characters[newString.length() - 1].isWhitespace()
).toBe true
describe 'HTMLString.String.trimRight)', () ->
it 'should return a copy of a string converted with whitespaces trimmed \
from the left.`', () ->
string = new HTMLString.String(quotes.Kernighan)
newString = string.trimRight()
expect(newString.characters[0].isWhitespace()).toBe true
expect(
newString.characters[newString.length() - 1].isWhitespace()
).toBe false
describe 'HTMLString.String.unformat()', () ->
it 'should return a sting unformatted (no tags)', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
# Test clearing tags individually
clearEachString = string.unformat(
0,
-1,
new HTMLString.Tag('q'),
new HTMLString.Tag('span', {class: 'question'}),
new HTMLString.Tag('b')
)
expect(clearEachString.html()).toBe string.text()
# Test clearing tags by name
clearEachString = string.unformat(0, -1, 'q', 'span', 'b')
expect(clearEachString.html()).toBe string.text()
# Test clearing all tags in one go
clearAllString = string.unformat(0, -1)
expect(clearAllString.html()).toBe string.text() | 114360 | quotes = {
<NAME>: '''<!-- --><b><!-- Comments are ignored --><q data-example>We all</q></b><q data-example> need people who will give us feedback. That's how we improve. <a href="#"><img src="bill-gates.jpg"></a></q>'''
<NAME>an: ''' <q>
Everyone knows that debugging is twice as hard as writing a program in
the first place. So if you're as clever as you can be when you write
it, <span class="question">how will you ever <b>debug</b> it?</span>
</q> '''
<NAME>: '''
I can't recall any difficulty in making the C language definition completely
open - any discussion on the matter tended to mention languages whose
inventors tried to keep tight control, and consequent ill fate.'''
Turing: '''
<q id="turings-quote">Machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency.</i></q>
'''
Wozniak: '''
all the best people in life seem to like LINUX.
'''
WozniakNamespaced: '''
all the best people in life seem to like <ns:tag ns:attr="foo">LINUX</ns:tag>.
'''
WozniakWhitespace: '''
all the best people in life seem to like LINUX.
'''
AmbiguousAmpersand: '''
& &<a href="/foo?bar=1&zee=2&omm=3&end">amp</a> &foo && && &end
'''
}
describe 'HTMLString.String()', () ->
it 'should parse and render text (no HTML)', () ->
string = new HTMLString.String(quotes.Wozniak)
expect(string.text()).toBe quotes.Wozniak
it 'should parse and render text (no HTML with whitespace preserved)', () ->
string = new HTMLString.String(quotes.WozniakWhitespace, true)
expect(string.text()).toBe quotes.WozniakWhitespace
it 'should parse and render a string (HTML)', () ->
string = new HTMLString.String(quotes.Turing)
expect(string.html()).toBe quotes.Turing
# Check names spaced tags are supported
string = new HTMLString.String(quotes.WozniakNamespaced)
expect(string.html()).toBe quotes.WozniakNamespaced
it 'should parse and render a string (HTML with ambiguous ampersands)', () ->
string = new HTMLString.String(quotes.AmbiguousAmpersand)
expect(string.html()).toBe quotes.AmbiguousAmpersand
console.log string.html()
describe 'HTMLString.String.isWhitespace()', () ->
it 'should return true if a string consists entirely of whitespace \
characters', () ->
string = new HTMLString.String(" <br>")
expect(string.isWhitespace()).toBe true
it 'should return false if a string contains any non-whitespace \
character', () ->
string = new HTMLString.String(" a <br>")
expect(string.isWhitespace()).toBe false
describe 'HTMLString.String.length()', () ->
it 'should return the length of a string', () ->
string = new HTMLString.String(quotes.Turing)
expect(string.length()).toBe 52
describe 'HTMLString.String.preserveWhitespace()', () ->
it 'should return the true if whitespace is reserved for the string', () ->
# Not preserved
string = new HTMLString.String(quotes.Turing)
expect(string.preserveWhitespace()).toBe false
# Preserved
string = new HTMLString.String(quotes.Turing, true)
expect(string.preserveWhitespace()).toBe true
describe 'HTMLString.String.capitalize()', () ->
it 'should capitalize the first character of a string', () ->
string = new HTMLString.String(quotes.Wozniak)
newString = string.capitalize()
expect(newString.charAt(0).c()).toBe 'A'
describe 'HTMLString.String.charAt()', () ->
it 'should return a character from a string at the specified index', () ->
string = new HTMLString.String(quotes.Turing)
expect(string.charAt(18).c()).toBe 'y'
describe 'HTMLString.String.concat()', () ->
it 'should combine 2 or more strings and return a new string', () ->
stringA = new HTMLString.String(quotes.Turing)
stringB = new HTMLString.String(quotes.Wozniak)
newString = stringA.concat(stringB)
expect(newString.html()).toBe '''<q id="turings-quote">Machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency.all the best people in life seem to like LINUX.</i></q>'''
describe 'HTMLString.String.contain()', () ->
it 'should return true if a string contains a substring', () ->
string = new HTMLString.String(quotes.Turing)
substring = new HTMLString.String('<q id="turings-quote">take me</q>')
expect(string.contains('take me')).toBe true
expect(string.contains(substring)).toBe true
describe 'HTMLString.String.endswith()', () ->
it 'should return true if a string ends with a substring.`', () ->
string = new HTMLString.String(quotes.Turing)
substring = new HTMLString.String(
'<q id="turings-quote"><i>great frequency.</i></q>'
)
expect(
string.endsWith(
"great#{ HTMLString.String.decode(' ') }frequency."
)
).toBe true
expect(string.endsWith(substring)).toBe true
describe 'HTMLString.String.format()', () ->
it 'should format a selection of characters in a string (add tags)', () ->
string = new HTMLString.String(quotes.Ritchie)
string = string.format(0, -1, new HTMLString.Tag('q'))
string = string.format(
19,
29,
new HTMLString.Tag('a', {href: 'http://www.getme.co.uk'}),
new HTMLString.Tag('b')
)
expect(string.html()).toBe """
<q>I can't recall any <a href="http://www.getme.co.uk"><b>difficulty</b></a> in making the C language definition completely open - any discussion on the matter tended to mention languages whose inventors tried to keep tight control, and consequent ill fate.</q>
""".trim()
describe 'HTMLString.String.hasTags()', () ->
it 'should return true if the string has and characters formatted with the \
specifed tags', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
expect(
string.hasTags(
new HTMLString.Tag('q'),
'b'
)
).toBe true
expect(string.hasTags(new HTMLString.Tag('q')), true).toBe true
describe 'HTMLString.String.indexOf()', () ->
it 'should return the first position of an substring in another string, \
or -1 if there is no match', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
substring = new HTMLString.String('<q>debugging</q>')
expect(string.indexOf('debugging')).toBe 20
expect(string.indexOf(substring)).toBe 20
expect(string.indexOf(substring, 30)).toBe -1
describe 'HTMLString.String.insert()', () ->
it 'should insert a string into another string and return a new \
string', () ->
stringA = new HTMLString.String(quotes.Kernighan).trim()
stringB = new HTMLString.String(quotes.Turing)
# Inherit formatting
newString = stringA.insert(9, stringB)
newString = newString.insert(9 + stringB.length(), ' - new string inserted - ')
expect(newString.html()).toBe '''<q>Everyone <q id="turings-quote">Machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency. - new string inserted - </i></q>knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, <span class="question">how will you ever <b>debug</b> it?</span></q>'''
# Do not inherit formatting
newString = stringA.insert(9, ' - insert unformatted string - ', false)
expect(newString.html()).toBe '''<q>Everyone </q> - insert unformatted string - <q>knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, <span class="question">how will you ever <b>debug</b> it?</span></q>'''
describe 'HTMLString.String.lastIndexOf()', () ->
it 'should return the last position of an substring in another string, \
or -1 if there is no match', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
substring = new HTMLString.String('<q>debugging</q>')
expect(string.lastIndexOf('debugging')).toBe 142
expect(string.lastIndexOf(substring)).toBe 142
expect(string.lastIndexOf(substring, 30)).toBe -1
describe 'HTMLString.String.optimize()', () ->
it 'should optimize the string (in place) so that tags are restacked in \
order of longest running', () ->
string = new HTMLString.String(quotes.Gates)
string.optimize()
expect(string.html()).toBe '''<q data-example><b>We all</b> need people who will give us feedback. That's how we improve. <a href="#"><img src="bill-gates.jpg"></a></q>'''
describe 'HTMLString.String.slice()', () ->
it 'should extract a section of a string and return a new string', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
newString = string.slice(10, 19)
expect(newString.html()).toBe '''<q>nows that</q>'''
describe 'HTMLString.String.split()', () ->
it 'should split a string by the separator and return a list of \
sub-strings', () ->
string = new HTMLString.String(' ', true)
substrings = string.split(' ')
expect(substrings.length).toBe 2
expect(substrings[0].length()).toBe 0
expect(substrings[1].length()).toBe 0
string = new HTMLString.String(quotes.Kernighan).trim()
substrings = string.split('a')
expect(substrings.length).toBe 11
substrings = string.split('@@')
expect(substrings.length).toBe 1
substrings = string.split(
new HTMLString.String(
'<q><span class="question"><b>e</b></span></q>'
)
)
expect(substrings.length).toBe 2
describe 'HTMLString.String.startsWith()', () ->
it 'should return true if a string starts with a substring.`', () ->
string = new HTMLString.String(quotes.Turing)
substring = new HTMLString.String(
'<q id="turings-quote">Machines take</q>'
)
expect(string.startsWith("Machines take")).toBe true
expect(string.startsWith(substring)).toBe true
describe 'HTMLString.String.substr()', () ->
it 'should return a subset of a string from an offset for a specified \
length`', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
newString = string.substr(10, 9)
expect(newString.html()).toBe '''<q>nows that</q>'''
describe 'HTMLString.String.substring()', () ->
it 'should return a subset of a string between 2 indexes`', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
newString = string.substring(10, 19)
expect(newString.html()).toBe '''<q>nows that</q>'''
describe 'HTMLString.String.toLowerCase()', () ->
it 'should return a copy of a string converted to lower case.`', () ->
string = new HTMLString.String(quotes.Turing)
newString = string.toLowerCase()
expect(newString.html()).toBe '''<q id="turings-quote">machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency.</i></q>'''
describe 'HTMLString.String.toUpperCase()', () ->
it 'should return a copy of a string converted to upper case.`', () ->
string = new HTMLString.String(quotes.Turing)
newString = string.toUpperCase()
expect(newString.html()).toBe '''<q id="turings-quote">MACHINES TAKE ME BY <br> <span class="suprised">SURPRISE</span> WITH <i>GREAT FREQUENCY.</i></q>'''
describe 'HTMLString.String.trim()', () ->
it 'should return a copy of a string converted with whitespaces trimmed \
from both ends.`', () ->
string = new HTMLString.String(quotes.Kernighan)
newString = string.trim()
expect(newString.characters[0].isWhitespace()).toBe false
expect(
newString.characters[newString.length() - 1].isWhitespace()
).toBe false
describe 'HTMLString.String.trimLeft()', () ->
it 'should return a copy of a string converted with whitespaces trimmed \
from the left.`', () ->
string = new HTMLString.String(quotes.Kernighan)
newString = string.trimLeft()
expect(newString.characters[0].isWhitespace()).toBe false
expect(
newString.characters[newString.length() - 1].isWhitespace()
).toBe true
describe 'HTMLString.String.trimRight)', () ->
it 'should return a copy of a string converted with whitespaces trimmed \
from the left.`', () ->
string = new HTMLString.String(quotes.Kernighan)
newString = string.trimRight()
expect(newString.characters[0].isWhitespace()).toBe true
expect(
newString.characters[newString.length() - 1].isWhitespace()
).toBe false
describe 'HTMLString.String.unformat()', () ->
it 'should return a sting unformatted (no tags)', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
# Test clearing tags individually
clearEachString = string.unformat(
0,
-1,
new HTMLString.Tag('q'),
new HTMLString.Tag('span', {class: 'question'}),
new HTMLString.Tag('b')
)
expect(clearEachString.html()).toBe string.text()
# Test clearing tags by name
clearEachString = string.unformat(0, -1, 'q', 'span', 'b')
expect(clearEachString.html()).toBe string.text()
# Test clearing all tags in one go
clearAllString = string.unformat(0, -1)
expect(clearAllString.html()).toBe string.text() | true | quotes = {
PI:NAME:<NAME>END_PI: '''<!-- --><b><!-- Comments are ignored --><q data-example>We all</q></b><q data-example> need people who will give us feedback. That's how we improve. <a href="#"><img src="bill-gates.jpg"></a></q>'''
PI:NAME:<NAME>END_PIan: ''' <q>
Everyone knows that debugging is twice as hard as writing a program in
the first place. So if you're as clever as you can be when you write
it, <span class="question">how will you ever <b>debug</b> it?</span>
</q> '''
PI:NAME:<NAME>END_PI: '''
I can't recall any difficulty in making the C language definition completely
open - any discussion on the matter tended to mention languages whose
inventors tried to keep tight control, and consequent ill fate.'''
Turing: '''
<q id="turings-quote">Machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency.</i></q>
'''
Wozniak: '''
all the best people in life seem to like LINUX.
'''
WozniakNamespaced: '''
all the best people in life seem to like <ns:tag ns:attr="foo">LINUX</ns:tag>.
'''
WozniakWhitespace: '''
all the best people in life seem to like LINUX.
'''
AmbiguousAmpersand: '''
& &<a href="/foo?bar=1&zee=2&omm=3&end">amp</a> &foo && && &end
'''
}
describe 'HTMLString.String()', () ->
it 'should parse and render text (no HTML)', () ->
string = new HTMLString.String(quotes.Wozniak)
expect(string.text()).toBe quotes.Wozniak
it 'should parse and render text (no HTML with whitespace preserved)', () ->
string = new HTMLString.String(quotes.WozniakWhitespace, true)
expect(string.text()).toBe quotes.WozniakWhitespace
it 'should parse and render a string (HTML)', () ->
string = new HTMLString.String(quotes.Turing)
expect(string.html()).toBe quotes.Turing
# Check names spaced tags are supported
string = new HTMLString.String(quotes.WozniakNamespaced)
expect(string.html()).toBe quotes.WozniakNamespaced
it 'should parse and render a string (HTML with ambiguous ampersands)', () ->
string = new HTMLString.String(quotes.AmbiguousAmpersand)
expect(string.html()).toBe quotes.AmbiguousAmpersand
console.log string.html()
describe 'HTMLString.String.isWhitespace()', () ->
it 'should return true if a string consists entirely of whitespace \
characters', () ->
string = new HTMLString.String(" <br>")
expect(string.isWhitespace()).toBe true
it 'should return false if a string contains any non-whitespace \
character', () ->
string = new HTMLString.String(" a <br>")
expect(string.isWhitespace()).toBe false
describe 'HTMLString.String.length()', () ->
it 'should return the length of a string', () ->
string = new HTMLString.String(quotes.Turing)
expect(string.length()).toBe 52
describe 'HTMLString.String.preserveWhitespace()', () ->
it 'should return the true if whitespace is reserved for the string', () ->
# Not preserved
string = new HTMLString.String(quotes.Turing)
expect(string.preserveWhitespace()).toBe false
# Preserved
string = new HTMLString.String(quotes.Turing, true)
expect(string.preserveWhitespace()).toBe true
describe 'HTMLString.String.capitalize()', () ->
it 'should capitalize the first character of a string', () ->
string = new HTMLString.String(quotes.Wozniak)
newString = string.capitalize()
expect(newString.charAt(0).c()).toBe 'A'
describe 'HTMLString.String.charAt()', () ->
it 'should return a character from a string at the specified index', () ->
string = new HTMLString.String(quotes.Turing)
expect(string.charAt(18).c()).toBe 'y'
describe 'HTMLString.String.concat()', () ->
it 'should combine 2 or more strings and return a new string', () ->
stringA = new HTMLString.String(quotes.Turing)
stringB = new HTMLString.String(quotes.Wozniak)
newString = stringA.concat(stringB)
expect(newString.html()).toBe '''<q id="turings-quote">Machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency.all the best people in life seem to like LINUX.</i></q>'''
describe 'HTMLString.String.contain()', () ->
it 'should return true if a string contains a substring', () ->
string = new HTMLString.String(quotes.Turing)
substring = new HTMLString.String('<q id="turings-quote">take me</q>')
expect(string.contains('take me')).toBe true
expect(string.contains(substring)).toBe true
describe 'HTMLString.String.endswith()', () ->
it 'should return true if a string ends with a substring.`', () ->
string = new HTMLString.String(quotes.Turing)
substring = new HTMLString.String(
'<q id="turings-quote"><i>great frequency.</i></q>'
)
expect(
string.endsWith(
"great#{ HTMLString.String.decode(' ') }frequency."
)
).toBe true
expect(string.endsWith(substring)).toBe true
describe 'HTMLString.String.format()', () ->
it 'should format a selection of characters in a string (add tags)', () ->
string = new HTMLString.String(quotes.Ritchie)
string = string.format(0, -1, new HTMLString.Tag('q'))
string = string.format(
19,
29,
new HTMLString.Tag('a', {href: 'http://www.getme.co.uk'}),
new HTMLString.Tag('b')
)
expect(string.html()).toBe """
<q>I can't recall any <a href="http://www.getme.co.uk"><b>difficulty</b></a> in making the C language definition completely open - any discussion on the matter tended to mention languages whose inventors tried to keep tight control, and consequent ill fate.</q>
""".trim()
describe 'HTMLString.String.hasTags()', () ->
it 'should return true if the string has and characters formatted with the \
specifed tags', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
expect(
string.hasTags(
new HTMLString.Tag('q'),
'b'
)
).toBe true
expect(string.hasTags(new HTMLString.Tag('q')), true).toBe true
describe 'HTMLString.String.indexOf()', () ->
it 'should return the first position of an substring in another string, \
or -1 if there is no match', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
substring = new HTMLString.String('<q>debugging</q>')
expect(string.indexOf('debugging')).toBe 20
expect(string.indexOf(substring)).toBe 20
expect(string.indexOf(substring, 30)).toBe -1
describe 'HTMLString.String.insert()', () ->
it 'should insert a string into another string and return a new \
string', () ->
stringA = new HTMLString.String(quotes.Kernighan).trim()
stringB = new HTMLString.String(quotes.Turing)
# Inherit formatting
newString = stringA.insert(9, stringB)
newString = newString.insert(9 + stringB.length(), ' - new string inserted - ')
expect(newString.html()).toBe '''<q>Everyone <q id="turings-quote">Machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency. - new string inserted - </i></q>knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, <span class="question">how will you ever <b>debug</b> it?</span></q>'''
# Do not inherit formatting
newString = stringA.insert(9, ' - insert unformatted string - ', false)
expect(newString.html()).toBe '''<q>Everyone </q> - insert unformatted string - <q>knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, <span class="question">how will you ever <b>debug</b> it?</span></q>'''
describe 'HTMLString.String.lastIndexOf()', () ->
it 'should return the last position of an substring in another string, \
or -1 if there is no match', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
substring = new HTMLString.String('<q>debugging</q>')
expect(string.lastIndexOf('debugging')).toBe 142
expect(string.lastIndexOf(substring)).toBe 142
expect(string.lastIndexOf(substring, 30)).toBe -1
describe 'HTMLString.String.optimize()', () ->
it 'should optimize the string (in place) so that tags are restacked in \
order of longest running', () ->
string = new HTMLString.String(quotes.Gates)
string.optimize()
expect(string.html()).toBe '''<q data-example><b>We all</b> need people who will give us feedback. That's how we improve. <a href="#"><img src="bill-gates.jpg"></a></q>'''
describe 'HTMLString.String.slice()', () ->
it 'should extract a section of a string and return a new string', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
newString = string.slice(10, 19)
expect(newString.html()).toBe '''<q>nows that</q>'''
describe 'HTMLString.String.split()', () ->
it 'should split a string by the separator and return a list of \
sub-strings', () ->
string = new HTMLString.String(' ', true)
substrings = string.split(' ')
expect(substrings.length).toBe 2
expect(substrings[0].length()).toBe 0
expect(substrings[1].length()).toBe 0
string = new HTMLString.String(quotes.Kernighan).trim()
substrings = string.split('a')
expect(substrings.length).toBe 11
substrings = string.split('@@')
expect(substrings.length).toBe 1
substrings = string.split(
new HTMLString.String(
'<q><span class="question"><b>e</b></span></q>'
)
)
expect(substrings.length).toBe 2
describe 'HTMLString.String.startsWith()', () ->
it 'should return true if a string starts with a substring.`', () ->
string = new HTMLString.String(quotes.Turing)
substring = new HTMLString.String(
'<q id="turings-quote">Machines take</q>'
)
expect(string.startsWith("Machines take")).toBe true
expect(string.startsWith(substring)).toBe true
describe 'HTMLString.String.substr()', () ->
it 'should return a subset of a string from an offset for a specified \
length`', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
newString = string.substr(10, 9)
expect(newString.html()).toBe '''<q>nows that</q>'''
describe 'HTMLString.String.substring()', () ->
it 'should return a subset of a string between 2 indexes`', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
newString = string.substring(10, 19)
expect(newString.html()).toBe '''<q>nows that</q>'''
describe 'HTMLString.String.toLowerCase()', () ->
it 'should return a copy of a string converted to lower case.`', () ->
string = new HTMLString.String(quotes.Turing)
newString = string.toLowerCase()
expect(newString.html()).toBe '''<q id="turings-quote">machines take me by <br> <span class="suprised">surprise</span> with <i>great frequency.</i></q>'''
describe 'HTMLString.String.toUpperCase()', () ->
it 'should return a copy of a string converted to upper case.`', () ->
string = new HTMLString.String(quotes.Turing)
newString = string.toUpperCase()
expect(newString.html()).toBe '''<q id="turings-quote">MACHINES TAKE ME BY <br> <span class="suprised">SURPRISE</span> WITH <i>GREAT FREQUENCY.</i></q>'''
describe 'HTMLString.String.trim()', () ->
it 'should return a copy of a string converted with whitespaces trimmed \
from both ends.`', () ->
string = new HTMLString.String(quotes.Kernighan)
newString = string.trim()
expect(newString.characters[0].isWhitespace()).toBe false
expect(
newString.characters[newString.length() - 1].isWhitespace()
).toBe false
describe 'HTMLString.String.trimLeft()', () ->
it 'should return a copy of a string converted with whitespaces trimmed \
from the left.`', () ->
string = new HTMLString.String(quotes.Kernighan)
newString = string.trimLeft()
expect(newString.characters[0].isWhitespace()).toBe false
expect(
newString.characters[newString.length() - 1].isWhitespace()
).toBe true
describe 'HTMLString.String.trimRight)', () ->
it 'should return a copy of a string converted with whitespaces trimmed \
from the left.`', () ->
string = new HTMLString.String(quotes.Kernighan)
newString = string.trimRight()
expect(newString.characters[0].isWhitespace()).toBe true
expect(
newString.characters[newString.length() - 1].isWhitespace()
).toBe false
describe 'HTMLString.String.unformat()', () ->
it 'should return a sting unformatted (no tags)', () ->
string = new HTMLString.String(quotes.Kernighan).trim()
# Test clearing tags individually
clearEachString = string.unformat(
0,
-1,
new HTMLString.Tag('q'),
new HTMLString.Tag('span', {class: 'question'}),
new HTMLString.Tag('b')
)
expect(clearEachString.html()).toBe string.text()
# Test clearing tags by name
clearEachString = string.unformat(0, -1, 'q', 'span', 'b')
expect(clearEachString.html()).toBe string.text()
# Test clearing all tags in one go
clearAllString = string.unformat(0, -1)
expect(clearAllString.html()).toBe string.text() |
[
{
"context": " than using a coin.\r\n#\r\n# Examples:\r\n#\r\n# decide \"Vodka Tonic\" \"Tom Collins\" \"Rum & Coke\"\r\n# decide \"Stay in be",
"end": 248,
"score": 0.9998594522476196,
"start": 237,
"tag": "NAME",
"value": "Vodka Tonic"
},
{
"context": "coin.\r\n#\r\n# Examples:\r\n#\r\n# decide \"Vodka Tonic\" \"Tom Collins\" \"Rum & Coke\"\r\n# decide \"Stay in bed like a lazy ",
"end": 262,
"score": 0.9998605251312256,
"start": 251,
"tag": "NAME",
"value": "Tom Collins"
},
{
"context": "amples:\r\n#\r\n# decide \"Vodka Tonic\" \"Tom Collins\" \"Rum & Coke\"\r\n# decide \"Stay in bed like a lazy bastard\" \"You",
"end": 275,
"score": 0.9719489216804504,
"start": 265,
"tag": "NAME",
"value": "Rum & Coke"
}
] | src/scripts/decide.coffee | aroben/hubot-scripts | 0 | # Allows Hubot to help you decide between multiple options.
#
# decide "<option1>" "<option2>" "<optionx>" - Randomly picks an option.
# More fun than using a coin.
#
# Examples:
#
# decide "Vodka Tonic" "Tom Collins" "Rum & Coke"
# decide "Stay in bed like a lazy bastard" "You have shit to code, get up!"
#
module.exports = (robot) ->
robot.respond /decide "(.*)"/i, (msg) ->
options = msg.match[1].split('" "')
msg.reply("Definitely \"#{ msg.random options }\".") | 143404 | # Allows Hubot to help you decide between multiple options.
#
# decide "<option1>" "<option2>" "<optionx>" - Randomly picks an option.
# More fun than using a coin.
#
# Examples:
#
# decide "<NAME>" "<NAME>" "<NAME>"
# decide "Stay in bed like a lazy bastard" "You have shit to code, get up!"
#
module.exports = (robot) ->
robot.respond /decide "(.*)"/i, (msg) ->
options = msg.match[1].split('" "')
msg.reply("Definitely \"#{ msg.random options }\".") | true | # Allows Hubot to help you decide between multiple options.
#
# decide "<option1>" "<option2>" "<optionx>" - Randomly picks an option.
# More fun than using a coin.
#
# Examples:
#
# decide "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"
# decide "Stay in bed like a lazy bastard" "You have shit to code, get up!"
#
module.exports = (robot) ->
robot.respond /decide "(.*)"/i, (msg) ->
options = msg.match[1].split('" "')
msg.reply("Definitely \"#{ msg.random options }\".") |
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9992642402648926,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-net-listen-fd0.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
gotError = false
process.on "exit", ->
assert gotError instanceof Error
return
# this should fail with an async EINVAL error, not throw an exception
net.createServer(assert.fail).listen(fd: 0).on "error", (e) ->
switch e.code
when "EINVAL", "ENOTSOCK"
gotError = e
| 99594 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
gotError = false
process.on "exit", ->
assert gotError instanceof Error
return
# this should fail with an async EINVAL error, not throw an exception
net.createServer(assert.fail).listen(fd: 0).on "error", (e) ->
switch e.code
when "EINVAL", "ENOTSOCK"
gotError = e
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
gotError = false
process.on "exit", ->
assert gotError instanceof Error
return
# this should fail with an async EINVAL error, not throw an exception
net.createServer(assert.fail).listen(fd: 0).on "error", (e) ->
switch e.code
when "EINVAL", "ENOTSOCK"
gotError = e
|
[
{
"context": " tytoData =\n dummy: \"yes\"\n name: \"test\"\n tyto.prototype.saveBarn JSON.stringify tyt",
"end": 566,
"score": 0.9929855465888977,
"start": 562,
"tag": "NAME",
"value": "test"
}
] | src/coffeescript/test.coffee | logorrhea/tyto | 0 | describe "tyto", ->
describe "tyto initialization", ->
it "should be available as a function", ->
expect(typeof(window.tyto)).to.equal "function"
return
return
describe "tyto actions", ->
it "should remove tyto data from localStorage using deleteSave", ->
window.localStorage.setItem "tyto", {}
tyto.prototype.deleteSave()
expect(typeof(window.localStorage.tyto)).to.equal "undefined"
return
it "should add tyto data to localStorage using saveBarn", ->
tytoData =
dummy: "yes"
name: "test"
tyto.prototype.saveBarn JSON.stringify tytoData
expect(window.localStorage.tyto).to.equal JSON.stringify tytoData
return
it "should encode tyto escapes with _encodeJSON", ->
tytoJSON = """{"hashes":"#"}"""
expect("""{"hashes":"@tyto-hash"}""")
.to.equal tyto.prototype._encodeJSON tytoJSON
return
it "should decode tyto escapes with _decodeJSON", ->
tytoJSON = """{"hashes":"@tyto-hash"}"""
expect("""{"hashes":"#"}""")
.to.equal tyto.prototype._decodeJSON tytoJSON
return
return
return
| 205403 | describe "tyto", ->
describe "tyto initialization", ->
it "should be available as a function", ->
expect(typeof(window.tyto)).to.equal "function"
return
return
describe "tyto actions", ->
it "should remove tyto data from localStorage using deleteSave", ->
window.localStorage.setItem "tyto", {}
tyto.prototype.deleteSave()
expect(typeof(window.localStorage.tyto)).to.equal "undefined"
return
it "should add tyto data to localStorage using saveBarn", ->
tytoData =
dummy: "yes"
name: "<NAME>"
tyto.prototype.saveBarn JSON.stringify tytoData
expect(window.localStorage.tyto).to.equal JSON.stringify tytoData
return
it "should encode tyto escapes with _encodeJSON", ->
tytoJSON = """{"hashes":"#"}"""
expect("""{"hashes":"@tyto-hash"}""")
.to.equal tyto.prototype._encodeJSON tytoJSON
return
it "should decode tyto escapes with _decodeJSON", ->
tytoJSON = """{"hashes":"@tyto-hash"}"""
expect("""{"hashes":"#"}""")
.to.equal tyto.prototype._decodeJSON tytoJSON
return
return
return
| true | describe "tyto", ->
describe "tyto initialization", ->
it "should be available as a function", ->
expect(typeof(window.tyto)).to.equal "function"
return
return
describe "tyto actions", ->
it "should remove tyto data from localStorage using deleteSave", ->
window.localStorage.setItem "tyto", {}
tyto.prototype.deleteSave()
expect(typeof(window.localStorage.tyto)).to.equal "undefined"
return
it "should add tyto data to localStorage using saveBarn", ->
tytoData =
dummy: "yes"
name: "PI:NAME:<NAME>END_PI"
tyto.prototype.saveBarn JSON.stringify tytoData
expect(window.localStorage.tyto).to.equal JSON.stringify tytoData
return
it "should encode tyto escapes with _encodeJSON", ->
tytoJSON = """{"hashes":"#"}"""
expect("""{"hashes":"@tyto-hash"}""")
.to.equal tyto.prototype._encodeJSON tytoJSON
return
it "should decode tyto escapes with _decodeJSON", ->
tytoJSON = """{"hashes":"@tyto-hash"}"""
expect("""{"hashes":"#"}""")
.to.equal tyto.prototype._decodeJSON tytoJSON
return
return
return
|
[
{
"context": "ket_type: 'persona',\n bucket: 'persona',\n key: '078b80e8-7f79-481c-bd7c-a61a5d0a5203',\n vclock: 'a85hYGBgzGDKBVIcypz/fgZPu6SewZTImMfK",
"end": 1335,
"score": 0.9997695088386536,
"start": 1299,
"tag": "KEY",
"value": "078b80e8-7f79-481c-bd7c-a61a5d0a5203"
},
{
"context": " data: '{\"name\":\"Joukou Ltd\",\"agents\":[{\"key\":\"718ccee0-514c-4370-976d-6798e05d25cd\",\"role\":\"creator\"}]}' } ] }\n\nkeyData: {}\narg: {}\n",
"end": 1703,
"score": 0.9997541308403015,
"start": 1667,
"tag": "KEY",
"value": "718ccee0-514c-4370-976d-6798e05d25cd"
}
] | src/riak/mapred.coffee | joukou/joukou-api | 0 | # using search as an input to map/reduce
###*
Copyright 2014 Joukou Ltd
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.
###
request(
uri: 'http://localhost:8098/mapred'
method: 'POST'
json:
inputs:
module: 'yokozuna'
function: 'mapred_search'
arg: [ 'persona', 'agents.key:' + req.user.getKey() ]
query: [
{
map:
language: 'javascript'
keep: false
source: ( ( v, keyData, arg ) ->
ejsLog( '/tmp/map_reduce.log', JSON.stringify( arg ) )
return [ 1 ]
).toString()
}
{
reduce:
language: 'javascript'
keep: true
name: 'Riak.reduceSum'
}
]
, ( err, reply ) ->
res.send( 200, reply.body )
)
###
v:
{ bucket_type: 'persona',
bucket: 'persona',
key: '078b80e8-7f79-481c-bd7c-a61a5d0a5203',
vclock: 'a85hYGBgzGDKBVIcypz/fgZPu6SewZTImMfKwBHLfZYvCwA=',
values:
[ { metadata:
{ 'X-Riak-VTag': '4IXaKVVnMY7gSWYRqSXm8U',
'content-type': 'application/json',
index: [],
'X-Riak-Last-Modified': 'Tue, 10 Jun 2014 10:42:16 GMT' },
data: '{"name":"Joukou Ltd","agents":[{"key":"718ccee0-514c-4370-976d-6798e05d25cd","role":"creator"}]}' } ] }
keyData: {}
arg: {}
###
###
simple search (not mapred)
request(
uri: 'http://localhost:8098/search/persona?wt=json&q=agents.key:' + req.user.getKey()
, ( err, reply ) ->
res.send( 200, reply.body )
)
faulty:
{
reduce:
language: 'javascript'
keep: true
source: ( ( values, arg ) ->
for value in values
value._links = {}
value._links['joukou:agent'] = []
for agent in agents
value._links['joukou:agent'].push(
href: "/agent/#{agent.key}"
role: agent.role
)
values
).toString()
}
###
| 77531 | # using search as an input to map/reduce
###*
Copyright 2014 Joukou Ltd
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.
###
request(
uri: 'http://localhost:8098/mapred'
method: 'POST'
json:
inputs:
module: 'yokozuna'
function: 'mapred_search'
arg: [ 'persona', 'agents.key:' + req.user.getKey() ]
query: [
{
map:
language: 'javascript'
keep: false
source: ( ( v, keyData, arg ) ->
ejsLog( '/tmp/map_reduce.log', JSON.stringify( arg ) )
return [ 1 ]
).toString()
}
{
reduce:
language: 'javascript'
keep: true
name: 'Riak.reduceSum'
}
]
, ( err, reply ) ->
res.send( 200, reply.body )
)
###
v:
{ bucket_type: 'persona',
bucket: 'persona',
key: '<KEY>',
vclock: 'a85hYGBgzGDKBVIcypz/fgZPu6SewZTImMfKwBHLfZYvCwA=',
values:
[ { metadata:
{ 'X-Riak-VTag': '4IXaKVVnMY7gSWYRqSXm8U',
'content-type': 'application/json',
index: [],
'X-Riak-Last-Modified': 'Tue, 10 Jun 2014 10:42:16 GMT' },
data: '{"name":"Joukou Ltd","agents":[{"key":"<KEY>","role":"creator"}]}' } ] }
keyData: {}
arg: {}
###
###
simple search (not mapred)
request(
uri: 'http://localhost:8098/search/persona?wt=json&q=agents.key:' + req.user.getKey()
, ( err, reply ) ->
res.send( 200, reply.body )
)
faulty:
{
reduce:
language: 'javascript'
keep: true
source: ( ( values, arg ) ->
for value in values
value._links = {}
value._links['joukou:agent'] = []
for agent in agents
value._links['joukou:agent'].push(
href: "/agent/#{agent.key}"
role: agent.role
)
values
).toString()
}
###
| true | # using search as an input to map/reduce
###*
Copyright 2014 Joukou Ltd
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.
###
request(
uri: 'http://localhost:8098/mapred'
method: 'POST'
json:
inputs:
module: 'yokozuna'
function: 'mapred_search'
arg: [ 'persona', 'agents.key:' + req.user.getKey() ]
query: [
{
map:
language: 'javascript'
keep: false
source: ( ( v, keyData, arg ) ->
ejsLog( '/tmp/map_reduce.log', JSON.stringify( arg ) )
return [ 1 ]
).toString()
}
{
reduce:
language: 'javascript'
keep: true
name: 'Riak.reduceSum'
}
]
, ( err, reply ) ->
res.send( 200, reply.body )
)
###
v:
{ bucket_type: 'persona',
bucket: 'persona',
key: 'PI:KEY:<KEY>END_PI',
vclock: 'a85hYGBgzGDKBVIcypz/fgZPu6SewZTImMfKwBHLfZYvCwA=',
values:
[ { metadata:
{ 'X-Riak-VTag': '4IXaKVVnMY7gSWYRqSXm8U',
'content-type': 'application/json',
index: [],
'X-Riak-Last-Modified': 'Tue, 10 Jun 2014 10:42:16 GMT' },
data: '{"name":"Joukou Ltd","agents":[{"key":"PI:KEY:<KEY>END_PI","role":"creator"}]}' } ] }
keyData: {}
arg: {}
###
###
simple search (not mapred)
request(
uri: 'http://localhost:8098/search/persona?wt=json&q=agents.key:' + req.user.getKey()
, ( err, reply ) ->
res.send( 200, reply.body )
)
faulty:
{
reduce:
language: 'javascript'
keep: true
source: ( ( values, arg ) ->
for value in values
value._links = {}
value._links['joukou:agent'] = []
for agent in agents
value._links['joukou:agent'].push(
href: "/agent/#{agent.key}"
role: agent.role
)
values
).toString()
}
###
|
[
{
"context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\npanelContainerPath = atom.",
"end": 35,
"score": 0.9996797442436218,
"start": 21,
"tag": "NAME",
"value": "Jesse Grosjean"
}
] | atom/packages/foldingtext-for-atom/lib/extensions/ui/popovers.coffee | prookie/dotfiles-1 | 0 | # Copyright (c) 2015 Jesse Grosjean. All rights reserved.
panelContainerPath = atom.config.resourcePath + '/src/panel-container'
PanelContainer = require panelContainerPath
panelElementPath = atom.config.resourcePath + '/src/panel-element'
PanelElement = require panelElementPath
atom.workspace.panelContainers.popover = new PanelContainer({location: 'popover'})
workspaceElement = atom.views.getView(atom.workspace)
workspaceElement.panelContainers.popover = atom.views.getView(atom.workspace.panelContainers.popover)
workspaceElement.appendChild workspaceElement.panelContainers.popover
atom.workspace.panelContainers.popover.onDidAddPanel ({panel, index}) ->
schedulePositionPopovers()
panel.onDidChangeVisible (visible) ->
schedulePositionPopovers()
atom.workspace.getPopoverPanels = ->
atom.workspace.getPanels('popover')
atom.workspace.addPopoverPanel = (options) ->
panel = atom.workspace.addPanel('popover', options)
options ?= {}
panel.target = options.target
panel.viewport = options.viewport
panel.placement = options.placement or 'top'
schedulePositionPopovers()
panel
PanelElement.prototype.positionPopover = ->
unless target = @model.target
return
viewport = @model.viewport or workspaceElement
placement = @model.placement
panelRect = @getBoundingClientRect()
panelRect = # mutable
top: panelRect.top
bottom: panelRect.bottom
left: panelRect.left
right: panelRect.right
width: panelRect.width
height: panelRect.height
# Target can be a DOM element, a function that returns a rect, or a rect.
# If they target is dynamic then the popover is continuously positioned in
# a requestAnimationFrame loop until it's hidden.
if targetRect = target.getBoundingClientRect?()
schedulePositionPopovers()
else if targetRect ?= target?()
schedulePositionPopovers()
else
targetRect = target
# Target can be a DOM element, a function that returns a rect, or a rect.
# If they viewport is dynamic then the popover is continuously positioned
# in a requestAnimationFrame loop until it's hidden.
if viewportRect = viewport?.getBoundingClientRect?()
schedulePositionPopovers()
else if viewportRect ?= viewport?()
schedulePositionPopovers()
else
viewportRect = viewport
constraintedPlacement = placement
# Initial positioning and report when out of viewport
out = @positionPopoverRect panelRect, targetRect, viewportRect, placement
# Flip placement and reposition panel rect if out of viewport
if out.top and constraintedPlacement is 'top'
constraintedPlacement = 'bottom'
else if out.bottom and constraintedPlacement is 'bottom'
constraintedPlacement = 'top'
else if out.left and constraintedPlacement is 'left'
constraintedPlacement = 'right'
else if out.right and constraintedPlacement is 'right'
constraintedPlacement = 'left'
unless placement is constraintedPlacement
out = @positionPopoverRect panelRect, targetRect, viewportRect, constraintedPlacement
# Constrain panel rect to viewport
if out.top
panelRect.top = viewportRect.top
if out.bottom
panelRect.top = viewportRect.bottom - panelRect.height
if out.left
panelRect.left = viewportRect.left
if out.right
panelRect.left = viewportRect.right - panelRect.width
# Update panel top, left style if changed
unless @cachedTop is panelRect.top and @cachedLeft is panelRect.left
unless @_arrowDIV
@_arrowDIV = document.createElement 'div'
@_arrowDIV.classList.add 'arrow'
@insertBefore @_arrowDIV, @firstChild
arrowRect = @_arrowDIV.getBoundingClientRect()
if constraintedPlacement is 'top' or constraintedPlacement is 'bottom'
targetX = targetRect.left + (targetRect.width / 2.0)
left = (targetX - panelRect.left) - (arrowRect.width / 2.0)
@_arrowDIV.style.left = left + 'px'
else if constraintedPlacement is 'left' or constraintedPlacement is 'right'
targetY = targetRect.top + (targetRect.height / 2.0)
@_arrowDIV.style.top = (targetY - (arrowRect.height / 2.0)) + 'px'
@setAttribute 'data-arrow', constraintedPlacement
@style.top = panelRect.top + 'px'
@style.left = panelRect.left + 'px'
@cachedTop = panelRect.top
@cachedLeft = panelRect.left
PanelElement.prototype.positionPopoverRect = (panelRect, targetRect, viewportRect, placement) ->
switch placement
when 'top'
panelRect.top = targetRect.top - panelRect.height
panelRect.left = targetRect.left - ((panelRect.width - targetRect.width) / 2.0)
when 'bottom'
panelRect.top = targetRect.bottom
panelRect.left = targetRect.left - ((panelRect.width - targetRect.width) / 2.0)
when 'left'
panelRect.left = targetRect.left - panelRect.width
panelRect.top = targetRect.top - ((panelRect.height - targetRect.height) / 2.0)
when 'right'
panelRect.left = targetRect.right
panelRect.top = targetRect.top - ((panelRect.height - targetRect.height) / 2.0)
panelRect.bottom = panelRect.top + panelRect.height
panelRect.right = panelRect.left + panelRect.width
out = {}
if viewportRect
if panelRect.top < viewportRect.top
out['top'] = true
if panelRect.bottom > viewportRect.bottom
out['bottom'] = true
if panelRect.left < viewportRect.left
out['left'] = true
if panelRect.right > viewportRect.right
out['right'] = true
out
# Popover positioning is performed in a `requestAnimationFrame` loop when
# either of `target` or `viewport` are dynamic (ie functions or elements)
positionPopoversFrameID = null
schedulePositionPopovers = ->
unless positionPopoversFrameID
positionPopoversFrameID = window.requestAnimationFrame positionPopovers
positionPopovers = ->
positionPopoversFrameID = null
for panel in atom.workspace?.getPopoverPanels?() or []
if panel.isVisible()
atom.views.getView(panel).positionPopover() | 178327 | # Copyright (c) 2015 <NAME>. All rights reserved.
panelContainerPath = atom.config.resourcePath + '/src/panel-container'
PanelContainer = require panelContainerPath
panelElementPath = atom.config.resourcePath + '/src/panel-element'
PanelElement = require panelElementPath
atom.workspace.panelContainers.popover = new PanelContainer({location: 'popover'})
workspaceElement = atom.views.getView(atom.workspace)
workspaceElement.panelContainers.popover = atom.views.getView(atom.workspace.panelContainers.popover)
workspaceElement.appendChild workspaceElement.panelContainers.popover
atom.workspace.panelContainers.popover.onDidAddPanel ({panel, index}) ->
schedulePositionPopovers()
panel.onDidChangeVisible (visible) ->
schedulePositionPopovers()
atom.workspace.getPopoverPanels = ->
atom.workspace.getPanels('popover')
atom.workspace.addPopoverPanel = (options) ->
panel = atom.workspace.addPanel('popover', options)
options ?= {}
panel.target = options.target
panel.viewport = options.viewport
panel.placement = options.placement or 'top'
schedulePositionPopovers()
panel
PanelElement.prototype.positionPopover = ->
unless target = @model.target
return
viewport = @model.viewport or workspaceElement
placement = @model.placement
panelRect = @getBoundingClientRect()
panelRect = # mutable
top: panelRect.top
bottom: panelRect.bottom
left: panelRect.left
right: panelRect.right
width: panelRect.width
height: panelRect.height
# Target can be a DOM element, a function that returns a rect, or a rect.
# If they target is dynamic then the popover is continuously positioned in
# a requestAnimationFrame loop until it's hidden.
if targetRect = target.getBoundingClientRect?()
schedulePositionPopovers()
else if targetRect ?= target?()
schedulePositionPopovers()
else
targetRect = target
# Target can be a DOM element, a function that returns a rect, or a rect.
# If they viewport is dynamic then the popover is continuously positioned
# in a requestAnimationFrame loop until it's hidden.
if viewportRect = viewport?.getBoundingClientRect?()
schedulePositionPopovers()
else if viewportRect ?= viewport?()
schedulePositionPopovers()
else
viewportRect = viewport
constraintedPlacement = placement
# Initial positioning and report when out of viewport
out = @positionPopoverRect panelRect, targetRect, viewportRect, placement
# Flip placement and reposition panel rect if out of viewport
if out.top and constraintedPlacement is 'top'
constraintedPlacement = 'bottom'
else if out.bottom and constraintedPlacement is 'bottom'
constraintedPlacement = 'top'
else if out.left and constraintedPlacement is 'left'
constraintedPlacement = 'right'
else if out.right and constraintedPlacement is 'right'
constraintedPlacement = 'left'
unless placement is constraintedPlacement
out = @positionPopoverRect panelRect, targetRect, viewportRect, constraintedPlacement
# Constrain panel rect to viewport
if out.top
panelRect.top = viewportRect.top
if out.bottom
panelRect.top = viewportRect.bottom - panelRect.height
if out.left
panelRect.left = viewportRect.left
if out.right
panelRect.left = viewportRect.right - panelRect.width
# Update panel top, left style if changed
unless @cachedTop is panelRect.top and @cachedLeft is panelRect.left
unless @_arrowDIV
@_arrowDIV = document.createElement 'div'
@_arrowDIV.classList.add 'arrow'
@insertBefore @_arrowDIV, @firstChild
arrowRect = @_arrowDIV.getBoundingClientRect()
if constraintedPlacement is 'top' or constraintedPlacement is 'bottom'
targetX = targetRect.left + (targetRect.width / 2.0)
left = (targetX - panelRect.left) - (arrowRect.width / 2.0)
@_arrowDIV.style.left = left + 'px'
else if constraintedPlacement is 'left' or constraintedPlacement is 'right'
targetY = targetRect.top + (targetRect.height / 2.0)
@_arrowDIV.style.top = (targetY - (arrowRect.height / 2.0)) + 'px'
@setAttribute 'data-arrow', constraintedPlacement
@style.top = panelRect.top + 'px'
@style.left = panelRect.left + 'px'
@cachedTop = panelRect.top
@cachedLeft = panelRect.left
PanelElement.prototype.positionPopoverRect = (panelRect, targetRect, viewportRect, placement) ->
switch placement
when 'top'
panelRect.top = targetRect.top - panelRect.height
panelRect.left = targetRect.left - ((panelRect.width - targetRect.width) / 2.0)
when 'bottom'
panelRect.top = targetRect.bottom
panelRect.left = targetRect.left - ((panelRect.width - targetRect.width) / 2.0)
when 'left'
panelRect.left = targetRect.left - panelRect.width
panelRect.top = targetRect.top - ((panelRect.height - targetRect.height) / 2.0)
when 'right'
panelRect.left = targetRect.right
panelRect.top = targetRect.top - ((panelRect.height - targetRect.height) / 2.0)
panelRect.bottom = panelRect.top + panelRect.height
panelRect.right = panelRect.left + panelRect.width
out = {}
if viewportRect
if panelRect.top < viewportRect.top
out['top'] = true
if panelRect.bottom > viewportRect.bottom
out['bottom'] = true
if panelRect.left < viewportRect.left
out['left'] = true
if panelRect.right > viewportRect.right
out['right'] = true
out
# Popover positioning is performed in a `requestAnimationFrame` loop when
# either of `target` or `viewport` are dynamic (ie functions or elements)
positionPopoversFrameID = null
schedulePositionPopovers = ->
unless positionPopoversFrameID
positionPopoversFrameID = window.requestAnimationFrame positionPopovers
positionPopovers = ->
positionPopoversFrameID = null
for panel in atom.workspace?.getPopoverPanels?() or []
if panel.isVisible()
atom.views.getView(panel).positionPopover() | true | # Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved.
panelContainerPath = atom.config.resourcePath + '/src/panel-container'
PanelContainer = require panelContainerPath
panelElementPath = atom.config.resourcePath + '/src/panel-element'
PanelElement = require panelElementPath
atom.workspace.panelContainers.popover = new PanelContainer({location: 'popover'})
workspaceElement = atom.views.getView(atom.workspace)
workspaceElement.panelContainers.popover = atom.views.getView(atom.workspace.panelContainers.popover)
workspaceElement.appendChild workspaceElement.panelContainers.popover
atom.workspace.panelContainers.popover.onDidAddPanel ({panel, index}) ->
schedulePositionPopovers()
panel.onDidChangeVisible (visible) ->
schedulePositionPopovers()
atom.workspace.getPopoverPanels = ->
atom.workspace.getPanels('popover')
atom.workspace.addPopoverPanel = (options) ->
panel = atom.workspace.addPanel('popover', options)
options ?= {}
panel.target = options.target
panel.viewport = options.viewport
panel.placement = options.placement or 'top'
schedulePositionPopovers()
panel
PanelElement.prototype.positionPopover = ->
unless target = @model.target
return
viewport = @model.viewport or workspaceElement
placement = @model.placement
panelRect = @getBoundingClientRect()
panelRect = # mutable
top: panelRect.top
bottom: panelRect.bottom
left: panelRect.left
right: panelRect.right
width: panelRect.width
height: panelRect.height
# Target can be a DOM element, a function that returns a rect, or a rect.
# If they target is dynamic then the popover is continuously positioned in
# a requestAnimationFrame loop until it's hidden.
if targetRect = target.getBoundingClientRect?()
schedulePositionPopovers()
else if targetRect ?= target?()
schedulePositionPopovers()
else
targetRect = target
# Target can be a DOM element, a function that returns a rect, or a rect.
# If they viewport is dynamic then the popover is continuously positioned
# in a requestAnimationFrame loop until it's hidden.
if viewportRect = viewport?.getBoundingClientRect?()
schedulePositionPopovers()
else if viewportRect ?= viewport?()
schedulePositionPopovers()
else
viewportRect = viewport
constraintedPlacement = placement
# Initial positioning and report when out of viewport
out = @positionPopoverRect panelRect, targetRect, viewportRect, placement
# Flip placement and reposition panel rect if out of viewport
if out.top and constraintedPlacement is 'top'
constraintedPlacement = 'bottom'
else if out.bottom and constraintedPlacement is 'bottom'
constraintedPlacement = 'top'
else if out.left and constraintedPlacement is 'left'
constraintedPlacement = 'right'
else if out.right and constraintedPlacement is 'right'
constraintedPlacement = 'left'
unless placement is constraintedPlacement
out = @positionPopoverRect panelRect, targetRect, viewportRect, constraintedPlacement
# Constrain panel rect to viewport
if out.top
panelRect.top = viewportRect.top
if out.bottom
panelRect.top = viewportRect.bottom - panelRect.height
if out.left
panelRect.left = viewportRect.left
if out.right
panelRect.left = viewportRect.right - panelRect.width
# Update panel top, left style if changed
unless @cachedTop is panelRect.top and @cachedLeft is panelRect.left
unless @_arrowDIV
@_arrowDIV = document.createElement 'div'
@_arrowDIV.classList.add 'arrow'
@insertBefore @_arrowDIV, @firstChild
arrowRect = @_arrowDIV.getBoundingClientRect()
if constraintedPlacement is 'top' or constraintedPlacement is 'bottom'
targetX = targetRect.left + (targetRect.width / 2.0)
left = (targetX - panelRect.left) - (arrowRect.width / 2.0)
@_arrowDIV.style.left = left + 'px'
else if constraintedPlacement is 'left' or constraintedPlacement is 'right'
targetY = targetRect.top + (targetRect.height / 2.0)
@_arrowDIV.style.top = (targetY - (arrowRect.height / 2.0)) + 'px'
@setAttribute 'data-arrow', constraintedPlacement
@style.top = panelRect.top + 'px'
@style.left = panelRect.left + 'px'
@cachedTop = panelRect.top
@cachedLeft = panelRect.left
PanelElement.prototype.positionPopoverRect = (panelRect, targetRect, viewportRect, placement) ->
switch placement
when 'top'
panelRect.top = targetRect.top - panelRect.height
panelRect.left = targetRect.left - ((panelRect.width - targetRect.width) / 2.0)
when 'bottom'
panelRect.top = targetRect.bottom
panelRect.left = targetRect.left - ((panelRect.width - targetRect.width) / 2.0)
when 'left'
panelRect.left = targetRect.left - panelRect.width
panelRect.top = targetRect.top - ((panelRect.height - targetRect.height) / 2.0)
when 'right'
panelRect.left = targetRect.right
panelRect.top = targetRect.top - ((panelRect.height - targetRect.height) / 2.0)
panelRect.bottom = panelRect.top + panelRect.height
panelRect.right = panelRect.left + panelRect.width
out = {}
if viewportRect
if panelRect.top < viewportRect.top
out['top'] = true
if panelRect.bottom > viewportRect.bottom
out['bottom'] = true
if panelRect.left < viewportRect.left
out['left'] = true
if panelRect.right > viewportRect.right
out['right'] = true
out
# Popover positioning is performed in a `requestAnimationFrame` loop when
# either of `target` or `viewport` are dynamic (ie functions or elements)
positionPopoversFrameID = null
schedulePositionPopovers = ->
unless positionPopoversFrameID
positionPopoversFrameID = window.requestAnimationFrame positionPopovers
positionPopovers = ->
positionPopoversFrameID = null
for panel in atom.workspace?.getPopoverPanels?() or []
if panel.isVisible()
atom.views.getView(panel).positionPopover() |
[
{
"context": ".value? att\n params: {\n auth: { key: \"a6e2fe37faca47efa9a8f0f9c3c1a44d\" },\n steps: {\n files: {\n ",
"end": 1531,
"score": 0.9997563362121582,
"start": 1499,
"tag": "KEY",
"value": "a6e2fe37faca47efa9a8f0f9c3c1a44d"
}
] | app/browser/template/bindings/dataBind/uploadFile.coffee | mojo-js/mojojs.com | 0 | pc = require("paperclip")
bindable = require("bindable")
Url = require "url"
class UploadFileDataBinding extends pc.BaseAttrDataBinding
###
###
bind: () ->
super arguments...
###
###
_onChange: (options) ->
return unless process.browser
@onUpload = options.onUpload ? () ->
@progress = options.progress
@error = options.error
@attachment = options.attachment
return if @__initialized
@__initialized = true
$(this.node).attr("action", "#")
$(this.node).transloadit({
wait: true,
triggerUploadOnFileSelection: true,
autoSubmit: false,
modal: false,
onStart: () =>
@error?.value? undefined
@progress?.value? undefined
@attachment?.value? undefined
onProgress: (bytesReceived, bytesExpected) =>
@progress?.value? Math.floor bytesReceived / bytesExpected * 100
onError: (e) =>
@error?.value? e
@progress?.value? undefined
onResult: (type, data) =>
tracker.track "teacher_added_photo"
@progress?.value? undefined
return unless type is ":original"
@onUpload att = {
url: data.ssl_url,
path: Url.parse(data.ssl_url).pathname.substr(1),
name: data.name,
size: data.size,
type: if data.type is "image" then "photo" else "file",
contentType: data.mime
}
@attachment?.value? att
params: {
auth: { key: "a6e2fe37faca47efa9a8f0f9c3c1a44d" },
steps: {
files: {
robot: "/file/filter",
error_on_decline: true
},
thumb: {
robot: "/image/resize",
format: "png"
}
},
template_id: options.templateId || "bcdfda60184311e48c523f48f47bf7a1"
}
});
module.exports = UploadFileDataBinding
| 48131 | pc = require("paperclip")
bindable = require("bindable")
Url = require "url"
class UploadFileDataBinding extends pc.BaseAttrDataBinding
###
###
bind: () ->
super arguments...
###
###
_onChange: (options) ->
return unless process.browser
@onUpload = options.onUpload ? () ->
@progress = options.progress
@error = options.error
@attachment = options.attachment
return if @__initialized
@__initialized = true
$(this.node).attr("action", "#")
$(this.node).transloadit({
wait: true,
triggerUploadOnFileSelection: true,
autoSubmit: false,
modal: false,
onStart: () =>
@error?.value? undefined
@progress?.value? undefined
@attachment?.value? undefined
onProgress: (bytesReceived, bytesExpected) =>
@progress?.value? Math.floor bytesReceived / bytesExpected * 100
onError: (e) =>
@error?.value? e
@progress?.value? undefined
onResult: (type, data) =>
tracker.track "teacher_added_photo"
@progress?.value? undefined
return unless type is ":original"
@onUpload att = {
url: data.ssl_url,
path: Url.parse(data.ssl_url).pathname.substr(1),
name: data.name,
size: data.size,
type: if data.type is "image" then "photo" else "file",
contentType: data.mime
}
@attachment?.value? att
params: {
auth: { key: "<KEY>" },
steps: {
files: {
robot: "/file/filter",
error_on_decline: true
},
thumb: {
robot: "/image/resize",
format: "png"
}
},
template_id: options.templateId || "bcdfda60184311e48c523f48f47bf7a1"
}
});
module.exports = UploadFileDataBinding
| true | pc = require("paperclip")
bindable = require("bindable")
Url = require "url"
class UploadFileDataBinding extends pc.BaseAttrDataBinding
###
###
bind: () ->
super arguments...
###
###
_onChange: (options) ->
return unless process.browser
@onUpload = options.onUpload ? () ->
@progress = options.progress
@error = options.error
@attachment = options.attachment
return if @__initialized
@__initialized = true
$(this.node).attr("action", "#")
$(this.node).transloadit({
wait: true,
triggerUploadOnFileSelection: true,
autoSubmit: false,
modal: false,
onStart: () =>
@error?.value? undefined
@progress?.value? undefined
@attachment?.value? undefined
onProgress: (bytesReceived, bytesExpected) =>
@progress?.value? Math.floor bytesReceived / bytesExpected * 100
onError: (e) =>
@error?.value? e
@progress?.value? undefined
onResult: (type, data) =>
tracker.track "teacher_added_photo"
@progress?.value? undefined
return unless type is ":original"
@onUpload att = {
url: data.ssl_url,
path: Url.parse(data.ssl_url).pathname.substr(1),
name: data.name,
size: data.size,
type: if data.type is "image" then "photo" else "file",
contentType: data.mime
}
@attachment?.value? att
params: {
auth: { key: "PI:KEY:<KEY>END_PI" },
steps: {
files: {
robot: "/file/filter",
error_on_decline: true
},
thumb: {
robot: "/image/resize",
format: "png"
}
},
template_id: options.templateId || "bcdfda60184311e48c523f48f47bf7a1"
}
});
module.exports = UploadFileDataBinding
|
[
{
"context": "# phantomjs-persistent-server\n# MIT License ben@latenightsketches.com\n# Main Test Runner\n\nconsole.time 'phantomLaunch'\n",
"end": 69,
"score": 0.9999198913574219,
"start": 44,
"tag": "EMAIL",
"value": "ben@latenightsketches.com"
}
] | test/main.coffee | praneybehl/phantomjs-persistent-server | 1 | # phantomjs-persistent-server
# MIT License ben@latenightsketches.com
# Main Test Runner
console.time 'phantomLaunch'
phantomExec = phantomLaunch()
console.timeEnd 'phantomLaunch'
testAsyncMulti 'phantomjs-persistent-server - echo', [
(test, expect) ->
sample = {cow: 'horse'}
echoTest = (options, callback) ->
callback undefined, options
result = phantomExec echoTest, sample
test.isTrue _.isEqual result, sample
]
testAsyncMulti 'phantomjs-persistent-server - no arguments', [
(test, expect) ->
argTest = (callback) ->
callback undefined, 'someval'
result = phantomExec argTest
test.isTrue _.isEqual result, 'someval'
]
testAsyncMulti 'phantomjs-persistent-server - many arguments', [
(test, expect) ->
argTest = (callback) ->
args = Array.prototype.slice.call arguments, 0
callback = args.pop()
sum = args.reduce (prev, cur) ->
return prev + cur
callback undefined, sum
result = phantomExec argTest, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
# result is the sum of 1..13
max = 13
test.isTrue _.isEqual result, (max * (max + 1)) / 2
]
titleTest = (url, callback) ->
webpage = require 'webpage'
page = webpage.create()
page.open url, (status) ->
if status == 'fail'
callback 'load-failure'
else
title = page.evaluate ()->
return document.title
callback undefined, title
testAsyncMulti 'phantomjs-persistent-server - get page title (success)', [
(test, expect) ->
result = phantomExec titleTest, 'http://google.com/'
test.isTrue _.isEqual result, 'Google'
]
testAsyncMulti 'phantomjs-persistent-server - get page title (failure)', [
(test, expect) ->
try
result = phantomExec titleTest, 'http://asjdfoafm/'
catch err
test.equal err.toString(),
'Error: failed [500] {"error":500,"reason":"load-failure"}'
hadError = true
finally
test.isTrue hadError
]
| 53808 | # phantomjs-persistent-server
# MIT License <EMAIL>
# Main Test Runner
console.time 'phantomLaunch'
phantomExec = phantomLaunch()
console.timeEnd 'phantomLaunch'
testAsyncMulti 'phantomjs-persistent-server - echo', [
(test, expect) ->
sample = {cow: 'horse'}
echoTest = (options, callback) ->
callback undefined, options
result = phantomExec echoTest, sample
test.isTrue _.isEqual result, sample
]
testAsyncMulti 'phantomjs-persistent-server - no arguments', [
(test, expect) ->
argTest = (callback) ->
callback undefined, 'someval'
result = phantomExec argTest
test.isTrue _.isEqual result, 'someval'
]
testAsyncMulti 'phantomjs-persistent-server - many arguments', [
(test, expect) ->
argTest = (callback) ->
args = Array.prototype.slice.call arguments, 0
callback = args.pop()
sum = args.reduce (prev, cur) ->
return prev + cur
callback undefined, sum
result = phantomExec argTest, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
# result is the sum of 1..13
max = 13
test.isTrue _.isEqual result, (max * (max + 1)) / 2
]
titleTest = (url, callback) ->
webpage = require 'webpage'
page = webpage.create()
page.open url, (status) ->
if status == 'fail'
callback 'load-failure'
else
title = page.evaluate ()->
return document.title
callback undefined, title
testAsyncMulti 'phantomjs-persistent-server - get page title (success)', [
(test, expect) ->
result = phantomExec titleTest, 'http://google.com/'
test.isTrue _.isEqual result, 'Google'
]
testAsyncMulti 'phantomjs-persistent-server - get page title (failure)', [
(test, expect) ->
try
result = phantomExec titleTest, 'http://asjdfoafm/'
catch err
test.equal err.toString(),
'Error: failed [500] {"error":500,"reason":"load-failure"}'
hadError = true
finally
test.isTrue hadError
]
| true | # phantomjs-persistent-server
# MIT License PI:EMAIL:<EMAIL>END_PI
# Main Test Runner
console.time 'phantomLaunch'
phantomExec = phantomLaunch()
console.timeEnd 'phantomLaunch'
testAsyncMulti 'phantomjs-persistent-server - echo', [
(test, expect) ->
sample = {cow: 'horse'}
echoTest = (options, callback) ->
callback undefined, options
result = phantomExec echoTest, sample
test.isTrue _.isEqual result, sample
]
testAsyncMulti 'phantomjs-persistent-server - no arguments', [
(test, expect) ->
argTest = (callback) ->
callback undefined, 'someval'
result = phantomExec argTest
test.isTrue _.isEqual result, 'someval'
]
testAsyncMulti 'phantomjs-persistent-server - many arguments', [
(test, expect) ->
argTest = (callback) ->
args = Array.prototype.slice.call arguments, 0
callback = args.pop()
sum = args.reduce (prev, cur) ->
return prev + cur
callback undefined, sum
result = phantomExec argTest, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
# result is the sum of 1..13
max = 13
test.isTrue _.isEqual result, (max * (max + 1)) / 2
]
titleTest = (url, callback) ->
webpage = require 'webpage'
page = webpage.create()
page.open url, (status) ->
if status == 'fail'
callback 'load-failure'
else
title = page.evaluate ()->
return document.title
callback undefined, title
testAsyncMulti 'phantomjs-persistent-server - get page title (success)', [
(test, expect) ->
result = phantomExec titleTest, 'http://google.com/'
test.isTrue _.isEqual result, 'Google'
]
testAsyncMulti 'phantomjs-persistent-server - get page title (failure)', [
(test, expect) ->
try
result = phantomExec titleTest, 'http://asjdfoafm/'
catch err
test.equal err.toString(),
'Error: failed [500] {"error":500,"reason":"load-failure"}'
hadError = true
finally
test.isTrue hadError
]
|
[
{
"context": "haves similarly to a physical credit card.\n@author Ken Keiter <ken@kenkeiter.com>\n@updated 2013-07-25\n@website ",
"end": 295,
"score": 0.9998671412467957,
"start": 285,
"tag": "NAME",
"value": "Ken Keiter"
},
{
"context": "ly to a physical credit card.\n@author Ken Keiter <ken@kenkeiter.com>\n@updated 2013-07-25\n@website http://kenkeiter.co",
"end": 314,
"score": 0.9999285936355591,
"start": 297,
"tag": "EMAIL",
"value": "ken@kenkeiter.com"
},
{
"context": "{}\n\nCCProducts[/^30[0-5][0-9]/] =\n companyName: \"Diners Club\"\n companyShortname: \"dinersclubintl\"\n cardNumbe",
"end": 32335,
"score": 0.831150472164154,
"start": 32324,
"tag": "NAME",
"value": "Diners Club"
},
{
"context": " companyName: \"Diners Club\"\n companyShortname: \"dinersclubintl\"\n cardNumberGrouping: [4,6,4]\n expirationFormat",
"end": 32372,
"score": 0.7644999027252197,
"start": 32358,
"tag": "USERNAME",
"value": "dinersclubintl"
},
{
"context": "cvc: 'front'\n\nCCProducts[/^38/] =\n companyName: \"Hipercard\"\n companyShortname: \"hipercard\"\n cardNumberGrou",
"end": 33557,
"score": 0.6413532495498657,
"start": 33548,
"tag": "NAME",
"value": "Hipercard"
},
{
"context": "ck'\n\nCCProducts[/^5[0-8]\\d{2}/] =\n companyName: \"Mastercard\"\n companyShortname: \"mastercard\"\n cardNumberGro",
"end": 34038,
"score": 0.8844882249832153,
"start": 34028,
"tag": "NAME",
"value": "Mastercard"
},
{
"context": "\n companyName: \"Mastercard\"\n companyShortname: \"mastercard\"\n cardNumberGrouping: [4,4,4,4]\n expirationForm",
"end": 34071,
"score": 0.7656944990158081,
"start": 34061,
"tag": "NAME",
"value": "mastercard"
},
{
"context": "20/] =\n issuingAuthority: \"Chase\"\n issuerName: \"Chase Sapphire Card\"\n issuerShortname: \"chase-sapphire\"\n layout:\n ",
"end": 34650,
"score": 0.7844160199165344,
"start": 34631,
"tag": "NAME",
"value": "Chase Sapphire Card"
}
] | javascripts/src/skeuocard.coffee | canerdogan/skeuocard | 0 | ###
"Skeuocard" -- A Skeuomorphic Credit-Card Input Enhancement
@description Skeuocard is a skeuomorphic credit card input plugin, supporting
progressive enhancement. It renders a credit-card input which
behaves similarly to a physical credit card.
@author Ken Keiter <ken@kenkeiter.com>
@updated 2013-07-25
@website http://kenkeiter.com/
@exports [window.Skeuocard]
###
class Skeuocard
constructor: (el, opts = {})->
@el = {container: $(el), underlyingFields: {}}
@_inputViews = {}
@_tabViews = {}
@product = undefined
@productShortname = undefined
@issuerShortname = undefined
@_cardProductNeedsLayout = true
@acceptedCardProducts = {}
@visibleFace = 'front'
@_initialValidationState = {}
@_validationState = {number: false, exp: false, name: false, cvc: false}
@_faceFillState = {front: false, back: false}
# configure default opts
optDefaults =
debug: false
acceptedCardProducts: []
cardNumberPlaceholderChar: 'X'
genericPlaceholder: "XXXX XXXX XXXX XXXX"
typeInputSelector: '[name="cc_type"]'
numberInputSelector: '[name="cc_number"]'
expInputSelector: '[name="cc_exp"]'
nameInputSelector: '[name="cc_name"]'
cvcInputSelector: '[name="cc_cvc"]'
currentDate: new Date()
initialValues: {}
validationState: {}
strings:
hiddenFaceFillPrompt: "Click here to<br /> fill in the other side."
hiddenFaceErrorWarning: "There's a problem on the other side."
hiddenFaceSwitchPrompt: "Back to the other side..."
@options = $.extend(optDefaults, opts)
# initialize the card
@_conformDOM() # conform the DOM to match our styling requirements
@_setAcceptedCardProducts() # determine which card products to accept
@_createInputs() # create reconfigurable input views
@_updateProductIfNeeded()
@_flipToInvalidSide()
# Transform the elements within the container, conforming the DOM so that it
# becomes styleable, and that the underlying inputs are hidden.
_conformDOM: ->
# for CSS determination that this is an enhanced input, add 'js' class to
# the container
@el.container.removeClass('no-js')
@el.container.addClass("skeuocard js")
# remove anything that's not an underlying form field
@el.container.find("> :not(input,select,textarea)").remove()
@el.container.find("> input,select,textarea").hide()
# attach underlying form elements
@el.underlyingFields =
type: @el.container.find(@options.typeInputSelector)
number: @el.container.find(@options.numberInputSelector)
exp: @el.container.find(@options.expInputSelector)
name: @el.container.find(@options.nameInputSelector)
cvc: @el.container.find(@options.cvcInputSelector)
# sync initial values, with constructor options taking precedence
for fieldName, fieldValue of @options.initialValues
@el.underlyingFields[fieldName].val(fieldValue)
for fieldName, el of @el.underlyingFields
@options.initialValues[fieldName] = el.val()
# sync initial validation state, with constructor options taking precedence
# we use the underlying form values to track state
for fieldName, el of @el.underlyingFields
if @options.validationState[fieldName] is false or el.hasClass('invalid')
@_initialValidationState[fieldName] = false
unless el.hasClass('invalid')
el.addClass('invalid')
# bind change handlers to render
@el.underlyingFields.number.bind "change", (e)=>
@_inputViews.number.setValue @_getUnderlyingValue('number')
@render()
@el.underlyingFields.exp.bind "change", (e)=>
@_inputViews.exp.setValue @_getUnderlyingValue('exp')
@render()
@el.underlyingFields.name.bind "change", (e)=>
@_inputViews.exp.setValue @_getUnderlyingValue('name')
@render()
@el.underlyingFields.cvc.bind "change", (e)=>
@_inputViews.exp.setValue @_getUnderlyingValue('cvc')
@render()
# construct the necessary card elements
@el.surfaceFront = $("<div>").attr(class: "face front")
@el.surfaceBack = $("<div>").attr(class: "face back")
@el.cardBody = $("<div>").attr(class: "card-body")
# add elements to the DOM
@el.surfaceFront.appendTo(@el.cardBody)
@el.surfaceBack.appendTo(@el.cardBody)
@el.cardBody.appendTo(@el.container)
# create the validation indicator (flip tab), and attach them.
@_tabViews.front = new @FlipTabView('front')
@_tabViews.back = new @FlipTabView('back')
@el.surfaceFront.prepend(@_tabViews.front.el)
@el.surfaceBack.prepend(@_tabViews.back.el)
@_tabViews.front.hide()
@_tabViews.back.hide()
@_tabViews.front.el.click =>
@flip()
@_tabViews.back.el.click =>
@flip()
return @el.container
_setAcceptedCardProducts: ->
# build the set of accepted card products
if @options.acceptedCardProducts.length is 0
@el.underlyingFields.type.find('option').each (i, _el)=>
el = $(_el)
cardProductShortname = el.attr('data-card-product-shortname') || el.attr('value')
@options.acceptedCardProducts.push cardProductShortname
# find all matching card products by shortname, and add them to the
# list of @acceptedCardProducts
for matcher, product of CCProducts
if product.companyShortname in @options.acceptedCardProducts
@acceptedCardProducts[matcher] = product
return @acceptedCardProducts
_updateProductIfNeeded: ->
# determine if product changed; if so, change it globally, and
# call render() to render the changes.
number = @_getUnderlyingValue('number')
matchedProduct = @getProductForNumber(number)
matchedProductIdentifier = matchedProduct?.companyShortname || ''
matchedIssuerIdentifier = matchedProduct?.issuerShortname || ''
if (@productShortname isnt matchedProductIdentifier) or
(@issuerShortname isnt matchedIssuerIdentifier)
@productShortname = matchedProductIdentifier
@issuerShortname = matchedIssuerIdentifier
@product = matchedProduct
@_cardProductNeedsLayout = true
@trigger 'productWillChange.skeuocard',
[@, @productShortname, matchedProductIdentifier]
@_log("Triggering render because product changed.")
@render()
@trigger('productDidChange.skeuocard', [@, @productShortname, matchedProductIdentifier])
# Create the new inputs, and attach them to their appropriate card face els.
_createInputs: ->
@_inputViews.number = new @SegmentedCardNumberInputView()
@_inputViews.exp = new @ExpirationInputView(currentDate: @options.currentDate)
@_inputViews.name = new @TextInputView(
class: "cc-name", placeholder: "YOUR NAME")
@_inputViews.cvc = new @TextInputView(
class: "cc-cvc", placeholder: "XXX", requireMaxLength: true)
# style and attach the number view to the DOM
@_inputViews.number.el.addClass('cc-number')
@_inputViews.number.el.appendTo(@el.surfaceFront)
# attach name input
@_inputViews.name.el.appendTo(@el.surfaceFront)
# style and attach the exp view to the DOM
@_inputViews.exp.el.addClass('cc-exp')
@_inputViews.exp.el.appendTo(@el.surfaceFront)
# attach cvc field to the DOM
@_inputViews.cvc.el.appendTo(@el.surfaceBack)
# bind change events to their underlying form elements
@_inputViews.number.bind "keyup", (e, input)=>
@_setUnderlyingValue('number', input.value)
@_updateValidationStateForInputView('number')
@_updateProductIfNeeded()
@_inputViews.exp.bind "keyup", (e, input)=>
@_setUnderlyingValue('exp', input.value)
@_updateValidationStateForInputView('exp')
@_inputViews.name.bind "keyup", (e)=>
@_setUnderlyingValue('name', $(e.target).val())
@_updateValidationStateForInputView('name')
@_inputViews.cvc.bind "keyup", (e)=>
@_setUnderlyingValue('cvc', $(e.target).val())
@_updateValidationStateForInputView('cvc')
# setup default values; when render is called, these will be picked up
@_inputViews.number.setValue @_getUnderlyingValue('number')
@_inputViews.exp.setValue @_getUnderlyingValue('exp')
@_inputViews.name.el.val @_getUnderlyingValue('name')
@_inputViews.cvc.el.val @_getUnderlyingValue('cvc')
# Debugging helper; if debug is set to true at instantiation, messages will
# be printed to the console.
_log: (msg...)->
if console?.log and !!@options.debug
console.log("[skeuocard]", msg...) if @options.debug?
_flipToInvalidSide: ->
if Object.keys(@_initialValidationState).length > 0
_oppositeFace = if @visibleFace is 'front' then 'back' else 'front'
# if the back face has errors, and the front does not, flip there.
_errorCounts = {front: 0, back: 0}
for fieldName, state of @_initialValidationState
_errorCounts[@product?.layout[fieldName]]++
if _errorCounts[@visibleFace] == 0 and _errorCounts[_oppositeFace] > 0
@flip()
# Update the card's visual representation to reflect internal state.
render: ->
@_log("*** start rendering ***")
# Render card product layout changes.
if @_cardProductNeedsLayout is true
# Update product-specific details
if @product isnt undefined
# change the design and layout of the card to match the matched prod.
@_log("[render]", "Activating product", @product)
@el.container.removeClass (index, css)=>
(css.match(/\b(product|issuer)-\S+/g) || []).join(' ')
@el.container.addClass("product-#{@product.companyShortname}")
if @product.issuerShortname?
@el.container.addClass("issuer-#{@product.issuerShortname}")
# Adjust underlying card type to match detected type
@_setUnderlyingCardType(@product.companyShortname)
# Reconfigure input to match product
@_inputViews.number.reconfigure
groupings: @product.cardNumberGrouping
placeholderChar: @options.cardNumberPlaceholderChar
@_inputViews.exp.show()
@_inputViews.name.show()
@_inputViews.exp.reconfigure
pattern: @product.expirationFormat
@_inputViews.cvc.show()
@_inputViews.cvc.attr
maxlength: @product.cvcLength
placeholder: new Array(@product.cvcLength + 1).join(@options.cardNumberPlaceholderChar)
for fieldName, surfaceName of @product.layout
sel = if surfaceName is 'front' then 'surfaceFront' else 'surfaceBack'
container = @el[sel]
inputEl = @_inputViews[fieldName].el
unless container.has(inputEl).length > 0
@_log("Moving", inputEl, "=>", container)
el = @_inputViews[fieldName].el.detach()
$(el).appendTo(@el[sel])
else
@_log("[render]", "Becoming generic.")
# Reset to generic input
@_inputViews.exp.clear()
@_inputViews.cvc.clear()
@_inputViews.exp.hide()
@_inputViews.name.hide()
@_inputViews.cvc.hide()
@_inputViews.number.reconfigure
groupings: [@options.genericPlaceholder.length],
placeholder: @options.genericPlaceholder
@el.container.removeClass (index, css)=>
(css.match(/\bproduct-\S+/g) || []).join(' ')
@el.container.removeClass (index, css)=>
(css.match(/\bissuer-\S+/g) || []).join(' ')
@_cardProductNeedsLayout = false
@_log("Validation state:", @_validationState)
# Render validation changes
@showInitialValidationErrors()
# If the current face is filled, and there are validation errors, show 'em
_oppositeFace = if @visibleFace is 'front' then 'back' else 'front'
_visibleFaceFilled = @_faceFillState[@visibleFace]
_visibleFaceValid = @isFaceValid(@visibleFace)
_hiddenFaceFilled = @_faceFillState[_oppositeFace]
_hiddenFaceValid = @isFaceValid(_oppositeFace)
if _visibleFaceFilled and not _visibleFaceValid
@_log("Visible face is filled, but invalid; showing validation errors.")
@showValidationErrors()
else if not _visibleFaceFilled
@_log("Visible face hasn't been filled; hiding validation errors.")
@hideValidationErrors()
else
@_log("Visible face has been filled, and is valid.")
@hideValidationErrors()
if @visibleFace is 'front' and @fieldsForFace('back').length > 0
if _visibleFaceFilled and _visibleFaceValid and not _hiddenFaceFilled
@_tabViews.front.prompt(@options.strings.hiddenFaceFillPrompt, true)
else if _hiddenFaceFilled and not _hiddenFaceValid
@_tabViews.front.warn(@options.strings.hiddenFaceErrorWarning, true)
else if _hiddenFaceFilled and _hiddenFaceValid
@_tabViews.front.prompt(@options.strings.hiddenFaceSwitchPrompt, true)
else
@_tabViews.front.hide()
else
if _hiddenFaceValid
@_tabViews.back.prompt(@options.strings.hiddenFaceSwitchPrompt, true)
else
@_tabViews.back.warn(@options.strings.hiddenFaceErrorWarning, true)
# Update the validity indicator for the whole card body
if not @isValid()
@el.container.removeClass('valid')
@el.container.addClass('invalid')
else
@el.container.addClass('valid')
@el.container.removeClass('invalid')
@_log("*** rendering complete ***")
# We should *always* show initial validation errors; they shouldn't show and
# hide with the rest of the errors unless their value has been changed.
showInitialValidationErrors: ->
for fieldName, state of @_initialValidationState
if state is false and @_validationState[fieldName] is false
# if the error hasn't been rectified
@_inputViews[fieldName].addClass('invalid')
else
@_inputViews[fieldName].removeClass('invalid')
showValidationErrors: ->
for fieldName, state of @_validationState
if state is true
@_inputViews[fieldName].removeClass('invalid')
else
@_inputViews[fieldName].addClass('invalid')
hideValidationErrors: ->
for fieldName, state of @_validationState
if (@_initialValidationState[fieldName] is false and state is true) or
(not @_initialValidationState[fieldName]?)
@_inputViews[fieldName].el.removeClass('invalid')
setFieldValidationState: (fieldName, valid)->
if valid
@el.underlyingFields[fieldName].removeClass('invalid')
else
@el.underlyingFields[fieldName].addClass('invalid')
@_validationState[fieldName] = valid
isFaceFilled: (faceName)->
fields = @fieldsForFace(faceName)
filled = (name for name in fields when @_inputViews[name].isFilled())
if fields.length > 0
return filled.length is fields.length
else
return false
fieldsForFace: (faceName)->
if @product?.layout
return (fn for fn, face of @product.layout when face is faceName)
return []
_updateValidationStateForInputView: (fieldName)->
field = @_inputViews[fieldName]
fieldValid = field.isValid() and
not (@_initialValidationState[fieldName] is false and
field.getValue() is @options.initialValues[fieldName])
# trigger a change event if the field has changed
if fieldValid isnt @_validationState[fieldName]
@setFieldValidationState(fieldName, fieldValid)
# Update the fill state
@_faceFillState.front = @isFaceFilled('front')
@_faceFillState.back = @isFaceFilled('back')
@trigger('validationStateDidChange.skeuocard', [@, @_validationState])
@_log("Change in validation for #{fieldName} triggers re-render.")
@render()
isFaceValid: (faceName)->
valid = true
for fieldName in @fieldsForFace(faceName)
valid &= @_validationState[fieldName]
return !!valid
isValid: ->
@_validationState.number and
@_validationState.exp and
@_validationState.name and
@_validationState.cvc
# Get a value from the underlying form.
_getUnderlyingValue: (field)->
@el.underlyingFields[field].val()
# Set a value in the underlying form.
_setUnderlyingValue: (field, newValue)->
@trigger('change.skeuocard', [@]) # changing the underlying value triggers a change.
@el.underlyingFields[field].val(newValue)
# Flip the card over.
flip: ->
targetFace = if @visibleFace is 'front' then 'back' else 'front'
@trigger('faceWillBecomeVisible.skeuocard', [@, targetFace])
@visibleFace = targetFace
@render()
@el.cardBody.toggleClass('flip')
@trigger('faceDidBecomeVisible.skeuocard', [@, targetFace])
getProductForNumber: (num)->
for m, d of @acceptedCardProducts
parts = m.split('/')
matcher = new RegExp(parts[1], parts[2])
if matcher.test(num)
issuer = @getIssuerForNumber(num) || {}
return $.extend({}, d, issuer)
return undefined
getIssuerForNumber: (num)->
for m, d of CCIssuers
parts = m.split('/')
matcher = new RegExp(parts[1], parts[2])
if matcher.test(num)
return d
return undefined
_setUnderlyingCardType: (shortname)->
@el.underlyingFields.type.find('option').each (i, _el)=>
el = $(_el)
if shortname is (el.attr('data-card-product-shortname') || el.attr('value'))
el.val(el.attr('value')) # change which option is selected
trigger: (args...)->
@el.container.trigger(args...)
bind: (args...)->
@el.container.trigger(args...)
###
Skeuocard::FlipTabView
Handles rendering of the "flip button" control and its various warning and
prompt states.
###
class Skeuocard::FlipTabView
constructor: (face, opts = {})->
@el = $("<div class=\"flip-tab #{face}\"><p></p></div>")
@options = opts
_setText: (text)->
@el.find('p').html(text)
warn: (message, withAnimation = false)->
@_resetClasses()
@el.addClass('warn')
@_setText(message)
@show()
if withAnimation
@el.removeClass('warn-anim')
@el.addClass('warn-anim')
prompt: (message, withAnimation = false)->
@_resetClasses()
@el.addClass('prompt')
@_setText(message)
@show()
if withAnimation
@el.removeClass('valid-anim')
@el.addClass('valid-anim')
_resetClasses: ->
@el.removeClass('valid-anim')
@el.removeClass('warn-anim')
@el.removeClass('warn')
@el.removeClass('prompt')
show: ->
@el.show()
hide: ->
@el.hide()
###
Skeuocard::TextInputView
###
class Skeuocard::TextInputView
bind: (args...)->
@el.bind(args...)
trigger: (args...)->
@el.trigger(args...)
_getFieldCaretPosition: (el)->
input = el.get(0)
if input.selectionEnd?
return input.selectionEnd
else if document.selection
input.focus()
sel = document.selection.createRange()
selLength = document.selection.createRange().text.length
sel.moveStart('character', -input.value.length)
return selLength
_setFieldCaretPosition: (el, pos)->
input = el.get(0)
if input.createTextRange?
range = input.createTextRange()
range.move "character", pos
range.select()
else if input.selectionStart?
input.focus()
input.setSelectionRange(pos, pos)
show: ->
@el.show()
hide: ->
@el.hide()
addClass: (args...)->
@el.addClass(args...)
removeClass: (args...)->
@el.removeClass(args...)
_zeroPadNumber: (num, places)->
zero = places - num.toString().length + 1
return Array(zero).join("0") + num
class Skeuocard::SegmentedCardNumberInputView extends Skeuocard::TextInputView
constructor: (opts = {})->
# Setup option defaults
opts.value ||= ""
opts.groupings ||= [19]
opts.placeholderChar ||= "X"
@options = opts
# everythIng else
@value = @options.value
@el = $("<fieldset>")
@el.delegate "input", "keydown", (e)=> @_onGroupKeyDown(e)
@el.delegate "input", "keyup", (e)=> @_onGroupKeyUp(e)
@groupEls = $()
_onGroupKeyDown: (e)->
e.stopPropagation()
groupEl = $(e.currentTarget)
arrowKeys = [37, 38, 39, 40]
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
if e.which is 8 and groupCaretPos is 0 and not $.isEmptyObject(groupEl.prev())
groupEl.prev().focus()
if e.which in arrowKeys
switch e.which
when 37 # left
if groupCaretPos is 0 and not $.isEmptyObject(groupEl.prev())
groupEl.prev().focus()
when 39 # right
if groupCaretPos is groupMaxLength and not $.isEmptyObject(groupEl.next())
groupEl.next().focus()
when 38 # up
if not $.isEmptyObject(groupEl.prev())
groupEl.prev().focus()
when 40 # down
if not $.isEmptyObject(groupEl.next())
groupEl.next().focus()
_onGroupKeyUp: (e)->
e.stopPropagation() # prevent event from bubbling up
specialKeys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36,
37, 38, 39, 40, 45, 46, 91, 93, 144, 145, 224]
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
if e.which not in specialKeys
# intercept bad chars, returning user to the right char pos if need be
groupValLength = groupEl.val().length
pattern = new RegExp('[^0-9]+', 'g')
groupEl.val(groupEl.val().replace(pattern, ''))
if groupEl.val().length < groupValLength # we caught bad char
@_setFieldCaretPosition(groupEl, groupCaretPos - 1)
else
@_setFieldCaretPosition(groupEl, groupCaretPos)
if e.which not in specialKeys and
groupEl.val().length is groupMaxLength and
not $.isEmptyObject(groupEl.next()) and
@_getFieldCaretPosition(groupEl) is groupMaxLength
groupEl.next().focus()
# update the value
newValue = ""
@groupEls.each -> newValue += $(@).val()
@value = newValue
@trigger("keyup", [@])
return false
setGroupings: (groupings)->
caretPos = @_caretPosition()
@el.empty() # remove all inputs
_startLength = 0
for groupLength in groupings
groupEl = $("<input>").attr
type: 'text'
size: groupLength
maxlength: groupLength
class: "group#{groupLength}"
# restore value, if necessary
if @value.length > _startLength
groupEl.val(@value.substr(_startLength, groupLength))
_startLength += groupLength
@el.append(groupEl)
@options.groupings = groupings
@groupEls = @el.find("input")
# restore to previous settings
@_caretTo(caretPos)
if @options.placeholderChar isnt undefined
@setPlaceholderChar(@options.placeholderChar)
if @options.placeholder isnt undefined
@setPlaceholder(@options.placeholder)
setPlaceholderChar: (ch)->
@groupEls.each ->
el = $(@)
el.attr 'placeholder', new Array(parseInt(el.attr('maxlength'))+1).join(ch)
@options.placeholder = undefined
@options.placeholderChar = ch
setPlaceholder: (str)->
@groupEls.each ->
$(@).attr 'placeholder', str
@options.placeholderChar = undefined
@options.placeholder = str
setValue: (newValue)->
lastPos = 0
@groupEls.each ->
el = $(@)
len = parseInt(el.attr('maxlength'))
el.val(newValue.substr(lastPos, len))
lastPos += len
@value = newValue
getValue: ->
@value
reconfigure: (changes = {})->
if changes.groupings?
@setGroupings(changes.groupings)
if changes.placeholderChar?
@setPlaceholderChar(changes.placeholderChar)
if changes.placeholder?
@setPlaceholder(changes.placeholder)
if changes.value?
@setValue(changes.value)
_caretTo: (index)->
pos = 0
inputEl = undefined
inputElIndex = 0
# figure out which group we're in
@groupEls.each (i, e)=>
el = $(e)
elLength = parseInt(el.attr('maxlength'))
if index <= elLength + pos and index >= pos
inputEl = el
inputElIndex = index - pos
pos += elLength
# move the caret there
@_setFieldCaretPosition(inputEl, inputElIndex)
_caretPosition: ->
iPos = 0
finalPos = 0
@groupEls.each (i, e)=>
el = $(e)
if el.is(':focus')
finalPos = iPos + @_getFieldCaretPosition(el)
iPos += parseInt(el.attr('maxlength'))
return finalPos
maxLength: ->
@options.groupings.reduce((a,b)->(a+b))
isFilled: ->
@value.length == @maxLength()
isValid: ->
@isFilled() and @isValidLuhn(@value)
isValidLuhn: (identifier)->
sum = 0
alt = false
for i in [identifier.length - 1..0] by -1
num = parseInt identifier.charAt(i), 10
return false if isNaN(num)
if alt
num *= 2
num = (num % 10) + 1 if num > 9
alt = !alt
sum += num
sum % 10 is 0
###
Skeuocard::ExpirationInputView
###
class Skeuocard::ExpirationInputView extends Skeuocard::TextInputView
constructor: (opts = {})->
# setup option defaults
opts.dateFormatter ||= (date)->
date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear()
opts.dateParser ||= (value)->
dateParts = value.split('-')
new Date(dateParts[2], dateParts[1]-1, dateParts[0])
opts.currentDate ||= new Date()
opts.pattern ||= "MM/YY"
@options = opts
# setup default values
@date = undefined
@value = undefined
# create dom container
@el = $("<fieldset>")
@el.delegate "input", "keydown", (e)=> @_onKeyDown(e)
@el.delegate "input", "keyup", (e)=> @_onKeyUp(e)
_getFieldCaretPosition: (el)->
input = el.get(0)
if input.selectionEnd?
return input.selectionEnd
else if document.selection
input.focus()
sel = document.selection.createRange()
selLength = document.selection.createRange().text.length
sel.moveStart('character', -input.value.length)
return selLength
_setFieldCaretPosition: (el, pos)->
input = el.get(0)
if input.createTextRange?
range = input.createTextRange()
range.move "character", pos
range.select()
else if input.selectionStart?
input.focus()
input.setSelectionRange(pos, pos)
setPattern: (pattern)->
groupings = []
patternParts = pattern.split('')
_currentLength = 0
for char, i in patternParts
_currentLength++
if patternParts[i+1] != char
groupings.push([_currentLength, char])
_currentLength = 0
@options.groupings = groupings
@_setGroupings(@options.groupings)
_setGroupings: (groupings)->
fieldChars = ['D', 'M', 'Y']
@el.empty()
_startLength = 0
for group in groupings
groupLength = group[0]
groupChar = group[1]
if groupChar in fieldChars # this group is a field
input = $('<input>').attr
type: 'text'
placeholder: new Array(groupLength+1).join(groupChar)
maxlength: groupLength
class: 'cc-exp-field-' + groupChar.toLowerCase() +
' group' + groupLength
input.data('fieldtype', groupChar)
@el.append(input)
else # this group is a separator
sep = $('<span>').attr
class: 'separator'
sep.html(new Array(groupLength + 1).join(groupChar))
@el.append(sep)
@groupEls = @el.find('input')
@_updateFieldValues() if @date?
_updateFieldValues: ->
currentDate = @date
unless @groupEls # they need to be created
return @setPattern(@options.pattern)
@groupEls.each (i,_el)=>
el = $(_el)
groupLength = parseInt(el.attr('maxlength'))
switch el.data('fieldtype')
when 'M'
el.val @_zeroPadNumber(currentDate.getMonth() + 1, groupLength)
when 'D'
el.val @_zeroPadNumber(currentDate.getDate(), groupLength)
when 'Y'
year = if groupLength >= 4 then currentDate.getFullYear() else
currentDate.getFullYear().toString().substr(2,4)
el.val(year)
clear: ->
@value = ""
@date = null
@groupEls.each ->
$(@).val('')
setDate: (newDate)->
@date = newDate
@value = @options.dateFormatter(newDate)
@_updateFieldValues()
setValue: (newValue)->
@value = newValue
@date = @options.dateParser(newValue)
@_updateFieldValues()
getDate: ->
@date
getValue: ->
@value
reconfigure: (opts)->
if opts.pattern?
@setPattern(opts.pattern)
if opts.value?
@setValue(opts.value)
_onKeyDown: (e)->
e.stopPropagation()
groupEl = $(e.currentTarget)
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
prevInputEl = groupEl.prevAll('input').first()
nextInputEl = groupEl.nextAll('input').first()
# Handle delete key
if e.which is 8 and groupCaretPos is 0 and
not $.isEmptyObject(prevInputEl)
prevInputEl.focus()
if e.which in [37, 38, 39, 40] # arrow keys
switch e.which
when 37 # left
if groupCaretPos is 0 and not $.isEmptyObject(prevInputEl)
prevInputEl.focus()
when 39 # right
if groupCaretPos is groupMaxLength and not $.isEmptyObject(nextInputEl)
nextInputEl.focus()
when 38 # up
if not $.isEmptyObject(groupEl.prev('input'))
prevInputEl.focus()
when 40 # down
if not $.isEmptyObject(groupEl.next('input'))
nextInputEl.focus()
_onKeyUp: (e)->
e.stopPropagation()
specialKeys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36,
37, 38, 39, 40, 45, 46, 91, 93, 144, 145, 224]
arrowKeys = [37, 38, 39, 40]
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
if e.which not in specialKeys
# intercept bad chars, returning user to the right char pos if need be
groupValLength = groupEl.val().length
pattern = new RegExp('[^0-9]+', 'g')
groupEl.val(groupEl.val().replace(pattern, ''))
if groupEl.val().length < groupValLength # we caught bad char
@_setFieldCaretPosition(groupEl, groupCaretPos - 1)
else
@_setFieldCaretPosition(groupEl, groupCaretPos)
nextInputEl = groupEl.nextAll('input').first()
if e.which not in specialKeys and
groupEl.val().length is groupMaxLength and
not $.isEmptyObject(nextInputEl) and
@_getFieldCaretPosition(groupEl) is groupMaxLength
nextInputEl.focus()
# get a date object representing what's been entered
day = parseInt(@el.find('.cc-exp-field-d').val()) || 1
month = parseInt(@el.find('.cc-exp-field-m').val())
year = parseInt(@el.find('.cc-exp-field-y').val())
if month is 0 or year is 0
@value = ""
@date = null
else
year += 2000 if year < 2000
dateObj = new Date(year, month-1, day)
@value = @options.dateFormatter(dateObj)
@date = dateObj
@trigger("keyup", [@])
return false
_inputGroupEls: ->
@el.find("input")
isFilled: ->
for inputEl in @groupEls
el = $(inputEl)
return false if el.val().length != parseInt(el.attr('maxlength'))
return true
isValid: ->
@isFilled() and
((@date.getFullYear() == @options.currentDate.getFullYear() and
@date.getMonth() >= @options.currentDate.getMonth()) or
@date.getFullYear() > @options.currentDate.getFullYear())
class Skeuocard::TextInputView extends Skeuocard::TextInputView
constructor: (opts)->
@el = $("<input>").attr
type: 'text'
placeholder: opts.placeholder
class: opts.class
@options = opts
clear: ->
@el.val("")
attr: (args...)->
@el.attr(args...)
isFilled: ->
return @el.val().length > 0
isValid: ->
if @options.requireMaxLength
return @el.val().length is parseInt(@el.attr('maxlength'))
else
return @isFilled()
getValue: ->
@el.val()
# Export the object.
window.Skeuocard = Skeuocard
###
# Card Definitions
###
# List of credit card products by matching prefix.
CCProducts = {}
CCProducts[/^30[0-5][0-9]/] =
companyName: "Diners Club"
companyShortname: "dinersclubintl"
cardNumberGrouping: [4,6,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^3095/] =
companyName: "Diners Club International"
companyShortname: "dinersclubintl"
cardNumberGrouping: [4,6,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^36\d{2}/] =
companyName: "Diners Club International"
companyShortname: "dinersclubintl"
cardNumberGrouping: [4,6,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^35\d{2}/] =
companyName: "JCB"
companyShortname: "jcb"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^37/] =
companyName: "American Express"
companyShortname: "amex"
cardNumberGrouping: [4,6,5]
expirationFormat: "MM/YY"
cvcLength: 4
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'front'
CCProducts[/^38/] =
companyName: "Hipercard"
companyShortname: "hipercard"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^4[0-9]\d{2}/] =
companyName: "Visa"
companyShortname: "visa"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^5[0-8]\d{2}/] =
companyName: "Mastercard"
companyShortname: "mastercard"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^6011/] =
companyName: "Discover"
companyShortname: "discover"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCIssuers = {}
###
Hack fixes the Chase Sapphire card's stupid (nice?) layout non-conformity.
###
CCIssuers[/^414720/] =
issuingAuthority: "Chase"
issuerName: "Chase Sapphire Card"
issuerShortname: "chase-sapphire"
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'front'
| 179678 | ###
"Skeuocard" -- A Skeuomorphic Credit-Card Input Enhancement
@description Skeuocard is a skeuomorphic credit card input plugin, supporting
progressive enhancement. It renders a credit-card input which
behaves similarly to a physical credit card.
@author <NAME> <<EMAIL>>
@updated 2013-07-25
@website http://kenkeiter.com/
@exports [window.Skeuocard]
###
class Skeuocard
constructor: (el, opts = {})->
@el = {container: $(el), underlyingFields: {}}
@_inputViews = {}
@_tabViews = {}
@product = undefined
@productShortname = undefined
@issuerShortname = undefined
@_cardProductNeedsLayout = true
@acceptedCardProducts = {}
@visibleFace = 'front'
@_initialValidationState = {}
@_validationState = {number: false, exp: false, name: false, cvc: false}
@_faceFillState = {front: false, back: false}
# configure default opts
optDefaults =
debug: false
acceptedCardProducts: []
cardNumberPlaceholderChar: 'X'
genericPlaceholder: "XXXX XXXX XXXX XXXX"
typeInputSelector: '[name="cc_type"]'
numberInputSelector: '[name="cc_number"]'
expInputSelector: '[name="cc_exp"]'
nameInputSelector: '[name="cc_name"]'
cvcInputSelector: '[name="cc_cvc"]'
currentDate: new Date()
initialValues: {}
validationState: {}
strings:
hiddenFaceFillPrompt: "Click here to<br /> fill in the other side."
hiddenFaceErrorWarning: "There's a problem on the other side."
hiddenFaceSwitchPrompt: "Back to the other side..."
@options = $.extend(optDefaults, opts)
# initialize the card
@_conformDOM() # conform the DOM to match our styling requirements
@_setAcceptedCardProducts() # determine which card products to accept
@_createInputs() # create reconfigurable input views
@_updateProductIfNeeded()
@_flipToInvalidSide()
# Transform the elements within the container, conforming the DOM so that it
# becomes styleable, and that the underlying inputs are hidden.
_conformDOM: ->
# for CSS determination that this is an enhanced input, add 'js' class to
# the container
@el.container.removeClass('no-js')
@el.container.addClass("skeuocard js")
# remove anything that's not an underlying form field
@el.container.find("> :not(input,select,textarea)").remove()
@el.container.find("> input,select,textarea").hide()
# attach underlying form elements
@el.underlyingFields =
type: @el.container.find(@options.typeInputSelector)
number: @el.container.find(@options.numberInputSelector)
exp: @el.container.find(@options.expInputSelector)
name: @el.container.find(@options.nameInputSelector)
cvc: @el.container.find(@options.cvcInputSelector)
# sync initial values, with constructor options taking precedence
for fieldName, fieldValue of @options.initialValues
@el.underlyingFields[fieldName].val(fieldValue)
for fieldName, el of @el.underlyingFields
@options.initialValues[fieldName] = el.val()
# sync initial validation state, with constructor options taking precedence
# we use the underlying form values to track state
for fieldName, el of @el.underlyingFields
if @options.validationState[fieldName] is false or el.hasClass('invalid')
@_initialValidationState[fieldName] = false
unless el.hasClass('invalid')
el.addClass('invalid')
# bind change handlers to render
@el.underlyingFields.number.bind "change", (e)=>
@_inputViews.number.setValue @_getUnderlyingValue('number')
@render()
@el.underlyingFields.exp.bind "change", (e)=>
@_inputViews.exp.setValue @_getUnderlyingValue('exp')
@render()
@el.underlyingFields.name.bind "change", (e)=>
@_inputViews.exp.setValue @_getUnderlyingValue('name')
@render()
@el.underlyingFields.cvc.bind "change", (e)=>
@_inputViews.exp.setValue @_getUnderlyingValue('cvc')
@render()
# construct the necessary card elements
@el.surfaceFront = $("<div>").attr(class: "face front")
@el.surfaceBack = $("<div>").attr(class: "face back")
@el.cardBody = $("<div>").attr(class: "card-body")
# add elements to the DOM
@el.surfaceFront.appendTo(@el.cardBody)
@el.surfaceBack.appendTo(@el.cardBody)
@el.cardBody.appendTo(@el.container)
# create the validation indicator (flip tab), and attach them.
@_tabViews.front = new @FlipTabView('front')
@_tabViews.back = new @FlipTabView('back')
@el.surfaceFront.prepend(@_tabViews.front.el)
@el.surfaceBack.prepend(@_tabViews.back.el)
@_tabViews.front.hide()
@_tabViews.back.hide()
@_tabViews.front.el.click =>
@flip()
@_tabViews.back.el.click =>
@flip()
return @el.container
_setAcceptedCardProducts: ->
# build the set of accepted card products
if @options.acceptedCardProducts.length is 0
@el.underlyingFields.type.find('option').each (i, _el)=>
el = $(_el)
cardProductShortname = el.attr('data-card-product-shortname') || el.attr('value')
@options.acceptedCardProducts.push cardProductShortname
# find all matching card products by shortname, and add them to the
# list of @acceptedCardProducts
for matcher, product of CCProducts
if product.companyShortname in @options.acceptedCardProducts
@acceptedCardProducts[matcher] = product
return @acceptedCardProducts
_updateProductIfNeeded: ->
# determine if product changed; if so, change it globally, and
# call render() to render the changes.
number = @_getUnderlyingValue('number')
matchedProduct = @getProductForNumber(number)
matchedProductIdentifier = matchedProduct?.companyShortname || ''
matchedIssuerIdentifier = matchedProduct?.issuerShortname || ''
if (@productShortname isnt matchedProductIdentifier) or
(@issuerShortname isnt matchedIssuerIdentifier)
@productShortname = matchedProductIdentifier
@issuerShortname = matchedIssuerIdentifier
@product = matchedProduct
@_cardProductNeedsLayout = true
@trigger 'productWillChange.skeuocard',
[@, @productShortname, matchedProductIdentifier]
@_log("Triggering render because product changed.")
@render()
@trigger('productDidChange.skeuocard', [@, @productShortname, matchedProductIdentifier])
# Create the new inputs, and attach them to their appropriate card face els.
_createInputs: ->
@_inputViews.number = new @SegmentedCardNumberInputView()
@_inputViews.exp = new @ExpirationInputView(currentDate: @options.currentDate)
@_inputViews.name = new @TextInputView(
class: "cc-name", placeholder: "YOUR NAME")
@_inputViews.cvc = new @TextInputView(
class: "cc-cvc", placeholder: "XXX", requireMaxLength: true)
# style and attach the number view to the DOM
@_inputViews.number.el.addClass('cc-number')
@_inputViews.number.el.appendTo(@el.surfaceFront)
# attach name input
@_inputViews.name.el.appendTo(@el.surfaceFront)
# style and attach the exp view to the DOM
@_inputViews.exp.el.addClass('cc-exp')
@_inputViews.exp.el.appendTo(@el.surfaceFront)
# attach cvc field to the DOM
@_inputViews.cvc.el.appendTo(@el.surfaceBack)
# bind change events to their underlying form elements
@_inputViews.number.bind "keyup", (e, input)=>
@_setUnderlyingValue('number', input.value)
@_updateValidationStateForInputView('number')
@_updateProductIfNeeded()
@_inputViews.exp.bind "keyup", (e, input)=>
@_setUnderlyingValue('exp', input.value)
@_updateValidationStateForInputView('exp')
@_inputViews.name.bind "keyup", (e)=>
@_setUnderlyingValue('name', $(e.target).val())
@_updateValidationStateForInputView('name')
@_inputViews.cvc.bind "keyup", (e)=>
@_setUnderlyingValue('cvc', $(e.target).val())
@_updateValidationStateForInputView('cvc')
# setup default values; when render is called, these will be picked up
@_inputViews.number.setValue @_getUnderlyingValue('number')
@_inputViews.exp.setValue @_getUnderlyingValue('exp')
@_inputViews.name.el.val @_getUnderlyingValue('name')
@_inputViews.cvc.el.val @_getUnderlyingValue('cvc')
# Debugging helper; if debug is set to true at instantiation, messages will
# be printed to the console.
_log: (msg...)->
if console?.log and !!@options.debug
console.log("[skeuocard]", msg...) if @options.debug?
_flipToInvalidSide: ->
if Object.keys(@_initialValidationState).length > 0
_oppositeFace = if @visibleFace is 'front' then 'back' else 'front'
# if the back face has errors, and the front does not, flip there.
_errorCounts = {front: 0, back: 0}
for fieldName, state of @_initialValidationState
_errorCounts[@product?.layout[fieldName]]++
if _errorCounts[@visibleFace] == 0 and _errorCounts[_oppositeFace] > 0
@flip()
# Update the card's visual representation to reflect internal state.
render: ->
@_log("*** start rendering ***")
# Render card product layout changes.
if @_cardProductNeedsLayout is true
# Update product-specific details
if @product isnt undefined
# change the design and layout of the card to match the matched prod.
@_log("[render]", "Activating product", @product)
@el.container.removeClass (index, css)=>
(css.match(/\b(product|issuer)-\S+/g) || []).join(' ')
@el.container.addClass("product-#{@product.companyShortname}")
if @product.issuerShortname?
@el.container.addClass("issuer-#{@product.issuerShortname}")
# Adjust underlying card type to match detected type
@_setUnderlyingCardType(@product.companyShortname)
# Reconfigure input to match product
@_inputViews.number.reconfigure
groupings: @product.cardNumberGrouping
placeholderChar: @options.cardNumberPlaceholderChar
@_inputViews.exp.show()
@_inputViews.name.show()
@_inputViews.exp.reconfigure
pattern: @product.expirationFormat
@_inputViews.cvc.show()
@_inputViews.cvc.attr
maxlength: @product.cvcLength
placeholder: new Array(@product.cvcLength + 1).join(@options.cardNumberPlaceholderChar)
for fieldName, surfaceName of @product.layout
sel = if surfaceName is 'front' then 'surfaceFront' else 'surfaceBack'
container = @el[sel]
inputEl = @_inputViews[fieldName].el
unless container.has(inputEl).length > 0
@_log("Moving", inputEl, "=>", container)
el = @_inputViews[fieldName].el.detach()
$(el).appendTo(@el[sel])
else
@_log("[render]", "Becoming generic.")
# Reset to generic input
@_inputViews.exp.clear()
@_inputViews.cvc.clear()
@_inputViews.exp.hide()
@_inputViews.name.hide()
@_inputViews.cvc.hide()
@_inputViews.number.reconfigure
groupings: [@options.genericPlaceholder.length],
placeholder: @options.genericPlaceholder
@el.container.removeClass (index, css)=>
(css.match(/\bproduct-\S+/g) || []).join(' ')
@el.container.removeClass (index, css)=>
(css.match(/\bissuer-\S+/g) || []).join(' ')
@_cardProductNeedsLayout = false
@_log("Validation state:", @_validationState)
# Render validation changes
@showInitialValidationErrors()
# If the current face is filled, and there are validation errors, show 'em
_oppositeFace = if @visibleFace is 'front' then 'back' else 'front'
_visibleFaceFilled = @_faceFillState[@visibleFace]
_visibleFaceValid = @isFaceValid(@visibleFace)
_hiddenFaceFilled = @_faceFillState[_oppositeFace]
_hiddenFaceValid = @isFaceValid(_oppositeFace)
if _visibleFaceFilled and not _visibleFaceValid
@_log("Visible face is filled, but invalid; showing validation errors.")
@showValidationErrors()
else if not _visibleFaceFilled
@_log("Visible face hasn't been filled; hiding validation errors.")
@hideValidationErrors()
else
@_log("Visible face has been filled, and is valid.")
@hideValidationErrors()
if @visibleFace is 'front' and @fieldsForFace('back').length > 0
if _visibleFaceFilled and _visibleFaceValid and not _hiddenFaceFilled
@_tabViews.front.prompt(@options.strings.hiddenFaceFillPrompt, true)
else if _hiddenFaceFilled and not _hiddenFaceValid
@_tabViews.front.warn(@options.strings.hiddenFaceErrorWarning, true)
else if _hiddenFaceFilled and _hiddenFaceValid
@_tabViews.front.prompt(@options.strings.hiddenFaceSwitchPrompt, true)
else
@_tabViews.front.hide()
else
if _hiddenFaceValid
@_tabViews.back.prompt(@options.strings.hiddenFaceSwitchPrompt, true)
else
@_tabViews.back.warn(@options.strings.hiddenFaceErrorWarning, true)
# Update the validity indicator for the whole card body
if not @isValid()
@el.container.removeClass('valid')
@el.container.addClass('invalid')
else
@el.container.addClass('valid')
@el.container.removeClass('invalid')
@_log("*** rendering complete ***")
# We should *always* show initial validation errors; they shouldn't show and
# hide with the rest of the errors unless their value has been changed.
showInitialValidationErrors: ->
for fieldName, state of @_initialValidationState
if state is false and @_validationState[fieldName] is false
# if the error hasn't been rectified
@_inputViews[fieldName].addClass('invalid')
else
@_inputViews[fieldName].removeClass('invalid')
showValidationErrors: ->
for fieldName, state of @_validationState
if state is true
@_inputViews[fieldName].removeClass('invalid')
else
@_inputViews[fieldName].addClass('invalid')
hideValidationErrors: ->
for fieldName, state of @_validationState
if (@_initialValidationState[fieldName] is false and state is true) or
(not @_initialValidationState[fieldName]?)
@_inputViews[fieldName].el.removeClass('invalid')
setFieldValidationState: (fieldName, valid)->
if valid
@el.underlyingFields[fieldName].removeClass('invalid')
else
@el.underlyingFields[fieldName].addClass('invalid')
@_validationState[fieldName] = valid
isFaceFilled: (faceName)->
fields = @fieldsForFace(faceName)
filled = (name for name in fields when @_inputViews[name].isFilled())
if fields.length > 0
return filled.length is fields.length
else
return false
fieldsForFace: (faceName)->
if @product?.layout
return (fn for fn, face of @product.layout when face is faceName)
return []
_updateValidationStateForInputView: (fieldName)->
field = @_inputViews[fieldName]
fieldValid = field.isValid() and
not (@_initialValidationState[fieldName] is false and
field.getValue() is @options.initialValues[fieldName])
# trigger a change event if the field has changed
if fieldValid isnt @_validationState[fieldName]
@setFieldValidationState(fieldName, fieldValid)
# Update the fill state
@_faceFillState.front = @isFaceFilled('front')
@_faceFillState.back = @isFaceFilled('back')
@trigger('validationStateDidChange.skeuocard', [@, @_validationState])
@_log("Change in validation for #{fieldName} triggers re-render.")
@render()
isFaceValid: (faceName)->
valid = true
for fieldName in @fieldsForFace(faceName)
valid &= @_validationState[fieldName]
return !!valid
isValid: ->
@_validationState.number and
@_validationState.exp and
@_validationState.name and
@_validationState.cvc
# Get a value from the underlying form.
_getUnderlyingValue: (field)->
@el.underlyingFields[field].val()
# Set a value in the underlying form.
_setUnderlyingValue: (field, newValue)->
@trigger('change.skeuocard', [@]) # changing the underlying value triggers a change.
@el.underlyingFields[field].val(newValue)
# Flip the card over.
flip: ->
targetFace = if @visibleFace is 'front' then 'back' else 'front'
@trigger('faceWillBecomeVisible.skeuocard', [@, targetFace])
@visibleFace = targetFace
@render()
@el.cardBody.toggleClass('flip')
@trigger('faceDidBecomeVisible.skeuocard', [@, targetFace])
getProductForNumber: (num)->
for m, d of @acceptedCardProducts
parts = m.split('/')
matcher = new RegExp(parts[1], parts[2])
if matcher.test(num)
issuer = @getIssuerForNumber(num) || {}
return $.extend({}, d, issuer)
return undefined
getIssuerForNumber: (num)->
for m, d of CCIssuers
parts = m.split('/')
matcher = new RegExp(parts[1], parts[2])
if matcher.test(num)
return d
return undefined
_setUnderlyingCardType: (shortname)->
@el.underlyingFields.type.find('option').each (i, _el)=>
el = $(_el)
if shortname is (el.attr('data-card-product-shortname') || el.attr('value'))
el.val(el.attr('value')) # change which option is selected
trigger: (args...)->
@el.container.trigger(args...)
bind: (args...)->
@el.container.trigger(args...)
###
Skeuocard::FlipTabView
Handles rendering of the "flip button" control and its various warning and
prompt states.
###
class Skeuocard::FlipTabView
constructor: (face, opts = {})->
@el = $("<div class=\"flip-tab #{face}\"><p></p></div>")
@options = opts
_setText: (text)->
@el.find('p').html(text)
warn: (message, withAnimation = false)->
@_resetClasses()
@el.addClass('warn')
@_setText(message)
@show()
if withAnimation
@el.removeClass('warn-anim')
@el.addClass('warn-anim')
prompt: (message, withAnimation = false)->
@_resetClasses()
@el.addClass('prompt')
@_setText(message)
@show()
if withAnimation
@el.removeClass('valid-anim')
@el.addClass('valid-anim')
_resetClasses: ->
@el.removeClass('valid-anim')
@el.removeClass('warn-anim')
@el.removeClass('warn')
@el.removeClass('prompt')
show: ->
@el.show()
hide: ->
@el.hide()
###
Skeuocard::TextInputView
###
class Skeuocard::TextInputView
bind: (args...)->
@el.bind(args...)
trigger: (args...)->
@el.trigger(args...)
_getFieldCaretPosition: (el)->
input = el.get(0)
if input.selectionEnd?
return input.selectionEnd
else if document.selection
input.focus()
sel = document.selection.createRange()
selLength = document.selection.createRange().text.length
sel.moveStart('character', -input.value.length)
return selLength
_setFieldCaretPosition: (el, pos)->
input = el.get(0)
if input.createTextRange?
range = input.createTextRange()
range.move "character", pos
range.select()
else if input.selectionStart?
input.focus()
input.setSelectionRange(pos, pos)
show: ->
@el.show()
hide: ->
@el.hide()
addClass: (args...)->
@el.addClass(args...)
removeClass: (args...)->
@el.removeClass(args...)
_zeroPadNumber: (num, places)->
zero = places - num.toString().length + 1
return Array(zero).join("0") + num
class Skeuocard::SegmentedCardNumberInputView extends Skeuocard::TextInputView
constructor: (opts = {})->
# Setup option defaults
opts.value ||= ""
opts.groupings ||= [19]
opts.placeholderChar ||= "X"
@options = opts
# everythIng else
@value = @options.value
@el = $("<fieldset>")
@el.delegate "input", "keydown", (e)=> @_onGroupKeyDown(e)
@el.delegate "input", "keyup", (e)=> @_onGroupKeyUp(e)
@groupEls = $()
_onGroupKeyDown: (e)->
e.stopPropagation()
groupEl = $(e.currentTarget)
arrowKeys = [37, 38, 39, 40]
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
if e.which is 8 and groupCaretPos is 0 and not $.isEmptyObject(groupEl.prev())
groupEl.prev().focus()
if e.which in arrowKeys
switch e.which
when 37 # left
if groupCaretPos is 0 and not $.isEmptyObject(groupEl.prev())
groupEl.prev().focus()
when 39 # right
if groupCaretPos is groupMaxLength and not $.isEmptyObject(groupEl.next())
groupEl.next().focus()
when 38 # up
if not $.isEmptyObject(groupEl.prev())
groupEl.prev().focus()
when 40 # down
if not $.isEmptyObject(groupEl.next())
groupEl.next().focus()
_onGroupKeyUp: (e)->
e.stopPropagation() # prevent event from bubbling up
specialKeys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36,
37, 38, 39, 40, 45, 46, 91, 93, 144, 145, 224]
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
if e.which not in specialKeys
# intercept bad chars, returning user to the right char pos if need be
groupValLength = groupEl.val().length
pattern = new RegExp('[^0-9]+', 'g')
groupEl.val(groupEl.val().replace(pattern, ''))
if groupEl.val().length < groupValLength # we caught bad char
@_setFieldCaretPosition(groupEl, groupCaretPos - 1)
else
@_setFieldCaretPosition(groupEl, groupCaretPos)
if e.which not in specialKeys and
groupEl.val().length is groupMaxLength and
not $.isEmptyObject(groupEl.next()) and
@_getFieldCaretPosition(groupEl) is groupMaxLength
groupEl.next().focus()
# update the value
newValue = ""
@groupEls.each -> newValue += $(@).val()
@value = newValue
@trigger("keyup", [@])
return false
setGroupings: (groupings)->
caretPos = @_caretPosition()
@el.empty() # remove all inputs
_startLength = 0
for groupLength in groupings
groupEl = $("<input>").attr
type: 'text'
size: groupLength
maxlength: groupLength
class: "group#{groupLength}"
# restore value, if necessary
if @value.length > _startLength
groupEl.val(@value.substr(_startLength, groupLength))
_startLength += groupLength
@el.append(groupEl)
@options.groupings = groupings
@groupEls = @el.find("input")
# restore to previous settings
@_caretTo(caretPos)
if @options.placeholderChar isnt undefined
@setPlaceholderChar(@options.placeholderChar)
if @options.placeholder isnt undefined
@setPlaceholder(@options.placeholder)
setPlaceholderChar: (ch)->
@groupEls.each ->
el = $(@)
el.attr 'placeholder', new Array(parseInt(el.attr('maxlength'))+1).join(ch)
@options.placeholder = undefined
@options.placeholderChar = ch
setPlaceholder: (str)->
@groupEls.each ->
$(@).attr 'placeholder', str
@options.placeholderChar = undefined
@options.placeholder = str
setValue: (newValue)->
lastPos = 0
@groupEls.each ->
el = $(@)
len = parseInt(el.attr('maxlength'))
el.val(newValue.substr(lastPos, len))
lastPos += len
@value = newValue
getValue: ->
@value
reconfigure: (changes = {})->
if changes.groupings?
@setGroupings(changes.groupings)
if changes.placeholderChar?
@setPlaceholderChar(changes.placeholderChar)
if changes.placeholder?
@setPlaceholder(changes.placeholder)
if changes.value?
@setValue(changes.value)
_caretTo: (index)->
pos = 0
inputEl = undefined
inputElIndex = 0
# figure out which group we're in
@groupEls.each (i, e)=>
el = $(e)
elLength = parseInt(el.attr('maxlength'))
if index <= elLength + pos and index >= pos
inputEl = el
inputElIndex = index - pos
pos += elLength
# move the caret there
@_setFieldCaretPosition(inputEl, inputElIndex)
_caretPosition: ->
iPos = 0
finalPos = 0
@groupEls.each (i, e)=>
el = $(e)
if el.is(':focus')
finalPos = iPos + @_getFieldCaretPosition(el)
iPos += parseInt(el.attr('maxlength'))
return finalPos
maxLength: ->
@options.groupings.reduce((a,b)->(a+b))
isFilled: ->
@value.length == @maxLength()
isValid: ->
@isFilled() and @isValidLuhn(@value)
isValidLuhn: (identifier)->
sum = 0
alt = false
for i in [identifier.length - 1..0] by -1
num = parseInt identifier.charAt(i), 10
return false if isNaN(num)
if alt
num *= 2
num = (num % 10) + 1 if num > 9
alt = !alt
sum += num
sum % 10 is 0
###
Skeuocard::ExpirationInputView
###
class Skeuocard::ExpirationInputView extends Skeuocard::TextInputView
constructor: (opts = {})->
# setup option defaults
opts.dateFormatter ||= (date)->
date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear()
opts.dateParser ||= (value)->
dateParts = value.split('-')
new Date(dateParts[2], dateParts[1]-1, dateParts[0])
opts.currentDate ||= new Date()
opts.pattern ||= "MM/YY"
@options = opts
# setup default values
@date = undefined
@value = undefined
# create dom container
@el = $("<fieldset>")
@el.delegate "input", "keydown", (e)=> @_onKeyDown(e)
@el.delegate "input", "keyup", (e)=> @_onKeyUp(e)
_getFieldCaretPosition: (el)->
input = el.get(0)
if input.selectionEnd?
return input.selectionEnd
else if document.selection
input.focus()
sel = document.selection.createRange()
selLength = document.selection.createRange().text.length
sel.moveStart('character', -input.value.length)
return selLength
_setFieldCaretPosition: (el, pos)->
input = el.get(0)
if input.createTextRange?
range = input.createTextRange()
range.move "character", pos
range.select()
else if input.selectionStart?
input.focus()
input.setSelectionRange(pos, pos)
setPattern: (pattern)->
groupings = []
patternParts = pattern.split('')
_currentLength = 0
for char, i in patternParts
_currentLength++
if patternParts[i+1] != char
groupings.push([_currentLength, char])
_currentLength = 0
@options.groupings = groupings
@_setGroupings(@options.groupings)
_setGroupings: (groupings)->
fieldChars = ['D', 'M', 'Y']
@el.empty()
_startLength = 0
for group in groupings
groupLength = group[0]
groupChar = group[1]
if groupChar in fieldChars # this group is a field
input = $('<input>').attr
type: 'text'
placeholder: new Array(groupLength+1).join(groupChar)
maxlength: groupLength
class: 'cc-exp-field-' + groupChar.toLowerCase() +
' group' + groupLength
input.data('fieldtype', groupChar)
@el.append(input)
else # this group is a separator
sep = $('<span>').attr
class: 'separator'
sep.html(new Array(groupLength + 1).join(groupChar))
@el.append(sep)
@groupEls = @el.find('input')
@_updateFieldValues() if @date?
_updateFieldValues: ->
currentDate = @date
unless @groupEls # they need to be created
return @setPattern(@options.pattern)
@groupEls.each (i,_el)=>
el = $(_el)
groupLength = parseInt(el.attr('maxlength'))
switch el.data('fieldtype')
when 'M'
el.val @_zeroPadNumber(currentDate.getMonth() + 1, groupLength)
when 'D'
el.val @_zeroPadNumber(currentDate.getDate(), groupLength)
when 'Y'
year = if groupLength >= 4 then currentDate.getFullYear() else
currentDate.getFullYear().toString().substr(2,4)
el.val(year)
clear: ->
@value = ""
@date = null
@groupEls.each ->
$(@).val('')
setDate: (newDate)->
@date = newDate
@value = @options.dateFormatter(newDate)
@_updateFieldValues()
setValue: (newValue)->
@value = newValue
@date = @options.dateParser(newValue)
@_updateFieldValues()
getDate: ->
@date
getValue: ->
@value
reconfigure: (opts)->
if opts.pattern?
@setPattern(opts.pattern)
if opts.value?
@setValue(opts.value)
_onKeyDown: (e)->
e.stopPropagation()
groupEl = $(e.currentTarget)
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
prevInputEl = groupEl.prevAll('input').first()
nextInputEl = groupEl.nextAll('input').first()
# Handle delete key
if e.which is 8 and groupCaretPos is 0 and
not $.isEmptyObject(prevInputEl)
prevInputEl.focus()
if e.which in [37, 38, 39, 40] # arrow keys
switch e.which
when 37 # left
if groupCaretPos is 0 and not $.isEmptyObject(prevInputEl)
prevInputEl.focus()
when 39 # right
if groupCaretPos is groupMaxLength and not $.isEmptyObject(nextInputEl)
nextInputEl.focus()
when 38 # up
if not $.isEmptyObject(groupEl.prev('input'))
prevInputEl.focus()
when 40 # down
if not $.isEmptyObject(groupEl.next('input'))
nextInputEl.focus()
_onKeyUp: (e)->
e.stopPropagation()
specialKeys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36,
37, 38, 39, 40, 45, 46, 91, 93, 144, 145, 224]
arrowKeys = [37, 38, 39, 40]
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
if e.which not in specialKeys
# intercept bad chars, returning user to the right char pos if need be
groupValLength = groupEl.val().length
pattern = new RegExp('[^0-9]+', 'g')
groupEl.val(groupEl.val().replace(pattern, ''))
if groupEl.val().length < groupValLength # we caught bad char
@_setFieldCaretPosition(groupEl, groupCaretPos - 1)
else
@_setFieldCaretPosition(groupEl, groupCaretPos)
nextInputEl = groupEl.nextAll('input').first()
if e.which not in specialKeys and
groupEl.val().length is groupMaxLength and
not $.isEmptyObject(nextInputEl) and
@_getFieldCaretPosition(groupEl) is groupMaxLength
nextInputEl.focus()
# get a date object representing what's been entered
day = parseInt(@el.find('.cc-exp-field-d').val()) || 1
month = parseInt(@el.find('.cc-exp-field-m').val())
year = parseInt(@el.find('.cc-exp-field-y').val())
if month is 0 or year is 0
@value = ""
@date = null
else
year += 2000 if year < 2000
dateObj = new Date(year, month-1, day)
@value = @options.dateFormatter(dateObj)
@date = dateObj
@trigger("keyup", [@])
return false
_inputGroupEls: ->
@el.find("input")
isFilled: ->
for inputEl in @groupEls
el = $(inputEl)
return false if el.val().length != parseInt(el.attr('maxlength'))
return true
isValid: ->
@isFilled() and
((@date.getFullYear() == @options.currentDate.getFullYear() and
@date.getMonth() >= @options.currentDate.getMonth()) or
@date.getFullYear() > @options.currentDate.getFullYear())
class Skeuocard::TextInputView extends Skeuocard::TextInputView
constructor: (opts)->
@el = $("<input>").attr
type: 'text'
placeholder: opts.placeholder
class: opts.class
@options = opts
clear: ->
@el.val("")
attr: (args...)->
@el.attr(args...)
isFilled: ->
return @el.val().length > 0
isValid: ->
if @options.requireMaxLength
return @el.val().length is parseInt(@el.attr('maxlength'))
else
return @isFilled()
getValue: ->
@el.val()
# Export the object.
window.Skeuocard = Skeuocard
###
# Card Definitions
###
# List of credit card products by matching prefix.
CCProducts = {}
CCProducts[/^30[0-5][0-9]/] =
companyName: "<NAME>"
companyShortname: "dinersclubintl"
cardNumberGrouping: [4,6,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^3095/] =
companyName: "Diners Club International"
companyShortname: "dinersclubintl"
cardNumberGrouping: [4,6,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^36\d{2}/] =
companyName: "Diners Club International"
companyShortname: "dinersclubintl"
cardNumberGrouping: [4,6,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^35\d{2}/] =
companyName: "JCB"
companyShortname: "jcb"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^37/] =
companyName: "American Express"
companyShortname: "amex"
cardNumberGrouping: [4,6,5]
expirationFormat: "MM/YY"
cvcLength: 4
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'front'
CCProducts[/^38/] =
companyName: "<NAME>"
companyShortname: "hipercard"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^4[0-9]\d{2}/] =
companyName: "Visa"
companyShortname: "visa"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^5[0-8]\d{2}/] =
companyName: "<NAME>"
companyShortname: "<NAME>"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^6011/] =
companyName: "Discover"
companyShortname: "discover"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCIssuers = {}
###
Hack fixes the Chase Sapphire card's stupid (nice?) layout non-conformity.
###
CCIssuers[/^414720/] =
issuingAuthority: "Chase"
issuerName: "<NAME>"
issuerShortname: "chase-sapphire"
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'front'
| true | ###
"Skeuocard" -- A Skeuomorphic Credit-Card Input Enhancement
@description Skeuocard is a skeuomorphic credit card input plugin, supporting
progressive enhancement. It renders a credit-card input which
behaves similarly to a physical credit card.
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
@updated 2013-07-25
@website http://kenkeiter.com/
@exports [window.Skeuocard]
###
class Skeuocard
constructor: (el, opts = {})->
@el = {container: $(el), underlyingFields: {}}
@_inputViews = {}
@_tabViews = {}
@product = undefined
@productShortname = undefined
@issuerShortname = undefined
@_cardProductNeedsLayout = true
@acceptedCardProducts = {}
@visibleFace = 'front'
@_initialValidationState = {}
@_validationState = {number: false, exp: false, name: false, cvc: false}
@_faceFillState = {front: false, back: false}
# configure default opts
optDefaults =
debug: false
acceptedCardProducts: []
cardNumberPlaceholderChar: 'X'
genericPlaceholder: "XXXX XXXX XXXX XXXX"
typeInputSelector: '[name="cc_type"]'
numberInputSelector: '[name="cc_number"]'
expInputSelector: '[name="cc_exp"]'
nameInputSelector: '[name="cc_name"]'
cvcInputSelector: '[name="cc_cvc"]'
currentDate: new Date()
initialValues: {}
validationState: {}
strings:
hiddenFaceFillPrompt: "Click here to<br /> fill in the other side."
hiddenFaceErrorWarning: "There's a problem on the other side."
hiddenFaceSwitchPrompt: "Back to the other side..."
@options = $.extend(optDefaults, opts)
# initialize the card
@_conformDOM() # conform the DOM to match our styling requirements
@_setAcceptedCardProducts() # determine which card products to accept
@_createInputs() # create reconfigurable input views
@_updateProductIfNeeded()
@_flipToInvalidSide()
# Transform the elements within the container, conforming the DOM so that it
# becomes styleable, and that the underlying inputs are hidden.
_conformDOM: ->
# for CSS determination that this is an enhanced input, add 'js' class to
# the container
@el.container.removeClass('no-js')
@el.container.addClass("skeuocard js")
# remove anything that's not an underlying form field
@el.container.find("> :not(input,select,textarea)").remove()
@el.container.find("> input,select,textarea").hide()
# attach underlying form elements
@el.underlyingFields =
type: @el.container.find(@options.typeInputSelector)
number: @el.container.find(@options.numberInputSelector)
exp: @el.container.find(@options.expInputSelector)
name: @el.container.find(@options.nameInputSelector)
cvc: @el.container.find(@options.cvcInputSelector)
# sync initial values, with constructor options taking precedence
for fieldName, fieldValue of @options.initialValues
@el.underlyingFields[fieldName].val(fieldValue)
for fieldName, el of @el.underlyingFields
@options.initialValues[fieldName] = el.val()
# sync initial validation state, with constructor options taking precedence
# we use the underlying form values to track state
for fieldName, el of @el.underlyingFields
if @options.validationState[fieldName] is false or el.hasClass('invalid')
@_initialValidationState[fieldName] = false
unless el.hasClass('invalid')
el.addClass('invalid')
# bind change handlers to render
@el.underlyingFields.number.bind "change", (e)=>
@_inputViews.number.setValue @_getUnderlyingValue('number')
@render()
@el.underlyingFields.exp.bind "change", (e)=>
@_inputViews.exp.setValue @_getUnderlyingValue('exp')
@render()
@el.underlyingFields.name.bind "change", (e)=>
@_inputViews.exp.setValue @_getUnderlyingValue('name')
@render()
@el.underlyingFields.cvc.bind "change", (e)=>
@_inputViews.exp.setValue @_getUnderlyingValue('cvc')
@render()
# construct the necessary card elements
@el.surfaceFront = $("<div>").attr(class: "face front")
@el.surfaceBack = $("<div>").attr(class: "face back")
@el.cardBody = $("<div>").attr(class: "card-body")
# add elements to the DOM
@el.surfaceFront.appendTo(@el.cardBody)
@el.surfaceBack.appendTo(@el.cardBody)
@el.cardBody.appendTo(@el.container)
# create the validation indicator (flip tab), and attach them.
@_tabViews.front = new @FlipTabView('front')
@_tabViews.back = new @FlipTabView('back')
@el.surfaceFront.prepend(@_tabViews.front.el)
@el.surfaceBack.prepend(@_tabViews.back.el)
@_tabViews.front.hide()
@_tabViews.back.hide()
@_tabViews.front.el.click =>
@flip()
@_tabViews.back.el.click =>
@flip()
return @el.container
_setAcceptedCardProducts: ->
# build the set of accepted card products
if @options.acceptedCardProducts.length is 0
@el.underlyingFields.type.find('option').each (i, _el)=>
el = $(_el)
cardProductShortname = el.attr('data-card-product-shortname') || el.attr('value')
@options.acceptedCardProducts.push cardProductShortname
# find all matching card products by shortname, and add them to the
# list of @acceptedCardProducts
for matcher, product of CCProducts
if product.companyShortname in @options.acceptedCardProducts
@acceptedCardProducts[matcher] = product
return @acceptedCardProducts
_updateProductIfNeeded: ->
# determine if product changed; if so, change it globally, and
# call render() to render the changes.
number = @_getUnderlyingValue('number')
matchedProduct = @getProductForNumber(number)
matchedProductIdentifier = matchedProduct?.companyShortname || ''
matchedIssuerIdentifier = matchedProduct?.issuerShortname || ''
if (@productShortname isnt matchedProductIdentifier) or
(@issuerShortname isnt matchedIssuerIdentifier)
@productShortname = matchedProductIdentifier
@issuerShortname = matchedIssuerIdentifier
@product = matchedProduct
@_cardProductNeedsLayout = true
@trigger 'productWillChange.skeuocard',
[@, @productShortname, matchedProductIdentifier]
@_log("Triggering render because product changed.")
@render()
@trigger('productDidChange.skeuocard', [@, @productShortname, matchedProductIdentifier])
# Create the new inputs, and attach them to their appropriate card face els.
_createInputs: ->
@_inputViews.number = new @SegmentedCardNumberInputView()
@_inputViews.exp = new @ExpirationInputView(currentDate: @options.currentDate)
@_inputViews.name = new @TextInputView(
class: "cc-name", placeholder: "YOUR NAME")
@_inputViews.cvc = new @TextInputView(
class: "cc-cvc", placeholder: "XXX", requireMaxLength: true)
# style and attach the number view to the DOM
@_inputViews.number.el.addClass('cc-number')
@_inputViews.number.el.appendTo(@el.surfaceFront)
# attach name input
@_inputViews.name.el.appendTo(@el.surfaceFront)
# style and attach the exp view to the DOM
@_inputViews.exp.el.addClass('cc-exp')
@_inputViews.exp.el.appendTo(@el.surfaceFront)
# attach cvc field to the DOM
@_inputViews.cvc.el.appendTo(@el.surfaceBack)
# bind change events to their underlying form elements
@_inputViews.number.bind "keyup", (e, input)=>
@_setUnderlyingValue('number', input.value)
@_updateValidationStateForInputView('number')
@_updateProductIfNeeded()
@_inputViews.exp.bind "keyup", (e, input)=>
@_setUnderlyingValue('exp', input.value)
@_updateValidationStateForInputView('exp')
@_inputViews.name.bind "keyup", (e)=>
@_setUnderlyingValue('name', $(e.target).val())
@_updateValidationStateForInputView('name')
@_inputViews.cvc.bind "keyup", (e)=>
@_setUnderlyingValue('cvc', $(e.target).val())
@_updateValidationStateForInputView('cvc')
# setup default values; when render is called, these will be picked up
@_inputViews.number.setValue @_getUnderlyingValue('number')
@_inputViews.exp.setValue @_getUnderlyingValue('exp')
@_inputViews.name.el.val @_getUnderlyingValue('name')
@_inputViews.cvc.el.val @_getUnderlyingValue('cvc')
# Debugging helper; if debug is set to true at instantiation, messages will
# be printed to the console.
_log: (msg...)->
if console?.log and !!@options.debug
console.log("[skeuocard]", msg...) if @options.debug?
_flipToInvalidSide: ->
if Object.keys(@_initialValidationState).length > 0
_oppositeFace = if @visibleFace is 'front' then 'back' else 'front'
# if the back face has errors, and the front does not, flip there.
_errorCounts = {front: 0, back: 0}
for fieldName, state of @_initialValidationState
_errorCounts[@product?.layout[fieldName]]++
if _errorCounts[@visibleFace] == 0 and _errorCounts[_oppositeFace] > 0
@flip()
# Update the card's visual representation to reflect internal state.
render: ->
@_log("*** start rendering ***")
# Render card product layout changes.
if @_cardProductNeedsLayout is true
# Update product-specific details
if @product isnt undefined
# change the design and layout of the card to match the matched prod.
@_log("[render]", "Activating product", @product)
@el.container.removeClass (index, css)=>
(css.match(/\b(product|issuer)-\S+/g) || []).join(' ')
@el.container.addClass("product-#{@product.companyShortname}")
if @product.issuerShortname?
@el.container.addClass("issuer-#{@product.issuerShortname}")
# Adjust underlying card type to match detected type
@_setUnderlyingCardType(@product.companyShortname)
# Reconfigure input to match product
@_inputViews.number.reconfigure
groupings: @product.cardNumberGrouping
placeholderChar: @options.cardNumberPlaceholderChar
@_inputViews.exp.show()
@_inputViews.name.show()
@_inputViews.exp.reconfigure
pattern: @product.expirationFormat
@_inputViews.cvc.show()
@_inputViews.cvc.attr
maxlength: @product.cvcLength
placeholder: new Array(@product.cvcLength + 1).join(@options.cardNumberPlaceholderChar)
for fieldName, surfaceName of @product.layout
sel = if surfaceName is 'front' then 'surfaceFront' else 'surfaceBack'
container = @el[sel]
inputEl = @_inputViews[fieldName].el
unless container.has(inputEl).length > 0
@_log("Moving", inputEl, "=>", container)
el = @_inputViews[fieldName].el.detach()
$(el).appendTo(@el[sel])
else
@_log("[render]", "Becoming generic.")
# Reset to generic input
@_inputViews.exp.clear()
@_inputViews.cvc.clear()
@_inputViews.exp.hide()
@_inputViews.name.hide()
@_inputViews.cvc.hide()
@_inputViews.number.reconfigure
groupings: [@options.genericPlaceholder.length],
placeholder: @options.genericPlaceholder
@el.container.removeClass (index, css)=>
(css.match(/\bproduct-\S+/g) || []).join(' ')
@el.container.removeClass (index, css)=>
(css.match(/\bissuer-\S+/g) || []).join(' ')
@_cardProductNeedsLayout = false
@_log("Validation state:", @_validationState)
# Render validation changes
@showInitialValidationErrors()
# If the current face is filled, and there are validation errors, show 'em
_oppositeFace = if @visibleFace is 'front' then 'back' else 'front'
_visibleFaceFilled = @_faceFillState[@visibleFace]
_visibleFaceValid = @isFaceValid(@visibleFace)
_hiddenFaceFilled = @_faceFillState[_oppositeFace]
_hiddenFaceValid = @isFaceValid(_oppositeFace)
if _visibleFaceFilled and not _visibleFaceValid
@_log("Visible face is filled, but invalid; showing validation errors.")
@showValidationErrors()
else if not _visibleFaceFilled
@_log("Visible face hasn't been filled; hiding validation errors.")
@hideValidationErrors()
else
@_log("Visible face has been filled, and is valid.")
@hideValidationErrors()
if @visibleFace is 'front' and @fieldsForFace('back').length > 0
if _visibleFaceFilled and _visibleFaceValid and not _hiddenFaceFilled
@_tabViews.front.prompt(@options.strings.hiddenFaceFillPrompt, true)
else if _hiddenFaceFilled and not _hiddenFaceValid
@_tabViews.front.warn(@options.strings.hiddenFaceErrorWarning, true)
else if _hiddenFaceFilled and _hiddenFaceValid
@_tabViews.front.prompt(@options.strings.hiddenFaceSwitchPrompt, true)
else
@_tabViews.front.hide()
else
if _hiddenFaceValid
@_tabViews.back.prompt(@options.strings.hiddenFaceSwitchPrompt, true)
else
@_tabViews.back.warn(@options.strings.hiddenFaceErrorWarning, true)
# Update the validity indicator for the whole card body
if not @isValid()
@el.container.removeClass('valid')
@el.container.addClass('invalid')
else
@el.container.addClass('valid')
@el.container.removeClass('invalid')
@_log("*** rendering complete ***")
# We should *always* show initial validation errors; they shouldn't show and
# hide with the rest of the errors unless their value has been changed.
showInitialValidationErrors: ->
for fieldName, state of @_initialValidationState
if state is false and @_validationState[fieldName] is false
# if the error hasn't been rectified
@_inputViews[fieldName].addClass('invalid')
else
@_inputViews[fieldName].removeClass('invalid')
showValidationErrors: ->
for fieldName, state of @_validationState
if state is true
@_inputViews[fieldName].removeClass('invalid')
else
@_inputViews[fieldName].addClass('invalid')
hideValidationErrors: ->
for fieldName, state of @_validationState
if (@_initialValidationState[fieldName] is false and state is true) or
(not @_initialValidationState[fieldName]?)
@_inputViews[fieldName].el.removeClass('invalid')
setFieldValidationState: (fieldName, valid)->
if valid
@el.underlyingFields[fieldName].removeClass('invalid')
else
@el.underlyingFields[fieldName].addClass('invalid')
@_validationState[fieldName] = valid
isFaceFilled: (faceName)->
fields = @fieldsForFace(faceName)
filled = (name for name in fields when @_inputViews[name].isFilled())
if fields.length > 0
return filled.length is fields.length
else
return false
fieldsForFace: (faceName)->
if @product?.layout
return (fn for fn, face of @product.layout when face is faceName)
return []
_updateValidationStateForInputView: (fieldName)->
field = @_inputViews[fieldName]
fieldValid = field.isValid() and
not (@_initialValidationState[fieldName] is false and
field.getValue() is @options.initialValues[fieldName])
# trigger a change event if the field has changed
if fieldValid isnt @_validationState[fieldName]
@setFieldValidationState(fieldName, fieldValid)
# Update the fill state
@_faceFillState.front = @isFaceFilled('front')
@_faceFillState.back = @isFaceFilled('back')
@trigger('validationStateDidChange.skeuocard', [@, @_validationState])
@_log("Change in validation for #{fieldName} triggers re-render.")
@render()
isFaceValid: (faceName)->
valid = true
for fieldName in @fieldsForFace(faceName)
valid &= @_validationState[fieldName]
return !!valid
isValid: ->
@_validationState.number and
@_validationState.exp and
@_validationState.name and
@_validationState.cvc
# Get a value from the underlying form.
_getUnderlyingValue: (field)->
@el.underlyingFields[field].val()
# Set a value in the underlying form.
_setUnderlyingValue: (field, newValue)->
@trigger('change.skeuocard', [@]) # changing the underlying value triggers a change.
@el.underlyingFields[field].val(newValue)
# Flip the card over.
flip: ->
targetFace = if @visibleFace is 'front' then 'back' else 'front'
@trigger('faceWillBecomeVisible.skeuocard', [@, targetFace])
@visibleFace = targetFace
@render()
@el.cardBody.toggleClass('flip')
@trigger('faceDidBecomeVisible.skeuocard', [@, targetFace])
getProductForNumber: (num)->
for m, d of @acceptedCardProducts
parts = m.split('/')
matcher = new RegExp(parts[1], parts[2])
if matcher.test(num)
issuer = @getIssuerForNumber(num) || {}
return $.extend({}, d, issuer)
return undefined
getIssuerForNumber: (num)->
for m, d of CCIssuers
parts = m.split('/')
matcher = new RegExp(parts[1], parts[2])
if matcher.test(num)
return d
return undefined
_setUnderlyingCardType: (shortname)->
@el.underlyingFields.type.find('option').each (i, _el)=>
el = $(_el)
if shortname is (el.attr('data-card-product-shortname') || el.attr('value'))
el.val(el.attr('value')) # change which option is selected
trigger: (args...)->
@el.container.trigger(args...)
bind: (args...)->
@el.container.trigger(args...)
###
Skeuocard::FlipTabView
Handles rendering of the "flip button" control and its various warning and
prompt states.
###
class Skeuocard::FlipTabView
constructor: (face, opts = {})->
@el = $("<div class=\"flip-tab #{face}\"><p></p></div>")
@options = opts
_setText: (text)->
@el.find('p').html(text)
warn: (message, withAnimation = false)->
@_resetClasses()
@el.addClass('warn')
@_setText(message)
@show()
if withAnimation
@el.removeClass('warn-anim')
@el.addClass('warn-anim')
prompt: (message, withAnimation = false)->
@_resetClasses()
@el.addClass('prompt')
@_setText(message)
@show()
if withAnimation
@el.removeClass('valid-anim')
@el.addClass('valid-anim')
_resetClasses: ->
@el.removeClass('valid-anim')
@el.removeClass('warn-anim')
@el.removeClass('warn')
@el.removeClass('prompt')
show: ->
@el.show()
hide: ->
@el.hide()
###
Skeuocard::TextInputView
###
class Skeuocard::TextInputView
bind: (args...)->
@el.bind(args...)
trigger: (args...)->
@el.trigger(args...)
_getFieldCaretPosition: (el)->
input = el.get(0)
if input.selectionEnd?
return input.selectionEnd
else if document.selection
input.focus()
sel = document.selection.createRange()
selLength = document.selection.createRange().text.length
sel.moveStart('character', -input.value.length)
return selLength
_setFieldCaretPosition: (el, pos)->
input = el.get(0)
if input.createTextRange?
range = input.createTextRange()
range.move "character", pos
range.select()
else if input.selectionStart?
input.focus()
input.setSelectionRange(pos, pos)
show: ->
@el.show()
hide: ->
@el.hide()
addClass: (args...)->
@el.addClass(args...)
removeClass: (args...)->
@el.removeClass(args...)
_zeroPadNumber: (num, places)->
zero = places - num.toString().length + 1
return Array(zero).join("0") + num
class Skeuocard::SegmentedCardNumberInputView extends Skeuocard::TextInputView
constructor: (opts = {})->
# Setup option defaults
opts.value ||= ""
opts.groupings ||= [19]
opts.placeholderChar ||= "X"
@options = opts
# everythIng else
@value = @options.value
@el = $("<fieldset>")
@el.delegate "input", "keydown", (e)=> @_onGroupKeyDown(e)
@el.delegate "input", "keyup", (e)=> @_onGroupKeyUp(e)
@groupEls = $()
_onGroupKeyDown: (e)->
e.stopPropagation()
groupEl = $(e.currentTarget)
arrowKeys = [37, 38, 39, 40]
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
if e.which is 8 and groupCaretPos is 0 and not $.isEmptyObject(groupEl.prev())
groupEl.prev().focus()
if e.which in arrowKeys
switch e.which
when 37 # left
if groupCaretPos is 0 and not $.isEmptyObject(groupEl.prev())
groupEl.prev().focus()
when 39 # right
if groupCaretPos is groupMaxLength and not $.isEmptyObject(groupEl.next())
groupEl.next().focus()
when 38 # up
if not $.isEmptyObject(groupEl.prev())
groupEl.prev().focus()
when 40 # down
if not $.isEmptyObject(groupEl.next())
groupEl.next().focus()
_onGroupKeyUp: (e)->
e.stopPropagation() # prevent event from bubbling up
specialKeys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36,
37, 38, 39, 40, 45, 46, 91, 93, 144, 145, 224]
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
if e.which not in specialKeys
# intercept bad chars, returning user to the right char pos if need be
groupValLength = groupEl.val().length
pattern = new RegExp('[^0-9]+', 'g')
groupEl.val(groupEl.val().replace(pattern, ''))
if groupEl.val().length < groupValLength # we caught bad char
@_setFieldCaretPosition(groupEl, groupCaretPos - 1)
else
@_setFieldCaretPosition(groupEl, groupCaretPos)
if e.which not in specialKeys and
groupEl.val().length is groupMaxLength and
not $.isEmptyObject(groupEl.next()) and
@_getFieldCaretPosition(groupEl) is groupMaxLength
groupEl.next().focus()
# update the value
newValue = ""
@groupEls.each -> newValue += $(@).val()
@value = newValue
@trigger("keyup", [@])
return false
setGroupings: (groupings)->
caretPos = @_caretPosition()
@el.empty() # remove all inputs
_startLength = 0
for groupLength in groupings
groupEl = $("<input>").attr
type: 'text'
size: groupLength
maxlength: groupLength
class: "group#{groupLength}"
# restore value, if necessary
if @value.length > _startLength
groupEl.val(@value.substr(_startLength, groupLength))
_startLength += groupLength
@el.append(groupEl)
@options.groupings = groupings
@groupEls = @el.find("input")
# restore to previous settings
@_caretTo(caretPos)
if @options.placeholderChar isnt undefined
@setPlaceholderChar(@options.placeholderChar)
if @options.placeholder isnt undefined
@setPlaceholder(@options.placeholder)
setPlaceholderChar: (ch)->
@groupEls.each ->
el = $(@)
el.attr 'placeholder', new Array(parseInt(el.attr('maxlength'))+1).join(ch)
@options.placeholder = undefined
@options.placeholderChar = ch
setPlaceholder: (str)->
@groupEls.each ->
$(@).attr 'placeholder', str
@options.placeholderChar = undefined
@options.placeholder = str
setValue: (newValue)->
lastPos = 0
@groupEls.each ->
el = $(@)
len = parseInt(el.attr('maxlength'))
el.val(newValue.substr(lastPos, len))
lastPos += len
@value = newValue
getValue: ->
@value
reconfigure: (changes = {})->
if changes.groupings?
@setGroupings(changes.groupings)
if changes.placeholderChar?
@setPlaceholderChar(changes.placeholderChar)
if changes.placeholder?
@setPlaceholder(changes.placeholder)
if changes.value?
@setValue(changes.value)
_caretTo: (index)->
pos = 0
inputEl = undefined
inputElIndex = 0
# figure out which group we're in
@groupEls.each (i, e)=>
el = $(e)
elLength = parseInt(el.attr('maxlength'))
if index <= elLength + pos and index >= pos
inputEl = el
inputElIndex = index - pos
pos += elLength
# move the caret there
@_setFieldCaretPosition(inputEl, inputElIndex)
_caretPosition: ->
iPos = 0
finalPos = 0
@groupEls.each (i, e)=>
el = $(e)
if el.is(':focus')
finalPos = iPos + @_getFieldCaretPosition(el)
iPos += parseInt(el.attr('maxlength'))
return finalPos
maxLength: ->
@options.groupings.reduce((a,b)->(a+b))
isFilled: ->
@value.length == @maxLength()
isValid: ->
@isFilled() and @isValidLuhn(@value)
isValidLuhn: (identifier)->
sum = 0
alt = false
for i in [identifier.length - 1..0] by -1
num = parseInt identifier.charAt(i), 10
return false if isNaN(num)
if alt
num *= 2
num = (num % 10) + 1 if num > 9
alt = !alt
sum += num
sum % 10 is 0
###
Skeuocard::ExpirationInputView
###
class Skeuocard::ExpirationInputView extends Skeuocard::TextInputView
constructor: (opts = {})->
# setup option defaults
opts.dateFormatter ||= (date)->
date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear()
opts.dateParser ||= (value)->
dateParts = value.split('-')
new Date(dateParts[2], dateParts[1]-1, dateParts[0])
opts.currentDate ||= new Date()
opts.pattern ||= "MM/YY"
@options = opts
# setup default values
@date = undefined
@value = undefined
# create dom container
@el = $("<fieldset>")
@el.delegate "input", "keydown", (e)=> @_onKeyDown(e)
@el.delegate "input", "keyup", (e)=> @_onKeyUp(e)
_getFieldCaretPosition: (el)->
input = el.get(0)
if input.selectionEnd?
return input.selectionEnd
else if document.selection
input.focus()
sel = document.selection.createRange()
selLength = document.selection.createRange().text.length
sel.moveStart('character', -input.value.length)
return selLength
_setFieldCaretPosition: (el, pos)->
input = el.get(0)
if input.createTextRange?
range = input.createTextRange()
range.move "character", pos
range.select()
else if input.selectionStart?
input.focus()
input.setSelectionRange(pos, pos)
setPattern: (pattern)->
groupings = []
patternParts = pattern.split('')
_currentLength = 0
for char, i in patternParts
_currentLength++
if patternParts[i+1] != char
groupings.push([_currentLength, char])
_currentLength = 0
@options.groupings = groupings
@_setGroupings(@options.groupings)
_setGroupings: (groupings)->
fieldChars = ['D', 'M', 'Y']
@el.empty()
_startLength = 0
for group in groupings
groupLength = group[0]
groupChar = group[1]
if groupChar in fieldChars # this group is a field
input = $('<input>').attr
type: 'text'
placeholder: new Array(groupLength+1).join(groupChar)
maxlength: groupLength
class: 'cc-exp-field-' + groupChar.toLowerCase() +
' group' + groupLength
input.data('fieldtype', groupChar)
@el.append(input)
else # this group is a separator
sep = $('<span>').attr
class: 'separator'
sep.html(new Array(groupLength + 1).join(groupChar))
@el.append(sep)
@groupEls = @el.find('input')
@_updateFieldValues() if @date?
_updateFieldValues: ->
currentDate = @date
unless @groupEls # they need to be created
return @setPattern(@options.pattern)
@groupEls.each (i,_el)=>
el = $(_el)
groupLength = parseInt(el.attr('maxlength'))
switch el.data('fieldtype')
when 'M'
el.val @_zeroPadNumber(currentDate.getMonth() + 1, groupLength)
when 'D'
el.val @_zeroPadNumber(currentDate.getDate(), groupLength)
when 'Y'
year = if groupLength >= 4 then currentDate.getFullYear() else
currentDate.getFullYear().toString().substr(2,4)
el.val(year)
clear: ->
@value = ""
@date = null
@groupEls.each ->
$(@).val('')
setDate: (newDate)->
@date = newDate
@value = @options.dateFormatter(newDate)
@_updateFieldValues()
setValue: (newValue)->
@value = newValue
@date = @options.dateParser(newValue)
@_updateFieldValues()
getDate: ->
@date
getValue: ->
@value
reconfigure: (opts)->
if opts.pattern?
@setPattern(opts.pattern)
if opts.value?
@setValue(opts.value)
_onKeyDown: (e)->
e.stopPropagation()
groupEl = $(e.currentTarget)
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
prevInputEl = groupEl.prevAll('input').first()
nextInputEl = groupEl.nextAll('input').first()
# Handle delete key
if e.which is 8 and groupCaretPos is 0 and
not $.isEmptyObject(prevInputEl)
prevInputEl.focus()
if e.which in [37, 38, 39, 40] # arrow keys
switch e.which
when 37 # left
if groupCaretPos is 0 and not $.isEmptyObject(prevInputEl)
prevInputEl.focus()
when 39 # right
if groupCaretPos is groupMaxLength and not $.isEmptyObject(nextInputEl)
nextInputEl.focus()
when 38 # up
if not $.isEmptyObject(groupEl.prev('input'))
prevInputEl.focus()
when 40 # down
if not $.isEmptyObject(groupEl.next('input'))
nextInputEl.focus()
_onKeyUp: (e)->
e.stopPropagation()
specialKeys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36,
37, 38, 39, 40, 45, 46, 91, 93, 144, 145, 224]
arrowKeys = [37, 38, 39, 40]
groupEl = $(e.currentTarget)
groupMaxLength = parseInt(groupEl.attr('maxlength'))
groupCaretPos = @_getFieldCaretPosition(groupEl)
if e.which not in specialKeys
# intercept bad chars, returning user to the right char pos if need be
groupValLength = groupEl.val().length
pattern = new RegExp('[^0-9]+', 'g')
groupEl.val(groupEl.val().replace(pattern, ''))
if groupEl.val().length < groupValLength # we caught bad char
@_setFieldCaretPosition(groupEl, groupCaretPos - 1)
else
@_setFieldCaretPosition(groupEl, groupCaretPos)
nextInputEl = groupEl.nextAll('input').first()
if e.which not in specialKeys and
groupEl.val().length is groupMaxLength and
not $.isEmptyObject(nextInputEl) and
@_getFieldCaretPosition(groupEl) is groupMaxLength
nextInputEl.focus()
# get a date object representing what's been entered
day = parseInt(@el.find('.cc-exp-field-d').val()) || 1
month = parseInt(@el.find('.cc-exp-field-m').val())
year = parseInt(@el.find('.cc-exp-field-y').val())
if month is 0 or year is 0
@value = ""
@date = null
else
year += 2000 if year < 2000
dateObj = new Date(year, month-1, day)
@value = @options.dateFormatter(dateObj)
@date = dateObj
@trigger("keyup", [@])
return false
_inputGroupEls: ->
@el.find("input")
isFilled: ->
for inputEl in @groupEls
el = $(inputEl)
return false if el.val().length != parseInt(el.attr('maxlength'))
return true
isValid: ->
@isFilled() and
((@date.getFullYear() == @options.currentDate.getFullYear() and
@date.getMonth() >= @options.currentDate.getMonth()) or
@date.getFullYear() > @options.currentDate.getFullYear())
class Skeuocard::TextInputView extends Skeuocard::TextInputView
constructor: (opts)->
@el = $("<input>").attr
type: 'text'
placeholder: opts.placeholder
class: opts.class
@options = opts
clear: ->
@el.val("")
attr: (args...)->
@el.attr(args...)
isFilled: ->
return @el.val().length > 0
isValid: ->
if @options.requireMaxLength
return @el.val().length is parseInt(@el.attr('maxlength'))
else
return @isFilled()
getValue: ->
@el.val()
# Export the object.
window.Skeuocard = Skeuocard
###
# Card Definitions
###
# List of credit card products by matching prefix.
CCProducts = {}
CCProducts[/^30[0-5][0-9]/] =
companyName: "PI:NAME:<NAME>END_PI"
companyShortname: "dinersclubintl"
cardNumberGrouping: [4,6,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^3095/] =
companyName: "Diners Club International"
companyShortname: "dinersclubintl"
cardNumberGrouping: [4,6,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^36\d{2}/] =
companyName: "Diners Club International"
companyShortname: "dinersclubintl"
cardNumberGrouping: [4,6,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^35\d{2}/] =
companyName: "JCB"
companyShortname: "jcb"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^37/] =
companyName: "American Express"
companyShortname: "amex"
cardNumberGrouping: [4,6,5]
expirationFormat: "MM/YY"
cvcLength: 4
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'front'
CCProducts[/^38/] =
companyName: "PI:NAME:<NAME>END_PI"
companyShortname: "hipercard"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^4[0-9]\d{2}/] =
companyName: "Visa"
companyShortname: "visa"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^5[0-8]\d{2}/] =
companyName: "PI:NAME:<NAME>END_PI"
companyShortname: "PI:NAME:<NAME>END_PI"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCProducts[/^6011/] =
companyName: "Discover"
companyShortname: "discover"
cardNumberGrouping: [4,4,4,4]
expirationFormat: "MM/YY"
cvcLength: 3
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'back'
CCIssuers = {}
###
Hack fixes the Chase Sapphire card's stupid (nice?) layout non-conformity.
###
CCIssuers[/^414720/] =
issuingAuthority: "Chase"
issuerName: "PI:NAME:<NAME>END_PI"
issuerShortname: "chase-sapphire"
layout:
number: 'front'
exp: 'front'
name: 'front'
cvc: 'front'
|
[
{
"context": "#!/usr/bin/env iced\n#\n# Original script written by Vird for Arweave mining on Vird's pool (https://ar.",
"end": 52,
"score": 0.6813979744911194,
"start": 51,
"tag": "NAME",
"value": "V"
},
{
"context": "/usr/bin/env iced\n#\n# Original script written by Vird for Arweave mining on Vird's pool (https://ar.vir",
"end": 55,
"score": 0.6171956658363342,
"start": 52,
"tag": "USERNAME",
"value": "ird"
},
{
"context": "://ar.virdpool.com/)\n# Github: https://github.com/virdpool/miner/blob/master/proxy.coffee\n#\n# Small mods hav",
"end": 154,
"score": 0.9996677041053772,
"start": 146,
"tag": "USERNAME",
"value": "virdpool"
},
{
"context": "#######\nminer_url = argv[\"miner-url\"] ? \"http://127.0.0.1:2984\"\n\napi_network = argv[\"api-network\"] # undefi",
"end": 1206,
"score": 0.9859035015106201,
"start": 1197,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "cb err if err\n{nonce_filter} = res\n\nswitch_key = \"job\"\nloc_opt = {\n sub : switch : \"#{switch_key}_su",
"end": 2144,
"score": 0.997771143913269,
"start": 2141,
"tag": "KEY",
"value": "job"
}
] | proxy.coffee | wxt30/arpanel | 5 | #!/usr/bin/env iced
#
# Original script written by Vird for Arweave mining on Vird's pool (https://ar.virdpool.com/)
# Github: https://github.com/virdpool/miner/blob/master/proxy.coffee
#
# Small mods have been made for arPanel usage. Functionality has not been modified.
# Log file: logs/proxy.log
#
require "fy"
Ws_wrap = require "ws_wrap"
Ws_rs = require "wsrs"
ws_mod_sub= require "ws_mod_sub"
axios = require "axios"
colors = require "colors"
argv = require("minimist")(process.argv.slice(2))
# arPanel Fix
fs = require "fs"
api_secret = argv["api-secret"]
if !argv.wallet or !api_secret
perr "usage ./proxy.coffee --wallet <your wallet> --api-secret <arweave node api secret>"
process.exit 1
argv.worker ?= "default_worker"
puts "Your mining wallet: #{colors.green argv.wallet}"
#puts "For hashrate look at arweave console (this is temporary solution)"
#puts " screen -R virdpool_arweave_miner"
puts ""
# ###################################################################################################
# config
# ###################################################################################################
miner_url = argv["miner-url"] ? "http://127.0.0.1:2984"
api_network = argv["api-network"] # undefined for mainnet
ws_pool_url = argv["ws-pool-url"] ? "ws://ar.virdpool.com:8801"
# TODO? local vardiff for health check
# TODO FUTURE miner_url_list
# ###################################################################################################
cb = (err)->throw err if err
ws = new Ws_wrap ws_pool_url
wsrs = new Ws_rs ws
ws_mod_sub ws, wsrs
do ()=>
loop
await wsrs.request {switch : "ping"}, defer(err)
perr err.message if err
await setTimeout defer(), 1000
return
log = (args...)->
puts new Date().toISOString(), args...
log_err = (args...)->
perr new Date().toISOString(), args...
# ###################################################################################################
req_opt =
switch : "nonce_filter_get"
wallet : argv.wallet
await wsrs.request req_opt, defer(err, res); return cb err if err
{nonce_filter} = res
switch_key = "job"
loc_opt = {
sub : switch : "#{switch_key}_sub"
unsub : switch : "#{switch_key}_unsub"
switch: "#{switch_key}_stream"
}
share_count =
accepted : 0
stale : 0
rejected : 0
last_hash = null
ws.sub loc_opt, (data)=>
return if !data.res
data = data.res
return if !data.state
axios_opt =
transformResponse : []
headers :
"x-internal-api-secret" : api_secret
if api_network
axios_opt.headers["x-network"] = api_network
# TODO probe joined
url = "#{miner_url}"
await axios.get(url, axios_opt).cb defer(err, res);
if err
last_hash = null
return log_err "local miner not connected. See arweave.log"
json = JSON.parse res.data
return if typeof json.height != "number"
return if json.height < 0
if last_hash != data.state.block.previous_block # TODO or tx_root
url = "#{miner_url}/mine"
data.nonce_filter = nonce_filter
await axios.post(url, data, axios_opt).cb defer(err, res); return log_err err if err
last_hash = data.state.block.previous_block
log "send new job OK", data.state.block.previous_block, data.state.block.height
url = "#{miner_url}/mine_get_results"
await axios.get(url, axios_opt).cb defer(err, res); return log_err err if err
json = JSON.parse res.data
if json.finished_job_list.length
req_opt = {
switch : "share_put_bulk"
finished_job_list : json.finished_job_list
wallet : argv.wallet
worker : argv.worker
}
await wsrs.request req_opt, defer(err, res); return log_err err if err
# ###################################################################################################
# share stat
# ###################################################################################################
share_count.accepted += res.accepted
share_count.rejected += res.rejected
share_count.stale += res.stale
rejected = share_count.rejected.toString()
rejected = if share_count.rejected then colors.red rejected else rejected
stale = share_count.stale.toString()
stale = if share_count.stale then colors.yellow stale else stale
# TODO total reported hashrate
log [
"share"
"accepted:#{colors.green share_count.accepted}"
"rejected:#{rejected}"
"stale:#{stale}"
].join " "
# arPanel Fix: Write share count to file
shareAccepted = share_count.accepted.toString()
shareRejected = share_count.rejected.toString()
shareStale = share_count.stale.toString()
shareInfo = shareAccepted + ":" + shareRejected + ":" + shareStale
fs.writeFile('data/shareInfo.dat', shareInfo, (err) => {
})
# ###################################################################################################
# sync watcher
# ###################################################################################################
max_available_dataset = 6274081889424
my_available_dataset = 0
do ()=>
loop
await axios.get("https://arweave.net/metrics").cb defer(err, res);
if !err
res = res.data.toString()
list = res.split("\n").filter (t)->
return false if t[0] == "#"
/v2_index_data_size/.test t
if list.length
value = +list.last().split(" ")[1]
if isFinite value
max_available_dataset = Math.max max_available_dataset, value
await setTimeout defer(), 10*60*1000 # 10 min
return
do ()=>
loop
await axios.get("#{miner_url}/metrics").cb defer(err, res);
if !err
res = res.data.toString()
list = res.split("\n").filter (t)->
return false if t[0] == "#"
/v2_index_data_size/.test t
if list.length
value = +list.last().split(" ")[1]
if isFinite value
my_available_dataset = Math.max my_available_dataset, value
puts [
"dataset (weave) sync"
"#{my_available_dataset}/#{max_available_dataset}"
"(#{(my_available_dataset/max_available_dataset*100).toFixed(2).rjust 6}%)"
].join " "
await setTimeout defer(), 60*1000 # 1 min
return
| 172017 | #!/usr/bin/env iced
#
# Original script written by <NAME>ird for Arweave mining on Vird's pool (https://ar.virdpool.com/)
# Github: https://github.com/virdpool/miner/blob/master/proxy.coffee
#
# Small mods have been made for arPanel usage. Functionality has not been modified.
# Log file: logs/proxy.log
#
require "fy"
Ws_wrap = require "ws_wrap"
Ws_rs = require "wsrs"
ws_mod_sub= require "ws_mod_sub"
axios = require "axios"
colors = require "colors"
argv = require("minimist")(process.argv.slice(2))
# arPanel Fix
fs = require "fs"
api_secret = argv["api-secret"]
if !argv.wallet or !api_secret
perr "usage ./proxy.coffee --wallet <your wallet> --api-secret <arweave node api secret>"
process.exit 1
argv.worker ?= "default_worker"
puts "Your mining wallet: #{colors.green argv.wallet}"
#puts "For hashrate look at arweave console (this is temporary solution)"
#puts " screen -R virdpool_arweave_miner"
puts ""
# ###################################################################################################
# config
# ###################################################################################################
miner_url = argv["miner-url"] ? "http://127.0.0.1:2984"
api_network = argv["api-network"] # undefined for mainnet
ws_pool_url = argv["ws-pool-url"] ? "ws://ar.virdpool.com:8801"
# TODO? local vardiff for health check
# TODO FUTURE miner_url_list
# ###################################################################################################
cb = (err)->throw err if err
ws = new Ws_wrap ws_pool_url
wsrs = new Ws_rs ws
ws_mod_sub ws, wsrs
do ()=>
loop
await wsrs.request {switch : "ping"}, defer(err)
perr err.message if err
await setTimeout defer(), 1000
return
log = (args...)->
puts new Date().toISOString(), args...
log_err = (args...)->
perr new Date().toISOString(), args...
# ###################################################################################################
req_opt =
switch : "nonce_filter_get"
wallet : argv.wallet
await wsrs.request req_opt, defer(err, res); return cb err if err
{nonce_filter} = res
switch_key = "<KEY>"
loc_opt = {
sub : switch : "#{switch_key}_sub"
unsub : switch : "#{switch_key}_unsub"
switch: "#{switch_key}_stream"
}
share_count =
accepted : 0
stale : 0
rejected : 0
last_hash = null
ws.sub loc_opt, (data)=>
return if !data.res
data = data.res
return if !data.state
axios_opt =
transformResponse : []
headers :
"x-internal-api-secret" : api_secret
if api_network
axios_opt.headers["x-network"] = api_network
# TODO probe joined
url = "#{miner_url}"
await axios.get(url, axios_opt).cb defer(err, res);
if err
last_hash = null
return log_err "local miner not connected. See arweave.log"
json = JSON.parse res.data
return if typeof json.height != "number"
return if json.height < 0
if last_hash != data.state.block.previous_block # TODO or tx_root
url = "#{miner_url}/mine"
data.nonce_filter = nonce_filter
await axios.post(url, data, axios_opt).cb defer(err, res); return log_err err if err
last_hash = data.state.block.previous_block
log "send new job OK", data.state.block.previous_block, data.state.block.height
url = "#{miner_url}/mine_get_results"
await axios.get(url, axios_opt).cb defer(err, res); return log_err err if err
json = JSON.parse res.data
if json.finished_job_list.length
req_opt = {
switch : "share_put_bulk"
finished_job_list : json.finished_job_list
wallet : argv.wallet
worker : argv.worker
}
await wsrs.request req_opt, defer(err, res); return log_err err if err
# ###################################################################################################
# share stat
# ###################################################################################################
share_count.accepted += res.accepted
share_count.rejected += res.rejected
share_count.stale += res.stale
rejected = share_count.rejected.toString()
rejected = if share_count.rejected then colors.red rejected else rejected
stale = share_count.stale.toString()
stale = if share_count.stale then colors.yellow stale else stale
# TODO total reported hashrate
log [
"share"
"accepted:#{colors.green share_count.accepted}"
"rejected:#{rejected}"
"stale:#{stale}"
].join " "
# arPanel Fix: Write share count to file
shareAccepted = share_count.accepted.toString()
shareRejected = share_count.rejected.toString()
shareStale = share_count.stale.toString()
shareInfo = shareAccepted + ":" + shareRejected + ":" + shareStale
fs.writeFile('data/shareInfo.dat', shareInfo, (err) => {
})
# ###################################################################################################
# sync watcher
# ###################################################################################################
max_available_dataset = 6274081889424
my_available_dataset = 0
do ()=>
loop
await axios.get("https://arweave.net/metrics").cb defer(err, res);
if !err
res = res.data.toString()
list = res.split("\n").filter (t)->
return false if t[0] == "#"
/v2_index_data_size/.test t
if list.length
value = +list.last().split(" ")[1]
if isFinite value
max_available_dataset = Math.max max_available_dataset, value
await setTimeout defer(), 10*60*1000 # 10 min
return
do ()=>
loop
await axios.get("#{miner_url}/metrics").cb defer(err, res);
if !err
res = res.data.toString()
list = res.split("\n").filter (t)->
return false if t[0] == "#"
/v2_index_data_size/.test t
if list.length
value = +list.last().split(" ")[1]
if isFinite value
my_available_dataset = Math.max my_available_dataset, value
puts [
"dataset (weave) sync"
"#{my_available_dataset}/#{max_available_dataset}"
"(#{(my_available_dataset/max_available_dataset*100).toFixed(2).rjust 6}%)"
].join " "
await setTimeout defer(), 60*1000 # 1 min
return
| true | #!/usr/bin/env iced
#
# Original script written by PI:NAME:<NAME>END_PIird for Arweave mining on Vird's pool (https://ar.virdpool.com/)
# Github: https://github.com/virdpool/miner/blob/master/proxy.coffee
#
# Small mods have been made for arPanel usage. Functionality has not been modified.
# Log file: logs/proxy.log
#
require "fy"
Ws_wrap = require "ws_wrap"
Ws_rs = require "wsrs"
ws_mod_sub= require "ws_mod_sub"
axios = require "axios"
colors = require "colors"
argv = require("minimist")(process.argv.slice(2))
# arPanel Fix
fs = require "fs"
api_secret = argv["api-secret"]
if !argv.wallet or !api_secret
perr "usage ./proxy.coffee --wallet <your wallet> --api-secret <arweave node api secret>"
process.exit 1
argv.worker ?= "default_worker"
puts "Your mining wallet: #{colors.green argv.wallet}"
#puts "For hashrate look at arweave console (this is temporary solution)"
#puts " screen -R virdpool_arweave_miner"
puts ""
# ###################################################################################################
# config
# ###################################################################################################
miner_url = argv["miner-url"] ? "http://127.0.0.1:2984"
api_network = argv["api-network"] # undefined for mainnet
ws_pool_url = argv["ws-pool-url"] ? "ws://ar.virdpool.com:8801"
# TODO? local vardiff for health check
# TODO FUTURE miner_url_list
# ###################################################################################################
cb = (err)->throw err if err
ws = new Ws_wrap ws_pool_url
wsrs = new Ws_rs ws
ws_mod_sub ws, wsrs
do ()=>
loop
await wsrs.request {switch : "ping"}, defer(err)
perr err.message if err
await setTimeout defer(), 1000
return
log = (args...)->
puts new Date().toISOString(), args...
log_err = (args...)->
perr new Date().toISOString(), args...
# ###################################################################################################
req_opt =
switch : "nonce_filter_get"
wallet : argv.wallet
await wsrs.request req_opt, defer(err, res); return cb err if err
{nonce_filter} = res
switch_key = "PI:KEY:<KEY>END_PI"
loc_opt = {
sub : switch : "#{switch_key}_sub"
unsub : switch : "#{switch_key}_unsub"
switch: "#{switch_key}_stream"
}
share_count =
accepted : 0
stale : 0
rejected : 0
last_hash = null
ws.sub loc_opt, (data)=>
return if !data.res
data = data.res
return if !data.state
axios_opt =
transformResponse : []
headers :
"x-internal-api-secret" : api_secret
if api_network
axios_opt.headers["x-network"] = api_network
# TODO probe joined
url = "#{miner_url}"
await axios.get(url, axios_opt).cb defer(err, res);
if err
last_hash = null
return log_err "local miner not connected. See arweave.log"
json = JSON.parse res.data
return if typeof json.height != "number"
return if json.height < 0
if last_hash != data.state.block.previous_block # TODO or tx_root
url = "#{miner_url}/mine"
data.nonce_filter = nonce_filter
await axios.post(url, data, axios_opt).cb defer(err, res); return log_err err if err
last_hash = data.state.block.previous_block
log "send new job OK", data.state.block.previous_block, data.state.block.height
url = "#{miner_url}/mine_get_results"
await axios.get(url, axios_opt).cb defer(err, res); return log_err err if err
json = JSON.parse res.data
if json.finished_job_list.length
req_opt = {
switch : "share_put_bulk"
finished_job_list : json.finished_job_list
wallet : argv.wallet
worker : argv.worker
}
await wsrs.request req_opt, defer(err, res); return log_err err if err
# ###################################################################################################
# share stat
# ###################################################################################################
share_count.accepted += res.accepted
share_count.rejected += res.rejected
share_count.stale += res.stale
rejected = share_count.rejected.toString()
rejected = if share_count.rejected then colors.red rejected else rejected
stale = share_count.stale.toString()
stale = if share_count.stale then colors.yellow stale else stale
# TODO total reported hashrate
log [
"share"
"accepted:#{colors.green share_count.accepted}"
"rejected:#{rejected}"
"stale:#{stale}"
].join " "
# arPanel Fix: Write share count to file
shareAccepted = share_count.accepted.toString()
shareRejected = share_count.rejected.toString()
shareStale = share_count.stale.toString()
shareInfo = shareAccepted + ":" + shareRejected + ":" + shareStale
fs.writeFile('data/shareInfo.dat', shareInfo, (err) => {
})
# ###################################################################################################
# sync watcher
# ###################################################################################################
max_available_dataset = 6274081889424
my_available_dataset = 0
do ()=>
loop
await axios.get("https://arweave.net/metrics").cb defer(err, res);
if !err
res = res.data.toString()
list = res.split("\n").filter (t)->
return false if t[0] == "#"
/v2_index_data_size/.test t
if list.length
value = +list.last().split(" ")[1]
if isFinite value
max_available_dataset = Math.max max_available_dataset, value
await setTimeout defer(), 10*60*1000 # 10 min
return
do ()=>
loop
await axios.get("#{miner_url}/metrics").cb defer(err, res);
if !err
res = res.data.toString()
list = res.split("\n").filter (t)->
return false if t[0] == "#"
/v2_index_data_size/.test t
if list.length
value = +list.last().split(" ")[1]
if isFinite value
my_available_dataset = Math.max my_available_dataset, value
puts [
"dataset (weave) sync"
"#{my_available_dataset}/#{max_available_dataset}"
"(#{(my_available_dataset/max_available_dataset*100).toFixed(2).rjust 6}%)"
].join " "
await setTimeout defer(), 60*1000 # 1 min
return
|
[
{
"context": "1'\n\t\t\t\t\trequest.setRequestHeader 'X-Auth-Token', 'orHOAa1lK7RcM-vtcwSp28w67wAi6LZpsMBEM2DX4AY'\n\t\t\t\t\treturn\n\t\t\t\tsuccess: (result) ->\n\t\t\t\t\tdeferr",
"end": 1012,
"score": 0.9207274913787842,
"start": 969,
"tag": "PASSWORD",
"value": "orHOAa1lK7RcM-vtcwSp28w67wAi6LZpsMBEM2DX4AY"
}
] | packages/steedos-creator/client/views/custom_data_source.coffee | zonglu233/fuel-car | 42 | Template.custom_data_source.helpers Creator.helpers
Template.custom_data_source.helpers
Template.custom_data_source.events
Template.custom_data_source.onRendered ()->
orders = new (DevExpress.data.CustomStore)(
load: (loadOptions) ->
deferred = $.Deferred()
args = {}
if loadOptions.sort
args.orderby = loadOptions.sort[0].selector
if loadOptions.sort[0].desc
args.orderby += ' desc'
args.skip = loadOptions.skip or 0
args.take = loadOptions.take or 1
filter = ''
if loadOptions.filter
filter = '&$filter=' + DevExpress.data.queryAdapters.odata.compileCriteria(loadOptions.filter,4,[])
$.ajax
url: 'http://127.0.0.1:5000/api/odata/v4/'+Steedos.spaceId()+'/archive_records?'+filter
data: args
beforeSend: (request) ->
request.setRequestHeader 'X-User-Id', '5194c66ef4a563537a000003'
request.setRequestHeader 'X-Space-Id', '51ae9b1a8e296a29c9000001'
request.setRequestHeader 'X-Auth-Token', 'orHOAa1lK7RcM-vtcwSp28w67wAi6LZpsMBEM2DX4AY'
return
success: (result) ->
deferred.resolve result.data, totalCount: result.count
return
error: ->
deferred.reject 'Data Loading Error'
return
timeout: 5000
deferred.promise()
)
dataGrid = $('#gridContainer').dxDataGrid(
dataSource:
store: orders
remoteOperations:
sorting: true
paging: true
paging:
pageSize: 1
pager:
showPageSizeSelector: true
allowedPageSizes: [
8
12
20
]
columns: [
'title'
'date'
]
columnsAutoWidth: true
filterRow:
visible: true,
applyFilter: "auto"
searchPanel:
visible: true
width: 240
placeholder: "Search..."
headerFilter:
visible: true
remoteOperations:
filtering: true
).dxDataGrid 'instance'
applyFilterTypes = [{
key: "auto",
name: "Immediately"
}, {
key: "onClick",
name: "On Button Click"
}];
applyFilterModeEditor = $("#useFilterApplyButton").dxSelectBox({
items: applyFilterTypes,
value: applyFilterTypes[0].key,
valueExpr: "key",
displayExpr: "name",
onValueChanged: (data) ->
dataGrid.option("filterRow.applyFilter", data.value);
}).dxSelectBox("instance")
$("#filterRow").dxCheckBox({
text: "Filter Row",
value: true,
onValueChanged: (data) ->
dataGrid.clearFilter()
dataGrid.option("filterRow.visible", data.value)
applyFilterModeEditor.option("disabled", !data.value)
})
$("#headerFilter").dxCheckBox({
text: "Header Filter",
value: true,
onValueChanged: (data) ->
dataGrid.clearFilter()
dataGrid.option("headerFilter.visible", data.value)
})
getOrderDay = (rowData) ->
return (new Date(rowData.OrderDate)).getDay()
| 41734 | Template.custom_data_source.helpers Creator.helpers
Template.custom_data_source.helpers
Template.custom_data_source.events
Template.custom_data_source.onRendered ()->
orders = new (DevExpress.data.CustomStore)(
load: (loadOptions) ->
deferred = $.Deferred()
args = {}
if loadOptions.sort
args.orderby = loadOptions.sort[0].selector
if loadOptions.sort[0].desc
args.orderby += ' desc'
args.skip = loadOptions.skip or 0
args.take = loadOptions.take or 1
filter = ''
if loadOptions.filter
filter = '&$filter=' + DevExpress.data.queryAdapters.odata.compileCriteria(loadOptions.filter,4,[])
$.ajax
url: 'http://127.0.0.1:5000/api/odata/v4/'+Steedos.spaceId()+'/archive_records?'+filter
data: args
beforeSend: (request) ->
request.setRequestHeader 'X-User-Id', '5194c66ef4a563537a000003'
request.setRequestHeader 'X-Space-Id', '51ae9b1a8e296a29c9000001'
request.setRequestHeader 'X-Auth-Token', '<PASSWORD>'
return
success: (result) ->
deferred.resolve result.data, totalCount: result.count
return
error: ->
deferred.reject 'Data Loading Error'
return
timeout: 5000
deferred.promise()
)
dataGrid = $('#gridContainer').dxDataGrid(
dataSource:
store: orders
remoteOperations:
sorting: true
paging: true
paging:
pageSize: 1
pager:
showPageSizeSelector: true
allowedPageSizes: [
8
12
20
]
columns: [
'title'
'date'
]
columnsAutoWidth: true
filterRow:
visible: true,
applyFilter: "auto"
searchPanel:
visible: true
width: 240
placeholder: "Search..."
headerFilter:
visible: true
remoteOperations:
filtering: true
).dxDataGrid 'instance'
applyFilterTypes = [{
key: "auto",
name: "Immediately"
}, {
key: "onClick",
name: "On Button Click"
}];
applyFilterModeEditor = $("#useFilterApplyButton").dxSelectBox({
items: applyFilterTypes,
value: applyFilterTypes[0].key,
valueExpr: "key",
displayExpr: "name",
onValueChanged: (data) ->
dataGrid.option("filterRow.applyFilter", data.value);
}).dxSelectBox("instance")
$("#filterRow").dxCheckBox({
text: "Filter Row",
value: true,
onValueChanged: (data) ->
dataGrid.clearFilter()
dataGrid.option("filterRow.visible", data.value)
applyFilterModeEditor.option("disabled", !data.value)
})
$("#headerFilter").dxCheckBox({
text: "Header Filter",
value: true,
onValueChanged: (data) ->
dataGrid.clearFilter()
dataGrid.option("headerFilter.visible", data.value)
})
getOrderDay = (rowData) ->
return (new Date(rowData.OrderDate)).getDay()
| true | Template.custom_data_source.helpers Creator.helpers
Template.custom_data_source.helpers
Template.custom_data_source.events
Template.custom_data_source.onRendered ()->
orders = new (DevExpress.data.CustomStore)(
load: (loadOptions) ->
deferred = $.Deferred()
args = {}
if loadOptions.sort
args.orderby = loadOptions.sort[0].selector
if loadOptions.sort[0].desc
args.orderby += ' desc'
args.skip = loadOptions.skip or 0
args.take = loadOptions.take or 1
filter = ''
if loadOptions.filter
filter = '&$filter=' + DevExpress.data.queryAdapters.odata.compileCriteria(loadOptions.filter,4,[])
$.ajax
url: 'http://127.0.0.1:5000/api/odata/v4/'+Steedos.spaceId()+'/archive_records?'+filter
data: args
beforeSend: (request) ->
request.setRequestHeader 'X-User-Id', '5194c66ef4a563537a000003'
request.setRequestHeader 'X-Space-Id', '51ae9b1a8e296a29c9000001'
request.setRequestHeader 'X-Auth-Token', 'PI:PASSWORD:<PASSWORD>END_PI'
return
success: (result) ->
deferred.resolve result.data, totalCount: result.count
return
error: ->
deferred.reject 'Data Loading Error'
return
timeout: 5000
deferred.promise()
)
dataGrid = $('#gridContainer').dxDataGrid(
dataSource:
store: orders
remoteOperations:
sorting: true
paging: true
paging:
pageSize: 1
pager:
showPageSizeSelector: true
allowedPageSizes: [
8
12
20
]
columns: [
'title'
'date'
]
columnsAutoWidth: true
filterRow:
visible: true,
applyFilter: "auto"
searchPanel:
visible: true
width: 240
placeholder: "Search..."
headerFilter:
visible: true
remoteOperations:
filtering: true
).dxDataGrid 'instance'
applyFilterTypes = [{
key: "auto",
name: "Immediately"
}, {
key: "onClick",
name: "On Button Click"
}];
applyFilterModeEditor = $("#useFilterApplyButton").dxSelectBox({
items: applyFilterTypes,
value: applyFilterTypes[0].key,
valueExpr: "key",
displayExpr: "name",
onValueChanged: (data) ->
dataGrid.option("filterRow.applyFilter", data.value);
}).dxSelectBox("instance")
$("#filterRow").dxCheckBox({
text: "Filter Row",
value: true,
onValueChanged: (data) ->
dataGrid.clearFilter()
dataGrid.option("filterRow.visible", data.value)
applyFilterModeEditor.option("disabled", !data.value)
})
$("#headerFilter").dxCheckBox({
text: "Header Filter",
value: true,
onValueChanged: (data) ->
dataGrid.clearFilter()
dataGrid.option("headerFilter.visible", data.value)
})
getOrderDay = (rowData) ->
return (new Date(rowData.OrderDate)).getDay()
|
[
{
"context": "###\n QuoJS 2.1\n (c) 2011, 2012 Javi Jiménez Villar (@soyjavi)\n http://quojs.tapquo.com\n###\n\n(($$)",
"end": 56,
"score": 0.9998692870140076,
"start": 37,
"tag": "NAME",
"value": "Javi Jiménez Villar"
},
{
"context": " QuoJS 2.1\n (c) 2011, 2012 Javi Jiménez Villar (@soyjavi)\n http://quojs.tapquo.com\n###\n\n(($$) ->\n\n E",
"end": 66,
"score": 0.9995668530464172,
"start": 57,
"tag": "USERNAME",
"value": "(@soyjavi"
}
] | src/QuoJS/src/quo.events.manager.coffee | biojazzard/kirbout | 2 | ###
QuoJS 2.1
(c) 2011, 2012 Javi Jiménez Villar (@soyjavi)
http://quojs.tapquo.com
###
(($$) ->
ELEMENT_ID = 1
HANDLERS = {}
EVENT_METHODS =
preventDefault: "isDefaultPrevented"
stopImmediatePropagation: "isImmediatePropagationStopped"
stopPropagation: "isPropagationStopped"
EVENTS_DESKTOP =
touchstart: "mousedown"
touchmove: "mousemove"
touchend: "mouseup"
tap: "click"
doubletap: "dblclick"
orientationchange: "resize"
$$.Event = (type, touch) ->
event = document.createEvent("Events")
event.initEvent type, true, true, null, null, null, null, null, null, null, null, null, null, null, null
if touch
event.pageX = touch.x1
event.pageY = touch.y1
event.toX = touch.x2
event.toY = touch.y2
event.fingers = touch.fingers
event
$$.fn.bind = (event, callback) ->
@each ->
_subscribe @, event, callback
return
$$.fn.unbind = (event, callback) ->
@each ->
_unsubscribe @, event, callback
return
$$.fn.delegate = (selector, event, callback) ->
@each (i, element) ->
_subscribe element, event, callback, selector, (fn) ->
(e) ->
match = $$(e.target).closest(selector, element).get(0)
if match
evt = $$.extend(_createProxy(e),
currentTarget: match
liveFired: element
)
fn.apply match, [ evt ].concat([].slice.call(arguments, 1))
return
$$.fn.undelegate = (selector, event, callback) ->
@each ->
_unsubscribe @, event, callback, selector
return
$$.fn.trigger = (event, touch) ->
event = $$.Event(event, touch) if $$.toType(event) is "string"
@each ->
@dispatchEvent event
return
$$.fn.addEvent = (element, event_name, callback) ->
if element.addEventListener
element.addEventListener event_name, callback, false
else if element.attachEvent
element.attachEvent "on" + event_name, callback
else
element["on" + event_name] = callback
$$.fn.removeEvent = (element, event_name, callback) ->
if element.removeEventListener
element.removeEventListener event_name, callback, false
else if element.detachEvent
element.detachEvent "on" + event_name, callback
else
element["on" + event_name] = null
_subscribe = (element, event, callback, selector, delegate_callback) ->
event = _environmentEvent(event)
element_id = _getElementId(element)
element_handlers = HANDLERS[element_id] or (HANDLERS[element_id] = [])
delegate = delegate_callback and delegate_callback(callback, event)
handler =
event: event
callback: callback
selector: selector
proxy: _createProxyCallback(delegate, callback, element)
delegate: delegate
index: element_handlers.length
element_handlers.push handler
$$.fn.addEvent element, handler.event, handler.proxy
_unsubscribe = (element, event, callback, selector) ->
event = _environmentEvent(event)
element_id = _getElementId(element)
_findHandlers(element_id, event, callback, selector).forEach (handler) ->
delete HANDLERS[element_id][handler.index]
$$.fn.removeEvent element, handler.event, handler.proxy
_getElementId = (element) -> element._id or (element._id = ELEMENT_ID++)
_environmentEvent = (event) ->
environment_event = (if ($$.isMobile()) then event else EVENTS_DESKTOP[event])
(environment_event) or event
_createProxyCallback = (delegate, callback, element) ->
callback = delegate or callback
proxy = (event) ->
result = callback.apply(element, [ event ].concat(event.data))
event.preventDefault() if result is false
result
proxy
_findHandlers = (element_id, event, fn, selector) ->
(HANDLERS[element_id] or []).filter (handler) ->
handler and (not event or handler.event is event) and (not fn or handler.fn is fn) and (not selector or handler.selector is selector)
_createProxy = (event) ->
proxy = $$.extend( originalEvent: event, event)
$$.each EVENT_METHODS, (name, method) ->
proxy[name] = ->
@[method] = ->
true
event[name].apply event, arguments
proxy[method] = ->
false
proxy
return
) Quo
| 84570 | ###
QuoJS 2.1
(c) 2011, 2012 <NAME> (@soyjavi)
http://quojs.tapquo.com
###
(($$) ->
ELEMENT_ID = 1
HANDLERS = {}
EVENT_METHODS =
preventDefault: "isDefaultPrevented"
stopImmediatePropagation: "isImmediatePropagationStopped"
stopPropagation: "isPropagationStopped"
EVENTS_DESKTOP =
touchstart: "mousedown"
touchmove: "mousemove"
touchend: "mouseup"
tap: "click"
doubletap: "dblclick"
orientationchange: "resize"
$$.Event = (type, touch) ->
event = document.createEvent("Events")
event.initEvent type, true, true, null, null, null, null, null, null, null, null, null, null, null, null
if touch
event.pageX = touch.x1
event.pageY = touch.y1
event.toX = touch.x2
event.toY = touch.y2
event.fingers = touch.fingers
event
$$.fn.bind = (event, callback) ->
@each ->
_subscribe @, event, callback
return
$$.fn.unbind = (event, callback) ->
@each ->
_unsubscribe @, event, callback
return
$$.fn.delegate = (selector, event, callback) ->
@each (i, element) ->
_subscribe element, event, callback, selector, (fn) ->
(e) ->
match = $$(e.target).closest(selector, element).get(0)
if match
evt = $$.extend(_createProxy(e),
currentTarget: match
liveFired: element
)
fn.apply match, [ evt ].concat([].slice.call(arguments, 1))
return
$$.fn.undelegate = (selector, event, callback) ->
@each ->
_unsubscribe @, event, callback, selector
return
$$.fn.trigger = (event, touch) ->
event = $$.Event(event, touch) if $$.toType(event) is "string"
@each ->
@dispatchEvent event
return
$$.fn.addEvent = (element, event_name, callback) ->
if element.addEventListener
element.addEventListener event_name, callback, false
else if element.attachEvent
element.attachEvent "on" + event_name, callback
else
element["on" + event_name] = callback
$$.fn.removeEvent = (element, event_name, callback) ->
if element.removeEventListener
element.removeEventListener event_name, callback, false
else if element.detachEvent
element.detachEvent "on" + event_name, callback
else
element["on" + event_name] = null
_subscribe = (element, event, callback, selector, delegate_callback) ->
event = _environmentEvent(event)
element_id = _getElementId(element)
element_handlers = HANDLERS[element_id] or (HANDLERS[element_id] = [])
delegate = delegate_callback and delegate_callback(callback, event)
handler =
event: event
callback: callback
selector: selector
proxy: _createProxyCallback(delegate, callback, element)
delegate: delegate
index: element_handlers.length
element_handlers.push handler
$$.fn.addEvent element, handler.event, handler.proxy
_unsubscribe = (element, event, callback, selector) ->
event = _environmentEvent(event)
element_id = _getElementId(element)
_findHandlers(element_id, event, callback, selector).forEach (handler) ->
delete HANDLERS[element_id][handler.index]
$$.fn.removeEvent element, handler.event, handler.proxy
_getElementId = (element) -> element._id or (element._id = ELEMENT_ID++)
_environmentEvent = (event) ->
environment_event = (if ($$.isMobile()) then event else EVENTS_DESKTOP[event])
(environment_event) or event
_createProxyCallback = (delegate, callback, element) ->
callback = delegate or callback
proxy = (event) ->
result = callback.apply(element, [ event ].concat(event.data))
event.preventDefault() if result is false
result
proxy
_findHandlers = (element_id, event, fn, selector) ->
(HANDLERS[element_id] or []).filter (handler) ->
handler and (not event or handler.event is event) and (not fn or handler.fn is fn) and (not selector or handler.selector is selector)
_createProxy = (event) ->
proxy = $$.extend( originalEvent: event, event)
$$.each EVENT_METHODS, (name, method) ->
proxy[name] = ->
@[method] = ->
true
event[name].apply event, arguments
proxy[method] = ->
false
proxy
return
) Quo
| true | ###
QuoJS 2.1
(c) 2011, 2012 PI:NAME:<NAME>END_PI (@soyjavi)
http://quojs.tapquo.com
###
(($$) ->
ELEMENT_ID = 1
HANDLERS = {}
EVENT_METHODS =
preventDefault: "isDefaultPrevented"
stopImmediatePropagation: "isImmediatePropagationStopped"
stopPropagation: "isPropagationStopped"
EVENTS_DESKTOP =
touchstart: "mousedown"
touchmove: "mousemove"
touchend: "mouseup"
tap: "click"
doubletap: "dblclick"
orientationchange: "resize"
$$.Event = (type, touch) ->
event = document.createEvent("Events")
event.initEvent type, true, true, null, null, null, null, null, null, null, null, null, null, null, null
if touch
event.pageX = touch.x1
event.pageY = touch.y1
event.toX = touch.x2
event.toY = touch.y2
event.fingers = touch.fingers
event
$$.fn.bind = (event, callback) ->
@each ->
_subscribe @, event, callback
return
$$.fn.unbind = (event, callback) ->
@each ->
_unsubscribe @, event, callback
return
$$.fn.delegate = (selector, event, callback) ->
@each (i, element) ->
_subscribe element, event, callback, selector, (fn) ->
(e) ->
match = $$(e.target).closest(selector, element).get(0)
if match
evt = $$.extend(_createProxy(e),
currentTarget: match
liveFired: element
)
fn.apply match, [ evt ].concat([].slice.call(arguments, 1))
return
$$.fn.undelegate = (selector, event, callback) ->
@each ->
_unsubscribe @, event, callback, selector
return
$$.fn.trigger = (event, touch) ->
event = $$.Event(event, touch) if $$.toType(event) is "string"
@each ->
@dispatchEvent event
return
$$.fn.addEvent = (element, event_name, callback) ->
if element.addEventListener
element.addEventListener event_name, callback, false
else if element.attachEvent
element.attachEvent "on" + event_name, callback
else
element["on" + event_name] = callback
$$.fn.removeEvent = (element, event_name, callback) ->
if element.removeEventListener
element.removeEventListener event_name, callback, false
else if element.detachEvent
element.detachEvent "on" + event_name, callback
else
element["on" + event_name] = null
_subscribe = (element, event, callback, selector, delegate_callback) ->
event = _environmentEvent(event)
element_id = _getElementId(element)
element_handlers = HANDLERS[element_id] or (HANDLERS[element_id] = [])
delegate = delegate_callback and delegate_callback(callback, event)
handler =
event: event
callback: callback
selector: selector
proxy: _createProxyCallback(delegate, callback, element)
delegate: delegate
index: element_handlers.length
element_handlers.push handler
$$.fn.addEvent element, handler.event, handler.proxy
_unsubscribe = (element, event, callback, selector) ->
event = _environmentEvent(event)
element_id = _getElementId(element)
_findHandlers(element_id, event, callback, selector).forEach (handler) ->
delete HANDLERS[element_id][handler.index]
$$.fn.removeEvent element, handler.event, handler.proxy
_getElementId = (element) -> element._id or (element._id = ELEMENT_ID++)
_environmentEvent = (event) ->
environment_event = (if ($$.isMobile()) then event else EVENTS_DESKTOP[event])
(environment_event) or event
_createProxyCallback = (delegate, callback, element) ->
callback = delegate or callback
proxy = (event) ->
result = callback.apply(element, [ event ].concat(event.data))
event.preventDefault() if result is false
result
proxy
_findHandlers = (element_id, event, fn, selector) ->
(HANDLERS[element_id] or []).filter (handler) ->
handler and (not event or handler.event is event) and (not fn or handler.fn is fn) and (not selector or handler.selector is selector)
_createProxy = (event) ->
proxy = $$.extend( originalEvent: event, event)
$$.each EVENT_METHODS, (name, method) ->
proxy[name] = ->
@[method] = ->
true
event[name].apply event, arguments
proxy[method] = ->
false
proxy
return
) Quo
|
[
{
"context": "can set/get config', ->\n papercut.set 'name', 'John'\n papercut.get('name').should.eql 'John'\n\n it",
"end": 301,
"score": 0.9996092915534973,
"start": 297,
"tag": "NAME",
"value": "John"
},
{
"context": "ame', 'John'\n papercut.get('name').should.eql 'John'\n\n it 'have default config', ->\n papercut.get",
"end": 344,
"score": 0.9994531273841858,
"start": 340,
"tag": "NAME",
"value": "John"
},
{
"context": "process: 'crop'\n @version\n name: 'test2'\n size: '16x16'\n @version\n ",
"end": 2394,
"score": 0.7892287969589233,
"start": 2389,
"tag": "NAME",
"value": "test2"
}
] | test/papercut_test.coffee | Rafe/papercut | 33 | fs = require('fs')
sample = './images/sample.jpg'
errorSample = './images/error.jpg'
{ S3Store, FileStore, TestStore } = require('../lib/store')
describe 'papercut', ->
papercut = ''
beforeEach ->
papercut = require('../index')
it 'can set/get config', ->
papercut.set 'name', 'John'
papercut.get('name').should.eql 'John'
it 'have default config', ->
papercut.get('storage').should.eql 'file'
papercut.get('extension').should.eql 'jpg'
papercut.get('process').should.eql 'resize'
describe '.configure', ->
it 'executed in all env', ->
papercut.configure ->
papercut.set 'flag', true
papercut.get('flag').should.be.true
it 'executed in specific env', ->
process.env.NODE_ENV = 'test'
papercut.configure 'test', ->
papercut.set 'flag', true
papercut.get('flag').should.be.true
describe 'storage', ->
it "initialize FileStore", ->
papercut.set 'storage', 'file'
Uploader = papercut.Schema ->
uploader = new Uploader()
uploader.store.should.be.an.instanceof FileStore
it "initialize S3Store", ->
papercut.set 'storage', 's3'
papercut.set 'S3_KEY', 'test'
papercut.set 'S3_SECRET', 'test'
papercut.set 'bucket', 'test'
Uploader = papercut.Schema ->
uploader = new Uploader()
uploader.store.should.be.an.instanceof S3Store
it "initialize TestStore", ->
papercut.set 'storage', 'test'
Uploader = papercut.Schema ->
uploader = new Uploader()
uploader.store.should.be.an.instanceof TestStore
afterEach ->
process.env.NODE_ENV = undefined
describe 'Schema', ->
it 'run initialize function', (done)->
Uploader = papercut.Schema (schema)->
schema.should.be.instanceof(Uploader)
this.should.be.instanceof(Uploader)
done()
uploader = new Uploader()
it 'store configs', ->
papercut.set('flag', on)
papercut.set('store', 's3')
Uploader = papercut.Schema()
uploader = new Uploader()
uploader.config.flag.should.be.ok
uploader.config.store.should.eql 's3'
uploader.store
it 'store versions', ->
Uploader = papercut.Schema ->
@version
name: 'test'
size: '250x250'
process: 'crop'
@version
name: 'test2'
size: '16x16'
@version
name: ''
process: 'copy'
uploader = new Uploader()
uploader.versions.length.should.eql 3
version = uploader.versions[0]
version.name.should.eql 'test'
version.size.should.eql '250x250'
describe 'process', ->
uploader = ''
beforeEach ->
papercut.set('directory', './images/output')
papercut.set('url', '/images')
papercut.set('storage', 'file')
Uploader = papercut.Schema ->
@version
name: 'cropped'
size: '250x250'
process: 'crop'
@version
name: 'origin'
process: 'copy'
@version
name: 'resized'
size: '250x250'
process: 'resize'
uploader = new Uploader()
it 'process and store image to directory', (done)->
uploader.process 'test', sample, (err, images)->
fs.existsSync('./images/output/test-cropped.jpg').should.be.true
fs.existsSync('./images/output/test-resized.jpg').should.be.true
fs.existsSync('./images/output/test-origin.jpg').should.be.true
images.origin.should.eql '/images/test-origin.jpg'
images.cropped.should.eql '/images/test-cropped.jpg'
images.resized.should.eql '/images/test-resized.jpg'
done()
it 'should handle error', (done)->
uploader.process 'error', errorSample, (err, images)->
fs.existsSync('./images/output/error-cropped.jpg').should.be.false
fs.existsSync('./images/output/error-resized.jpg').should.be.false
# copy will still copy file
fs.existsSync('./images/output/error-origin.jpg').should.be.true
err.should.be.ok
done()
#should in processor_test
it 'should throw no file error', (done)->
uploader.process 'nofile', './images/nofile.jpg', (err, images)->
err.should.be.ok
done()
after cleanFiles
| 115673 | fs = require('fs')
sample = './images/sample.jpg'
errorSample = './images/error.jpg'
{ S3Store, FileStore, TestStore } = require('../lib/store')
describe 'papercut', ->
papercut = ''
beforeEach ->
papercut = require('../index')
it 'can set/get config', ->
papercut.set 'name', '<NAME>'
papercut.get('name').should.eql '<NAME>'
it 'have default config', ->
papercut.get('storage').should.eql 'file'
papercut.get('extension').should.eql 'jpg'
papercut.get('process').should.eql 'resize'
describe '.configure', ->
it 'executed in all env', ->
papercut.configure ->
papercut.set 'flag', true
papercut.get('flag').should.be.true
it 'executed in specific env', ->
process.env.NODE_ENV = 'test'
papercut.configure 'test', ->
papercut.set 'flag', true
papercut.get('flag').should.be.true
describe 'storage', ->
it "initialize FileStore", ->
papercut.set 'storage', 'file'
Uploader = papercut.Schema ->
uploader = new Uploader()
uploader.store.should.be.an.instanceof FileStore
it "initialize S3Store", ->
papercut.set 'storage', 's3'
papercut.set 'S3_KEY', 'test'
papercut.set 'S3_SECRET', 'test'
papercut.set 'bucket', 'test'
Uploader = papercut.Schema ->
uploader = new Uploader()
uploader.store.should.be.an.instanceof S3Store
it "initialize TestStore", ->
papercut.set 'storage', 'test'
Uploader = papercut.Schema ->
uploader = new Uploader()
uploader.store.should.be.an.instanceof TestStore
afterEach ->
process.env.NODE_ENV = undefined
describe 'Schema', ->
it 'run initialize function', (done)->
Uploader = papercut.Schema (schema)->
schema.should.be.instanceof(Uploader)
this.should.be.instanceof(Uploader)
done()
uploader = new Uploader()
it 'store configs', ->
papercut.set('flag', on)
papercut.set('store', 's3')
Uploader = papercut.Schema()
uploader = new Uploader()
uploader.config.flag.should.be.ok
uploader.config.store.should.eql 's3'
uploader.store
it 'store versions', ->
Uploader = papercut.Schema ->
@version
name: 'test'
size: '250x250'
process: 'crop'
@version
name: '<NAME>'
size: '16x16'
@version
name: ''
process: 'copy'
uploader = new Uploader()
uploader.versions.length.should.eql 3
version = uploader.versions[0]
version.name.should.eql 'test'
version.size.should.eql '250x250'
describe 'process', ->
uploader = ''
beforeEach ->
papercut.set('directory', './images/output')
papercut.set('url', '/images')
papercut.set('storage', 'file')
Uploader = papercut.Schema ->
@version
name: 'cropped'
size: '250x250'
process: 'crop'
@version
name: 'origin'
process: 'copy'
@version
name: 'resized'
size: '250x250'
process: 'resize'
uploader = new Uploader()
it 'process and store image to directory', (done)->
uploader.process 'test', sample, (err, images)->
fs.existsSync('./images/output/test-cropped.jpg').should.be.true
fs.existsSync('./images/output/test-resized.jpg').should.be.true
fs.existsSync('./images/output/test-origin.jpg').should.be.true
images.origin.should.eql '/images/test-origin.jpg'
images.cropped.should.eql '/images/test-cropped.jpg'
images.resized.should.eql '/images/test-resized.jpg'
done()
it 'should handle error', (done)->
uploader.process 'error', errorSample, (err, images)->
fs.existsSync('./images/output/error-cropped.jpg').should.be.false
fs.existsSync('./images/output/error-resized.jpg').should.be.false
# copy will still copy file
fs.existsSync('./images/output/error-origin.jpg').should.be.true
err.should.be.ok
done()
#should in processor_test
it 'should throw no file error', (done)->
uploader.process 'nofile', './images/nofile.jpg', (err, images)->
err.should.be.ok
done()
after cleanFiles
| true | fs = require('fs')
sample = './images/sample.jpg'
errorSample = './images/error.jpg'
{ S3Store, FileStore, TestStore } = require('../lib/store')
describe 'papercut', ->
papercut = ''
beforeEach ->
papercut = require('../index')
it 'can set/get config', ->
papercut.set 'name', 'PI:NAME:<NAME>END_PI'
papercut.get('name').should.eql 'PI:NAME:<NAME>END_PI'
it 'have default config', ->
papercut.get('storage').should.eql 'file'
papercut.get('extension').should.eql 'jpg'
papercut.get('process').should.eql 'resize'
describe '.configure', ->
it 'executed in all env', ->
papercut.configure ->
papercut.set 'flag', true
papercut.get('flag').should.be.true
it 'executed in specific env', ->
process.env.NODE_ENV = 'test'
papercut.configure 'test', ->
papercut.set 'flag', true
papercut.get('flag').should.be.true
describe 'storage', ->
it "initialize FileStore", ->
papercut.set 'storage', 'file'
Uploader = papercut.Schema ->
uploader = new Uploader()
uploader.store.should.be.an.instanceof FileStore
it "initialize S3Store", ->
papercut.set 'storage', 's3'
papercut.set 'S3_KEY', 'test'
papercut.set 'S3_SECRET', 'test'
papercut.set 'bucket', 'test'
Uploader = papercut.Schema ->
uploader = new Uploader()
uploader.store.should.be.an.instanceof S3Store
it "initialize TestStore", ->
papercut.set 'storage', 'test'
Uploader = papercut.Schema ->
uploader = new Uploader()
uploader.store.should.be.an.instanceof TestStore
afterEach ->
process.env.NODE_ENV = undefined
describe 'Schema', ->
it 'run initialize function', (done)->
Uploader = papercut.Schema (schema)->
schema.should.be.instanceof(Uploader)
this.should.be.instanceof(Uploader)
done()
uploader = new Uploader()
it 'store configs', ->
papercut.set('flag', on)
papercut.set('store', 's3')
Uploader = papercut.Schema()
uploader = new Uploader()
uploader.config.flag.should.be.ok
uploader.config.store.should.eql 's3'
uploader.store
it 'store versions', ->
Uploader = papercut.Schema ->
@version
name: 'test'
size: '250x250'
process: 'crop'
@version
name: 'PI:NAME:<NAME>END_PI'
size: '16x16'
@version
name: ''
process: 'copy'
uploader = new Uploader()
uploader.versions.length.should.eql 3
version = uploader.versions[0]
version.name.should.eql 'test'
version.size.should.eql '250x250'
describe 'process', ->
uploader = ''
beforeEach ->
papercut.set('directory', './images/output')
papercut.set('url', '/images')
papercut.set('storage', 'file')
Uploader = papercut.Schema ->
@version
name: 'cropped'
size: '250x250'
process: 'crop'
@version
name: 'origin'
process: 'copy'
@version
name: 'resized'
size: '250x250'
process: 'resize'
uploader = new Uploader()
it 'process and store image to directory', (done)->
uploader.process 'test', sample, (err, images)->
fs.existsSync('./images/output/test-cropped.jpg').should.be.true
fs.existsSync('./images/output/test-resized.jpg').should.be.true
fs.existsSync('./images/output/test-origin.jpg').should.be.true
images.origin.should.eql '/images/test-origin.jpg'
images.cropped.should.eql '/images/test-cropped.jpg'
images.resized.should.eql '/images/test-resized.jpg'
done()
it 'should handle error', (done)->
uploader.process 'error', errorSample, (err, images)->
fs.existsSync('./images/output/error-cropped.jpg').should.be.false
fs.existsSync('./images/output/error-resized.jpg').should.be.false
# copy will still copy file
fs.existsSync('./images/output/error-origin.jpg').should.be.true
err.should.be.ok
done()
#should in processor_test
it 'should throw no file error', (done)->
uploader.process 'nofile', './images/nofile.jpg', (err, images)->
err.should.be.ok
done()
after cleanFiles
|
[
{
"context": " properties:\n username:\n title: 'Username'\n type: 'string'\n minLength: 3\n",
"end": 311,
"score": 0.9923322200775146,
"start": 303,
"tag": "USERNAME",
"value": "Username"
},
{
"context": "equired: true\n password:\n title: 'Password'\n type: 'string'\n minLength: 6\n",
"end": 430,
"score": 0.8495124578475952,
"start": 422,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": " required: true\n\n $scope.form = [\n 'username'\n { key: 'password', type: 'password', disab",
"end": 541,
"score": 0.9981613755226135,
"start": 533,
"tag": "USERNAME",
"value": "username"
},
{
"context": " $scope.form = [\n 'username'\n { key: 'password', type: 'password', disableSuccessState: true, fe",
"end": 565,
"score": 0.7746947407722473,
"start": 557,
"tag": "PASSWORD",
"value": "password"
}
] | app/assets/javascripts/controllers/users/sign_in.coffee | zhoutong/coledger | 1 | angular.module("coledger").controller("SignInController", ['$scope', '$location', '$window', 'Resources', 'flash',
($scope, $location, $window, Resources, flash) ->
$scope.user = {}
$scope.schema =
type: 'object'
title: 'User'
properties:
username:
title: 'Username'
type: 'string'
minLength: 3
required: true
password:
title: 'Password'
type: 'string'
minLength: 6
required: true
$scope.form = [
'username'
{ key: 'password', type: 'password', disableSuccessState: true, feedback: false }
{ type: 'submit', style: 'btn btn-primary', title: 'Sign In'}
]
$scope.submitForm = (form) ->
flash.error = null
session = new Resources.Session($scope.user)
session.$save (success) ->
$window.sessionStorage.token = session.token
$scope.$parent.refreshUser()
$location.path($location.search().return_to || "/projects").search('return_to', null)
, (failure) ->
if failure.data.error
flash.error = failure.data.error
if failure.data.error_code == "AUTHENTICATION_ERROR"
$window.sessionStorage.token = null
form.password = null
])
| 131740 | angular.module("coledger").controller("SignInController", ['$scope', '$location', '$window', 'Resources', 'flash',
($scope, $location, $window, Resources, flash) ->
$scope.user = {}
$scope.schema =
type: 'object'
title: 'User'
properties:
username:
title: 'Username'
type: 'string'
minLength: 3
required: true
password:
title: '<PASSWORD>'
type: 'string'
minLength: 6
required: true
$scope.form = [
'username'
{ key: '<PASSWORD>', type: 'password', disableSuccessState: true, feedback: false }
{ type: 'submit', style: 'btn btn-primary', title: 'Sign In'}
]
$scope.submitForm = (form) ->
flash.error = null
session = new Resources.Session($scope.user)
session.$save (success) ->
$window.sessionStorage.token = session.token
$scope.$parent.refreshUser()
$location.path($location.search().return_to || "/projects").search('return_to', null)
, (failure) ->
if failure.data.error
flash.error = failure.data.error
if failure.data.error_code == "AUTHENTICATION_ERROR"
$window.sessionStorage.token = null
form.password = null
])
| true | angular.module("coledger").controller("SignInController", ['$scope', '$location', '$window', 'Resources', 'flash',
($scope, $location, $window, Resources, flash) ->
$scope.user = {}
$scope.schema =
type: 'object'
title: 'User'
properties:
username:
title: 'Username'
type: 'string'
minLength: 3
required: true
password:
title: 'PI:PASSWORD:<PASSWORD>END_PI'
type: 'string'
minLength: 6
required: true
$scope.form = [
'username'
{ key: 'PI:PASSWORD:<PASSWORD>END_PI', type: 'password', disableSuccessState: true, feedback: false }
{ type: 'submit', style: 'btn btn-primary', title: 'Sign In'}
]
$scope.submitForm = (form) ->
flash.error = null
session = new Resources.Session($scope.user)
session.$save (success) ->
$window.sessionStorage.token = session.token
$scope.$parent.refreshUser()
$location.path($location.search().return_to || "/projects").search('return_to', null)
, (failure) ->
if failure.data.error
flash.error = failure.data.error
if failure.data.error_code == "AUTHENTICATION_ERROR"
$window.sessionStorage.token = null
form.password = null
])
|
[
{
"context": "S.Complex extends mathJS.Number\n\n PARSE_KEY = \"0c\"\n\n ###########################################",
"end": 389,
"score": 0.9937224388122559,
"start": 387,
"tag": "KEY",
"value": "0c"
}
] | js/Numbers/Complex.coffee | jneuendorf/mathJS | 0 | ###*
* @abstract
* @class Complex
* @constructor
* @param {Number} real
* Real part of the number. Either a mathJS.Number or primitive number.
* @param {Number} image
* Real part of the number. Either a mathJS.Number or primitive number.
* @extends Number
*###
# TODO: maybe extend mathJS.Vector instead?! or mix them
class mathJS.Complex extends mathJS.Number
PARSE_KEY = "0c"
###########################################################################
# STATIC
# ###*
# * @Override
# *###
# @_valueIsValid: (value) ->
# return value instanceof mathJS.Number or mathJS.isNum(value)
###*
* @Override
* This method creates an object with the keys "real" and "img" which have primitive numbers as their values.
* @static
* @method _getValueFromParam
* @param {Complex|Number} real
* @param {Number} img
* @return {Object}
*###
@_getValueFromParam: (real, img) ->
if real instanceof mathJS.Complex
return {
real: real.real
img: real.img
}
if real instanceof mathJS.Number and img instanceof mathJS.Number
return {
real: real.value
img: img.value
}
if mathJS.isNum(real) and mathJS.isNum(img)
return {
real: real
img: img
}
return null
@_fromPool: (real, img) ->
if @_pool.length > 0
if @_valueIsValid(real) and @_valueIsValid(img)
number = @_pool.pop()
number.real = real
number.img = img
return number
return null
else
return new @(real, img)
@parse: (str) ->
idx = str.toLowerCase().indexOf(PARSE_KEY)
if idx >= 0
parts = str.substring(idx + PARSE_KEY.length).split ","
if mathJS.isNum(real = parseFloat(parts[0])) and mathJS.isNum(img = parseFloat(parts[1]))
return @_fromPool real, img
return NaN
@random: (max1, min1, max2, min2) ->
return @_fromPool mathJS.randNum(max1, min1), mathJS.randNum(max2, min2)
###########################################################################
# CONSTRUCTOR
constructor: (real, img) ->
values = @_getValueFromParam(real, img)
# if not values?
# fStr = arguments.callee.caller.toString()
# throw new Error("mathJS: Expected 2 numbers or a complex number! Given (#{real}, #{img}) in \"#{fStr.substring(0, fStr.indexOf(")") + 1)}\"")
Object.defineProperties @, {
real:
get: @_getReal
set: @_setReal
img:
get: @_getImg
set: @_setImg
_fromPool:
value: @constructor._fromPool.bind(@constructor)
writable: false
enumarable: false
configurable: false
}
@real = values.real
@img = values.img
###########################################################################
# PRIVATE METHODS
###########################################################################
# PROTECTED METHODS
_setReal: (value) ->
if @_valueIsValid(value)
@_real = value.value or value.real or value
return @
_getReal: () ->
return @_real
_setImg: (value) ->
if @_valueIsValid(value)
@_img = value.value or value.img or value
return @
_getImg: () ->
return @_img
_getValueFromParam: @_getValueFromParam
###########################################################################
# PUBLIC METHODS
###*
* This method check for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2)
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @real is values.real and @img is values.img
return false
plus: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real + values.real, @img + values.img)
return NaN
increase: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
@real += values.real
@img += values.img
return @
plusSelf: @increase
minus: (n) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real - values.real, @img - values.img)
return NaN
decrease: (n) ->
values = @_getValueFromParam(r, i)
if values?
@real -= values.real
@img -= values.img
return @
minusSelf: @decrease
# TODO: adjust last functions for complex numbers
times: (r, i) ->
# return @_fromPool(@value * _getValueFromParam(n))
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real * values.real, @img * values.img)
return NaN
timesSelf: (n) ->
@value *= _getValueFromParam(n)
return @
divide: (n) ->
return @_fromPool(@value / _getValueFromParam(n))
divideSelf: (n) ->
@value /= _getValueFromParam(n)
return @
square: () ->
return @_fromPool(@value * @value)
squareSelf: () ->
@value *= @value
return @
cube: () ->
return @_fromPool(@value * @value * @value)
squareSelf: () ->
@value *= @value * @value
return @
sqrt: () ->
return @_fromPool(mathJS.sqrt @value)
sqrtSelf: () ->
@value = mathJS.sqrt @value
return @
pow: (n) ->
return @_fromPool(mathJS.pow @value, _getValueFromParam(n))
powSelf: (n) ->
@value = mathJS.pow @value, _getValueFromParam(n)
return @
sign: () ->
return mathJS.sign @value
toInt: () ->
return mathJS.Int._fromPool mathJS.floor(@value)
toDouble: () ->
return mathJS.Double._fromPool @value
toString: () ->
return "#{PARSE_KEY}#{@real.toString()},#{@img.toString()}"
clone: () ->
return @_fromPool(@value)
# add instance to pool
release: () ->
@constructor._pool.push @
return @constructor
| 225210 | ###*
* @abstract
* @class Complex
* @constructor
* @param {Number} real
* Real part of the number. Either a mathJS.Number or primitive number.
* @param {Number} image
* Real part of the number. Either a mathJS.Number or primitive number.
* @extends Number
*###
# TODO: maybe extend mathJS.Vector instead?! or mix them
class mathJS.Complex extends mathJS.Number
PARSE_KEY = "<KEY>"
###########################################################################
# STATIC
# ###*
# * @Override
# *###
# @_valueIsValid: (value) ->
# return value instanceof mathJS.Number or mathJS.isNum(value)
###*
* @Override
* This method creates an object with the keys "real" and "img" which have primitive numbers as their values.
* @static
* @method _getValueFromParam
* @param {Complex|Number} real
* @param {Number} img
* @return {Object}
*###
@_getValueFromParam: (real, img) ->
if real instanceof mathJS.Complex
return {
real: real.real
img: real.img
}
if real instanceof mathJS.Number and img instanceof mathJS.Number
return {
real: real.value
img: img.value
}
if mathJS.isNum(real) and mathJS.isNum(img)
return {
real: real
img: img
}
return null
@_fromPool: (real, img) ->
if @_pool.length > 0
if @_valueIsValid(real) and @_valueIsValid(img)
number = @_pool.pop()
number.real = real
number.img = img
return number
return null
else
return new @(real, img)
@parse: (str) ->
idx = str.toLowerCase().indexOf(PARSE_KEY)
if idx >= 0
parts = str.substring(idx + PARSE_KEY.length).split ","
if mathJS.isNum(real = parseFloat(parts[0])) and mathJS.isNum(img = parseFloat(parts[1]))
return @_fromPool real, img
return NaN
@random: (max1, min1, max2, min2) ->
return @_fromPool mathJS.randNum(max1, min1), mathJS.randNum(max2, min2)
###########################################################################
# CONSTRUCTOR
constructor: (real, img) ->
values = @_getValueFromParam(real, img)
# if not values?
# fStr = arguments.callee.caller.toString()
# throw new Error("mathJS: Expected 2 numbers or a complex number! Given (#{real}, #{img}) in \"#{fStr.substring(0, fStr.indexOf(")") + 1)}\"")
Object.defineProperties @, {
real:
get: @_getReal
set: @_setReal
img:
get: @_getImg
set: @_setImg
_fromPool:
value: @constructor._fromPool.bind(@constructor)
writable: false
enumarable: false
configurable: false
}
@real = values.real
@img = values.img
###########################################################################
# PRIVATE METHODS
###########################################################################
# PROTECTED METHODS
_setReal: (value) ->
if @_valueIsValid(value)
@_real = value.value or value.real or value
return @
_getReal: () ->
return @_real
_setImg: (value) ->
if @_valueIsValid(value)
@_img = value.value or value.img or value
return @
_getImg: () ->
return @_img
_getValueFromParam: @_getValueFromParam
###########################################################################
# PUBLIC METHODS
###*
* This method check for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2)
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @real is values.real and @img is values.img
return false
plus: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real + values.real, @img + values.img)
return NaN
increase: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
@real += values.real
@img += values.img
return @
plusSelf: @increase
minus: (n) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real - values.real, @img - values.img)
return NaN
decrease: (n) ->
values = @_getValueFromParam(r, i)
if values?
@real -= values.real
@img -= values.img
return @
minusSelf: @decrease
# TODO: adjust last functions for complex numbers
times: (r, i) ->
# return @_fromPool(@value * _getValueFromParam(n))
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real * values.real, @img * values.img)
return NaN
timesSelf: (n) ->
@value *= _getValueFromParam(n)
return @
divide: (n) ->
return @_fromPool(@value / _getValueFromParam(n))
divideSelf: (n) ->
@value /= _getValueFromParam(n)
return @
square: () ->
return @_fromPool(@value * @value)
squareSelf: () ->
@value *= @value
return @
cube: () ->
return @_fromPool(@value * @value * @value)
squareSelf: () ->
@value *= @value * @value
return @
sqrt: () ->
return @_fromPool(mathJS.sqrt @value)
sqrtSelf: () ->
@value = mathJS.sqrt @value
return @
pow: (n) ->
return @_fromPool(mathJS.pow @value, _getValueFromParam(n))
powSelf: (n) ->
@value = mathJS.pow @value, _getValueFromParam(n)
return @
sign: () ->
return mathJS.sign @value
toInt: () ->
return mathJS.Int._fromPool mathJS.floor(@value)
toDouble: () ->
return mathJS.Double._fromPool @value
toString: () ->
return "#{PARSE_KEY}#{@real.toString()},#{@img.toString()}"
clone: () ->
return @_fromPool(@value)
# add instance to pool
release: () ->
@constructor._pool.push @
return @constructor
| true | ###*
* @abstract
* @class Complex
* @constructor
* @param {Number} real
* Real part of the number. Either a mathJS.Number or primitive number.
* @param {Number} image
* Real part of the number. Either a mathJS.Number or primitive number.
* @extends Number
*###
# TODO: maybe extend mathJS.Vector instead?! or mix them
class mathJS.Complex extends mathJS.Number
PARSE_KEY = "PI:KEY:<KEY>END_PI"
###########################################################################
# STATIC
# ###*
# * @Override
# *###
# @_valueIsValid: (value) ->
# return value instanceof mathJS.Number or mathJS.isNum(value)
###*
* @Override
* This method creates an object with the keys "real" and "img" which have primitive numbers as their values.
* @static
* @method _getValueFromParam
* @param {Complex|Number} real
* @param {Number} img
* @return {Object}
*###
@_getValueFromParam: (real, img) ->
if real instanceof mathJS.Complex
return {
real: real.real
img: real.img
}
if real instanceof mathJS.Number and img instanceof mathJS.Number
return {
real: real.value
img: img.value
}
if mathJS.isNum(real) and mathJS.isNum(img)
return {
real: real
img: img
}
return null
@_fromPool: (real, img) ->
if @_pool.length > 0
if @_valueIsValid(real) and @_valueIsValid(img)
number = @_pool.pop()
number.real = real
number.img = img
return number
return null
else
return new @(real, img)
@parse: (str) ->
idx = str.toLowerCase().indexOf(PARSE_KEY)
if idx >= 0
parts = str.substring(idx + PARSE_KEY.length).split ","
if mathJS.isNum(real = parseFloat(parts[0])) and mathJS.isNum(img = parseFloat(parts[1]))
return @_fromPool real, img
return NaN
@random: (max1, min1, max2, min2) ->
return @_fromPool mathJS.randNum(max1, min1), mathJS.randNum(max2, min2)
###########################################################################
# CONSTRUCTOR
constructor: (real, img) ->
values = @_getValueFromParam(real, img)
# if not values?
# fStr = arguments.callee.caller.toString()
# throw new Error("mathJS: Expected 2 numbers or a complex number! Given (#{real}, #{img}) in \"#{fStr.substring(0, fStr.indexOf(")") + 1)}\"")
Object.defineProperties @, {
real:
get: @_getReal
set: @_setReal
img:
get: @_getImg
set: @_setImg
_fromPool:
value: @constructor._fromPool.bind(@constructor)
writable: false
enumarable: false
configurable: false
}
@real = values.real
@img = values.img
###########################################################################
# PRIVATE METHODS
###########################################################################
# PROTECTED METHODS
_setReal: (value) ->
if @_valueIsValid(value)
@_real = value.value or value.real or value
return @
_getReal: () ->
return @_real
_setImg: (value) ->
if @_valueIsValid(value)
@_img = value.value or value.img or value
return @
_getImg: () ->
return @_img
_getValueFromParam: @_getValueFromParam
###########################################################################
# PUBLIC METHODS
###*
* This method check for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2)
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @real is values.real and @img is values.img
return false
plus: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real + values.real, @img + values.img)
return NaN
increase: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
@real += values.real
@img += values.img
return @
plusSelf: @increase
minus: (n) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real - values.real, @img - values.img)
return NaN
decrease: (n) ->
values = @_getValueFromParam(r, i)
if values?
@real -= values.real
@img -= values.img
return @
minusSelf: @decrease
# TODO: adjust last functions for complex numbers
times: (r, i) ->
# return @_fromPool(@value * _getValueFromParam(n))
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real * values.real, @img * values.img)
return NaN
timesSelf: (n) ->
@value *= _getValueFromParam(n)
return @
divide: (n) ->
return @_fromPool(@value / _getValueFromParam(n))
divideSelf: (n) ->
@value /= _getValueFromParam(n)
return @
square: () ->
return @_fromPool(@value * @value)
squareSelf: () ->
@value *= @value
return @
cube: () ->
return @_fromPool(@value * @value * @value)
squareSelf: () ->
@value *= @value * @value
return @
sqrt: () ->
return @_fromPool(mathJS.sqrt @value)
sqrtSelf: () ->
@value = mathJS.sqrt @value
return @
pow: (n) ->
return @_fromPool(mathJS.pow @value, _getValueFromParam(n))
powSelf: (n) ->
@value = mathJS.pow @value, _getValueFromParam(n)
return @
sign: () ->
return mathJS.sign @value
toInt: () ->
return mathJS.Int._fromPool mathJS.floor(@value)
toDouble: () ->
return mathJS.Double._fromPool @value
toString: () ->
return "#{PARSE_KEY}#{@real.toString()},#{@img.toString()}"
clone: () ->
return @_fromPool(@value)
# add instance to pool
release: () ->
@constructor._pool.push @
return @constructor
|
[
{
"context": "re = fuzzy_filter all_temp_list, query_temp, key:'name'\n # console.log filter_re\n @load_search",
"end": 3894,
"score": 0.9762274026870728,
"start": 3890,
"tag": "KEY",
"value": "name"
}
] | lib/views/template_list/package-detail-view.coffee | jcrom/emp-template-management | 1 | {$$, TextEditorView, View} = require 'atom-space-pen-views'
{CompositeDisposable} = require 'atom'
_ = require 'underscore-plus'
emp = require '../../exports/emp'
fuzzy_filter = require('fuzzaldrin').filter
AvailableTypePanel = require './available-type-panel'
AvailableTemplatePanel = require './available-template-panel'
module.exports =
class PackageDetailPanel extends View
# Subscriber.includeInto(this)
@content: ->
@div =>
@ol outlet: 'breadcrumbContainer', class: 'native-key-bindings breadcrumb', tabindex: -1, =>
@li =>
@a outlet: 'breadcrumb'
@li class: 'active', =>
@a outlet: 'title'
@section class: 'section', =>
@div class: 'section-container', =>
@section outlet:'package_list', class: 'sub-section installed-packages', =>
@div class: 'section-heading icon icon-package', =>
@text "Search Templates: "
# @span outlet: 'total_temp', class:'section-heading-count', ' (…)'
@div class: 'container package-container', =>
# @div class: 'alert alert-info loading-area icon icon-hourglass', "No CBB Element"
@subview "temp_search", new TextEditorView(mini: true,attributes: {id: 'temp_search', type: 'string'}, placeholderText: ' Template Name')
@section class: 'section', =>
@div class: 'section-container', =>
@section class: 'sub-section installed-packages', =>
@div class: 'section-heading icon icon-package', =>
@text "校验组件: "
# @span outlet: 'total_temp', class:'section-heading-count', ' (…)'
# @div class: 'container package-container', =>
# # @div class: 'alert alert-info loading-area icon icon-hourglass', "No CBB Element"
# # @subview "temp_search", new TextEditorView(mini: true,attributes: {id: 'cbb_check', type: 'string'}, placeholderText: ' Template Name')
# @button class: 'control-btn btn btn-info', click:'do_cbb_check','Check CBB List'
@div outlet:"search_container", style:"display:none;", class: 'section-container', =>
@section class: 'sub-section installed-packages', =>
@div class: 'section-heading icon icon-package', =>
@text "Search Result"
@div outlet: 'template_element', class: 'container package-container', =>
@div class: 'alert alert-info loading-area icon icon-hourglass', "No CBB Element"
@div outlet:"section_container", class: 'section-container'
initialize: () ->
@disposables = new CompositeDisposable()
@packageViews = []
@cbb_management = atom.project.cbb_management
@disposables.add atom.commands.add @temp_search.element, 'core:confirm', =>
@do_temp_search()
refresh_detail:(@pack={}) ->
# console.log "do refresh"
# console.log @pack
@title.text("#{_.undasherize(_.uncamelcase(@pack.name))}")
@temp_search.setText ""
@loadTemplates()
@section_container.show()
@search_container.hide()
loadTemplates: ->
# console.log "loadTemplates1"
@section_container.empty()
type_list = @pack.type_list
# console.log type_list
for tmp_type in type_list
tmp_type_panel = new AvailableTypePanel(tmp_type, @pack)
@section_container.append tmp_type_panel
detached: ->
# @unsubscribe()
dispose: ->
@disposables.dispose()
beforeShow: (opts) ->
if opts?.back
@breadcrumb.text(opts.back).on 'click', () =>
@parents('.emp-template-management').view()?.showPanel(opts.back)
else
@breadcrumbContainer.hide()
do_temp_search: ->
query_temp = @temp_search.getText()?.trim()
if query_temp
# console.log query_temp
all_temp_list = @get_temp_list()
# console.log all_temp_list
filter_re = fuzzy_filter all_temp_list, query_temp, key:'name'
# console.log filter_re
@load_search_templates(filter_re)
@section_container.hide()
@search_container.show()
else
# console.log "do search null"
@section_container.show()
@search_container.hide()
load_search_templates: (filter_re)->
@template_element.empty()
@template_element.empty()
for ele_obj in filter_re
ele_panel = new AvailableTemplatePanel(ele_obj.obj, this, @pack, ele_obj.type)
@template_element.append ele_panel
get_temp_list: ->
temp_list = new Array()
for tmp_type in @pack.type_list
for tmp_name, tmp_obj of @pack.get_element(tmp_type)
temp_list.push @new_temp(tmp_name, tmp_type, tmp_obj)
temp_list
new_temp:(tmp_name, tmp_type, tmp_obj) ->
{name:tmp_name, type:tmp_type, obj:tmp_obj}
do_cbb_check: ()->
console.log "do check"
# console.log @pack
@pack.check_path()
# @cbb_management.check_cbb_list(@pack?.name)
| 112309 | {$$, TextEditorView, View} = require 'atom-space-pen-views'
{CompositeDisposable} = require 'atom'
_ = require 'underscore-plus'
emp = require '../../exports/emp'
fuzzy_filter = require('fuzzaldrin').filter
AvailableTypePanel = require './available-type-panel'
AvailableTemplatePanel = require './available-template-panel'
module.exports =
class PackageDetailPanel extends View
# Subscriber.includeInto(this)
@content: ->
@div =>
@ol outlet: 'breadcrumbContainer', class: 'native-key-bindings breadcrumb', tabindex: -1, =>
@li =>
@a outlet: 'breadcrumb'
@li class: 'active', =>
@a outlet: 'title'
@section class: 'section', =>
@div class: 'section-container', =>
@section outlet:'package_list', class: 'sub-section installed-packages', =>
@div class: 'section-heading icon icon-package', =>
@text "Search Templates: "
# @span outlet: 'total_temp', class:'section-heading-count', ' (…)'
@div class: 'container package-container', =>
# @div class: 'alert alert-info loading-area icon icon-hourglass', "No CBB Element"
@subview "temp_search", new TextEditorView(mini: true,attributes: {id: 'temp_search', type: 'string'}, placeholderText: ' Template Name')
@section class: 'section', =>
@div class: 'section-container', =>
@section class: 'sub-section installed-packages', =>
@div class: 'section-heading icon icon-package', =>
@text "校验组件: "
# @span outlet: 'total_temp', class:'section-heading-count', ' (…)'
# @div class: 'container package-container', =>
# # @div class: 'alert alert-info loading-area icon icon-hourglass', "No CBB Element"
# # @subview "temp_search", new TextEditorView(mini: true,attributes: {id: 'cbb_check', type: 'string'}, placeholderText: ' Template Name')
# @button class: 'control-btn btn btn-info', click:'do_cbb_check','Check CBB List'
@div outlet:"search_container", style:"display:none;", class: 'section-container', =>
@section class: 'sub-section installed-packages', =>
@div class: 'section-heading icon icon-package', =>
@text "Search Result"
@div outlet: 'template_element', class: 'container package-container', =>
@div class: 'alert alert-info loading-area icon icon-hourglass', "No CBB Element"
@div outlet:"section_container", class: 'section-container'
initialize: () ->
@disposables = new CompositeDisposable()
@packageViews = []
@cbb_management = atom.project.cbb_management
@disposables.add atom.commands.add @temp_search.element, 'core:confirm', =>
@do_temp_search()
refresh_detail:(@pack={}) ->
# console.log "do refresh"
# console.log @pack
@title.text("#{_.undasherize(_.uncamelcase(@pack.name))}")
@temp_search.setText ""
@loadTemplates()
@section_container.show()
@search_container.hide()
loadTemplates: ->
# console.log "loadTemplates1"
@section_container.empty()
type_list = @pack.type_list
# console.log type_list
for tmp_type in type_list
tmp_type_panel = new AvailableTypePanel(tmp_type, @pack)
@section_container.append tmp_type_panel
detached: ->
# @unsubscribe()
dispose: ->
@disposables.dispose()
beforeShow: (opts) ->
if opts?.back
@breadcrumb.text(opts.back).on 'click', () =>
@parents('.emp-template-management').view()?.showPanel(opts.back)
else
@breadcrumbContainer.hide()
do_temp_search: ->
query_temp = @temp_search.getText()?.trim()
if query_temp
# console.log query_temp
all_temp_list = @get_temp_list()
# console.log all_temp_list
filter_re = fuzzy_filter all_temp_list, query_temp, key:'<KEY>'
# console.log filter_re
@load_search_templates(filter_re)
@section_container.hide()
@search_container.show()
else
# console.log "do search null"
@section_container.show()
@search_container.hide()
load_search_templates: (filter_re)->
@template_element.empty()
@template_element.empty()
for ele_obj in filter_re
ele_panel = new AvailableTemplatePanel(ele_obj.obj, this, @pack, ele_obj.type)
@template_element.append ele_panel
get_temp_list: ->
temp_list = new Array()
for tmp_type in @pack.type_list
for tmp_name, tmp_obj of @pack.get_element(tmp_type)
temp_list.push @new_temp(tmp_name, tmp_type, tmp_obj)
temp_list
new_temp:(tmp_name, tmp_type, tmp_obj) ->
{name:tmp_name, type:tmp_type, obj:tmp_obj}
do_cbb_check: ()->
console.log "do check"
# console.log @pack
@pack.check_path()
# @cbb_management.check_cbb_list(@pack?.name)
| true | {$$, TextEditorView, View} = require 'atom-space-pen-views'
{CompositeDisposable} = require 'atom'
_ = require 'underscore-plus'
emp = require '../../exports/emp'
fuzzy_filter = require('fuzzaldrin').filter
AvailableTypePanel = require './available-type-panel'
AvailableTemplatePanel = require './available-template-panel'
module.exports =
class PackageDetailPanel extends View
# Subscriber.includeInto(this)
@content: ->
@div =>
@ol outlet: 'breadcrumbContainer', class: 'native-key-bindings breadcrumb', tabindex: -1, =>
@li =>
@a outlet: 'breadcrumb'
@li class: 'active', =>
@a outlet: 'title'
@section class: 'section', =>
@div class: 'section-container', =>
@section outlet:'package_list', class: 'sub-section installed-packages', =>
@div class: 'section-heading icon icon-package', =>
@text "Search Templates: "
# @span outlet: 'total_temp', class:'section-heading-count', ' (…)'
@div class: 'container package-container', =>
# @div class: 'alert alert-info loading-area icon icon-hourglass', "No CBB Element"
@subview "temp_search", new TextEditorView(mini: true,attributes: {id: 'temp_search', type: 'string'}, placeholderText: ' Template Name')
@section class: 'section', =>
@div class: 'section-container', =>
@section class: 'sub-section installed-packages', =>
@div class: 'section-heading icon icon-package', =>
@text "校验组件: "
# @span outlet: 'total_temp', class:'section-heading-count', ' (…)'
# @div class: 'container package-container', =>
# # @div class: 'alert alert-info loading-area icon icon-hourglass', "No CBB Element"
# # @subview "temp_search", new TextEditorView(mini: true,attributes: {id: 'cbb_check', type: 'string'}, placeholderText: ' Template Name')
# @button class: 'control-btn btn btn-info', click:'do_cbb_check','Check CBB List'
@div outlet:"search_container", style:"display:none;", class: 'section-container', =>
@section class: 'sub-section installed-packages', =>
@div class: 'section-heading icon icon-package', =>
@text "Search Result"
@div outlet: 'template_element', class: 'container package-container', =>
@div class: 'alert alert-info loading-area icon icon-hourglass', "No CBB Element"
@div outlet:"section_container", class: 'section-container'
initialize: () ->
@disposables = new CompositeDisposable()
@packageViews = []
@cbb_management = atom.project.cbb_management
@disposables.add atom.commands.add @temp_search.element, 'core:confirm', =>
@do_temp_search()
refresh_detail:(@pack={}) ->
# console.log "do refresh"
# console.log @pack
@title.text("#{_.undasherize(_.uncamelcase(@pack.name))}")
@temp_search.setText ""
@loadTemplates()
@section_container.show()
@search_container.hide()
loadTemplates: ->
# console.log "loadTemplates1"
@section_container.empty()
type_list = @pack.type_list
# console.log type_list
for tmp_type in type_list
tmp_type_panel = new AvailableTypePanel(tmp_type, @pack)
@section_container.append tmp_type_panel
detached: ->
# @unsubscribe()
dispose: ->
@disposables.dispose()
beforeShow: (opts) ->
if opts?.back
@breadcrumb.text(opts.back).on 'click', () =>
@parents('.emp-template-management').view()?.showPanel(opts.back)
else
@breadcrumbContainer.hide()
do_temp_search: ->
query_temp = @temp_search.getText()?.trim()
if query_temp
# console.log query_temp
all_temp_list = @get_temp_list()
# console.log all_temp_list
filter_re = fuzzy_filter all_temp_list, query_temp, key:'PI:KEY:<KEY>END_PI'
# console.log filter_re
@load_search_templates(filter_re)
@section_container.hide()
@search_container.show()
else
# console.log "do search null"
@section_container.show()
@search_container.hide()
load_search_templates: (filter_re)->
@template_element.empty()
@template_element.empty()
for ele_obj in filter_re
ele_panel = new AvailableTemplatePanel(ele_obj.obj, this, @pack, ele_obj.type)
@template_element.append ele_panel
get_temp_list: ->
temp_list = new Array()
for tmp_type in @pack.type_list
for tmp_name, tmp_obj of @pack.get_element(tmp_type)
temp_list.push @new_temp(tmp_name, tmp_type, tmp_obj)
temp_list
new_temp:(tmp_name, tmp_type, tmp_obj) ->
{name:tmp_name, type:tmp_type, obj:tmp_obj}
do_cbb_check: ()->
console.log "do check"
# console.log @pack
@pack.check_path()
# @cbb_management.check_cbb_list(@pack?.name)
|
[
{
"context": "fee script highlighter\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nColorifier.coffee = Colorifier.coffeescript = n",
"end": 79,
"score": 0.9998899102210999,
"start": 62,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | src/lang/coffeescript.coffee | MadRabbit/colorifier | 1 | #
# The coffee script highlighter
#
# Copyright (C) 2011-2012 Nikolay Nemshilov
#
Colorifier.coffee = Colorifier.coffeescript = new Class Colorifier,
comments: "#"
keywords: "function,return,for,if,else,while,do,throw,try,catch,instanceof,class,"+
"extends,in,of,where,super,is,isnt,until,unless,then,or,and,switch,when,"+
"break,continue"
objects: "new,this,self"
booleans: "true,false,null,undefined,typeof"
paint: (text)->
@$super text, (text)->
text = text.replace /(^|.)(@[a-z0-9_]*)/ig, (m, _1, _2)->
"#{_1}<span class=\"property\">#{_2}</span>"
text.replace /(^|[^a-z0-9_])([a-z0-9_]+)(\s*:)/ig, (m, _1, _2, _3)->
"#{_1}<span class=\"attribute\">#{_2}</span>#{_3}"
Colorifier.coffee::strings = "\"\"\",\",''','"
| 176986 | #
# The coffee script highlighter
#
# Copyright (C) 2011-2012 <NAME>
#
Colorifier.coffee = Colorifier.coffeescript = new Class Colorifier,
comments: "#"
keywords: "function,return,for,if,else,while,do,throw,try,catch,instanceof,class,"+
"extends,in,of,where,super,is,isnt,until,unless,then,or,and,switch,when,"+
"break,continue"
objects: "new,this,self"
booleans: "true,false,null,undefined,typeof"
paint: (text)->
@$super text, (text)->
text = text.replace /(^|.)(@[a-z0-9_]*)/ig, (m, _1, _2)->
"#{_1}<span class=\"property\">#{_2}</span>"
text.replace /(^|[^a-z0-9_])([a-z0-9_]+)(\s*:)/ig, (m, _1, _2, _3)->
"#{_1}<span class=\"attribute\">#{_2}</span>#{_3}"
Colorifier.coffee::strings = "\"\"\",\",''','"
| true | #
# The coffee script highlighter
#
# Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI
#
Colorifier.coffee = Colorifier.coffeescript = new Class Colorifier,
comments: "#"
keywords: "function,return,for,if,else,while,do,throw,try,catch,instanceof,class,"+
"extends,in,of,where,super,is,isnt,until,unless,then,or,and,switch,when,"+
"break,continue"
objects: "new,this,self"
booleans: "true,false,null,undefined,typeof"
paint: (text)->
@$super text, (text)->
text = text.replace /(^|.)(@[a-z0-9_]*)/ig, (m, _1, _2)->
"#{_1}<span class=\"property\">#{_2}</span>"
text.replace /(^|[^a-z0-9_])([a-z0-9_]+)(\s*:)/ig, (m, _1, _2, _3)->
"#{_1}<span class=\"attribute\">#{_2}</span>#{_3}"
Colorifier.coffee::strings = "\"\"\",\",''','"
|
[
{
"context": " expect(Watchers::watch).to.be.calledWith(\"/Users/brian/app/cypress.json\")\n\n it.skip \"passes watchers ",
"end": 7204,
"score": 0.7623712420463562,
"start": 7199,
"tag": "USERNAME",
"value": "brian"
},
{
"context": "stub(user, \"ensureAuthToken\").resolves(\"auth-token-123\")\n\n it \"closes server\", ->\n @project.serv",
"end": 7761,
"score": 0.7102938890457153,
"start": 7758,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "stub(user, \"ensureAuthToken\").resolves(\"auth-token-123\")\n\n it \"calls api.getProjectRuns with project ",
"end": 8463,
"score": 0.6829019784927368,
"start": 8460,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "->\n @recordKeys = []\n @project = Project(@pristinePath)\n @sandbox.stub(settings, \"read\").resolves({",
"end": 21175,
"score": 0.8239916563034058,
"start": 21162,
"tag": "USERNAME",
"value": "@pristinePath"
},
{
"context": "b(user, \"ensureAuthToken\").resolves(\"auth-token-123\")\n @sandbox.stub(api, \"getProjectRecordKeys\"",
"end": 21316,
"score": 0.5191074013710022,
"start": 21315,
"tag": "PASSWORD",
"value": "3"
},
{
"context": "ss\", ->\n beforeEach ->\n @project = Project(@pristinePath)\n @sandbox.stub(user, \"ensureAuthToken\").res",
"end": 21805,
"score": 0.8650370836257935,
"start": 21792,
"tag": "USERNAME",
"value": "@pristinePath"
}
] | packages/server/test/unit/project_spec.coffee | hunslater-olc/cypress | 0 | require("../spec_helper")
path = require("path")
Promise = require("bluebird")
fs = require("fs-extra")
Fixtures = require("../support/helpers/fixtures")
ids = require("#{root}lib/ids")
api = require("#{root}lib/api")
user = require("#{root}lib/user")
cache = require("#{root}lib/cache")
errors = require("#{root}lib/errors")
config = require("#{root}lib/config")
scaffold = require("#{root}lib/scaffold")
Server = require("#{root}lib/server")
Project = require("#{root}lib/project")
Automation = require("#{root}lib/automation")
settings = require("#{root}lib/util/settings")
savedState = require("#{root}lib/saved_state")
commitInfo = require("@cypress/commit-info")
preprocessor = require("#{root}lib/plugins/preprocessor")
plugins = require("#{root}lib/plugins")
describe "lib/project", ->
beforeEach ->
Fixtures.scaffold()
@todosPath = Fixtures.projectPath("todos")
@idsPath = Fixtures.projectPath("ids")
@pristinePath = Fixtures.projectPath("pristine")
settings.read(@todosPath).then (obj = {}) =>
{@projectId} = obj
config.set({projectName: "project", projectRoot: "/foo/bar"})
.then (@config) =>
@project = Project(@todosPath)
afterEach ->
Fixtures.remove()
@project?.close()
it "requires a projectRoot", ->
fn = -> Project()
expect(fn).to.throw "Instantiating lib/project requires a projectRoot!"
it "always resolves the projectRoot to be absolute", ->
p = Project("../foo/bar")
expect(p.projectRoot).not.to.eq("../foo/bar")
expect(p.projectRoot).to.eq(path.resolve("../foo/bar"))
context "#saveState", ->
beforeEach ->
integrationFolder = "the/save/state/test"
@sandbox.stub(config, "get").withArgs(@todosPath).resolves({ integrationFolder })
@sandbox.stub(@project, "determineIsNewProject").withArgs(integrationFolder).resolves(false)
@project.cfg = { integrationFolder }
savedState(@project.projectRoot)
.then (state) -> state.remove()
afterEach ->
savedState(@project.projectRoot)
.then (state) -> state.remove()
it "saves state without modification", ->
@project.saveState()
.then (state) ->
expect(state).to.deep.eq({})
it "adds property", ->
@project.saveState()
.then () => @project.saveState({ foo: 42 })
.then (state) ->
expect(state).to.deep.eq({ foo: 42 })
it "adds second property", ->
@project.saveState()
.then () => @project.saveState({ foo: 42 })
.then () => @project.saveState({ bar: true })
.then (state) ->
expect(state).to.deep.eq({ foo: 42, bar: true })
it "modifes property", ->
@project.saveState()
.then () => @project.saveState({ foo: 42 })
.then () => @project.saveState({ foo: 'modified' })
.then (state) ->
expect(state).to.deep.eq({ foo: 'modified' })
context "#getConfig", ->
integrationFolder = "foo/bar/baz"
beforeEach ->
@sandbox.stub(config, "get").withArgs(@todosPath, {foo: "bar"}).resolves({ baz: "quux", integrationFolder })
@sandbox.stub(@project, "determineIsNewProject").withArgs(integrationFolder).resolves(false)
it "calls config.get with projectRoot + options + saved state", ->
savedState(@todosPath)
.then (state) =>
@sandbox.stub(state, "get").resolves({ reporterWidth: 225 })
@project.getConfig({foo: "bar"})
.then (cfg) ->
expect(cfg).to.deep.eq({
integrationFolder
isNewProject: false
baz: "quux"
state: {
reporterWidth: 225
}
})
it "resolves if cfg is already set", ->
@project.cfg = {
integrationFolder: integrationFolder,
foo: "bar"
}
@project.getConfig()
.then (cfg) ->
expect(cfg).to.deep.eq({
integrationFolder: integrationFolder,
foo: "bar"
})
it "sets cfg.isNewProject to true when state.showedOnBoardingModal is true", ->
savedState(@todosPath)
.then (state) =>
@sandbox.stub(state, "get").resolves({ showedOnBoardingModal: true })
@project.getConfig({foo: "bar"})
.then (cfg) ->
expect(cfg).to.deep.eq({
integrationFolder
isNewProject: false
baz: "quux"
state: {
showedOnBoardingModal: true
}
})
context "#open", ->
beforeEach ->
@sandbox.stub(@project, "watchSettingsAndStartWebsockets").resolves()
@sandbox.stub(@project, "checkSupportFile").resolves()
@sandbox.stub(@project, "scaffold").resolves()
@sandbox.stub(@project, "getConfig").resolves(@config)
@sandbox.stub(Server.prototype, "open").resolves([])
@sandbox.stub(Server.prototype, "reset")
@sandbox.stub(config, "updateWithPluginValues").returns(@config)
@sandbox.stub(scaffold, "plugins").resolves()
@sandbox.stub(plugins, "init").resolves()
it "calls #watchSettingsAndStartWebsockets with options + config", ->
opts = {changeEvents: false, onAutomationRequest: ->}
@project.cfg = {}
@project.open(opts).then =>
expect(@project.watchSettingsAndStartWebsockets).to.be.calledWith(opts, @project.cfg)
it "calls #scaffold with server config promise", ->
@project.open().then =>
expect(@project.scaffold).to.be.calledWith(@config)
it "calls #checkSupportFile with server config when scaffolding is finished", ->
@project.open().then =>
expect(@project.checkSupportFile).to.be.calledWith(@config)
it "calls #getConfig options", ->
opts = {}
@project.open(opts).then =>
expect(@project.getConfig).to.be.calledWith(opts)
it "initializes the plugins", ->
@project.open({}).then =>
expect(plugins.init).to.be.called
it "calls support.plugins with pluginsFile directory", ->
@project.open({}).then =>
expect(scaffold.plugins).to.be.calledWith(path.dirname(@config.pluginsFile))
it "calls options.onError with plugins error when there is a plugins error", ->
onError = @sandbox.spy()
err = {
name: "plugin error name"
message: "plugin error message"
}
@project.open({ onError: onError }).then =>
pluginsOnError = plugins.init.lastCall.args[1].onError
expect(pluginsOnError).to.be.a("function")
pluginsOnError(err)
expect(onError).to.be.calledWith(err)
it "updates config.state when saved state changes", ->
@sandbox.spy(@project, "saveState")
options = {}
@project.open(options)
.then =>
options.onSavedStateChanged({ autoScrollingEnabled: false })
.then =>
@project.getConfig()
.then (config) =>
expect(@project.saveState).to.be.calledWith({ autoScrollingEnabled: false})
expect(config.state).to.eql({ autoScrollingEnabled: false })
it.skip "watches cypress.json", ->
@server.open().bind(@).then ->
expect(Watchers::watch).to.be.calledWith("/Users/brian/app/cypress.json")
it.skip "passes watchers to Socket.startListening", ->
options = {}
@server.open(options).then ->
startListening = Socket::startListening
expect(startListening.getCall(0).args[0]).to.be.instanceof(Watchers)
expect(startListening.getCall(0).args[1]).to.eq(options)
context "#close", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@sandbox.stub(@project, "getConfig").resolves(@config)
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "closes server", ->
@project.server = @sandbox.stub({close: ->})
@project.close().then =>
expect(@project.server.close).to.be.calledOnce
it "closes watchers", ->
@project.watchers = @sandbox.stub({close: ->})
@project.close().then =>
expect(@project.watchers.close).to.be.calledOnce
it "can close when server + watchers arent open", ->
@project.close()
context "#getRuns", ->
beforeEach ->
@project = Project(@todosPath)
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@sandbox.stub(api, "getProjectRuns").resolves('runs')
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "calls api.getProjectRuns with project id + session", ->
@project.getRuns().then (runs) ->
expect(api.getProjectRuns).to.be.calledWith("id-123", "auth-token-123")
expect(runs).to.equal("runs")
context "#scaffold", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@sandbox.stub(scaffold, "integration").resolves()
@sandbox.stub(scaffold, "fixture").resolves()
@sandbox.stub(scaffold, "support").resolves()
@sandbox.stub(scaffold, "plugins").resolves()
@obj = {projectRoot: "pr", fixturesFolder: "ff", integrationFolder: "if", supportFolder: "sf", pluginsFile: "pf/index.js"}
it "calls scaffold.integration with integrationFolder", ->
@project.scaffold(@obj).then =>
expect(scaffold.integration).to.be.calledWith(@obj.integrationFolder)
it "calls fixture.scaffold with fixturesFolder", ->
@project.scaffold(@obj).then =>
expect(scaffold.fixture).to.be.calledWith(@obj.fixturesFolder)
it "calls support.scaffold with supportFolder", ->
@project.scaffold(@obj).then =>
expect(scaffold.support).to.be.calledWith(@obj.supportFolder)
it "does not call support.plugins if config.pluginsFile is falsey", ->
@obj.pluginsFile = false
@project.scaffold(@obj).then =>
expect(scaffold.plugins).not.to.be.called
context "#watchSettings", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@project.server = {startWebsockets: ->}
@sandbox.stub(settings, "pathToCypressJson").returns("/path/to/cypress.json")
@sandbox.stub(settings, "pathToCypressEnvJson").returns("/path/to/cypress.env.json")
@watch = @sandbox.stub(@project.watchers, "watch")
it "watches cypress.json and cypress.env.json", ->
@project.watchSettingsAndStartWebsockets({onSettingsChanged: ->})
expect(@watch).to.be.calledTwice
expect(@watch).to.be.calledWith("/path/to/cypress.json")
expect(@watch).to.be.calledWith("/path/to/cypress.env.json")
it "sets onChange event when {changeEvents: true}", (done) ->
@project.watchSettingsAndStartWebsockets({onSettingsChanged: done})
## get the object passed to watchers.watch
obj = @watch.getCall(0).args[1]
expect(obj.onChange).to.be.a("function")
obj.onChange()
it "does not call watch when {changeEvents: false}", ->
@project.watchSettingsAndStartWebsockets({onSettingsChanged: undefined})
expect(@watch).not.to.be.called
it "does not call onSettingsChanged when generatedProjectIdTimestamp is less than 1 second", ->
@project.generatedProjectIdTimestamp = timestamp = new Date()
emit = @sandbox.spy(@project, "emit")
stub = @sandbox.stub()
@project.watchSettingsAndStartWebsockets({onSettingsChanged: stub})
## get the object passed to watchers.watch
obj = @watch.getCall(0).args[1]
obj.onChange()
expect(stub).not.to.be.called
## subtract 1 second from our timestamp
timestamp.setSeconds(timestamp.getSeconds() - 1)
obj.onChange()
expect(stub).to.be.calledOnce
context "#checkSupportFile", ->
beforeEach ->
@sandbox.stub(fs, "pathExists").resolves(true)
@project = Project("/_test-output/path/to/project")
@project.server = {onTestFileChange: @sandbox.spy()}
@sandbox.stub(preprocessor, "getFile").resolves()
@config = {
projectRoot: "/path/to/root/"
supportFile: "/path/to/root/foo/bar.js"
}
it "does nothing when {supportFile: false}", ->
ret = @project.checkSupportFile({supportFile: false})
expect(ret).to.be.undefined
it "throws when support file does not exist", ->
fs.pathExists.resolves(false)
@project.checkSupportFile(@config)
.catch (e) ->
expect(e.message).to.include("The support file is missing or invalid.")
context "#watchPluginsFile", ->
beforeEach ->
@sandbox.stub(fs, "pathExists").resolves(true)
@project = Project("/_test-output/path/to/project")
@project.watchers = { watch: @sandbox.spy() }
@sandbox.stub(plugins, "init").resolves()
@config = {
pluginsFile: "/path/to/plugins-file"
}
it "does nothing when {pluginsFile: false}", ->
@config.pluginsFile = false
@project.watchPluginsFile(@config).then =>
expect(@project.watchers.watch).not.to.be.called
it "does nothing if pluginsFile does not exist", ->
fs.pathExists.resolves(false)
@project.watchPluginsFile(@config).then =>
expect(@project.watchers.watch).not.to.be.called
it "watches the pluginsFile", ->
@project.watchPluginsFile(@config).then =>
expect(@project.watchers.watch).to.be.calledWith(@config.pluginsFile)
expect(@project.watchers.watch.lastCall.args[1]).to.be.an("object")
expect(@project.watchers.watch.lastCall.args[1].onChange).to.be.a("function")
it "calls plugins.init when file changes", ->
@project.watchPluginsFile(@config).then =>
@project.watchers.watch.firstCall.args[1].onChange()
expect(plugins.init).to.be.calledWith(@config)
it "handles errors from calling plugins.init", (done) ->
error = {name: "foo", message: "foo"}
plugins.init.rejects(error)
@project.watchPluginsFile(@config, {
onError: (err) ->
expect(err).to.eql(error)
done()
})
.then =>
@project.watchers.watch.firstCall.args[1].onChange()
return
context "#watchSettingsAndStartWebsockets", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@project.watchers = {}
@project.server = @sandbox.stub({startWebsockets: ->})
@sandbox.stub(@project, "watchSettings")
@sandbox.stub(Automation, "create").returns("automation")
it "calls server.startWebsockets with automation + config", ->
c = {}
@project.watchSettingsAndStartWebsockets({}, c)
expect(@project.server.startWebsockets).to.be.calledWith("automation", c)
it "passes onReloadBrowser callback", ->
fn = @sandbox.stub()
@project.server.startWebsockets.yieldsTo("onReloadBrowser")
@project.watchSettingsAndStartWebsockets({onReloadBrowser: fn}, {})
expect(fn).to.be.calledOnce
context "#getProjectId", ->
afterEach ->
delete process.env.CYPRESS_PROJECT_ID
beforeEach ->
@project = Project("/_test-output/path/to/project")
@verifyExistence = @sandbox.stub(Project.prototype, "verifyExistence").resolves()
it "resolves with process.env.CYPRESS_PROJECT_ID if set", ->
process.env.CYPRESS_PROJECT_ID = "123"
@project.getProjectId().then (id) ->
expect(id).to.eq("123")
it "calls verifyExistence", ->
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@project.getProjectId()
.then =>
expect(@verifyExistence).to.be.calledOnce
it "returns the project id from settings", ->
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@project.getProjectId()
.then (id) ->
expect(id).to.eq "id-123"
it "throws NO_PROJECT_ID with the projectRoot when no projectId was found", ->
@sandbox.stub(settings, "read").resolves({})
@project.getProjectId()
.then (id) ->
throw new Error("expected to fail, but did not")
.catch (err) ->
expect(err.type).to.eq("NO_PROJECT_ID")
expect(err.message).to.include("/_test-output/path/to/project")
it "bubbles up Settings.read errors", ->
err = new Error()
err.code = "EACCES"
@sandbox.stub(settings, "read").rejects(err)
@project.getProjectId()
.then (id) ->
throw new Error("expected to fail, but did not")
.catch (err) ->
expect(err.code).to.eq("EACCES")
context "#writeProjectId", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@sandbox.stub(settings, "write")
.withArgs(@project.projectRoot, {projectId: "id-123"})
.resolves({projectId: "id-123"})
it "calls Settings.write with projectRoot and attrs", ->
@project.writeProjectId("id-123").then (id) ->
expect(id).to.eq("id-123")
it "sets generatedProjectIdTimestamp", ->
@project.writeProjectId("id-123").then =>
expect(@project.generatedProjectIdTimestamp).to.be.a("date")
context "#ensureSpecUrl", ->
beforeEach ->
@project2 = Project(@idsPath)
settings.write(@idsPath, {port: 2020})
it "returns fully qualified url when spec exists", ->
@project2.ensureSpecUrl("cypress/integration/bar.js")
.then (str) ->
expect(str).to.eq("http://localhost:2020/__/#/tests/integration/bar.js")
it "returns fully qualified url on absolute path to spec", ->
todosSpec = path.join(@todosPath, "tests/sub/sub_test.coffee")
@project.ensureSpecUrl(todosSpec)
.then (str) ->
expect(str).to.eq("http://localhost:8888/__/#/tests/integration/sub/sub_test.coffee")
it "returns __all spec url", ->
@project.ensureSpecUrl()
.then (str) ->
expect(str).to.eq("http://localhost:8888/__/#/tests/__all")
it "returns __all spec url with spec is __all", ->
@project.ensureSpecUrl('__all')
.then (str) ->
expect(str).to.eq("http://localhost:8888/__/#/tests/__all")
it "throws when spec isnt found", ->
@project.ensureSpecUrl("does/not/exist.js")
.catch (err) ->
expect(err.type).to.eq("SPEC_FILE_NOT_FOUND")
context "#ensureSpecExists", ->
beforeEach ->
@project2 = Project(@idsPath)
it "resolves relative path to test file against projectRoot", ->
@project2.ensureSpecExists("cypress/integration/foo.coffee")
.then =>
@project.ensureSpecExists("tests/test1.js")
it "resolves + returns absolute path to test file", ->
idsSpec = path.join(@idsPath, "cypress/integration/foo.coffee")
todosSpec = path.join(@todosPath, "tests/sub/sub_test.coffee")
@project2.ensureSpecExists(idsSpec)
.then (spec1) =>
expect(spec1).to.eq(idsSpec)
@project.ensureSpecExists(todosSpec)
.then (spec2) ->
expect(spec2).to.eq(todosSpec)
it "throws SPEC_FILE_NOT_FOUND when spec does not exist", ->
@project2.ensureSpecExists("does/not/exist.js")
.catch (err) =>
expect(err.type).to.eq("SPEC_FILE_NOT_FOUND")
expect(err.message).to.include(path.join(@idsPath, "does/not/exist.js"))
context ".add", ->
beforeEach ->
@pristinePath = Fixtures.projectPath("pristine")
it "inserts path into cache", ->
Project.add(@pristinePath)
.then =>
cache.read()
.then (json) =>
expect(json.PROJECTS).to.deep.eq([@pristinePath])
describe "if project at path has id", ->
it "returns object containing path and id", ->
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
Project.add(@pristinePath)
.then (project) =>
expect(project.id).to.equal("id-123")
expect(project.path).to.equal(@pristinePath)
describe "if project at path does not have id", ->
it "returns object containing just the path", ->
@sandbox.stub(settings, "read").rejects()
Project.add(@pristinePath)
.then (project) =>
expect(project.id).to.be.undefined
expect(project.path).to.equal(@pristinePath)
context "#createCiProject", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@newProject = { id: "project-id-123" }
@sandbox.stub(@project, "writeProjectId").resolves("project-id-123")
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(commitInfo, "getRemoteOrigin").resolves("remoteOrigin")
@sandbox.stub(api, "createProject")
.withArgs({foo: "bar"}, "remoteOrigin", "auth-token-123")
.resolves(@newProject)
it "calls api.createProject with user session", ->
@project.createCiProject({foo: "bar"}).then ->
expect(api.createProject).to.be.calledWith({foo: "bar"}, "remoteOrigin", "auth-token-123")
it "calls writeProjectId with id", ->
@project.createCiProject({foo: "bar"}).then =>
expect(@project.writeProjectId).to.be.calledWith("project-id-123")
it "returns project id", ->
@project.createCiProject({foo: "bar"}).then (projectId) =>
expect(projectId).to.eql(@newProject)
context "#getRecordKeys", ->
beforeEach ->
@recordKeys = []
@project = Project(@pristinePath)
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(api, "getProjectRecordKeys").resolves(@recordKeys)
it "calls api.getProjectRecordKeys with project id + session", ->
@project.getRecordKeys().then ->
expect(api.getProjectRecordKeys).to.be.calledWith("id-123", "auth-token-123")
it "returns ci keys", ->
@project.getRecordKeys().then (recordKeys) =>
expect(recordKeys).to.equal(@recordKeys)
context "#requestAccess", ->
beforeEach ->
@project = Project(@pristinePath)
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(api, "requestAccess").resolves("response")
it "calls api.requestAccess with project id + auth token", ->
@project.requestAccess("project-id-123").then ->
expect(api.requestAccess).to.be.calledWith("project-id-123", "auth-token-123")
it "returns response", ->
@project.requestAccess("project-id-123").then (response) =>
expect(response).to.equal("response")
context ".remove", ->
beforeEach ->
@sandbox.stub(cache, "removeProject").resolves()
it "calls cache.removeProject with path", ->
Project.remove("/_test-output/path/to/project").then ->
expect(cache.removeProject).to.be.calledWith("/_test-output/path/to/project")
context ".id", ->
it "returns project id", ->
Project.id(@todosPath).then (id) =>
expect(id).to.eq(@projectId)
context ".getOrgs", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(api, "getOrgs").resolves([])
it "calls api.getOrgs", ->
Project.getOrgs().then (orgs) ->
expect(orgs).to.deep.eq([])
expect(api.getOrgs).to.be.calledOnce
expect(api.getOrgs).to.be.calledWith("auth-token-123")
context ".paths", ->
beforeEach ->
@sandbox.stub(cache, "getProjectPaths").resolves([])
it "calls cache.getProjectPaths", ->
Project.paths().then (ret) ->
expect(ret).to.deep.eq([])
expect(cache.getProjectPaths).to.be.calledOnce
context ".getPathsAndIds", ->
beforeEach ->
@sandbox.stub(cache, "getProjectPaths").resolves([
"/path/to/first"
"/path/to/second"
])
@sandbox.stub(settings, "id").resolves("id-123")
it "returns array of objects with paths and ids", ->
Project.getPathsAndIds().then (pathsAndIds) ->
expect(pathsAndIds).to.eql([
{
path: "/path/to/first"
id: "id-123"
}
{
path: "/path/to/second"
id: "id-123"
}
])
context ".getProjectStatuses", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "gets projects from api", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([])
.then ->
expect(api.getProjects).to.have.been.calledWith("auth-token-123")
it "returns array of projects", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses).to.eql([])
it "returns same number as client projects, even if there are less api projects", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([{}])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses.length).to.eql(1)
it "returns same number as client projects, even if there are more api projects", ->
@sandbox.stub(api, "getProjects").resolves([{}, {}])
Project.getProjectStatuses([{}])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses.length).to.eql(1)
it "merges in details of matching projects", ->
@sandbox.stub(api, "getProjects").resolves([
{ id: "id-123", lastBuildStatus: "passing" }
])
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
lastBuildStatus: "passing"
state: "VALID"
})
it "returns client project when it has no id", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([{ path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
path: "/_test-output/path/to/project"
state: "VALID"
})
describe "when client project has id and there is no matching user project", ->
beforeEach ->
@sandbox.stub(api, "getProjects").resolves([])
it "marks project as invalid if api 404s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 404})
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "INVALID"
})
it "marks project as unauthorized if api 403s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 403})
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "UNAUTHORIZED"
})
it "merges in project details and marks valid if somehow project exists and is authorized", ->
@sandbox.stub(api, "getProject").resolves({ id: "id-123", lastBuildStatus: "passing" })
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
lastBuildStatus: "passing"
state: "VALID"
})
it "throws error if not accounted for", ->
error = {name: "", message: ""}
@sandbox.stub(api, "getProject").rejects(error)
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then =>
throw new Error("Should throw error")
.catch (err) ->
expect(err).to.equal(error)
context ".getProjectStatus", ->
beforeEach ->
@clientProject = {
id: "id-123",
path: "/_test-output/path/to/project"
}
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "gets project from api", ->
@sandbox.stub(api, "getProject").resolves([])
Project.getProjectStatus(@clientProject)
.then ->
expect(api.getProject).to.have.been.calledWith("id-123", "auth-token-123")
it "returns project merged with details", ->
@sandbox.stub(api, "getProject").resolves({
lastBuildStatus: "passing"
})
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
lastBuildStatus: "passing"
state: "VALID"
})
it "returns project, marked as valid, if it does not have an id, without querying api", ->
@sandbox.stub(api, "getProject")
@clientProject.id = undefined
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: undefined
path: "/_test-output/path/to/project"
state: "VALID"
})
expect(api.getProject).not.to.be.called
it "marks project as invalid if api 404s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 404})
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "INVALID"
})
it "marks project as unauthorized if api 403s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 403})
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "UNAUTHORIZED"
})
it "throws error if not accounted for", ->
error = {name: "", message: ""}
@sandbox.stub(api, "getProject").rejects(error)
Project.getProjectStatus(@clientProject)
.then =>
throw new Error("Should throw error")
.catch (err) ->
expect(err).to.equal(error)
context ".removeIds", ->
beforeEach ->
@sandbox.stub(ids, "remove").resolves({})
it "calls id.remove with path to project tests", ->
p = Fixtures.projectPath("ids")
Project.removeIds(p).then ->
expect(ids.remove).to.be.calledWith(p + "/cypress/integration")
context ".getSecretKeyByPath", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "calls api.getProjectToken with id + session", ->
@sandbox.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("key-123")
Project.getSecretKeyByPath(@todosPath).then (key) ->
expect(key).to.eq("key-123")
it "throws CANNOT_FETCH_PROJECT_TOKEN on error", ->
@sandbox.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
Project.getSecretKeyByPath(@todosPath)
.then ->
throw new Error("should have caught error but did not")
.catch (err) ->
expect(err.type).to.eq("CANNOT_FETCH_PROJECT_TOKEN")
context ".generateSecretKeyByPath", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "calls api.updateProjectToken with id + session", ->
@sandbox.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("new-key-123")
Project.generateSecretKeyByPath(@todosPath).then (key) ->
expect(key).to.eq("new-key-123")
it "throws CANNOT_CREATE_PROJECT_TOKEN on error", ->
@sandbox.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
Project.generateSecretKeyByPath(@todosPath)
.then ->
throw new Error("should have caught error but did not")
.catch (err) ->
expect(err.type).to.eq("CANNOT_CREATE_PROJECT_TOKEN")
context ".findSpecs", ->
it "returns all the specs without a specPattern", ->
Project.findSpecs(@todosPath)
.then (specs = []) ->
expect(specs).to.deep.eq([
"etc/etc.js"
"sub/sub_test.coffee"
"test1.js"
"test2.coffee"
])
it "returns glob subset matching specPattern", ->
Project.findSpecs(@todosPath, "tests/*")
.then (specs = []) ->
expect(specs).to.deep.eq([
"test1.js"
"test2.coffee"
])
| 131034 | require("../spec_helper")
path = require("path")
Promise = require("bluebird")
fs = require("fs-extra")
Fixtures = require("../support/helpers/fixtures")
ids = require("#{root}lib/ids")
api = require("#{root}lib/api")
user = require("#{root}lib/user")
cache = require("#{root}lib/cache")
errors = require("#{root}lib/errors")
config = require("#{root}lib/config")
scaffold = require("#{root}lib/scaffold")
Server = require("#{root}lib/server")
Project = require("#{root}lib/project")
Automation = require("#{root}lib/automation")
settings = require("#{root}lib/util/settings")
savedState = require("#{root}lib/saved_state")
commitInfo = require("@cypress/commit-info")
preprocessor = require("#{root}lib/plugins/preprocessor")
plugins = require("#{root}lib/plugins")
describe "lib/project", ->
beforeEach ->
Fixtures.scaffold()
@todosPath = Fixtures.projectPath("todos")
@idsPath = Fixtures.projectPath("ids")
@pristinePath = Fixtures.projectPath("pristine")
settings.read(@todosPath).then (obj = {}) =>
{@projectId} = obj
config.set({projectName: "project", projectRoot: "/foo/bar"})
.then (@config) =>
@project = Project(@todosPath)
afterEach ->
Fixtures.remove()
@project?.close()
it "requires a projectRoot", ->
fn = -> Project()
expect(fn).to.throw "Instantiating lib/project requires a projectRoot!"
it "always resolves the projectRoot to be absolute", ->
p = Project("../foo/bar")
expect(p.projectRoot).not.to.eq("../foo/bar")
expect(p.projectRoot).to.eq(path.resolve("../foo/bar"))
context "#saveState", ->
beforeEach ->
integrationFolder = "the/save/state/test"
@sandbox.stub(config, "get").withArgs(@todosPath).resolves({ integrationFolder })
@sandbox.stub(@project, "determineIsNewProject").withArgs(integrationFolder).resolves(false)
@project.cfg = { integrationFolder }
savedState(@project.projectRoot)
.then (state) -> state.remove()
afterEach ->
savedState(@project.projectRoot)
.then (state) -> state.remove()
it "saves state without modification", ->
@project.saveState()
.then (state) ->
expect(state).to.deep.eq({})
it "adds property", ->
@project.saveState()
.then () => @project.saveState({ foo: 42 })
.then (state) ->
expect(state).to.deep.eq({ foo: 42 })
it "adds second property", ->
@project.saveState()
.then () => @project.saveState({ foo: 42 })
.then () => @project.saveState({ bar: true })
.then (state) ->
expect(state).to.deep.eq({ foo: 42, bar: true })
it "modifes property", ->
@project.saveState()
.then () => @project.saveState({ foo: 42 })
.then () => @project.saveState({ foo: 'modified' })
.then (state) ->
expect(state).to.deep.eq({ foo: 'modified' })
context "#getConfig", ->
integrationFolder = "foo/bar/baz"
beforeEach ->
@sandbox.stub(config, "get").withArgs(@todosPath, {foo: "bar"}).resolves({ baz: "quux", integrationFolder })
@sandbox.stub(@project, "determineIsNewProject").withArgs(integrationFolder).resolves(false)
it "calls config.get with projectRoot + options + saved state", ->
savedState(@todosPath)
.then (state) =>
@sandbox.stub(state, "get").resolves({ reporterWidth: 225 })
@project.getConfig({foo: "bar"})
.then (cfg) ->
expect(cfg).to.deep.eq({
integrationFolder
isNewProject: false
baz: "quux"
state: {
reporterWidth: 225
}
})
it "resolves if cfg is already set", ->
@project.cfg = {
integrationFolder: integrationFolder,
foo: "bar"
}
@project.getConfig()
.then (cfg) ->
expect(cfg).to.deep.eq({
integrationFolder: integrationFolder,
foo: "bar"
})
it "sets cfg.isNewProject to true when state.showedOnBoardingModal is true", ->
savedState(@todosPath)
.then (state) =>
@sandbox.stub(state, "get").resolves({ showedOnBoardingModal: true })
@project.getConfig({foo: "bar"})
.then (cfg) ->
expect(cfg).to.deep.eq({
integrationFolder
isNewProject: false
baz: "quux"
state: {
showedOnBoardingModal: true
}
})
context "#open", ->
beforeEach ->
@sandbox.stub(@project, "watchSettingsAndStartWebsockets").resolves()
@sandbox.stub(@project, "checkSupportFile").resolves()
@sandbox.stub(@project, "scaffold").resolves()
@sandbox.stub(@project, "getConfig").resolves(@config)
@sandbox.stub(Server.prototype, "open").resolves([])
@sandbox.stub(Server.prototype, "reset")
@sandbox.stub(config, "updateWithPluginValues").returns(@config)
@sandbox.stub(scaffold, "plugins").resolves()
@sandbox.stub(plugins, "init").resolves()
it "calls #watchSettingsAndStartWebsockets with options + config", ->
opts = {changeEvents: false, onAutomationRequest: ->}
@project.cfg = {}
@project.open(opts).then =>
expect(@project.watchSettingsAndStartWebsockets).to.be.calledWith(opts, @project.cfg)
it "calls #scaffold with server config promise", ->
@project.open().then =>
expect(@project.scaffold).to.be.calledWith(@config)
it "calls #checkSupportFile with server config when scaffolding is finished", ->
@project.open().then =>
expect(@project.checkSupportFile).to.be.calledWith(@config)
it "calls #getConfig options", ->
opts = {}
@project.open(opts).then =>
expect(@project.getConfig).to.be.calledWith(opts)
it "initializes the plugins", ->
@project.open({}).then =>
expect(plugins.init).to.be.called
it "calls support.plugins with pluginsFile directory", ->
@project.open({}).then =>
expect(scaffold.plugins).to.be.calledWith(path.dirname(@config.pluginsFile))
it "calls options.onError with plugins error when there is a plugins error", ->
onError = @sandbox.spy()
err = {
name: "plugin error name"
message: "plugin error message"
}
@project.open({ onError: onError }).then =>
pluginsOnError = plugins.init.lastCall.args[1].onError
expect(pluginsOnError).to.be.a("function")
pluginsOnError(err)
expect(onError).to.be.calledWith(err)
it "updates config.state when saved state changes", ->
@sandbox.spy(@project, "saveState")
options = {}
@project.open(options)
.then =>
options.onSavedStateChanged({ autoScrollingEnabled: false })
.then =>
@project.getConfig()
.then (config) =>
expect(@project.saveState).to.be.calledWith({ autoScrollingEnabled: false})
expect(config.state).to.eql({ autoScrollingEnabled: false })
it.skip "watches cypress.json", ->
@server.open().bind(@).then ->
expect(Watchers::watch).to.be.calledWith("/Users/brian/app/cypress.json")
it.skip "passes watchers to Socket.startListening", ->
options = {}
@server.open(options).then ->
startListening = Socket::startListening
expect(startListening.getCall(0).args[0]).to.be.instanceof(Watchers)
expect(startListening.getCall(0).args[1]).to.eq(options)
context "#close", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@sandbox.stub(@project, "getConfig").resolves(@config)
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-<PASSWORD>")
it "closes server", ->
@project.server = @sandbox.stub({close: ->})
@project.close().then =>
expect(@project.server.close).to.be.calledOnce
it "closes watchers", ->
@project.watchers = @sandbox.stub({close: ->})
@project.close().then =>
expect(@project.watchers.close).to.be.calledOnce
it "can close when server + watchers arent open", ->
@project.close()
context "#getRuns", ->
beforeEach ->
@project = Project(@todosPath)
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@sandbox.stub(api, "getProjectRuns").resolves('runs')
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-<PASSWORD>")
it "calls api.getProjectRuns with project id + session", ->
@project.getRuns().then (runs) ->
expect(api.getProjectRuns).to.be.calledWith("id-123", "auth-token-123")
expect(runs).to.equal("runs")
context "#scaffold", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@sandbox.stub(scaffold, "integration").resolves()
@sandbox.stub(scaffold, "fixture").resolves()
@sandbox.stub(scaffold, "support").resolves()
@sandbox.stub(scaffold, "plugins").resolves()
@obj = {projectRoot: "pr", fixturesFolder: "ff", integrationFolder: "if", supportFolder: "sf", pluginsFile: "pf/index.js"}
it "calls scaffold.integration with integrationFolder", ->
@project.scaffold(@obj).then =>
expect(scaffold.integration).to.be.calledWith(@obj.integrationFolder)
it "calls fixture.scaffold with fixturesFolder", ->
@project.scaffold(@obj).then =>
expect(scaffold.fixture).to.be.calledWith(@obj.fixturesFolder)
it "calls support.scaffold with supportFolder", ->
@project.scaffold(@obj).then =>
expect(scaffold.support).to.be.calledWith(@obj.supportFolder)
it "does not call support.plugins if config.pluginsFile is falsey", ->
@obj.pluginsFile = false
@project.scaffold(@obj).then =>
expect(scaffold.plugins).not.to.be.called
context "#watchSettings", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@project.server = {startWebsockets: ->}
@sandbox.stub(settings, "pathToCypressJson").returns("/path/to/cypress.json")
@sandbox.stub(settings, "pathToCypressEnvJson").returns("/path/to/cypress.env.json")
@watch = @sandbox.stub(@project.watchers, "watch")
it "watches cypress.json and cypress.env.json", ->
@project.watchSettingsAndStartWebsockets({onSettingsChanged: ->})
expect(@watch).to.be.calledTwice
expect(@watch).to.be.calledWith("/path/to/cypress.json")
expect(@watch).to.be.calledWith("/path/to/cypress.env.json")
it "sets onChange event when {changeEvents: true}", (done) ->
@project.watchSettingsAndStartWebsockets({onSettingsChanged: done})
## get the object passed to watchers.watch
obj = @watch.getCall(0).args[1]
expect(obj.onChange).to.be.a("function")
obj.onChange()
it "does not call watch when {changeEvents: false}", ->
@project.watchSettingsAndStartWebsockets({onSettingsChanged: undefined})
expect(@watch).not.to.be.called
it "does not call onSettingsChanged when generatedProjectIdTimestamp is less than 1 second", ->
@project.generatedProjectIdTimestamp = timestamp = new Date()
emit = @sandbox.spy(@project, "emit")
stub = @sandbox.stub()
@project.watchSettingsAndStartWebsockets({onSettingsChanged: stub})
## get the object passed to watchers.watch
obj = @watch.getCall(0).args[1]
obj.onChange()
expect(stub).not.to.be.called
## subtract 1 second from our timestamp
timestamp.setSeconds(timestamp.getSeconds() - 1)
obj.onChange()
expect(stub).to.be.calledOnce
context "#checkSupportFile", ->
beforeEach ->
@sandbox.stub(fs, "pathExists").resolves(true)
@project = Project("/_test-output/path/to/project")
@project.server = {onTestFileChange: @sandbox.spy()}
@sandbox.stub(preprocessor, "getFile").resolves()
@config = {
projectRoot: "/path/to/root/"
supportFile: "/path/to/root/foo/bar.js"
}
it "does nothing when {supportFile: false}", ->
ret = @project.checkSupportFile({supportFile: false})
expect(ret).to.be.undefined
it "throws when support file does not exist", ->
fs.pathExists.resolves(false)
@project.checkSupportFile(@config)
.catch (e) ->
expect(e.message).to.include("The support file is missing or invalid.")
context "#watchPluginsFile", ->
beforeEach ->
@sandbox.stub(fs, "pathExists").resolves(true)
@project = Project("/_test-output/path/to/project")
@project.watchers = { watch: @sandbox.spy() }
@sandbox.stub(plugins, "init").resolves()
@config = {
pluginsFile: "/path/to/plugins-file"
}
it "does nothing when {pluginsFile: false}", ->
@config.pluginsFile = false
@project.watchPluginsFile(@config).then =>
expect(@project.watchers.watch).not.to.be.called
it "does nothing if pluginsFile does not exist", ->
fs.pathExists.resolves(false)
@project.watchPluginsFile(@config).then =>
expect(@project.watchers.watch).not.to.be.called
it "watches the pluginsFile", ->
@project.watchPluginsFile(@config).then =>
expect(@project.watchers.watch).to.be.calledWith(@config.pluginsFile)
expect(@project.watchers.watch.lastCall.args[1]).to.be.an("object")
expect(@project.watchers.watch.lastCall.args[1].onChange).to.be.a("function")
it "calls plugins.init when file changes", ->
@project.watchPluginsFile(@config).then =>
@project.watchers.watch.firstCall.args[1].onChange()
expect(plugins.init).to.be.calledWith(@config)
it "handles errors from calling plugins.init", (done) ->
error = {name: "foo", message: "foo"}
plugins.init.rejects(error)
@project.watchPluginsFile(@config, {
onError: (err) ->
expect(err).to.eql(error)
done()
})
.then =>
@project.watchers.watch.firstCall.args[1].onChange()
return
context "#watchSettingsAndStartWebsockets", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@project.watchers = {}
@project.server = @sandbox.stub({startWebsockets: ->})
@sandbox.stub(@project, "watchSettings")
@sandbox.stub(Automation, "create").returns("automation")
it "calls server.startWebsockets with automation + config", ->
c = {}
@project.watchSettingsAndStartWebsockets({}, c)
expect(@project.server.startWebsockets).to.be.calledWith("automation", c)
it "passes onReloadBrowser callback", ->
fn = @sandbox.stub()
@project.server.startWebsockets.yieldsTo("onReloadBrowser")
@project.watchSettingsAndStartWebsockets({onReloadBrowser: fn}, {})
expect(fn).to.be.calledOnce
context "#getProjectId", ->
afterEach ->
delete process.env.CYPRESS_PROJECT_ID
beforeEach ->
@project = Project("/_test-output/path/to/project")
@verifyExistence = @sandbox.stub(Project.prototype, "verifyExistence").resolves()
it "resolves with process.env.CYPRESS_PROJECT_ID if set", ->
process.env.CYPRESS_PROJECT_ID = "123"
@project.getProjectId().then (id) ->
expect(id).to.eq("123")
it "calls verifyExistence", ->
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@project.getProjectId()
.then =>
expect(@verifyExistence).to.be.calledOnce
it "returns the project id from settings", ->
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@project.getProjectId()
.then (id) ->
expect(id).to.eq "id-123"
it "throws NO_PROJECT_ID with the projectRoot when no projectId was found", ->
@sandbox.stub(settings, "read").resolves({})
@project.getProjectId()
.then (id) ->
throw new Error("expected to fail, but did not")
.catch (err) ->
expect(err.type).to.eq("NO_PROJECT_ID")
expect(err.message).to.include("/_test-output/path/to/project")
it "bubbles up Settings.read errors", ->
err = new Error()
err.code = "EACCES"
@sandbox.stub(settings, "read").rejects(err)
@project.getProjectId()
.then (id) ->
throw new Error("expected to fail, but did not")
.catch (err) ->
expect(err.code).to.eq("EACCES")
context "#writeProjectId", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@sandbox.stub(settings, "write")
.withArgs(@project.projectRoot, {projectId: "id-123"})
.resolves({projectId: "id-123"})
it "calls Settings.write with projectRoot and attrs", ->
@project.writeProjectId("id-123").then (id) ->
expect(id).to.eq("id-123")
it "sets generatedProjectIdTimestamp", ->
@project.writeProjectId("id-123").then =>
expect(@project.generatedProjectIdTimestamp).to.be.a("date")
context "#ensureSpecUrl", ->
beforeEach ->
@project2 = Project(@idsPath)
settings.write(@idsPath, {port: 2020})
it "returns fully qualified url when spec exists", ->
@project2.ensureSpecUrl("cypress/integration/bar.js")
.then (str) ->
expect(str).to.eq("http://localhost:2020/__/#/tests/integration/bar.js")
it "returns fully qualified url on absolute path to spec", ->
todosSpec = path.join(@todosPath, "tests/sub/sub_test.coffee")
@project.ensureSpecUrl(todosSpec)
.then (str) ->
expect(str).to.eq("http://localhost:8888/__/#/tests/integration/sub/sub_test.coffee")
it "returns __all spec url", ->
@project.ensureSpecUrl()
.then (str) ->
expect(str).to.eq("http://localhost:8888/__/#/tests/__all")
it "returns __all spec url with spec is __all", ->
@project.ensureSpecUrl('__all')
.then (str) ->
expect(str).to.eq("http://localhost:8888/__/#/tests/__all")
it "throws when spec isnt found", ->
@project.ensureSpecUrl("does/not/exist.js")
.catch (err) ->
expect(err.type).to.eq("SPEC_FILE_NOT_FOUND")
context "#ensureSpecExists", ->
beforeEach ->
@project2 = Project(@idsPath)
it "resolves relative path to test file against projectRoot", ->
@project2.ensureSpecExists("cypress/integration/foo.coffee")
.then =>
@project.ensureSpecExists("tests/test1.js")
it "resolves + returns absolute path to test file", ->
idsSpec = path.join(@idsPath, "cypress/integration/foo.coffee")
todosSpec = path.join(@todosPath, "tests/sub/sub_test.coffee")
@project2.ensureSpecExists(idsSpec)
.then (spec1) =>
expect(spec1).to.eq(idsSpec)
@project.ensureSpecExists(todosSpec)
.then (spec2) ->
expect(spec2).to.eq(todosSpec)
it "throws SPEC_FILE_NOT_FOUND when spec does not exist", ->
@project2.ensureSpecExists("does/not/exist.js")
.catch (err) =>
expect(err.type).to.eq("SPEC_FILE_NOT_FOUND")
expect(err.message).to.include(path.join(@idsPath, "does/not/exist.js"))
context ".add", ->
beforeEach ->
@pristinePath = Fixtures.projectPath("pristine")
it "inserts path into cache", ->
Project.add(@pristinePath)
.then =>
cache.read()
.then (json) =>
expect(json.PROJECTS).to.deep.eq([@pristinePath])
describe "if project at path has id", ->
it "returns object containing path and id", ->
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
Project.add(@pristinePath)
.then (project) =>
expect(project.id).to.equal("id-123")
expect(project.path).to.equal(@pristinePath)
describe "if project at path does not have id", ->
it "returns object containing just the path", ->
@sandbox.stub(settings, "read").rejects()
Project.add(@pristinePath)
.then (project) =>
expect(project.id).to.be.undefined
expect(project.path).to.equal(@pristinePath)
context "#createCiProject", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@newProject = { id: "project-id-123" }
@sandbox.stub(@project, "writeProjectId").resolves("project-id-123")
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(commitInfo, "getRemoteOrigin").resolves("remoteOrigin")
@sandbox.stub(api, "createProject")
.withArgs({foo: "bar"}, "remoteOrigin", "auth-token-123")
.resolves(@newProject)
it "calls api.createProject with user session", ->
@project.createCiProject({foo: "bar"}).then ->
expect(api.createProject).to.be.calledWith({foo: "bar"}, "remoteOrigin", "auth-token-123")
it "calls writeProjectId with id", ->
@project.createCiProject({foo: "bar"}).then =>
expect(@project.writeProjectId).to.be.calledWith("project-id-123")
it "returns project id", ->
@project.createCiProject({foo: "bar"}).then (projectId) =>
expect(projectId).to.eql(@newProject)
context "#getRecordKeys", ->
beforeEach ->
@recordKeys = []
@project = Project(@pristinePath)
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-12<PASSWORD>")
@sandbox.stub(api, "getProjectRecordKeys").resolves(@recordKeys)
it "calls api.getProjectRecordKeys with project id + session", ->
@project.getRecordKeys().then ->
expect(api.getProjectRecordKeys).to.be.calledWith("id-123", "auth-token-123")
it "returns ci keys", ->
@project.getRecordKeys().then (recordKeys) =>
expect(recordKeys).to.equal(@recordKeys)
context "#requestAccess", ->
beforeEach ->
@project = Project(@pristinePath)
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(api, "requestAccess").resolves("response")
it "calls api.requestAccess with project id + auth token", ->
@project.requestAccess("project-id-123").then ->
expect(api.requestAccess).to.be.calledWith("project-id-123", "auth-token-123")
it "returns response", ->
@project.requestAccess("project-id-123").then (response) =>
expect(response).to.equal("response")
context ".remove", ->
beforeEach ->
@sandbox.stub(cache, "removeProject").resolves()
it "calls cache.removeProject with path", ->
Project.remove("/_test-output/path/to/project").then ->
expect(cache.removeProject).to.be.calledWith("/_test-output/path/to/project")
context ".id", ->
it "returns project id", ->
Project.id(@todosPath).then (id) =>
expect(id).to.eq(@projectId)
context ".getOrgs", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(api, "getOrgs").resolves([])
it "calls api.getOrgs", ->
Project.getOrgs().then (orgs) ->
expect(orgs).to.deep.eq([])
expect(api.getOrgs).to.be.calledOnce
expect(api.getOrgs).to.be.calledWith("auth-token-123")
context ".paths", ->
beforeEach ->
@sandbox.stub(cache, "getProjectPaths").resolves([])
it "calls cache.getProjectPaths", ->
Project.paths().then (ret) ->
expect(ret).to.deep.eq([])
expect(cache.getProjectPaths).to.be.calledOnce
context ".getPathsAndIds", ->
beforeEach ->
@sandbox.stub(cache, "getProjectPaths").resolves([
"/path/to/first"
"/path/to/second"
])
@sandbox.stub(settings, "id").resolves("id-123")
it "returns array of objects with paths and ids", ->
Project.getPathsAndIds().then (pathsAndIds) ->
expect(pathsAndIds).to.eql([
{
path: "/path/to/first"
id: "id-123"
}
{
path: "/path/to/second"
id: "id-123"
}
])
context ".getProjectStatuses", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "gets projects from api", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([])
.then ->
expect(api.getProjects).to.have.been.calledWith("auth-token-123")
it "returns array of projects", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses).to.eql([])
it "returns same number as client projects, even if there are less api projects", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([{}])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses.length).to.eql(1)
it "returns same number as client projects, even if there are more api projects", ->
@sandbox.stub(api, "getProjects").resolves([{}, {}])
Project.getProjectStatuses([{}])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses.length).to.eql(1)
it "merges in details of matching projects", ->
@sandbox.stub(api, "getProjects").resolves([
{ id: "id-123", lastBuildStatus: "passing" }
])
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
lastBuildStatus: "passing"
state: "VALID"
})
it "returns client project when it has no id", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([{ path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
path: "/_test-output/path/to/project"
state: "VALID"
})
describe "when client project has id and there is no matching user project", ->
beforeEach ->
@sandbox.stub(api, "getProjects").resolves([])
it "marks project as invalid if api 404s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 404})
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "INVALID"
})
it "marks project as unauthorized if api 403s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 403})
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "UNAUTHORIZED"
})
it "merges in project details and marks valid if somehow project exists and is authorized", ->
@sandbox.stub(api, "getProject").resolves({ id: "id-123", lastBuildStatus: "passing" })
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
lastBuildStatus: "passing"
state: "VALID"
})
it "throws error if not accounted for", ->
error = {name: "", message: ""}
@sandbox.stub(api, "getProject").rejects(error)
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then =>
throw new Error("Should throw error")
.catch (err) ->
expect(err).to.equal(error)
context ".getProjectStatus", ->
beforeEach ->
@clientProject = {
id: "id-123",
path: "/_test-output/path/to/project"
}
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "gets project from api", ->
@sandbox.stub(api, "getProject").resolves([])
Project.getProjectStatus(@clientProject)
.then ->
expect(api.getProject).to.have.been.calledWith("id-123", "auth-token-123")
it "returns project merged with details", ->
@sandbox.stub(api, "getProject").resolves({
lastBuildStatus: "passing"
})
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
lastBuildStatus: "passing"
state: "VALID"
})
it "returns project, marked as valid, if it does not have an id, without querying api", ->
@sandbox.stub(api, "getProject")
@clientProject.id = undefined
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: undefined
path: "/_test-output/path/to/project"
state: "VALID"
})
expect(api.getProject).not.to.be.called
it "marks project as invalid if api 404s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 404})
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "INVALID"
})
it "marks project as unauthorized if api 403s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 403})
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "UNAUTHORIZED"
})
it "throws error if not accounted for", ->
error = {name: "", message: ""}
@sandbox.stub(api, "getProject").rejects(error)
Project.getProjectStatus(@clientProject)
.then =>
throw new Error("Should throw error")
.catch (err) ->
expect(err).to.equal(error)
context ".removeIds", ->
beforeEach ->
@sandbox.stub(ids, "remove").resolves({})
it "calls id.remove with path to project tests", ->
p = Fixtures.projectPath("ids")
Project.removeIds(p).then ->
expect(ids.remove).to.be.calledWith(p + "/cypress/integration")
context ".getSecretKeyByPath", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "calls api.getProjectToken with id + session", ->
@sandbox.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("key-123")
Project.getSecretKeyByPath(@todosPath).then (key) ->
expect(key).to.eq("key-123")
it "throws CANNOT_FETCH_PROJECT_TOKEN on error", ->
@sandbox.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
Project.getSecretKeyByPath(@todosPath)
.then ->
throw new Error("should have caught error but did not")
.catch (err) ->
expect(err.type).to.eq("CANNOT_FETCH_PROJECT_TOKEN")
context ".generateSecretKeyByPath", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "calls api.updateProjectToken with id + session", ->
@sandbox.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("new-key-123")
Project.generateSecretKeyByPath(@todosPath).then (key) ->
expect(key).to.eq("new-key-123")
it "throws CANNOT_CREATE_PROJECT_TOKEN on error", ->
@sandbox.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
Project.generateSecretKeyByPath(@todosPath)
.then ->
throw new Error("should have caught error but did not")
.catch (err) ->
expect(err.type).to.eq("CANNOT_CREATE_PROJECT_TOKEN")
context ".findSpecs", ->
it "returns all the specs without a specPattern", ->
Project.findSpecs(@todosPath)
.then (specs = []) ->
expect(specs).to.deep.eq([
"etc/etc.js"
"sub/sub_test.coffee"
"test1.js"
"test2.coffee"
])
it "returns glob subset matching specPattern", ->
Project.findSpecs(@todosPath, "tests/*")
.then (specs = []) ->
expect(specs).to.deep.eq([
"test1.js"
"test2.coffee"
])
| true | require("../spec_helper")
path = require("path")
Promise = require("bluebird")
fs = require("fs-extra")
Fixtures = require("../support/helpers/fixtures")
ids = require("#{root}lib/ids")
api = require("#{root}lib/api")
user = require("#{root}lib/user")
cache = require("#{root}lib/cache")
errors = require("#{root}lib/errors")
config = require("#{root}lib/config")
scaffold = require("#{root}lib/scaffold")
Server = require("#{root}lib/server")
Project = require("#{root}lib/project")
Automation = require("#{root}lib/automation")
settings = require("#{root}lib/util/settings")
savedState = require("#{root}lib/saved_state")
commitInfo = require("@cypress/commit-info")
preprocessor = require("#{root}lib/plugins/preprocessor")
plugins = require("#{root}lib/plugins")
describe "lib/project", ->
beforeEach ->
Fixtures.scaffold()
@todosPath = Fixtures.projectPath("todos")
@idsPath = Fixtures.projectPath("ids")
@pristinePath = Fixtures.projectPath("pristine")
settings.read(@todosPath).then (obj = {}) =>
{@projectId} = obj
config.set({projectName: "project", projectRoot: "/foo/bar"})
.then (@config) =>
@project = Project(@todosPath)
afterEach ->
Fixtures.remove()
@project?.close()
it "requires a projectRoot", ->
fn = -> Project()
expect(fn).to.throw "Instantiating lib/project requires a projectRoot!"
it "always resolves the projectRoot to be absolute", ->
p = Project("../foo/bar")
expect(p.projectRoot).not.to.eq("../foo/bar")
expect(p.projectRoot).to.eq(path.resolve("../foo/bar"))
context "#saveState", ->
beforeEach ->
integrationFolder = "the/save/state/test"
@sandbox.stub(config, "get").withArgs(@todosPath).resolves({ integrationFolder })
@sandbox.stub(@project, "determineIsNewProject").withArgs(integrationFolder).resolves(false)
@project.cfg = { integrationFolder }
savedState(@project.projectRoot)
.then (state) -> state.remove()
afterEach ->
savedState(@project.projectRoot)
.then (state) -> state.remove()
it "saves state without modification", ->
@project.saveState()
.then (state) ->
expect(state).to.deep.eq({})
it "adds property", ->
@project.saveState()
.then () => @project.saveState({ foo: 42 })
.then (state) ->
expect(state).to.deep.eq({ foo: 42 })
it "adds second property", ->
@project.saveState()
.then () => @project.saveState({ foo: 42 })
.then () => @project.saveState({ bar: true })
.then (state) ->
expect(state).to.deep.eq({ foo: 42, bar: true })
it "modifes property", ->
@project.saveState()
.then () => @project.saveState({ foo: 42 })
.then () => @project.saveState({ foo: 'modified' })
.then (state) ->
expect(state).to.deep.eq({ foo: 'modified' })
context "#getConfig", ->
integrationFolder = "foo/bar/baz"
beforeEach ->
@sandbox.stub(config, "get").withArgs(@todosPath, {foo: "bar"}).resolves({ baz: "quux", integrationFolder })
@sandbox.stub(@project, "determineIsNewProject").withArgs(integrationFolder).resolves(false)
it "calls config.get with projectRoot + options + saved state", ->
savedState(@todosPath)
.then (state) =>
@sandbox.stub(state, "get").resolves({ reporterWidth: 225 })
@project.getConfig({foo: "bar"})
.then (cfg) ->
expect(cfg).to.deep.eq({
integrationFolder
isNewProject: false
baz: "quux"
state: {
reporterWidth: 225
}
})
it "resolves if cfg is already set", ->
@project.cfg = {
integrationFolder: integrationFolder,
foo: "bar"
}
@project.getConfig()
.then (cfg) ->
expect(cfg).to.deep.eq({
integrationFolder: integrationFolder,
foo: "bar"
})
it "sets cfg.isNewProject to true when state.showedOnBoardingModal is true", ->
savedState(@todosPath)
.then (state) =>
@sandbox.stub(state, "get").resolves({ showedOnBoardingModal: true })
@project.getConfig({foo: "bar"})
.then (cfg) ->
expect(cfg).to.deep.eq({
integrationFolder
isNewProject: false
baz: "quux"
state: {
showedOnBoardingModal: true
}
})
context "#open", ->
beforeEach ->
@sandbox.stub(@project, "watchSettingsAndStartWebsockets").resolves()
@sandbox.stub(@project, "checkSupportFile").resolves()
@sandbox.stub(@project, "scaffold").resolves()
@sandbox.stub(@project, "getConfig").resolves(@config)
@sandbox.stub(Server.prototype, "open").resolves([])
@sandbox.stub(Server.prototype, "reset")
@sandbox.stub(config, "updateWithPluginValues").returns(@config)
@sandbox.stub(scaffold, "plugins").resolves()
@sandbox.stub(plugins, "init").resolves()
it "calls #watchSettingsAndStartWebsockets with options + config", ->
opts = {changeEvents: false, onAutomationRequest: ->}
@project.cfg = {}
@project.open(opts).then =>
expect(@project.watchSettingsAndStartWebsockets).to.be.calledWith(opts, @project.cfg)
it "calls #scaffold with server config promise", ->
@project.open().then =>
expect(@project.scaffold).to.be.calledWith(@config)
it "calls #checkSupportFile with server config when scaffolding is finished", ->
@project.open().then =>
expect(@project.checkSupportFile).to.be.calledWith(@config)
it "calls #getConfig options", ->
opts = {}
@project.open(opts).then =>
expect(@project.getConfig).to.be.calledWith(opts)
it "initializes the plugins", ->
@project.open({}).then =>
expect(plugins.init).to.be.called
it "calls support.plugins with pluginsFile directory", ->
@project.open({}).then =>
expect(scaffold.plugins).to.be.calledWith(path.dirname(@config.pluginsFile))
it "calls options.onError with plugins error when there is a plugins error", ->
onError = @sandbox.spy()
err = {
name: "plugin error name"
message: "plugin error message"
}
@project.open({ onError: onError }).then =>
pluginsOnError = plugins.init.lastCall.args[1].onError
expect(pluginsOnError).to.be.a("function")
pluginsOnError(err)
expect(onError).to.be.calledWith(err)
it "updates config.state when saved state changes", ->
@sandbox.spy(@project, "saveState")
options = {}
@project.open(options)
.then =>
options.onSavedStateChanged({ autoScrollingEnabled: false })
.then =>
@project.getConfig()
.then (config) =>
expect(@project.saveState).to.be.calledWith({ autoScrollingEnabled: false})
expect(config.state).to.eql({ autoScrollingEnabled: false })
it.skip "watches cypress.json", ->
@server.open().bind(@).then ->
expect(Watchers::watch).to.be.calledWith("/Users/brian/app/cypress.json")
it.skip "passes watchers to Socket.startListening", ->
options = {}
@server.open(options).then ->
startListening = Socket::startListening
expect(startListening.getCall(0).args[0]).to.be.instanceof(Watchers)
expect(startListening.getCall(0).args[1]).to.eq(options)
context "#close", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@sandbox.stub(@project, "getConfig").resolves(@config)
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-PI:PASSWORD:<PASSWORD>END_PI")
it "closes server", ->
@project.server = @sandbox.stub({close: ->})
@project.close().then =>
expect(@project.server.close).to.be.calledOnce
it "closes watchers", ->
@project.watchers = @sandbox.stub({close: ->})
@project.close().then =>
expect(@project.watchers.close).to.be.calledOnce
it "can close when server + watchers arent open", ->
@project.close()
context "#getRuns", ->
beforeEach ->
@project = Project(@todosPath)
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@sandbox.stub(api, "getProjectRuns").resolves('runs')
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-PI:PASSWORD:<PASSWORD>END_PI")
it "calls api.getProjectRuns with project id + session", ->
@project.getRuns().then (runs) ->
expect(api.getProjectRuns).to.be.calledWith("id-123", "auth-token-123")
expect(runs).to.equal("runs")
context "#scaffold", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@sandbox.stub(scaffold, "integration").resolves()
@sandbox.stub(scaffold, "fixture").resolves()
@sandbox.stub(scaffold, "support").resolves()
@sandbox.stub(scaffold, "plugins").resolves()
@obj = {projectRoot: "pr", fixturesFolder: "ff", integrationFolder: "if", supportFolder: "sf", pluginsFile: "pf/index.js"}
it "calls scaffold.integration with integrationFolder", ->
@project.scaffold(@obj).then =>
expect(scaffold.integration).to.be.calledWith(@obj.integrationFolder)
it "calls fixture.scaffold with fixturesFolder", ->
@project.scaffold(@obj).then =>
expect(scaffold.fixture).to.be.calledWith(@obj.fixturesFolder)
it "calls support.scaffold with supportFolder", ->
@project.scaffold(@obj).then =>
expect(scaffold.support).to.be.calledWith(@obj.supportFolder)
it "does not call support.plugins if config.pluginsFile is falsey", ->
@obj.pluginsFile = false
@project.scaffold(@obj).then =>
expect(scaffold.plugins).not.to.be.called
context "#watchSettings", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@project.server = {startWebsockets: ->}
@sandbox.stub(settings, "pathToCypressJson").returns("/path/to/cypress.json")
@sandbox.stub(settings, "pathToCypressEnvJson").returns("/path/to/cypress.env.json")
@watch = @sandbox.stub(@project.watchers, "watch")
it "watches cypress.json and cypress.env.json", ->
@project.watchSettingsAndStartWebsockets({onSettingsChanged: ->})
expect(@watch).to.be.calledTwice
expect(@watch).to.be.calledWith("/path/to/cypress.json")
expect(@watch).to.be.calledWith("/path/to/cypress.env.json")
it "sets onChange event when {changeEvents: true}", (done) ->
@project.watchSettingsAndStartWebsockets({onSettingsChanged: done})
## get the object passed to watchers.watch
obj = @watch.getCall(0).args[1]
expect(obj.onChange).to.be.a("function")
obj.onChange()
it "does not call watch when {changeEvents: false}", ->
@project.watchSettingsAndStartWebsockets({onSettingsChanged: undefined})
expect(@watch).not.to.be.called
it "does not call onSettingsChanged when generatedProjectIdTimestamp is less than 1 second", ->
@project.generatedProjectIdTimestamp = timestamp = new Date()
emit = @sandbox.spy(@project, "emit")
stub = @sandbox.stub()
@project.watchSettingsAndStartWebsockets({onSettingsChanged: stub})
## get the object passed to watchers.watch
obj = @watch.getCall(0).args[1]
obj.onChange()
expect(stub).not.to.be.called
## subtract 1 second from our timestamp
timestamp.setSeconds(timestamp.getSeconds() - 1)
obj.onChange()
expect(stub).to.be.calledOnce
context "#checkSupportFile", ->
beforeEach ->
@sandbox.stub(fs, "pathExists").resolves(true)
@project = Project("/_test-output/path/to/project")
@project.server = {onTestFileChange: @sandbox.spy()}
@sandbox.stub(preprocessor, "getFile").resolves()
@config = {
projectRoot: "/path/to/root/"
supportFile: "/path/to/root/foo/bar.js"
}
it "does nothing when {supportFile: false}", ->
ret = @project.checkSupportFile({supportFile: false})
expect(ret).to.be.undefined
it "throws when support file does not exist", ->
fs.pathExists.resolves(false)
@project.checkSupportFile(@config)
.catch (e) ->
expect(e.message).to.include("The support file is missing or invalid.")
context "#watchPluginsFile", ->
beforeEach ->
@sandbox.stub(fs, "pathExists").resolves(true)
@project = Project("/_test-output/path/to/project")
@project.watchers = { watch: @sandbox.spy() }
@sandbox.stub(plugins, "init").resolves()
@config = {
pluginsFile: "/path/to/plugins-file"
}
it "does nothing when {pluginsFile: false}", ->
@config.pluginsFile = false
@project.watchPluginsFile(@config).then =>
expect(@project.watchers.watch).not.to.be.called
it "does nothing if pluginsFile does not exist", ->
fs.pathExists.resolves(false)
@project.watchPluginsFile(@config).then =>
expect(@project.watchers.watch).not.to.be.called
it "watches the pluginsFile", ->
@project.watchPluginsFile(@config).then =>
expect(@project.watchers.watch).to.be.calledWith(@config.pluginsFile)
expect(@project.watchers.watch.lastCall.args[1]).to.be.an("object")
expect(@project.watchers.watch.lastCall.args[1].onChange).to.be.a("function")
it "calls plugins.init when file changes", ->
@project.watchPluginsFile(@config).then =>
@project.watchers.watch.firstCall.args[1].onChange()
expect(plugins.init).to.be.calledWith(@config)
it "handles errors from calling plugins.init", (done) ->
error = {name: "foo", message: "foo"}
plugins.init.rejects(error)
@project.watchPluginsFile(@config, {
onError: (err) ->
expect(err).to.eql(error)
done()
})
.then =>
@project.watchers.watch.firstCall.args[1].onChange()
return
context "#watchSettingsAndStartWebsockets", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@project.watchers = {}
@project.server = @sandbox.stub({startWebsockets: ->})
@sandbox.stub(@project, "watchSettings")
@sandbox.stub(Automation, "create").returns("automation")
it "calls server.startWebsockets with automation + config", ->
c = {}
@project.watchSettingsAndStartWebsockets({}, c)
expect(@project.server.startWebsockets).to.be.calledWith("automation", c)
it "passes onReloadBrowser callback", ->
fn = @sandbox.stub()
@project.server.startWebsockets.yieldsTo("onReloadBrowser")
@project.watchSettingsAndStartWebsockets({onReloadBrowser: fn}, {})
expect(fn).to.be.calledOnce
context "#getProjectId", ->
afterEach ->
delete process.env.CYPRESS_PROJECT_ID
beforeEach ->
@project = Project("/_test-output/path/to/project")
@verifyExistence = @sandbox.stub(Project.prototype, "verifyExistence").resolves()
it "resolves with process.env.CYPRESS_PROJECT_ID if set", ->
process.env.CYPRESS_PROJECT_ID = "123"
@project.getProjectId().then (id) ->
expect(id).to.eq("123")
it "calls verifyExistence", ->
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@project.getProjectId()
.then =>
expect(@verifyExistence).to.be.calledOnce
it "returns the project id from settings", ->
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@project.getProjectId()
.then (id) ->
expect(id).to.eq "id-123"
it "throws NO_PROJECT_ID with the projectRoot when no projectId was found", ->
@sandbox.stub(settings, "read").resolves({})
@project.getProjectId()
.then (id) ->
throw new Error("expected to fail, but did not")
.catch (err) ->
expect(err.type).to.eq("NO_PROJECT_ID")
expect(err.message).to.include("/_test-output/path/to/project")
it "bubbles up Settings.read errors", ->
err = new Error()
err.code = "EACCES"
@sandbox.stub(settings, "read").rejects(err)
@project.getProjectId()
.then (id) ->
throw new Error("expected to fail, but did not")
.catch (err) ->
expect(err.code).to.eq("EACCES")
context "#writeProjectId", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@sandbox.stub(settings, "write")
.withArgs(@project.projectRoot, {projectId: "id-123"})
.resolves({projectId: "id-123"})
it "calls Settings.write with projectRoot and attrs", ->
@project.writeProjectId("id-123").then (id) ->
expect(id).to.eq("id-123")
it "sets generatedProjectIdTimestamp", ->
@project.writeProjectId("id-123").then =>
expect(@project.generatedProjectIdTimestamp).to.be.a("date")
context "#ensureSpecUrl", ->
beforeEach ->
@project2 = Project(@idsPath)
settings.write(@idsPath, {port: 2020})
it "returns fully qualified url when spec exists", ->
@project2.ensureSpecUrl("cypress/integration/bar.js")
.then (str) ->
expect(str).to.eq("http://localhost:2020/__/#/tests/integration/bar.js")
it "returns fully qualified url on absolute path to spec", ->
todosSpec = path.join(@todosPath, "tests/sub/sub_test.coffee")
@project.ensureSpecUrl(todosSpec)
.then (str) ->
expect(str).to.eq("http://localhost:8888/__/#/tests/integration/sub/sub_test.coffee")
it "returns __all spec url", ->
@project.ensureSpecUrl()
.then (str) ->
expect(str).to.eq("http://localhost:8888/__/#/tests/__all")
it "returns __all spec url with spec is __all", ->
@project.ensureSpecUrl('__all')
.then (str) ->
expect(str).to.eq("http://localhost:8888/__/#/tests/__all")
it "throws when spec isnt found", ->
@project.ensureSpecUrl("does/not/exist.js")
.catch (err) ->
expect(err.type).to.eq("SPEC_FILE_NOT_FOUND")
context "#ensureSpecExists", ->
beforeEach ->
@project2 = Project(@idsPath)
it "resolves relative path to test file against projectRoot", ->
@project2.ensureSpecExists("cypress/integration/foo.coffee")
.then =>
@project.ensureSpecExists("tests/test1.js")
it "resolves + returns absolute path to test file", ->
idsSpec = path.join(@idsPath, "cypress/integration/foo.coffee")
todosSpec = path.join(@todosPath, "tests/sub/sub_test.coffee")
@project2.ensureSpecExists(idsSpec)
.then (spec1) =>
expect(spec1).to.eq(idsSpec)
@project.ensureSpecExists(todosSpec)
.then (spec2) ->
expect(spec2).to.eq(todosSpec)
it "throws SPEC_FILE_NOT_FOUND when spec does not exist", ->
@project2.ensureSpecExists("does/not/exist.js")
.catch (err) =>
expect(err.type).to.eq("SPEC_FILE_NOT_FOUND")
expect(err.message).to.include(path.join(@idsPath, "does/not/exist.js"))
context ".add", ->
beforeEach ->
@pristinePath = Fixtures.projectPath("pristine")
it "inserts path into cache", ->
Project.add(@pristinePath)
.then =>
cache.read()
.then (json) =>
expect(json.PROJECTS).to.deep.eq([@pristinePath])
describe "if project at path has id", ->
it "returns object containing path and id", ->
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
Project.add(@pristinePath)
.then (project) =>
expect(project.id).to.equal("id-123")
expect(project.path).to.equal(@pristinePath)
describe "if project at path does not have id", ->
it "returns object containing just the path", ->
@sandbox.stub(settings, "read").rejects()
Project.add(@pristinePath)
.then (project) =>
expect(project.id).to.be.undefined
expect(project.path).to.equal(@pristinePath)
context "#createCiProject", ->
beforeEach ->
@project = Project("/_test-output/path/to/project")
@newProject = { id: "project-id-123" }
@sandbox.stub(@project, "writeProjectId").resolves("project-id-123")
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(commitInfo, "getRemoteOrigin").resolves("remoteOrigin")
@sandbox.stub(api, "createProject")
.withArgs({foo: "bar"}, "remoteOrigin", "auth-token-123")
.resolves(@newProject)
it "calls api.createProject with user session", ->
@project.createCiProject({foo: "bar"}).then ->
expect(api.createProject).to.be.calledWith({foo: "bar"}, "remoteOrigin", "auth-token-123")
it "calls writeProjectId with id", ->
@project.createCiProject({foo: "bar"}).then =>
expect(@project.writeProjectId).to.be.calledWith("project-id-123")
it "returns project id", ->
@project.createCiProject({foo: "bar"}).then (projectId) =>
expect(projectId).to.eql(@newProject)
context "#getRecordKeys", ->
beforeEach ->
@recordKeys = []
@project = Project(@pristinePath)
@sandbox.stub(settings, "read").resolves({projectId: "id-123"})
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-12PI:PASSWORD:<PASSWORD>END_PI")
@sandbox.stub(api, "getProjectRecordKeys").resolves(@recordKeys)
it "calls api.getProjectRecordKeys with project id + session", ->
@project.getRecordKeys().then ->
expect(api.getProjectRecordKeys).to.be.calledWith("id-123", "auth-token-123")
it "returns ci keys", ->
@project.getRecordKeys().then (recordKeys) =>
expect(recordKeys).to.equal(@recordKeys)
context "#requestAccess", ->
beforeEach ->
@project = Project(@pristinePath)
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(api, "requestAccess").resolves("response")
it "calls api.requestAccess with project id + auth token", ->
@project.requestAccess("project-id-123").then ->
expect(api.requestAccess).to.be.calledWith("project-id-123", "auth-token-123")
it "returns response", ->
@project.requestAccess("project-id-123").then (response) =>
expect(response).to.equal("response")
context ".remove", ->
beforeEach ->
@sandbox.stub(cache, "removeProject").resolves()
it "calls cache.removeProject with path", ->
Project.remove("/_test-output/path/to/project").then ->
expect(cache.removeProject).to.be.calledWith("/_test-output/path/to/project")
context ".id", ->
it "returns project id", ->
Project.id(@todosPath).then (id) =>
expect(id).to.eq(@projectId)
context ".getOrgs", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
@sandbox.stub(api, "getOrgs").resolves([])
it "calls api.getOrgs", ->
Project.getOrgs().then (orgs) ->
expect(orgs).to.deep.eq([])
expect(api.getOrgs).to.be.calledOnce
expect(api.getOrgs).to.be.calledWith("auth-token-123")
context ".paths", ->
beforeEach ->
@sandbox.stub(cache, "getProjectPaths").resolves([])
it "calls cache.getProjectPaths", ->
Project.paths().then (ret) ->
expect(ret).to.deep.eq([])
expect(cache.getProjectPaths).to.be.calledOnce
context ".getPathsAndIds", ->
beforeEach ->
@sandbox.stub(cache, "getProjectPaths").resolves([
"/path/to/first"
"/path/to/second"
])
@sandbox.stub(settings, "id").resolves("id-123")
it "returns array of objects with paths and ids", ->
Project.getPathsAndIds().then (pathsAndIds) ->
expect(pathsAndIds).to.eql([
{
path: "/path/to/first"
id: "id-123"
}
{
path: "/path/to/second"
id: "id-123"
}
])
context ".getProjectStatuses", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "gets projects from api", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([])
.then ->
expect(api.getProjects).to.have.been.calledWith("auth-token-123")
it "returns array of projects", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses).to.eql([])
it "returns same number as client projects, even if there are less api projects", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([{}])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses.length).to.eql(1)
it "returns same number as client projects, even if there are more api projects", ->
@sandbox.stub(api, "getProjects").resolves([{}, {}])
Project.getProjectStatuses([{}])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses.length).to.eql(1)
it "merges in details of matching projects", ->
@sandbox.stub(api, "getProjects").resolves([
{ id: "id-123", lastBuildStatus: "passing" }
])
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
lastBuildStatus: "passing"
state: "VALID"
})
it "returns client project when it has no id", ->
@sandbox.stub(api, "getProjects").resolves([])
Project.getProjectStatuses([{ path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
path: "/_test-output/path/to/project"
state: "VALID"
})
describe "when client project has id and there is no matching user project", ->
beforeEach ->
@sandbox.stub(api, "getProjects").resolves([])
it "marks project as invalid if api 404s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 404})
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "INVALID"
})
it "marks project as unauthorized if api 403s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 403})
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "UNAUTHORIZED"
})
it "merges in project details and marks valid if somehow project exists and is authorized", ->
@sandbox.stub(api, "getProject").resolves({ id: "id-123", lastBuildStatus: "passing" })
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then (projectsWithStatuses) =>
expect(projectsWithStatuses[0]).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
lastBuildStatus: "passing"
state: "VALID"
})
it "throws error if not accounted for", ->
error = {name: "", message: ""}
@sandbox.stub(api, "getProject").rejects(error)
Project.getProjectStatuses([{ id: "id-123", path: "/_test-output/path/to/project" }])
.then =>
throw new Error("Should throw error")
.catch (err) ->
expect(err).to.equal(error)
context ".getProjectStatus", ->
beforeEach ->
@clientProject = {
id: "id-123",
path: "/_test-output/path/to/project"
}
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "gets project from api", ->
@sandbox.stub(api, "getProject").resolves([])
Project.getProjectStatus(@clientProject)
.then ->
expect(api.getProject).to.have.been.calledWith("id-123", "auth-token-123")
it "returns project merged with details", ->
@sandbox.stub(api, "getProject").resolves({
lastBuildStatus: "passing"
})
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
lastBuildStatus: "passing"
state: "VALID"
})
it "returns project, marked as valid, if it does not have an id, without querying api", ->
@sandbox.stub(api, "getProject")
@clientProject.id = undefined
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: undefined
path: "/_test-output/path/to/project"
state: "VALID"
})
expect(api.getProject).not.to.be.called
it "marks project as invalid if api 404s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 404})
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "INVALID"
})
it "marks project as unauthorized if api 403s", ->
@sandbox.stub(api, "getProject").rejects({name: "", message: "", statusCode: 403})
Project.getProjectStatus(@clientProject)
.then (project) =>
expect(project).to.eql({
id: "id-123"
path: "/_test-output/path/to/project"
state: "UNAUTHORIZED"
})
it "throws error if not accounted for", ->
error = {name: "", message: ""}
@sandbox.stub(api, "getProject").rejects(error)
Project.getProjectStatus(@clientProject)
.then =>
throw new Error("Should throw error")
.catch (err) ->
expect(err).to.equal(error)
context ".removeIds", ->
beforeEach ->
@sandbox.stub(ids, "remove").resolves({})
it "calls id.remove with path to project tests", ->
p = Fixtures.projectPath("ids")
Project.removeIds(p).then ->
expect(ids.remove).to.be.calledWith(p + "/cypress/integration")
context ".getSecretKeyByPath", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "calls api.getProjectToken with id + session", ->
@sandbox.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("key-123")
Project.getSecretKeyByPath(@todosPath).then (key) ->
expect(key).to.eq("key-123")
it "throws CANNOT_FETCH_PROJECT_TOKEN on error", ->
@sandbox.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
Project.getSecretKeyByPath(@todosPath)
.then ->
throw new Error("should have caught error but did not")
.catch (err) ->
expect(err.type).to.eq("CANNOT_FETCH_PROJECT_TOKEN")
context ".generateSecretKeyByPath", ->
beforeEach ->
@sandbox.stub(user, "ensureAuthToken").resolves("auth-token-123")
it "calls api.updateProjectToken with id + session", ->
@sandbox.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("new-key-123")
Project.generateSecretKeyByPath(@todosPath).then (key) ->
expect(key).to.eq("new-key-123")
it "throws CANNOT_CREATE_PROJECT_TOKEN on error", ->
@sandbox.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
Project.generateSecretKeyByPath(@todosPath)
.then ->
throw new Error("should have caught error but did not")
.catch (err) ->
expect(err.type).to.eq("CANNOT_CREATE_PROJECT_TOKEN")
context ".findSpecs", ->
it "returns all the specs without a specPattern", ->
Project.findSpecs(@todosPath)
.then (specs = []) ->
expect(specs).to.deep.eq([
"etc/etc.js"
"sub/sub_test.coffee"
"test1.js"
"test2.coffee"
])
it "returns glob subset matching specPattern", ->
Project.findSpecs(@todosPath, "tests/*")
.then (specs = []) ->
expect(specs).to.deep.eq([
"test1.js"
"test2.coffee"
])
|
[
{
"context": "tus: Dropzone.ADDED\n accepted: true\n name: \"test file name\"\n size: 123456\n type: \"text/html\"",
"end": 121,
"score": 0.8960472345352173,
"start": 117,
"tag": "NAME",
"value": "test"
},
{
"context": "zone.ADDED\n accepted: true\n name: \"test file name\"\n size: 123456\n type: \"text/html\"\n\n\n xhr =",
"end": 131,
"score": 0.8072825074195862,
"start": 127,
"tag": "NAME",
"value": "name"
},
{
"context": " beforeEach ->\n file =\n name: \"test name\"\n size: 2 * 1024 * 1024\n dropzone",
"end": 19684,
"score": 0.9906534552574158,
"start": 19675,
"tag": "NAME",
"value": "test name"
},
{
"context": "e = false\n dropzone.options.paramName = \"myName\"\n\n formData = [ ]\n sendingC",
"end": 53799,
"score": 0.7721171379089355,
"start": 53797,
"tag": "NAME",
"value": "my"
},
{
"context": " formData[0].append.args[0][0].should.eql \"myName\"\n\n done()\n , 10\n\n\n it ",
"end": 54500,
"score": 0.7175313234329224,
"start": 54494,
"tag": "NAME",
"value": "myName"
},
{
"context": "ple = yes\n dropzone.options.paramName = \"myName\"\n\n formData = null\n sendingMult",
"end": 54740,
"score": 0.7810537815093994,
"start": 54734,
"tag": "NAME",
"value": "myName"
},
{
"context": "ck3.status = Dropzone.ADDED\n mock1.name = \"mock1\"\n mock2.name = \"mock2\"\n mock3.name ",
"end": 56862,
"score": 0.8597497940063477,
"start": 56857,
"tag": "USERNAME",
"value": "mock1"
},
{
"context": " mock1.name = \"mock1\"\n mock2.name = \"mock2\"\n mock3.name = \"mock3\"\n\n\n dropzone.",
"end": 56891,
"score": 0.8155200481414795,
"start": 56886,
"tag": "USERNAME",
"value": "mock2"
},
{
"context": " mock2.name = \"mock2\"\n mock3.name = \"mock3\"\n\n\n dropzone.uploadFiles = (files) ->\n ",
"end": 56920,
"score": 0.738025963306427,
"start": 56915,
"tag": "USERNAME",
"value": "mock3"
}
] | test/test.coffee | notthetup/dropzone | 1 | chai.should()
describe "Dropzone", ->
getMockFile = ->
status: Dropzone.ADDED
accepted: true
name: "test file name"
size: 123456
type: "text/html"
xhr = null
beforeEach -> xhr = sinon.useFakeXMLHttpRequest()
describe "static functions", ->
describe "Dropzone.createElement()", ->
element = Dropzone.createElement """<div class="test"><span>Hallo</span></div>"""
it "should properly create an element from a string", ->
element.tagName.should.equal "DIV"
it "should properly add the correct class", ->
element.classList.contains("test").should.be.ok
it "should properly create child elements", ->
element.querySelector("span").tagName.should.equal "SPAN"
it "should always return only one element", ->
element = Dropzone.createElement """<div></div><span></span>"""
element.tagName.should.equal "DIV"
describe "Dropzone.elementInside()", ->
element = Dropzone.createElement """<div id="test"><div class="child1"><div class="child2"></div></div></div>"""
document.body.appendChild element
child1 = element.querySelector ".child1"
child2 = element.querySelector ".child2"
after -> document.body.removeChild element
it "should return yes if elements are the same", ->
Dropzone.elementInside(element, element).should.be.ok
it "should return yes if element is direct child", ->
Dropzone.elementInside(child1, element).should.be.ok
it "should return yes if element is some child", ->
Dropzone.elementInside(child2, element).should.be.ok
Dropzone.elementInside(child2, document.body).should.be.ok
it "should return no unless element is some child", ->
Dropzone.elementInside(element, child1).should.not.be.ok
Dropzone.elementInside(document.body, child1).should.not.be.ok
describe "Dropzone.optionsForElement()", ->
testOptions =
url: "/some/url"
method: "put"
before -> Dropzone.options.testElement = testOptions
after -> delete Dropzone.options.testElement
element = document.createElement "div"
it "should take options set in Dropzone.options from camelized id", ->
element.id = "test-element"
Dropzone.optionsForElement(element).should.equal testOptions
it "should return undefined if no options set", ->
element.id = "test-element2"
expect(Dropzone.optionsForElement(element)).to.equal undefined
it "should return undefined and not throw if it's a form with an input element of the name 'id'", ->
element = Dropzone.createElement """<form><input name="id" /</form>"""
expect(Dropzone.optionsForElement(element)).to.equal undefined
it "should ignore input fields with the name='id'", ->
element = Dropzone.createElement """<form id="test-element"><input type="hidden" name="id" value="fooo" /></form>"""
Dropzone.optionsForElement(element).should.equal testOptions
describe "Dropzone.forElement()", ->
element = document.createElement "div"
element.id = "some-test-element"
dropzone = null
before ->
document.body.appendChild element
dropzone = new Dropzone element, url: "/test"
after ->
dropzone.disable()
document.body.removeChild element
it "should throw an exception if no dropzone attached", ->
expect(-> Dropzone.forElement document.createElement "div").to.throw "No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."
it "should accept css selectors", ->
expect(Dropzone.forElement "#some-test-element").to.equal dropzone
it "should accept native elements", ->
expect(Dropzone.forElement element).to.equal dropzone
describe "Dropzone.discover()", ->
element1 = document.createElement "div"
element1.className = "dropzone"
element2 = element1.cloneNode()
element3 = element1.cloneNode()
element1.id = "test-element-1"
element2.id = "test-element-2"
element3.id = "test-element-3"
describe "specific options", ->
before ->
Dropzone.options.testElement1 = url: "test-url"
Dropzone.options.testElement2 = false # Disabled
document.body.appendChild element1
document.body.appendChild element2
Dropzone.discover()
after ->
document.body.removeChild element1
document.body.removeChild element2
it "should find elements with a .dropzone class", ->
element1.dropzone.should.be.ok
it "should not create dropzones with disabled options", ->
expect(element2.dropzone).to.not.be.ok
describe "Dropzone.autoDiscover", ->
before ->
Dropzone.options.testElement3 = url: "test-url"
document.body.appendChild element3
after ->
document.body.removeChild element3
it "should create dropzones even if Dropzone.autoDiscover == false", ->
# Because the check is in the actual contentLoaded function.
Dropzone.autoDiscover = off
Dropzone.discover()
expect(element3.dropzone).to.be.ok
it "should not automatically be called if Dropzone.autoDiscover == false", ->
Dropzone.autoDiscover = off
Dropzone.discover = -> expect(false).to.be.ok
Dropzone._autoDiscoverFunction()
describe "Dropzone.isValidFile()", ->
it "should return true if called without acceptedFiles", ->
Dropzone.isValidFile({ type: "some/type" }, null).should.be.ok
it "should properly validate if called with concrete mime types", ->
acceptedMimeTypes = "text/html,image/jpeg,application/json"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with base mime types", ->
acceptedMimeTypes = "text/*,image/*,application/*"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with mixed mime types", ->
acceptedMimeTypes = "text/*,image/jpeg,application/*"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok
Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok
it "should properly validate even with spaces in between", ->
acceptedMimeTypes = "text/html , image/jpeg, application/json"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
it "should properly validate extensions", ->
acceptedMimeTypes = "text/html , image/jpeg, .pdf ,.png"
Dropzone.isValidFile({ name: "somxsfsd", type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ name: "somesdfsdf", type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ name: "somesdfadfadf", type: "application/json" }, acceptedMimeTypes).should.not.be.ok
Dropzone.isValidFile({ name: "some-file file.pdf", type: "random/type" }, acceptedMimeTypes).should.be.ok
# .pdf has to be in the end
Dropzone.isValidFile({ name: "some-file.pdf file.gif", type: "random/type" }, acceptedMimeTypes).should.not.be.ok
Dropzone.isValidFile({ name: "some-file file.png", type: "random/type" }, acceptedMimeTypes).should.be.ok
describe "Dropzone.confirm", ->
beforeEach -> sinon.stub window, "confirm"
afterEach -> window.confirm.restore()
it "should forward to window.confirm and call the callbacks accordingly", ->
accepted = rejected = no
window.confirm.returns yes
Dropzone.confirm "test question", (-> accepted = yes), (-> rejected = yes)
window.confirm.args[0][0].should.equal "test question"
accepted.should.equal yes
rejected.should.equal no
accepted = rejected = no
window.confirm.returns no
Dropzone.confirm "test question 2", (-> accepted = yes), (-> rejected = yes)
window.confirm.args[1][0].should.equal "test question 2"
accepted.should.equal no
rejected.should.equal yes
it "should not error if rejected is not provided", ->
accepted = rejected = no
window.confirm.returns no
Dropzone.confirm "test question", (-> accepted = yes)
window.confirm.args[0][0].should.equal "test question"
# Nothing should have changed since there is no rejected function.
accepted.should.equal no
rejected.should.equal no
describe "Dropzone.getElement() / getElements()", ->
tmpElements = [ ]
beforeEach ->
tmpElements = [ ]
tmpElements.push Dropzone.createElement """<div class="tmptest"></div>"""
tmpElements.push Dropzone.createElement """<div id="tmptest1" class="random"></div>"""
tmpElements.push Dropzone.createElement """<div class="random div"></div>"""
tmpElements.forEach (el) -> document.body.appendChild el
afterEach ->
tmpElements.forEach (el) -> document.body.removeChild el
describe ".getElement()", ->
it "should accept a string", ->
el = Dropzone.getElement ".tmptest"
el.should.equal tmpElements[0]
el = Dropzone.getElement "#tmptest1"
el.should.equal tmpElements[1]
it "should accept a node", ->
el = Dropzone.getElement tmpElements[2]
el.should.equal tmpElements[2]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element."
expect(-> Dropzone.getElement "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElement { "lblasdlfsfl" }, "clickable").to.throw errorMessage
expect(-> Dropzone.getElement [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe ".getElements()", ->
it "should accept a list of strings", ->
els = Dropzone.getElements [ ".tmptest", "#tmptest1" ]
els.should.eql [ tmpElements[0], tmpElements[1] ]
it "should accept a list of nodes", ->
els = Dropzone.getElements [ tmpElements[0], tmpElements[2] ]
els.should.eql [ tmpElements[0], tmpElements[2] ]
it "should accept a mixed list", ->
els = Dropzone.getElements [ "#tmptest1", tmpElements[2] ]
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a string selector", ->
els = Dropzone.getElements ".random"
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a single node", ->
els = Dropzone.getElements tmpElements[1]
els.should.eql [ tmpElements[1] ]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
expect(-> Dropzone.getElements "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElements [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe "constructor()", ->
dropzone = null
afterEach -> dropzone.destroy() if dropzone?
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone "#invalid-element").to.throw "Invalid dropzone element."
it "should throw an exception if assigned twice to the same element", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
expect(-> new Dropzone element, url: "url").to.throw "Dropzone already attached."
it "should throw an exception if both acceptedFiles and acceptedMimeTypes are specified", ->
element = document.createElement "div"
expect(-> dropzone = new Dropzone element, url: "test", acceptedFiles: "param", acceptedMimeTypes: "types").to.throw "You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."
it "should set itself as element.dropzone", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
element.dropzone.should.equal dropzone
it "should add itself to Dropzone.instances", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
Dropzone.instances[Dropzone.instances.length - 1].should.equal dropzone
it "should use the action attribute not the element with the name action", ->
element = Dropzone.createElement """<form action="real-action"><input type="hidden" name="action" value="wrong-action" /></form>"""
dropzone = new Dropzone element
dropzone.options.url.should.equal "real-action"
describe "options", ->
element = null
element2 = null
beforeEach ->
element = document.createElement "div"
element.id = "test-element"
element2 = document.createElement "div"
element2.id = "test-element2"
Dropzone.options.testElement = url: "/some/url", parallelUploads: 10
afterEach -> delete Dropzone.options.testElement
it "should take the options set in Dropzone.options", ->
dropzone = new Dropzone element
dropzone.options.url.should.equal "/some/url"
dropzone.options.parallelUploads.should.equal 10
it "should prefer passed options over Dropzone.options", ->
dropzone = new Dropzone element, url: "/some/other/url"
dropzone.options.url.should.equal "/some/other/url"
it "should take the default options if nothing set in Dropzone.options", ->
dropzone = new Dropzone element2, url: "/some/url"
dropzone.options.parallelUploads.should.equal 2
it "should call the fallback function if forceFallback == true", (done) ->
dropzone = new Dropzone element,
url: "/some/other/url"
forceFallback: on
fallback: -> done()
it "should set acceptedFiles if deprecated acceptedMimetypes option has been passed", ->
dropzone = new Dropzone element,
url: "/some/other/url"
acceptedMimeTypes: "my/type"
dropzone.options.acceptedFiles.should.equal "my/type"
describe "options.clickable", ->
clickableElement = null
dropzone = null
beforeEach ->
clickableElement = document.createElement "div"
clickableElement.className = "some-clickable"
document.body.appendChild clickableElement
afterEach ->
document.body.removeChild clickableElement
dropzone.destroy if dropzone?
it "should use the default element if clickable == true", ->
dropzone = new Dropzone element, clickable: yes
dropzone.clickableElements.should.eql [ dropzone.element ]
it "should lookup the element if clickable is a CSS selector", ->
dropzone = new Dropzone element, clickable: ".some-clickable"
dropzone.clickableElements.should.eql [ clickableElement ]
it "should simply use the provided element", ->
dropzone = new Dropzone element, clickable: clickableElement
dropzone.clickableElements.should.eql [ clickableElement ]
it "should accept multiple clickable elements", ->
dropzone = new Dropzone element, clickable: [ document.body, ".some-clickable" ]
dropzone.clickableElements.should.eql [ document.body, clickableElement ]
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone element, clickable: ".some-invalid-clickable").to.throw "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
describe "init()", ->
describe "clickable", ->
dropzones =
"using acceptedFiles": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptedFiles: "audio/*,video/*" })
"using acceptedMimeTypes": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptedMimeTypes: "audio/*,video/*" })
it "should not add an accept attribute if no acceptParameter", ->
dropzone = new Dropzone (Dropzone.createElement """<form action="/"></form>"""), clickable: yes, acceptParameter: null, acceptedMimeTypes: null
dropzone.hiddenFileInput.hasAttribute("accept").should.be.false
for name, dropzone of dropzones
describe name, ->
do (dropzone) ->
it "should create a hidden file input if clickable", ->
dropzone.hiddenFileInput.should.be.ok
dropzone.hiddenFileInput.tagName.should.equal "INPUT"
it "should use the acceptParameter", ->
dropzone.hiddenFileInput.getAttribute("accept").should.equal "audio/*,video/*"
it "should create a new input element when something is selected to reset the input field", ->
for i in [0..3]
hiddenFileInput = dropzone.hiddenFileInput
event = document.createEvent "HTMLEvents"
event.initEvent "change", true, true
hiddenFileInput.dispatchEvent event
dropzone.hiddenFileInput.should.not.equal hiddenFileInput
Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok
it "should create a .dz-message element", ->
element = Dropzone.createElement """<form class="dropzone" action="/"></form>"""
dropzone = new Dropzone element, clickable: yes, acceptParameter: null, acceptedMimeTypes: null
element.querySelector(".dz-message").should.be.instanceof Element
it "should not create a .dz-message element if there already is one", ->
element = Dropzone.createElement """<form class="dropzone" action="/"></form>"""
msg = Dropzone.createElement """<div class="dz-message">TEST</div>"""
element.appendChild msg
dropzone = new Dropzone element, clickable: yes, acceptParameter: null, acceptedMimeTypes: null
element.querySelector(".dz-message").should.equal msg
element.querySelectorAll(".dz-message").length.should.equal 1
describe "options", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", maxFiles: 3
describe "file specific", ->
file = null
beforeEach ->
file =
name: "test name"
size: 2 * 1024 * 1024
dropzone.options.addedfile.call dropzone, file
describe ".addedFile()", ->
it "should properly create the previewElement", ->
file.previewElement.should.be.instanceof Element
file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql "test name"
file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql "<strong>2</strong> MiB"
describe ".error()", ->
it "should properly insert the error", ->
dropzone.options.error.call dropzone, file, "test message"
file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql "test message"
it "should properly insert the error when provided with an object containing the error", ->
dropzone.options.error.call dropzone, file, error: "test message"
file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql "test message"
describe ".thumbnail()", ->
it "should properly insert the error", ->
transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
dropzone.options.thumbnail.call dropzone, file, transparentGif
thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]")
thumbnail.src.should.eql transparentGif
thumbnail.alt.should.eql "test name"
describe ".uploadprogress()", ->
it "should properly set the width", ->
dropzone.options.uploadprogress.call dropzone, file, 0
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "0%"
dropzone.options.uploadprogress.call dropzone, file, 80
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "80%"
dropzone.options.uploadprogress.call dropzone, file, 90
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "90%"
dropzone.options.uploadprogress.call dropzone, file, 100
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "100%"
describe "instance", ->
element = null
dropzone = null
requests = null
beforeEach ->
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
element = Dropzone.createElement """<div></div>"""
document.body.appendChild element
dropzone = new Dropzone element, maxFilesize: 4, maxFiles: 100, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: ->
afterEach ->
document.body.removeChild element
dropzone.destroy()
xhr.restore()
describe ".accept()", ->
it "should pass if the filesize is OK", ->
dropzone.accept { size: 2 * 1024 * 1024, type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
it "shouldn't pass if the filesize is too big", ->
dropzone.accept { size: 10 * 1024 * 1024, type: "audio/mp3" }, (err) -> err.should.eql "File is too big (10MiB). Max filesize: 4MiB."
it "should properly accept files which mime types are listed in acceptedFiles", ->
dropzone.accept { type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "image/png" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "audio/wav" }, (err) -> expect(err).to.be.undefined
it "should properly reject files when the mime type isn't listed in acceptedFiles", ->
dropzone.accept { type: "image/jpeg" }, (err) -> err.should.eql "You can't upload files of this type."
it "should fail if maxFiles has been exceeded and call the event maxfilesexceeded", ->
sinon.stub dropzone, "getAcceptedFiles"
file = { type: "audio/mp3" }
dropzone.getAcceptedFiles.returns { length: 99 }
dropzone.options.dictMaxFilesExceeded = "You can only upload {{maxFiles}} files."
called = no
dropzone.on "maxfilesexceeded", (lfile) ->
lfile.should.equal file
called = yes
dropzone.accept file, (err) -> expect(err).to.be.undefined
called.should.not.be.ok
dropzone.getAcceptedFiles.returns { length: 100 }
dropzone.accept file, (err) -> expect(err).to.equal "You can only upload 100 files."
called.should.be.ok
dropzone.getAcceptedFiles.restore()
it "should properly handle if maxFiles is 0", ->
file = { type: "audio/mp3" }
dropzone.options.maxFiles = 0
called = no
dropzone.on "maxfilesexceeded", (lfile) ->
lfile.should.equal file
called = yes
dropzone.accept file, (err) -> expect(err).to.equal "You can not upload any more files."
called.should.be.ok
describe ".removeFile()", ->
it "should abort uploading if file is currently being uploaded", (done) ->
mockFile = getMockFile()
dropzone.uploadFile = (file) ->
dropzone.accept = (file, done) -> done()
sinon.stub dropzone, "cancelUpload"
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.getUploadingFiles()[0].should.equal mockFile
dropzone.cancelUpload.callCount.should.equal 0
dropzone.removeFile mockFile
dropzone.cancelUpload.callCount.should.equal 1
done()
, 10
describe ".cancelUpload()", ->
it "should properly cancel upload if file currently uploading", (done) ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.getUploadingFiles()[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.getUploadingFiles().length.should.equal 0
dropzone.getQueuedFiles().length.should.equal 0
done()
, 10
it "should properly cancel the upload if file is not yet uploading", ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.parallelUploads = 0
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.QUEUED
dropzone.getQueuedFiles()[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.getQueuedFiles().length.should.equal 0
dropzone.getUploadingFiles().length.should.equal 0
it "should call processQueue()", (done) ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.parallelUploads = 0
sinon.spy dropzone, "processQueue"
dropzone.addFile mockFile
setTimeout ->
dropzone.processQueue.callCount.should.equal 1
dropzone.cancelUpload mockFile
dropzone.processQueue.callCount.should.equal 2
done()
, 10
it "should properly cancel all files with the same XHR if uploadMultiple is true", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.uploadMultiple = yes
dropzone.options.parallelUploads = 3
sinon.spy dropzone, "processFiles"
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
setTimeout ->
dropzone.processFiles.callCount.should.equal 1
sinon.spy mock1.xhr, "abort"
dropzone.cancelUpload mock1
expect(mock1.xhr == mock2.xhr == mock3.xhr).to.be.ok
mock1.status.should.equal Dropzone.CANCELED
mock2.status.should.equal Dropzone.CANCELED
mock3.status.should.equal Dropzone.CANCELED
# The XHR should only be aborted once!
mock1.xhr.abort.callCount.should.equal 1
done()
, 10
describe ".disable()", ->
it "should properly cancel all pending uploads", (done) ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
setTimeout ->
dropzone.getUploadingFiles().length.should.equal 1
dropzone.getQueuedFiles().length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy requests[0], "abort"
requests[0].abort.callCount.should.equal 0
dropzone.disable()
requests[0].abort.callCount.should.equal 1
dropzone.getUploadingFiles().length.should.equal 0
dropzone.getQueuedFiles().length.should.equal 0
dropzone.files.length.should.equal 2
dropzone.files[0].status.should.equal Dropzone.CANCELED
dropzone.files[1].status.should.equal Dropzone.CANCELED
done()
, 10
describe ".destroy()", ->
it "should properly cancel all pending uploads and remove all file references", (done) ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
setTimeout ->
dropzone.getUploadingFiles().length.should.equal 1
dropzone.getQueuedFiles().length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy dropzone, "disable"
dropzone.destroy()
dropzone.disable.callCount.should.equal 1
element.should.not.have.property "dropzone"
done()
, 10
it "should be able to create instance of dropzone on the same element after destroy", ->
dropzone.destroy()
( -> new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: -> ).should.not.throw( Error )
it "should remove itself from Dropzone.instances", ->
(Dropzone.instances.indexOf(dropzone) != -1).should.be.ok
dropzone.destroy()
(Dropzone.instances.indexOf(dropzone) == -1).should.be.ok
describe ".filesize()", ->
it "should convert to KiloBytes, etc.. not KibiBytes", ->
# dropzone.filesize(2 * 1000 * 1000).should.eql "<strong>1.9</strong> MiB"
dropzone.filesize(2 * 1024 * 1024).should.eql "<strong>2</strong> MiB"
dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql "<strong>1.9</strong> GiB"
dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql "<strong>2</strong> GiB"
describe "._updateMaxFilesReachedClass()", ->
it "should properly add the dz-max-files-reached class", ->
dropzone.getAcceptedFiles = -> length: 10
dropzone.options.maxFiles = 10
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok
dropzone._updateMaxFilesReachedClass()
dropzone.element.classList.contains("dz-max-files-reached").should.be.ok
it "should fire the 'maxfilesreached' event when appropriate", ->
spy = sinon.spy()
dropzone.on "maxfilesreached", -> spy()
dropzone.getAcceptedFiles = -> length: 9
dropzone.options.maxFiles = 10
dropzone._updateMaxFilesReachedClass()
spy.should.not.have.been.called
dropzone.getAcceptedFiles = -> length: 10
dropzone._updateMaxFilesReachedClass()
spy.should.have.been.called
dropzone.getAcceptedFiles = -> length: 11
dropzone._updateMaxFilesReachedClass()
spy.should.have.been.calledOnce #ie, it has not been called again
it "should properly remove the dz-max-files-reached class", ->
dropzone.getAcceptedFiles = -> length: 10
dropzone.options.maxFiles = 10
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok
dropzone._updateMaxFilesReachedClass()
dropzone.element.classList.contains("dz-max-files-reached").should.be.ok
dropzone.getAcceptedFiles = -> length: 9
dropzone._updateMaxFilesReachedClass()
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok
describe "events", ->
describe "progress updates", ->
it "should properly emit a totaluploadprogress event", (done) ->
dropzone.files = [
{
size: 1990
accepted: true
status: Dropzone.UPLOADING
upload:
progress: 20
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 400
}
{
size: 1990
accepted: true
status: Dropzone.UPLOADING
upload:
progress: 10
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 200
}
]
_called = 0
dropzone.on "totaluploadprogress", (progress) ->
progress.should.equal totalProgressExpectation
done() if ++_called == 3
totalProgressExpectation = 15
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 97.5
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 1900
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 100
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 2000
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.emit "uploadprogress", { }
# Just so the afterEach hook doesn't try to cancel them.
dropzone.files[0].status = Dropzone.CANCELED
dropzone.files[1].status = Dropzone.CANCELED
describe "helper function", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "url"
describe "getExistingFallback()", ->
it "should return undefined if no fallback", ->
expect(dropzone.getExistingFallback()).to.equal undefined
it "should only return the fallback element if it contains exactly fallback", ->
element.appendChild Dropzone.createElement """<form class="fallbacks"></form>"""
element.appendChild Dropzone.createElement """<form class="sfallback"></form>"""
expect(dropzone.getExistingFallback()).to.equal undefined
it "should return divs as fallback", ->
fallback = Dropzone.createElement """<form class=" abc fallback test "></form>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
it "should return forms as fallback", ->
fallback = Dropzone.createElement """<div class=" abc fallback test "></div>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
describe "getFallbackForm()", ->
it "should use the paramName without [] if uploadMultiple is false", ->
dropzone.options.uploadMultiple = false
dropzone.options.paramName = "myFile"
fallback = dropzone.getFallbackForm()
fileInput = fallback.querySelector "input[type=file]"
fileInput.name.should.equal "myFile"
it "should properly add [] to the file name if uploadMultiple is true", ->
dropzone.options.uploadMultiple = yes
dropzone.options.paramName = "myFile"
fallback = dropzone.getFallbackForm()
fileInput = fallback.querySelector "input[type=file]"
fileInput.name.should.equal "myFile[]"
describe "getAcceptedFiles() / getRejectedFiles()", ->
mock1 = mock2 = mock3 = mock4 = null
beforeEach ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, done) ->
if file in [ mock1, mock3 ]
done()
else
done "error"
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
it "getAcceptedFiles() should only return accepted files", ->
dropzone.getAcceptedFiles().should.eql [ mock1, mock3 ]
it "getRejectedFiles() should only return rejected files", ->
dropzone.getRejectedFiles().should.eql [ mock2, mock4 ]
describe "getQueuedFiles()", ->
it "should return all files with the status Dropzone.QUEUED", ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, done) -> file.done = done
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getQueuedFiles().should.eql [ ]
mock1.done()
mock3.done()
dropzone.getQueuedFiles().should.eql [ mock1, mock3 ]
mock1.status.should.equal Dropzone.QUEUED
mock3.status.should.equal Dropzone.QUEUED
mock2.status.should.equal Dropzone.ADDED
mock4.status.should.equal Dropzone.ADDED
describe "getUploadingFiles()", ->
it "should return all files with the status Dropzone.UPLOADING", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, _done) -> file.done = _done
dropzone.uploadFile = ->
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getUploadingFiles().should.eql [ ]
mock1.done()
mock3.done()
setTimeout (->
dropzone.getUploadingFiles().should.eql [ mock1, mock3 ]
mock1.status.should.equal Dropzone.UPLOADING
mock3.status.should.equal Dropzone.UPLOADING
mock2.status.should.equal Dropzone.ADDED
mock4.status.should.equal Dropzone.ADDED
done()
), 10
describe "getActiveFiles()", ->
it "should return all files with the status Dropzone.UPLOADING or Dropzone.QUEUED", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, _done) -> file.done = _done
dropzone.uploadFile = ->
dropzone.options.parallelUploads = 2
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getActiveFiles().should.eql [ ]
mock1.done()
mock3.done()
mock4.done()
setTimeout (->
dropzone.getActiveFiles().should.eql [ mock1, mock3, mock4 ]
mock1.status.should.equal Dropzone.UPLOADING
mock3.status.should.equal Dropzone.UPLOADING
mock2.status.should.equal Dropzone.ADDED
mock4.status.should.equal Dropzone.QUEUED
done()
), 10
describe "getFilesWithStatus()", ->
it "should return all files with provided status", ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, _done) -> file.done = _done
dropzone.uploadFile = ->
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql [ mock1, mock2, mock3, mock4 ]
mock1.status = Dropzone.UPLOADING
mock3.status = Dropzone.QUEUED
mock4.status = Dropzone.QUEUED
dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql [ mock2 ]
dropzone.getFilesWithStatus(Dropzone.UPLOADING).should.eql [ mock1 ]
dropzone.getFilesWithStatus(Dropzone.QUEUED).should.eql [ mock3, mock4 ]
describe "file handling", ->
mockFile = null
dropzone = null
beforeEach ->
mockFile = getMockFile()
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "/the/url"
afterEach ->
dropzone.destroy()
describe "addFile()", ->
it "should properly set the status of the file", ->
doneFunction = null
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.QUEUED
mockFile = getMockFile()
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction("error")
mockFile.status.should.eql Dropzone.ERROR
it "should properly set the status of the file if autoProcessQueue is false and not call processQueue", (done) ->
doneFunction = null
dropzone.options.autoProcessQueue = false
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
sinon.stub dropzone, "processQueue"
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.QUEUED
dropzone.processQueue.callCount.should.equal 0
setTimeout (->
dropzone.processQueue.callCount.should.equal 0
done()
), 10
it "should not add the file to the queue if autoQueue is false", ->
doneFunction = null
dropzone.options.autoQueue = false
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.ADDED
it "should create a remove link if configured to do so", ->
dropzone.options.addRemoveLinks = true
dropzone.processFile = ->
dropzone.uploadFile = ->
sinon.stub dropzone, "processQueue"
dropzone.addFile mockFile
dropzone.files[0].previewElement.querySelector("a[data-dz-remove].dz-remove").should.be.ok
it "should attach an event handler to data-dz-remove links", ->
dropzone.options.previewTemplate = """
<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-filename"><span data-dz-name></span></div>
<div class="dz-size" data-dz-size></div>
<img data-dz-thumbnail />
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-success-mark"><span>✔</span></div>
<div class="dz-error-mark"><span>✘</span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<a class="link1" data-dz-remove></a>
<a class="link2" data-dz-remove></a>
</div>
"""
sinon.stub dropzone, "processQueue"
dropzone.addFile mockFile
file = dropzone.files[0]
removeLink1 = file.previewElement.querySelector("a[data-dz-remove].link1")
removeLink2 = file.previewElement.querySelector("a[data-dz-remove].link2")
sinon.stub dropzone, "removeFile"
event = document.createEvent "HTMLEvents"
event.initEvent "click", true, true
removeLink1.dispatchEvent event
dropzone.removeFile.callCount.should.eql 1
event = document.createEvent "HTMLEvents"
event.initEvent "click", true, true
removeLink2.dispatchEvent event
dropzone.removeFile.callCount.should.eql 2
describe "thumbnails", ->
it "should properly queue the thumbnail creation", (done) ->
doneFunction = null
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock1.type = "image/jpg"
mock2.type = "image/jpg"
mock3.type = "image/jpg"
dropzone.on "thumbnail", ->
console.log "HII"
ct_file = ct_callback = null
dropzone.createThumbnail = (file, callback) ->
ct_file = file
ct_callback = callback
sinon.spy dropzone, "createThumbnail"
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.files.length.should.eql 3
setTimeout (->
dropzone.createThumbnail.callCount.should.eql 1
mock1.should.equal ct_file
ct_callback()
dropzone.createThumbnail.callCount.should.eql 2
mock2.should.equal ct_file
ct_callback()
dropzone.createThumbnail.callCount.should.eql 3
mock3.should.equal ct_file
done()
), 10
# dropzone.addFile mock1
describe "enqueueFile()", ->
it "should be wrapped by enqueueFiles()", ->
sinon.stub dropzone, "enqueueFile"
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
dropzone.enqueueFiles [ mock1, mock2, mock3 ]
dropzone.enqueueFile.callCount.should.equal 3
dropzone.enqueueFile.args[0][0].should.equal mock1
dropzone.enqueueFile.args[1][0].should.equal mock2
dropzone.enqueueFile.args[2][0].should.equal mock3
it "should fail if the file has already been processed", ->
mockFile.status = Dropzone.ERROR
expect((-> dropzone.enqueueFile(mockFile))).to.throw "This file can't be queued because it has already been processed or was rejected."
mockFile.status = Dropzone.COMPLETE
expect((-> dropzone.enqueueFile(mockFile))).to.throw "This file can't be queued because it has already been processed or was rejected."
mockFile.status = Dropzone.UPLOADING
expect((-> dropzone.enqueueFile(mockFile))).to.throw "This file can't be queued because it has already been processed or was rejected."
it "should set the status to QUEUED and call processQueue asynchronously if everything's ok", (done) ->
mockFile.status = Dropzone.ADDED
sinon.stub dropzone, "processQueue"
dropzone.processQueue.callCount.should.equal 0
dropzone.enqueueFile mockFile
mockFile.status.should.equal Dropzone.QUEUED
dropzone.processQueue.callCount.should.equal 0
setTimeout ->
dropzone.processQueue.callCount.should.equal 1
done()
, 10
describe "uploadFiles()", ->
requests = null
beforeEach ->
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
afterEach ->
xhr.restore()
# Removed this test because multiple filenames can be transmitted now
# it "should properly urlencode the filename for the headers"
it "should be wrapped by uploadFile()", ->
sinon.stub dropzone, "uploadFiles"
dropzone.uploadFile mockFile
dropzone.uploadFiles.callCount.should.equal 1
dropzone.uploadFiles.calledWith([ mockFile ]).should.be.ok
it "should ignore the onreadystate callback if readyState != 4", (done) ->
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests[0].status = 200
requests[0].readyState = 3
requests[0].onload()
mockFile.status.should.eql Dropzone.UPLOADING
requests[0].readyState = 4
requests[0].onload()
mockFile.status.should.eql Dropzone.SUCCESS
done()
, 10
it "should emit error and errormultiple when response was not OK", (done) ->
dropzone.options.uploadMultiple = yes
error = no
errormultiple = no
complete = no
completemultiple = no
dropzone.on "error", -> error = yes
dropzone.on "errormultiple", -> errormultiple = yes
dropzone.on "complete", -> complete = yes
dropzone.on "completemultiple", -> completemultiple = yes
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests[0].status = 400
requests[0].readyState = 4
requests[0].onload()
expect(yes == error == errormultiple == complete == completemultiple).to.be.ok
done()
, 10
it "should include hidden files in the form and unchecked checkboxes and radiobuttons should be excluded", (done) ->
element = Dropzone.createElement """<form action="/the/url">
<input type="hidden" name="test" value="hidden" />
<input type="checkbox" name="unchecked" value="1" />
<input type="checkbox" name="checked" value="value1" checked="checked" />
<input type="radio" value="radiovalue1" name="radio1" />
<input type="radio" value="radiovalue2" name="radio1" checked="checked" />
<select name="select"><option value="1">1</option><option value="2" selected>2</option></select>
</form>"""
dropzone = new Dropzone element, url: "/the/url"
formData = null
dropzone.on "sending", (file, xhr, tformData) ->
formData = tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
dropzone.addFile mock1
setTimeout ->
formData.append.callCount.should.equal 5
formData.append.args[0][0].should.eql "test"
formData.append.args[0][1].should.eql "hidden"
formData.append.args[1][0].should.eql "checked"
formData.append.args[1][1].should.eql "value1"
formData.append.args[2][0].should.eql "radio1"
formData.append.args[2][1].should.eql "radiovalue2"
formData.append.args[3][0].should.eql "select"
formData.append.args[3][1].should.eql "2"
formData.append.args[4][0].should.eql "file"
formData.append.args[4][1].should.equal mock1
# formData.append.args[1][0].should.eql "myName[]"
done()
, 10
it "should all values of a select that has the multiple attribute", (done) ->
element = Dropzone.createElement """<form action="/the/url">
<select name="select" multiple>
<option value="value1">1</option>
<option value="value2" selected>2</option>
<option value="value3">3</option>
<option value="value4" selected>4</option>
</select>
</form>"""
dropzone = new Dropzone element, url: "/the/url"
formData = null
dropzone.on "sending", (file, xhr, tformData) ->
formData = tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
dropzone.addFile mock1
setTimeout ->
formData.append.callCount.should.equal 3
formData.append.args[0][0].should.eql "select"
formData.append.args[0][1].should.eql "value2"
formData.append.args[1][0].should.eql "select"
formData.append.args[1][1].should.eql "value4"
formData.append.args[2][0].should.eql "file"
formData.append.args[2][1].should.equal mock1
# formData.append.args[1][0].should.eql "myName[]"
done()
, 10
describe "settings()", ->
it "should correctly set `withCredentials` on the xhr object", ->
dropzone.uploadFile mockFile
requests.length.should.eql 1
requests[0].withCredentials.should.eql no
dropzone.options.withCredentials = yes
dropzone.uploadFile mockFile
requests.length.should.eql 2
requests[1].withCredentials.should.eql yes
it "should correctly override headers on the xhr object", ->
dropzone.options.headers = {"Foo-Header": "foobar"}
dropzone.uploadFile mockFile
requests[0].requestHeaders["Foo-Header"].should.eql 'foobar'
it "should properly use the paramName without [] as file upload if uploadMultiple is false", (done) ->
dropzone.options.uploadMultiple = false
dropzone.options.paramName = "myName"
formData = [ ]
sendingCount = 0
dropzone.on "sending", (files, xhr, tformData) ->
sendingCount++
formData.push tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
mock2 = getMockFile()
dropzone.addFile mock1
dropzone.addFile mock2
setTimeout ->
sendingCount.should.equal 2
formData.length.should.equal 2
formData[0].append.callCount.should.equal 1
formData[1].append.callCount.should.equal 1
formData[0].append.args[0][0].should.eql "myName"
formData[0].append.args[0][0].should.eql "myName"
done()
, 10
it "should properly use the paramName with [] as file upload if uploadMultiple is true", (done) ->
dropzone.options.uploadMultiple = yes
dropzone.options.paramName = "myName"
formData = null
sendingMultipleCount = 0
sendingCount = 0
dropzone.on "sending", (file, xhr, tformData) -> sendingCount++
dropzone.on "sendingmultiple", (files, xhr, tformData) ->
sendingMultipleCount++
formData = tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
mock2 = getMockFile()
dropzone.addFile mock1
dropzone.addFile mock2
setTimeout ->
sendingCount.should.equal 2
sendingMultipleCount.should.equal 1
dropzone.uploadFiles [ mock1, mock2 ]
formData.append.callCount.should.equal 2
formData.append.args[0][0].should.eql "myName[]"
formData.append.args[1][0].should.eql "myName[]"
done()
, 10
describe "should properly set status of file", ->
it "should correctly set `withCredentials` on the xhr object", (done) ->
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 1
requests[0].status = 400
requests[0].readyState = 4
requests[0].onload()
mockFile.status.should.eql Dropzone.ERROR
mockFile = getMockFile()
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 2
requests[1].status = 200
requests[1].readyState = 4
requests[1].onload()
mockFile.status.should.eql Dropzone.SUCCESS
done()
, 10
, 10
describe "complete file", ->
it "should properly emit the queuecomplete event when the complete queue is finished", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock1.status = Dropzone.ADDED
mock2.status = Dropzone.ADDED
mock3.status = Dropzone.ADDED
mock1.name = "mock1"
mock2.name = "mock2"
mock3.name = "mock3"
dropzone.uploadFiles = (files) ->
setTimeout (=>
@_finished files, null, null
), 1
completedFiles = 0
dropzone.on "complete", (file) ->
completedFiles++
dropzone.on "queuecomplete", ->
completedFiles.should.equal 3
done()
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
| 138855 | chai.should()
describe "Dropzone", ->
getMockFile = ->
status: Dropzone.ADDED
accepted: true
name: "<NAME> file <NAME>"
size: 123456
type: "text/html"
xhr = null
beforeEach -> xhr = sinon.useFakeXMLHttpRequest()
describe "static functions", ->
describe "Dropzone.createElement()", ->
element = Dropzone.createElement """<div class="test"><span>Hallo</span></div>"""
it "should properly create an element from a string", ->
element.tagName.should.equal "DIV"
it "should properly add the correct class", ->
element.classList.contains("test").should.be.ok
it "should properly create child elements", ->
element.querySelector("span").tagName.should.equal "SPAN"
it "should always return only one element", ->
element = Dropzone.createElement """<div></div><span></span>"""
element.tagName.should.equal "DIV"
describe "Dropzone.elementInside()", ->
element = Dropzone.createElement """<div id="test"><div class="child1"><div class="child2"></div></div></div>"""
document.body.appendChild element
child1 = element.querySelector ".child1"
child2 = element.querySelector ".child2"
after -> document.body.removeChild element
it "should return yes if elements are the same", ->
Dropzone.elementInside(element, element).should.be.ok
it "should return yes if element is direct child", ->
Dropzone.elementInside(child1, element).should.be.ok
it "should return yes if element is some child", ->
Dropzone.elementInside(child2, element).should.be.ok
Dropzone.elementInside(child2, document.body).should.be.ok
it "should return no unless element is some child", ->
Dropzone.elementInside(element, child1).should.not.be.ok
Dropzone.elementInside(document.body, child1).should.not.be.ok
describe "Dropzone.optionsForElement()", ->
testOptions =
url: "/some/url"
method: "put"
before -> Dropzone.options.testElement = testOptions
after -> delete Dropzone.options.testElement
element = document.createElement "div"
it "should take options set in Dropzone.options from camelized id", ->
element.id = "test-element"
Dropzone.optionsForElement(element).should.equal testOptions
it "should return undefined if no options set", ->
element.id = "test-element2"
expect(Dropzone.optionsForElement(element)).to.equal undefined
it "should return undefined and not throw if it's a form with an input element of the name 'id'", ->
element = Dropzone.createElement """<form><input name="id" /</form>"""
expect(Dropzone.optionsForElement(element)).to.equal undefined
it "should ignore input fields with the name='id'", ->
element = Dropzone.createElement """<form id="test-element"><input type="hidden" name="id" value="fooo" /></form>"""
Dropzone.optionsForElement(element).should.equal testOptions
describe "Dropzone.forElement()", ->
element = document.createElement "div"
element.id = "some-test-element"
dropzone = null
before ->
document.body.appendChild element
dropzone = new Dropzone element, url: "/test"
after ->
dropzone.disable()
document.body.removeChild element
it "should throw an exception if no dropzone attached", ->
expect(-> Dropzone.forElement document.createElement "div").to.throw "No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."
it "should accept css selectors", ->
expect(Dropzone.forElement "#some-test-element").to.equal dropzone
it "should accept native elements", ->
expect(Dropzone.forElement element).to.equal dropzone
describe "Dropzone.discover()", ->
element1 = document.createElement "div"
element1.className = "dropzone"
element2 = element1.cloneNode()
element3 = element1.cloneNode()
element1.id = "test-element-1"
element2.id = "test-element-2"
element3.id = "test-element-3"
describe "specific options", ->
before ->
Dropzone.options.testElement1 = url: "test-url"
Dropzone.options.testElement2 = false # Disabled
document.body.appendChild element1
document.body.appendChild element2
Dropzone.discover()
after ->
document.body.removeChild element1
document.body.removeChild element2
it "should find elements with a .dropzone class", ->
element1.dropzone.should.be.ok
it "should not create dropzones with disabled options", ->
expect(element2.dropzone).to.not.be.ok
describe "Dropzone.autoDiscover", ->
before ->
Dropzone.options.testElement3 = url: "test-url"
document.body.appendChild element3
after ->
document.body.removeChild element3
it "should create dropzones even if Dropzone.autoDiscover == false", ->
# Because the check is in the actual contentLoaded function.
Dropzone.autoDiscover = off
Dropzone.discover()
expect(element3.dropzone).to.be.ok
it "should not automatically be called if Dropzone.autoDiscover == false", ->
Dropzone.autoDiscover = off
Dropzone.discover = -> expect(false).to.be.ok
Dropzone._autoDiscoverFunction()
describe "Dropzone.isValidFile()", ->
it "should return true if called without acceptedFiles", ->
Dropzone.isValidFile({ type: "some/type" }, null).should.be.ok
it "should properly validate if called with concrete mime types", ->
acceptedMimeTypes = "text/html,image/jpeg,application/json"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with base mime types", ->
acceptedMimeTypes = "text/*,image/*,application/*"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with mixed mime types", ->
acceptedMimeTypes = "text/*,image/jpeg,application/*"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok
Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok
it "should properly validate even with spaces in between", ->
acceptedMimeTypes = "text/html , image/jpeg, application/json"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
it "should properly validate extensions", ->
acceptedMimeTypes = "text/html , image/jpeg, .pdf ,.png"
Dropzone.isValidFile({ name: "somxsfsd", type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ name: "somesdfsdf", type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ name: "somesdfadfadf", type: "application/json" }, acceptedMimeTypes).should.not.be.ok
Dropzone.isValidFile({ name: "some-file file.pdf", type: "random/type" }, acceptedMimeTypes).should.be.ok
# .pdf has to be in the end
Dropzone.isValidFile({ name: "some-file.pdf file.gif", type: "random/type" }, acceptedMimeTypes).should.not.be.ok
Dropzone.isValidFile({ name: "some-file file.png", type: "random/type" }, acceptedMimeTypes).should.be.ok
describe "Dropzone.confirm", ->
beforeEach -> sinon.stub window, "confirm"
afterEach -> window.confirm.restore()
it "should forward to window.confirm and call the callbacks accordingly", ->
accepted = rejected = no
window.confirm.returns yes
Dropzone.confirm "test question", (-> accepted = yes), (-> rejected = yes)
window.confirm.args[0][0].should.equal "test question"
accepted.should.equal yes
rejected.should.equal no
accepted = rejected = no
window.confirm.returns no
Dropzone.confirm "test question 2", (-> accepted = yes), (-> rejected = yes)
window.confirm.args[1][0].should.equal "test question 2"
accepted.should.equal no
rejected.should.equal yes
it "should not error if rejected is not provided", ->
accepted = rejected = no
window.confirm.returns no
Dropzone.confirm "test question", (-> accepted = yes)
window.confirm.args[0][0].should.equal "test question"
# Nothing should have changed since there is no rejected function.
accepted.should.equal no
rejected.should.equal no
describe "Dropzone.getElement() / getElements()", ->
tmpElements = [ ]
beforeEach ->
tmpElements = [ ]
tmpElements.push Dropzone.createElement """<div class="tmptest"></div>"""
tmpElements.push Dropzone.createElement """<div id="tmptest1" class="random"></div>"""
tmpElements.push Dropzone.createElement """<div class="random div"></div>"""
tmpElements.forEach (el) -> document.body.appendChild el
afterEach ->
tmpElements.forEach (el) -> document.body.removeChild el
describe ".getElement()", ->
it "should accept a string", ->
el = Dropzone.getElement ".tmptest"
el.should.equal tmpElements[0]
el = Dropzone.getElement "#tmptest1"
el.should.equal tmpElements[1]
it "should accept a node", ->
el = Dropzone.getElement tmpElements[2]
el.should.equal tmpElements[2]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element."
expect(-> Dropzone.getElement "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElement { "lblasdlfsfl" }, "clickable").to.throw errorMessage
expect(-> Dropzone.getElement [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe ".getElements()", ->
it "should accept a list of strings", ->
els = Dropzone.getElements [ ".tmptest", "#tmptest1" ]
els.should.eql [ tmpElements[0], tmpElements[1] ]
it "should accept a list of nodes", ->
els = Dropzone.getElements [ tmpElements[0], tmpElements[2] ]
els.should.eql [ tmpElements[0], tmpElements[2] ]
it "should accept a mixed list", ->
els = Dropzone.getElements [ "#tmptest1", tmpElements[2] ]
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a string selector", ->
els = Dropzone.getElements ".random"
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a single node", ->
els = Dropzone.getElements tmpElements[1]
els.should.eql [ tmpElements[1] ]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
expect(-> Dropzone.getElements "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElements [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe "constructor()", ->
dropzone = null
afterEach -> dropzone.destroy() if dropzone?
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone "#invalid-element").to.throw "Invalid dropzone element."
it "should throw an exception if assigned twice to the same element", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
expect(-> new Dropzone element, url: "url").to.throw "Dropzone already attached."
it "should throw an exception if both acceptedFiles and acceptedMimeTypes are specified", ->
element = document.createElement "div"
expect(-> dropzone = new Dropzone element, url: "test", acceptedFiles: "param", acceptedMimeTypes: "types").to.throw "You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."
it "should set itself as element.dropzone", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
element.dropzone.should.equal dropzone
it "should add itself to Dropzone.instances", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
Dropzone.instances[Dropzone.instances.length - 1].should.equal dropzone
it "should use the action attribute not the element with the name action", ->
element = Dropzone.createElement """<form action="real-action"><input type="hidden" name="action" value="wrong-action" /></form>"""
dropzone = new Dropzone element
dropzone.options.url.should.equal "real-action"
describe "options", ->
element = null
element2 = null
beforeEach ->
element = document.createElement "div"
element.id = "test-element"
element2 = document.createElement "div"
element2.id = "test-element2"
Dropzone.options.testElement = url: "/some/url", parallelUploads: 10
afterEach -> delete Dropzone.options.testElement
it "should take the options set in Dropzone.options", ->
dropzone = new Dropzone element
dropzone.options.url.should.equal "/some/url"
dropzone.options.parallelUploads.should.equal 10
it "should prefer passed options over Dropzone.options", ->
dropzone = new Dropzone element, url: "/some/other/url"
dropzone.options.url.should.equal "/some/other/url"
it "should take the default options if nothing set in Dropzone.options", ->
dropzone = new Dropzone element2, url: "/some/url"
dropzone.options.parallelUploads.should.equal 2
it "should call the fallback function if forceFallback == true", (done) ->
dropzone = new Dropzone element,
url: "/some/other/url"
forceFallback: on
fallback: -> done()
it "should set acceptedFiles if deprecated acceptedMimetypes option has been passed", ->
dropzone = new Dropzone element,
url: "/some/other/url"
acceptedMimeTypes: "my/type"
dropzone.options.acceptedFiles.should.equal "my/type"
describe "options.clickable", ->
clickableElement = null
dropzone = null
beforeEach ->
clickableElement = document.createElement "div"
clickableElement.className = "some-clickable"
document.body.appendChild clickableElement
afterEach ->
document.body.removeChild clickableElement
dropzone.destroy if dropzone?
it "should use the default element if clickable == true", ->
dropzone = new Dropzone element, clickable: yes
dropzone.clickableElements.should.eql [ dropzone.element ]
it "should lookup the element if clickable is a CSS selector", ->
dropzone = new Dropzone element, clickable: ".some-clickable"
dropzone.clickableElements.should.eql [ clickableElement ]
it "should simply use the provided element", ->
dropzone = new Dropzone element, clickable: clickableElement
dropzone.clickableElements.should.eql [ clickableElement ]
it "should accept multiple clickable elements", ->
dropzone = new Dropzone element, clickable: [ document.body, ".some-clickable" ]
dropzone.clickableElements.should.eql [ document.body, clickableElement ]
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone element, clickable: ".some-invalid-clickable").to.throw "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
describe "init()", ->
describe "clickable", ->
dropzones =
"using acceptedFiles": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptedFiles: "audio/*,video/*" })
"using acceptedMimeTypes": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptedMimeTypes: "audio/*,video/*" })
it "should not add an accept attribute if no acceptParameter", ->
dropzone = new Dropzone (Dropzone.createElement """<form action="/"></form>"""), clickable: yes, acceptParameter: null, acceptedMimeTypes: null
dropzone.hiddenFileInput.hasAttribute("accept").should.be.false
for name, dropzone of dropzones
describe name, ->
do (dropzone) ->
it "should create a hidden file input if clickable", ->
dropzone.hiddenFileInput.should.be.ok
dropzone.hiddenFileInput.tagName.should.equal "INPUT"
it "should use the acceptParameter", ->
dropzone.hiddenFileInput.getAttribute("accept").should.equal "audio/*,video/*"
it "should create a new input element when something is selected to reset the input field", ->
for i in [0..3]
hiddenFileInput = dropzone.hiddenFileInput
event = document.createEvent "HTMLEvents"
event.initEvent "change", true, true
hiddenFileInput.dispatchEvent event
dropzone.hiddenFileInput.should.not.equal hiddenFileInput
Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok
it "should create a .dz-message element", ->
element = Dropzone.createElement """<form class="dropzone" action="/"></form>"""
dropzone = new Dropzone element, clickable: yes, acceptParameter: null, acceptedMimeTypes: null
element.querySelector(".dz-message").should.be.instanceof Element
it "should not create a .dz-message element if there already is one", ->
element = Dropzone.createElement """<form class="dropzone" action="/"></form>"""
msg = Dropzone.createElement """<div class="dz-message">TEST</div>"""
element.appendChild msg
dropzone = new Dropzone element, clickable: yes, acceptParameter: null, acceptedMimeTypes: null
element.querySelector(".dz-message").should.equal msg
element.querySelectorAll(".dz-message").length.should.equal 1
describe "options", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", maxFiles: 3
describe "file specific", ->
file = null
beforeEach ->
file =
name: "<NAME>"
size: 2 * 1024 * 1024
dropzone.options.addedfile.call dropzone, file
describe ".addedFile()", ->
it "should properly create the previewElement", ->
file.previewElement.should.be.instanceof Element
file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql "test name"
file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql "<strong>2</strong> MiB"
describe ".error()", ->
it "should properly insert the error", ->
dropzone.options.error.call dropzone, file, "test message"
file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql "test message"
it "should properly insert the error when provided with an object containing the error", ->
dropzone.options.error.call dropzone, file, error: "test message"
file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql "test message"
describe ".thumbnail()", ->
it "should properly insert the error", ->
transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
dropzone.options.thumbnail.call dropzone, file, transparentGif
thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]")
thumbnail.src.should.eql transparentGif
thumbnail.alt.should.eql "test name"
describe ".uploadprogress()", ->
it "should properly set the width", ->
dropzone.options.uploadprogress.call dropzone, file, 0
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "0%"
dropzone.options.uploadprogress.call dropzone, file, 80
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "80%"
dropzone.options.uploadprogress.call dropzone, file, 90
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "90%"
dropzone.options.uploadprogress.call dropzone, file, 100
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "100%"
describe "instance", ->
element = null
dropzone = null
requests = null
beforeEach ->
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
element = Dropzone.createElement """<div></div>"""
document.body.appendChild element
dropzone = new Dropzone element, maxFilesize: 4, maxFiles: 100, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: ->
afterEach ->
document.body.removeChild element
dropzone.destroy()
xhr.restore()
describe ".accept()", ->
it "should pass if the filesize is OK", ->
dropzone.accept { size: 2 * 1024 * 1024, type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
it "shouldn't pass if the filesize is too big", ->
dropzone.accept { size: 10 * 1024 * 1024, type: "audio/mp3" }, (err) -> err.should.eql "File is too big (10MiB). Max filesize: 4MiB."
it "should properly accept files which mime types are listed in acceptedFiles", ->
dropzone.accept { type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "image/png" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "audio/wav" }, (err) -> expect(err).to.be.undefined
it "should properly reject files when the mime type isn't listed in acceptedFiles", ->
dropzone.accept { type: "image/jpeg" }, (err) -> err.should.eql "You can't upload files of this type."
it "should fail if maxFiles has been exceeded and call the event maxfilesexceeded", ->
sinon.stub dropzone, "getAcceptedFiles"
file = { type: "audio/mp3" }
dropzone.getAcceptedFiles.returns { length: 99 }
dropzone.options.dictMaxFilesExceeded = "You can only upload {{maxFiles}} files."
called = no
dropzone.on "maxfilesexceeded", (lfile) ->
lfile.should.equal file
called = yes
dropzone.accept file, (err) -> expect(err).to.be.undefined
called.should.not.be.ok
dropzone.getAcceptedFiles.returns { length: 100 }
dropzone.accept file, (err) -> expect(err).to.equal "You can only upload 100 files."
called.should.be.ok
dropzone.getAcceptedFiles.restore()
it "should properly handle if maxFiles is 0", ->
file = { type: "audio/mp3" }
dropzone.options.maxFiles = 0
called = no
dropzone.on "maxfilesexceeded", (lfile) ->
lfile.should.equal file
called = yes
dropzone.accept file, (err) -> expect(err).to.equal "You can not upload any more files."
called.should.be.ok
describe ".removeFile()", ->
it "should abort uploading if file is currently being uploaded", (done) ->
mockFile = getMockFile()
dropzone.uploadFile = (file) ->
dropzone.accept = (file, done) -> done()
sinon.stub dropzone, "cancelUpload"
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.getUploadingFiles()[0].should.equal mockFile
dropzone.cancelUpload.callCount.should.equal 0
dropzone.removeFile mockFile
dropzone.cancelUpload.callCount.should.equal 1
done()
, 10
describe ".cancelUpload()", ->
it "should properly cancel upload if file currently uploading", (done) ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.getUploadingFiles()[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.getUploadingFiles().length.should.equal 0
dropzone.getQueuedFiles().length.should.equal 0
done()
, 10
it "should properly cancel the upload if file is not yet uploading", ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.parallelUploads = 0
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.QUEUED
dropzone.getQueuedFiles()[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.getQueuedFiles().length.should.equal 0
dropzone.getUploadingFiles().length.should.equal 0
it "should call processQueue()", (done) ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.parallelUploads = 0
sinon.spy dropzone, "processQueue"
dropzone.addFile mockFile
setTimeout ->
dropzone.processQueue.callCount.should.equal 1
dropzone.cancelUpload mockFile
dropzone.processQueue.callCount.should.equal 2
done()
, 10
it "should properly cancel all files with the same XHR if uploadMultiple is true", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.uploadMultiple = yes
dropzone.options.parallelUploads = 3
sinon.spy dropzone, "processFiles"
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
setTimeout ->
dropzone.processFiles.callCount.should.equal 1
sinon.spy mock1.xhr, "abort"
dropzone.cancelUpload mock1
expect(mock1.xhr == mock2.xhr == mock3.xhr).to.be.ok
mock1.status.should.equal Dropzone.CANCELED
mock2.status.should.equal Dropzone.CANCELED
mock3.status.should.equal Dropzone.CANCELED
# The XHR should only be aborted once!
mock1.xhr.abort.callCount.should.equal 1
done()
, 10
describe ".disable()", ->
it "should properly cancel all pending uploads", (done) ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
setTimeout ->
dropzone.getUploadingFiles().length.should.equal 1
dropzone.getQueuedFiles().length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy requests[0], "abort"
requests[0].abort.callCount.should.equal 0
dropzone.disable()
requests[0].abort.callCount.should.equal 1
dropzone.getUploadingFiles().length.should.equal 0
dropzone.getQueuedFiles().length.should.equal 0
dropzone.files.length.should.equal 2
dropzone.files[0].status.should.equal Dropzone.CANCELED
dropzone.files[1].status.should.equal Dropzone.CANCELED
done()
, 10
describe ".destroy()", ->
it "should properly cancel all pending uploads and remove all file references", (done) ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
setTimeout ->
dropzone.getUploadingFiles().length.should.equal 1
dropzone.getQueuedFiles().length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy dropzone, "disable"
dropzone.destroy()
dropzone.disable.callCount.should.equal 1
element.should.not.have.property "dropzone"
done()
, 10
it "should be able to create instance of dropzone on the same element after destroy", ->
dropzone.destroy()
( -> new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: -> ).should.not.throw( Error )
it "should remove itself from Dropzone.instances", ->
(Dropzone.instances.indexOf(dropzone) != -1).should.be.ok
dropzone.destroy()
(Dropzone.instances.indexOf(dropzone) == -1).should.be.ok
describe ".filesize()", ->
it "should convert to KiloBytes, etc.. not KibiBytes", ->
# dropzone.filesize(2 * 1000 * 1000).should.eql "<strong>1.9</strong> MiB"
dropzone.filesize(2 * 1024 * 1024).should.eql "<strong>2</strong> MiB"
dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql "<strong>1.9</strong> GiB"
dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql "<strong>2</strong> GiB"
describe "._updateMaxFilesReachedClass()", ->
it "should properly add the dz-max-files-reached class", ->
dropzone.getAcceptedFiles = -> length: 10
dropzone.options.maxFiles = 10
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok
dropzone._updateMaxFilesReachedClass()
dropzone.element.classList.contains("dz-max-files-reached").should.be.ok
it "should fire the 'maxfilesreached' event when appropriate", ->
spy = sinon.spy()
dropzone.on "maxfilesreached", -> spy()
dropzone.getAcceptedFiles = -> length: 9
dropzone.options.maxFiles = 10
dropzone._updateMaxFilesReachedClass()
spy.should.not.have.been.called
dropzone.getAcceptedFiles = -> length: 10
dropzone._updateMaxFilesReachedClass()
spy.should.have.been.called
dropzone.getAcceptedFiles = -> length: 11
dropzone._updateMaxFilesReachedClass()
spy.should.have.been.calledOnce #ie, it has not been called again
it "should properly remove the dz-max-files-reached class", ->
dropzone.getAcceptedFiles = -> length: 10
dropzone.options.maxFiles = 10
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok
dropzone._updateMaxFilesReachedClass()
dropzone.element.classList.contains("dz-max-files-reached").should.be.ok
dropzone.getAcceptedFiles = -> length: 9
dropzone._updateMaxFilesReachedClass()
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok
describe "events", ->
describe "progress updates", ->
it "should properly emit a totaluploadprogress event", (done) ->
dropzone.files = [
{
size: 1990
accepted: true
status: Dropzone.UPLOADING
upload:
progress: 20
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 400
}
{
size: 1990
accepted: true
status: Dropzone.UPLOADING
upload:
progress: 10
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 200
}
]
_called = 0
dropzone.on "totaluploadprogress", (progress) ->
progress.should.equal totalProgressExpectation
done() if ++_called == 3
totalProgressExpectation = 15
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 97.5
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 1900
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 100
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 2000
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.emit "uploadprogress", { }
# Just so the afterEach hook doesn't try to cancel them.
dropzone.files[0].status = Dropzone.CANCELED
dropzone.files[1].status = Dropzone.CANCELED
describe "helper function", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "url"
describe "getExistingFallback()", ->
it "should return undefined if no fallback", ->
expect(dropzone.getExistingFallback()).to.equal undefined
it "should only return the fallback element if it contains exactly fallback", ->
element.appendChild Dropzone.createElement """<form class="fallbacks"></form>"""
element.appendChild Dropzone.createElement """<form class="sfallback"></form>"""
expect(dropzone.getExistingFallback()).to.equal undefined
it "should return divs as fallback", ->
fallback = Dropzone.createElement """<form class=" abc fallback test "></form>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
it "should return forms as fallback", ->
fallback = Dropzone.createElement """<div class=" abc fallback test "></div>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
describe "getFallbackForm()", ->
it "should use the paramName without [] if uploadMultiple is false", ->
dropzone.options.uploadMultiple = false
dropzone.options.paramName = "myFile"
fallback = dropzone.getFallbackForm()
fileInput = fallback.querySelector "input[type=file]"
fileInput.name.should.equal "myFile"
it "should properly add [] to the file name if uploadMultiple is true", ->
dropzone.options.uploadMultiple = yes
dropzone.options.paramName = "myFile"
fallback = dropzone.getFallbackForm()
fileInput = fallback.querySelector "input[type=file]"
fileInput.name.should.equal "myFile[]"
describe "getAcceptedFiles() / getRejectedFiles()", ->
mock1 = mock2 = mock3 = mock4 = null
beforeEach ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, done) ->
if file in [ mock1, mock3 ]
done()
else
done "error"
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
it "getAcceptedFiles() should only return accepted files", ->
dropzone.getAcceptedFiles().should.eql [ mock1, mock3 ]
it "getRejectedFiles() should only return rejected files", ->
dropzone.getRejectedFiles().should.eql [ mock2, mock4 ]
describe "getQueuedFiles()", ->
it "should return all files with the status Dropzone.QUEUED", ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, done) -> file.done = done
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getQueuedFiles().should.eql [ ]
mock1.done()
mock3.done()
dropzone.getQueuedFiles().should.eql [ mock1, mock3 ]
mock1.status.should.equal Dropzone.QUEUED
mock3.status.should.equal Dropzone.QUEUED
mock2.status.should.equal Dropzone.ADDED
mock4.status.should.equal Dropzone.ADDED
describe "getUploadingFiles()", ->
it "should return all files with the status Dropzone.UPLOADING", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, _done) -> file.done = _done
dropzone.uploadFile = ->
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getUploadingFiles().should.eql [ ]
mock1.done()
mock3.done()
setTimeout (->
dropzone.getUploadingFiles().should.eql [ mock1, mock3 ]
mock1.status.should.equal Dropzone.UPLOADING
mock3.status.should.equal Dropzone.UPLOADING
mock2.status.should.equal Dropzone.ADDED
mock4.status.should.equal Dropzone.ADDED
done()
), 10
describe "getActiveFiles()", ->
it "should return all files with the status Dropzone.UPLOADING or Dropzone.QUEUED", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, _done) -> file.done = _done
dropzone.uploadFile = ->
dropzone.options.parallelUploads = 2
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getActiveFiles().should.eql [ ]
mock1.done()
mock3.done()
mock4.done()
setTimeout (->
dropzone.getActiveFiles().should.eql [ mock1, mock3, mock4 ]
mock1.status.should.equal Dropzone.UPLOADING
mock3.status.should.equal Dropzone.UPLOADING
mock2.status.should.equal Dropzone.ADDED
mock4.status.should.equal Dropzone.QUEUED
done()
), 10
describe "getFilesWithStatus()", ->
it "should return all files with provided status", ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, _done) -> file.done = _done
dropzone.uploadFile = ->
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql [ mock1, mock2, mock3, mock4 ]
mock1.status = Dropzone.UPLOADING
mock3.status = Dropzone.QUEUED
mock4.status = Dropzone.QUEUED
dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql [ mock2 ]
dropzone.getFilesWithStatus(Dropzone.UPLOADING).should.eql [ mock1 ]
dropzone.getFilesWithStatus(Dropzone.QUEUED).should.eql [ mock3, mock4 ]
describe "file handling", ->
mockFile = null
dropzone = null
beforeEach ->
mockFile = getMockFile()
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "/the/url"
afterEach ->
dropzone.destroy()
describe "addFile()", ->
it "should properly set the status of the file", ->
doneFunction = null
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.QUEUED
mockFile = getMockFile()
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction("error")
mockFile.status.should.eql Dropzone.ERROR
it "should properly set the status of the file if autoProcessQueue is false and not call processQueue", (done) ->
doneFunction = null
dropzone.options.autoProcessQueue = false
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
sinon.stub dropzone, "processQueue"
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.QUEUED
dropzone.processQueue.callCount.should.equal 0
setTimeout (->
dropzone.processQueue.callCount.should.equal 0
done()
), 10
it "should not add the file to the queue if autoQueue is false", ->
doneFunction = null
dropzone.options.autoQueue = false
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.ADDED
it "should create a remove link if configured to do so", ->
dropzone.options.addRemoveLinks = true
dropzone.processFile = ->
dropzone.uploadFile = ->
sinon.stub dropzone, "processQueue"
dropzone.addFile mockFile
dropzone.files[0].previewElement.querySelector("a[data-dz-remove].dz-remove").should.be.ok
it "should attach an event handler to data-dz-remove links", ->
dropzone.options.previewTemplate = """
<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-filename"><span data-dz-name></span></div>
<div class="dz-size" data-dz-size></div>
<img data-dz-thumbnail />
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-success-mark"><span>✔</span></div>
<div class="dz-error-mark"><span>✘</span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<a class="link1" data-dz-remove></a>
<a class="link2" data-dz-remove></a>
</div>
"""
sinon.stub dropzone, "processQueue"
dropzone.addFile mockFile
file = dropzone.files[0]
removeLink1 = file.previewElement.querySelector("a[data-dz-remove].link1")
removeLink2 = file.previewElement.querySelector("a[data-dz-remove].link2")
sinon.stub dropzone, "removeFile"
event = document.createEvent "HTMLEvents"
event.initEvent "click", true, true
removeLink1.dispatchEvent event
dropzone.removeFile.callCount.should.eql 1
event = document.createEvent "HTMLEvents"
event.initEvent "click", true, true
removeLink2.dispatchEvent event
dropzone.removeFile.callCount.should.eql 2
describe "thumbnails", ->
it "should properly queue the thumbnail creation", (done) ->
doneFunction = null
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock1.type = "image/jpg"
mock2.type = "image/jpg"
mock3.type = "image/jpg"
dropzone.on "thumbnail", ->
console.log "HII"
ct_file = ct_callback = null
dropzone.createThumbnail = (file, callback) ->
ct_file = file
ct_callback = callback
sinon.spy dropzone, "createThumbnail"
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.files.length.should.eql 3
setTimeout (->
dropzone.createThumbnail.callCount.should.eql 1
mock1.should.equal ct_file
ct_callback()
dropzone.createThumbnail.callCount.should.eql 2
mock2.should.equal ct_file
ct_callback()
dropzone.createThumbnail.callCount.should.eql 3
mock3.should.equal ct_file
done()
), 10
# dropzone.addFile mock1
describe "enqueueFile()", ->
it "should be wrapped by enqueueFiles()", ->
sinon.stub dropzone, "enqueueFile"
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
dropzone.enqueueFiles [ mock1, mock2, mock3 ]
dropzone.enqueueFile.callCount.should.equal 3
dropzone.enqueueFile.args[0][0].should.equal mock1
dropzone.enqueueFile.args[1][0].should.equal mock2
dropzone.enqueueFile.args[2][0].should.equal mock3
it "should fail if the file has already been processed", ->
mockFile.status = Dropzone.ERROR
expect((-> dropzone.enqueueFile(mockFile))).to.throw "This file can't be queued because it has already been processed or was rejected."
mockFile.status = Dropzone.COMPLETE
expect((-> dropzone.enqueueFile(mockFile))).to.throw "This file can't be queued because it has already been processed or was rejected."
mockFile.status = Dropzone.UPLOADING
expect((-> dropzone.enqueueFile(mockFile))).to.throw "This file can't be queued because it has already been processed or was rejected."
it "should set the status to QUEUED and call processQueue asynchronously if everything's ok", (done) ->
mockFile.status = Dropzone.ADDED
sinon.stub dropzone, "processQueue"
dropzone.processQueue.callCount.should.equal 0
dropzone.enqueueFile mockFile
mockFile.status.should.equal Dropzone.QUEUED
dropzone.processQueue.callCount.should.equal 0
setTimeout ->
dropzone.processQueue.callCount.should.equal 1
done()
, 10
describe "uploadFiles()", ->
requests = null
beforeEach ->
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
afterEach ->
xhr.restore()
# Removed this test because multiple filenames can be transmitted now
# it "should properly urlencode the filename for the headers"
it "should be wrapped by uploadFile()", ->
sinon.stub dropzone, "uploadFiles"
dropzone.uploadFile mockFile
dropzone.uploadFiles.callCount.should.equal 1
dropzone.uploadFiles.calledWith([ mockFile ]).should.be.ok
it "should ignore the onreadystate callback if readyState != 4", (done) ->
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests[0].status = 200
requests[0].readyState = 3
requests[0].onload()
mockFile.status.should.eql Dropzone.UPLOADING
requests[0].readyState = 4
requests[0].onload()
mockFile.status.should.eql Dropzone.SUCCESS
done()
, 10
it "should emit error and errormultiple when response was not OK", (done) ->
dropzone.options.uploadMultiple = yes
error = no
errormultiple = no
complete = no
completemultiple = no
dropzone.on "error", -> error = yes
dropzone.on "errormultiple", -> errormultiple = yes
dropzone.on "complete", -> complete = yes
dropzone.on "completemultiple", -> completemultiple = yes
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests[0].status = 400
requests[0].readyState = 4
requests[0].onload()
expect(yes == error == errormultiple == complete == completemultiple).to.be.ok
done()
, 10
it "should include hidden files in the form and unchecked checkboxes and radiobuttons should be excluded", (done) ->
element = Dropzone.createElement """<form action="/the/url">
<input type="hidden" name="test" value="hidden" />
<input type="checkbox" name="unchecked" value="1" />
<input type="checkbox" name="checked" value="value1" checked="checked" />
<input type="radio" value="radiovalue1" name="radio1" />
<input type="radio" value="radiovalue2" name="radio1" checked="checked" />
<select name="select"><option value="1">1</option><option value="2" selected>2</option></select>
</form>"""
dropzone = new Dropzone element, url: "/the/url"
formData = null
dropzone.on "sending", (file, xhr, tformData) ->
formData = tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
dropzone.addFile mock1
setTimeout ->
formData.append.callCount.should.equal 5
formData.append.args[0][0].should.eql "test"
formData.append.args[0][1].should.eql "hidden"
formData.append.args[1][0].should.eql "checked"
formData.append.args[1][1].should.eql "value1"
formData.append.args[2][0].should.eql "radio1"
formData.append.args[2][1].should.eql "radiovalue2"
formData.append.args[3][0].should.eql "select"
formData.append.args[3][1].should.eql "2"
formData.append.args[4][0].should.eql "file"
formData.append.args[4][1].should.equal mock1
# formData.append.args[1][0].should.eql "myName[]"
done()
, 10
it "should all values of a select that has the multiple attribute", (done) ->
element = Dropzone.createElement """<form action="/the/url">
<select name="select" multiple>
<option value="value1">1</option>
<option value="value2" selected>2</option>
<option value="value3">3</option>
<option value="value4" selected>4</option>
</select>
</form>"""
dropzone = new Dropzone element, url: "/the/url"
formData = null
dropzone.on "sending", (file, xhr, tformData) ->
formData = tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
dropzone.addFile mock1
setTimeout ->
formData.append.callCount.should.equal 3
formData.append.args[0][0].should.eql "select"
formData.append.args[0][1].should.eql "value2"
formData.append.args[1][0].should.eql "select"
formData.append.args[1][1].should.eql "value4"
formData.append.args[2][0].should.eql "file"
formData.append.args[2][1].should.equal mock1
# formData.append.args[1][0].should.eql "myName[]"
done()
, 10
describe "settings()", ->
it "should correctly set `withCredentials` on the xhr object", ->
dropzone.uploadFile mockFile
requests.length.should.eql 1
requests[0].withCredentials.should.eql no
dropzone.options.withCredentials = yes
dropzone.uploadFile mockFile
requests.length.should.eql 2
requests[1].withCredentials.should.eql yes
it "should correctly override headers on the xhr object", ->
dropzone.options.headers = {"Foo-Header": "foobar"}
dropzone.uploadFile mockFile
requests[0].requestHeaders["Foo-Header"].should.eql 'foobar'
it "should properly use the paramName without [] as file upload if uploadMultiple is false", (done) ->
dropzone.options.uploadMultiple = false
dropzone.options.paramName = "<NAME>Name"
formData = [ ]
sendingCount = 0
dropzone.on "sending", (files, xhr, tformData) ->
sendingCount++
formData.push tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
mock2 = getMockFile()
dropzone.addFile mock1
dropzone.addFile mock2
setTimeout ->
sendingCount.should.equal 2
formData.length.should.equal 2
formData[0].append.callCount.should.equal 1
formData[1].append.callCount.should.equal 1
formData[0].append.args[0][0].should.eql "myName"
formData[0].append.args[0][0].should.eql "<NAME>"
done()
, 10
it "should properly use the paramName with [] as file upload if uploadMultiple is true", (done) ->
dropzone.options.uploadMultiple = yes
dropzone.options.paramName = "<NAME>"
formData = null
sendingMultipleCount = 0
sendingCount = 0
dropzone.on "sending", (file, xhr, tformData) -> sendingCount++
dropzone.on "sendingmultiple", (files, xhr, tformData) ->
sendingMultipleCount++
formData = tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
mock2 = getMockFile()
dropzone.addFile mock1
dropzone.addFile mock2
setTimeout ->
sendingCount.should.equal 2
sendingMultipleCount.should.equal 1
dropzone.uploadFiles [ mock1, mock2 ]
formData.append.callCount.should.equal 2
formData.append.args[0][0].should.eql "myName[]"
formData.append.args[1][0].should.eql "myName[]"
done()
, 10
describe "should properly set status of file", ->
it "should correctly set `withCredentials` on the xhr object", (done) ->
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 1
requests[0].status = 400
requests[0].readyState = 4
requests[0].onload()
mockFile.status.should.eql Dropzone.ERROR
mockFile = getMockFile()
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 2
requests[1].status = 200
requests[1].readyState = 4
requests[1].onload()
mockFile.status.should.eql Dropzone.SUCCESS
done()
, 10
, 10
describe "complete file", ->
it "should properly emit the queuecomplete event when the complete queue is finished", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock1.status = Dropzone.ADDED
mock2.status = Dropzone.ADDED
mock3.status = Dropzone.ADDED
mock1.name = "mock1"
mock2.name = "mock2"
mock3.name = "mock3"
dropzone.uploadFiles = (files) ->
setTimeout (=>
@_finished files, null, null
), 1
completedFiles = 0
dropzone.on "complete", (file) ->
completedFiles++
dropzone.on "queuecomplete", ->
completedFiles.should.equal 3
done()
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
| true | chai.should()
describe "Dropzone", ->
getMockFile = ->
status: Dropzone.ADDED
accepted: true
name: "PI:NAME:<NAME>END_PI file PI:NAME:<NAME>END_PI"
size: 123456
type: "text/html"
xhr = null
beforeEach -> xhr = sinon.useFakeXMLHttpRequest()
describe "static functions", ->
describe "Dropzone.createElement()", ->
element = Dropzone.createElement """<div class="test"><span>Hallo</span></div>"""
it "should properly create an element from a string", ->
element.tagName.should.equal "DIV"
it "should properly add the correct class", ->
element.classList.contains("test").should.be.ok
it "should properly create child elements", ->
element.querySelector("span").tagName.should.equal "SPAN"
it "should always return only one element", ->
element = Dropzone.createElement """<div></div><span></span>"""
element.tagName.should.equal "DIV"
describe "Dropzone.elementInside()", ->
element = Dropzone.createElement """<div id="test"><div class="child1"><div class="child2"></div></div></div>"""
document.body.appendChild element
child1 = element.querySelector ".child1"
child2 = element.querySelector ".child2"
after -> document.body.removeChild element
it "should return yes if elements are the same", ->
Dropzone.elementInside(element, element).should.be.ok
it "should return yes if element is direct child", ->
Dropzone.elementInside(child1, element).should.be.ok
it "should return yes if element is some child", ->
Dropzone.elementInside(child2, element).should.be.ok
Dropzone.elementInside(child2, document.body).should.be.ok
it "should return no unless element is some child", ->
Dropzone.elementInside(element, child1).should.not.be.ok
Dropzone.elementInside(document.body, child1).should.not.be.ok
describe "Dropzone.optionsForElement()", ->
testOptions =
url: "/some/url"
method: "put"
before -> Dropzone.options.testElement = testOptions
after -> delete Dropzone.options.testElement
element = document.createElement "div"
it "should take options set in Dropzone.options from camelized id", ->
element.id = "test-element"
Dropzone.optionsForElement(element).should.equal testOptions
it "should return undefined if no options set", ->
element.id = "test-element2"
expect(Dropzone.optionsForElement(element)).to.equal undefined
it "should return undefined and not throw if it's a form with an input element of the name 'id'", ->
element = Dropzone.createElement """<form><input name="id" /</form>"""
expect(Dropzone.optionsForElement(element)).to.equal undefined
it "should ignore input fields with the name='id'", ->
element = Dropzone.createElement """<form id="test-element"><input type="hidden" name="id" value="fooo" /></form>"""
Dropzone.optionsForElement(element).should.equal testOptions
describe "Dropzone.forElement()", ->
element = document.createElement "div"
element.id = "some-test-element"
dropzone = null
before ->
document.body.appendChild element
dropzone = new Dropzone element, url: "/test"
after ->
dropzone.disable()
document.body.removeChild element
it "should throw an exception if no dropzone attached", ->
expect(-> Dropzone.forElement document.createElement "div").to.throw "No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."
it "should accept css selectors", ->
expect(Dropzone.forElement "#some-test-element").to.equal dropzone
it "should accept native elements", ->
expect(Dropzone.forElement element).to.equal dropzone
describe "Dropzone.discover()", ->
element1 = document.createElement "div"
element1.className = "dropzone"
element2 = element1.cloneNode()
element3 = element1.cloneNode()
element1.id = "test-element-1"
element2.id = "test-element-2"
element3.id = "test-element-3"
describe "specific options", ->
before ->
Dropzone.options.testElement1 = url: "test-url"
Dropzone.options.testElement2 = false # Disabled
document.body.appendChild element1
document.body.appendChild element2
Dropzone.discover()
after ->
document.body.removeChild element1
document.body.removeChild element2
it "should find elements with a .dropzone class", ->
element1.dropzone.should.be.ok
it "should not create dropzones with disabled options", ->
expect(element2.dropzone).to.not.be.ok
describe "Dropzone.autoDiscover", ->
before ->
Dropzone.options.testElement3 = url: "test-url"
document.body.appendChild element3
after ->
document.body.removeChild element3
it "should create dropzones even if Dropzone.autoDiscover == false", ->
# Because the check is in the actual contentLoaded function.
Dropzone.autoDiscover = off
Dropzone.discover()
expect(element3.dropzone).to.be.ok
it "should not automatically be called if Dropzone.autoDiscover == false", ->
Dropzone.autoDiscover = off
Dropzone.discover = -> expect(false).to.be.ok
Dropzone._autoDiscoverFunction()
describe "Dropzone.isValidFile()", ->
it "should return true if called without acceptedFiles", ->
Dropzone.isValidFile({ type: "some/type" }, null).should.be.ok
it "should properly validate if called with concrete mime types", ->
acceptedMimeTypes = "text/html,image/jpeg,application/json"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with base mime types", ->
acceptedMimeTypes = "text/*,image/*,application/*"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with mixed mime types", ->
acceptedMimeTypes = "text/*,image/jpeg,application/*"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok
Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok
it "should properly validate even with spaces in between", ->
acceptedMimeTypes = "text/html , image/jpeg, application/json"
Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
it "should properly validate extensions", ->
acceptedMimeTypes = "text/html , image/jpeg, .pdf ,.png"
Dropzone.isValidFile({ name: "somxsfsd", type: "text/html" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ name: "somesdfsdf", type: "image/jpeg" }, acceptedMimeTypes).should.be.ok
Dropzone.isValidFile({ name: "somesdfadfadf", type: "application/json" }, acceptedMimeTypes).should.not.be.ok
Dropzone.isValidFile({ name: "some-file file.pdf", type: "random/type" }, acceptedMimeTypes).should.be.ok
# .pdf has to be in the end
Dropzone.isValidFile({ name: "some-file.pdf file.gif", type: "random/type" }, acceptedMimeTypes).should.not.be.ok
Dropzone.isValidFile({ name: "some-file file.png", type: "random/type" }, acceptedMimeTypes).should.be.ok
describe "Dropzone.confirm", ->
beforeEach -> sinon.stub window, "confirm"
afterEach -> window.confirm.restore()
it "should forward to window.confirm and call the callbacks accordingly", ->
accepted = rejected = no
window.confirm.returns yes
Dropzone.confirm "test question", (-> accepted = yes), (-> rejected = yes)
window.confirm.args[0][0].should.equal "test question"
accepted.should.equal yes
rejected.should.equal no
accepted = rejected = no
window.confirm.returns no
Dropzone.confirm "test question 2", (-> accepted = yes), (-> rejected = yes)
window.confirm.args[1][0].should.equal "test question 2"
accepted.should.equal no
rejected.should.equal yes
it "should not error if rejected is not provided", ->
accepted = rejected = no
window.confirm.returns no
Dropzone.confirm "test question", (-> accepted = yes)
window.confirm.args[0][0].should.equal "test question"
# Nothing should have changed since there is no rejected function.
accepted.should.equal no
rejected.should.equal no
describe "Dropzone.getElement() / getElements()", ->
tmpElements = [ ]
beforeEach ->
tmpElements = [ ]
tmpElements.push Dropzone.createElement """<div class="tmptest"></div>"""
tmpElements.push Dropzone.createElement """<div id="tmptest1" class="random"></div>"""
tmpElements.push Dropzone.createElement """<div class="random div"></div>"""
tmpElements.forEach (el) -> document.body.appendChild el
afterEach ->
tmpElements.forEach (el) -> document.body.removeChild el
describe ".getElement()", ->
it "should accept a string", ->
el = Dropzone.getElement ".tmptest"
el.should.equal tmpElements[0]
el = Dropzone.getElement "#tmptest1"
el.should.equal tmpElements[1]
it "should accept a node", ->
el = Dropzone.getElement tmpElements[2]
el.should.equal tmpElements[2]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element."
expect(-> Dropzone.getElement "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElement { "lblasdlfsfl" }, "clickable").to.throw errorMessage
expect(-> Dropzone.getElement [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe ".getElements()", ->
it "should accept a list of strings", ->
els = Dropzone.getElements [ ".tmptest", "#tmptest1" ]
els.should.eql [ tmpElements[0], tmpElements[1] ]
it "should accept a list of nodes", ->
els = Dropzone.getElements [ tmpElements[0], tmpElements[2] ]
els.should.eql [ tmpElements[0], tmpElements[2] ]
it "should accept a mixed list", ->
els = Dropzone.getElements [ "#tmptest1", tmpElements[2] ]
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a string selector", ->
els = Dropzone.getElements ".random"
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a single node", ->
els = Dropzone.getElements tmpElements[1]
els.should.eql [ tmpElements[1] ]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
expect(-> Dropzone.getElements "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElements [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe "constructor()", ->
dropzone = null
afterEach -> dropzone.destroy() if dropzone?
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone "#invalid-element").to.throw "Invalid dropzone element."
it "should throw an exception if assigned twice to the same element", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
expect(-> new Dropzone element, url: "url").to.throw "Dropzone already attached."
it "should throw an exception if both acceptedFiles and acceptedMimeTypes are specified", ->
element = document.createElement "div"
expect(-> dropzone = new Dropzone element, url: "test", acceptedFiles: "param", acceptedMimeTypes: "types").to.throw "You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."
it "should set itself as element.dropzone", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
element.dropzone.should.equal dropzone
it "should add itself to Dropzone.instances", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
Dropzone.instances[Dropzone.instances.length - 1].should.equal dropzone
it "should use the action attribute not the element with the name action", ->
element = Dropzone.createElement """<form action="real-action"><input type="hidden" name="action" value="wrong-action" /></form>"""
dropzone = new Dropzone element
dropzone.options.url.should.equal "real-action"
describe "options", ->
element = null
element2 = null
beforeEach ->
element = document.createElement "div"
element.id = "test-element"
element2 = document.createElement "div"
element2.id = "test-element2"
Dropzone.options.testElement = url: "/some/url", parallelUploads: 10
afterEach -> delete Dropzone.options.testElement
it "should take the options set in Dropzone.options", ->
dropzone = new Dropzone element
dropzone.options.url.should.equal "/some/url"
dropzone.options.parallelUploads.should.equal 10
it "should prefer passed options over Dropzone.options", ->
dropzone = new Dropzone element, url: "/some/other/url"
dropzone.options.url.should.equal "/some/other/url"
it "should take the default options if nothing set in Dropzone.options", ->
dropzone = new Dropzone element2, url: "/some/url"
dropzone.options.parallelUploads.should.equal 2
it "should call the fallback function if forceFallback == true", (done) ->
dropzone = new Dropzone element,
url: "/some/other/url"
forceFallback: on
fallback: -> done()
it "should set acceptedFiles if deprecated acceptedMimetypes option has been passed", ->
dropzone = new Dropzone element,
url: "/some/other/url"
acceptedMimeTypes: "my/type"
dropzone.options.acceptedFiles.should.equal "my/type"
describe "options.clickable", ->
clickableElement = null
dropzone = null
beforeEach ->
clickableElement = document.createElement "div"
clickableElement.className = "some-clickable"
document.body.appendChild clickableElement
afterEach ->
document.body.removeChild clickableElement
dropzone.destroy if dropzone?
it "should use the default element if clickable == true", ->
dropzone = new Dropzone element, clickable: yes
dropzone.clickableElements.should.eql [ dropzone.element ]
it "should lookup the element if clickable is a CSS selector", ->
dropzone = new Dropzone element, clickable: ".some-clickable"
dropzone.clickableElements.should.eql [ clickableElement ]
it "should simply use the provided element", ->
dropzone = new Dropzone element, clickable: clickableElement
dropzone.clickableElements.should.eql [ clickableElement ]
it "should accept multiple clickable elements", ->
dropzone = new Dropzone element, clickable: [ document.body, ".some-clickable" ]
dropzone.clickableElements.should.eql [ document.body, clickableElement ]
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone element, clickable: ".some-invalid-clickable").to.throw "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
describe "init()", ->
describe "clickable", ->
dropzones =
"using acceptedFiles": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptedFiles: "audio/*,video/*" })
"using acceptedMimeTypes": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptedMimeTypes: "audio/*,video/*" })
it "should not add an accept attribute if no acceptParameter", ->
dropzone = new Dropzone (Dropzone.createElement """<form action="/"></form>"""), clickable: yes, acceptParameter: null, acceptedMimeTypes: null
dropzone.hiddenFileInput.hasAttribute("accept").should.be.false
for name, dropzone of dropzones
describe name, ->
do (dropzone) ->
it "should create a hidden file input if clickable", ->
dropzone.hiddenFileInput.should.be.ok
dropzone.hiddenFileInput.tagName.should.equal "INPUT"
it "should use the acceptParameter", ->
dropzone.hiddenFileInput.getAttribute("accept").should.equal "audio/*,video/*"
it "should create a new input element when something is selected to reset the input field", ->
for i in [0..3]
hiddenFileInput = dropzone.hiddenFileInput
event = document.createEvent "HTMLEvents"
event.initEvent "change", true, true
hiddenFileInput.dispatchEvent event
dropzone.hiddenFileInput.should.not.equal hiddenFileInput
Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok
it "should create a .dz-message element", ->
element = Dropzone.createElement """<form class="dropzone" action="/"></form>"""
dropzone = new Dropzone element, clickable: yes, acceptParameter: null, acceptedMimeTypes: null
element.querySelector(".dz-message").should.be.instanceof Element
it "should not create a .dz-message element if there already is one", ->
element = Dropzone.createElement """<form class="dropzone" action="/"></form>"""
msg = Dropzone.createElement """<div class="dz-message">TEST</div>"""
element.appendChild msg
dropzone = new Dropzone element, clickable: yes, acceptParameter: null, acceptedMimeTypes: null
element.querySelector(".dz-message").should.equal msg
element.querySelectorAll(".dz-message").length.should.equal 1
describe "options", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", maxFiles: 3
describe "file specific", ->
file = null
beforeEach ->
file =
name: "PI:NAME:<NAME>END_PI"
size: 2 * 1024 * 1024
dropzone.options.addedfile.call dropzone, file
describe ".addedFile()", ->
it "should properly create the previewElement", ->
file.previewElement.should.be.instanceof Element
file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql "test name"
file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql "<strong>2</strong> MiB"
describe ".error()", ->
it "should properly insert the error", ->
dropzone.options.error.call dropzone, file, "test message"
file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql "test message"
it "should properly insert the error when provided with an object containing the error", ->
dropzone.options.error.call dropzone, file, error: "test message"
file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql "test message"
describe ".thumbnail()", ->
it "should properly insert the error", ->
transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
dropzone.options.thumbnail.call dropzone, file, transparentGif
thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]")
thumbnail.src.should.eql transparentGif
thumbnail.alt.should.eql "test name"
describe ".uploadprogress()", ->
it "should properly set the width", ->
dropzone.options.uploadprogress.call dropzone, file, 0
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "0%"
dropzone.options.uploadprogress.call dropzone, file, 80
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "80%"
dropzone.options.uploadprogress.call dropzone, file, 90
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "90%"
dropzone.options.uploadprogress.call dropzone, file, 100
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "100%"
describe "instance", ->
element = null
dropzone = null
requests = null
beforeEach ->
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
element = Dropzone.createElement """<div></div>"""
document.body.appendChild element
dropzone = new Dropzone element, maxFilesize: 4, maxFiles: 100, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: ->
afterEach ->
document.body.removeChild element
dropzone.destroy()
xhr.restore()
describe ".accept()", ->
it "should pass if the filesize is OK", ->
dropzone.accept { size: 2 * 1024 * 1024, type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
it "shouldn't pass if the filesize is too big", ->
dropzone.accept { size: 10 * 1024 * 1024, type: "audio/mp3" }, (err) -> err.should.eql "File is too big (10MiB). Max filesize: 4MiB."
it "should properly accept files which mime types are listed in acceptedFiles", ->
dropzone.accept { type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "image/png" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "audio/wav" }, (err) -> expect(err).to.be.undefined
it "should properly reject files when the mime type isn't listed in acceptedFiles", ->
dropzone.accept { type: "image/jpeg" }, (err) -> err.should.eql "You can't upload files of this type."
it "should fail if maxFiles has been exceeded and call the event maxfilesexceeded", ->
sinon.stub dropzone, "getAcceptedFiles"
file = { type: "audio/mp3" }
dropzone.getAcceptedFiles.returns { length: 99 }
dropzone.options.dictMaxFilesExceeded = "You can only upload {{maxFiles}} files."
called = no
dropzone.on "maxfilesexceeded", (lfile) ->
lfile.should.equal file
called = yes
dropzone.accept file, (err) -> expect(err).to.be.undefined
called.should.not.be.ok
dropzone.getAcceptedFiles.returns { length: 100 }
dropzone.accept file, (err) -> expect(err).to.equal "You can only upload 100 files."
called.should.be.ok
dropzone.getAcceptedFiles.restore()
it "should properly handle if maxFiles is 0", ->
file = { type: "audio/mp3" }
dropzone.options.maxFiles = 0
called = no
dropzone.on "maxfilesexceeded", (lfile) ->
lfile.should.equal file
called = yes
dropzone.accept file, (err) -> expect(err).to.equal "You can not upload any more files."
called.should.be.ok
describe ".removeFile()", ->
it "should abort uploading if file is currently being uploaded", (done) ->
mockFile = getMockFile()
dropzone.uploadFile = (file) ->
dropzone.accept = (file, done) -> done()
sinon.stub dropzone, "cancelUpload"
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.getUploadingFiles()[0].should.equal mockFile
dropzone.cancelUpload.callCount.should.equal 0
dropzone.removeFile mockFile
dropzone.cancelUpload.callCount.should.equal 1
done()
, 10
describe ".cancelUpload()", ->
it "should properly cancel upload if file currently uploading", (done) ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.getUploadingFiles()[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.getUploadingFiles().length.should.equal 0
dropzone.getQueuedFiles().length.should.equal 0
done()
, 10
it "should properly cancel the upload if file is not yet uploading", ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.parallelUploads = 0
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.QUEUED
dropzone.getQueuedFiles()[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.getQueuedFiles().length.should.equal 0
dropzone.getUploadingFiles().length.should.equal 0
it "should call processQueue()", (done) ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.parallelUploads = 0
sinon.spy dropzone, "processQueue"
dropzone.addFile mockFile
setTimeout ->
dropzone.processQueue.callCount.should.equal 1
dropzone.cancelUpload mockFile
dropzone.processQueue.callCount.should.equal 2
done()
, 10
it "should properly cancel all files with the same XHR if uploadMultiple is true", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.uploadMultiple = yes
dropzone.options.parallelUploads = 3
sinon.spy dropzone, "processFiles"
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
setTimeout ->
dropzone.processFiles.callCount.should.equal 1
sinon.spy mock1.xhr, "abort"
dropzone.cancelUpload mock1
expect(mock1.xhr == mock2.xhr == mock3.xhr).to.be.ok
mock1.status.should.equal Dropzone.CANCELED
mock2.status.should.equal Dropzone.CANCELED
mock3.status.should.equal Dropzone.CANCELED
# The XHR should only be aborted once!
mock1.xhr.abort.callCount.should.equal 1
done()
, 10
describe ".disable()", ->
it "should properly cancel all pending uploads", (done) ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
setTimeout ->
dropzone.getUploadingFiles().length.should.equal 1
dropzone.getQueuedFiles().length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy requests[0], "abort"
requests[0].abort.callCount.should.equal 0
dropzone.disable()
requests[0].abort.callCount.should.equal 1
dropzone.getUploadingFiles().length.should.equal 0
dropzone.getQueuedFiles().length.should.equal 0
dropzone.files.length.should.equal 2
dropzone.files[0].status.should.equal Dropzone.CANCELED
dropzone.files[1].status.should.equal Dropzone.CANCELED
done()
, 10
describe ".destroy()", ->
it "should properly cancel all pending uploads and remove all file references", (done) ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
setTimeout ->
dropzone.getUploadingFiles().length.should.equal 1
dropzone.getQueuedFiles().length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy dropzone, "disable"
dropzone.destroy()
dropzone.disable.callCount.should.equal 1
element.should.not.have.property "dropzone"
done()
, 10
it "should be able to create instance of dropzone on the same element after destroy", ->
dropzone.destroy()
( -> new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: -> ).should.not.throw( Error )
it "should remove itself from Dropzone.instances", ->
(Dropzone.instances.indexOf(dropzone) != -1).should.be.ok
dropzone.destroy()
(Dropzone.instances.indexOf(dropzone) == -1).should.be.ok
describe ".filesize()", ->
it "should convert to KiloBytes, etc.. not KibiBytes", ->
# dropzone.filesize(2 * 1000 * 1000).should.eql "<strong>1.9</strong> MiB"
dropzone.filesize(2 * 1024 * 1024).should.eql "<strong>2</strong> MiB"
dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql "<strong>1.9</strong> GiB"
dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql "<strong>2</strong> GiB"
describe "._updateMaxFilesReachedClass()", ->
it "should properly add the dz-max-files-reached class", ->
dropzone.getAcceptedFiles = -> length: 10
dropzone.options.maxFiles = 10
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok
dropzone._updateMaxFilesReachedClass()
dropzone.element.classList.contains("dz-max-files-reached").should.be.ok
it "should fire the 'maxfilesreached' event when appropriate", ->
spy = sinon.spy()
dropzone.on "maxfilesreached", -> spy()
dropzone.getAcceptedFiles = -> length: 9
dropzone.options.maxFiles = 10
dropzone._updateMaxFilesReachedClass()
spy.should.not.have.been.called
dropzone.getAcceptedFiles = -> length: 10
dropzone._updateMaxFilesReachedClass()
spy.should.have.been.called
dropzone.getAcceptedFiles = -> length: 11
dropzone._updateMaxFilesReachedClass()
spy.should.have.been.calledOnce #ie, it has not been called again
it "should properly remove the dz-max-files-reached class", ->
dropzone.getAcceptedFiles = -> length: 10
dropzone.options.maxFiles = 10
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok
dropzone._updateMaxFilesReachedClass()
dropzone.element.classList.contains("dz-max-files-reached").should.be.ok
dropzone.getAcceptedFiles = -> length: 9
dropzone._updateMaxFilesReachedClass()
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok
describe "events", ->
describe "progress updates", ->
it "should properly emit a totaluploadprogress event", (done) ->
dropzone.files = [
{
size: 1990
accepted: true
status: Dropzone.UPLOADING
upload:
progress: 20
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 400
}
{
size: 1990
accepted: true
status: Dropzone.UPLOADING
upload:
progress: 10
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 200
}
]
_called = 0
dropzone.on "totaluploadprogress", (progress) ->
progress.should.equal totalProgressExpectation
done() if ++_called == 3
totalProgressExpectation = 15
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 97.5
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 1900
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 100
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 2000
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.emit "uploadprogress", { }
# Just so the afterEach hook doesn't try to cancel them.
dropzone.files[0].status = Dropzone.CANCELED
dropzone.files[1].status = Dropzone.CANCELED
describe "helper function", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "url"
describe "getExistingFallback()", ->
it "should return undefined if no fallback", ->
expect(dropzone.getExistingFallback()).to.equal undefined
it "should only return the fallback element if it contains exactly fallback", ->
element.appendChild Dropzone.createElement """<form class="fallbacks"></form>"""
element.appendChild Dropzone.createElement """<form class="sfallback"></form>"""
expect(dropzone.getExistingFallback()).to.equal undefined
it "should return divs as fallback", ->
fallback = Dropzone.createElement """<form class=" abc fallback test "></form>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
it "should return forms as fallback", ->
fallback = Dropzone.createElement """<div class=" abc fallback test "></div>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
describe "getFallbackForm()", ->
it "should use the paramName without [] if uploadMultiple is false", ->
dropzone.options.uploadMultiple = false
dropzone.options.paramName = "myFile"
fallback = dropzone.getFallbackForm()
fileInput = fallback.querySelector "input[type=file]"
fileInput.name.should.equal "myFile"
it "should properly add [] to the file name if uploadMultiple is true", ->
dropzone.options.uploadMultiple = yes
dropzone.options.paramName = "myFile"
fallback = dropzone.getFallbackForm()
fileInput = fallback.querySelector "input[type=file]"
fileInput.name.should.equal "myFile[]"
describe "getAcceptedFiles() / getRejectedFiles()", ->
mock1 = mock2 = mock3 = mock4 = null
beforeEach ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, done) ->
if file in [ mock1, mock3 ]
done()
else
done "error"
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
it "getAcceptedFiles() should only return accepted files", ->
dropzone.getAcceptedFiles().should.eql [ mock1, mock3 ]
it "getRejectedFiles() should only return rejected files", ->
dropzone.getRejectedFiles().should.eql [ mock2, mock4 ]
describe "getQueuedFiles()", ->
it "should return all files with the status Dropzone.QUEUED", ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, done) -> file.done = done
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getQueuedFiles().should.eql [ ]
mock1.done()
mock3.done()
dropzone.getQueuedFiles().should.eql [ mock1, mock3 ]
mock1.status.should.equal Dropzone.QUEUED
mock3.status.should.equal Dropzone.QUEUED
mock2.status.should.equal Dropzone.ADDED
mock4.status.should.equal Dropzone.ADDED
describe "getUploadingFiles()", ->
it "should return all files with the status Dropzone.UPLOADING", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, _done) -> file.done = _done
dropzone.uploadFile = ->
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getUploadingFiles().should.eql [ ]
mock1.done()
mock3.done()
setTimeout (->
dropzone.getUploadingFiles().should.eql [ mock1, mock3 ]
mock1.status.should.equal Dropzone.UPLOADING
mock3.status.should.equal Dropzone.UPLOADING
mock2.status.should.equal Dropzone.ADDED
mock4.status.should.equal Dropzone.ADDED
done()
), 10
describe "getActiveFiles()", ->
it "should return all files with the status Dropzone.UPLOADING or Dropzone.QUEUED", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, _done) -> file.done = _done
dropzone.uploadFile = ->
dropzone.options.parallelUploads = 2
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getActiveFiles().should.eql [ ]
mock1.done()
mock3.done()
mock4.done()
setTimeout (->
dropzone.getActiveFiles().should.eql [ mock1, mock3, mock4 ]
mock1.status.should.equal Dropzone.UPLOADING
mock3.status.should.equal Dropzone.UPLOADING
mock2.status.should.equal Dropzone.ADDED
mock4.status.should.equal Dropzone.QUEUED
done()
), 10
describe "getFilesWithStatus()", ->
it "should return all files with provided status", ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock4 = getMockFile()
dropzone.options.accept = (file, _done) -> file.done = _done
dropzone.uploadFile = ->
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.addFile mock4
dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql [ mock1, mock2, mock3, mock4 ]
mock1.status = Dropzone.UPLOADING
mock3.status = Dropzone.QUEUED
mock4.status = Dropzone.QUEUED
dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql [ mock2 ]
dropzone.getFilesWithStatus(Dropzone.UPLOADING).should.eql [ mock1 ]
dropzone.getFilesWithStatus(Dropzone.QUEUED).should.eql [ mock3, mock4 ]
describe "file handling", ->
mockFile = null
dropzone = null
beforeEach ->
mockFile = getMockFile()
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "/the/url"
afterEach ->
dropzone.destroy()
describe "addFile()", ->
it "should properly set the status of the file", ->
doneFunction = null
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.QUEUED
mockFile = getMockFile()
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction("error")
mockFile.status.should.eql Dropzone.ERROR
it "should properly set the status of the file if autoProcessQueue is false and not call processQueue", (done) ->
doneFunction = null
dropzone.options.autoProcessQueue = false
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
sinon.stub dropzone, "processQueue"
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.QUEUED
dropzone.processQueue.callCount.should.equal 0
setTimeout (->
dropzone.processQueue.callCount.should.equal 0
done()
), 10
it "should not add the file to the queue if autoQueue is false", ->
doneFunction = null
dropzone.options.autoQueue = false
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.ADDED
it "should create a remove link if configured to do so", ->
dropzone.options.addRemoveLinks = true
dropzone.processFile = ->
dropzone.uploadFile = ->
sinon.stub dropzone, "processQueue"
dropzone.addFile mockFile
dropzone.files[0].previewElement.querySelector("a[data-dz-remove].dz-remove").should.be.ok
it "should attach an event handler to data-dz-remove links", ->
dropzone.options.previewTemplate = """
<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-filename"><span data-dz-name></span></div>
<div class="dz-size" data-dz-size></div>
<img data-dz-thumbnail />
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-success-mark"><span>✔</span></div>
<div class="dz-error-mark"><span>✘</span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<a class="link1" data-dz-remove></a>
<a class="link2" data-dz-remove></a>
</div>
"""
sinon.stub dropzone, "processQueue"
dropzone.addFile mockFile
file = dropzone.files[0]
removeLink1 = file.previewElement.querySelector("a[data-dz-remove].link1")
removeLink2 = file.previewElement.querySelector("a[data-dz-remove].link2")
sinon.stub dropzone, "removeFile"
event = document.createEvent "HTMLEvents"
event.initEvent "click", true, true
removeLink1.dispatchEvent event
dropzone.removeFile.callCount.should.eql 1
event = document.createEvent "HTMLEvents"
event.initEvent "click", true, true
removeLink2.dispatchEvent event
dropzone.removeFile.callCount.should.eql 2
describe "thumbnails", ->
it "should properly queue the thumbnail creation", (done) ->
doneFunction = null
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock1.type = "image/jpg"
mock2.type = "image/jpg"
mock3.type = "image/jpg"
dropzone.on "thumbnail", ->
console.log "HII"
ct_file = ct_callback = null
dropzone.createThumbnail = (file, callback) ->
ct_file = file
ct_callback = callback
sinon.spy dropzone, "createThumbnail"
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
dropzone.files.length.should.eql 3
setTimeout (->
dropzone.createThumbnail.callCount.should.eql 1
mock1.should.equal ct_file
ct_callback()
dropzone.createThumbnail.callCount.should.eql 2
mock2.should.equal ct_file
ct_callback()
dropzone.createThumbnail.callCount.should.eql 3
mock3.should.equal ct_file
done()
), 10
# dropzone.addFile mock1
describe "enqueueFile()", ->
it "should be wrapped by enqueueFiles()", ->
sinon.stub dropzone, "enqueueFile"
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
dropzone.enqueueFiles [ mock1, mock2, mock3 ]
dropzone.enqueueFile.callCount.should.equal 3
dropzone.enqueueFile.args[0][0].should.equal mock1
dropzone.enqueueFile.args[1][0].should.equal mock2
dropzone.enqueueFile.args[2][0].should.equal mock3
it "should fail if the file has already been processed", ->
mockFile.status = Dropzone.ERROR
expect((-> dropzone.enqueueFile(mockFile))).to.throw "This file can't be queued because it has already been processed or was rejected."
mockFile.status = Dropzone.COMPLETE
expect((-> dropzone.enqueueFile(mockFile))).to.throw "This file can't be queued because it has already been processed or was rejected."
mockFile.status = Dropzone.UPLOADING
expect((-> dropzone.enqueueFile(mockFile))).to.throw "This file can't be queued because it has already been processed or was rejected."
it "should set the status to QUEUED and call processQueue asynchronously if everything's ok", (done) ->
mockFile.status = Dropzone.ADDED
sinon.stub dropzone, "processQueue"
dropzone.processQueue.callCount.should.equal 0
dropzone.enqueueFile mockFile
mockFile.status.should.equal Dropzone.QUEUED
dropzone.processQueue.callCount.should.equal 0
setTimeout ->
dropzone.processQueue.callCount.should.equal 1
done()
, 10
describe "uploadFiles()", ->
requests = null
beforeEach ->
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
afterEach ->
xhr.restore()
# Removed this test because multiple filenames can be transmitted now
# it "should properly urlencode the filename for the headers"
it "should be wrapped by uploadFile()", ->
sinon.stub dropzone, "uploadFiles"
dropzone.uploadFile mockFile
dropzone.uploadFiles.callCount.should.equal 1
dropzone.uploadFiles.calledWith([ mockFile ]).should.be.ok
it "should ignore the onreadystate callback if readyState != 4", (done) ->
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests[0].status = 200
requests[0].readyState = 3
requests[0].onload()
mockFile.status.should.eql Dropzone.UPLOADING
requests[0].readyState = 4
requests[0].onload()
mockFile.status.should.eql Dropzone.SUCCESS
done()
, 10
it "should emit error and errormultiple when response was not OK", (done) ->
dropzone.options.uploadMultiple = yes
error = no
errormultiple = no
complete = no
completemultiple = no
dropzone.on "error", -> error = yes
dropzone.on "errormultiple", -> errormultiple = yes
dropzone.on "complete", -> complete = yes
dropzone.on "completemultiple", -> completemultiple = yes
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests[0].status = 400
requests[0].readyState = 4
requests[0].onload()
expect(yes == error == errormultiple == complete == completemultiple).to.be.ok
done()
, 10
it "should include hidden files in the form and unchecked checkboxes and radiobuttons should be excluded", (done) ->
element = Dropzone.createElement """<form action="/the/url">
<input type="hidden" name="test" value="hidden" />
<input type="checkbox" name="unchecked" value="1" />
<input type="checkbox" name="checked" value="value1" checked="checked" />
<input type="radio" value="radiovalue1" name="radio1" />
<input type="radio" value="radiovalue2" name="radio1" checked="checked" />
<select name="select"><option value="1">1</option><option value="2" selected>2</option></select>
</form>"""
dropzone = new Dropzone element, url: "/the/url"
formData = null
dropzone.on "sending", (file, xhr, tformData) ->
formData = tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
dropzone.addFile mock1
setTimeout ->
formData.append.callCount.should.equal 5
formData.append.args[0][0].should.eql "test"
formData.append.args[0][1].should.eql "hidden"
formData.append.args[1][0].should.eql "checked"
formData.append.args[1][1].should.eql "value1"
formData.append.args[2][0].should.eql "radio1"
formData.append.args[2][1].should.eql "radiovalue2"
formData.append.args[3][0].should.eql "select"
formData.append.args[3][1].should.eql "2"
formData.append.args[4][0].should.eql "file"
formData.append.args[4][1].should.equal mock1
# formData.append.args[1][0].should.eql "myName[]"
done()
, 10
it "should all values of a select that has the multiple attribute", (done) ->
element = Dropzone.createElement """<form action="/the/url">
<select name="select" multiple>
<option value="value1">1</option>
<option value="value2" selected>2</option>
<option value="value3">3</option>
<option value="value4" selected>4</option>
</select>
</form>"""
dropzone = new Dropzone element, url: "/the/url"
formData = null
dropzone.on "sending", (file, xhr, tformData) ->
formData = tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
dropzone.addFile mock1
setTimeout ->
formData.append.callCount.should.equal 3
formData.append.args[0][0].should.eql "select"
formData.append.args[0][1].should.eql "value2"
formData.append.args[1][0].should.eql "select"
formData.append.args[1][1].should.eql "value4"
formData.append.args[2][0].should.eql "file"
formData.append.args[2][1].should.equal mock1
# formData.append.args[1][0].should.eql "myName[]"
done()
, 10
describe "settings()", ->
it "should correctly set `withCredentials` on the xhr object", ->
dropzone.uploadFile mockFile
requests.length.should.eql 1
requests[0].withCredentials.should.eql no
dropzone.options.withCredentials = yes
dropzone.uploadFile mockFile
requests.length.should.eql 2
requests[1].withCredentials.should.eql yes
it "should correctly override headers on the xhr object", ->
dropzone.options.headers = {"Foo-Header": "foobar"}
dropzone.uploadFile mockFile
requests[0].requestHeaders["Foo-Header"].should.eql 'foobar'
it "should properly use the paramName without [] as file upload if uploadMultiple is false", (done) ->
dropzone.options.uploadMultiple = false
dropzone.options.paramName = "PI:NAME:<NAME>END_PIName"
formData = [ ]
sendingCount = 0
dropzone.on "sending", (files, xhr, tformData) ->
sendingCount++
formData.push tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
mock2 = getMockFile()
dropzone.addFile mock1
dropzone.addFile mock2
setTimeout ->
sendingCount.should.equal 2
formData.length.should.equal 2
formData[0].append.callCount.should.equal 1
formData[1].append.callCount.should.equal 1
formData[0].append.args[0][0].should.eql "myName"
formData[0].append.args[0][0].should.eql "PI:NAME:<NAME>END_PI"
done()
, 10
it "should properly use the paramName with [] as file upload if uploadMultiple is true", (done) ->
dropzone.options.uploadMultiple = yes
dropzone.options.paramName = "PI:NAME:<NAME>END_PI"
formData = null
sendingMultipleCount = 0
sendingCount = 0
dropzone.on "sending", (file, xhr, tformData) -> sendingCount++
dropzone.on "sendingmultiple", (files, xhr, tformData) ->
sendingMultipleCount++
formData = tformData
sinon.spy tformData, "append"
mock1 = getMockFile()
mock2 = getMockFile()
dropzone.addFile mock1
dropzone.addFile mock2
setTimeout ->
sendingCount.should.equal 2
sendingMultipleCount.should.equal 1
dropzone.uploadFiles [ mock1, mock2 ]
formData.append.callCount.should.equal 2
formData.append.args[0][0].should.eql "myName[]"
formData.append.args[1][0].should.eql "myName[]"
done()
, 10
describe "should properly set status of file", ->
it "should correctly set `withCredentials` on the xhr object", (done) ->
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 1
requests[0].status = 400
requests[0].readyState = 4
requests[0].onload()
mockFile.status.should.eql Dropzone.ERROR
mockFile = getMockFile()
dropzone.addFile mockFile
setTimeout ->
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 2
requests[1].status = 200
requests[1].readyState = 4
requests[1].onload()
mockFile.status.should.eql Dropzone.SUCCESS
done()
, 10
, 10
describe "complete file", ->
it "should properly emit the queuecomplete event when the complete queue is finished", (done) ->
mock1 = getMockFile()
mock2 = getMockFile()
mock3 = getMockFile()
mock1.status = Dropzone.ADDED
mock2.status = Dropzone.ADDED
mock3.status = Dropzone.ADDED
mock1.name = "mock1"
mock2.name = "mock2"
mock3.name = "mock3"
dropzone.uploadFiles = (files) ->
setTimeout (=>
@_finished files, null, null
), 1
completedFiles = 0
dropzone.on "complete", (file) ->
completedFiles++
dropzone.on "queuecomplete", ->
completedFiles.should.equal 3
done()
dropzone.addFile mock1
dropzone.addFile mock2
dropzone.addFile mock3
|
[
{
"context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> \n© Copyright 2006 Goog",
"end": 39,
"score": 0.9999008178710938,
"start": 26,
"tag": "NAME",
"value": "Stephan Jorek"
},
{
"context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> \n© Copyright 2006 Google Inc. <http://www.googl",
"end": 64,
"score": 0.9999348521232605,
"start": 41,
"tag": "EMAIL",
"value": "stephan.jorek@gmail.com"
},
{
"context": " Utility\n# @namespace goatee.Core\n# @author Steffen Meschkat <mesch@google.com>\n# @author Stephan Jorek ",
"end": 1145,
"score": 0.9999009966850281,
"start": 1129,
"tag": "NAME",
"value": "Steffen Meschkat"
},
{
"context": "ace goatee.Core\n# @author Steffen Meschkat <mesch@google.com>\n# @author Stephan Jorek <stephan.jorek@g",
"end": 1164,
"score": 0.999932587146759,
"start": 1148,
"tag": "EMAIL",
"value": "mesch@google.com"
},
{
"context": "Steffen Meschkat <mesch@google.com>\n# @author Stephan Jorek <stephan.jorek@gmail.com>\n# @type {Obje",
"end": 1193,
"score": 0.9998968243598938,
"start": 1180,
"tag": "NAME",
"value": "Stephan Jorek"
},
{
"context": "esch@google.com>\n# @author Stephan Jorek <stephan.jorek@gmail.com>\n# @type {Object}\nexports.Utility = Utility",
"end": 1222,
"score": 0.9999343156814575,
"start": 1199,
"tag": "EMAIL",
"value": "stephan.jorek@gmail.com"
}
] | src/Core/Utility.coffee | sjorek/goatee.js | 0 | ###
© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com>
© Copyright 2006 Google Inc. <http://www.google.com>
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.
###
#~ require
{Constants:{
CHAR_dash,
TYPE_number,
REGEXP_trim,
REGEXP_trimLeft,
REGEXP_trimRight,
REGEXP_camelize,
REGEXP_dashify
}} = require './Constants'
#~ export
exports = module?.exports ? this
# Utility
# ================================
# --------------------------------
# This objeect provides a collection of miscellaneous utility functions
# referenced in the main source files.
#
# @public
# @module Utility
# @namespace goatee.Core
# @author Steffen Meschkat <mesch@google.com>
# @author Stephan Jorek <stephan.jorek@gmail.com>
# @type {Object}
exports.Utility = Utility =
# --------------------------------
# Detect if an object looks like an Array.
# Note that instanceof Array is not robust; for example an Array
# created in another iframe fails instanceof Array.
#
# @static
# @public
# @method isArray
# @param {mixed} value Object to interrogate
# @return {Boolean} Is the object an array?
isArray: (value) ->
value.length? and typeof value.length is TYPE_number
# --------------------------------
# Finds a slice of an array.
#
# @static
# @public
# @method arraySlice
# @param {Array} array An array to be sliced.
# @param {Number} start The start of the slice.
# @param {Number} [end=undefined] The end of the slice.
# @return {Array} A sliced array from start to end.
arraySlice: (array, start, end) ->
# We use
#
# `return Function.prototype.call.apply(Array.prototype.slice, arguments);`
#
# instead of the simpler
#
# `return Array.prototype.slice.call(array, start, opt_end);`
#
# here because of a bug in the FF ≤ 3.6 and IE ≤ 7 implementations of
# `Array.prototype.slice` which causes this function to return
# an empty list if end is not provided.
Function.prototype.call.apply Array.prototype.slice, arguments
# --------------------------------
# Clears the array by setting the length property to 0. This usually
# works, and if it should turn out not to work everywhere, here would
# be the place to implement the <del>browser</del> specific workaround.
#
# @static
# @public
# @method arrayClear
# @param {Array} array Array to be cleared.
arrayClear: (array) ->
array.length = 0
return
# --------------------------------
# Jscompiler wrapper for parseInt() with base 10.
#
# @static
# @public
# @method parseInt10
# @param {String} string String representation of a number.
# @return {Number} The integer contained in string,
# converted to base 10.
parseInt10: (string) ->
parseInt(string, 10)
# --------------------------------
# Binds `this` within the given method to an object, but ignores all arguments
# passed to the resulting function, i.e. `args` are all the arguments that
# method is invoked with when invoking the bound function.
#
# @static
# @public
# @method bind
# @param {Object} [object] If object isn't `null` it becomes the method's
# call target to bind to.
# @param {Function} method The target method to bind.
# @param {mixed...} [args] The arguments to bind.
# @return {Function} Method with the target object bound and
# curried with provided arguments.
bind: (object, method, args...) ->
return -> method.apply(object, args)
# --------------------------------
# Trim whitespace from begin and end of string.
#
# @static
# @public
# @method trim
# @param {String} string Input string.
# @return {String} Trimmed string.
# @see `testStringTrim();`
trim: if String::trim?
then (string) -> string.trim()
# Is `Utility.trimRight(Utility.trimLeft(string));` an alternative ?
else (string) -> string.replace REGEXP_trim, ''
# --------------------------------
# Trim whitespace from beginning of string.
#
# @static
# @public
# @method trimLeft
# @param {String} string Input string.
# @return {String} Left trimmed string.
# @see `testStringTrimLeft();`
trimLeft: if String::trimLeft?
then (string) -> string.trimLeft()
else (string) -> string.replace REGEXP_trimLeft, ''
# --------------------------------
# Trim whitespace from end of string.
#
# @static
# @public
# @method trimRight
# @param {String} string Input string.
# @return {String} Right trimmed string.
# @see `testStringTrimRight();`
trimRight: if String::trimRight?
then (string) -> string.trimRight()
else (string) -> string.replace REGEXP_trimRight, ''
# --------------------------------
# Convert “a-property-name” to “aPropertyName”
#
# @static
# @public
# @method camelize
# @param {String} string Input string.
# @return {String} Camelized string.
camelize: do ->
# Internal camelize-helper function
#
# @private
# @method _camelize
# @param {String} match
# @param {String} char
# @param {Number} index
# @param {String} string
# @return {String} Camelized string fragment.
_camelize = (match, char, index, string) -> char.toUpperCase()
# The camelize implementation
(string) -> string.replace REGEXP_camelize, _camelize
# --------------------------------
# Convert “aPropertyName” to “a-property-name”
#
# @static
# @public
# @method dashify
# @param {String} string Input string.
# @return {String} Dashed string.
dashify: do ->
# Internal dashify-helper function
#
# @private
# @method _dashify
# @param {String} match
# @param {String} char
# @param {String} camel
# @param {Number} index
# @param {String} string
# @return {String} Dashed string fragment.
_dashify = (match, char, camel, index, string) ->
char + CHAR_dash + camel.toLowerCase()
# The dashify implementation
(string) -> string.replace REGEXP_dashify, _dashify
| 65021 | ###
© Copyright 2013-2014 <NAME> <<EMAIL>>
© Copyright 2006 Google Inc. <http://www.google.com>
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.
###
#~ require
{Constants:{
CHAR_dash,
TYPE_number,
REGEXP_trim,
REGEXP_trimLeft,
REGEXP_trimRight,
REGEXP_camelize,
REGEXP_dashify
}} = require './Constants'
#~ export
exports = module?.exports ? this
# Utility
# ================================
# --------------------------------
# This objeect provides a collection of miscellaneous utility functions
# referenced in the main source files.
#
# @public
# @module Utility
# @namespace goatee.Core
# @author <NAME> <<EMAIL>>
# @author <NAME> <<EMAIL>>
# @type {Object}
exports.Utility = Utility =
# --------------------------------
# Detect if an object looks like an Array.
# Note that instanceof Array is not robust; for example an Array
# created in another iframe fails instanceof Array.
#
# @static
# @public
# @method isArray
# @param {mixed} value Object to interrogate
# @return {Boolean} Is the object an array?
isArray: (value) ->
value.length? and typeof value.length is TYPE_number
# --------------------------------
# Finds a slice of an array.
#
# @static
# @public
# @method arraySlice
# @param {Array} array An array to be sliced.
# @param {Number} start The start of the slice.
# @param {Number} [end=undefined] The end of the slice.
# @return {Array} A sliced array from start to end.
arraySlice: (array, start, end) ->
# We use
#
# `return Function.prototype.call.apply(Array.prototype.slice, arguments);`
#
# instead of the simpler
#
# `return Array.prototype.slice.call(array, start, opt_end);`
#
# here because of a bug in the FF ≤ 3.6 and IE ≤ 7 implementations of
# `Array.prototype.slice` which causes this function to return
# an empty list if end is not provided.
Function.prototype.call.apply Array.prototype.slice, arguments
# --------------------------------
# Clears the array by setting the length property to 0. This usually
# works, and if it should turn out not to work everywhere, here would
# be the place to implement the <del>browser</del> specific workaround.
#
# @static
# @public
# @method arrayClear
# @param {Array} array Array to be cleared.
arrayClear: (array) ->
array.length = 0
return
# --------------------------------
# Jscompiler wrapper for parseInt() with base 10.
#
# @static
# @public
# @method parseInt10
# @param {String} string String representation of a number.
# @return {Number} The integer contained in string,
# converted to base 10.
parseInt10: (string) ->
parseInt(string, 10)
# --------------------------------
# Binds `this` within the given method to an object, but ignores all arguments
# passed to the resulting function, i.e. `args` are all the arguments that
# method is invoked with when invoking the bound function.
#
# @static
# @public
# @method bind
# @param {Object} [object] If object isn't `null` it becomes the method's
# call target to bind to.
# @param {Function} method The target method to bind.
# @param {mixed...} [args] The arguments to bind.
# @return {Function} Method with the target object bound and
# curried with provided arguments.
bind: (object, method, args...) ->
return -> method.apply(object, args)
# --------------------------------
# Trim whitespace from begin and end of string.
#
# @static
# @public
# @method trim
# @param {String} string Input string.
# @return {String} Trimmed string.
# @see `testStringTrim();`
trim: if String::trim?
then (string) -> string.trim()
# Is `Utility.trimRight(Utility.trimLeft(string));` an alternative ?
else (string) -> string.replace REGEXP_trim, ''
# --------------------------------
# Trim whitespace from beginning of string.
#
# @static
# @public
# @method trimLeft
# @param {String} string Input string.
# @return {String} Left trimmed string.
# @see `testStringTrimLeft();`
trimLeft: if String::trimLeft?
then (string) -> string.trimLeft()
else (string) -> string.replace REGEXP_trimLeft, ''
# --------------------------------
# Trim whitespace from end of string.
#
# @static
# @public
# @method trimRight
# @param {String} string Input string.
# @return {String} Right trimmed string.
# @see `testStringTrimRight();`
trimRight: if String::trimRight?
then (string) -> string.trimRight()
else (string) -> string.replace REGEXP_trimRight, ''
# --------------------------------
# Convert “a-property-name” to “aPropertyName”
#
# @static
# @public
# @method camelize
# @param {String} string Input string.
# @return {String} Camelized string.
camelize: do ->
# Internal camelize-helper function
#
# @private
# @method _camelize
# @param {String} match
# @param {String} char
# @param {Number} index
# @param {String} string
# @return {String} Camelized string fragment.
_camelize = (match, char, index, string) -> char.toUpperCase()
# The camelize implementation
(string) -> string.replace REGEXP_camelize, _camelize
# --------------------------------
# Convert “aPropertyName” to “a-property-name”
#
# @static
# @public
# @method dashify
# @param {String} string Input string.
# @return {String} Dashed string.
dashify: do ->
# Internal dashify-helper function
#
# @private
# @method _dashify
# @param {String} match
# @param {String} char
# @param {String} camel
# @param {Number} index
# @param {String} string
# @return {String} Dashed string fragment.
_dashify = (match, char, camel, index, string) ->
char + CHAR_dash + camel.toLowerCase()
# The dashify implementation
(string) -> string.replace REGEXP_dashify, _dashify
| true | ###
© Copyright 2013-2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
© Copyright 2006 Google Inc. <http://www.google.com>
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.
###
#~ require
{Constants:{
CHAR_dash,
TYPE_number,
REGEXP_trim,
REGEXP_trimLeft,
REGEXP_trimRight,
REGEXP_camelize,
REGEXP_dashify
}} = require './Constants'
#~ export
exports = module?.exports ? this
# Utility
# ================================
# --------------------------------
# This objeect provides a collection of miscellaneous utility functions
# referenced in the main source files.
#
# @public
# @module Utility
# @namespace goatee.Core
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# @type {Object}
exports.Utility = Utility =
# --------------------------------
# Detect if an object looks like an Array.
# Note that instanceof Array is not robust; for example an Array
# created in another iframe fails instanceof Array.
#
# @static
# @public
# @method isArray
# @param {mixed} value Object to interrogate
# @return {Boolean} Is the object an array?
isArray: (value) ->
value.length? and typeof value.length is TYPE_number
# --------------------------------
# Finds a slice of an array.
#
# @static
# @public
# @method arraySlice
# @param {Array} array An array to be sliced.
# @param {Number} start The start of the slice.
# @param {Number} [end=undefined] The end of the slice.
# @return {Array} A sliced array from start to end.
arraySlice: (array, start, end) ->
# We use
#
# `return Function.prototype.call.apply(Array.prototype.slice, arguments);`
#
# instead of the simpler
#
# `return Array.prototype.slice.call(array, start, opt_end);`
#
# here because of a bug in the FF ≤ 3.6 and IE ≤ 7 implementations of
# `Array.prototype.slice` which causes this function to return
# an empty list if end is not provided.
Function.prototype.call.apply Array.prototype.slice, arguments
# --------------------------------
# Clears the array by setting the length property to 0. This usually
# works, and if it should turn out not to work everywhere, here would
# be the place to implement the <del>browser</del> specific workaround.
#
# @static
# @public
# @method arrayClear
# @param {Array} array Array to be cleared.
arrayClear: (array) ->
array.length = 0
return
# --------------------------------
# Jscompiler wrapper for parseInt() with base 10.
#
# @static
# @public
# @method parseInt10
# @param {String} string String representation of a number.
# @return {Number} The integer contained in string,
# converted to base 10.
parseInt10: (string) ->
parseInt(string, 10)
# --------------------------------
# Binds `this` within the given method to an object, but ignores all arguments
# passed to the resulting function, i.e. `args` are all the arguments that
# method is invoked with when invoking the bound function.
#
# @static
# @public
# @method bind
# @param {Object} [object] If object isn't `null` it becomes the method's
# call target to bind to.
# @param {Function} method The target method to bind.
# @param {mixed...} [args] The arguments to bind.
# @return {Function} Method with the target object bound and
# curried with provided arguments.
bind: (object, method, args...) ->
return -> method.apply(object, args)
# --------------------------------
# Trim whitespace from begin and end of string.
#
# @static
# @public
# @method trim
# @param {String} string Input string.
# @return {String} Trimmed string.
# @see `testStringTrim();`
trim: if String::trim?
then (string) -> string.trim()
# Is `Utility.trimRight(Utility.trimLeft(string));` an alternative ?
else (string) -> string.replace REGEXP_trim, ''
# --------------------------------
# Trim whitespace from beginning of string.
#
# @static
# @public
# @method trimLeft
# @param {String} string Input string.
# @return {String} Left trimmed string.
# @see `testStringTrimLeft();`
trimLeft: if String::trimLeft?
then (string) -> string.trimLeft()
else (string) -> string.replace REGEXP_trimLeft, ''
# --------------------------------
# Trim whitespace from end of string.
#
# @static
# @public
# @method trimRight
# @param {String} string Input string.
# @return {String} Right trimmed string.
# @see `testStringTrimRight();`
trimRight: if String::trimRight?
then (string) -> string.trimRight()
else (string) -> string.replace REGEXP_trimRight, ''
# --------------------------------
# Convert “a-property-name” to “aPropertyName”
#
# @static
# @public
# @method camelize
# @param {String} string Input string.
# @return {String} Camelized string.
camelize: do ->
# Internal camelize-helper function
#
# @private
# @method _camelize
# @param {String} match
# @param {String} char
# @param {Number} index
# @param {String} string
# @return {String} Camelized string fragment.
_camelize = (match, char, index, string) -> char.toUpperCase()
# The camelize implementation
(string) -> string.replace REGEXP_camelize, _camelize
# --------------------------------
# Convert “aPropertyName” to “a-property-name”
#
# @static
# @public
# @method dashify
# @param {String} string Input string.
# @return {String} Dashed string.
dashify: do ->
# Internal dashify-helper function
#
# @private
# @method _dashify
# @param {String} match
# @param {String} char
# @param {String} camel
# @param {Number} index
# @param {String} string
# @return {String} Dashed string fragment.
_dashify = (match, char, camel, index, string) ->
char + CHAR_dash + camel.toLowerCase()
# The dashify implementation
(string) -> string.replace REGEXP_dashify, _dashify
|
[
{
"context": ": 10.32}\n joe =\n \"_id\": 3,\n \"name\": \"joe\",\n \"quizzes\": [\n { \"id\" : 1, \"score\" ",
"end": 1523,
"score": 0.9996098279953003,
"start": 1520,
"tag": "NAME",
"value": "joe"
},
{
"context": "e\", ->\n res =\n \"_id\" : 3,\n \"name\" : \"joe\",\n \"quizzes\" : [\n { \"id\" : 1, \"score\"",
"end": 2109,
"score": 0.9995534420013428,
"start": 2106,
"tag": "NAME",
"value": "joe"
}
] | test/src/query.coffee | basaundi/chongo | 1 |
describe "Compare", ->
a = b = c = d = e = null
beforeEach () ->
a = {'x': 'y', 'foo': 9, 'bar': "xxx", 'ding': [2,4,8],\
'dong': -10, 'bang': {'foo': 8}}
b = {'x': 'y', 'foo': 0, 'bar': "yyy", 'ding': [1,3,5,7],\
'bang': {'foo': 0, 'lst': [1,2,3]}}
c = {'type': 'tool', 'x': 'y', 'foo': 1, 'bar': "zzzz",\
'ding': [1,3,5,7],\
'bang': {'foo': 8, 'lst': [1,2,3]}}
d = {'type': 'food', qty: 354, price: 5.95}
e = {'type': 'food', qty: 254, price: 10.32}
it "can do simple comparisons", ->
C = Chongo.Compare({foo: 1})
expect(C(a, b)).toEqual(1) # 9 > 0
expect(C(b, c)).toEqual(-1) # 0 < 1
expect(C(c, d)).toEqual(1) # 1 > undefined
expect(C(d, e)).toEqual(0) # undefined = undefined
C = Chongo.Compare({bang: -1})
expect(C(a,b)).toEqual(1)
expect(C(b,c)).toEqual(-1)
C = Chongo.Compare({type: 1, qty: -1})
expect(C(c,d)).toEqual(1)
expect(C(d,e)).toEqual(1)
describe "Update", ->
joe = a = b = c = d = e = null
beforeEach () ->
a = {'x': 'y', 'foo': 9, 'bar': "xxx", 'ding': [2,4,8],\
'dong': -10, 'bang': {'foo': 8}}
b = {'x': 'y', 'foo': 0, 'bar': "yyy", 'ding': [1,3,5,7],\
'bang': {'foo': 0, 'lst': [1,2,3]}}
c = {'x': 'y', 'foo': 1, 'bar': "zzzz", 'ding': [1,3,5,7],\
'bang': {'foo': 8, 'lst': [1,2,3]}}
d = {'type': 'food', qty: 354, price: 5.95}
e = {'type': 'food', qty: 254, price: 10.32}
joe =
"_id": 3,
"name": "joe",
"quizzes": [
{ "id" : 1, "score" : 6 },
{ "id" : 2, "score" : 9 }
]
it "$set s elements", ->
Chongo.Update('$set', {'foo': 'z'}, a)
Chongo.Update('$set', {'foo': 'z'}, b)
Chongo.Update('$set', {'foo': 'z'}, c)
Chongo.Update('$set', {'foo': 'z'}, d)
Chongo.Update('$set', {'foo': 'z'}, e)
expect(a.foo).toEqual('z')
expect(b.foo).toEqual('z')
expect(c.foo).toEqual('z')
expect(d.foo).toEqual('z')
expect(e.foo).toEqual('z')
it "does $push-$each-$short-$slice", ->
res =
"_id" : 3,
"name" : "joe",
"quizzes" : [
{ "id" : 1, "score" : 6 },
{ "id" : 5, "score" : 6 },
{ "id" : 4, "score" : 7 },
{ "id" : 3, "score" : 8 },
{ "id" : 2, "score" : 9 }
]
Chongo.Update('$push', {
quizzes: {
$each: [
{ id: 3, score: 8 },
{ id: 4, score: 7 },
{ id: 5, score: 6 } ],
$sort: { score: 1 },
$slice: -5
}
}, joe)
expect(joe).toEqual(res)
describe "Query", ->
a = b = c = d = e = null
beforeEach () ->
a = {'x': 'y', 'foo': 9, 'bar': "xxx", 'ding': [2,4,8],\
'dong': -10, 'bang': {'foo': 8}}
b = {'x': 'y', 'foo': 0, 'bar': "yyy", 'ding': [1,3,5,7],\
'bang': {'foo': 0, 'lst': [1,2,3]}}
c = {'x': 'y', 'foo': 1, 'bar': "zzzz", 'ding': [1,3,5,7],\
'bang': {'foo': 8, 'lst': [1,2,3]}}
d = {'type': 'food', qty: 354, price: 5.95}
e = {'type': 'food', qty: 254, price: 10.32}
it "empty", ->
m = Chongo.Query({})
expect(m(a)).toBe(true)
expect(m(b)).toBe(true)
expect(m(c)).toBe(true)
m = Chongo.Query()
expect(m(a)).toBe(true)
expect(m(b)).toBe(true)
expect(m(c)).toBe(true)
it "scalar equality", ->
m = Chongo.Query('foo': 9)
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
it "with regex", ->
m = Chongo.Query('bar': /^z+$/)
expect(m(a)).toBe(false)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "perform compound queries", ->
m = Chongo.Query('x': 'y', 'foo': 0)
expect(m(a)).toBe(false)
expect(m(b)).toBe(true)
expect(m(c)).toBe(false)
it "in arrays", ->
m = Chongo.Query('ding': 4)
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
m = Chongo.Query('ding.1': 3)
expect(m(a)).toBe(false)
expect(m(b)).toBe(true)
expect(m(c)).toBe(true)
it "documents", ->
m = Chongo.Query('bang': {'foo': 8})
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
it "in nested documents", ->
m = Chongo.Query('bang.foo': 8)
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "works with $in operator", ->
m = Chongo.Query('bar': {'$in': ['xxx', 'zzzz']})
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "works with $or operator", ->
m = Chongo.Query('$or': [{'bar': 'xxx'},{'bar': 'zzzz'}])
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "works with complex queries", ->
m = Chongo.Query({ type: 'food', $or: [{ qty: { $gt: 100 }},
{ price: { $lt: 9.95 }}]})
expect(m(a)).toBe(false)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
expect(m(d)).toBe(true)
expect(m(e)).toBe(true)
m = Chongo.Query({ type: 'food', $and: [{ qty: { $gt: 100 }},
{ price: { $lt: 9.95 }}]})
expect(m(a)).toBe(false)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
expect(m(d)).toBe(true)
expect(m(e)).toBe(false)
| 75623 |
describe "Compare", ->
a = b = c = d = e = null
beforeEach () ->
a = {'x': 'y', 'foo': 9, 'bar': "xxx", 'ding': [2,4,8],\
'dong': -10, 'bang': {'foo': 8}}
b = {'x': 'y', 'foo': 0, 'bar': "yyy", 'ding': [1,3,5,7],\
'bang': {'foo': 0, 'lst': [1,2,3]}}
c = {'type': 'tool', 'x': 'y', 'foo': 1, 'bar': "zzzz",\
'ding': [1,3,5,7],\
'bang': {'foo': 8, 'lst': [1,2,3]}}
d = {'type': 'food', qty: 354, price: 5.95}
e = {'type': 'food', qty: 254, price: 10.32}
it "can do simple comparisons", ->
C = Chongo.Compare({foo: 1})
expect(C(a, b)).toEqual(1) # 9 > 0
expect(C(b, c)).toEqual(-1) # 0 < 1
expect(C(c, d)).toEqual(1) # 1 > undefined
expect(C(d, e)).toEqual(0) # undefined = undefined
C = Chongo.Compare({bang: -1})
expect(C(a,b)).toEqual(1)
expect(C(b,c)).toEqual(-1)
C = Chongo.Compare({type: 1, qty: -1})
expect(C(c,d)).toEqual(1)
expect(C(d,e)).toEqual(1)
describe "Update", ->
joe = a = b = c = d = e = null
beforeEach () ->
a = {'x': 'y', 'foo': 9, 'bar': "xxx", 'ding': [2,4,8],\
'dong': -10, 'bang': {'foo': 8}}
b = {'x': 'y', 'foo': 0, 'bar': "yyy", 'ding': [1,3,5,7],\
'bang': {'foo': 0, 'lst': [1,2,3]}}
c = {'x': 'y', 'foo': 1, 'bar': "zzzz", 'ding': [1,3,5,7],\
'bang': {'foo': 8, 'lst': [1,2,3]}}
d = {'type': 'food', qty: 354, price: 5.95}
e = {'type': 'food', qty: 254, price: 10.32}
joe =
"_id": 3,
"name": "<NAME>",
"quizzes": [
{ "id" : 1, "score" : 6 },
{ "id" : 2, "score" : 9 }
]
it "$set s elements", ->
Chongo.Update('$set', {'foo': 'z'}, a)
Chongo.Update('$set', {'foo': 'z'}, b)
Chongo.Update('$set', {'foo': 'z'}, c)
Chongo.Update('$set', {'foo': 'z'}, d)
Chongo.Update('$set', {'foo': 'z'}, e)
expect(a.foo).toEqual('z')
expect(b.foo).toEqual('z')
expect(c.foo).toEqual('z')
expect(d.foo).toEqual('z')
expect(e.foo).toEqual('z')
it "does $push-$each-$short-$slice", ->
res =
"_id" : 3,
"name" : "<NAME>",
"quizzes" : [
{ "id" : 1, "score" : 6 },
{ "id" : 5, "score" : 6 },
{ "id" : 4, "score" : 7 },
{ "id" : 3, "score" : 8 },
{ "id" : 2, "score" : 9 }
]
Chongo.Update('$push', {
quizzes: {
$each: [
{ id: 3, score: 8 },
{ id: 4, score: 7 },
{ id: 5, score: 6 } ],
$sort: { score: 1 },
$slice: -5
}
}, joe)
expect(joe).toEqual(res)
describe "Query", ->
a = b = c = d = e = null
beforeEach () ->
a = {'x': 'y', 'foo': 9, 'bar': "xxx", 'ding': [2,4,8],\
'dong': -10, 'bang': {'foo': 8}}
b = {'x': 'y', 'foo': 0, 'bar': "yyy", 'ding': [1,3,5,7],\
'bang': {'foo': 0, 'lst': [1,2,3]}}
c = {'x': 'y', 'foo': 1, 'bar': "zzzz", 'ding': [1,3,5,7],\
'bang': {'foo': 8, 'lst': [1,2,3]}}
d = {'type': 'food', qty: 354, price: 5.95}
e = {'type': 'food', qty: 254, price: 10.32}
it "empty", ->
m = Chongo.Query({})
expect(m(a)).toBe(true)
expect(m(b)).toBe(true)
expect(m(c)).toBe(true)
m = Chongo.Query()
expect(m(a)).toBe(true)
expect(m(b)).toBe(true)
expect(m(c)).toBe(true)
it "scalar equality", ->
m = Chongo.Query('foo': 9)
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
it "with regex", ->
m = Chongo.Query('bar': /^z+$/)
expect(m(a)).toBe(false)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "perform compound queries", ->
m = Chongo.Query('x': 'y', 'foo': 0)
expect(m(a)).toBe(false)
expect(m(b)).toBe(true)
expect(m(c)).toBe(false)
it "in arrays", ->
m = Chongo.Query('ding': 4)
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
m = Chongo.Query('ding.1': 3)
expect(m(a)).toBe(false)
expect(m(b)).toBe(true)
expect(m(c)).toBe(true)
it "documents", ->
m = Chongo.Query('bang': {'foo': 8})
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
it "in nested documents", ->
m = Chongo.Query('bang.foo': 8)
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "works with $in operator", ->
m = Chongo.Query('bar': {'$in': ['xxx', 'zzzz']})
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "works with $or operator", ->
m = Chongo.Query('$or': [{'bar': 'xxx'},{'bar': 'zzzz'}])
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "works with complex queries", ->
m = Chongo.Query({ type: 'food', $or: [{ qty: { $gt: 100 }},
{ price: { $lt: 9.95 }}]})
expect(m(a)).toBe(false)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
expect(m(d)).toBe(true)
expect(m(e)).toBe(true)
m = Chongo.Query({ type: 'food', $and: [{ qty: { $gt: 100 }},
{ price: { $lt: 9.95 }}]})
expect(m(a)).toBe(false)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
expect(m(d)).toBe(true)
expect(m(e)).toBe(false)
| true |
describe "Compare", ->
a = b = c = d = e = null
beforeEach () ->
a = {'x': 'y', 'foo': 9, 'bar': "xxx", 'ding': [2,4,8],\
'dong': -10, 'bang': {'foo': 8}}
b = {'x': 'y', 'foo': 0, 'bar': "yyy", 'ding': [1,3,5,7],\
'bang': {'foo': 0, 'lst': [1,2,3]}}
c = {'type': 'tool', 'x': 'y', 'foo': 1, 'bar': "zzzz",\
'ding': [1,3,5,7],\
'bang': {'foo': 8, 'lst': [1,2,3]}}
d = {'type': 'food', qty: 354, price: 5.95}
e = {'type': 'food', qty: 254, price: 10.32}
it "can do simple comparisons", ->
C = Chongo.Compare({foo: 1})
expect(C(a, b)).toEqual(1) # 9 > 0
expect(C(b, c)).toEqual(-1) # 0 < 1
expect(C(c, d)).toEqual(1) # 1 > undefined
expect(C(d, e)).toEqual(0) # undefined = undefined
C = Chongo.Compare({bang: -1})
expect(C(a,b)).toEqual(1)
expect(C(b,c)).toEqual(-1)
C = Chongo.Compare({type: 1, qty: -1})
expect(C(c,d)).toEqual(1)
expect(C(d,e)).toEqual(1)
describe "Update", ->
joe = a = b = c = d = e = null
beforeEach () ->
a = {'x': 'y', 'foo': 9, 'bar': "xxx", 'ding': [2,4,8],\
'dong': -10, 'bang': {'foo': 8}}
b = {'x': 'y', 'foo': 0, 'bar': "yyy", 'ding': [1,3,5,7],\
'bang': {'foo': 0, 'lst': [1,2,3]}}
c = {'x': 'y', 'foo': 1, 'bar': "zzzz", 'ding': [1,3,5,7],\
'bang': {'foo': 8, 'lst': [1,2,3]}}
d = {'type': 'food', qty: 354, price: 5.95}
e = {'type': 'food', qty: 254, price: 10.32}
joe =
"_id": 3,
"name": "PI:NAME:<NAME>END_PI",
"quizzes": [
{ "id" : 1, "score" : 6 },
{ "id" : 2, "score" : 9 }
]
it "$set s elements", ->
Chongo.Update('$set', {'foo': 'z'}, a)
Chongo.Update('$set', {'foo': 'z'}, b)
Chongo.Update('$set', {'foo': 'z'}, c)
Chongo.Update('$set', {'foo': 'z'}, d)
Chongo.Update('$set', {'foo': 'z'}, e)
expect(a.foo).toEqual('z')
expect(b.foo).toEqual('z')
expect(c.foo).toEqual('z')
expect(d.foo).toEqual('z')
expect(e.foo).toEqual('z')
it "does $push-$each-$short-$slice", ->
res =
"_id" : 3,
"name" : "PI:NAME:<NAME>END_PI",
"quizzes" : [
{ "id" : 1, "score" : 6 },
{ "id" : 5, "score" : 6 },
{ "id" : 4, "score" : 7 },
{ "id" : 3, "score" : 8 },
{ "id" : 2, "score" : 9 }
]
Chongo.Update('$push', {
quizzes: {
$each: [
{ id: 3, score: 8 },
{ id: 4, score: 7 },
{ id: 5, score: 6 } ],
$sort: { score: 1 },
$slice: -5
}
}, joe)
expect(joe).toEqual(res)
describe "Query", ->
a = b = c = d = e = null
beforeEach () ->
a = {'x': 'y', 'foo': 9, 'bar': "xxx", 'ding': [2,4,8],\
'dong': -10, 'bang': {'foo': 8}}
b = {'x': 'y', 'foo': 0, 'bar': "yyy", 'ding': [1,3,5,7],\
'bang': {'foo': 0, 'lst': [1,2,3]}}
c = {'x': 'y', 'foo': 1, 'bar': "zzzz", 'ding': [1,3,5,7],\
'bang': {'foo': 8, 'lst': [1,2,3]}}
d = {'type': 'food', qty: 354, price: 5.95}
e = {'type': 'food', qty: 254, price: 10.32}
it "empty", ->
m = Chongo.Query({})
expect(m(a)).toBe(true)
expect(m(b)).toBe(true)
expect(m(c)).toBe(true)
m = Chongo.Query()
expect(m(a)).toBe(true)
expect(m(b)).toBe(true)
expect(m(c)).toBe(true)
it "scalar equality", ->
m = Chongo.Query('foo': 9)
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
it "with regex", ->
m = Chongo.Query('bar': /^z+$/)
expect(m(a)).toBe(false)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "perform compound queries", ->
m = Chongo.Query('x': 'y', 'foo': 0)
expect(m(a)).toBe(false)
expect(m(b)).toBe(true)
expect(m(c)).toBe(false)
it "in arrays", ->
m = Chongo.Query('ding': 4)
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
m = Chongo.Query('ding.1': 3)
expect(m(a)).toBe(false)
expect(m(b)).toBe(true)
expect(m(c)).toBe(true)
it "documents", ->
m = Chongo.Query('bang': {'foo': 8})
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
it "in nested documents", ->
m = Chongo.Query('bang.foo': 8)
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "works with $in operator", ->
m = Chongo.Query('bar': {'$in': ['xxx', 'zzzz']})
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "works with $or operator", ->
m = Chongo.Query('$or': [{'bar': 'xxx'},{'bar': 'zzzz'}])
expect(m(a)).toBe(true)
expect(m(b)).toBe(false)
expect(m(c)).toBe(true)
it "works with complex queries", ->
m = Chongo.Query({ type: 'food', $or: [{ qty: { $gt: 100 }},
{ price: { $lt: 9.95 }}]})
expect(m(a)).toBe(false)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
expect(m(d)).toBe(true)
expect(m(e)).toBe(true)
m = Chongo.Query({ type: 'food', $and: [{ qty: { $gt: 100 }},
{ price: { $lt: 9.95 }}]})
expect(m(a)).toBe(false)
expect(m(b)).toBe(false)
expect(m(c)).toBe(false)
expect(m(d)).toBe(true)
expect(m(e)).toBe(false)
|
[
{
"context": "###*\n * Normalize i18n object\n * @input { key: 'value1', key2:{fr: 'value', 'en': 'value'} }\n * @output ",
"end": 54,
"score": 0.7256240248680115,
"start": 48,
"tag": "KEY",
"value": "value1"
}
] | assets/_noramlize.coffee | gridfw/i18n-gulp | 0 | ###*
* Normalize i18n object
* @input { key: 'value1', key2:{fr: 'value', 'en': 'value'} }
* @output { en: {key:'value1', key2: 'value'}, fr: {key: 'value1', key2: 'value'} }
###
# normalize i18n
_normalize = (data)->
throw new Error "Normalize: Illegal input" unless typeof data is 'object' and data
# look for all used locals
usedLocals = []
result = Object.create null
for k,v of data
if typeof v is 'object'
throw new Error "Normalize: Illegal value at: #{k}" unless v
# add language
unless I18N_SYMBOL of v
for lg of v
unless lg in usedLocals
usedLocals.push lg
result[lg] = Object.create null
throw new Error "Unless one key with all used languages mast be specified!" if usedLocals.length is 0
# normalize
requiredLocalMsgs = Object.create null
for k,v of data
# general value
if typeof v is 'string'
result[lg][k] = v for lg in usedLocals
# object
else if typeof v is 'object'
# general value
if I18N_SYMBOL of v
result[lg][k] = v for lg in usedLocals
# locals
else
for lg in usedLocals
if lg of v
result[lg][k] = v[lg]
else
(requiredLocalMsgs[k] ?= []).push lg
else
throw new Error "Normalize:: Illegal type at: #{k}"
# throw required languages on fields
for k in requiredLocalMsgs
throw new Error "Required locals:\n #{JSON.stringify requiredLocalMsgs, null, "\t"}"
# return result
result
| 124823 | ###*
* Normalize i18n object
* @input { key: '<KEY>', key2:{fr: 'value', 'en': 'value'} }
* @output { en: {key:'value1', key2: 'value'}, fr: {key: 'value1', key2: 'value'} }
###
# normalize i18n
_normalize = (data)->
throw new Error "Normalize: Illegal input" unless typeof data is 'object' and data
# look for all used locals
usedLocals = []
result = Object.create null
for k,v of data
if typeof v is 'object'
throw new Error "Normalize: Illegal value at: #{k}" unless v
# add language
unless I18N_SYMBOL of v
for lg of v
unless lg in usedLocals
usedLocals.push lg
result[lg] = Object.create null
throw new Error "Unless one key with all used languages mast be specified!" if usedLocals.length is 0
# normalize
requiredLocalMsgs = Object.create null
for k,v of data
# general value
if typeof v is 'string'
result[lg][k] = v for lg in usedLocals
# object
else if typeof v is 'object'
# general value
if I18N_SYMBOL of v
result[lg][k] = v for lg in usedLocals
# locals
else
for lg in usedLocals
if lg of v
result[lg][k] = v[lg]
else
(requiredLocalMsgs[k] ?= []).push lg
else
throw new Error "Normalize:: Illegal type at: #{k}"
# throw required languages on fields
for k in requiredLocalMsgs
throw new Error "Required locals:\n #{JSON.stringify requiredLocalMsgs, null, "\t"}"
# return result
result
| true | ###*
* Normalize i18n object
* @input { key: 'PI:KEY:<KEY>END_PI', key2:{fr: 'value', 'en': 'value'} }
* @output { en: {key:'value1', key2: 'value'}, fr: {key: 'value1', key2: 'value'} }
###
# normalize i18n
_normalize = (data)->
throw new Error "Normalize: Illegal input" unless typeof data is 'object' and data
# look for all used locals
usedLocals = []
result = Object.create null
for k,v of data
if typeof v is 'object'
throw new Error "Normalize: Illegal value at: #{k}" unless v
# add language
unless I18N_SYMBOL of v
for lg of v
unless lg in usedLocals
usedLocals.push lg
result[lg] = Object.create null
throw new Error "Unless one key with all used languages mast be specified!" if usedLocals.length is 0
# normalize
requiredLocalMsgs = Object.create null
for k,v of data
# general value
if typeof v is 'string'
result[lg][k] = v for lg in usedLocals
# object
else if typeof v is 'object'
# general value
if I18N_SYMBOL of v
result[lg][k] = v for lg in usedLocals
# locals
else
for lg in usedLocals
if lg of v
result[lg][k] = v[lg]
else
(requiredLocalMsgs[k] ?= []).push lg
else
throw new Error "Normalize:: Illegal type at: #{k}"
# throw required languages on fields
for k in requiredLocalMsgs
throw new Error "Required locals:\n #{JSON.stringify requiredLocalMsgs, null, "\t"}"
# return result
result
|
[
{
"context": "key: 'mark'\n\npatterns: [\n\n # Matches mark unconstrained phr",
"end": 10,
"score": 0.7764093279838562,
"start": 6,
"tag": "KEY",
"value": "mark"
}
] | grammars/repositories/inlines/mark-grammar.cson | andrewcarver/atom-language-asciidoc | 45 | key: 'mark'
patterns: [
# Matches mark unconstrained phrases
#
# Examples:
#
# m[role]##ark## phrase
#
name: 'markup.mark.unconstrained.asciidoc'
match: '(?<!\\\\\\\\)(\\[[^\\]]+?\\])((##)(.+?)(##))'
captures:
1: name: 'markup.meta.attribute-list.asciidoc'
2: name: 'markup.mark.asciidoc'
3: name: 'punctuation.definition.asciidoc'
5: name: 'punctuation.definition.asciidoc'
,
# Matches mark unconstrained phrases. (highlight)
#
# Examples:
#
# m##ark## phrase
#
name: 'markup.mark.unconstrained.asciidoc'
match: '(?<!\\\\\\\\)((##)(.+?)(##))'
captures:
1: name: 'markup.highlight.asciidoc'
2: name: 'punctuation.definition.asciidoc'
4: name: 'punctuation.definition.asciidoc'
,
# Matches mark constrained phrases
#
# Examples:
#
# [smal]#mark phrase#
#
name: 'markup.mark.constrained.asciidoc'
match: '(?<![\\\\;:\\p{Word}#])(\\[[^\\]]+?\\])((#)(\\S|\\S.*?\\S)(#)(?!\\p{Word}))'
captures:
1: name: 'markup.meta.attribute-list.asciidoc'
2: name: 'markup.mark.asciidoc'
3: name: 'punctuation.definition.asciidoc'
5: name: 'punctuation.definition.asciidoc'
,
# Matches mark constrained phrases (highlight)
#
# Examples:
#
# #mark phrase#
#
name: 'markup.mark.constrained.asciidoc'
match: '(?<![\\\\;:\\p{Word}#])(\\[[^\\]]+?\\])?((#)(\\S|\\S.*?\\S)(#)(?!\\p{Word}))'
captures:
1: name: 'markup.meta.attribute-list.asciidoc'
2: name: 'markup.highlight.asciidoc'
3: name: 'punctuation.definition.asciidoc'
5: name: 'punctuation.definition.asciidoc'
]
| 97217 | key: '<KEY>'
patterns: [
# Matches mark unconstrained phrases
#
# Examples:
#
# m[role]##ark## phrase
#
name: 'markup.mark.unconstrained.asciidoc'
match: '(?<!\\\\\\\\)(\\[[^\\]]+?\\])((##)(.+?)(##))'
captures:
1: name: 'markup.meta.attribute-list.asciidoc'
2: name: 'markup.mark.asciidoc'
3: name: 'punctuation.definition.asciidoc'
5: name: 'punctuation.definition.asciidoc'
,
# Matches mark unconstrained phrases. (highlight)
#
# Examples:
#
# m##ark## phrase
#
name: 'markup.mark.unconstrained.asciidoc'
match: '(?<!\\\\\\\\)((##)(.+?)(##))'
captures:
1: name: 'markup.highlight.asciidoc'
2: name: 'punctuation.definition.asciidoc'
4: name: 'punctuation.definition.asciidoc'
,
# Matches mark constrained phrases
#
# Examples:
#
# [smal]#mark phrase#
#
name: 'markup.mark.constrained.asciidoc'
match: '(?<![\\\\;:\\p{Word}#])(\\[[^\\]]+?\\])((#)(\\S|\\S.*?\\S)(#)(?!\\p{Word}))'
captures:
1: name: 'markup.meta.attribute-list.asciidoc'
2: name: 'markup.mark.asciidoc'
3: name: 'punctuation.definition.asciidoc'
5: name: 'punctuation.definition.asciidoc'
,
# Matches mark constrained phrases (highlight)
#
# Examples:
#
# #mark phrase#
#
name: 'markup.mark.constrained.asciidoc'
match: '(?<![\\\\;:\\p{Word}#])(\\[[^\\]]+?\\])?((#)(\\S|\\S.*?\\S)(#)(?!\\p{Word}))'
captures:
1: name: 'markup.meta.attribute-list.asciidoc'
2: name: 'markup.highlight.asciidoc'
3: name: 'punctuation.definition.asciidoc'
5: name: 'punctuation.definition.asciidoc'
]
| true | key: 'PI:KEY:<KEY>END_PI'
patterns: [
# Matches mark unconstrained phrases
#
# Examples:
#
# m[role]##ark## phrase
#
name: 'markup.mark.unconstrained.asciidoc'
match: '(?<!\\\\\\\\)(\\[[^\\]]+?\\])((##)(.+?)(##))'
captures:
1: name: 'markup.meta.attribute-list.asciidoc'
2: name: 'markup.mark.asciidoc'
3: name: 'punctuation.definition.asciidoc'
5: name: 'punctuation.definition.asciidoc'
,
# Matches mark unconstrained phrases. (highlight)
#
# Examples:
#
# m##ark## phrase
#
name: 'markup.mark.unconstrained.asciidoc'
match: '(?<!\\\\\\\\)((##)(.+?)(##))'
captures:
1: name: 'markup.highlight.asciidoc'
2: name: 'punctuation.definition.asciidoc'
4: name: 'punctuation.definition.asciidoc'
,
# Matches mark constrained phrases
#
# Examples:
#
# [smal]#mark phrase#
#
name: 'markup.mark.constrained.asciidoc'
match: '(?<![\\\\;:\\p{Word}#])(\\[[^\\]]+?\\])((#)(\\S|\\S.*?\\S)(#)(?!\\p{Word}))'
captures:
1: name: 'markup.meta.attribute-list.asciidoc'
2: name: 'markup.mark.asciidoc'
3: name: 'punctuation.definition.asciidoc'
5: name: 'punctuation.definition.asciidoc'
,
# Matches mark constrained phrases (highlight)
#
# Examples:
#
# #mark phrase#
#
name: 'markup.mark.constrained.asciidoc'
match: '(?<![\\\\;:\\p{Word}#])(\\[[^\\]]+?\\])?((#)(\\S|\\S.*?\\S)(#)(?!\\p{Word}))'
captures:
1: name: 'markup.meta.attribute-list.asciidoc'
2: name: 'markup.highlight.asciidoc'
3: name: 'punctuation.definition.asciidoc'
5: name: 'punctuation.definition.asciidoc'
]
|
[
{
"context": "###\n knockback_factory.js\n (c) 2011-2013 Kevin Malakoff.\n Knockback.Factory is freely distributable unde",
"end": 57,
"score": 0.999787449836731,
"start": 43,
"tag": "NAME",
"value": "Kevin Malakoff"
},
{
"context": " for full license details:\n https://github.com/kmalakoff/knockback/blob/master/LICENSE\n###\n\n# Used to shar",
"end": 204,
"score": 0.9956916570663452,
"start": 195,
"tag": "USERNAME",
"value": "kmalakoff"
},
{
"context": " factory.createForPath(new Backbone.Model({name: 'Bob'}), 'bob.the.builder'); // creates kb.ViewModel\nc",
"end": 571,
"score": 0.9980189800262451,
"start": 568,
"tag": "NAME",
"value": "Bob"
},
{
"context": " factory.createForPath(new Backbone.Model({name: 'Bob'}), 'bob.the.builder'); // creates kb.ViewModel\n ",
"end": 2711,
"score": 0.9992075562477112,
"start": 2708,
"tag": "NAME",
"value": "Bob"
}
] | src/core/factory.coffee | npmcomponent/kmalakoff-knockback | 1 | ###
knockback_factory.js
(c) 2011-2013 Kevin Malakoff.
Knockback.Factory is freely distributable under the MIT license.
See the following for full license details:
https://github.com/kmalakoff/knockback/blob/master/LICENSE
###
# Used to share the hierachy of constructors and create functions by path to allow for custom creation per Model attribute.
#
# @example Create an instance by path.
# var factory = new kb.Factory();
# factory.addPathMapping('bob.the.builder', kb.ViewModel);
# view_model = factory.createForPath(new Backbone.Model({name: 'Bob'}), 'bob.the.builder'); // creates kb.ViewModel
class kb.Factory
# Used to either register yourself with the existing factory or to create a new factory.
#
# @param [Object] options please pass the options from your constructor to the register method. For example, constructor(model, options)
# @option options [Object] factories a map of dot-deliminated paths; for example 'models.owner': kb.ViewModel to either constructors or create functions. Signature: 'some.path': function(object, options)
# @param [Instance] obj the instance that will own or register with the store
# @param [String] owner_path the path to the owning object for turning relative scoping of the factories to absolute paths.
@useOptionsOrCreate: (options, obj, owner_path) ->
# share
if options.factory and (not options.factories or (options.factories and options.factory.hasPathMappings(options.factories, owner_path)))
return kb.utils.wrappedFactory(obj, options.factory)
# create a new factory
factory = kb.utils.wrappedFactory(obj, new kb.Factory(options.factory))
factory.addPathMappings(options.factories, owner_path) if options.factories
return factory
constructor: (@parent_factory) ->
@paths = {}
hasPath: (path) -> return @paths.hasOwnProperty(path) or (@parent_factory and @parent_factory.hasPath(path))
addPathMapping: (path, create_info) ->
@paths[path] = create_info
addPathMappings: (factories, owner_path) ->
for path, create_info of factories
@paths[kb.utils.pathJoin(owner_path, path)] = create_info
return
hasPathMappings: (factories, owner_path) ->
all_exist = true
for path, creator of factories
all_exist &= ((existing_creator = @creatorForPath(null, kb.utils.pathJoin(owner_path, path))) and (creator is existing_creator))
return all_exist
# If possible, creates an observable for an object using a dot-deliminated path.
#
# @example Create an instance by path.
# var factory = new kb.Factory();
# factory.addPathMapping('bob.the.builder', kb.ViewModel);
# view_model = factory.createForPath(new Backbone.Model({name: 'Bob'}), 'bob.the.builder'); // creates kb.ViewModel
creatorForPath: (obj, path) ->
if (creator = @paths[path])
return if creator.view_model then creator.view_model else creator
if @parent_factory
return creator if (creator = @parent_factory.creatorForPath(obj, path))
return null | 146983 | ###
knockback_factory.js
(c) 2011-2013 <NAME>.
Knockback.Factory is freely distributable under the MIT license.
See the following for full license details:
https://github.com/kmalakoff/knockback/blob/master/LICENSE
###
# Used to share the hierachy of constructors and create functions by path to allow for custom creation per Model attribute.
#
# @example Create an instance by path.
# var factory = new kb.Factory();
# factory.addPathMapping('bob.the.builder', kb.ViewModel);
# view_model = factory.createForPath(new Backbone.Model({name: '<NAME>'}), 'bob.the.builder'); // creates kb.ViewModel
class kb.Factory
# Used to either register yourself with the existing factory or to create a new factory.
#
# @param [Object] options please pass the options from your constructor to the register method. For example, constructor(model, options)
# @option options [Object] factories a map of dot-deliminated paths; for example 'models.owner': kb.ViewModel to either constructors or create functions. Signature: 'some.path': function(object, options)
# @param [Instance] obj the instance that will own or register with the store
# @param [String] owner_path the path to the owning object for turning relative scoping of the factories to absolute paths.
@useOptionsOrCreate: (options, obj, owner_path) ->
# share
if options.factory and (not options.factories or (options.factories and options.factory.hasPathMappings(options.factories, owner_path)))
return kb.utils.wrappedFactory(obj, options.factory)
# create a new factory
factory = kb.utils.wrappedFactory(obj, new kb.Factory(options.factory))
factory.addPathMappings(options.factories, owner_path) if options.factories
return factory
constructor: (@parent_factory) ->
@paths = {}
hasPath: (path) -> return @paths.hasOwnProperty(path) or (@parent_factory and @parent_factory.hasPath(path))
addPathMapping: (path, create_info) ->
@paths[path] = create_info
addPathMappings: (factories, owner_path) ->
for path, create_info of factories
@paths[kb.utils.pathJoin(owner_path, path)] = create_info
return
hasPathMappings: (factories, owner_path) ->
all_exist = true
for path, creator of factories
all_exist &= ((existing_creator = @creatorForPath(null, kb.utils.pathJoin(owner_path, path))) and (creator is existing_creator))
return all_exist
# If possible, creates an observable for an object using a dot-deliminated path.
#
# @example Create an instance by path.
# var factory = new kb.Factory();
# factory.addPathMapping('bob.the.builder', kb.ViewModel);
# view_model = factory.createForPath(new Backbone.Model({name: '<NAME>'}), 'bob.the.builder'); // creates kb.ViewModel
creatorForPath: (obj, path) ->
if (creator = @paths[path])
return if creator.view_model then creator.view_model else creator
if @parent_factory
return creator if (creator = @parent_factory.creatorForPath(obj, path))
return null | true | ###
knockback_factory.js
(c) 2011-2013 PI:NAME:<NAME>END_PI.
Knockback.Factory is freely distributable under the MIT license.
See the following for full license details:
https://github.com/kmalakoff/knockback/blob/master/LICENSE
###
# Used to share the hierachy of constructors and create functions by path to allow for custom creation per Model attribute.
#
# @example Create an instance by path.
# var factory = new kb.Factory();
# factory.addPathMapping('bob.the.builder', kb.ViewModel);
# view_model = factory.createForPath(new Backbone.Model({name: 'PI:NAME:<NAME>END_PI'}), 'bob.the.builder'); // creates kb.ViewModel
class kb.Factory
# Used to either register yourself with the existing factory or to create a new factory.
#
# @param [Object] options please pass the options from your constructor to the register method. For example, constructor(model, options)
# @option options [Object] factories a map of dot-deliminated paths; for example 'models.owner': kb.ViewModel to either constructors or create functions. Signature: 'some.path': function(object, options)
# @param [Instance] obj the instance that will own or register with the store
# @param [String] owner_path the path to the owning object for turning relative scoping of the factories to absolute paths.
@useOptionsOrCreate: (options, obj, owner_path) ->
# share
if options.factory and (not options.factories or (options.factories and options.factory.hasPathMappings(options.factories, owner_path)))
return kb.utils.wrappedFactory(obj, options.factory)
# create a new factory
factory = kb.utils.wrappedFactory(obj, new kb.Factory(options.factory))
factory.addPathMappings(options.factories, owner_path) if options.factories
return factory
constructor: (@parent_factory) ->
@paths = {}
hasPath: (path) -> return @paths.hasOwnProperty(path) or (@parent_factory and @parent_factory.hasPath(path))
addPathMapping: (path, create_info) ->
@paths[path] = create_info
addPathMappings: (factories, owner_path) ->
for path, create_info of factories
@paths[kb.utils.pathJoin(owner_path, path)] = create_info
return
hasPathMappings: (factories, owner_path) ->
all_exist = true
for path, creator of factories
all_exist &= ((existing_creator = @creatorForPath(null, kb.utils.pathJoin(owner_path, path))) and (creator is existing_creator))
return all_exist
# If possible, creates an observable for an object using a dot-deliminated path.
#
# @example Create an instance by path.
# var factory = new kb.Factory();
# factory.addPathMapping('bob.the.builder', kb.ViewModel);
# view_model = factory.createForPath(new Backbone.Model({name: 'PI:NAME:<NAME>END_PI'}), 'bob.the.builder'); // creates kb.ViewModel
creatorForPath: (obj, path) ->
if (creator = @paths[path])
return if creator.view_model then creator.view_model else creator
if @parent_factory
return creator if (creator = @parent_factory.creatorForPath(obj, path))
return null |
[
{
"context": "enerator-joomla-component\n\n\tindex.coffee\n\n\t@author Sean\n\n\t@note Created on 2014-10-04 by PhpStorm\n\t@note ",
"end": 61,
"score": 0.9991904497146606,
"start": 57,
"tag": "NAME",
"value": "Sean"
},
{
"context": "pStorm\n\t@note uses Codoc\n\t@see https://github.com/coffeedoc/codo\n###\n\"use strict\"\nyeoman = require(\"yeoman-ge",
"end": 156,
"score": 0.9994767904281616,
"start": 147,
"tag": "USERNAME",
"value": "coffeedoc"
},
{
"context": "la component controllers\n\t@see https://github.com/mklabs/yeoman/wiki/generators coffeescript with yeoman\n#",
"end": 350,
"score": 0.9992413520812988,
"start": 344,
"tag": "USERNAME",
"value": "mklabs"
},
{
"context": "\t\t\t\tdefault: \"default-value\"\n\t\t\t}\n\t\t\t{\n\t\t\t\tname: \"authorName\"\n\t\t\t\tmessage: \"What's your name?\"\n\t\t\t\tdefault: \"A",
"end": 1222,
"score": 0.915542721748352,
"start": 1212,
"tag": "USERNAME",
"value": "authorName"
},
{
"context": "e\"\n\t\t\t\tmessage: \"What's your name?\"\n\t\t\t\tdefault: \"Author name\"\n\t\t\t}\n\t\t\t{\n\t\t\t\tname: \"authorEmail\"\n\t\t\t\tmessage: \"",
"end": 1282,
"score": 0.6977293491363525,
"start": 1271,
"tag": "NAME",
"value": "Author name"
},
{
"context": "\"\n\t\t\t\tdefault: \"Author name\"\n\t\t\t}\n\t\t\t{\n\t\t\t\tname: \"authorEmail\"\n\t\t\t\tmessage: \"What's your e-mail?\"\n\t\t\t\tdefault: ",
"end": 1316,
"score": 0.6569507122039795,
"start": 1305,
"tag": "USERNAME",
"value": "authorEmail"
},
{
"context": "\n\t\t\t\tmessage: \"What's your e-mail?\"\n\t\t\t\tdefault: \"email@somedomain.com\"\n\t\t\t}\n\t\t\t{\n\t\t\t\tname: \"authorURL\"\n\t\t\t\tmessage: \"Wh",
"end": 1387,
"score": 0.9998757243156433,
"start": 1367,
"tag": "EMAIL",
"value": "email@somedomain.com"
}
] | app/index.coffee | srsgores/generator-joomla-component | 16 | ###
generator-joomla-component
index.coffee
@author Sean
@note Created on 2014-10-04 by PhpStorm
@note uses Codoc
@see https://github.com/coffeedoc/codo
###
"use strict"
yeoman = require("yeoman-generator")
path = require("path")
###
@class ControllerGenerator sub-generator for joomla component controllers
@see https://github.com/mklabs/yeoman/wiki/generators coffeescript with yeoman
###
module.exports = class JoomlaComponentGenerator extends yeoman.generators.Base
###
@param [Array] args command-line arguments passed in (if any)
@param [Array] options any additional options
@param [Array] config the yeoman configuration
###
constructor: (args, options, config) ->
super args, options, config
@on "end", ->
@installDependencies skipInstall: options["skip-install"]
@pkg = JSON.parse(@readFileAsString(path.join(__dirname, "../package.json")))
askFor: ->
cb = @async()
# have Yeoman greet the user.
console.log @yeoman
prompts = [
{
name: "description"
message: "Describe your component"
default: "A sample description"
}
{
name: "componentName"
message: "What's the component's name?"
default: "default-value"
}
{
name: "authorName"
message: "What's your name?"
default: "Author name"
}
{
name: "authorEmail"
message: "What's your e-mail?"
default: "email@somedomain.com"
}
{
name: "authorURL"
message: "What's your website?"
default: "somedomain.com"
}
{
name: "license"
message: "What's the copyright license?"
default: "MIT"
}
{
type: "confirm"
name: "requireManageRights"
message: "Does your component require admin manage rights to access it?"
}
{
type: "confirm"
name: "legacyJoomla"
message: "Support Joomla 2.5x with compatibility layer?"
}
]
@prompt prompts, ((props) ->
# for own prompt of prompts
# @prompt.name = prompt.name?
@description = props.description
@componentName = props.componentName
@authorName = props.authorName
@authorEmail = props.authorEmail
@authorURL = props.authorURL
@license = props.license
@requireManageRights = props.requireManageRights
@legacyJoomla = props.legacyJoomla
@currentDate = @_getCurrentDate()
cb()
).bind(@)
app: ->
@mkdir "app"
@mkdir "app/templates"
@template "_package.json", "package.json"
@template "_bower.json", "bower.json"
@copy "_gitignore", ".gitignore"
_getCurrentDate: ->
new Date().getUTCDate()
projectfiles: ->
@copy "editorconfig", ".editorconfig"
@copy "jshintrc", ".jshintrc"
createConfigFiles: ->
@template "_component-name.xml", @_.slugify(@componentName) + ".xml"
@template "_config.xml", "config.xml"
@template "_access.xml", "access.xml"
###
Create legacy files for fallback to Joomla 2.5x
###
createLegacyFallbackFiles: ->
@template "_legacy.php", "legacy.php" if @legacyJoomla is on
createPHPFiles: ->
@template "_component-name.php", @_.slugify(@componentName) + ".php"
@template "_router.php", "router.php"
createDatabaseFiles: ->
@template "sql/_install.mysql.utf8.sql", "sql/install.mysql.utf8.sql"
@template "sql/_uninstall.mysql.utf8.sql", "sql/uninstall.mysql.utf8.sql"
@template "_install-uninstall.php", "install-uninstall.php"
createLanguageFiles: ->
@template "languages/en-GB/_en-GB.com_component-name.ini", "languages/en-GB/en-GB.com_" + @_.slugify(@componentName) + ".ini"
@template "languages/en-GB/_en-GB.com_component-name.ini", "languages/en-GB/en-GB.com_" + @_.slugify(@componentName) + ".sys.ini"
createEmptyMVCFolders: ->
emptyMVCFolders = [
"controllers"
"helpers"
"models"
"sql"
"tables"
"views"
]
for folderName in emptyMVCFolders
@template "_index.html", "#{folderName}/index.html"
@template "_index.html", "index.html"
@template "_index.html", "languages/index.html"
@template "_index.html", "languages/en-GB/index.html"
| 142098 | ###
generator-joomla-component
index.coffee
@author <NAME>
@note Created on 2014-10-04 by PhpStorm
@note uses Codoc
@see https://github.com/coffeedoc/codo
###
"use strict"
yeoman = require("yeoman-generator")
path = require("path")
###
@class ControllerGenerator sub-generator for joomla component controllers
@see https://github.com/mklabs/yeoman/wiki/generators coffeescript with yeoman
###
module.exports = class JoomlaComponentGenerator extends yeoman.generators.Base
###
@param [Array] args command-line arguments passed in (if any)
@param [Array] options any additional options
@param [Array] config the yeoman configuration
###
constructor: (args, options, config) ->
super args, options, config
@on "end", ->
@installDependencies skipInstall: options["skip-install"]
@pkg = JSON.parse(@readFileAsString(path.join(__dirname, "../package.json")))
askFor: ->
cb = @async()
# have Yeoman greet the user.
console.log @yeoman
prompts = [
{
name: "description"
message: "Describe your component"
default: "A sample description"
}
{
name: "componentName"
message: "What's the component's name?"
default: "default-value"
}
{
name: "authorName"
message: "What's your name?"
default: "<NAME>"
}
{
name: "authorEmail"
message: "What's your e-mail?"
default: "<EMAIL>"
}
{
name: "authorURL"
message: "What's your website?"
default: "somedomain.com"
}
{
name: "license"
message: "What's the copyright license?"
default: "MIT"
}
{
type: "confirm"
name: "requireManageRights"
message: "Does your component require admin manage rights to access it?"
}
{
type: "confirm"
name: "legacyJoomla"
message: "Support Joomla 2.5x with compatibility layer?"
}
]
@prompt prompts, ((props) ->
# for own prompt of prompts
# @prompt.name = prompt.name?
@description = props.description
@componentName = props.componentName
@authorName = props.authorName
@authorEmail = props.authorEmail
@authorURL = props.authorURL
@license = props.license
@requireManageRights = props.requireManageRights
@legacyJoomla = props.legacyJoomla
@currentDate = @_getCurrentDate()
cb()
).bind(@)
app: ->
@mkdir "app"
@mkdir "app/templates"
@template "_package.json", "package.json"
@template "_bower.json", "bower.json"
@copy "_gitignore", ".gitignore"
_getCurrentDate: ->
new Date().getUTCDate()
projectfiles: ->
@copy "editorconfig", ".editorconfig"
@copy "jshintrc", ".jshintrc"
createConfigFiles: ->
@template "_component-name.xml", @_.slugify(@componentName) + ".xml"
@template "_config.xml", "config.xml"
@template "_access.xml", "access.xml"
###
Create legacy files for fallback to Joomla 2.5x
###
createLegacyFallbackFiles: ->
@template "_legacy.php", "legacy.php" if @legacyJoomla is on
createPHPFiles: ->
@template "_component-name.php", @_.slugify(@componentName) + ".php"
@template "_router.php", "router.php"
createDatabaseFiles: ->
@template "sql/_install.mysql.utf8.sql", "sql/install.mysql.utf8.sql"
@template "sql/_uninstall.mysql.utf8.sql", "sql/uninstall.mysql.utf8.sql"
@template "_install-uninstall.php", "install-uninstall.php"
createLanguageFiles: ->
@template "languages/en-GB/_en-GB.com_component-name.ini", "languages/en-GB/en-GB.com_" + @_.slugify(@componentName) + ".ini"
@template "languages/en-GB/_en-GB.com_component-name.ini", "languages/en-GB/en-GB.com_" + @_.slugify(@componentName) + ".sys.ini"
createEmptyMVCFolders: ->
emptyMVCFolders = [
"controllers"
"helpers"
"models"
"sql"
"tables"
"views"
]
for folderName in emptyMVCFolders
@template "_index.html", "#{folderName}/index.html"
@template "_index.html", "index.html"
@template "_index.html", "languages/index.html"
@template "_index.html", "languages/en-GB/index.html"
| true | ###
generator-joomla-component
index.coffee
@author PI:NAME:<NAME>END_PI
@note Created on 2014-10-04 by PhpStorm
@note uses Codoc
@see https://github.com/coffeedoc/codo
###
"use strict"
yeoman = require("yeoman-generator")
path = require("path")
###
@class ControllerGenerator sub-generator for joomla component controllers
@see https://github.com/mklabs/yeoman/wiki/generators coffeescript with yeoman
###
module.exports = class JoomlaComponentGenerator extends yeoman.generators.Base
###
@param [Array] args command-line arguments passed in (if any)
@param [Array] options any additional options
@param [Array] config the yeoman configuration
###
constructor: (args, options, config) ->
super args, options, config
@on "end", ->
@installDependencies skipInstall: options["skip-install"]
@pkg = JSON.parse(@readFileAsString(path.join(__dirname, "../package.json")))
askFor: ->
cb = @async()
# have Yeoman greet the user.
console.log @yeoman
prompts = [
{
name: "description"
message: "Describe your component"
default: "A sample description"
}
{
name: "componentName"
message: "What's the component's name?"
default: "default-value"
}
{
name: "authorName"
message: "What's your name?"
default: "PI:NAME:<NAME>END_PI"
}
{
name: "authorEmail"
message: "What's your e-mail?"
default: "PI:EMAIL:<EMAIL>END_PI"
}
{
name: "authorURL"
message: "What's your website?"
default: "somedomain.com"
}
{
name: "license"
message: "What's the copyright license?"
default: "MIT"
}
{
type: "confirm"
name: "requireManageRights"
message: "Does your component require admin manage rights to access it?"
}
{
type: "confirm"
name: "legacyJoomla"
message: "Support Joomla 2.5x with compatibility layer?"
}
]
@prompt prompts, ((props) ->
# for own prompt of prompts
# @prompt.name = prompt.name?
@description = props.description
@componentName = props.componentName
@authorName = props.authorName
@authorEmail = props.authorEmail
@authorURL = props.authorURL
@license = props.license
@requireManageRights = props.requireManageRights
@legacyJoomla = props.legacyJoomla
@currentDate = @_getCurrentDate()
cb()
).bind(@)
app: ->
@mkdir "app"
@mkdir "app/templates"
@template "_package.json", "package.json"
@template "_bower.json", "bower.json"
@copy "_gitignore", ".gitignore"
_getCurrentDate: ->
new Date().getUTCDate()
projectfiles: ->
@copy "editorconfig", ".editorconfig"
@copy "jshintrc", ".jshintrc"
createConfigFiles: ->
@template "_component-name.xml", @_.slugify(@componentName) + ".xml"
@template "_config.xml", "config.xml"
@template "_access.xml", "access.xml"
###
Create legacy files for fallback to Joomla 2.5x
###
createLegacyFallbackFiles: ->
@template "_legacy.php", "legacy.php" if @legacyJoomla is on
createPHPFiles: ->
@template "_component-name.php", @_.slugify(@componentName) + ".php"
@template "_router.php", "router.php"
createDatabaseFiles: ->
@template "sql/_install.mysql.utf8.sql", "sql/install.mysql.utf8.sql"
@template "sql/_uninstall.mysql.utf8.sql", "sql/uninstall.mysql.utf8.sql"
@template "_install-uninstall.php", "install-uninstall.php"
createLanguageFiles: ->
@template "languages/en-GB/_en-GB.com_component-name.ini", "languages/en-GB/en-GB.com_" + @_.slugify(@componentName) + ".ini"
@template "languages/en-GB/_en-GB.com_component-name.ini", "languages/en-GB/en-GB.com_" + @_.slugify(@componentName) + ".sys.ini"
createEmptyMVCFolders: ->
emptyMVCFolders = [
"controllers"
"helpers"
"models"
"sql"
"tables"
"views"
]
for folderName in emptyMVCFolders
@template "_index.html", "#{folderName}/index.html"
@template "_index.html", "index.html"
@template "_index.html", "languages/index.html"
@template "_index.html", "languages/en-GB/index.html"
|
[
{
"context": "g (save)'] = (test) ->\n\tcount = 0\n\tModel.withKey 'benchmarkid2', (err, model) ->\n\t\tstartTime = new Date\n\t\tdo rec",
"end": 1752,
"score": 0.7083948254585266,
"start": 1740,
"tag": "KEY",
"value": "benchmarkid2"
}
] | test/benchmarks.coffee | ajorkowski/redis-model | 1 | RedisModel = require '../lib/redis-model'
redis = require("redis").createClient()
redis.flushall()
class Model extends RedisModel
constructor: ->
super redis, 'Model'
@addFields 'field1', 'field2'
Model = new Model
exports['Pure redis (read)'] = (test) ->
count = 0
redis.hset 'MODEL_id', 'field1', 'value', ->
startTime = new Date
do rec = () ->
if count > 1000
console.log "1000 normal sequential requests done in #{new Date - startTime}ms"
test.done()
else
count++
redis.hget 'id', 'field1', ->
rec()
exports['Redis-Model (read)'] = (test) ->
count = 0
Model.withKey 'benchmarkid', (err, model) ->
model.field1 'value', ->
startTime = new Date
do rec = () ->
if count > 1000
console.log "1000 redis-model sequential requests done in #{new Date - startTime}ms"
test.done()
else
count++
model.field1 (err2, val) ->
rec()
exports['Redis-Model with locking (read)'] = (test) ->
count = 0
Model.withKey 'benchmarkid2', (err, model) ->
model.lock()
model.field1 'value'
model.field2 'value2'
model.unlock () ->
startTime = new Date
do rec = () ->
if count > 500
console.log "500 redis-model sequential requests for two fields done in #{new Date - startTime}ms"
test.done()
else
count++
model.getAll (err2, obj) ->
rec()
exports['Pure redis (save)'] = (test) ->
count = 0
startTime = new Date
do rec = () ->
if count > 1000
console.log "1000 normal sequential requests done in #{new Date - startTime}ms"
test.done()
else
count++
redis.hset 'MODEL_id2', 'field1', 'value', ->
rec()
exports['Redis-Model with locking (save)'] = (test) ->
count = 0
Model.withKey 'benchmarkid2', (err, model) ->
startTime = new Date
do rec = () ->
if count > 500
console.log "500 redis-model sequential requests for two fields done in #{new Date - startTime}ms"
test.done()
else
count++
model.lock()
model.field1 'val'
model.field2 'val2'
model.unlock ->
rec()
exports['Complete'] = (test) ->
# This is a dummy test to finish off the tests
redis.flushall ->
redis.quit()
test.done()
| 52961 | RedisModel = require '../lib/redis-model'
redis = require("redis").createClient()
redis.flushall()
class Model extends RedisModel
constructor: ->
super redis, 'Model'
@addFields 'field1', 'field2'
Model = new Model
exports['Pure redis (read)'] = (test) ->
count = 0
redis.hset 'MODEL_id', 'field1', 'value', ->
startTime = new Date
do rec = () ->
if count > 1000
console.log "1000 normal sequential requests done in #{new Date - startTime}ms"
test.done()
else
count++
redis.hget 'id', 'field1', ->
rec()
exports['Redis-Model (read)'] = (test) ->
count = 0
Model.withKey 'benchmarkid', (err, model) ->
model.field1 'value', ->
startTime = new Date
do rec = () ->
if count > 1000
console.log "1000 redis-model sequential requests done in #{new Date - startTime}ms"
test.done()
else
count++
model.field1 (err2, val) ->
rec()
exports['Redis-Model with locking (read)'] = (test) ->
count = 0
Model.withKey 'benchmarkid2', (err, model) ->
model.lock()
model.field1 'value'
model.field2 'value2'
model.unlock () ->
startTime = new Date
do rec = () ->
if count > 500
console.log "500 redis-model sequential requests for two fields done in #{new Date - startTime}ms"
test.done()
else
count++
model.getAll (err2, obj) ->
rec()
exports['Pure redis (save)'] = (test) ->
count = 0
startTime = new Date
do rec = () ->
if count > 1000
console.log "1000 normal sequential requests done in #{new Date - startTime}ms"
test.done()
else
count++
redis.hset 'MODEL_id2', 'field1', 'value', ->
rec()
exports['Redis-Model with locking (save)'] = (test) ->
count = 0
Model.withKey '<KEY>', (err, model) ->
startTime = new Date
do rec = () ->
if count > 500
console.log "500 redis-model sequential requests for two fields done in #{new Date - startTime}ms"
test.done()
else
count++
model.lock()
model.field1 'val'
model.field2 'val2'
model.unlock ->
rec()
exports['Complete'] = (test) ->
# This is a dummy test to finish off the tests
redis.flushall ->
redis.quit()
test.done()
| true | RedisModel = require '../lib/redis-model'
redis = require("redis").createClient()
redis.flushall()
class Model extends RedisModel
constructor: ->
super redis, 'Model'
@addFields 'field1', 'field2'
Model = new Model
exports['Pure redis (read)'] = (test) ->
count = 0
redis.hset 'MODEL_id', 'field1', 'value', ->
startTime = new Date
do rec = () ->
if count > 1000
console.log "1000 normal sequential requests done in #{new Date - startTime}ms"
test.done()
else
count++
redis.hget 'id', 'field1', ->
rec()
exports['Redis-Model (read)'] = (test) ->
count = 0
Model.withKey 'benchmarkid', (err, model) ->
model.field1 'value', ->
startTime = new Date
do rec = () ->
if count > 1000
console.log "1000 redis-model sequential requests done in #{new Date - startTime}ms"
test.done()
else
count++
model.field1 (err2, val) ->
rec()
exports['Redis-Model with locking (read)'] = (test) ->
count = 0
Model.withKey 'benchmarkid2', (err, model) ->
model.lock()
model.field1 'value'
model.field2 'value2'
model.unlock () ->
startTime = new Date
do rec = () ->
if count > 500
console.log "500 redis-model sequential requests for two fields done in #{new Date - startTime}ms"
test.done()
else
count++
model.getAll (err2, obj) ->
rec()
exports['Pure redis (save)'] = (test) ->
count = 0
startTime = new Date
do rec = () ->
if count > 1000
console.log "1000 normal sequential requests done in #{new Date - startTime}ms"
test.done()
else
count++
redis.hset 'MODEL_id2', 'field1', 'value', ->
rec()
exports['Redis-Model with locking (save)'] = (test) ->
count = 0
Model.withKey 'PI:KEY:<KEY>END_PI', (err, model) ->
startTime = new Date
do rec = () ->
if count > 500
console.log "500 redis-model sequential requests for two fields done in #{new Date - startTime}ms"
test.done()
else
count++
model.lock()
model.field1 'val'
model.field2 'val2'
model.unlock ->
rec()
exports['Complete'] = (test) ->
# This is a dummy test to finish off the tests
redis.flushall ->
redis.quit()
test.done()
|
[
{
"context": "playName in a React component definition\n# @author Yannick Croissant\n###\n'use strict'\n\n# -----------------------------",
"end": 108,
"score": 0.9998201727867126,
"start": 91,
"tag": "NAME",
"value": "Yannick Croissant"
}
] | src/tests/rules/display-name.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Prevent missing displayName in a React component definition
# @author Yannick Croissant
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/display-name'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'display-name', rule,
valid: [
code: '''
Hello = createReactClass({
displayName: 'Hello',
render: ->
return <div>Hello {this.props.name}</div>
})
'''
options: [ignoreTranspilerName: yes]
,
code: '''
Hello = React.createClass({
displayName: 'Hello',
render: ->
return <div>Hello {this.props.name}</div>
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
,
code: '''
class Hello extends React.Component
render: ->
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
code: '''
class Hello
render: ->
return 'Hello World'
'''
,
code: '''
class Hello extends Greetings
@text = 'Hello World'
render: ->
return Hello.text
'''
,
# ,
# # parser: 'babel-eslint'
# code: """
# class Hello extends React.Component {
# static get displayName() {
# return 'Hello'
# }
# render() {
# return <div>Hello {this.props.name}</div>
# }
# }
# """
# options: [ignoreTranspilerName: yes]
code: '''
class Hello extends React.Component
@displayName: 'Widget'
render: ->
return <div>Hello {this.props.name}</div>
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
,
code: '''
class Hello extends React.Component
render: ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
export default class Hello
render: ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = null
Hello = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
,
code: '''
module.exports = createReactClass({
"displayName": "Hello",
"render": ->
return <div>Hello {this.props.name}</div>
})
'''
,
code: '''
Hello = createReactClass({
displayName: 'Hello',
render: ->
{ a, ...b } = obj
c = { ...d }
return <div />
})
'''
options: [ignoreTranspilerName: yes]
,
code: '''
export default class
render: ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = ->
<div>Hello {@props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = () =>
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
module.exports = Hello = ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = ->
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = () =>
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = ->
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Mixins = {
Greetings: {
Hello: ->
return <div>Hello {this.props.name}</div>
}
}
Mixins.Greetings.Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <div>{this._renderHello()}</div>
_renderHello: ->
return <span>Hello {this.props.name}</span>
})
'''
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
displayName: 'Hello',
render: ->
return <div>{this._renderHello()}</div>
_renderHello: ->
return <span>Hello {this.props.name}</span>
})
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Mixin = {
Button: ->
return (
<button />
)
}
'''
,
# parser: 'babel-eslint'
code: '''
obj = {
pouf: ->
return any
}
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
obj = {
pouf: ->
return any
}
'''
,
# parser: 'babel-eslint'
code: '''
export default {
renderHello: ->
{name} = this.props
return <div>{name}</div>
}
'''
,
# parser: 'babel-eslint'
code: '''
import React, { createClass } from 'react'
export default createClass({
displayName: 'Foo',
render: ->
return <h1>foo</h1>
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
,
# parser: 'babel-eslint'
code: '''
import React, {Component} from "react"
someDecorator = (ComposedComponent) ->
return class MyDecorator extends Component
render: -> <ComposedComponent {...@props} />
module.exports = someDecorator
'''
,
# parser: 'babel-eslint'
code: '''
element = (
<Media query={query} render={() =>
renderWasCalled = true
return <div/>
}/>
)
'''
,
# parser: 'babel-eslint'
code: '''
element = (
<Media query={query} render={->
renderWasCalled = true
return <div/>
}/>
)
'''
,
# parser: 'babel-eslint'
code: '''
module.exports = {
createElement: (tagName) => document.createElement(tagName)
}
'''
,
# parser: 'babel-eslint'
code: '''
{ createElement } = document
createElement("a")
'''
# parser: 'babel-eslint'
]
invalid: [
code: '''
Hello = createReactClass({
render: ->
return React.createElement("div", {}, "text content")
})
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = React.createClass({
render: ->
return React.createElement("div", {}, "text content")
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
class Hello extends React.Component
render: ->
return <div>Hello {this.props.name}</div>
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
HelloComponent = ->
return createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
module.exports = HelloComponent()
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
module.exports = () =>
return <div>Hello {props.name}</div>
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
module.exports = ->
<div>Hello {props.name}</div>
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
module.exports = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = createReactClass({
_renderHello: ->
return <span>Hello {this.props.name}</span>
render: ->
return <div>{this._renderHello()}</div>
})
'''
options: [ignoreTranspilerName: yes]
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = Foo.createClass({
_renderHello: ->
return <span>Hello {this.props.name}</span>
render: ->
return <div>{this._renderHello()}</div>
})
'''
options: [ignoreTranspilerName: yes]
# parser: 'babel-eslint'
settings:
react:
pragma: 'Foo'
createClass: 'createClass'
errors: [message: 'Component definition is missing display name']
,
code: '''
###* @jsx Foo ###
Hello = Foo.createClass({
_renderHello: ->
return <span>Hello {this.props.name}</span>
render: ->
return <div>{this._renderHello()}</div>
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
Mixin = {
Button: ->
return (
<button />
)
}
'''
options: [ignoreTranspilerName: yes]
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
import React, { createElement } from "react"
export default (props) =>
return createElement("div", {}, "hello")
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
import React from "react"
{ createElement } = React
export default (props) =>
return createElement("div", {}, "hello")
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
import React from "react"
createElement = React.createElement
export default (props) =>
return createElement("div", {}, "hello")
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
]
| 217642 | ###*
# @fileoverview Prevent missing displayName in a React component definition
# @author <NAME>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/display-name'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'display-name', rule,
valid: [
code: '''
Hello = createReactClass({
displayName: 'Hello',
render: ->
return <div>Hello {this.props.name}</div>
})
'''
options: [ignoreTranspilerName: yes]
,
code: '''
Hello = React.createClass({
displayName: 'Hello',
render: ->
return <div>Hello {this.props.name}</div>
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
,
code: '''
class Hello extends React.Component
render: ->
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
code: '''
class Hello
render: ->
return 'Hello World'
'''
,
code: '''
class Hello extends Greetings
@text = 'Hello World'
render: ->
return Hello.text
'''
,
# ,
# # parser: 'babel-eslint'
# code: """
# class Hello extends React.Component {
# static get displayName() {
# return 'Hello'
# }
# render() {
# return <div>Hello {this.props.name}</div>
# }
# }
# """
# options: [ignoreTranspilerName: yes]
code: '''
class Hello extends React.Component
@displayName: 'Widget'
render: ->
return <div>Hello {this.props.name}</div>
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
,
code: '''
class Hello extends React.Component
render: ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
export default class Hello
render: ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = null
Hello = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
,
code: '''
module.exports = createReactClass({
"displayName": "Hello",
"render": ->
return <div>Hello {this.props.name}</div>
})
'''
,
code: '''
Hello = createReactClass({
displayName: 'Hello',
render: ->
{ a, ...b } = obj
c = { ...d }
return <div />
})
'''
options: [ignoreTranspilerName: yes]
,
code: '''
export default class
render: ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = ->
<div>Hello {@props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = () =>
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
module.exports = Hello = ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = ->
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = () =>
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = ->
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Mixins = {
Greetings: {
Hello: ->
return <div>Hello {this.props.name}</div>
}
}
Mixins.Greetings.Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <div>{this._renderHello()}</div>
_renderHello: ->
return <span>Hello {this.props.name}</span>
})
'''
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
displayName: 'Hello',
render: ->
return <div>{this._renderHello()}</div>
_renderHello: ->
return <span>Hello {this.props.name}</span>
})
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Mixin = {
Button: ->
return (
<button />
)
}
'''
,
# parser: 'babel-eslint'
code: '''
obj = {
pouf: ->
return any
}
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
obj = {
pouf: ->
return any
}
'''
,
# parser: 'babel-eslint'
code: '''
export default {
renderHello: ->
{name} = this.props
return <div>{name}</div>
}
'''
,
# parser: 'babel-eslint'
code: '''
import React, { createClass } from 'react'
export default createClass({
displayName: 'Foo',
render: ->
return <h1>foo</h1>
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
,
# parser: 'babel-eslint'
code: '''
import React, {Component} from "react"
someDecorator = (ComposedComponent) ->
return class MyDecorator extends Component
render: -> <ComposedComponent {...@props} />
module.exports = someDecorator
'''
,
# parser: 'babel-eslint'
code: '''
element = (
<Media query={query} render={() =>
renderWasCalled = true
return <div/>
}/>
)
'''
,
# parser: 'babel-eslint'
code: '''
element = (
<Media query={query} render={->
renderWasCalled = true
return <div/>
}/>
)
'''
,
# parser: 'babel-eslint'
code: '''
module.exports = {
createElement: (tagName) => document.createElement(tagName)
}
'''
,
# parser: 'babel-eslint'
code: '''
{ createElement } = document
createElement("a")
'''
# parser: 'babel-eslint'
]
invalid: [
code: '''
Hello = createReactClass({
render: ->
return React.createElement("div", {}, "text content")
})
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = React.createClass({
render: ->
return React.createElement("div", {}, "text content")
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
class Hello extends React.Component
render: ->
return <div>Hello {this.props.name}</div>
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
HelloComponent = ->
return createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
module.exports = HelloComponent()
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
module.exports = () =>
return <div>Hello {props.name}</div>
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
module.exports = ->
<div>Hello {props.name}</div>
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
module.exports = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = createReactClass({
_renderHello: ->
return <span>Hello {this.props.name}</span>
render: ->
return <div>{this._renderHello()}</div>
})
'''
options: [ignoreTranspilerName: yes]
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = Foo.createClass({
_renderHello: ->
return <span>Hello {this.props.name}</span>
render: ->
return <div>{this._renderHello()}</div>
})
'''
options: [ignoreTranspilerName: yes]
# parser: 'babel-eslint'
settings:
react:
pragma: 'Foo'
createClass: 'createClass'
errors: [message: 'Component definition is missing display name']
,
code: '''
###* @jsx Foo ###
Hello = Foo.createClass({
_renderHello: ->
return <span>Hello {this.props.name}</span>
render: ->
return <div>{this._renderHello()}</div>
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
Mixin = {
Button: ->
return (
<button />
)
}
'''
options: [ignoreTranspilerName: yes]
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
import React, { createElement } from "react"
export default (props) =>
return createElement("div", {}, "hello")
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
import React from "react"
{ createElement } = React
export default (props) =>
return createElement("div", {}, "hello")
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
import React from "react"
createElement = React.createElement
export default (props) =>
return createElement("div", {}, "hello")
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
]
| true | ###*
# @fileoverview Prevent missing displayName in a React component definition
# @author PI:NAME:<NAME>END_PI
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/display-name'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'display-name', rule,
valid: [
code: '''
Hello = createReactClass({
displayName: 'Hello',
render: ->
return <div>Hello {this.props.name}</div>
})
'''
options: [ignoreTranspilerName: yes]
,
code: '''
Hello = React.createClass({
displayName: 'Hello',
render: ->
return <div>Hello {this.props.name}</div>
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
,
code: '''
class Hello extends React.Component
render: ->
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
code: '''
class Hello
render: ->
return 'Hello World'
'''
,
code: '''
class Hello extends Greetings
@text = 'Hello World'
render: ->
return Hello.text
'''
,
# ,
# # parser: 'babel-eslint'
# code: """
# class Hello extends React.Component {
# static get displayName() {
# return 'Hello'
# }
# render() {
# return <div>Hello {this.props.name}</div>
# }
# }
# """
# options: [ignoreTranspilerName: yes]
code: '''
class Hello extends React.Component
@displayName: 'Widget'
render: ->
return <div>Hello {this.props.name}</div>
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
,
code: '''
class Hello extends React.Component
render: ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
export default class Hello
render: ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = null
Hello = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
,
code: '''
module.exports = createReactClass({
"displayName": "Hello",
"render": ->
return <div>Hello {this.props.name}</div>
})
'''
,
code: '''
Hello = createReactClass({
displayName: 'Hello',
render: ->
{ a, ...b } = obj
c = { ...d }
return <div />
})
'''
options: [ignoreTranspilerName: yes]
,
code: '''
export default class
render: ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = ->
<div>Hello {@props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = () =>
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
module.exports = Hello = ->
return <div>Hello {this.props.name}</div>
'''
,
# parser: 'babel-eslint'
code: '''
Hello = ->
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = () =>
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = ->
return <div>Hello {this.props.name}</div>
Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Mixins = {
Greetings: {
Hello: ->
return <div>Hello {this.props.name}</div>
}
}
Mixins.Greetings.Hello.displayName = 'Hello'
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <div>{this._renderHello()}</div>
_renderHello: ->
return <span>Hello {this.props.name}</span>
})
'''
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
displayName: 'Hello',
render: ->
return <div>{this._renderHello()}</div>
_renderHello: ->
return <span>Hello {this.props.name}</span>
})
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
Mixin = {
Button: ->
return (
<button />
)
}
'''
,
# parser: 'babel-eslint'
code: '''
obj = {
pouf: ->
return any
}
'''
options: [ignoreTranspilerName: yes]
,
# parser: 'babel-eslint'
code: '''
obj = {
pouf: ->
return any
}
'''
,
# parser: 'babel-eslint'
code: '''
export default {
renderHello: ->
{name} = this.props
return <div>{name}</div>
}
'''
,
# parser: 'babel-eslint'
code: '''
import React, { createClass } from 'react'
export default createClass({
displayName: 'Foo',
render: ->
return <h1>foo</h1>
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
,
# parser: 'babel-eslint'
code: '''
import React, {Component} from "react"
someDecorator = (ComposedComponent) ->
return class MyDecorator extends Component
render: -> <ComposedComponent {...@props} />
module.exports = someDecorator
'''
,
# parser: 'babel-eslint'
code: '''
element = (
<Media query={query} render={() =>
renderWasCalled = true
return <div/>
}/>
)
'''
,
# parser: 'babel-eslint'
code: '''
element = (
<Media query={query} render={->
renderWasCalled = true
return <div/>
}/>
)
'''
,
# parser: 'babel-eslint'
code: '''
module.exports = {
createElement: (tagName) => document.createElement(tagName)
}
'''
,
# parser: 'babel-eslint'
code: '''
{ createElement } = document
createElement("a")
'''
# parser: 'babel-eslint'
]
invalid: [
code: '''
Hello = createReactClass({
render: ->
return React.createElement("div", {}, "text content")
})
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = React.createClass({
render: ->
return React.createElement("div", {}, "text content")
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
class Hello extends React.Component
render: ->
return <div>Hello {this.props.name}</div>
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
HelloComponent = ->
return createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
module.exports = HelloComponent()
'''
options: [ignoreTranspilerName: yes]
errors: [message: 'Component definition is missing display name']
,
code: '''
module.exports = () =>
return <div>Hello {props.name}</div>
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
module.exports = ->
<div>Hello {props.name}</div>
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
module.exports = createReactClass({
render: ->
return <div>Hello {this.props.name}</div>
})
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = createReactClass({
_renderHello: ->
return <span>Hello {this.props.name}</span>
render: ->
return <div>{this._renderHello()}</div>
})
'''
options: [ignoreTranspilerName: yes]
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
Hello = Foo.createClass({
_renderHello: ->
return <span>Hello {this.props.name}</span>
render: ->
return <div>{this._renderHello()}</div>
})
'''
options: [ignoreTranspilerName: yes]
# parser: 'babel-eslint'
settings:
react:
pragma: 'Foo'
createClass: 'createClass'
errors: [message: 'Component definition is missing display name']
,
code: '''
###* @jsx Foo ###
Hello = Foo.createClass({
_renderHello: ->
return <span>Hello {this.props.name}</span>
render: ->
return <div>{this._renderHello()}</div>
})
'''
options: [ignoreTranspilerName: yes]
settings:
react:
createClass: 'createClass'
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
Mixin = {
Button: ->
return (
<button />
)
}
'''
options: [ignoreTranspilerName: yes]
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
import React, { createElement } from "react"
export default (props) =>
return createElement("div", {}, "hello")
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
import React from "react"
{ createElement } = React
export default (props) =>
return createElement("div", {}, "hello")
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
,
code: '''
import React from "react"
createElement = React.createElement
export default (props) =>
return createElement("div", {}, "hello")
'''
# parser: 'babel-eslint'
errors: [message: 'Component definition is missing display name']
]
|
[
{
"context": " [\"do\", \"re\", \"mi\", \"fa\", \"so\"]\n singers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n $('.account').attr ",
"end": 7829,
"score": 0.5908118486404419,
"start": 7824,
"tag": "NAME",
"value": "agger"
},
{
"context": "n [47, 92, 13]\n print inspect \"My name is \\#{@name}\"\n \"\"\".split /\\n/\n for sample in sample_lis",
"end": 10645,
"score": 0.9983677864074707,
"start": 10640,
"tag": "USERNAME",
"value": "@name"
},
{
"context": "()->\n sample_list = \"\"\"\n sam = new Snake \"Sammy the Python\"\n tom = new Horse \"Tommy the Palomino\"\n ",
"end": 11274,
"score": 0.9095856547355652,
"start": 11258,
"tag": "NAME",
"value": "Sammy the Python"
},
{
"context": "w Snake \"Sammy the Python\"\n tom = new Horse \"Tommy the Palomino\"\n sam.move()\n tom.move()\n String::",
"end": 11317,
"score": 0.9517411589622498,
"start": 11299,
"tag": "NAME",
"value": "Tommy the Palomino"
},
{
"context": "average'} = options\n tim = new Person name: 'Tim', age: 4\n \"\"\".split /\\n/ #\"\n for sample in ",
"end": 12053,
"score": 0.99977707862854,
"start": 12050,
"tag": "NAME",
"value": "Tim"
}
] | test/gram.coffee | hu2prod/scriptscript | 1 | assert = require 'assert'
util = require 'fy/test_util'
{_tokenize} = require '../src/tokenizer'
{_parse } = require '../src/grammar'
full = (t)->
tok = _tokenize(t)
_parse(tok, mode_full:true)
describe 'gram section', ()->
# fuckups
###
a /= b / c
###
sample_list = '''
HEAT_UP
a
+a
a+b
1
a+1
a+a+a
(a)
a+a*a
a|b
a|b|c
-a+b
~a
!a
typeof a
not a
void a
new a
delete a
a + b
a - b
a * b
a / b
a % b
a ** b
a // b
a %% b
a and b
a && b
a or b
a || b
a xor b
a < b
a <= b
a == b
a > b
a >= b
a != b
a << b
a >> b
a >>> b
a instanceof b
a++
a--
a+ b
a +b
a + b
a?
a = b
a += b
a -= b
a *= b
a /= b
a %= b
a **= b
a //= b
a %%= b
a <<= b
a >>= b
a >>>= b
a and= b
a or= b
a xor= b
a ?= b
a[b]
a.b
a.0
a .0
a.rgb
a.0123
a .0123
1
1.1
1.
1e1
1e+1
1e-1
-1e-1
a()
a(b)
a(b,c)
a(b,c=d)
# a
@
@a
@.a
a:b
a:b,c:d
(a):b
a ? b : c
#comment
a#comment
"abcd"
'abcd'
"a#{b+c}d"
'''.split /\n/g
# NOTE a +b is NOT bin_op. It's function call
for sample in sample_list
do (sample)->
it sample, ()->
full sample
# BUG in gram2
# sample_list = """
# a +
# b
# """.split /\n?---\n?/g
# for sample in sample_list
# continue if !sample
# do (sample)->
# it JSON.stringify(sample), ()->
# full sample
sample_list = """
a ?
a++++
a++++ # a
a++ ++
a++ ++ # a
a ++
a ++ # a
a+
a+ # a
кирилица
a === b
a === b # a
a !== b
a !== b # a
++a
++a # a
--a
--a # a
+ a
+ a # a
a ? b:c : d
@=1
""".split /\n/g
# KNOWN fuckup a ? b:c : d # comment
# b:c can be bracketless hash and c:d can be bracketless hash
for sample in sample_list
do (sample)->
it "#{sample} should not parse", ()->
util.throws ()->
full sample
it 'a+a*a priority', ()->
ret = full 'a+a*a'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[1].value_view, "+"
it 'a*a+a priority', ()->
ret = full 'a*a+a'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[1].value_view, "+"
it 'void a+a priority', ()->
ret = full 'void a+a'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[0].value_view, "void"
it '-a+b priority', ()->
ret = full '-a+b'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[1].value_view, "+"
describe 'macro-block section', ()->
describe 'array section', ()->
sample_list = """
loop
a
---
if a
b
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
it '1a1 throw', ()->
util.throws ()->
full '1a1'
describe 'array section', ()->
sample_list = """
[]
---
[ ]
---
[a]
---
[a,b]
---
[a,b,c]
---
[
]
---
[
]
---
[
]
---
[
a
]
---
[
a,b
]
---
[
a
b
]
---
[
a,
b
]
---
[
a
,b
]
---
[
a
]
---
[
a,b
]
---
[
a
b
]
---
[
a,
b
]
---
[
a
,b
]
---
[0 .. 2]
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
# sample_list = """
# [a
# ]
# ---
# [
# a]
# """.split /\n?---\n?/g
# for sample in sample_list
# continue if !sample
# do (sample)->
# it "#{JSON.stringify(sample)} bad codestyle not parsed", ()-> # или говнокодеры должны страдать
# util.throws ()->
# full sample
###
string not defined yet
---
{\"a\":b}
---
{'a':b}
###
describe 'hash section', ()->
sample_list = """
{}
---
{ }
---
{a}
---
{a:b}
---
{1:b}
---
{a,b}
---
{a:1,b:2}
---
{a:1,b}
---
{a,b,c}
---
{
}
---
{
}
---
{
}
---
{
a
}
---
{
a
b
}
---
{
a,
b
}
---
{
a
,b
}
---
{
a
}
---
{
a
b
}
---
{
a : b
}
---
{
(a) : b
}
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
# sample_list = """
# [a
# ]
# ---
# [
# a]
# """.split /\n?---\n?/g
# for sample in sample_list
# continue if !sample
# do (sample)->
# it "#{JSON.stringify(sample)} bad codestyle not parsed", ()-> # или говнокодеры должны страдать
# util.throws ()->
# full sample
describe 'pipe section', ()->
sample_list = """
a|b
---
a | | b
---
a | b | c
---
a |
| b
---
a |
| b | c
---
a |
| b
| c
---
a |
| b
| c | d
---
a |
| b | c
| d | e
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
describe 'function decl section', ()->
sample_list = """
->
---
=>
---
()->
---
()->a
---
(a)->a
---
(a,b)->a
---
(a,b=c)->a
---
(a:int)->a
---
(a:int):int->a
---
(a:int):int=>a
---
()->
a
---
()->
a
b
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
describe "Gram TODO: all exapmles from coffeescript documentation (oneliners only) should be tokenizable and parsable", ()->
# check only if it doesn't throw
describe "Overview", ()->
sample_list = """
number = 42
opposite = true
number = -42 if opposite
square = (x) -> x * x
list = [1, 2, 3, 4, 5]
race = (winner, runners...) -> print winner, runners
alert "I knew it!" if elvis?
cubes = (math.cube num for num in list)
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Functions", ()->
sample_list = """
square = (x) -> x * x
cube = (x) -> square(x) * x
fill = (container, liquid = "coffee") -> "Filling the \#{container} with \#{liquid}..."
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Objects and Arrays", ()->
sample_list = """
song = ["do", "re", "mi", "fa", "so"]
singers = {Jagger: "Rock", Elvis: "Roll"}
$('.account').attr class: 'active'
log object.class
turtle = {name, mask, weapon}
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "If, Else, Unless, and Conditional Assignment", ()->
sample_list = """
mood = greatlyImproved if singing
date = if friday then sue else jill
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Splats…", ()->
sample_list = """
awardMedals contenders...
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Loops and Comprehensions", ()->
sample_list = """
eat food for food in ['toast', 'cheese', 'wine']
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
shortNames = (name for name in list when name.length < 5)
countdown = (num for num in [10..1])
evens = (x for x in [0..10] by 2)
browser.closeCurrentTab() for [0...count]
yearsOld = max: 10, ida: 9, tim: 11
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Array Slicing and Splicing with Ranges", ()->
sample_list = """
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
start = numbers[0..2]
middle = numbers[3...-2]
end = numbers[-2..]
copy = numbers[..]
numbers[3..6] = [-3, -4, -5, -6]
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Everything is an Expression (at least, as much as possible)", ()->
sample_list = """
eldest = if 24 > 21 then "Liz" else "Ike"
six = (one = 1) + (two = 2) + (three = 3)
globals = (name for name of window)[0...10]
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Operators and Aliases", ()->
sample_list = """
-7 % 5 == -2 # The remainder of 7 / 5
-7 %% 5 == 3 # n %% 5 is always between 0 and 4
tabs.selectTabAtIndex((tabs.currentIndex - count) %% tabs.length)
launch() if ignition is on
volume = 10 if band isnt SpinalTap
letTheWildRumpusBegin() unless answer is no
if car.speed < limit then accelerate()
winner = yes if pick in [47, 92, 13]
print inspect "My name is \#{@name}"
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "The Existential Operator", ()->
sample_list = """
solipsism = true if mind? and not world?
speed = 0
speed ?= 15
footprints = yeti ? "bear"
zip = lottery.drawWinner?().address?.zipcode
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Classes, Inheritance, and Super", ()->
sample_list = """
sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
sam.move()
tom.move()
String::dasherize = -> this.replace /_/g, "-"
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Destructuring Assignment", ()->
sample_list = """
[theBait, theSwitch] = [theSwitch, theBait]
weatherReport = (location) -> [location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
{sculptor} = futurists
{poet: {name, address: [street, city]}} = futurists
[open, contents..., close] = tag.split("")
[first, ..., last] = text.split " "
{@name, @age, @height = 'average'} = options
tim = new Person name: 'Tim', age: 4
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
# describe "Bound Functions, Generator Functions", ()->
describe "Embedded JavaScript", ()->
sample_list = """
hi = `function() {return [document.title, "Hello JavaScript"].join(": ");}`
markdown = `function () {return \\`In Markdown, write code like \\\\\\`this\\\\\\`\\`;}`
```function time() {return `The time is ${new Date().toLocaleTimeString()}`;}```
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
# describe "Switch/When/Else", ()->
# describe "Try/Catch/Finally", ()->
describe "Chained Comparisons", ()->
sample_list = """
healthy = 200 > cholesterol > 60
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "String Interpolation, Block Strings, and Block Comments", ()->
sample_list = """
quote = "A picture is a fact. -- \#{ author }"
sentence = "\#{ 22 / 7 } is a decent approximation of π"
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Tagged Template Literals", ()->
sample_list = """
upperCaseExpr = (textParts, expressions...) -> textParts.reduce (text, textPart, i) -> text + expressions[i - 1].toUpperCase() + textPart
greet = (name, adjective) -> upperCaseExpr\"""Hi \#{name}. You look \#{adjective}!\"""
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
# describe "Block Regular Expressions", ()->
describe "Modules", ()->
sample_list = """
import 'local-file.coffee'
import 'coffee-script'
import _ from 'underscore'
import * as underscore from 'underscore'
import { now } from 'underscore'
import { now as currentTimestamp } from 'underscore'
import { first, last } from 'underscore'
import utilityBelt, { each } from 'underscore'
export default Math
export square = (x) -> x * x
export { sqrt }
export { sqrt as squareRoot }
export { Mathematics as default, sqrt as squareRoot }
export * from 'underscore'
export { max, min } from 'underscore'
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Gram TODO: fuckups", ()->
it "a/2+b/7" # Parsing error. No proper combination found
it "{1}" # Parsing error. No proper combination found
| 26530 | assert = require 'assert'
util = require 'fy/test_util'
{_tokenize} = require '../src/tokenizer'
{_parse } = require '../src/grammar'
full = (t)->
tok = _tokenize(t)
_parse(tok, mode_full:true)
describe 'gram section', ()->
# fuckups
###
a /= b / c
###
sample_list = '''
HEAT_UP
a
+a
a+b
1
a+1
a+a+a
(a)
a+a*a
a|b
a|b|c
-a+b
~a
!a
typeof a
not a
void a
new a
delete a
a + b
a - b
a * b
a / b
a % b
a ** b
a // b
a %% b
a and b
a && b
a or b
a || b
a xor b
a < b
a <= b
a == b
a > b
a >= b
a != b
a << b
a >> b
a >>> b
a instanceof b
a++
a--
a+ b
a +b
a + b
a?
a = b
a += b
a -= b
a *= b
a /= b
a %= b
a **= b
a //= b
a %%= b
a <<= b
a >>= b
a >>>= b
a and= b
a or= b
a xor= b
a ?= b
a[b]
a.b
a.0
a .0
a.rgb
a.0123
a .0123
1
1.1
1.
1e1
1e+1
1e-1
-1e-1
a()
a(b)
a(b,c)
a(b,c=d)
# a
@
@a
@.a
a:b
a:b,c:d
(a):b
a ? b : c
#comment
a#comment
"abcd"
'abcd'
"a#{b+c}d"
'''.split /\n/g
# NOTE a +b is NOT bin_op. It's function call
for sample in sample_list
do (sample)->
it sample, ()->
full sample
# BUG in gram2
# sample_list = """
# a +
# b
# """.split /\n?---\n?/g
# for sample in sample_list
# continue if !sample
# do (sample)->
# it JSON.stringify(sample), ()->
# full sample
sample_list = """
a ?
a++++
a++++ # a
a++ ++
a++ ++ # a
a ++
a ++ # a
a+
a+ # a
кирилица
a === b
a === b # a
a !== b
a !== b # a
++a
++a # a
--a
--a # a
+ a
+ a # a
a ? b:c : d
@=1
""".split /\n/g
# KNOWN fuckup a ? b:c : d # comment
# b:c can be bracketless hash and c:d can be bracketless hash
for sample in sample_list
do (sample)->
it "#{sample} should not parse", ()->
util.throws ()->
full sample
it 'a+a*a priority', ()->
ret = full 'a+a*a'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[1].value_view, "+"
it 'a*a+a priority', ()->
ret = full 'a*a+a'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[1].value_view, "+"
it 'void a+a priority', ()->
ret = full 'void a+a'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[0].value_view, "void"
it '-a+b priority', ()->
ret = full '-a+b'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[1].value_view, "+"
describe 'macro-block section', ()->
describe 'array section', ()->
sample_list = """
loop
a
---
if a
b
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
it '1a1 throw', ()->
util.throws ()->
full '1a1'
describe 'array section', ()->
sample_list = """
[]
---
[ ]
---
[a]
---
[a,b]
---
[a,b,c]
---
[
]
---
[
]
---
[
]
---
[
a
]
---
[
a,b
]
---
[
a
b
]
---
[
a,
b
]
---
[
a
,b
]
---
[
a
]
---
[
a,b
]
---
[
a
b
]
---
[
a,
b
]
---
[
a
,b
]
---
[0 .. 2]
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
# sample_list = """
# [a
# ]
# ---
# [
# a]
# """.split /\n?---\n?/g
# for sample in sample_list
# continue if !sample
# do (sample)->
# it "#{JSON.stringify(sample)} bad codestyle not parsed", ()-> # или говнокодеры должны страдать
# util.throws ()->
# full sample
###
string not defined yet
---
{\"a\":b}
---
{'a':b}
###
describe 'hash section', ()->
sample_list = """
{}
---
{ }
---
{a}
---
{a:b}
---
{1:b}
---
{a,b}
---
{a:1,b:2}
---
{a:1,b}
---
{a,b,c}
---
{
}
---
{
}
---
{
}
---
{
a
}
---
{
a
b
}
---
{
a,
b
}
---
{
a
,b
}
---
{
a
}
---
{
a
b
}
---
{
a : b
}
---
{
(a) : b
}
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
# sample_list = """
# [a
# ]
# ---
# [
# a]
# """.split /\n?---\n?/g
# for sample in sample_list
# continue if !sample
# do (sample)->
# it "#{JSON.stringify(sample)} bad codestyle not parsed", ()-> # или говнокодеры должны страдать
# util.throws ()->
# full sample
describe 'pipe section', ()->
sample_list = """
a|b
---
a | | b
---
a | b | c
---
a |
| b
---
a |
| b | c
---
a |
| b
| c
---
a |
| b
| c | d
---
a |
| b | c
| d | e
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
describe 'function decl section', ()->
sample_list = """
->
---
=>
---
()->
---
()->a
---
(a)->a
---
(a,b)->a
---
(a,b=c)->a
---
(a:int)->a
---
(a:int):int->a
---
(a:int):int=>a
---
()->
a
---
()->
a
b
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
describe "Gram TODO: all exapmles from coffeescript documentation (oneliners only) should be tokenizable and parsable", ()->
# check only if it doesn't throw
describe "Overview", ()->
sample_list = """
number = 42
opposite = true
number = -42 if opposite
square = (x) -> x * x
list = [1, 2, 3, 4, 5]
race = (winner, runners...) -> print winner, runners
alert "I knew it!" if elvis?
cubes = (math.cube num for num in list)
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Functions", ()->
sample_list = """
square = (x) -> x * x
cube = (x) -> square(x) * x
fill = (container, liquid = "coffee") -> "Filling the \#{container} with \#{liquid}..."
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Objects and Arrays", ()->
sample_list = """
song = ["do", "re", "mi", "fa", "so"]
singers = {J<NAME>: "Rock", Elvis: "Roll"}
$('.account').attr class: 'active'
log object.class
turtle = {name, mask, weapon}
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "If, Else, Unless, and Conditional Assignment", ()->
sample_list = """
mood = greatlyImproved if singing
date = if friday then sue else jill
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Splats…", ()->
sample_list = """
awardMedals contenders...
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Loops and Comprehensions", ()->
sample_list = """
eat food for food in ['toast', 'cheese', 'wine']
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
shortNames = (name for name in list when name.length < 5)
countdown = (num for num in [10..1])
evens = (x for x in [0..10] by 2)
browser.closeCurrentTab() for [0...count]
yearsOld = max: 10, ida: 9, tim: 11
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Array Slicing and Splicing with Ranges", ()->
sample_list = """
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
start = numbers[0..2]
middle = numbers[3...-2]
end = numbers[-2..]
copy = numbers[..]
numbers[3..6] = [-3, -4, -5, -6]
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Everything is an Expression (at least, as much as possible)", ()->
sample_list = """
eldest = if 24 > 21 then "Liz" else "Ike"
six = (one = 1) + (two = 2) + (three = 3)
globals = (name for name of window)[0...10]
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Operators and Aliases", ()->
sample_list = """
-7 % 5 == -2 # The remainder of 7 / 5
-7 %% 5 == 3 # n %% 5 is always between 0 and 4
tabs.selectTabAtIndex((tabs.currentIndex - count) %% tabs.length)
launch() if ignition is on
volume = 10 if band isnt SpinalTap
letTheWildRumpusBegin() unless answer is no
if car.speed < limit then accelerate()
winner = yes if pick in [47, 92, 13]
print inspect "My name is \#{@name}"
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "The Existential Operator", ()->
sample_list = """
solipsism = true if mind? and not world?
speed = 0
speed ?= 15
footprints = yeti ? "bear"
zip = lottery.drawWinner?().address?.zipcode
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Classes, Inheritance, and Super", ()->
sample_list = """
sam = new Snake "<NAME>"
tom = new Horse "<NAME>"
sam.move()
tom.move()
String::dasherize = -> this.replace /_/g, "-"
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Destructuring Assignment", ()->
sample_list = """
[theBait, theSwitch] = [theSwitch, theBait]
weatherReport = (location) -> [location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
{sculptor} = futurists
{poet: {name, address: [street, city]}} = futurists
[open, contents..., close] = tag.split("")
[first, ..., last] = text.split " "
{@name, @age, @height = 'average'} = options
tim = new Person name: '<NAME>', age: 4
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
# describe "Bound Functions, Generator Functions", ()->
describe "Embedded JavaScript", ()->
sample_list = """
hi = `function() {return [document.title, "Hello JavaScript"].join(": ");}`
markdown = `function () {return \\`In Markdown, write code like \\\\\\`this\\\\\\`\\`;}`
```function time() {return `The time is ${new Date().toLocaleTimeString()}`;}```
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
# describe "Switch/When/Else", ()->
# describe "Try/Catch/Finally", ()->
describe "Chained Comparisons", ()->
sample_list = """
healthy = 200 > cholesterol > 60
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "String Interpolation, Block Strings, and Block Comments", ()->
sample_list = """
quote = "A picture is a fact. -- \#{ author }"
sentence = "\#{ 22 / 7 } is a decent approximation of π"
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Tagged Template Literals", ()->
sample_list = """
upperCaseExpr = (textParts, expressions...) -> textParts.reduce (text, textPart, i) -> text + expressions[i - 1].toUpperCase() + textPart
greet = (name, adjective) -> upperCaseExpr\"""Hi \#{name}. You look \#{adjective}!\"""
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
# describe "Block Regular Expressions", ()->
describe "Modules", ()->
sample_list = """
import 'local-file.coffee'
import 'coffee-script'
import _ from 'underscore'
import * as underscore from 'underscore'
import { now } from 'underscore'
import { now as currentTimestamp } from 'underscore'
import { first, last } from 'underscore'
import utilityBelt, { each } from 'underscore'
export default Math
export square = (x) -> x * x
export { sqrt }
export { sqrt as squareRoot }
export { Mathematics as default, sqrt as squareRoot }
export * from 'underscore'
export { max, min } from 'underscore'
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Gram TODO: fuckups", ()->
it "a/2+b/7" # Parsing error. No proper combination found
it "{1}" # Parsing error. No proper combination found
| true | assert = require 'assert'
util = require 'fy/test_util'
{_tokenize} = require '../src/tokenizer'
{_parse } = require '../src/grammar'
full = (t)->
tok = _tokenize(t)
_parse(tok, mode_full:true)
describe 'gram section', ()->
# fuckups
###
a /= b / c
###
sample_list = '''
HEAT_UP
a
+a
a+b
1
a+1
a+a+a
(a)
a+a*a
a|b
a|b|c
-a+b
~a
!a
typeof a
not a
void a
new a
delete a
a + b
a - b
a * b
a / b
a % b
a ** b
a // b
a %% b
a and b
a && b
a or b
a || b
a xor b
a < b
a <= b
a == b
a > b
a >= b
a != b
a << b
a >> b
a >>> b
a instanceof b
a++
a--
a+ b
a +b
a + b
a?
a = b
a += b
a -= b
a *= b
a /= b
a %= b
a **= b
a //= b
a %%= b
a <<= b
a >>= b
a >>>= b
a and= b
a or= b
a xor= b
a ?= b
a[b]
a.b
a.0
a .0
a.rgb
a.0123
a .0123
1
1.1
1.
1e1
1e+1
1e-1
-1e-1
a()
a(b)
a(b,c)
a(b,c=d)
# a
@
@a
@.a
a:b
a:b,c:d
(a):b
a ? b : c
#comment
a#comment
"abcd"
'abcd'
"a#{b+c}d"
'''.split /\n/g
# NOTE a +b is NOT bin_op. It's function call
for sample in sample_list
do (sample)->
it sample, ()->
full sample
# BUG in gram2
# sample_list = """
# a +
# b
# """.split /\n?---\n?/g
# for sample in sample_list
# continue if !sample
# do (sample)->
# it JSON.stringify(sample), ()->
# full sample
sample_list = """
a ?
a++++
a++++ # a
a++ ++
a++ ++ # a
a ++
a ++ # a
a+
a+ # a
кирилица
a === b
a === b # a
a !== b
a !== b # a
++a
++a # a
--a
--a # a
+ a
+ a # a
a ? b:c : d
@=1
""".split /\n/g
# KNOWN fuckup a ? b:c : d # comment
# b:c can be bracketless hash and c:d can be bracketless hash
for sample in sample_list
do (sample)->
it "#{sample} should not parse", ()->
util.throws ()->
full sample
it 'a+a*a priority', ()->
ret = full 'a+a*a'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[1].value_view, "+"
it 'a*a+a priority', ()->
ret = full 'a*a+a'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[1].value_view, "+"
it 'void a+a priority', ()->
ret = full 'void a+a'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[0].value_view, "void"
it '-a+b priority', ()->
ret = full '-a+b'
rvalue = ret[0].value_array[0]
assert.equal rvalue.value_array[0].value_array[1].value_view, "+"
describe 'macro-block section', ()->
describe 'array section', ()->
sample_list = """
loop
a
---
if a
b
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
it '1a1 throw', ()->
util.throws ()->
full '1a1'
describe 'array section', ()->
sample_list = """
[]
---
[ ]
---
[a]
---
[a,b]
---
[a,b,c]
---
[
]
---
[
]
---
[
]
---
[
a
]
---
[
a,b
]
---
[
a
b
]
---
[
a,
b
]
---
[
a
,b
]
---
[
a
]
---
[
a,b
]
---
[
a
b
]
---
[
a,
b
]
---
[
a
,b
]
---
[0 .. 2]
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
# sample_list = """
# [a
# ]
# ---
# [
# a]
# """.split /\n?---\n?/g
# for sample in sample_list
# continue if !sample
# do (sample)->
# it "#{JSON.stringify(sample)} bad codestyle not parsed", ()-> # или говнокодеры должны страдать
# util.throws ()->
# full sample
###
string not defined yet
---
{\"a\":b}
---
{'a':b}
###
describe 'hash section', ()->
sample_list = """
{}
---
{ }
---
{a}
---
{a:b}
---
{1:b}
---
{a,b}
---
{a:1,b:2}
---
{a:1,b}
---
{a,b,c}
---
{
}
---
{
}
---
{
}
---
{
a
}
---
{
a
b
}
---
{
a,
b
}
---
{
a
,b
}
---
{
a
}
---
{
a
b
}
---
{
a : b
}
---
{
(a) : b
}
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
# sample_list = """
# [a
# ]
# ---
# [
# a]
# """.split /\n?---\n?/g
# for sample in sample_list
# continue if !sample
# do (sample)->
# it "#{JSON.stringify(sample)} bad codestyle not parsed", ()-> # или говнокодеры должны страдать
# util.throws ()->
# full sample
describe 'pipe section', ()->
sample_list = """
a|b
---
a | | b
---
a | b | c
---
a |
| b
---
a |
| b | c
---
a |
| b
| c
---
a |
| b
| c | d
---
a |
| b | c
| d | e
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
describe 'function decl section', ()->
sample_list = """
->
---
=>
---
()->
---
()->a
---
(a)->a
---
(a,b)->a
---
(a,b=c)->a
---
(a:int)->a
---
(a:int):int->a
---
(a:int):int=>a
---
()->
a
---
()->
a
b
""".split /\n?---\n?/g
for sample in sample_list
continue if !sample
do (sample)->
it JSON.stringify(sample), ()->
full sample
describe "Gram TODO: all exapmles from coffeescript documentation (oneliners only) should be tokenizable and parsable", ()->
# check only if it doesn't throw
describe "Overview", ()->
sample_list = """
number = 42
opposite = true
number = -42 if opposite
square = (x) -> x * x
list = [1, 2, 3, 4, 5]
race = (winner, runners...) -> print winner, runners
alert "I knew it!" if elvis?
cubes = (math.cube num for num in list)
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Functions", ()->
sample_list = """
square = (x) -> x * x
cube = (x) -> square(x) * x
fill = (container, liquid = "coffee") -> "Filling the \#{container} with \#{liquid}..."
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Objects and Arrays", ()->
sample_list = """
song = ["do", "re", "mi", "fa", "so"]
singers = {JPI:NAME:<NAME>END_PI: "Rock", Elvis: "Roll"}
$('.account').attr class: 'active'
log object.class
turtle = {name, mask, weapon}
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "If, Else, Unless, and Conditional Assignment", ()->
sample_list = """
mood = greatlyImproved if singing
date = if friday then sue else jill
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Splats…", ()->
sample_list = """
awardMedals contenders...
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Loops and Comprehensions", ()->
sample_list = """
eat food for food in ['toast', 'cheese', 'wine']
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
shortNames = (name for name in list when name.length < 5)
countdown = (num for num in [10..1])
evens = (x for x in [0..10] by 2)
browser.closeCurrentTab() for [0...count]
yearsOld = max: 10, ida: 9, tim: 11
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Array Slicing and Splicing with Ranges", ()->
sample_list = """
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
start = numbers[0..2]
middle = numbers[3...-2]
end = numbers[-2..]
copy = numbers[..]
numbers[3..6] = [-3, -4, -5, -6]
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Everything is an Expression (at least, as much as possible)", ()->
sample_list = """
eldest = if 24 > 21 then "Liz" else "Ike"
six = (one = 1) + (two = 2) + (three = 3)
globals = (name for name of window)[0...10]
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Operators and Aliases", ()->
sample_list = """
-7 % 5 == -2 # The remainder of 7 / 5
-7 %% 5 == 3 # n %% 5 is always between 0 and 4
tabs.selectTabAtIndex((tabs.currentIndex - count) %% tabs.length)
launch() if ignition is on
volume = 10 if band isnt SpinalTap
letTheWildRumpusBegin() unless answer is no
if car.speed < limit then accelerate()
winner = yes if pick in [47, 92, 13]
print inspect "My name is \#{@name}"
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "The Existential Operator", ()->
sample_list = """
solipsism = true if mind? and not world?
speed = 0
speed ?= 15
footprints = yeti ? "bear"
zip = lottery.drawWinner?().address?.zipcode
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Classes, Inheritance, and Super", ()->
sample_list = """
sam = new Snake "PI:NAME:<NAME>END_PI"
tom = new Horse "PI:NAME:<NAME>END_PI"
sam.move()
tom.move()
String::dasherize = -> this.replace /_/g, "-"
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Destructuring Assignment", ()->
sample_list = """
[theBait, theSwitch] = [theSwitch, theBait]
weatherReport = (location) -> [location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
{sculptor} = futurists
{poet: {name, address: [street, city]}} = futurists
[open, contents..., close] = tag.split("")
[first, ..., last] = text.split " "
{@name, @age, @height = 'average'} = options
tim = new Person name: 'PI:NAME:<NAME>END_PI', age: 4
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
# describe "Bound Functions, Generator Functions", ()->
describe "Embedded JavaScript", ()->
sample_list = """
hi = `function() {return [document.title, "Hello JavaScript"].join(": ");}`
markdown = `function () {return \\`In Markdown, write code like \\\\\\`this\\\\\\`\\`;}`
```function time() {return `The time is ${new Date().toLocaleTimeString()}`;}```
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
# describe "Switch/When/Else", ()->
# describe "Try/Catch/Finally", ()->
describe "Chained Comparisons", ()->
sample_list = """
healthy = 200 > cholesterol > 60
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "String Interpolation, Block Strings, and Block Comments", ()->
sample_list = """
quote = "A picture is a fact. -- \#{ author }"
sentence = "\#{ 22 / 7 } is a decent approximation of π"
""".split /\n/ #"
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Tagged Template Literals", ()->
sample_list = """
upperCaseExpr = (textParts, expressions...) -> textParts.reduce (text, textPart, i) -> text + expressions[i - 1].toUpperCase() + textPart
greet = (name, adjective) -> upperCaseExpr\"""Hi \#{name}. You look \#{adjective}!\"""
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
# describe "Block Regular Expressions", ()->
describe "Modules", ()->
sample_list = """
import 'local-file.coffee'
import 'coffee-script'
import _ from 'underscore'
import * as underscore from 'underscore'
import { now } from 'underscore'
import { now as currentTimestamp } from 'underscore'
import { first, last } from 'underscore'
import utilityBelt, { each } from 'underscore'
export default Math
export square = (x) -> x * x
export { sqrt }
export { sqrt as squareRoot }
export { Mathematics as default, sqrt as squareRoot }
export * from 'underscore'
export { max, min } from 'underscore'
""".split /\n/
for sample in sample_list
do (sample)->
it sample
# it sample, ()->
# full sample
describe "Gram TODO: fuckups", ()->
it "a/2+b/7" # Parsing error. No proper combination found
it "{1}" # Parsing error. No proper combination found
|
[
{
"context": " cacheParams = {\n key: \"#{api.fullname}-champions-#{region}-#{options.locale}-#{options.version}-\" +\n ",
"end": 1759,
"score": 0.9699857234954834,
"start": 1737,
"tag": "KEY",
"value": "champions-#{region}-#{"
},
{
"context": "api.fullname}-champions-#{region}-#{options.locale}-#{options.version}-\" +\n \"#{if options",
"end": 1777,
"score": 0.9711272716522217,
"start": 1775,
"tag": "KEY",
"value": "#{"
},
{
"context": "ions-#{region}-#{options.locale}-#{options.version}-\" +\n \"#{if options.dataById then 't",
"end": 1792,
"score": 0.9854126572608948,
"start": 1792,
"tag": "KEY",
"value": ""
},
{
"context": " cacheParams = {\n key: \"#{api.fullname}-champions-#{region}-#{options.locale}-#{options.ve",
"end": 5124,
"score": 0.8294845223426819,
"start": 5124,
"tag": "KEY",
"value": ""
},
{
"context": "Params = {\n key: \"#{api.fullname}-champions-#{region}-#{options.locale}-#{options.version}-\" +\n ",
"end": 5138,
"score": 0.6611222624778748,
"start": 5131,
"tag": "KEY",
"value": "ions-#{"
},
{
"context": " key: \"#{api.fullname}-champions-#{region}-#{options.locale}-#{options.version}-\" +\n ",
"end": 5144,
"score": 0.6708790063858032,
"start": 5144,
"tag": "KEY",
"value": ""
},
{
"context": " cacheParams = {\n key: \"#{api.fullname}-versions-#{region}\"\n api, region, objectType: 'ver",
"end": 6148,
"score": 0.8063446283340454,
"start": 6137,
"tag": "KEY",
"value": "versions-#{"
}
] | src/api/lolStaticData.coffee | jwalton/lol-js | 30 | ld = require 'lodash'
pb = require 'promise-breaker'
api = exports.api = {
fullname: "lol-static-data-v1.2",
name: "lol-static-data",
version: "v1.2"
}
makeUrl = (region) -> "https://global.api.pvp.net/api/lol/static-data/#{region}/v1.2"
exports.methods = {
# Retrieve a list of champions
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `options.locale` - Locale code for returned data (e.g., en_US, es_ES). If not specified,
# the default locale for the region is used.
# * `options.version` - Data dragon version for returned data. If not specified, the latest
# version for the region is used. List of valid versions can be obtained from
# `getVersions()`.
# * `options.dataById` - If true, the results will be indexed by ID instead of by key.
# * `options.champData` - Array of tags to return additional data. Only type, version, data,
# id, key, name, and title are returned by default if this parameter isn't specified. To
# return all additional data, use the tag 'all'. Valid values are: 'all', 'allytips',
# 'altimages', 'blurb', 'enemytips', 'image', 'info', 'lore', 'partype', 'passive',
# 'recommended', 'skins', 'spells', 'stats', 'tags'.
#
getChampions: pb.break (region, options={}) ->
options = ld.defaults {}, options, {
dataById: false
}
requestParams = {
caller: "getChampions",
region: region,
url: "#{makeUrl region, api}/champion",
queryParams: ld.pick options, ['locale', 'version', 'dataById', 'champData']
rateLimit: false
}
cacheParams = {
key: "#{api.fullname}-champions-#{region}-#{options.locale}-#{options.version}-" +
"#{if options.dataById then 't' else 'f'}-#{(options.champData ? []).join ','}"
api, region, objectType: 'champions', params: requestParams.queryParams
}
@_riotRequestWithCache requestParams, cacheParams, {}
# Retrieve a champion using its ID.
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `id` - the ID of the champion to retrieve.
# * `options` are the same as for `getChampions()`, except that `dataById` cannot be specified.
#
getChampionById: pb.break (region, id, options={}) ->
options = ld.extend {}, options, {dataById: true}
@getChampions(region, options)
.then (champions) -> champions.data[id]
# Retrieve a champion using its key.
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `id` - the ID of the champion to retrieve.
# * `options` are the same as for `getChampions()`, except that `dataById` cannot be specified.
#
getChampionByKey: pb.break (region, key, options={}) ->
options = ld.extend {}, options, {dataById: false}
@getChampions(region, options)
.then (champions) -> champions.data[key]
getChampionByName: pb.break (region, name, options={}) ->
options = ld.extend {}, options, {dataById: false}
@getChampions(region, options)
.then (champions) ->
# First try the name as a key, because this is the fastest way to do this.
answer = champions.data[name]
# If this doesn't work, try searching for a champion with the same name, ignoring
# punctuation and case.
if !answer?
championsByName = ld.indexBy champions.data, (c) ->
c.name.toLowerCase().replace(/\W/g, '')
answer = championsByName[name.toLowerCase().replace(/\W/g, '')]
return answer
# Retrieve a list of items.
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `options.locale` - Locale code for returned data (e.g., en_US, es_ES). If not specified,
# the default locale for the region is used.
# * `options.version` - Data dragon version for returned data. If not specified, the latest
# version for the region is used. List of valid versions can be obtained from
# `getVersions()`.
# * `options.tags` - Tags to return additional data. Only type, version, basic, data, id, name,
# plaintext, group, and description are returned by default if this parameter isn't
# specified. To return all additional data, use the tag 'all'. Valid options are:
# all, colloq, consumeOnFull, consumed, depth, from, gold, groups, hideFromAll, image,
# inStore, into, maps, requiredChampion, sanitizedDescription, specialRecipe, stacks, stats,
# tags, tree
#
getItems: pb.break (region, options={}) ->
options = ld.defaults {}, options, {
dataById: false
}
requestParams = {
caller: "getItems",
region: region,
url: "#{makeUrl region, api}/item",
queryParams: ld.pick options, ['locale', 'version', 'tags']
rateLimit: false
}
cacheParams = {
key: "#{api.fullname}-champions-#{region}-#{options.locale}-#{options.version}-" +
options.tags.join(",")
api, region, objectType: 'items', params: requestParams.queryParams
}
@_riotRequestWithCache requestParams, cacheParams, {}
# Retrieve an item using its ID.
#
# Parameters:
# * `id` - the ID of the item to retrieve.
# * `options` are the same as for `getItems()`.
#
getItemById: pb.break (region, id, options={}) ->
@getItems(region, options)
.then (objects) ->
return objects.data[id]
# TODO: Lots more things to implement here.
# Retrieve a list of versions.
#
# Parameters:
# * `region` - Region from which to retrieve data.
getVersions: pb.break (region) ->
requestParams = {
caller: "getVersions",
region: region,
url: "#{makeUrl region, api}/versions",
rateLimit: false
}
cacheParams = {
key: "#{api.fullname}-versions-#{region}"
api, region, objectType: 'versions', params: {}
}
@_riotRequestWithCache requestParams, cacheParams, {}
# Converts a team name ("red" or "blue") to a team ID (100, 200).
# Note this returns the actual value, and not a promise.
teamNameToId: (teamName) ->
if teamName.toLowerCase() is "blue" then 100 else 200
}
| 65976 | ld = require 'lodash'
pb = require 'promise-breaker'
api = exports.api = {
fullname: "lol-static-data-v1.2",
name: "lol-static-data",
version: "v1.2"
}
makeUrl = (region) -> "https://global.api.pvp.net/api/lol/static-data/#{region}/v1.2"
exports.methods = {
# Retrieve a list of champions
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `options.locale` - Locale code for returned data (e.g., en_US, es_ES). If not specified,
# the default locale for the region is used.
# * `options.version` - Data dragon version for returned data. If not specified, the latest
# version for the region is used. List of valid versions can be obtained from
# `getVersions()`.
# * `options.dataById` - If true, the results will be indexed by ID instead of by key.
# * `options.champData` - Array of tags to return additional data. Only type, version, data,
# id, key, name, and title are returned by default if this parameter isn't specified. To
# return all additional data, use the tag 'all'. Valid values are: 'all', 'allytips',
# 'altimages', 'blurb', 'enemytips', 'image', 'info', 'lore', 'partype', 'passive',
# 'recommended', 'skins', 'spells', 'stats', 'tags'.
#
getChampions: pb.break (region, options={}) ->
options = ld.defaults {}, options, {
dataById: false
}
requestParams = {
caller: "getChampions",
region: region,
url: "#{makeUrl region, api}/champion",
queryParams: ld.pick options, ['locale', 'version', 'dataById', 'champData']
rateLimit: false
}
cacheParams = {
key: "#{api.fullname}-<KEY>options.locale}-<KEY>options.version<KEY>}-" +
"#{if options.dataById then 't' else 'f'}-#{(options.champData ? []).join ','}"
api, region, objectType: 'champions', params: requestParams.queryParams
}
@_riotRequestWithCache requestParams, cacheParams, {}
# Retrieve a champion using its ID.
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `id` - the ID of the champion to retrieve.
# * `options` are the same as for `getChampions()`, except that `dataById` cannot be specified.
#
getChampionById: pb.break (region, id, options={}) ->
options = ld.extend {}, options, {dataById: true}
@getChampions(region, options)
.then (champions) -> champions.data[id]
# Retrieve a champion using its key.
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `id` - the ID of the champion to retrieve.
# * `options` are the same as for `getChampions()`, except that `dataById` cannot be specified.
#
getChampionByKey: pb.break (region, key, options={}) ->
options = ld.extend {}, options, {dataById: false}
@getChampions(region, options)
.then (champions) -> champions.data[key]
getChampionByName: pb.break (region, name, options={}) ->
options = ld.extend {}, options, {dataById: false}
@getChampions(region, options)
.then (champions) ->
# First try the name as a key, because this is the fastest way to do this.
answer = champions.data[name]
# If this doesn't work, try searching for a champion with the same name, ignoring
# punctuation and case.
if !answer?
championsByName = ld.indexBy champions.data, (c) ->
c.name.toLowerCase().replace(/\W/g, '')
answer = championsByName[name.toLowerCase().replace(/\W/g, '')]
return answer
# Retrieve a list of items.
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `options.locale` - Locale code for returned data (e.g., en_US, es_ES). If not specified,
# the default locale for the region is used.
# * `options.version` - Data dragon version for returned data. If not specified, the latest
# version for the region is used. List of valid versions can be obtained from
# `getVersions()`.
# * `options.tags` - Tags to return additional data. Only type, version, basic, data, id, name,
# plaintext, group, and description are returned by default if this parameter isn't
# specified. To return all additional data, use the tag 'all'. Valid options are:
# all, colloq, consumeOnFull, consumed, depth, from, gold, groups, hideFromAll, image,
# inStore, into, maps, requiredChampion, sanitizedDescription, specialRecipe, stacks, stats,
# tags, tree
#
getItems: pb.break (region, options={}) ->
options = ld.defaults {}, options, {
dataById: false
}
requestParams = {
caller: "getItems",
region: region,
url: "#{makeUrl region, api}/item",
queryParams: ld.pick options, ['locale', 'version', 'tags']
rateLimit: false
}
cacheParams = {
key: "#{api.fullname<KEY>}-champ<KEY>region<KEY>}-#{options.locale}-#{options.version}-" +
options.tags.join(",")
api, region, objectType: 'items', params: requestParams.queryParams
}
@_riotRequestWithCache requestParams, cacheParams, {}
# Retrieve an item using its ID.
#
# Parameters:
# * `id` - the ID of the item to retrieve.
# * `options` are the same as for `getItems()`.
#
getItemById: pb.break (region, id, options={}) ->
@getItems(region, options)
.then (objects) ->
return objects.data[id]
# TODO: Lots more things to implement here.
# Retrieve a list of versions.
#
# Parameters:
# * `region` - Region from which to retrieve data.
getVersions: pb.break (region) ->
requestParams = {
caller: "getVersions",
region: region,
url: "#{makeUrl region, api}/versions",
rateLimit: false
}
cacheParams = {
key: "#{api.fullname}-<KEY>region}"
api, region, objectType: 'versions', params: {}
}
@_riotRequestWithCache requestParams, cacheParams, {}
# Converts a team name ("red" or "blue") to a team ID (100, 200).
# Note this returns the actual value, and not a promise.
teamNameToId: (teamName) ->
if teamName.toLowerCase() is "blue" then 100 else 200
}
| true | ld = require 'lodash'
pb = require 'promise-breaker'
api = exports.api = {
fullname: "lol-static-data-v1.2",
name: "lol-static-data",
version: "v1.2"
}
makeUrl = (region) -> "https://global.api.pvp.net/api/lol/static-data/#{region}/v1.2"
exports.methods = {
# Retrieve a list of champions
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `options.locale` - Locale code for returned data (e.g., en_US, es_ES). If not specified,
# the default locale for the region is used.
# * `options.version` - Data dragon version for returned data. If not specified, the latest
# version for the region is used. List of valid versions can be obtained from
# `getVersions()`.
# * `options.dataById` - If true, the results will be indexed by ID instead of by key.
# * `options.champData` - Array of tags to return additional data. Only type, version, data,
# id, key, name, and title are returned by default if this parameter isn't specified. To
# return all additional data, use the tag 'all'. Valid values are: 'all', 'allytips',
# 'altimages', 'blurb', 'enemytips', 'image', 'info', 'lore', 'partype', 'passive',
# 'recommended', 'skins', 'spells', 'stats', 'tags'.
#
getChampions: pb.break (region, options={}) ->
options = ld.defaults {}, options, {
dataById: false
}
requestParams = {
caller: "getChampions",
region: region,
url: "#{makeUrl region, api}/champion",
queryParams: ld.pick options, ['locale', 'version', 'dataById', 'champData']
rateLimit: false
}
cacheParams = {
key: "#{api.fullname}-PI:KEY:<KEY>END_PIoptions.locale}-PI:KEY:<KEY>END_PIoptions.versionPI:KEY:<KEY>END_PI}-" +
"#{if options.dataById then 't' else 'f'}-#{(options.champData ? []).join ','}"
api, region, objectType: 'champions', params: requestParams.queryParams
}
@_riotRequestWithCache requestParams, cacheParams, {}
# Retrieve a champion using its ID.
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `id` - the ID of the champion to retrieve.
# * `options` are the same as for `getChampions()`, except that `dataById` cannot be specified.
#
getChampionById: pb.break (region, id, options={}) ->
options = ld.extend {}, options, {dataById: true}
@getChampions(region, options)
.then (champions) -> champions.data[id]
# Retrieve a champion using its key.
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `id` - the ID of the champion to retrieve.
# * `options` are the same as for `getChampions()`, except that `dataById` cannot be specified.
#
getChampionByKey: pb.break (region, key, options={}) ->
options = ld.extend {}, options, {dataById: false}
@getChampions(region, options)
.then (champions) -> champions.data[key]
getChampionByName: pb.break (region, name, options={}) ->
options = ld.extend {}, options, {dataById: false}
@getChampions(region, options)
.then (champions) ->
# First try the name as a key, because this is the fastest way to do this.
answer = champions.data[name]
# If this doesn't work, try searching for a champion with the same name, ignoring
# punctuation and case.
if !answer?
championsByName = ld.indexBy champions.data, (c) ->
c.name.toLowerCase().replace(/\W/g, '')
answer = championsByName[name.toLowerCase().replace(/\W/g, '')]
return answer
# Retrieve a list of items.
#
# Parameters:
# * `region` - Region from which to retrieve data.
# * `options.locale` - Locale code for returned data (e.g., en_US, es_ES). If not specified,
# the default locale for the region is used.
# * `options.version` - Data dragon version for returned data. If not specified, the latest
# version for the region is used. List of valid versions can be obtained from
# `getVersions()`.
# * `options.tags` - Tags to return additional data. Only type, version, basic, data, id, name,
# plaintext, group, and description are returned by default if this parameter isn't
# specified. To return all additional data, use the tag 'all'. Valid options are:
# all, colloq, consumeOnFull, consumed, depth, from, gold, groups, hideFromAll, image,
# inStore, into, maps, requiredChampion, sanitizedDescription, specialRecipe, stacks, stats,
# tags, tree
#
getItems: pb.break (region, options={}) ->
options = ld.defaults {}, options, {
dataById: false
}
requestParams = {
caller: "getItems",
region: region,
url: "#{makeUrl region, api}/item",
queryParams: ld.pick options, ['locale', 'version', 'tags']
rateLimit: false
}
cacheParams = {
key: "#{api.fullnamePI:KEY:<KEY>END_PI}-champPI:KEY:<KEY>END_PIregionPI:KEY:<KEY>END_PI}-#{options.locale}-#{options.version}-" +
options.tags.join(",")
api, region, objectType: 'items', params: requestParams.queryParams
}
@_riotRequestWithCache requestParams, cacheParams, {}
# Retrieve an item using its ID.
#
# Parameters:
# * `id` - the ID of the item to retrieve.
# * `options` are the same as for `getItems()`.
#
getItemById: pb.break (region, id, options={}) ->
@getItems(region, options)
.then (objects) ->
return objects.data[id]
# TODO: Lots more things to implement here.
# Retrieve a list of versions.
#
# Parameters:
# * `region` - Region from which to retrieve data.
getVersions: pb.break (region) ->
requestParams = {
caller: "getVersions",
region: region,
url: "#{makeUrl region, api}/versions",
rateLimit: false
}
cacheParams = {
key: "#{api.fullname}-PI:KEY:<KEY>END_PIregion}"
api, region, objectType: 'versions', params: {}
}
@_riotRequestWithCache requestParams, cacheParams, {}
# Converts a team name ("red" or "blue") to a team ID (100, 200).
# Note this returns the actual value, and not a promise.
teamNameToId: (teamName) ->
if teamName.toLowerCase() is "blue" then 100 else 200
}
|
[
{
"context": " 0.6 }\n ]\n\nclient = new Myna.Client\n apiKey: \"092c90f6-a8f2-11e2-a2b9-7c6d628b25f7\"\n apiRoot: testApiRoot\n settings: \"myna.web.au",
"end": 407,
"score": 0.9997016191482544,
"start": 371,
"tag": "KEY",
"value": "092c90f6-a8f2-11e2-a2b9-7c6d628b25f7"
}
] | src/test/reward-spec.coffee | plyfe/myna-js | 2 | expt = new Myna.Experiment
uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c"
id: "id"
settings: "myna.web.sticky": true
variants: [
{ id: "a", settings: { buttons: "red" }, weight: 0.2 }
{ id: "b", settings: { buttons: "green" }, weight: 0.4 }
{ id: "c", settings: { buttons: "blue" }, weight: 0.6 }
]
client = new Myna.Client
apiKey: "092c90f6-a8f2-11e2-a2b9-7c6d628b25f7"
apiRoot: testApiRoot
settings: "myna.web.autoSync": false
experiments: [ expt ]
recorder = new Myna.Recorder client
recorder.listenTo(expt)
for sticky in [false, true]
initialized = (fn) ->
return ->
expt.callbacks = {}
expt.settings.set("myna.web.sticky", sticky)
expt.unstick()
recorder.clearQueuedEvents()
fn()
@removeAllSpies()
describe "Myna.Experiment.reward (#{(if sticky then 'sticky' else 'non-sticky')})", ->
it "should reward the last suggestion", initialized ->
withSuggestion expt, (variant) ->
withReward expt, 0.8, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ],
[ "reward", variant.id, 0.8 ]
]
it "should clear the last suggestion", initialized ->
withSuggestion expt, (variant) ->
withReward expt, 0.8, ->
expect(expt.loadLastView()).toEqual(null)
it "should #{if sticky then 'save' else 'NOT save'} the sticky reward", initialized ->
withSuggestion expt, (variant) ->
withReward expt, 0.8, ->
if sticky
expect(expt.loadStickyReward()).toBe(variant)
else
expect(expt.loadStickyReward()).toBe(null)
it "should queue a reward event for upload", initialized ->
withSuggestion expt, (variant) ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ]
]
withReward expt, 0.8, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ],
[ "reward", variant.id, 0.8 ]
]
it "should guard against duplicate rewards", initialized ->
finished = false
withSuggestion expt, (variant) ->
expect(variant).toBeInstanceOf(Myna.Variant)
withReward expt, 0.8, ->
withReward expt, 0.6, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ],
[ "reward", variant.id, 0.8 ]
]
finished = true
waitsFor -> finished
runs -> expect(finished).toEqual(true)
it "should #{if sticky then 'NOT' else ''} enqueue events for successive suggest/reward cycles", initialized ->
finished = false
withSuggestion expt, (v1) ->
expect(v1).toBeInstanceOf(Myna.Variant)
withReward expt, 0.8, ->
withSuggestion expt, (v2) ->
withReward expt, 0.6, ->
if sticky
expect(v1.id).toEqual(v2.id)
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", v1.id, null ],
[ "reward", v1.id, 0.8 ]
]
else
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", v1.id, null ],
[ "reward", v1.id, 0.8 ]
[ "view", v2.id, null ],
[ "reward", v2.id, 0.6 ]
]
finished = true
waitsFor -> finished
runs -> expect(finished).toEqual(true)
it "should be reset by unstick, saving new events on future calls to reward", initialized ->
withSuggestion expt, (v1) ->
withReward expt, 0.8, ->
expt.unstick()
withSuggestion expt, (v2) ->
withReward expt, 0.6, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", v1.id, null ],
[ "reward", v1.id, 0.8 ]
[ "view", v2.id, null ],
[ "reward", v2.id, 0.6 ]
]
| 127103 | expt = new Myna.Experiment
uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c"
id: "id"
settings: "myna.web.sticky": true
variants: [
{ id: "a", settings: { buttons: "red" }, weight: 0.2 }
{ id: "b", settings: { buttons: "green" }, weight: 0.4 }
{ id: "c", settings: { buttons: "blue" }, weight: 0.6 }
]
client = new Myna.Client
apiKey: "<KEY>"
apiRoot: testApiRoot
settings: "myna.web.autoSync": false
experiments: [ expt ]
recorder = new Myna.Recorder client
recorder.listenTo(expt)
for sticky in [false, true]
initialized = (fn) ->
return ->
expt.callbacks = {}
expt.settings.set("myna.web.sticky", sticky)
expt.unstick()
recorder.clearQueuedEvents()
fn()
@removeAllSpies()
describe "Myna.Experiment.reward (#{(if sticky then 'sticky' else 'non-sticky')})", ->
it "should reward the last suggestion", initialized ->
withSuggestion expt, (variant) ->
withReward expt, 0.8, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ],
[ "reward", variant.id, 0.8 ]
]
it "should clear the last suggestion", initialized ->
withSuggestion expt, (variant) ->
withReward expt, 0.8, ->
expect(expt.loadLastView()).toEqual(null)
it "should #{if sticky then 'save' else 'NOT save'} the sticky reward", initialized ->
withSuggestion expt, (variant) ->
withReward expt, 0.8, ->
if sticky
expect(expt.loadStickyReward()).toBe(variant)
else
expect(expt.loadStickyReward()).toBe(null)
it "should queue a reward event for upload", initialized ->
withSuggestion expt, (variant) ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ]
]
withReward expt, 0.8, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ],
[ "reward", variant.id, 0.8 ]
]
it "should guard against duplicate rewards", initialized ->
finished = false
withSuggestion expt, (variant) ->
expect(variant).toBeInstanceOf(Myna.Variant)
withReward expt, 0.8, ->
withReward expt, 0.6, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ],
[ "reward", variant.id, 0.8 ]
]
finished = true
waitsFor -> finished
runs -> expect(finished).toEqual(true)
it "should #{if sticky then 'NOT' else ''} enqueue events for successive suggest/reward cycles", initialized ->
finished = false
withSuggestion expt, (v1) ->
expect(v1).toBeInstanceOf(Myna.Variant)
withReward expt, 0.8, ->
withSuggestion expt, (v2) ->
withReward expt, 0.6, ->
if sticky
expect(v1.id).toEqual(v2.id)
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", v1.id, null ],
[ "reward", v1.id, 0.8 ]
]
else
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", v1.id, null ],
[ "reward", v1.id, 0.8 ]
[ "view", v2.id, null ],
[ "reward", v2.id, 0.6 ]
]
finished = true
waitsFor -> finished
runs -> expect(finished).toEqual(true)
it "should be reset by unstick, saving new events on future calls to reward", initialized ->
withSuggestion expt, (v1) ->
withReward expt, 0.8, ->
expt.unstick()
withSuggestion expt, (v2) ->
withReward expt, 0.6, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", v1.id, null ],
[ "reward", v1.id, 0.8 ]
[ "view", v2.id, null ],
[ "reward", v2.id, 0.6 ]
]
| true | expt = new Myna.Experiment
uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c"
id: "id"
settings: "myna.web.sticky": true
variants: [
{ id: "a", settings: { buttons: "red" }, weight: 0.2 }
{ id: "b", settings: { buttons: "green" }, weight: 0.4 }
{ id: "c", settings: { buttons: "blue" }, weight: 0.6 }
]
client = new Myna.Client
apiKey: "PI:KEY:<KEY>END_PI"
apiRoot: testApiRoot
settings: "myna.web.autoSync": false
experiments: [ expt ]
recorder = new Myna.Recorder client
recorder.listenTo(expt)
for sticky in [false, true]
initialized = (fn) ->
return ->
expt.callbacks = {}
expt.settings.set("myna.web.sticky", sticky)
expt.unstick()
recorder.clearQueuedEvents()
fn()
@removeAllSpies()
describe "Myna.Experiment.reward (#{(if sticky then 'sticky' else 'non-sticky')})", ->
it "should reward the last suggestion", initialized ->
withSuggestion expt, (variant) ->
withReward expt, 0.8, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ],
[ "reward", variant.id, 0.8 ]
]
it "should clear the last suggestion", initialized ->
withSuggestion expt, (variant) ->
withReward expt, 0.8, ->
expect(expt.loadLastView()).toEqual(null)
it "should #{if sticky then 'save' else 'NOT save'} the sticky reward", initialized ->
withSuggestion expt, (variant) ->
withReward expt, 0.8, ->
if sticky
expect(expt.loadStickyReward()).toBe(variant)
else
expect(expt.loadStickyReward()).toBe(null)
it "should queue a reward event for upload", initialized ->
withSuggestion expt, (variant) ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ]
]
withReward expt, 0.8, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ],
[ "reward", variant.id, 0.8 ]
]
it "should guard against duplicate rewards", initialized ->
finished = false
withSuggestion expt, (variant) ->
expect(variant).toBeInstanceOf(Myna.Variant)
withReward expt, 0.8, ->
withReward expt, 0.6, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", variant.id, null ],
[ "reward", variant.id, 0.8 ]
]
finished = true
waitsFor -> finished
runs -> expect(finished).toEqual(true)
it "should #{if sticky then 'NOT' else ''} enqueue events for successive suggest/reward cycles", initialized ->
finished = false
withSuggestion expt, (v1) ->
expect(v1).toBeInstanceOf(Myna.Variant)
withReward expt, 0.8, ->
withSuggestion expt, (v2) ->
withReward expt, 0.6, ->
if sticky
expect(v1.id).toEqual(v2.id)
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", v1.id, null ],
[ "reward", v1.id, 0.8 ]
]
else
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", v1.id, null ],
[ "reward", v1.id, 0.8 ]
[ "view", v2.id, null ],
[ "reward", v2.id, 0.6 ]
]
finished = true
waitsFor -> finished
runs -> expect(finished).toEqual(true)
it "should be reset by unstick, saving new events on future calls to reward", initialized ->
withSuggestion expt, (v1) ->
withReward expt, 0.8, ->
expt.unstick()
withSuggestion expt, (v2) ->
withReward expt, 0.6, ->
expect(eventSummaries(recorder.queuedEvents())).toEqual [
[ "view", v1.id, null ],
[ "reward", v1.id, 0.8 ]
[ "view", v2.id, null ],
[ "reward", v2.id, 0.6 ]
]
|
[
{
"context": "\n COUNTRIES = {}\n\n users = []\n names = ['Abbot', 'Brandt', 'Compton', 'Dykes', 'Ernst', 'Fultz',",
"end": 1526,
"score": 0.9998258948326111,
"start": 1521,
"tag": "NAME",
"value": "Abbot"
},
{
"context": "TRIES = {}\n\n users = []\n names = ['Abbot', 'Brandt', 'Compton', 'Dykes', 'Ernst', 'Fultz', 'Gutierre",
"end": 1536,
"score": 0.9997879266738892,
"start": 1530,
"tag": "NAME",
"value": "Brandt"
},
{
"context": "\n\n users = []\n names = ['Abbot', 'Brandt', 'Compton', 'Dykes', 'Ernst', 'Fultz', 'Gutierrez', 'Yamamo",
"end": 1547,
"score": 0.999779462814331,
"start": 1540,
"tag": "NAME",
"value": "Compton"
},
{
"context": " = []\n names = ['Abbot', 'Brandt', 'Compton', 'Dykes', 'Ernst', 'Fultz', 'Gutierrez', 'Yamamoto']\n ",
"end": 1556,
"score": 0.9997876286506653,
"start": 1551,
"tag": "NAME",
"value": "Dykes"
},
{
"context": " names = ['Abbot', 'Brandt', 'Compton', 'Dykes', 'Ernst', 'Fultz', 'Gutierrez', 'Yamamoto']\n firstName",
"end": 1565,
"score": 0.9997934699058533,
"start": 1560,
"tag": "NAME",
"value": "Ernst"
},
{
"context": "['Abbot', 'Brandt', 'Compton', 'Dykes', 'Ernst', 'Fultz', 'Gutierrez', 'Yamamoto']\n firstNames = ['Bri",
"end": 1574,
"score": 0.9997677803039551,
"start": 1569,
"tag": "NAME",
"value": "Fultz"
},
{
"context": " 'Brandt', 'Compton', 'Dykes', 'Ernst', 'Fultz', 'Gutierrez', 'Yamamoto']\n firstNames = ['Brice', 'Felton'",
"end": 1587,
"score": 0.9997745156288147,
"start": 1578,
"tag": "NAME",
"value": "Gutierrez"
},
{
"context": "ompton', 'Dykes', 'Ernst', 'Fultz', 'Gutierrez', 'Yamamoto']\n firstNames = ['Brice', 'Felton', 'Lee', 'Tr",
"end": 1599,
"score": 0.9998020529747009,
"start": 1591,
"tag": "NAME",
"value": "Yamamoto"
},
{
"context": "ltz', 'Gutierrez', 'Yamamoto']\n firstNames = ['Brice', 'Felton', 'Lee', 'Trent', 'Hank', 'Ismael'].con",
"end": 1626,
"score": 0.9997997283935547,
"start": 1621,
"tag": "NAME",
"value": "Brice"
},
{
"context": "tierrez', 'Yamamoto']\n firstNames = ['Brice', 'Felton', 'Lee', 'Trent', 'Hank', 'Ismael'].concat ['Clar",
"end": 1636,
"score": 0.999711811542511,
"start": 1630,
"tag": "NAME",
"value": "Felton"
},
{
"context": "'Yamamoto']\n firstNames = ['Brice', 'Felton', 'Lee', 'Trent', 'Hank', 'Ismael'].concat ['Clara', 'Ky",
"end": 1643,
"score": 0.9996644258499146,
"start": 1640,
"tag": "NAME",
"value": "Lee"
},
{
"context": "to']\n firstNames = ['Brice', 'Felton', 'Lee', 'Trent', 'Hank', 'Ismael'].concat ['Clara', 'Kyoko', 'Pe",
"end": 1652,
"score": 0.9996964931488037,
"start": 1647,
"tag": "NAME",
"value": "Trent"
},
{
"context": "firstNames = ['Brice', 'Felton', 'Lee', 'Trent', 'Hank', 'Ismael'].concat ['Clara', 'Kyoko', 'Pearl', 'S",
"end": 1660,
"score": 0.9996784925460815,
"start": 1656,
"tag": "NAME",
"value": "Hank"
},
{
"context": "es = ['Brice', 'Felton', 'Lee', 'Trent', 'Hank', 'Ismael'].concat ['Clara', 'Kyoko', 'Pearl', 'Sofia', 'Ju",
"end": 1670,
"score": 0.9997539520263672,
"start": 1664,
"tag": "NAME",
"value": "Ismael"
},
{
"context": "lton', 'Lee', 'Trent', 'Hank', 'Ismael'].concat ['Clara', 'Kyoko', 'Pearl', 'Sofia', 'Julie', 'Melba']\n ",
"end": 1687,
"score": 0.999791145324707,
"start": 1682,
"tag": "NAME",
"value": "Clara"
},
{
"context": "ee', 'Trent', 'Hank', 'Ismael'].concat ['Clara', 'Kyoko', 'Pearl', 'Sofia', 'Julie', 'Melba']\n occupat",
"end": 1696,
"score": 0.9997738599777222,
"start": 1691,
"tag": "NAME",
"value": "Kyoko"
},
{
"context": "nt', 'Hank', 'Ismael'].concat ['Clara', 'Kyoko', 'Pearl', 'Sofia', 'Julie', 'Melba']\n occupations = ['",
"end": 1705,
"score": 0.9997355937957764,
"start": 1700,
"tag": "NAME",
"value": "Pearl"
},
{
"context": "k', 'Ismael'].concat ['Clara', 'Kyoko', 'Pearl', 'Sofia', 'Julie', 'Melba']\n occupations = ['Drafter',",
"end": 1714,
"score": 0.9995705485343933,
"start": 1709,
"tag": "NAME",
"value": "Sofia"
},
{
"context": "el'].concat ['Clara', 'Kyoko', 'Pearl', 'Sofia', 'Julie', 'Melba']\n occupations = ['Drafter', 'Housebr",
"end": 1723,
"score": 0.9997196197509766,
"start": 1718,
"tag": "NAME",
"value": "Julie"
},
{
"context": "at ['Clara', 'Kyoko', 'Pearl', 'Sofia', 'Julie', 'Melba']\n occupations = ['Drafter', 'Housebreaker', '",
"end": 1732,
"score": 0.9992406368255615,
"start": 1727,
"tag": "NAME",
"value": "Melba"
},
{
"context": " return\n (res, next)->\n name = 'admin'\n firstName = 'admin'\n pMgr",
"end": 3863,
"score": 0.9927948117256165,
"start": 3858,
"tag": "USERNAME",
"value": "admin"
},
{
"context": " name = 'admin'\n firstName = 'admin'\n pMgr.insertUser {\n na",
"end": 3895,
"score": 0.9260484576225281,
"start": 3890,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "ame: name.toUpperCase()\n firstName: firstName\n email: firstName.toLowerCase() + ",
"end": 4004,
"score": 0.5005090832710266,
"start": 3995,
"tag": "NAME",
"value": "firstName"
},
{
"context": " users.push\n name: name.toUpperCase()\n firstName: ",
"end": 4637,
"score": 0.5372335314750671,
"start": 4633,
"tag": "NAME",
"value": "name"
},
{
"context": "e.toUpperCase()\n firstName: firstName\n email: firstName.toLowerC",
"end": 4696,
"score": 0.7631277441978455,
"start": 4687,
"tag": "NAME",
"value": "firstName"
}
] | test/sqlscripts.coffee | smbape/node-dblayer | 0 | async = require 'async'
_ = require 'lodash'
{squel} = require('../')
module.exports = (config, connectors, done)->
pMgr = globals.pMgr
scripts = []
languages = []
languages.push
data:
code: 'fr-FR'
key: 'FR'
label: 'Français'
translation:
'fr-FR': 'Français'
'en-GB': 'French'
languages.push
data:
code: 'en-GB'
key: 'EN'
label: 'English'
translation:
'fr-FR': 'Anglais'
'en-GB': 'English'
countries = []
countries.push
data:
code: 'ARGENTINA'
translation:
'fr-FR': 'Argentine'
'en-GB': 'Argentina'
countries.push
data:
code: 'CAMEROUN'
translation:
'fr-FR': 'Cameroun'
'en-GB': 'Cameroon'
countries.push
data:
code: 'FRANCE'
translation:
'fr-FR': 'France'
'en-GB': 'France'
countries.push
data:
code: 'UNITED KINGDOM'
translation:
'fr-FR': 'Royaumes Unis'
'en-GB': 'United Kingdom'
data = languages.concat(countries)
properties = data.map (data)-> data.data
translations = data.map (data)-> data.translation
insertPropertiesQuery = pMgr.getInsertQueryString 'Property', properties, {dialect: config.dialect}
PROPERTIES = {}
LANGUAGES = {}
COUNTRIES = {}
users = []
names = ['Abbot', 'Brandt', 'Compton', 'Dykes', 'Ernst', 'Fultz', 'Gutierrez', 'Yamamoto']
firstNames = ['Brice', 'Felton', 'Lee', 'Trent', 'Hank', 'Ismael'].concat ['Clara', 'Kyoko', 'Pearl', 'Sofia', 'Julie', 'Melba']
occupations = ['Drafter', 'Housebreaker', 'Miner', 'Physician']
async.waterfall [
(next)-> connectors.writer.query insertPropertiesQuery, next
(res, next)-> pMgr.listProperty {type: 'json'}, next
(rows, next)->
for row in rows
PROPERTIES[row.code] = pMgr.newProperty row
for language in languages
language.data.property = PROPERTIES[language.data.code]
insertLanguagesQuery = pMgr.getInsertQueryString 'Language', languages.map((data)-> data.data), {dialect: config.dialect}
connectors.writer.query insertLanguagesQuery, next
return
(res, next)->
pMgr.listLanguage {
type: 'json'
fields: ['*', 'property:*']
}, next
return
(rows, next)->
for row in rows
LANGUAGES[row.code] = pMgr.newLanguage row
for country in countries
country.data.property = PROPERTIES[country.data.code]
insertCountriesQuery = pMgr.getInsertQueryString 'Country', countries.map((data)-> data.data), {dialect: config.dialect}
connectors.writer.query insertCountriesQuery, next
return
(res, next)->
pMgr.listCountry {
type: 'json'
fields: ['*', 'property:*']
}, next
return
(rows, next)->
for row in rows
COUNTRIES[row.code] = pMgr.newLanguage row
entries = []
i = 0
_.forEach PROPERTIES, (property)->
for lng, value of translations[i]
entries.push
language: LANGUAGES[lng]
property: property
value: value
i++
return
insertTranslationsQuery = pMgr.getInsertQueryString 'Translation', entries, {dialect: config.dialect}
connectors.writer.query insertTranslationsQuery, next
return
(res, next)->
name = 'admin'
firstName = 'admin'
pMgr.insertUser {
name: name.toUpperCase()
firstName: firstName
email: firstName.toLowerCase() + '.' + name.toLowerCase() + '@xxxxx.com'
login: firstName.charAt(0).toLowerCase() + name.toLowerCase()
occupation: occupations[0]
country: COUNTRIES.CAMEROUN
language: LANGUAGES['fr-FR']
}, next
return
(admin, next)->
countries = Object.keys(COUNTRIES)
languages = Object.keys(LANGUAGES)
author = null
for name, iname in names
for firstName, i in firstNames
users.push
name: name.toUpperCase()
firstName: firstName
email: firstName.toLowerCase() + '.' + name.toLowerCase() + '@xxxxx.com'
login: firstName.charAt(0).toLowerCase() + name.toLowerCase()
occupation: occupations[(iname + i) % occupations.length]
country: COUNTRIES[countries[(iname + i + 1) % countries.length]]
language: LANGUAGES[languages[(iname + i + 1) % languages.length]]
author: admin
insertUsersDataQuery = pMgr.getInsertQueryString 'Data', users, {dialect: config.dialect}
connectors.writer.query insertUsersDataQuery, next
return
(id, next)->
pMgr.listData {
type: 'json'
fields: ['id']
limit: 18446744073709552
offset: 1
}, next
return
(rows, next)->
for row, i in rows
users[i].id = row.id
insertUsersQuery = pMgr.getInsertQueryString 'User', users, {dialect: config.dialect}
connectors.writer.query insertUsersQuery, next
return
], done
return
| 80296 | async = require 'async'
_ = require 'lodash'
{squel} = require('../')
module.exports = (config, connectors, done)->
pMgr = globals.pMgr
scripts = []
languages = []
languages.push
data:
code: 'fr-FR'
key: 'FR'
label: 'Français'
translation:
'fr-FR': 'Français'
'en-GB': 'French'
languages.push
data:
code: 'en-GB'
key: 'EN'
label: 'English'
translation:
'fr-FR': 'Anglais'
'en-GB': 'English'
countries = []
countries.push
data:
code: 'ARGENTINA'
translation:
'fr-FR': 'Argentine'
'en-GB': 'Argentina'
countries.push
data:
code: 'CAMEROUN'
translation:
'fr-FR': 'Cameroun'
'en-GB': 'Cameroon'
countries.push
data:
code: 'FRANCE'
translation:
'fr-FR': 'France'
'en-GB': 'France'
countries.push
data:
code: 'UNITED KINGDOM'
translation:
'fr-FR': 'Royaumes Unis'
'en-GB': 'United Kingdom'
data = languages.concat(countries)
properties = data.map (data)-> data.data
translations = data.map (data)-> data.translation
insertPropertiesQuery = pMgr.getInsertQueryString 'Property', properties, {dialect: config.dialect}
PROPERTIES = {}
LANGUAGES = {}
COUNTRIES = {}
users = []
names = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']
firstNames = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'].concat ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']
occupations = ['Drafter', 'Housebreaker', 'Miner', 'Physician']
async.waterfall [
(next)-> connectors.writer.query insertPropertiesQuery, next
(res, next)-> pMgr.listProperty {type: 'json'}, next
(rows, next)->
for row in rows
PROPERTIES[row.code] = pMgr.newProperty row
for language in languages
language.data.property = PROPERTIES[language.data.code]
insertLanguagesQuery = pMgr.getInsertQueryString 'Language', languages.map((data)-> data.data), {dialect: config.dialect}
connectors.writer.query insertLanguagesQuery, next
return
(res, next)->
pMgr.listLanguage {
type: 'json'
fields: ['*', 'property:*']
}, next
return
(rows, next)->
for row in rows
LANGUAGES[row.code] = pMgr.newLanguage row
for country in countries
country.data.property = PROPERTIES[country.data.code]
insertCountriesQuery = pMgr.getInsertQueryString 'Country', countries.map((data)-> data.data), {dialect: config.dialect}
connectors.writer.query insertCountriesQuery, next
return
(res, next)->
pMgr.listCountry {
type: 'json'
fields: ['*', 'property:*']
}, next
return
(rows, next)->
for row in rows
COUNTRIES[row.code] = pMgr.newLanguage row
entries = []
i = 0
_.forEach PROPERTIES, (property)->
for lng, value of translations[i]
entries.push
language: LANGUAGES[lng]
property: property
value: value
i++
return
insertTranslationsQuery = pMgr.getInsertQueryString 'Translation', entries, {dialect: config.dialect}
connectors.writer.query insertTranslationsQuery, next
return
(res, next)->
name = 'admin'
firstName = 'admin'
pMgr.insertUser {
name: name.toUpperCase()
firstName: <NAME>
email: firstName.toLowerCase() + '.' + name.toLowerCase() + '@xxxxx.com'
login: firstName.charAt(0).toLowerCase() + name.toLowerCase()
occupation: occupations[0]
country: COUNTRIES.CAMEROUN
language: LANGUAGES['fr-FR']
}, next
return
(admin, next)->
countries = Object.keys(COUNTRIES)
languages = Object.keys(LANGUAGES)
author = null
for name, iname in names
for firstName, i in firstNames
users.push
name: <NAME>.toUpperCase()
firstName: <NAME>
email: firstName.toLowerCase() + '.' + name.toLowerCase() + '@xxxxx.com'
login: firstName.charAt(0).toLowerCase() + name.toLowerCase()
occupation: occupations[(iname + i) % occupations.length]
country: COUNTRIES[countries[(iname + i + 1) % countries.length]]
language: LANGUAGES[languages[(iname + i + 1) % languages.length]]
author: admin
insertUsersDataQuery = pMgr.getInsertQueryString 'Data', users, {dialect: config.dialect}
connectors.writer.query insertUsersDataQuery, next
return
(id, next)->
pMgr.listData {
type: 'json'
fields: ['id']
limit: 18446744073709552
offset: 1
}, next
return
(rows, next)->
for row, i in rows
users[i].id = row.id
insertUsersQuery = pMgr.getInsertQueryString 'User', users, {dialect: config.dialect}
connectors.writer.query insertUsersQuery, next
return
], done
return
| true | async = require 'async'
_ = require 'lodash'
{squel} = require('../')
module.exports = (config, connectors, done)->
pMgr = globals.pMgr
scripts = []
languages = []
languages.push
data:
code: 'fr-FR'
key: 'FR'
label: 'Français'
translation:
'fr-FR': 'Français'
'en-GB': 'French'
languages.push
data:
code: 'en-GB'
key: 'EN'
label: 'English'
translation:
'fr-FR': 'Anglais'
'en-GB': 'English'
countries = []
countries.push
data:
code: 'ARGENTINA'
translation:
'fr-FR': 'Argentine'
'en-GB': 'Argentina'
countries.push
data:
code: 'CAMEROUN'
translation:
'fr-FR': 'Cameroun'
'en-GB': 'Cameroon'
countries.push
data:
code: 'FRANCE'
translation:
'fr-FR': 'France'
'en-GB': 'France'
countries.push
data:
code: 'UNITED KINGDOM'
translation:
'fr-FR': 'Royaumes Unis'
'en-GB': 'United Kingdom'
data = languages.concat(countries)
properties = data.map (data)-> data.data
translations = data.map (data)-> data.translation
insertPropertiesQuery = pMgr.getInsertQueryString 'Property', properties, {dialect: config.dialect}
PROPERTIES = {}
LANGUAGES = {}
COUNTRIES = {}
users = []
names = ['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']
firstNames = ['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'].concat ['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']
occupations = ['Drafter', 'Housebreaker', 'Miner', 'Physician']
async.waterfall [
(next)-> connectors.writer.query insertPropertiesQuery, next
(res, next)-> pMgr.listProperty {type: 'json'}, next
(rows, next)->
for row in rows
PROPERTIES[row.code] = pMgr.newProperty row
for language in languages
language.data.property = PROPERTIES[language.data.code]
insertLanguagesQuery = pMgr.getInsertQueryString 'Language', languages.map((data)-> data.data), {dialect: config.dialect}
connectors.writer.query insertLanguagesQuery, next
return
(res, next)->
pMgr.listLanguage {
type: 'json'
fields: ['*', 'property:*']
}, next
return
(rows, next)->
for row in rows
LANGUAGES[row.code] = pMgr.newLanguage row
for country in countries
country.data.property = PROPERTIES[country.data.code]
insertCountriesQuery = pMgr.getInsertQueryString 'Country', countries.map((data)-> data.data), {dialect: config.dialect}
connectors.writer.query insertCountriesQuery, next
return
(res, next)->
pMgr.listCountry {
type: 'json'
fields: ['*', 'property:*']
}, next
return
(rows, next)->
for row in rows
COUNTRIES[row.code] = pMgr.newLanguage row
entries = []
i = 0
_.forEach PROPERTIES, (property)->
for lng, value of translations[i]
entries.push
language: LANGUAGES[lng]
property: property
value: value
i++
return
insertTranslationsQuery = pMgr.getInsertQueryString 'Translation', entries, {dialect: config.dialect}
connectors.writer.query insertTranslationsQuery, next
return
(res, next)->
name = 'admin'
firstName = 'admin'
pMgr.insertUser {
name: name.toUpperCase()
firstName: PI:NAME:<NAME>END_PI
email: firstName.toLowerCase() + '.' + name.toLowerCase() + '@xxxxx.com'
login: firstName.charAt(0).toLowerCase() + name.toLowerCase()
occupation: occupations[0]
country: COUNTRIES.CAMEROUN
language: LANGUAGES['fr-FR']
}, next
return
(admin, next)->
countries = Object.keys(COUNTRIES)
languages = Object.keys(LANGUAGES)
author = null
for name, iname in names
for firstName, i in firstNames
users.push
name: PI:NAME:<NAME>END_PI.toUpperCase()
firstName: PI:NAME:<NAME>END_PI
email: firstName.toLowerCase() + '.' + name.toLowerCase() + '@xxxxx.com'
login: firstName.charAt(0).toLowerCase() + name.toLowerCase()
occupation: occupations[(iname + i) % occupations.length]
country: COUNTRIES[countries[(iname + i + 1) % countries.length]]
language: LANGUAGES[languages[(iname + i + 1) % languages.length]]
author: admin
insertUsersDataQuery = pMgr.getInsertQueryString 'Data', users, {dialect: config.dialect}
connectors.writer.query insertUsersDataQuery, next
return
(id, next)->
pMgr.listData {
type: 'json'
fields: ['id']
limit: 18446744073709552
offset: 1
}, next
return
(rows, next)->
for row, i in rows
users[i].id = row.id
insertUsersQuery = pMgr.getInsertQueryString 'User', users, {dialect: config.dialect}
connectors.writer.query insertUsersQuery, next
return
], done
return
|
[
{
"context": "rn\n\n User.create(name: req.body.name, password: req.body.password)\n .success (user) =>\n @res.json u",
"end": 351,
"score": 0.9726322293281555,
"start": 334,
"tag": "PASSWORD",
"value": "req.body.password"
}
] | example/app/controllers/User.coffee | luin/Suki | 0 | module.exports = class extends Suki.Controller
@before '_checkPermission', only: 'createTask'
# GET /users/:userId
show: (@user) ->
@res.render()
# POST /users
create: ->
unless req.body.name or req.body.password
@next new Error 'Invalid params'
return
User.create(name: req.body.name, password: req.body.password)
.success (user) =>
@res.json user
# POST /users/:userId/tasks
createTask: ->
unless req.body.title
@next new Error 'Invalid params'
return
Task.create({ title: req.body.title }).success (task) =>
@user.addTask task
@res.json task
# GET /users/:userId/tasks
listTask: ->
@res.json @user.getTasks()
# Private methods
_checkPermission: (me, @user) ->
@next()
| 105460 | module.exports = class extends Suki.Controller
@before '_checkPermission', only: 'createTask'
# GET /users/:userId
show: (@user) ->
@res.render()
# POST /users
create: ->
unless req.body.name or req.body.password
@next new Error 'Invalid params'
return
User.create(name: req.body.name, password: <PASSWORD>)
.success (user) =>
@res.json user
# POST /users/:userId/tasks
createTask: ->
unless req.body.title
@next new Error 'Invalid params'
return
Task.create({ title: req.body.title }).success (task) =>
@user.addTask task
@res.json task
# GET /users/:userId/tasks
listTask: ->
@res.json @user.getTasks()
# Private methods
_checkPermission: (me, @user) ->
@next()
| true | module.exports = class extends Suki.Controller
@before '_checkPermission', only: 'createTask'
# GET /users/:userId
show: (@user) ->
@res.render()
# POST /users
create: ->
unless req.body.name or req.body.password
@next new Error 'Invalid params'
return
User.create(name: req.body.name, password: PI:PASSWORD:<PASSWORD>END_PI)
.success (user) =>
@res.json user
# POST /users/:userId/tasks
createTask: ->
unless req.body.title
@next new Error 'Invalid params'
return
Task.create({ title: req.body.title }).success (task) =>
@user.addTask task
@res.json task
# GET /users/:userId/tasks
listTask: ->
@res.json @user.getTasks()
# Private methods
_checkPermission: (me, @user) ->
@next()
|
[
{
"context": " /Liorean/g\n sample = \"Liorean said: My name is Liorean!\"\n pat = new BetterRegExp exp\n ours = sampl",
"end": 1926,
"score": 0.999792754650116,
"start": 1919,
"tag": "NAME",
"value": "Liorean"
}
] | node_modules/BetterRegExp/test/compatibility.coffee | DORCAS12345/lamisplus-angular | 1 | {util} = BetterRegExp = require '../'
should = require 'should'
require 'mocha'
# These samples are from http://www.javascriptkit.com/javatutors/redev3.shtml
describe 'instanceof', ->
it 'should be the same', (done) ->
exp = /sample/
pat = new BetterRegExp exp
(exp instanceof RegExp).should.equal true
(pat instanceof RegExp).should.equal true
done()
describe 'test()', ->
it 'should return identical results', (done) ->
exp = /sample/
sample = "Sample text"
pat = new BetterRegExp exp
ours = pat.test sample
theirs = exp.test sample
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.equal theirs
done()
describe 'exec()', ->
it 'should return identical results', (done) ->
exp = /s(amp)le/i
sample = "Sample text"
pat = new BetterRegExp exp
ours = pat.exec sample
theirs = exp.exec sample
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.match()', ->
it 'should return identical results', (done) ->
exp = /r?or?/g
sample = "Watch out for the rock!"
pat = new BetterRegExp exp
ours = sample.match pat
theirs = sample.match exp
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.search()', ->
it 'should return identical results', (done) ->
exp = /for/
sample = "Watch out for the rock!"
pat = new BetterRegExp exp
ours = sample.search pat
theirs = sample.search exp
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.replace()', ->
it 'should return identical results', (done) ->
exp = /Liorean/g
sample = "Liorean said: My name is Liorean!"
pat = new BetterRegExp exp
ours = sample.replace pat, 'shawty'
theirs = sample.replace exp, 'shawty'
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.split()', ->
it 'should return identical results', (done) ->
exp = /\s/g
sample = "I am confused"
pat = new BetterRegExp exp
ours = sample.split pat
theirs = sample.split exp
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done() | 51242 | {util} = BetterRegExp = require '../'
should = require 'should'
require 'mocha'
# These samples are from http://www.javascriptkit.com/javatutors/redev3.shtml
describe 'instanceof', ->
it 'should be the same', (done) ->
exp = /sample/
pat = new BetterRegExp exp
(exp instanceof RegExp).should.equal true
(pat instanceof RegExp).should.equal true
done()
describe 'test()', ->
it 'should return identical results', (done) ->
exp = /sample/
sample = "Sample text"
pat = new BetterRegExp exp
ours = pat.test sample
theirs = exp.test sample
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.equal theirs
done()
describe 'exec()', ->
it 'should return identical results', (done) ->
exp = /s(amp)le/i
sample = "Sample text"
pat = new BetterRegExp exp
ours = pat.exec sample
theirs = exp.exec sample
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.match()', ->
it 'should return identical results', (done) ->
exp = /r?or?/g
sample = "Watch out for the rock!"
pat = new BetterRegExp exp
ours = sample.match pat
theirs = sample.match exp
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.search()', ->
it 'should return identical results', (done) ->
exp = /for/
sample = "Watch out for the rock!"
pat = new BetterRegExp exp
ours = sample.search pat
theirs = sample.search exp
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.replace()', ->
it 'should return identical results', (done) ->
exp = /Liorean/g
sample = "Liorean said: My name is <NAME>!"
pat = new BetterRegExp exp
ours = sample.replace pat, 'shawty'
theirs = sample.replace exp, 'shawty'
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.split()', ->
it 'should return identical results', (done) ->
exp = /\s/g
sample = "I am confused"
pat = new BetterRegExp exp
ours = sample.split pat
theirs = sample.split exp
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done() | true | {util} = BetterRegExp = require '../'
should = require 'should'
require 'mocha'
# These samples are from http://www.javascriptkit.com/javatutors/redev3.shtml
describe 'instanceof', ->
it 'should be the same', (done) ->
exp = /sample/
pat = new BetterRegExp exp
(exp instanceof RegExp).should.equal true
(pat instanceof RegExp).should.equal true
done()
describe 'test()', ->
it 'should return identical results', (done) ->
exp = /sample/
sample = "Sample text"
pat = new BetterRegExp exp
ours = pat.test sample
theirs = exp.test sample
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.equal theirs
done()
describe 'exec()', ->
it 'should return identical results', (done) ->
exp = /s(amp)le/i
sample = "Sample text"
pat = new BetterRegExp exp
ours = pat.exec sample
theirs = exp.exec sample
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.match()', ->
it 'should return identical results', (done) ->
exp = /r?or?/g
sample = "Watch out for the rock!"
pat = new BetterRegExp exp
ours = sample.match pat
theirs = sample.match exp
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.search()', ->
it 'should return identical results', (done) ->
exp = /for/
sample = "Watch out for the rock!"
pat = new BetterRegExp exp
ours = sample.search pat
theirs = sample.search exp
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.replace()', ->
it 'should return identical results', (done) ->
exp = /Liorean/g
sample = "Liorean said: My name is PI:NAME:<NAME>END_PI!"
pat = new BetterRegExp exp
ours = sample.replace pat, 'shawty'
theirs = sample.replace exp, 'shawty'
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done()
describe 'String.split()', ->
it 'should return identical results', (done) ->
exp = /\s/g
sample = "I am confused"
pat = new BetterRegExp exp
ours = sample.split pat
theirs = sample.split exp
should.exist ours, "ours does not exist"
should.exist theirs, "theirs does not exist"
ours.should.eql theirs
done() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.