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": " uuid: 'whoever-uuid'\n token: 'some-token'\n responseId: 'its-electric'\n ", "end": 1675, "score": 0.9835603833198547, "start": 1665, "tag": "KEY", "value": "some-token" }, { "context": "auth).to.deep.equal uuid: 'someone-uuid', token: 'some-token'\n expect(@request.metadata.jobType).to", "end": 2482, "score": 0.46680137515068054, "start": 2472, "tag": "KEY", "value": "some-token" }, { "context": " uuid: 'whoever-uuid'\n token: 'some-token'\n responseId: 'its-electric'\n ", "end": 3568, "score": 0.3995068371295929, "start": 3564, "tag": "PASSWORD", "value": "some" }, { "context": " uuid: 'whoever-uuid'\n token: 'some-token'\n responseId: 'its-electric'\n ", "end": 3574, "score": 0.4813767075538635, "start": 3569, "tag": "KEY", "value": "token" }, { "context": "auth).to.deep.equal uuid: 'someone-uuid', token: 'some-token'\n expect(@request.metadata.jobType).to", "end": 4376, "score": 0.7164180278778076, "start": 4366, "tag": "KEY", "value": "some-token" }, { "context": " uuid: 'whoever-uuid'\n token: 'some-token'\n responseId: 'its-electric'\n ", "end": 5590, "score": 0.8446062207221985, "start": 5580, "tag": "KEY", "value": "some-token" }, { "context": "auth).to.deep.equal uuid: 'someone-uuid', token: 'some-token'\n expect(@request.metadata.jobType).to", "end": 6392, "score": 0.7551313042640686, "start": 6382, "tag": "KEY", "value": "some-token" }, { "context": "auth).to.deep.equal uuid: 'someone-uuid', token: 'some-token'\n expect(@request.metadata.jobType).", "end": 7223, "score": 0.8350362777709961, "start": 7213, "tag": "KEY", "value": "some-token" }, { "context": " metadata:\n auth:\n uuid: 'whoever-uuid'\n token: 'some-token'\n re", "end": 8217, "score": 0.7656593322753906, "start": 8205, "tag": "USERNAME", "value": "whoever-uuid" }, { "context": " uuid: 'whoever-uuid'\n token: 'some-token'\n responseId: 'its-electric'\n ", "end": 8251, "score": 0.9190504550933838, "start": 8241, "tag": "KEY", "value": "some-token" }, { "context": "auth).to.deep.equal uuid: 'emitter-uuid', token: 'some-token'\n expect(@request.metadata.jobType).to.e", "end": 9032, "score": 0.6203221678733826, "start": 9022, "tag": "KEY", "value": "some-token" }, { "context": " uuid: 'whoever-uuid'\n token: 'some-token'\n responseId: 'its-electric'\n ", "end": 10104, "score": 0.4636436402797699, "start": 10099, "tag": "KEY", "value": "token" } ]
test/enqueue-webhook-spec.coffee
octoblu/meshblu-core-task-enqueue-webhooks
0
{describe,beforeEach,it,expect} = global uuid = require 'uuid' redis = require 'fakeredis' mongojs = require 'mongojs' Datastore = require 'meshblu-core-datastore' JobManager = require 'meshblu-core-job-manager' RedisNS = require '@octoblu/redis-ns' EnqueueWebhooks = require '../' describe 'EnqueueWebhooks', -> beforeEach (done) -> database = mongojs 'enqueue-webhook-test', ['devices'] @datastore = new Datastore database: database collection: 'devices' database.devices.remove => done() beforeEach -> @redisKey = uuid.v1() pepper = 'im-a-pepper' @jobManager = new JobManager client: new RedisNS 'ns', redis.createClient(@redisKey) timeoutSeconds: 1 jobLogSampleRate: 1 @cache = new RedisNS 'ns', redis.createClient(@redisKey) @uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid) options = { @datastore @uuidAliasResolver @jobManager pepper @cache } @sut = new EnqueueWebhooks options describe '->do', -> describe 'messageType: broadcast', -> describe 'when given a device', -> beforeEach (done) -> record = uuid: 'someone-uuid' meshblu: forwarders: broadcast: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'some-token' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'broadcast' rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: 'some-token' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'broadcast' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'messageType: sent', -> describe 'when given a device', -> beforeEach (done) -> record = uuid: 'someone-uuid' meshblu: forwarders: sent: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'some-token' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'sent' rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: 'some-token' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'sent' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'when given a device with two webhooks of the same type', -> beforeEach (done) -> record = uuid: 'someone-uuid' meshblu: forwarders: sent: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' , type: 'webhook' url: 'http://example.com', method: 'GET' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'some-token' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'sent' rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: 'some-token' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'sent' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'the second job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create another job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: 'some-token' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'sent' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://example.com' method: 'GET' type: 'webhook' describe 'messageType: received', -> beforeEach (done) -> record = uuid: 'emitter-uuid' meshblu: forwarders: received: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'some-token' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'received' rawData: '{"devices":["emitter-uuid"]}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'emitter-uuid', token: 'some-token' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'received' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":["emitter-uuid"]}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'messageType: broadcast with new style hooks', -> beforeEach (done) -> record = uuid: 'emitter-uuid' meshblu: forwarders: broadcast: sent: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'some-token' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'emitter-uuid' messageType: 'broadcast' rawData: '{"devices":["emitter-uuid"]}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should not create a job', -> expect(@request).not.to.exist describe '->getUniqueForwarders', -> describe 'when there are duplicates', -> beforeEach -> device = meshblu: forwarders: 'some-type': [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } { method: 'UNIQUE', url: 2 } ] @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.deep.equal [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } ] describe 'when there are no dups', -> beforeEach -> device = meshblu: forwarders: 'some-type': [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } ] @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.deep.equal [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } ] describe 'when there are no forwarders', -> beforeEach -> device = meshblu: {} @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.be.null describe 'when the forwarders are not an array', -> beforeEach -> device = meshblu: forwarders: 'some-type': {'oh': 'no'} @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.be.null
103701
{describe,beforeEach,it,expect} = global uuid = require 'uuid' redis = require 'fakeredis' mongojs = require 'mongojs' Datastore = require 'meshblu-core-datastore' JobManager = require 'meshblu-core-job-manager' RedisNS = require '@octoblu/redis-ns' EnqueueWebhooks = require '../' describe 'EnqueueWebhooks', -> beforeEach (done) -> database = mongojs 'enqueue-webhook-test', ['devices'] @datastore = new Datastore database: database collection: 'devices' database.devices.remove => done() beforeEach -> @redisKey = uuid.v1() pepper = 'im-a-pepper' @jobManager = new JobManager client: new RedisNS 'ns', redis.createClient(@redisKey) timeoutSeconds: 1 jobLogSampleRate: 1 @cache = new RedisNS 'ns', redis.createClient(@redisKey) @uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid) options = { @datastore @uuidAliasResolver @jobManager pepper @cache } @sut = new EnqueueWebhooks options describe '->do', -> describe 'messageType: broadcast', -> describe 'when given a device', -> beforeEach (done) -> record = uuid: 'someone-uuid' meshblu: forwarders: broadcast: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: '<KEY>' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'broadcast' rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: '<KEY>' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'broadcast' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'messageType: sent', -> describe 'when given a device', -> beforeEach (done) -> record = uuid: 'someone-uuid' meshblu: forwarders: sent: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: '<PASSWORD>-<KEY>' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'sent' rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: '<KEY>' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'sent' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'when given a device with two webhooks of the same type', -> beforeEach (done) -> record = uuid: 'someone-uuid' meshblu: forwarders: sent: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' , type: 'webhook' url: 'http://example.com', method: 'GET' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: '<KEY>' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'sent' rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: '<KEY>' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'sent' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'the second job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create another job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: '<KEY>' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'sent' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://example.com' method: 'GET' type: 'webhook' describe 'messageType: received', -> beforeEach (done) -> record = uuid: 'emitter-uuid' meshblu: forwarders: received: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: '<KEY>' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'received' rawData: '{"devices":["emitter-uuid"]}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'emitter-uuid', token: '<KEY>' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'received' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":["emitter-uuid"]}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'messageType: broadcast with new style hooks', -> beforeEach (done) -> record = uuid: 'emitter-uuid' meshblu: forwarders: broadcast: sent: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'some-<KEY>' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'emitter-uuid' messageType: 'broadcast' rawData: '{"devices":["emitter-uuid"]}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should not create a job', -> expect(@request).not.to.exist describe '->getUniqueForwarders', -> describe 'when there are duplicates', -> beforeEach -> device = meshblu: forwarders: 'some-type': [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } { method: 'UNIQUE', url: 2 } ] @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.deep.equal [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } ] describe 'when there are no dups', -> beforeEach -> device = meshblu: forwarders: 'some-type': [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } ] @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.deep.equal [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } ] describe 'when there are no forwarders', -> beforeEach -> device = meshblu: {} @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.be.null describe 'when the forwarders are not an array', -> beforeEach -> device = meshblu: forwarders: 'some-type': {'oh': 'no'} @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.be.null
true
{describe,beforeEach,it,expect} = global uuid = require 'uuid' redis = require 'fakeredis' mongojs = require 'mongojs' Datastore = require 'meshblu-core-datastore' JobManager = require 'meshblu-core-job-manager' RedisNS = require '@octoblu/redis-ns' EnqueueWebhooks = require '../' describe 'EnqueueWebhooks', -> beforeEach (done) -> database = mongojs 'enqueue-webhook-test', ['devices'] @datastore = new Datastore database: database collection: 'devices' database.devices.remove => done() beforeEach -> @redisKey = uuid.v1() pepper = 'im-a-pepper' @jobManager = new JobManager client: new RedisNS 'ns', redis.createClient(@redisKey) timeoutSeconds: 1 jobLogSampleRate: 1 @cache = new RedisNS 'ns', redis.createClient(@redisKey) @uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid) options = { @datastore @uuidAliasResolver @jobManager pepper @cache } @sut = new EnqueueWebhooks options describe '->do', -> describe 'messageType: broadcast', -> describe 'when given a device', -> beforeEach (done) -> record = uuid: 'someone-uuid' meshblu: forwarders: broadcast: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'PI:KEY:<KEY>END_PI' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'broadcast' rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: 'PI:KEY:<KEY>END_PI' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'broadcast' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'messageType: sent', -> describe 'when given a device', -> beforeEach (done) -> record = uuid: 'someone-uuid' meshblu: forwarders: sent: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'PI:PASSWORD:<PASSWORD>END_PI-PI:KEY:<KEY>END_PI' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'sent' rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: 'PI:KEY:<KEY>END_PI' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'sent' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'when given a device with two webhooks of the same type', -> beforeEach (done) -> record = uuid: 'someone-uuid' meshblu: forwarders: sent: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' , type: 'webhook' url: 'http://example.com', method: 'GET' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'PI:KEY:<KEY>END_PI' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'sent' rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: 'PI:KEY:<KEY>END_PI' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'sent' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'the second job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create another job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'someone-uuid', token: 'PI:KEY:<KEY>END_PI' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'sent' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":"*"}' expect(@request.metadata.options).to.deep.equal url: 'http://example.com' method: 'GET' type: 'webhook' describe 'messageType: received', -> beforeEach (done) -> record = uuid: 'emitter-uuid' meshblu: forwarders: received: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'PI:KEY:<KEY>END_PI' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'someone-uuid' messageType: 'received' rawData: '{"devices":["emitter-uuid"]}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should create a job', -> expect(@request.metadata.auth).to.deep.equal uuid: 'emitter-uuid', token: 'PI:KEY:<KEY>END_PI' expect(@request.metadata.jobType).to.equal 'DeliverWebhook' expect(@request.metadata.toUuid).to.equal 'emitter-uuid' expect(@request.metadata.messageType).to.equal 'received' expect(@request.metadata.fromUuid).to.equal 'someone-uuid' expect(@request.rawData).to.equal '{"devices":["emitter-uuid"]}' expect(@request.metadata.options).to.deep.equal url: 'http://requestb.in/18gkt511' method: 'POST' type: 'webhook' describe 'messageType: broadcast with new style hooks', -> beforeEach (done) -> record = uuid: 'emitter-uuid' meshblu: forwarders: broadcast: sent: [ type: 'webhook' url: 'http://requestb.in/18gkt511', method: 'POST' ] @datastore.insert record, done beforeEach (done) -> request = metadata: auth: uuid: 'whoever-uuid' token: 'some-PI:KEY:<KEY>END_PI' responseId: 'its-electric' toUuid: 'emitter-uuid' fromUuid: 'emitter-uuid' messageType: 'broadcast' rawData: '{"devices":["emitter-uuid"]}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'the first job', -> beforeEach (done) -> @jobManager.getRequest ['request'], (error, @request) => done error it 'should not create a job', -> expect(@request).not.to.exist describe '->getUniqueForwarders', -> describe 'when there are duplicates', -> beforeEach -> device = meshblu: forwarders: 'some-type': [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } { method: 'UNIQUE', url: 2 } ] @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.deep.equal [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } ] describe 'when there are no dups', -> beforeEach -> device = meshblu: forwarders: 'some-type': [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } ] @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.deep.equal [ { method: 'UNIQUE', url: 1 } { method: 'UNIQUE', url: 2 } ] describe 'when there are no forwarders', -> beforeEach -> device = meshblu: {} @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.be.null describe 'when the forwarders are not an array', -> beforeEach -> device = meshblu: forwarders: 'some-type': {'oh': 'no'} @forwarders = @sut.getUniqueForwarders { device, messageType: 'some-type' } it 'should have unique forwarders', -> expect(@forwarders).to.be.null
[ { "context": "escribe 'ingress: badges', ->\n user =\n name: 'user'\n id: 'U123'\n robot =\n respond: sinon.spy(", "end": 154, "score": 0.9994454979896545, "start": 150, "tag": "USERNAME", "value": "user" }, { "context": ",\n ':p-a-chapeau-2:',\n ':susanna-moyer1:',\n ':susanna-moyer2:'\n ", "end": 651, "score": 0.7108927965164185, "start": 647, "tag": "USERNAME", "value": "anna" }, { "context": " ':p-a-chapeau-2:',\n ':susanna-moyer1:',\n ':susanna-moyer2:'\n ]\n ", "end": 657, "score": 0.7452017664909363, "start": 652, "tag": "USERNAME", "value": "moyer" }, { "context": "\n ':susanna-moyer1:',\n ':susanna-moyer2:'\n ]\n }\n }\n user", "end": 683, "score": 0.5989996790885925, "start": 679, "tag": "USERNAME", "value": "anna" }, { "context": " ':susanna-moyer1:',\n ':susanna-moyer2:'\n ]\n }\n }\n userForNam", "end": 689, "score": 0.649275541305542, "start": 684, "tag": "USERNAME", "value": "moyer" }, { "context": "old and new badge', ->\n @msg.match = [0, 'I', 'susanna-moyer, susanna-moyer-2016']\n @robot.respond.args[0][", "end": 5536, "score": 0.9192171096801758, "start": 5523, "tag": "USERNAME", "value": "susanna-moyer" }, { "context": "lready been added', ->\n @msg.match = [0, 'I', 'shonin']\n @robot.respond.args[0][1](@msg)\n @ro", "end": 5908, "score": 0.5484053492546082, "start": 5906, "tag": "USERNAME", "value": "sh" }, { "context": "eady been added', ->\n @msg.match = [0, 'I', 'shonin']\n @robot.respond.args[0][1](@msg)\n @robot.", "end": 5912, "score": 0.7028292417526245, "start": 5908, "tag": "NAME", "value": "onin" }, { "context": "4\n expect(@msg.send).to.have.been.calledWith('@user2: congrats on earning the :verified: badge!')\n ", "end": 6417, "score": 0.9907934665679932, "start": 6412, "tag": "USERNAME", "value": "user2" }, { "context": "escribe 'handles usernames with special characters [@-.]', ->\n it '(user-2)', ->\n @msg.match = [0", "end": 7324, "score": 0.7248166799545288, "start": 7324, "tag": "USERNAME", "value": "" }, { "context": " expect(@msg.send).to.have.been.calledWith('@user-2: congrats on earning the :verified: badge!')\n ", "end": 7619, "score": 0.8220633864402771, "start": 7615, "tag": "USERNAME", "value": "user" }, { "context": "')\n expect(@msg.send).to.have.been.calledWith('@user.2: congrats on earning the :verified: badge!')\n ", "end": 7952, "score": 0.9899169206619263, "start": 7945, "tag": "USERNAME", "value": "@user.2" }, { "context": "ngrats on earning the :verified: badge!')\n it '(@user2)', ->\n @msg.match = [0, '@user2', 'verified'", "end": 8013, "score": 0.9903801083564758, "start": 8007, "tag": "USERNAME", "value": "@user2" }, { "context": "ge!')\n it '(@user2)', ->\n @msg.match = [0, '@user2', 'verified']\n @robot.respond.args[0][1](@ms", "end": 8050, "score": 0.9966723322868347, "start": 8043, "tag": "USERNAME", "value": "'@user2" }, { "context": "')\n expect(@msg.send).to.have.been.calledWith('@user2: congrats on earning the :verified: badge!')\n", "end": 8282, "score": 0.9907253384590149, "start": 8276, "tag": "USERNAME", "value": "@user2" } ]
test/badges-test.coffee
adglueck/hubot-ingress
52
chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' expect = chai.expect describe 'ingress: badges', -> user = name: 'user' id: 'U123' robot = respond: sinon.spy() hear: sinon.spy() brain: on: (_, cb) -> cb() data: { ingressBadges: { U012: [ ':ada-1:', ':ada-2:', ':aegis:', ':akira:', ':devra-1:', ':goruckstealh:', ':goruckurban:', ':nl-1331-1:', ':nl-1331-2:', ':oliver-lynton-wolfe-2:', ':p-a-chapeau-2:', ':susanna-moyer1:', ':susanna-moyer2:' ] } } userForName: (who) -> forName = name: who id: 'U234' beforeEach -> @user = user @robot = robot @data = @robot.brain.data @msg = send: sinon.spy() reply: sinon.spy() envelope: user: @user message: user: @user require('../src/badges')(robot) it 'updates user badge names when robot brain is loaded', -> badges = @data.ingressBadges.U012 badgeUpdateMapVersion = @data.ingressBadgeNameUpdateVersion expect(badges).to.be.a('array') expect(badges).to.include(':ada:') expect(badges).to.include(':ada-2016:') expect(badges).to.include(':aegis-nova:') expect(badges).to.include(':akira-tsukasa:') expect(badges).to.include(':devra-bogdanovich:') expect(badges).to.include(':goruck-stealth:') expect(badges).to.include(':goruck-urban:') expect(badges).to.include(':nl-1331:') expect(badges).to.include(':nl-1331-2016:') expect(badges).to.include(':oliver-lynton-wolfe-2016:') expect(badges).to.include(':p-a-chapeau-2016:') expect(badges).to.include(':susanna-moyer:') expect(badges).to.include(':susanna-moyer-2016:') expect(badgeUpdateMapVersion).to.equal 1 it 'registers "have badge" listener', -> expect(@robot.respond).to.have.been.calledWith(/(@?[.\w\-]+) (?:have|has|got|earned)(?: the)? :?([\-\w,\s]+):? badges?/i) it 'registers "what badges" listener', -> expect(@robot.respond).to.have.been.calledWith(/wh(?:at|ich) badges? do(?:es)? (@?[.\w\-]+) have/i) it 'registers "do not have" listener', -> expect(@robot.respond).to.have.been.calledWith(/(@?[.\w\-]+) (?:do(?:n't|esn't| not)) have the :?([\-\w]+):? badge/i) it 'responds to "I have the founder badge"', -> @msg.match = [0, 'I', 'founder'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :founder: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':founder:') it 'responds to "I have the oliver-lynton-wolfe badge"', -> @msg.match = [0, 'I', 'oliver-lynton-wolfe'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :oliver-lynton-wolfe: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':oliver-lynton-wolfe:') it 'responds to "I have the black guardian badge"', -> @msg.match = [0, 'I', 'black guardian'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :guardian5: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':guardian5:') it 'responds to "I have the guardian badge"', -> @msg.match = [0, 'I', 'guardian'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :guardian1: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':guardian1:') it 'responds with error message on invalid badge name', -> @msg.match = [0, 'I', 'random'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('invalid badge name(s): random1.') expect(badges).to.be.a('array') expect(badges).not.to.include(':random1:') it '"I have" automatically replaces badge of same type', -> @msg.match = [0, 'I', 'hacker1'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :hacker1: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':hacker1:') @msg.match = [0, 'I', 'hacker2'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :hacker2: badge!') expect(badges).to.be.a('array') expect(badges).not.to.include(':hacker1:') expect(badges).to.include(':hacker2:') it '"I have" can handle multiple badge names', -> @msg.match = [0, 'I', 'pioneer3, hacker4, builder1, oliver-lynton-wolfe'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith(sinon.match(/congrats on earning the .* badges!/)) expect(badges).to.be.a('array') expect(badges).to.include(':pioneer3:') expect(badges).to.include(':hacker4:') expect(badges).to.include(':builder1:') expect(badges).to.include(':oliver-lynton-wolfe:') it '"I have" can handle multiple character badges when the respective character has an old and new badge', -> @msg.match = [0, 'I', 'susanna-moyer, susanna-moyer-2016'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(badges).to.be.a('array') expect(badges).to.include(':susanna-moyer:') expect(badges).to.include(':susanna-moyer-2016:') it '"I have" doesn\'t attempt to add an anomaly or character badge that has already been added', -> @msg.match = [0, 'I', 'shonin'] @robot.respond.args[0][1](@msg) @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(badges).to.be.a('array') expect(badges).to.include(':shonin:') expect(badges).to.satisfy((bdgs) -> (bdgs.filter (x) -> x == ':shonin:').length == 1) it 'responds to "user2 has the verified badge"', -> @msg.match = [0, 'user2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(@msg.send).to.have.been.calledWith('@user2: congrats on earning the :verified: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':verified:') it 'responds to "what badges do I have"', -> @msg.match = [0, 'I'] @robot.respond.args[1][1](@msg) expect(@msg.reply).to.have.been.calledWith(sinon.match(/You have (the following|no) badges.*/)) it 'responds to "what badges does user2 have"', -> @msg.match = [0, 'user2'] @robot.respond.args[1][1](@msg) expect(@msg.reply).to.have.been.calledWith(sinon.match(/user2 has (the following|no) badges.*/)) it 'responds to "I don\'t have the founder badge"', -> @msg.match = [0, 'I', 'founder'] @robot.respond.args[2][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('removed the :founder: badge') expect(badges).not.to.include(':founder:') describe 'handles usernames with special characters [@-.]', -> it '(user-2)', -> @msg.match = [0, 'user-2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(badges).to.be.a('array') expect(badges).to.include(':verified:') expect(@msg.send).to.have.been.calledWith('@user-2: congrats on earning the :verified: badge!') it '(user.2)', -> @msg.match = [0, 'user.2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(badges).to.be.a('array') expect(badges).to.include(':verified:') expect(@msg.send).to.have.been.calledWith('@user.2: congrats on earning the :verified: badge!') it '(@user2)', -> @msg.match = [0, '@user2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(badges).to.be.a('array') expect(badges).to.include(':verified:') expect(@msg.send).to.have.been.calledWith('@user2: congrats on earning the :verified: badge!')
129688
chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' expect = chai.expect describe 'ingress: badges', -> user = name: 'user' id: 'U123' robot = respond: sinon.spy() hear: sinon.spy() brain: on: (_, cb) -> cb() data: { ingressBadges: { U012: [ ':ada-1:', ':ada-2:', ':aegis:', ':akira:', ':devra-1:', ':goruckstealh:', ':goruckurban:', ':nl-1331-1:', ':nl-1331-2:', ':oliver-lynton-wolfe-2:', ':p-a-chapeau-2:', ':susanna-moyer1:', ':susanna-moyer2:' ] } } userForName: (who) -> forName = name: who id: 'U234' beforeEach -> @user = user @robot = robot @data = @robot.brain.data @msg = send: sinon.spy() reply: sinon.spy() envelope: user: @user message: user: @user require('../src/badges')(robot) it 'updates user badge names when robot brain is loaded', -> badges = @data.ingressBadges.U012 badgeUpdateMapVersion = @data.ingressBadgeNameUpdateVersion expect(badges).to.be.a('array') expect(badges).to.include(':ada:') expect(badges).to.include(':ada-2016:') expect(badges).to.include(':aegis-nova:') expect(badges).to.include(':akira-tsukasa:') expect(badges).to.include(':devra-bogdanovich:') expect(badges).to.include(':goruck-stealth:') expect(badges).to.include(':goruck-urban:') expect(badges).to.include(':nl-1331:') expect(badges).to.include(':nl-1331-2016:') expect(badges).to.include(':oliver-lynton-wolfe-2016:') expect(badges).to.include(':p-a-chapeau-2016:') expect(badges).to.include(':susanna-moyer:') expect(badges).to.include(':susanna-moyer-2016:') expect(badgeUpdateMapVersion).to.equal 1 it 'registers "have badge" listener', -> expect(@robot.respond).to.have.been.calledWith(/(@?[.\w\-]+) (?:have|has|got|earned)(?: the)? :?([\-\w,\s]+):? badges?/i) it 'registers "what badges" listener', -> expect(@robot.respond).to.have.been.calledWith(/wh(?:at|ich) badges? do(?:es)? (@?[.\w\-]+) have/i) it 'registers "do not have" listener', -> expect(@robot.respond).to.have.been.calledWith(/(@?[.\w\-]+) (?:do(?:n't|esn't| not)) have the :?([\-\w]+):? badge/i) it 'responds to "I have the founder badge"', -> @msg.match = [0, 'I', 'founder'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :founder: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':founder:') it 'responds to "I have the oliver-lynton-wolfe badge"', -> @msg.match = [0, 'I', 'oliver-lynton-wolfe'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :oliver-lynton-wolfe: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':oliver-lynton-wolfe:') it 'responds to "I have the black guardian badge"', -> @msg.match = [0, 'I', 'black guardian'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :guardian5: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':guardian5:') it 'responds to "I have the guardian badge"', -> @msg.match = [0, 'I', 'guardian'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :guardian1: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':guardian1:') it 'responds with error message on invalid badge name', -> @msg.match = [0, 'I', 'random'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('invalid badge name(s): random1.') expect(badges).to.be.a('array') expect(badges).not.to.include(':random1:') it '"I have" automatically replaces badge of same type', -> @msg.match = [0, 'I', 'hacker1'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :hacker1: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':hacker1:') @msg.match = [0, 'I', 'hacker2'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :hacker2: badge!') expect(badges).to.be.a('array') expect(badges).not.to.include(':hacker1:') expect(badges).to.include(':hacker2:') it '"I have" can handle multiple badge names', -> @msg.match = [0, 'I', 'pioneer3, hacker4, builder1, oliver-lynton-wolfe'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith(sinon.match(/congrats on earning the .* badges!/)) expect(badges).to.be.a('array') expect(badges).to.include(':pioneer3:') expect(badges).to.include(':hacker4:') expect(badges).to.include(':builder1:') expect(badges).to.include(':oliver-lynton-wolfe:') it '"I have" can handle multiple character badges when the respective character has an old and new badge', -> @msg.match = [0, 'I', 'susanna-moyer, susanna-moyer-2016'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(badges).to.be.a('array') expect(badges).to.include(':susanna-moyer:') expect(badges).to.include(':susanna-moyer-2016:') it '"I have" doesn\'t attempt to add an anomaly or character badge that has already been added', -> @msg.match = [0, 'I', 'sh<NAME>'] @robot.respond.args[0][1](@msg) @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(badges).to.be.a('array') expect(badges).to.include(':shonin:') expect(badges).to.satisfy((bdgs) -> (bdgs.filter (x) -> x == ':shonin:').length == 1) it 'responds to "user2 has the verified badge"', -> @msg.match = [0, 'user2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(@msg.send).to.have.been.calledWith('@user2: congrats on earning the :verified: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':verified:') it 'responds to "what badges do I have"', -> @msg.match = [0, 'I'] @robot.respond.args[1][1](@msg) expect(@msg.reply).to.have.been.calledWith(sinon.match(/You have (the following|no) badges.*/)) it 'responds to "what badges does user2 have"', -> @msg.match = [0, 'user2'] @robot.respond.args[1][1](@msg) expect(@msg.reply).to.have.been.calledWith(sinon.match(/user2 has (the following|no) badges.*/)) it 'responds to "I don\'t have the founder badge"', -> @msg.match = [0, 'I', 'founder'] @robot.respond.args[2][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('removed the :founder: badge') expect(badges).not.to.include(':founder:') describe 'handles usernames with special characters [@-.]', -> it '(user-2)', -> @msg.match = [0, 'user-2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(badges).to.be.a('array') expect(badges).to.include(':verified:') expect(@msg.send).to.have.been.calledWith('@user-2: congrats on earning the :verified: badge!') it '(user.2)', -> @msg.match = [0, 'user.2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(badges).to.be.a('array') expect(badges).to.include(':verified:') expect(@msg.send).to.have.been.calledWith('@user.2: congrats on earning the :verified: badge!') it '(@user2)', -> @msg.match = [0, '@user2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(badges).to.be.a('array') expect(badges).to.include(':verified:') expect(@msg.send).to.have.been.calledWith('@user2: congrats on earning the :verified: badge!')
true
chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' expect = chai.expect describe 'ingress: badges', -> user = name: 'user' id: 'U123' robot = respond: sinon.spy() hear: sinon.spy() brain: on: (_, cb) -> cb() data: { ingressBadges: { U012: [ ':ada-1:', ':ada-2:', ':aegis:', ':akira:', ':devra-1:', ':goruckstealh:', ':goruckurban:', ':nl-1331-1:', ':nl-1331-2:', ':oliver-lynton-wolfe-2:', ':p-a-chapeau-2:', ':susanna-moyer1:', ':susanna-moyer2:' ] } } userForName: (who) -> forName = name: who id: 'U234' beforeEach -> @user = user @robot = robot @data = @robot.brain.data @msg = send: sinon.spy() reply: sinon.spy() envelope: user: @user message: user: @user require('../src/badges')(robot) it 'updates user badge names when robot brain is loaded', -> badges = @data.ingressBadges.U012 badgeUpdateMapVersion = @data.ingressBadgeNameUpdateVersion expect(badges).to.be.a('array') expect(badges).to.include(':ada:') expect(badges).to.include(':ada-2016:') expect(badges).to.include(':aegis-nova:') expect(badges).to.include(':akira-tsukasa:') expect(badges).to.include(':devra-bogdanovich:') expect(badges).to.include(':goruck-stealth:') expect(badges).to.include(':goruck-urban:') expect(badges).to.include(':nl-1331:') expect(badges).to.include(':nl-1331-2016:') expect(badges).to.include(':oliver-lynton-wolfe-2016:') expect(badges).to.include(':p-a-chapeau-2016:') expect(badges).to.include(':susanna-moyer:') expect(badges).to.include(':susanna-moyer-2016:') expect(badgeUpdateMapVersion).to.equal 1 it 'registers "have badge" listener', -> expect(@robot.respond).to.have.been.calledWith(/(@?[.\w\-]+) (?:have|has|got|earned)(?: the)? :?([\-\w,\s]+):? badges?/i) it 'registers "what badges" listener', -> expect(@robot.respond).to.have.been.calledWith(/wh(?:at|ich) badges? do(?:es)? (@?[.\w\-]+) have/i) it 'registers "do not have" listener', -> expect(@robot.respond).to.have.been.calledWith(/(@?[.\w\-]+) (?:do(?:n't|esn't| not)) have the :?([\-\w]+):? badge/i) it 'responds to "I have the founder badge"', -> @msg.match = [0, 'I', 'founder'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :founder: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':founder:') it 'responds to "I have the oliver-lynton-wolfe badge"', -> @msg.match = [0, 'I', 'oliver-lynton-wolfe'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :oliver-lynton-wolfe: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':oliver-lynton-wolfe:') it 'responds to "I have the black guardian badge"', -> @msg.match = [0, 'I', 'black guardian'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :guardian5: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':guardian5:') it 'responds to "I have the guardian badge"', -> @msg.match = [0, 'I', 'guardian'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :guardian1: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':guardian1:') it 'responds with error message on invalid badge name', -> @msg.match = [0, 'I', 'random'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('invalid badge name(s): random1.') expect(badges).to.be.a('array') expect(badges).not.to.include(':random1:') it '"I have" automatically replaces badge of same type', -> @msg.match = [0, 'I', 'hacker1'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :hacker1: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':hacker1:') @msg.match = [0, 'I', 'hacker2'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('congrats on earning the :hacker2: badge!') expect(badges).to.be.a('array') expect(badges).not.to.include(':hacker1:') expect(badges).to.include(':hacker2:') it '"I have" can handle multiple badge names', -> @msg.match = [0, 'I', 'pioneer3, hacker4, builder1, oliver-lynton-wolfe'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith(sinon.match(/congrats on earning the .* badges!/)) expect(badges).to.be.a('array') expect(badges).to.include(':pioneer3:') expect(badges).to.include(':hacker4:') expect(badges).to.include(':builder1:') expect(badges).to.include(':oliver-lynton-wolfe:') it '"I have" can handle multiple character badges when the respective character has an old and new badge', -> @msg.match = [0, 'I', 'susanna-moyer, susanna-moyer-2016'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(badges).to.be.a('array') expect(badges).to.include(':susanna-moyer:') expect(badges).to.include(':susanna-moyer-2016:') it '"I have" doesn\'t attempt to add an anomaly or character badge that has already been added', -> @msg.match = [0, 'I', 'shPI:NAME:<NAME>END_PI'] @robot.respond.args[0][1](@msg) @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U123 expect(badges).to.be.a('array') expect(badges).to.include(':shonin:') expect(badges).to.satisfy((bdgs) -> (bdgs.filter (x) -> x == ':shonin:').length == 1) it 'responds to "user2 has the verified badge"', -> @msg.match = [0, 'user2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(@msg.send).to.have.been.calledWith('@user2: congrats on earning the :verified: badge!') expect(badges).to.be.a('array') expect(badges).to.include(':verified:') it 'responds to "what badges do I have"', -> @msg.match = [0, 'I'] @robot.respond.args[1][1](@msg) expect(@msg.reply).to.have.been.calledWith(sinon.match(/You have (the following|no) badges.*/)) it 'responds to "what badges does user2 have"', -> @msg.match = [0, 'user2'] @robot.respond.args[1][1](@msg) expect(@msg.reply).to.have.been.calledWith(sinon.match(/user2 has (the following|no) badges.*/)) it 'responds to "I don\'t have the founder badge"', -> @msg.match = [0, 'I', 'founder'] @robot.respond.args[2][1](@msg) badges = @data.ingressBadges.U123 expect(@msg.reply).to.have.been.calledWith('removed the :founder: badge') expect(badges).not.to.include(':founder:') describe 'handles usernames with special characters [@-.]', -> it '(user-2)', -> @msg.match = [0, 'user-2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(badges).to.be.a('array') expect(badges).to.include(':verified:') expect(@msg.send).to.have.been.calledWith('@user-2: congrats on earning the :verified: badge!') it '(user.2)', -> @msg.match = [0, 'user.2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(badges).to.be.a('array') expect(badges).to.include(':verified:') expect(@msg.send).to.have.been.calledWith('@user.2: congrats on earning the :verified: badge!') it '(@user2)', -> @msg.match = [0, '@user2', 'verified'] @robot.respond.args[0][1](@msg) badges = @data.ingressBadges.U234 expect(badges).to.be.a('array') expect(badges).to.include(':verified:') expect(@msg.send).to.have.been.calledWith('@user2: congrats on earning the :verified: badge!')
[ { "context": "it 'should capitalize a provided string', ->\n \"patrick\".capitalize().should.equal 'Patrick'\n\n it 'shoul", "end": 359, "score": 0.9444742202758789, "start": 352, "tag": "NAME", "value": "patrick" }, { "context": "ing', ->\n \"patrick\".capitalize().should.equal 'Patrick'\n\n it 'should left-pad a provided string', ->\n ", "end": 395, "score": 0.9976369142532349, "start": 388, "tag": "NAME", "value": "Patrick" }, { "context": "arguments', ->\n String.format(\"Hello, %s!\", 'Patrick').should.equal 'Hello, Patrick!'\n\n it 'should ", "end": 1002, "score": 0.9977405667304993, "start": 995, "tag": "NAME", "value": "Patrick" }, { "context": "rmat(\"Hello, %s!\", 'Patrick').should.equal 'Hello, Patrick!'\n\n it 'should provide a convenience shortcut ", "end": 1033, "score": 0.9975419640541077, "start": 1026, "tag": "NAME", "value": "Patrick" }, { "context": "ormatting strings', ->\n \"Hello, %s!\".format('Patrick').should.equal 'Hello, Patrick!'\n\n it 'should ", "end": 1145, "score": 0.9961751103401184, "start": 1138, "tag": "NAME", "value": "Patrick" }, { "context": "Hello, %s!\".format('Patrick').should.equal 'Hello, Patrick!'\n\n it 'should not format if not provided with", "end": 1176, "score": 0.9971132278442383, "start": 1169, "tag": "NAME", "value": "Patrick" }, { "context": "p['u'] = 'toUpperCase'\n \"Hello, %u!\".format('Patrick').should.equal 'Hello, PATRICK!'\n\n it 'should ", "end": 1576, "score": 0.9950108528137207, "start": 1569, "tag": "NAME", "value": "Patrick" }, { "context": "Hello, %u!\".format('Patrick').should.equal 'Hello, PATRICK!'\n\n it 'should allow replacement specifiers in", "end": 1607, "score": 0.9977691173553467, "start": 1600, "tag": "NAME", "value": "PATRICK" }, { "context": "inside brackets', ->\n \"Hello, %{s}!\".format('Patrick').should.equal 'Hello, Patrick!'\n\n it 'should ", "end": 1712, "score": 0.9949909448623657, "start": 1705, "tag": "NAME", "value": "Patrick" }, { "context": "llo, %{s}!\".format('Patrick').should.equal 'Hello, Patrick!'\n\n it 'should allow replacement specifiers in", "end": 1743, "score": 0.9972531795501709, "start": 1736, "tag": "NAME", "value": "Patrick" }, { "context": "'u'] = 'toUpperCase'\n \"Hello, %{u}!\".format('Patrick').should.equal 'Hello, PATRICK!'\n\n it 'should ", "end": 1893, "score": 0.9993133544921875, "start": 1886, "tag": "NAME", "value": "Patrick" }, { "context": "llo, %{u}!\".format('Patrick').should.equal 'Hello, PATRICK!'\n\n it 'should capitalize when replacement spe", "end": 1924, "score": 0.9994139671325684, "start": 1917, "tag": "NAME", "value": "PATRICK" }, { "context": "'toLowerCase'\n \"Hello, %{NameCase}!\".format('PATRICK').should.equal 'Hello, Patrick!'\n\n it 'should ", "end": 2114, "score": 0.9986866116523743, "start": 2107, "tag": "NAME", "value": "PATRICK" }, { "context": "NameCase}!\".format('PATRICK').should.equal 'Hello, Patrick!'\n\n it 'should escape %% as %', ->\n \"Hell", "end": 2145, "score": 0.9992189407348633, "start": 2138, "tag": "NAME", "value": "Patrick" }, { "context": "d escape %% as %', ->\n \"Hello, %%s!\".format('Patrick').should.equal 'Hello, %s!'\n\n#-------------------", "end": 2219, "score": 0.9984279870986938, "start": 2212, "tag": "NAME", "value": "Patrick" } ]
_old/node/test/js/stringTest.coffee
lagdotcom/rot.js
1,653
# stringTest.coffee #---------------------------------------------------------------------------- should = require 'should' ROT = require '../../lib/rot' describe 'string', -> it 'should extend the String prototype', -> "".should.have.properties ['capitalize', 'lpad', 'rpad', 'format'] it 'should capitalize a provided string', -> "patrick".capitalize().should.equal 'Patrick' it 'should left-pad a provided string', -> "ea".lpad('0', 4).should.equal '00ea' it 'should left-pad a provided string with spaces', -> "$1,000".lpad(' ', 10).should.equal ' $1,000' it 'should left-pad a provided number', -> "5".lpad().should.equal '05' it 'should right-pad a provided string', -> "Long Sword +1".rpad(' ', 20).should.equal 'Long Sword +1 ' it 'should right-pad a provided number', -> "5".rpad().should.equal '50' describe 'format', -> it 'should format strings with provided arguments', -> String.format("Hello, %s!", 'Patrick').should.equal 'Hello, Patrick!' it 'should provide a convenience shortcut for formatting strings', -> "Hello, %s!".format('Patrick').should.equal 'Hello, Patrick!' it 'should not format if not provided with arguments', -> 'Hello, %s!'.format().should.equal 'Hello, %s!' it 'should not format if an unknown replacement is specified', -> 'Gallons of Fuel: %d'.format(20).should.equal 'Gallons of Fuel: %d' it 'should allow a custom replacement mapping', -> String.format.map['u'] = 'toUpperCase' "Hello, %u!".format('Patrick').should.equal 'Hello, PATRICK!' it 'should allow replacement specifiers inside brackets', -> "Hello, %{s}!".format('Patrick').should.equal 'Hello, Patrick!' it 'should allow replacement specifiers inside brackets', -> String.format.map['u'] = 'toUpperCase' "Hello, %{u}!".format('Patrick').should.equal 'Hello, PATRICK!' it 'should capitalize when replacement specifiers inside brackets are capitalized', -> String.format.map['namecase'] = 'toLowerCase' "Hello, %{NameCase}!".format('PATRICK').should.equal 'Hello, Patrick!' it 'should escape %% as %', -> "Hello, %%s!".format('Patrick').should.equal 'Hello, %s!' #---------------------------------------------------------------------------- # end of stringTest.coffee
57781
# stringTest.coffee #---------------------------------------------------------------------------- should = require 'should' ROT = require '../../lib/rot' describe 'string', -> it 'should extend the String prototype', -> "".should.have.properties ['capitalize', 'lpad', 'rpad', 'format'] it 'should capitalize a provided string', -> "<NAME>".capitalize().should.equal '<NAME>' it 'should left-pad a provided string', -> "ea".lpad('0', 4).should.equal '00ea' it 'should left-pad a provided string with spaces', -> "$1,000".lpad(' ', 10).should.equal ' $1,000' it 'should left-pad a provided number', -> "5".lpad().should.equal '05' it 'should right-pad a provided string', -> "Long Sword +1".rpad(' ', 20).should.equal 'Long Sword +1 ' it 'should right-pad a provided number', -> "5".rpad().should.equal '50' describe 'format', -> it 'should format strings with provided arguments', -> String.format("Hello, %s!", '<NAME>').should.equal 'Hello, <NAME>!' it 'should provide a convenience shortcut for formatting strings', -> "Hello, %s!".format('<NAME>').should.equal 'Hello, <NAME>!' it 'should not format if not provided with arguments', -> 'Hello, %s!'.format().should.equal 'Hello, %s!' it 'should not format if an unknown replacement is specified', -> 'Gallons of Fuel: %d'.format(20).should.equal 'Gallons of Fuel: %d' it 'should allow a custom replacement mapping', -> String.format.map['u'] = 'toUpperCase' "Hello, %u!".format('<NAME>').should.equal 'Hello, <NAME>!' it 'should allow replacement specifiers inside brackets', -> "Hello, %{s}!".format('<NAME>').should.equal 'Hello, <NAME>!' it 'should allow replacement specifiers inside brackets', -> String.format.map['u'] = 'toUpperCase' "Hello, %{u}!".format('<NAME>').should.equal 'Hello, <NAME>!' it 'should capitalize when replacement specifiers inside brackets are capitalized', -> String.format.map['namecase'] = 'toLowerCase' "Hello, %{NameCase}!".format('<NAME>').should.equal 'Hello, <NAME>!' it 'should escape %% as %', -> "Hello, %%s!".format('<NAME>').should.equal 'Hello, %s!' #---------------------------------------------------------------------------- # end of stringTest.coffee
true
# stringTest.coffee #---------------------------------------------------------------------------- should = require 'should' ROT = require '../../lib/rot' describe 'string', -> it 'should extend the String prototype', -> "".should.have.properties ['capitalize', 'lpad', 'rpad', 'format'] it 'should capitalize a provided string', -> "PI:NAME:<NAME>END_PI".capitalize().should.equal 'PI:NAME:<NAME>END_PI' it 'should left-pad a provided string', -> "ea".lpad('0', 4).should.equal '00ea' it 'should left-pad a provided string with spaces', -> "$1,000".lpad(' ', 10).should.equal ' $1,000' it 'should left-pad a provided number', -> "5".lpad().should.equal '05' it 'should right-pad a provided string', -> "Long Sword +1".rpad(' ', 20).should.equal 'Long Sword +1 ' it 'should right-pad a provided number', -> "5".rpad().should.equal '50' describe 'format', -> it 'should format strings with provided arguments', -> String.format("Hello, %s!", 'PI:NAME:<NAME>END_PI').should.equal 'Hello, PI:NAME:<NAME>END_PI!' it 'should provide a convenience shortcut for formatting strings', -> "Hello, %s!".format('PI:NAME:<NAME>END_PI').should.equal 'Hello, PI:NAME:<NAME>END_PI!' it 'should not format if not provided with arguments', -> 'Hello, %s!'.format().should.equal 'Hello, %s!' it 'should not format if an unknown replacement is specified', -> 'Gallons of Fuel: %d'.format(20).should.equal 'Gallons of Fuel: %d' it 'should allow a custom replacement mapping', -> String.format.map['u'] = 'toUpperCase' "Hello, %u!".format('PI:NAME:<NAME>END_PI').should.equal 'Hello, PI:NAME:<NAME>END_PI!' it 'should allow replacement specifiers inside brackets', -> "Hello, %{s}!".format('PI:NAME:<NAME>END_PI').should.equal 'Hello, PI:NAME:<NAME>END_PI!' it 'should allow replacement specifiers inside brackets', -> String.format.map['u'] = 'toUpperCase' "Hello, %{u}!".format('PI:NAME:<NAME>END_PI').should.equal 'Hello, PI:NAME:<NAME>END_PI!' it 'should capitalize when replacement specifiers inside brackets are capitalized', -> String.format.map['namecase'] = 'toLowerCase' "Hello, %{NameCase}!".format('PI:NAME:<NAME>END_PI').should.equal 'Hello, PI:NAME:<NAME>END_PI!' it 'should escape %% as %', -> "Hello, %%s!".format('PI:NAME:<NAME>END_PI').should.equal 'Hello, %s!' #---------------------------------------------------------------------------- # end of stringTest.coffee
[ { "context": "'t\n # change the method name during refactoring - Sinan 10 May 2012\n selectItem:(item, event = {})->\n\n ", "end": 6864, "score": 0.9481362104415894, "start": 6859, "tag": "NAME", "value": "Sinan" }, { "context": "o not CHANGE\n # or ask one of those two, namely Gokmen or Sinan\n @deselectAllItems() if not multiple", "end": 7217, "score": 0.8899502754211426, "start": 7211, "tag": "NAME", "value": "Gokmen" }, { "context": "GE\n # or ask one of those two, namely Gokmen or Sinan\n @deselectAllItems() if not multipleSelection", "end": 7226, "score": 0.9231206178665161, "start": 7221, "tag": "NAME", "value": "Sinan" } ]
src/components/list/listviewcontroller.coffee
burakcan/kd
0
KDView = require './../../core/view.coffee' KDScrollView = require './../../core/scrollview.coffee' KDViewController = require './../../core/viewcontroller.coffee' KDListView = require './../list/listview.coffee' KDLoaderView = require './../loader/loaderview.coffee' module.exports = class KDListViewController extends KDViewController constructor:(options = {}, data)-> options.wrapper ?= yes options.scrollView ?= yes options.keyNav ?= no options.multipleSelection ?= no options.selection ?= yes options.startWithLazyLoader ?= no options.itemChildClass or= null options.itemChildOptions or= {} # rename these options options.noItemFoundWidget or= null options.noMoreItemFoundWidget or= null @itemsOrdered = [] unless @itemsOrdered # CtF: this must be fixed: duplicate itemsOrdered and KDListView.items # Object.defineProperty this, "itemsOrdered", get : => @getListView().items @itemsIndexed = {} @selectedItems = [] @lazyLoader = null if options.view @setListView listView = options.view else viewOptions = options.viewOptions or {} viewOptions.lastToFirst or= options.lastToFirst viewOptions.itemClass or= options.itemClass viewOptions.itemOptions or= options.itemOptions viewOptions.itemChildClass or= options.itemChildClass viewOptions.itemChildOptions or= options.itemChildOptions @setListView listView = new KDListView viewOptions if options.scrollView @scrollView = new KDScrollView lazyLoadThreshold : options.lazyLoadThreshold ownScrollBars : options.ownScrollBars options.view = if options.wrapper then new KDView cssClass : "listview-wrapper" else listView super options, data {noItemFoundWidget} = @getOptions() listView.on 'ItemWasAdded', (view, index)=> @registerItem view, index @hideNoItemWidget() if noItemFoundWidget listView.on 'ItemIsBeingDestroyed', (itemInfo)=> @unregisterItem itemInfo @showNoItemWidget() if noItemFoundWidget if options.keyNav listView.on 'KeyDownOnList', (event)=> @keyDownPerformed listView, event loadView:(mainView)-> options = @getOptions() if options.scrollView mainView.addSubView @scrollView @scrollView.addSubView @getListView() if options.startWithLazyLoader @showLazyLoader no @scrollView.on 'LazyLoadThresholdReached', @bound "showLazyLoader" if options.noItemFoundWidget @putNoItemView() @instantiateListItems(@getData()?.items or []) KD.getSingleton("windowController").on "ReceivedMouseUpElsewhere", (event)=> @mouseUpHappened event instantiateListItems:(items)-> newItems = for itemData in items @getListView().addItem itemData @emit "AllItemsAddedToList" return newItems ### HELPERS ### itemForId:(id)-> @itemsIndexed[id] getItemsOrdered:-> @itemsOrdered getItemCount:-> @itemsOrdered.length setListView:(listView)-> @listView = listView getListView:-> @listView forEachItemByIndex:(ids, callback)-> [callback, ids] = [ids, callback] unless callback ids = [ids] unless Array.isArray ids ids.forEach (id)=> item = @itemsIndexed[id] callback item if item? putNoItemView:-> {noItemFoundWidget} = @getOptions() @getListView().addSubView @noItemView = noItemFoundWidget showNoItemWidget:-> @noItemView?.show() if @itemsOrdered.length is 0 hideNoItemWidget:-> @noItemView?.hide() # regressed, will put back whenever i'm here again. - SY showNoMoreItemWidget:-> {noMoreItemFoundWidget} = @getOptions() @scrollView.addSubView noMoreItemFoundWidget if noMoreItemFoundWidget ### ITEM OPERATIONS ### addItem:(itemData, index, animation)-> @getListView().addItem itemData, index, animation removeItem:(itemInstance, itemData, index)-> @getListView().removeItem itemInstance, itemData, index registerItem:(view, index)-> options = @getOptions() if index? actualIndex = if @getOptions().lastToFirst then @getListView().items.length - index - 1 else index @itemsOrdered.splice(actualIndex, 0, view) else @itemsOrdered[if @getOptions().lastToFirst then 'unshift' else 'push'] view if view.getData()? @itemsIndexed[view.getItemDataId()] = view if options.selection view.on 'click', (event)=> @selectItem view, event if options.keyNav or options.multipleSelection view.on "mousedown", (event)=> @mouseDownHappenedOnItem view, event view.on "mouseenter", (event)=> @mouseEnterHappenedOnItem view, event unregisterItem:(itemInfo)-> @emit "UnregisteringItem", itemInfo {index, view} = itemInfo actualIndex = if @getOptions().lastToFirst then @getListView().items.length - index - 1 else index @itemsOrdered.splice actualIndex, 1 if view.getData()? delete @itemsIndexed[view.getItemDataId()] replaceAllItems:(items)-> @removeAllItems() @instantiateListItems items removeAllItems:-> {itemsOrdered} = @ @itemsOrdered.length = 0 @itemsIndexed = {} listView = @getListView() listView.empty() if listView.items.length return itemsOrdered moveItemToIndex:(item, newIndex)-> newIndex = Math.max(0, Math.min(@itemsOrdered.length-1, newIndex)) @itemsOrdered = @getListView().moveItemToIndex(item, newIndex).slice() ### HANDLING MOUSE EVENTS ### mouseDownHappenedOnItem:(item, event)-> KD.getSingleton("windowController").setKeyView @getListView() if @getOptions().keyNav @lastEvent = event unless item in @selectedItems @mouseDown = yes @mouseDownTempItem = item @mouseDownTimer = setTimeout => @mouseDown = no @mouseDownTempItem = null @selectItem item, event , 300 else @mouseDown = no @mouseDownTempItem = null mouseUpHappened:(event)-> clearTimeout @mouseDownTimer @mouseDown = no @mouseDownTempItem = null mouseEnterHappenedOnItem:(item, event)-> clearTimeout @mouseDownTimer if @mouseDown @deselectAllItems() unless event.metaKey or event.ctrlKey or event.shiftKey @selectItemsByRange @mouseDownTempItem,item else @emit "MouseEnterHappenedOnItem", item ### HANDLING KEY EVENTS ### keyDownPerformed:(mainView, event)-> switch event.which when 40, 38 @selectItemBelowOrAbove event @emit "KeyDownOnListHandled", @selectedItems ### ITEM SELECTION ### # bad naming because of backwards compatibility i didn't # change the method name during refactoring - Sinan 10 May 2012 selectItem:(item, event = {})-> return unless item? @lastEvent = event {selectable} = item.getOptions() {multipleSelection} = @getOptions() {metaKey, ctrlKey, shiftKey} = event # we lost two developers on these two lines below do not CHANGE # or ask one of those two, namely Gokmen or Sinan @deselectAllItems() if not multipleSelection @deselectAllItems() if selectable and not(metaKey or ctrlKey or shiftKey) if event.shiftKey and @selectedItems.length > 0 @selectItemsByRange @selectedItems[0], item else unless item in @selectedItems @selectSingleItem item else @deselectSingleItem item return @selectedItems selectItemBelowOrAbove:(event)-> direction = if event.which is 40 then "down" else "up" addend = if event.which is 40 then 1 else -1 selectedIndex = @itemsOrdered.indexOf @selectedItems[0] lastSelectedIndex = @itemsOrdered.indexOf @selectedItems[@selectedItems.length - 1] if @itemsOrdered[selectedIndex + addend] unless event.metaKey or event.ctrlKey or event.shiftKey # navigate normally if meta key is NOT pressed @selectItem @itemsOrdered[selectedIndex + addend] else # take extra actions if meta key is pressed if @selectedItems.indexOf(@itemsOrdered[lastSelectedIndex + addend]) isnt -1 # to be deselected item is in @selectedItems if @itemsOrdered[lastSelectedIndex] @deselectSingleItem @itemsOrdered[lastSelectedIndex] else # to be deselected item is NOT in @selectedItems if @itemsOrdered[lastSelectedIndex + addend ] @selectSingleItem @itemsOrdered[lastSelectedIndex + addend ] selectNextItem:(item, event)-> [item] = @selectedItems unless item selectedIndex = @itemsOrdered.indexOf item @selectItem @itemsOrdered[selectedIndex + 1] selectPrevItem:(item, event)-> [item] = @selectedItems unless item selectedIndex = @itemsOrdered.indexOf item @selectItem @itemsOrdered[selectedIndex + -1] deselectAllItems:-> for selectedItem in @selectedItems selectedItem.removeHighlight() deselectedItems = @selectedItems.concat [] @selectedItems = [] @getListView().unsetClass "last-item-selected" @itemDeselectionPerformed deselectedItems deselectSingleItem:(item)-> item.removeHighlight() @selectedItems.splice @selectedItems.indexOf(item), 1 if item is @itemsOrdered[@itemsOrdered.length-1] @getListView().unsetClass "last-item-selected" @itemDeselectionPerformed [item] selectSingleItem:(item)-> if item.getOption("selectable") and !(item in @selectedItems) item.highlight() @selectedItems.push item if item is @itemsOrdered[@itemsOrdered.length-1] @getListView().setClass "last-item-selected" @itemSelectionPerformed() selectAllItems:-> @selectSingleItem item for item in @itemsOrdered selectItemsByRange:(item1, item2)-> indicesToBeSliced = [@itemsOrdered.indexOf(item1), @itemsOrdered.indexOf(item2)] indicesToBeSliced.sort (a, b)-> a - b itemsToBeSelected = @itemsOrdered.slice indicesToBeSliced[0], indicesToBeSliced[1] + 1 @selectSingleItem item for item in itemsToBeSelected @itemSelectionPerformed() itemSelectionPerformed:-> @emit "ItemSelectionPerformed", @, (event : @lastEvent, items : @selectedItems) itemDeselectionPerformed:(deselectedItems)-> @emit "ItemDeselectionPerformed", @, (event : @lastEvent, items : deselectedItems) ### LAZY LOADER ### showLazyLoader:(emitWhenReached = yes)-> @hideNoItemWidget() if @noItemView and @getOptions().noItemFoundWidget unless @lazyLoader {lazyLoaderOptions} = @getOptions() lazyLoaderOptions or= {} lazyLoaderOptions.itemClass or= KDCustomHTMLView lazyLoaderOptions.partial ?= '' lazyLoaderOptions.cssClass = KD.utils.curry 'lazy-loader', lazyLoaderOptions.cssClass lazyLoaderOptions.spinnerOptions or= size : width : 32 {itemClass, spinnerOptions} = lazyLoaderOptions delete lazyLoaderOptions.itemClass wrapper = @scrollView or @getView() wrapper.addSubView @lazyLoader = new itemClass lazyLoaderOptions @lazyLoader.addSubView @lazyLoader.spinner = new KDLoaderView spinnerOptions @lazyLoader.spinner.show() @emit 'LazyLoadThresholdReached' if emitWhenReached KD.utils.defer => @scrollView?.stopScrolling = yes hideLazyLoader:-> KD.utils.wait 300, => @scrollView?.stopScrolling = no @showNoItemWidget() if @noItemView and @getOptions().noItemFoundWidget if @lazyLoader @lazyLoader.spinner.hide() @lazyLoader.destroy() @lazyLoader = null
10952
KDView = require './../../core/view.coffee' KDScrollView = require './../../core/scrollview.coffee' KDViewController = require './../../core/viewcontroller.coffee' KDListView = require './../list/listview.coffee' KDLoaderView = require './../loader/loaderview.coffee' module.exports = class KDListViewController extends KDViewController constructor:(options = {}, data)-> options.wrapper ?= yes options.scrollView ?= yes options.keyNav ?= no options.multipleSelection ?= no options.selection ?= yes options.startWithLazyLoader ?= no options.itemChildClass or= null options.itemChildOptions or= {} # rename these options options.noItemFoundWidget or= null options.noMoreItemFoundWidget or= null @itemsOrdered = [] unless @itemsOrdered # CtF: this must be fixed: duplicate itemsOrdered and KDListView.items # Object.defineProperty this, "itemsOrdered", get : => @getListView().items @itemsIndexed = {} @selectedItems = [] @lazyLoader = null if options.view @setListView listView = options.view else viewOptions = options.viewOptions or {} viewOptions.lastToFirst or= options.lastToFirst viewOptions.itemClass or= options.itemClass viewOptions.itemOptions or= options.itemOptions viewOptions.itemChildClass or= options.itemChildClass viewOptions.itemChildOptions or= options.itemChildOptions @setListView listView = new KDListView viewOptions if options.scrollView @scrollView = new KDScrollView lazyLoadThreshold : options.lazyLoadThreshold ownScrollBars : options.ownScrollBars options.view = if options.wrapper then new KDView cssClass : "listview-wrapper" else listView super options, data {noItemFoundWidget} = @getOptions() listView.on 'ItemWasAdded', (view, index)=> @registerItem view, index @hideNoItemWidget() if noItemFoundWidget listView.on 'ItemIsBeingDestroyed', (itemInfo)=> @unregisterItem itemInfo @showNoItemWidget() if noItemFoundWidget if options.keyNav listView.on 'KeyDownOnList', (event)=> @keyDownPerformed listView, event loadView:(mainView)-> options = @getOptions() if options.scrollView mainView.addSubView @scrollView @scrollView.addSubView @getListView() if options.startWithLazyLoader @showLazyLoader no @scrollView.on 'LazyLoadThresholdReached', @bound "showLazyLoader" if options.noItemFoundWidget @putNoItemView() @instantiateListItems(@getData()?.items or []) KD.getSingleton("windowController").on "ReceivedMouseUpElsewhere", (event)=> @mouseUpHappened event instantiateListItems:(items)-> newItems = for itemData in items @getListView().addItem itemData @emit "AllItemsAddedToList" return newItems ### HELPERS ### itemForId:(id)-> @itemsIndexed[id] getItemsOrdered:-> @itemsOrdered getItemCount:-> @itemsOrdered.length setListView:(listView)-> @listView = listView getListView:-> @listView forEachItemByIndex:(ids, callback)-> [callback, ids] = [ids, callback] unless callback ids = [ids] unless Array.isArray ids ids.forEach (id)=> item = @itemsIndexed[id] callback item if item? putNoItemView:-> {noItemFoundWidget} = @getOptions() @getListView().addSubView @noItemView = noItemFoundWidget showNoItemWidget:-> @noItemView?.show() if @itemsOrdered.length is 0 hideNoItemWidget:-> @noItemView?.hide() # regressed, will put back whenever i'm here again. - SY showNoMoreItemWidget:-> {noMoreItemFoundWidget} = @getOptions() @scrollView.addSubView noMoreItemFoundWidget if noMoreItemFoundWidget ### ITEM OPERATIONS ### addItem:(itemData, index, animation)-> @getListView().addItem itemData, index, animation removeItem:(itemInstance, itemData, index)-> @getListView().removeItem itemInstance, itemData, index registerItem:(view, index)-> options = @getOptions() if index? actualIndex = if @getOptions().lastToFirst then @getListView().items.length - index - 1 else index @itemsOrdered.splice(actualIndex, 0, view) else @itemsOrdered[if @getOptions().lastToFirst then 'unshift' else 'push'] view if view.getData()? @itemsIndexed[view.getItemDataId()] = view if options.selection view.on 'click', (event)=> @selectItem view, event if options.keyNav or options.multipleSelection view.on "mousedown", (event)=> @mouseDownHappenedOnItem view, event view.on "mouseenter", (event)=> @mouseEnterHappenedOnItem view, event unregisterItem:(itemInfo)-> @emit "UnregisteringItem", itemInfo {index, view} = itemInfo actualIndex = if @getOptions().lastToFirst then @getListView().items.length - index - 1 else index @itemsOrdered.splice actualIndex, 1 if view.getData()? delete @itemsIndexed[view.getItemDataId()] replaceAllItems:(items)-> @removeAllItems() @instantiateListItems items removeAllItems:-> {itemsOrdered} = @ @itemsOrdered.length = 0 @itemsIndexed = {} listView = @getListView() listView.empty() if listView.items.length return itemsOrdered moveItemToIndex:(item, newIndex)-> newIndex = Math.max(0, Math.min(@itemsOrdered.length-1, newIndex)) @itemsOrdered = @getListView().moveItemToIndex(item, newIndex).slice() ### HANDLING MOUSE EVENTS ### mouseDownHappenedOnItem:(item, event)-> KD.getSingleton("windowController").setKeyView @getListView() if @getOptions().keyNav @lastEvent = event unless item in @selectedItems @mouseDown = yes @mouseDownTempItem = item @mouseDownTimer = setTimeout => @mouseDown = no @mouseDownTempItem = null @selectItem item, event , 300 else @mouseDown = no @mouseDownTempItem = null mouseUpHappened:(event)-> clearTimeout @mouseDownTimer @mouseDown = no @mouseDownTempItem = null mouseEnterHappenedOnItem:(item, event)-> clearTimeout @mouseDownTimer if @mouseDown @deselectAllItems() unless event.metaKey or event.ctrlKey or event.shiftKey @selectItemsByRange @mouseDownTempItem,item else @emit "MouseEnterHappenedOnItem", item ### HANDLING KEY EVENTS ### keyDownPerformed:(mainView, event)-> switch event.which when 40, 38 @selectItemBelowOrAbove event @emit "KeyDownOnListHandled", @selectedItems ### ITEM SELECTION ### # bad naming because of backwards compatibility i didn't # change the method name during refactoring - <NAME> 10 May 2012 selectItem:(item, event = {})-> return unless item? @lastEvent = event {selectable} = item.getOptions() {multipleSelection} = @getOptions() {metaKey, ctrlKey, shiftKey} = event # we lost two developers on these two lines below do not CHANGE # or ask one of those two, namely <NAME> or <NAME> @deselectAllItems() if not multipleSelection @deselectAllItems() if selectable and not(metaKey or ctrlKey or shiftKey) if event.shiftKey and @selectedItems.length > 0 @selectItemsByRange @selectedItems[0], item else unless item in @selectedItems @selectSingleItem item else @deselectSingleItem item return @selectedItems selectItemBelowOrAbove:(event)-> direction = if event.which is 40 then "down" else "up" addend = if event.which is 40 then 1 else -1 selectedIndex = @itemsOrdered.indexOf @selectedItems[0] lastSelectedIndex = @itemsOrdered.indexOf @selectedItems[@selectedItems.length - 1] if @itemsOrdered[selectedIndex + addend] unless event.metaKey or event.ctrlKey or event.shiftKey # navigate normally if meta key is NOT pressed @selectItem @itemsOrdered[selectedIndex + addend] else # take extra actions if meta key is pressed if @selectedItems.indexOf(@itemsOrdered[lastSelectedIndex + addend]) isnt -1 # to be deselected item is in @selectedItems if @itemsOrdered[lastSelectedIndex] @deselectSingleItem @itemsOrdered[lastSelectedIndex] else # to be deselected item is NOT in @selectedItems if @itemsOrdered[lastSelectedIndex + addend ] @selectSingleItem @itemsOrdered[lastSelectedIndex + addend ] selectNextItem:(item, event)-> [item] = @selectedItems unless item selectedIndex = @itemsOrdered.indexOf item @selectItem @itemsOrdered[selectedIndex + 1] selectPrevItem:(item, event)-> [item] = @selectedItems unless item selectedIndex = @itemsOrdered.indexOf item @selectItem @itemsOrdered[selectedIndex + -1] deselectAllItems:-> for selectedItem in @selectedItems selectedItem.removeHighlight() deselectedItems = @selectedItems.concat [] @selectedItems = [] @getListView().unsetClass "last-item-selected" @itemDeselectionPerformed deselectedItems deselectSingleItem:(item)-> item.removeHighlight() @selectedItems.splice @selectedItems.indexOf(item), 1 if item is @itemsOrdered[@itemsOrdered.length-1] @getListView().unsetClass "last-item-selected" @itemDeselectionPerformed [item] selectSingleItem:(item)-> if item.getOption("selectable") and !(item in @selectedItems) item.highlight() @selectedItems.push item if item is @itemsOrdered[@itemsOrdered.length-1] @getListView().setClass "last-item-selected" @itemSelectionPerformed() selectAllItems:-> @selectSingleItem item for item in @itemsOrdered selectItemsByRange:(item1, item2)-> indicesToBeSliced = [@itemsOrdered.indexOf(item1), @itemsOrdered.indexOf(item2)] indicesToBeSliced.sort (a, b)-> a - b itemsToBeSelected = @itemsOrdered.slice indicesToBeSliced[0], indicesToBeSliced[1] + 1 @selectSingleItem item for item in itemsToBeSelected @itemSelectionPerformed() itemSelectionPerformed:-> @emit "ItemSelectionPerformed", @, (event : @lastEvent, items : @selectedItems) itemDeselectionPerformed:(deselectedItems)-> @emit "ItemDeselectionPerformed", @, (event : @lastEvent, items : deselectedItems) ### LAZY LOADER ### showLazyLoader:(emitWhenReached = yes)-> @hideNoItemWidget() if @noItemView and @getOptions().noItemFoundWidget unless @lazyLoader {lazyLoaderOptions} = @getOptions() lazyLoaderOptions or= {} lazyLoaderOptions.itemClass or= KDCustomHTMLView lazyLoaderOptions.partial ?= '' lazyLoaderOptions.cssClass = KD.utils.curry 'lazy-loader', lazyLoaderOptions.cssClass lazyLoaderOptions.spinnerOptions or= size : width : 32 {itemClass, spinnerOptions} = lazyLoaderOptions delete lazyLoaderOptions.itemClass wrapper = @scrollView or @getView() wrapper.addSubView @lazyLoader = new itemClass lazyLoaderOptions @lazyLoader.addSubView @lazyLoader.spinner = new KDLoaderView spinnerOptions @lazyLoader.spinner.show() @emit 'LazyLoadThresholdReached' if emitWhenReached KD.utils.defer => @scrollView?.stopScrolling = yes hideLazyLoader:-> KD.utils.wait 300, => @scrollView?.stopScrolling = no @showNoItemWidget() if @noItemView and @getOptions().noItemFoundWidget if @lazyLoader @lazyLoader.spinner.hide() @lazyLoader.destroy() @lazyLoader = null
true
KDView = require './../../core/view.coffee' KDScrollView = require './../../core/scrollview.coffee' KDViewController = require './../../core/viewcontroller.coffee' KDListView = require './../list/listview.coffee' KDLoaderView = require './../loader/loaderview.coffee' module.exports = class KDListViewController extends KDViewController constructor:(options = {}, data)-> options.wrapper ?= yes options.scrollView ?= yes options.keyNav ?= no options.multipleSelection ?= no options.selection ?= yes options.startWithLazyLoader ?= no options.itemChildClass or= null options.itemChildOptions or= {} # rename these options options.noItemFoundWidget or= null options.noMoreItemFoundWidget or= null @itemsOrdered = [] unless @itemsOrdered # CtF: this must be fixed: duplicate itemsOrdered and KDListView.items # Object.defineProperty this, "itemsOrdered", get : => @getListView().items @itemsIndexed = {} @selectedItems = [] @lazyLoader = null if options.view @setListView listView = options.view else viewOptions = options.viewOptions or {} viewOptions.lastToFirst or= options.lastToFirst viewOptions.itemClass or= options.itemClass viewOptions.itemOptions or= options.itemOptions viewOptions.itemChildClass or= options.itemChildClass viewOptions.itemChildOptions or= options.itemChildOptions @setListView listView = new KDListView viewOptions if options.scrollView @scrollView = new KDScrollView lazyLoadThreshold : options.lazyLoadThreshold ownScrollBars : options.ownScrollBars options.view = if options.wrapper then new KDView cssClass : "listview-wrapper" else listView super options, data {noItemFoundWidget} = @getOptions() listView.on 'ItemWasAdded', (view, index)=> @registerItem view, index @hideNoItemWidget() if noItemFoundWidget listView.on 'ItemIsBeingDestroyed', (itemInfo)=> @unregisterItem itemInfo @showNoItemWidget() if noItemFoundWidget if options.keyNav listView.on 'KeyDownOnList', (event)=> @keyDownPerformed listView, event loadView:(mainView)-> options = @getOptions() if options.scrollView mainView.addSubView @scrollView @scrollView.addSubView @getListView() if options.startWithLazyLoader @showLazyLoader no @scrollView.on 'LazyLoadThresholdReached', @bound "showLazyLoader" if options.noItemFoundWidget @putNoItemView() @instantiateListItems(@getData()?.items or []) KD.getSingleton("windowController").on "ReceivedMouseUpElsewhere", (event)=> @mouseUpHappened event instantiateListItems:(items)-> newItems = for itemData in items @getListView().addItem itemData @emit "AllItemsAddedToList" return newItems ### HELPERS ### itemForId:(id)-> @itemsIndexed[id] getItemsOrdered:-> @itemsOrdered getItemCount:-> @itemsOrdered.length setListView:(listView)-> @listView = listView getListView:-> @listView forEachItemByIndex:(ids, callback)-> [callback, ids] = [ids, callback] unless callback ids = [ids] unless Array.isArray ids ids.forEach (id)=> item = @itemsIndexed[id] callback item if item? putNoItemView:-> {noItemFoundWidget} = @getOptions() @getListView().addSubView @noItemView = noItemFoundWidget showNoItemWidget:-> @noItemView?.show() if @itemsOrdered.length is 0 hideNoItemWidget:-> @noItemView?.hide() # regressed, will put back whenever i'm here again. - SY showNoMoreItemWidget:-> {noMoreItemFoundWidget} = @getOptions() @scrollView.addSubView noMoreItemFoundWidget if noMoreItemFoundWidget ### ITEM OPERATIONS ### addItem:(itemData, index, animation)-> @getListView().addItem itemData, index, animation removeItem:(itemInstance, itemData, index)-> @getListView().removeItem itemInstance, itemData, index registerItem:(view, index)-> options = @getOptions() if index? actualIndex = if @getOptions().lastToFirst then @getListView().items.length - index - 1 else index @itemsOrdered.splice(actualIndex, 0, view) else @itemsOrdered[if @getOptions().lastToFirst then 'unshift' else 'push'] view if view.getData()? @itemsIndexed[view.getItemDataId()] = view if options.selection view.on 'click', (event)=> @selectItem view, event if options.keyNav or options.multipleSelection view.on "mousedown", (event)=> @mouseDownHappenedOnItem view, event view.on "mouseenter", (event)=> @mouseEnterHappenedOnItem view, event unregisterItem:(itemInfo)-> @emit "UnregisteringItem", itemInfo {index, view} = itemInfo actualIndex = if @getOptions().lastToFirst then @getListView().items.length - index - 1 else index @itemsOrdered.splice actualIndex, 1 if view.getData()? delete @itemsIndexed[view.getItemDataId()] replaceAllItems:(items)-> @removeAllItems() @instantiateListItems items removeAllItems:-> {itemsOrdered} = @ @itemsOrdered.length = 0 @itemsIndexed = {} listView = @getListView() listView.empty() if listView.items.length return itemsOrdered moveItemToIndex:(item, newIndex)-> newIndex = Math.max(0, Math.min(@itemsOrdered.length-1, newIndex)) @itemsOrdered = @getListView().moveItemToIndex(item, newIndex).slice() ### HANDLING MOUSE EVENTS ### mouseDownHappenedOnItem:(item, event)-> KD.getSingleton("windowController").setKeyView @getListView() if @getOptions().keyNav @lastEvent = event unless item in @selectedItems @mouseDown = yes @mouseDownTempItem = item @mouseDownTimer = setTimeout => @mouseDown = no @mouseDownTempItem = null @selectItem item, event , 300 else @mouseDown = no @mouseDownTempItem = null mouseUpHappened:(event)-> clearTimeout @mouseDownTimer @mouseDown = no @mouseDownTempItem = null mouseEnterHappenedOnItem:(item, event)-> clearTimeout @mouseDownTimer if @mouseDown @deselectAllItems() unless event.metaKey or event.ctrlKey or event.shiftKey @selectItemsByRange @mouseDownTempItem,item else @emit "MouseEnterHappenedOnItem", item ### HANDLING KEY EVENTS ### keyDownPerformed:(mainView, event)-> switch event.which when 40, 38 @selectItemBelowOrAbove event @emit "KeyDownOnListHandled", @selectedItems ### ITEM SELECTION ### # bad naming because of backwards compatibility i didn't # change the method name during refactoring - PI:NAME:<NAME>END_PI 10 May 2012 selectItem:(item, event = {})-> return unless item? @lastEvent = event {selectable} = item.getOptions() {multipleSelection} = @getOptions() {metaKey, ctrlKey, shiftKey} = event # we lost two developers on these two lines below do not CHANGE # or ask one of those two, namely PI:NAME:<NAME>END_PI or PI:NAME:<NAME>END_PI @deselectAllItems() if not multipleSelection @deselectAllItems() if selectable and not(metaKey or ctrlKey or shiftKey) if event.shiftKey and @selectedItems.length > 0 @selectItemsByRange @selectedItems[0], item else unless item in @selectedItems @selectSingleItem item else @deselectSingleItem item return @selectedItems selectItemBelowOrAbove:(event)-> direction = if event.which is 40 then "down" else "up" addend = if event.which is 40 then 1 else -1 selectedIndex = @itemsOrdered.indexOf @selectedItems[0] lastSelectedIndex = @itemsOrdered.indexOf @selectedItems[@selectedItems.length - 1] if @itemsOrdered[selectedIndex + addend] unless event.metaKey or event.ctrlKey or event.shiftKey # navigate normally if meta key is NOT pressed @selectItem @itemsOrdered[selectedIndex + addend] else # take extra actions if meta key is pressed if @selectedItems.indexOf(@itemsOrdered[lastSelectedIndex + addend]) isnt -1 # to be deselected item is in @selectedItems if @itemsOrdered[lastSelectedIndex] @deselectSingleItem @itemsOrdered[lastSelectedIndex] else # to be deselected item is NOT in @selectedItems if @itemsOrdered[lastSelectedIndex + addend ] @selectSingleItem @itemsOrdered[lastSelectedIndex + addend ] selectNextItem:(item, event)-> [item] = @selectedItems unless item selectedIndex = @itemsOrdered.indexOf item @selectItem @itemsOrdered[selectedIndex + 1] selectPrevItem:(item, event)-> [item] = @selectedItems unless item selectedIndex = @itemsOrdered.indexOf item @selectItem @itemsOrdered[selectedIndex + -1] deselectAllItems:-> for selectedItem in @selectedItems selectedItem.removeHighlight() deselectedItems = @selectedItems.concat [] @selectedItems = [] @getListView().unsetClass "last-item-selected" @itemDeselectionPerformed deselectedItems deselectSingleItem:(item)-> item.removeHighlight() @selectedItems.splice @selectedItems.indexOf(item), 1 if item is @itemsOrdered[@itemsOrdered.length-1] @getListView().unsetClass "last-item-selected" @itemDeselectionPerformed [item] selectSingleItem:(item)-> if item.getOption("selectable") and !(item in @selectedItems) item.highlight() @selectedItems.push item if item is @itemsOrdered[@itemsOrdered.length-1] @getListView().setClass "last-item-selected" @itemSelectionPerformed() selectAllItems:-> @selectSingleItem item for item in @itemsOrdered selectItemsByRange:(item1, item2)-> indicesToBeSliced = [@itemsOrdered.indexOf(item1), @itemsOrdered.indexOf(item2)] indicesToBeSliced.sort (a, b)-> a - b itemsToBeSelected = @itemsOrdered.slice indicesToBeSliced[0], indicesToBeSliced[1] + 1 @selectSingleItem item for item in itemsToBeSelected @itemSelectionPerformed() itemSelectionPerformed:-> @emit "ItemSelectionPerformed", @, (event : @lastEvent, items : @selectedItems) itemDeselectionPerformed:(deselectedItems)-> @emit "ItemDeselectionPerformed", @, (event : @lastEvent, items : deselectedItems) ### LAZY LOADER ### showLazyLoader:(emitWhenReached = yes)-> @hideNoItemWidget() if @noItemView and @getOptions().noItemFoundWidget unless @lazyLoader {lazyLoaderOptions} = @getOptions() lazyLoaderOptions or= {} lazyLoaderOptions.itemClass or= KDCustomHTMLView lazyLoaderOptions.partial ?= '' lazyLoaderOptions.cssClass = KD.utils.curry 'lazy-loader', lazyLoaderOptions.cssClass lazyLoaderOptions.spinnerOptions or= size : width : 32 {itemClass, spinnerOptions} = lazyLoaderOptions delete lazyLoaderOptions.itemClass wrapper = @scrollView or @getView() wrapper.addSubView @lazyLoader = new itemClass lazyLoaderOptions @lazyLoader.addSubView @lazyLoader.spinner = new KDLoaderView spinnerOptions @lazyLoader.spinner.show() @emit 'LazyLoadThresholdReached' if emitWhenReached KD.utils.defer => @scrollView?.stopScrolling = yes hideLazyLoader:-> KD.utils.wait 300, => @scrollView?.stopScrolling = no @showNoItemWidget() if @noItemView and @getOptions().noItemFoundWidget if @lazyLoader @lazyLoader.spinner.hide() @lazyLoader.destroy() @lazyLoader = null
[ { "context": "RequiredForVaulting : \"83502\"\n TokenIsInUse : \"93503\"\n PaymentMethodNonceConsumed : \"93504\"\n ", "end": 1100, "score": 0.6361071467399597, "start": 1099, "tag": "KEY", "value": "9" }, { "context": "equiredForVaulting : \"83502\"\n TokenIsInUse : \"93503\"\n PaymentMethodNonceConsumed : \"93504\"\n Pay", "end": 1104, "score": 0.6068366765975952, "start": 1100, "tag": "PASSWORD", "value": "3503" }, { "context": "uired : \"93509\"\n ExpirationYearIsRequired : \"93510\"\n CryptogramIsRequired : \"93511\"\n Decrypti", "end": 1449, "score": 0.7793885469436646, "start": 1447, "tag": "KEY", "value": "51" }, { "context": "CertificateMismatch : \"93519\"\n InvalidToken : \"83520\"\n PrivateKeyMismatch : \"93521\"\n KeyMismatch", "end": 1753, "score": 0.7597765922546387, "start": 1748, "tag": "PASSWORD", "value": "83520" }, { "context": " InvalidFormat : \"93202\"\n InvalidPublicKey : \"93205\"\n InvalidSignature : \"93206\"\n MissingFinger", "end": 1951, "score": 0.984632134437561, "start": 1946, "tag": "KEY", "value": "93205" }, { "context": "ationFailed : \"81737\"\n TokenFormatIsInvalid : \"91718\"\n TokenInvalid : \"91718\"\n TokenIsInUse : \"9", "end": 3913, "score": 0.6112924218177795, "start": 3908, "tag": "PASSWORD", "value": "91718" }, { "context": "okenFormatIsInvalid : \"91718\"\n TokenInvalid : \"91718\"\n TokenIsInUse : \"91719\"\n TokenIsNotAllowed", "end": 3940, "score": 0.8387022018432617, "start": 3935, "tag": "PASSWORD", "value": "91718" }, { "context": "8\"\n TokenInvalid : \"91718\"\n TokenIsInUse : \"91719\"\n TokenIsNotAllowed : \"91721\"\n TokenIsRequi", "end": 3967, "score": 0.7155903577804565, "start": 3962, "tag": "PASSWORD", "value": "91719" }, { "context": " TokenIsInUse : \"91719\"\n TokenIsNotAllowed : \"91721\"\n TokenIsRequired : \"91722\"\n TokenIsTooLong", "end": 3999, "score": 0.741610586643219, "start": 3994, "tag": "PASSWORD", "value": "91721" }, { "context": "kenIsNotAllowed : \"91721\"\n TokenIsRequired : \"91722\"\n TokenIsTooLong : \"91720\"\n VenmoSDKPaymen", "end": 4028, "score": 0.5909634232521057, "start": 4025, "tag": "PASSWORD", "value": "172" }, { "context": " TokenIsRequired : \"91722\"\n TokenIsTooLong : \"91720\"\n VenmoSDKPaymentMethodCodeCardTypeIsNotAccept", "end": 4058, "score": 0.8052203059196472, "start": 4053, "tag": "PASSWORD", "value": "91720" }, { "context": " Options:\n UpdateExistingTokenIsInvalid : \"91723\"\n UpdateExistingTokenNotAllowed : \"91729\"\n ", "end": 4237, "score": 0.7312965989112854, "start": 4233, "tag": "PASSWORD", "value": "1723" }, { "context": " : \"91723\"\n UpdateExistingTokenNotAllowed : \"91729\"\n VerificationMerchantAccountIdIsInvalid : \"", "end": 4283, "score": 0.6564500331878662, "start": 4278, "tag": "PASSWORD", "value": "91729" }, { "context": " IdIsTooLong : \"91612\"\n LastNameIsTooLong : \"81613\"\n PhoneIsTooLong : \"81614\"\n WebsiteForm", "end": 4927, "score": 0.6199862957000732, "start": 4926, "tag": "NAME", "value": "8" }, { "context": "equiredForVaulting : \"82905\"\n TokenIsInUse : \"92906\"\n PaymentMethodNonceConsumed : \"92907\"\n Pay", "end": 8953, "score": 0.5374999046325684, "start": 8949, "tag": "KEY", "value": "2906" }, { "context": "pted : \"91902\"\n PaymentMethodTokenIsInvalid : \"91903\"\n PaymentMethodTokenNotAssociatedWithCustomer ", "end": 11241, "score": 0.9080976247787476, "start": 11236, "tag": "PASSWORD", "value": "91903" }, { "context": " PaymentMethodTokenNotAssociatedWithCustomer : \"91905\"\n PlanBillingFrequencyCannotBeUpdated : \"91922", "end": 11299, "score": 0.9275433421134949, "start": 11294, "tag": "PASSWORD", "value": "91905" }, { "context": "sIsCanceled : \"81905\"\n TokenFormatIsInvalid : \"81906\"\n TrialDurationFormatIsInvalid : \"81907\"\n T", "end": 11543, "score": 0.7018660306930542, "start": 11538, "tag": "PASSWORD", "value": "81906" }, { "context": "pted : \"91517\"\n PaymentMethodTokenIsInvalid : \"91518\"\n ProcessorAuthorizationCodeCannotBeSet : \"915", "end": 14610, "score": 0.8255206346511841, "start": 14605, "tag": "PASSWORD", "value": "91518" }, { "context": "Large : \"81536\"\n ThreeDSecureTokenIsInvalid : \"91568\"\n ThreeDSecureTransactionDataDoesntMatchVerify", "end": 15718, "score": 0.9831312894821167, "start": 15713, "tag": "PASSWORD", "value": "91568" } ]
src/braintree/validation_error_codes.coffee
StreamCo/braintree_node
0
class ValidationErrorCodes @Address = CannotBeBlank : "81801" CompanyIsInvalid : "91821" CompanyIsTooLong : "81802" CountryCodeAlpha2IsNotAccepted : "91814" CountryCodeAlpha3IsNotAccepted : "91816" CountryCodeNumericIsNotAccepted : "91817" CountryNameIsNotAccepted : "91803" ExtendedAddressIsInvalid : "91823" ExtendedAddressIsTooLong : "81804" FirstNameIsInvalid : "91819" FirstNameIsTooLong : "81805" InconsistentCountry : "91815" LastNameIsInvalid : "91820" LastNameIsTooLong : "81806" LocalityIsInvalid : "91824" LocalityIsTooLong : "81807" PostalCodeInvalidCharacters : "81813" PostalCodeIsInvalid : "91826" PostalCodeIsRequired : "81808" PostalCodeIsTooLong : "81809" RegionIsInvalid : "91825" RegionIsTooLong : "81810" StreetAddressIsInvalid : "91822" StreetAddressIsRequired : "81811" StreetAddressIsTooLong : "81812" TooManyAddressesPerCustomer : "91818" @ApplePayCard = ApplePayCardsAreNotAccepted : "83501" CustomerIdIsRequiredForVaulting : "83502" TokenIsInUse : "93503" PaymentMethodNonceConsumed : "93504" PaymentMethodNonceUnknown : "93505" PaymentMethodNonceLocked : "93506" PaymentMethodNonceCardTypeIsNotAccepted : "83518" CannotUpdateApplePayCardUsingPaymentMethodNonce : "93507" NumberIsRequired : "93508" ExpirationMonthIsRequired : "93509" ExpirationYearIsRequired : "93510" CryptogramIsRequired : "93511" DecryptionFailed : "83512" Disabled : "93513" MerchantNotConfigured : "93514" MerchantKeysAlreadyConfigured : "93515" MerchantKeysNotConfigured : "93516" CertificateInvalid : "93517" CertificateMismatch : "93519" InvalidToken : "83520" PrivateKeyMismatch : "93521" KeyMismatchStoringCertificate : "93522" @AuthorizationFingerprint = InvalidCreatedAt : "93204" InvalidFormat : "93202" InvalidPublicKey : "93205" InvalidSignature : "93206" MissingFingerprint : "93201" OptionsNotAllowedWithoutCustomer : "93207" SignatureRevoked : "93203" @ClientToken = CustomerDoesNotExist : "92804" FailOnDuplicatePaymentMethodRequiresCustomerId : "92803" MakeDefaultRequiresCustomerId : "92801" ProxyMerchantDoesNotExist : "92805" VerifyCardRequiresCustomerId : "92802" MerchantAccountDoesNotExist : "92807" UnsupportedVersion : "92806" @CreditCard = BillingAddressConflict : "91701" BillingAddressIdIsInvalid : "91702" CannotUpdateCardUsingPaymentMethodNonce : "91735" CardholderNameIsTooLong : "81723" CannotUpdateCardUsingPaymentMethodNonce : "91735" PaymentMethodNonceCardTypeIsNotAccepted : "91734" PaymentMethodNonceConsumed : "91731" PaymentMethodNonceLocked : "91733" PaymentMethodNonceUnknown : "91732" CreditCardTypeIsNotAccepted : "81703" CreditCardTypeIsNotAcceptedBySubscriptionMerchantAccount : "81718" CustomerIdIsInvalid : "91705" CustomerIdIsRequired : "91704" CvvIsInvalid : "81707" CvvIsRequired : "81706" CvvVerificationFailed : "81736" DuplicateCardExists : "81724" ExpirationDateConflict : "91708" ExpirationDateIsInvalid : "81710" ExpirationDateIsRequired : "81709" ExpirationDateYearIsInvalid : "81711" ExpirationMonthIsInvalid : "81712" ExpirationYearIsInvalid : "81713" InvalidVenmoSDKPaymentMethodCode : "91727" NumberHasInvalidLength : "81716" NumberIsInvalid : "81715" NumberIsRequired : "81714" NumberLengthIsInvalid : "81716" NumberMustBeTestNumber : "81717" PaymentMethodConflict : "81725" PaymentMethodIsNotACreditCard : "91738" PaymentMethodNonceCardTypeIsNotAccepted : "91734" PaymentMethodNonceConsumed : "91731" PaymentMethodNonceLocked : "91733" PaymentMethodNonceUnknown : "91732" PostalCodeVerificationFailed : "81737" TokenFormatIsInvalid : "91718" TokenInvalid : "91718" TokenIsInUse : "91719" TokenIsNotAllowed : "91721" TokenIsRequired : "91722" TokenIsTooLong : "91720" VenmoSDKPaymentMethodCodeCardTypeIsNotAccepted : "91726" VerificationNotSupportedOnThisMerchantAccount : "91730" Options: UpdateExistingTokenIsInvalid : "91723" UpdateExistingTokenNotAllowed : "91729" VerificationMerchantAccountIdIsInvalid : "91728" VerificationAmountCannotBeNegative : "91739" VerificationAmountFormatIsInvalid : "91740" VerificationAmountNotSupportedByProcessor : "91741" @Customer = CompanyIsTooLong : "81601" CustomFieldIsInvalid : "91602" CustomFieldIsTooLong : "81603" EmailFormatIsInvalid : "81604" EmailIsRequired : "81606" EmailIsTooLong : "81605" FaxIsTooLong : "81607" FirstNameIsTooLong : "81608" IdIsInUse : "91609" IdIsInvalid : "91610" IdIsNotAllowed : "91611" IdIsRequired : "91613" IdIsTooLong : "91612" LastNameIsTooLong : "81613" PhoneIsTooLong : "81614" WebsiteFormatIsInvalid : "81616" WebsiteIsTooLong : "81615" @Descriptor = InternationalNameFormatIsInvalid : "92204" PhoneFormatIsInvalid : "92202" DynamicDescriptorsDisabled : "92203" NameFormatIsInvalid : "92201" InternationalPhoneFormatIsInvalid : "92205" UrlFormatIsInvalid : "92206" @MerchantAccount = ApplicantDetails: AccountNumberIsInvalid : "82670" AccountNumberIsRequired : "82614" Address: LocalityIsRequired : "82618" PostalCodeIsInvalid : "82630" PostalCodeIsRequired : "82619" RegionIsInvalid : "82664" RegionIsRequired : "82620" StreetAddressIsInvalid : "82629" StreetAddressIsRequired : "82617" CompanyNameIsInvalid : "82631" CompanyNameIsRequiredWithTaxId : "82633" DateOfBirthIsInvalid : "82663" DateOfBirthIsRequired : "82612" Declined : "82626" DeclinedFailedKYC : "82623" DeclinedMasterCardMatch : "82622" DeclinedOFAC : "82621" DeclinedSsnInvalid : "82624" DeclinedSsnMatchesDeceased : "82625" EmailAddressIsInvalid : "82616" EmailAddressIsRequired : "82665" FirstNameIsInvalid : "82627" FirstNameIsRequired : "82609" LastNameIsInvalid : "82628" LastNameIsRequired : "82611" PhoneIsInvalid : "82636" RoutingNumberIsInvalid : "82635" RoutingNumberIsRequired : "82613" SsnIsInvalid : "82615" TaxIdIsInvalid : "82632" TaxIdIsRequiredWithCompanyName : "82634" TaxIdMustBeBlank : "82673" Individual: DateOfBirthIsInvalid : "82666" DateOfBirthIsRequired : "82639" EmailIsInvalid : "82643" EmailIsRequired : "82667" FirstNameIsInvalid : "82644" FirstNameIsRequired : "82637" LastNameIsInvalid : "82645" LastNameIsRequired : "82638" PhoneIsInvalid : "82656" SsnIsInvalid : "82642" Address: StreetAddressIsRequired : "82657" LocalityIsRequired : "82658" PostalCodeIsRequired : "82659" RegionIsRequired : "82660" StreetAddressIsInvalid : "82661" PostalCodeIsInvalid : "82662" RegionIsInvalid : "82668" Business: DbaNameIsInvalid : "82646" LegalNameIsInvalid : "82677" LegalNameIsRequiredWithTaxId : "82669" TaxIdIsInvalid : "82647" TaxIdIsRequiredWithLegalName : "82648" TaxIdMustBeBlank : "82672" Address: StreetAddressIsInvalid : "82685" PostalCodeIsInvalid : "82686" RegionIsInvalid : "82684" Funding: AccountNumberIsInvalid : "82671" AccountNumberIsRequired : "82641" DestinationIsInvalid : "82679" DestinationIsRequired : "82678" EmailIsInvalid : "82681" EmailIsRequired : "82680" MobilePhoneIsInvalid : "82683" MobilePhoneIsRequired : "82682" RoutingNumberIsInvalid : "82649" RoutingNumberIsRequired : "82640" CannotBeUpdated : "82674" IdCannotBeUpdated : "82675" IdFormatIsInvalid : "82603" IdIsInUse : "82604" IdIsNotAllowed : "82605" IdIsTooLong : "82602" MasterMerchantAccountIdCannotBeUpdated : "82676" MasterMerchantAccountIdIsInvalid : "82607" MasterMerchantAccountIdIsRequired : "82606" MasterMerchantAccountMustBeActive : "82608" TosAcceptedIsRequired : "82610" @PaymentMethod = CannotForwardPaymentMethodType : "93106" CustomerIdIsInvalid : "93105" CustomerIdIsRequired : "93104" NonceIsInvalid : "93102" NonceIsRequired : "93103" PaymentMethodParamsAreRequired : "93101" PaymentMethodNonceConsumed : "93107" PaymentMethodNonceUnknown : "93108" PaymentMethodNonceLocked : "93109" @PayPalAccount = ConsentCodeOrAccessTokenIsRequired : "82901" CannotVaultOneTimeUsePayPalAccount : "82902" CannotHaveBothAccessTokenAndConsentCode : "82903" PayPalAccountsAreNotAccepted : "82904" CustomerIdIsRequiredForVaulting : "82905" TokenIsInUse : "92906" PaymentMethodNonceConsumed : "92907" PaymentMethodNonceUnknown : "92908" PaymentMethodNonceLocked : "92909" PayPalCommunicationError : "92910" AuthExpired : "92911" CannotHaveFundingSourceWithoutAccessToken : "92912" InvalidFundingSourceSelection : "92913" CannotUpdatePayPalAccountUsingPaymentMethodNonce : "92914" @SEPABankAccount = IBANIsRequired : "93001" BICIsRequired : "93002" AccountHolderNameIsRequired : "93003" @SEPAMandate = AccountHolderNameIsRequired : "83301" BICIsRequired : "83302" IBANIsRequired : "83303" TypeIsRequired : "93304" IBANInvalidCharacter : "83305" BICInvalidCharacter : "83306" BICLengthIsInvalid : "83307" BICUnsupportedCountry : "83308" IBANUnsupportedCountry : "83309" IBANInvalidFormat : "83310" BillingAddressConflict : "93311" BillingAddressIdIsInvalid : "93312" TypeIsInvalid : "93313" @SettlementBatchSummary = SettlementDateIsInvalid : "82302" SettlementDateIsRequired : "82301" CustomFieldIsInvalid : "82303" @Subscription = BillingDayOfMonthCannotBeUpdated : "91918" BillingDayOfMonthIsInvalid : "91914" BillingDayOfMonthMustBeNumeric : "91913" CannotAddDuplicateAddonOrDiscount : "91911" CannotEditCanceledSubscription : "81901" CannotEditExpiredSubscription : "81910" CannotEditPriceChangingFieldsOnPastDueSubscription : "91920" FirstBillingDateCannotBeInThePast : "91916" FirstBillingDateCannotBeUpdated : "91919" FirstBillingDateIsInvalid : "91915" IdIsInUse : "81902" InconsistentNumberOfBillingCycles : "91908" InconsistentStartDate : "91917" InvalidRequestFormat : "91921" MerchantAccountIdIsInvalid : "91901" MismatchCurrencyISOCode : "91923" NumberOfBillingCyclesCannotBeBlank : "91912" NumberOfBillingCyclesIsTooSmall : "91909" NumberOfBillingCyclesMustBeGreaterThanZero : "91907" NumberOfBillingCyclesMustBeNumeric : "91906" PaymentMethodNonceCardTypeIsNotAccepted : "91924" PaymentMethodNonceIsInvalid : "91925" PaymentMethodNonceNotAssociatedWithCustomer : "91926" PaymentMethodNonceUnvaultedCardIsNotAccepted : "91927" PaymentMethodTokenCardTypeIsNotAccepted : "91902" PaymentMethodTokenIsInvalid : "91903" PaymentMethodTokenNotAssociatedWithCustomer : "91905" PlanBillingFrequencyCannotBeUpdated : "91922" PlanIdIsInvalid : "91904" PriceCannotBeBlank : "81903" PriceFormatIsInvalid : "81904" PriceIsTooLarge : "81923" StatusIsCanceled : "81905" TokenFormatIsInvalid : "81906" TrialDurationFormatIsInvalid : "81907" TrialDurationIsRequired : "81908" TrialDurationUnitIsInvalid : "81909" Modification: AmountCannotBeBlank : "92003" AmountIsInvalid : "92002" AmountIsTooLarge : "92023" CannotEditModificationsOnPastDueSubscription : "92022" CannotUpdateAndRemove : "92015" ExistingIdIsIncorrectKind : "92020" ExistingIdIsInvalid : "92011" ExistingIdIsRequired : "92012" IdToRemoveIsIncorrectKind : "92021" IdToRemoveIsInvalid : "92025" IdToRemoveIsNotPresent : "92016" InconsistentNumberOfBillingCycles : "92018" InheritedFromIdIsInvalid : "92013" InheritedFromIdIsRequired : "92014" Missing : "92024" NumberOfBillingCyclesCannotBeBlank : "92017" NumberOfBillingCyclesIsInvalid : "92005" NumberOfBillingCyclesMustBeGreaterThanZero : "92019" QuantityCannotBeBlank : "92004" QuantityIsInvalid : "92001" QuantityMustBeGreaterThanZero : "92010" @Transaction = AmountCannotBeNegative : "81501" AmountFormatIsInvalid : "81503" AmountIsRequired : "81502" AmountIsTooLarge : "81528" AmountMustBeGreaterThanZero : "81531" BillingAddressConflict : "91530" CannotBeVoided : "91504" CannotCancelRelease : "91562" CannotCloneCredit : "91543" CannotCloneTransactionWithPayPalAccount : "91573" CannotCloneTransactionWithVaultCreditCard : "91540" CannotCloneUnsuccessfulTransaction : "91542" CannotCloneVoiceAuthorizations : "91541" CannotHoldInEscrow : "91560" CannotPartiallyRefundEscrowedTransaction : "91563" CannotRefundCredit : "91505" CannotRefundUnlessSettled : "91506" CannotRefundWithPendingMerchantAccount : "91559" CannotRefundWithSuspendedMerchantAccount : "91538" CannotReleaseFromEscrow : "91561" CannotSubmitForSettlement : "91507" ChannelIsTooLong : "91550" CreditCardIsRequired : "91508" CustomFieldIsInvalid : "91526" CustomFieldIsTooLong : "81527" CustomerDefaultPaymentMethodCardTypeIsNotAccepted : "81509" CustomerDoesNotHaveCreditCard : "91511" CustomerIdIsInvalid : "91510" HasAlreadyBeenRefunded : "91512" MerchantAccountDoesNotSupportMOTO : "91558" MerchantAccountDoesNotSupportRefunds : "91547" MerchantAccountIdIsInvalid : "91513" MerchantAccountIsSuspended : "91514" Options: SubmitForSettlementIsRequiredForCloning : "91544" UseBillingForShippingDisabled : "91572" VaultIsDisabled : "91525" PayPal: CustomFieldTooLong : "91580" OrderIdIsTooLong : "91501" PaymentMethodConflict : "91515" PaymentMethodConflictWithVenmoSDK : "91549" PaymentMethodDoesNotBelongToCustomer : "91516" PaymentMethodDoesNotBelongToSubscription : "91527" PaymentMethodNonceCardTypeIsNotAccepted : "91567" PaymentMethodNonceConsumed : "91564" PaymentMethodNonceLocked : "91566" PaymentMethodNonceUnknown : "91565" PaymentMethodTokenCardTypeIsNotAccepted : "91517" PaymentMethodTokenIsInvalid : "91518" ProcessorAuthorizationCodeCannotBeSet : "91519" ProcessorAuthorizationCodeIsInvalid : "81520" ProcessorDoesNotSupportCredits : "91546" ProcessorDoesNotSupportVoiceAuthorizations : "91545" PurchaseOrderNumberIsInvalid : "91548" PurchaseOrderNumberIsTooLong : "91537" RefundAmountIsTooLarge : "91521" ServiceFeeAmountCannotBeNegative : "91554" ServiceFeeAmountFormatIsInvalid : "91555" ServiceFeeAmountIsTooLarge : "91556" ServiceFeeAmountNotAllowedOnMasterMerchantAccount : "91557" ServiceFeeIsNotAllowedOnCredits : "91552" ServiceFeeNotAcceptedForPayPal : "91578" SettlementAmountIsLessThanServiceFeeAmount : "91551" SettlementAmountIsTooLarge : "91522" ShippingAddressDoesntMatchCustomer : "91581" SubMerchantAccountRequiresServiceFeeAmount : "91553" SubscriptionDoesNotBelongToCustomer : "91529" SubscriptionIdIsInvalid : "91528" SubscriptionStatusMustBePastDue : "91531" TaxAmountCannotBeNegative : "81534" TaxAmountFormatIsInvalid : "81535" TaxAmountIsTooLarge : "81536" ThreeDSecureTokenIsInvalid : "91568" ThreeDSecureTransactionDataDoesntMatchVerify : "91570" TransactionSettlementAmountIsLessThanServiceFeeAmount : "91551" TypeIsInvalid : "91523" TypeIsRequired : "91524" UnsupportedVoiceAuthorization : "91539" CannotRefundSettlingTransaction : "91574" CannotSimulateSettlement : "91575" PaymentInstrumentNotSupportedByMerchantAccount : "91577" PayPalNotEnabled : "91576" PayPalAuthExpired : "91579" ThreeDSecureAuthenticationFailed : "81571" IndustryData: IndustryTypeIsInvalid : "93401" Lodging: EmptyData : "93402" FolioNumberIsInvalid : "93403" CheckInDateIsInvalid : "93404" CheckOutDateIsInvalid : "93405" CheckOutDateMustFollowCheckInDate : "93406" UnknownDataField : "93407" TravelCruise: EmptyData : "93408" UnknownDataField : "93409" TravelPackageIsInvalid : "93410" DepartureDateIsInvalid : "93411" CheckInDateIsInvalid : "93412" CheckOutDateIsInvalid : "93413" exports.ValidationErrorCodes = ValidationErrorCodes
178547
class ValidationErrorCodes @Address = CannotBeBlank : "81801" CompanyIsInvalid : "91821" CompanyIsTooLong : "81802" CountryCodeAlpha2IsNotAccepted : "91814" CountryCodeAlpha3IsNotAccepted : "91816" CountryCodeNumericIsNotAccepted : "91817" CountryNameIsNotAccepted : "91803" ExtendedAddressIsInvalid : "91823" ExtendedAddressIsTooLong : "81804" FirstNameIsInvalid : "91819" FirstNameIsTooLong : "81805" InconsistentCountry : "91815" LastNameIsInvalid : "91820" LastNameIsTooLong : "81806" LocalityIsInvalid : "91824" LocalityIsTooLong : "81807" PostalCodeInvalidCharacters : "81813" PostalCodeIsInvalid : "91826" PostalCodeIsRequired : "81808" PostalCodeIsTooLong : "81809" RegionIsInvalid : "91825" RegionIsTooLong : "81810" StreetAddressIsInvalid : "91822" StreetAddressIsRequired : "81811" StreetAddressIsTooLong : "81812" TooManyAddressesPerCustomer : "91818" @ApplePayCard = ApplePayCardsAreNotAccepted : "83501" CustomerIdIsRequiredForVaulting : "83502" TokenIsInUse : "<KEY> <PASSWORD>" PaymentMethodNonceConsumed : "93504" PaymentMethodNonceUnknown : "93505" PaymentMethodNonceLocked : "93506" PaymentMethodNonceCardTypeIsNotAccepted : "83518" CannotUpdateApplePayCardUsingPaymentMethodNonce : "93507" NumberIsRequired : "93508" ExpirationMonthIsRequired : "93509" ExpirationYearIsRequired : "93<KEY>0" CryptogramIsRequired : "93511" DecryptionFailed : "83512" Disabled : "93513" MerchantNotConfigured : "93514" MerchantKeysAlreadyConfigured : "93515" MerchantKeysNotConfigured : "93516" CertificateInvalid : "93517" CertificateMismatch : "93519" InvalidToken : "<PASSWORD>" PrivateKeyMismatch : "93521" KeyMismatchStoringCertificate : "93522" @AuthorizationFingerprint = InvalidCreatedAt : "93204" InvalidFormat : "93202" InvalidPublicKey : "<KEY>" InvalidSignature : "93206" MissingFingerprint : "93201" OptionsNotAllowedWithoutCustomer : "93207" SignatureRevoked : "93203" @ClientToken = CustomerDoesNotExist : "92804" FailOnDuplicatePaymentMethodRequiresCustomerId : "92803" MakeDefaultRequiresCustomerId : "92801" ProxyMerchantDoesNotExist : "92805" VerifyCardRequiresCustomerId : "92802" MerchantAccountDoesNotExist : "92807" UnsupportedVersion : "92806" @CreditCard = BillingAddressConflict : "91701" BillingAddressIdIsInvalid : "91702" CannotUpdateCardUsingPaymentMethodNonce : "91735" CardholderNameIsTooLong : "81723" CannotUpdateCardUsingPaymentMethodNonce : "91735" PaymentMethodNonceCardTypeIsNotAccepted : "91734" PaymentMethodNonceConsumed : "91731" PaymentMethodNonceLocked : "91733" PaymentMethodNonceUnknown : "91732" CreditCardTypeIsNotAccepted : "81703" CreditCardTypeIsNotAcceptedBySubscriptionMerchantAccount : "81718" CustomerIdIsInvalid : "91705" CustomerIdIsRequired : "91704" CvvIsInvalid : "81707" CvvIsRequired : "81706" CvvVerificationFailed : "81736" DuplicateCardExists : "81724" ExpirationDateConflict : "91708" ExpirationDateIsInvalid : "81710" ExpirationDateIsRequired : "81709" ExpirationDateYearIsInvalid : "81711" ExpirationMonthIsInvalid : "81712" ExpirationYearIsInvalid : "81713" InvalidVenmoSDKPaymentMethodCode : "91727" NumberHasInvalidLength : "81716" NumberIsInvalid : "81715" NumberIsRequired : "81714" NumberLengthIsInvalid : "81716" NumberMustBeTestNumber : "81717" PaymentMethodConflict : "81725" PaymentMethodIsNotACreditCard : "91738" PaymentMethodNonceCardTypeIsNotAccepted : "91734" PaymentMethodNonceConsumed : "91731" PaymentMethodNonceLocked : "91733" PaymentMethodNonceUnknown : "91732" PostalCodeVerificationFailed : "81737" TokenFormatIsInvalid : "<PASSWORD>" TokenInvalid : "<PASSWORD>" TokenIsInUse : "<PASSWORD>" TokenIsNotAllowed : "<PASSWORD>" TokenIsRequired : "9<PASSWORD>2" TokenIsTooLong : "<PASSWORD>" VenmoSDKPaymentMethodCodeCardTypeIsNotAccepted : "91726" VerificationNotSupportedOnThisMerchantAccount : "91730" Options: UpdateExistingTokenIsInvalid : "9<PASSWORD>" UpdateExistingTokenNotAllowed : "<PASSWORD>" VerificationMerchantAccountIdIsInvalid : "91728" VerificationAmountCannotBeNegative : "91739" VerificationAmountFormatIsInvalid : "91740" VerificationAmountNotSupportedByProcessor : "91741" @Customer = CompanyIsTooLong : "81601" CustomFieldIsInvalid : "91602" CustomFieldIsTooLong : "81603" EmailFormatIsInvalid : "81604" EmailIsRequired : "81606" EmailIsTooLong : "81605" FaxIsTooLong : "81607" FirstNameIsTooLong : "81608" IdIsInUse : "91609" IdIsInvalid : "91610" IdIsNotAllowed : "91611" IdIsRequired : "91613" IdIsTooLong : "91612" LastNameIsTooLong : "<NAME>1613" PhoneIsTooLong : "81614" WebsiteFormatIsInvalid : "81616" WebsiteIsTooLong : "81615" @Descriptor = InternationalNameFormatIsInvalid : "92204" PhoneFormatIsInvalid : "92202" DynamicDescriptorsDisabled : "92203" NameFormatIsInvalid : "92201" InternationalPhoneFormatIsInvalid : "92205" UrlFormatIsInvalid : "92206" @MerchantAccount = ApplicantDetails: AccountNumberIsInvalid : "82670" AccountNumberIsRequired : "82614" Address: LocalityIsRequired : "82618" PostalCodeIsInvalid : "82630" PostalCodeIsRequired : "82619" RegionIsInvalid : "82664" RegionIsRequired : "82620" StreetAddressIsInvalid : "82629" StreetAddressIsRequired : "82617" CompanyNameIsInvalid : "82631" CompanyNameIsRequiredWithTaxId : "82633" DateOfBirthIsInvalid : "82663" DateOfBirthIsRequired : "82612" Declined : "82626" DeclinedFailedKYC : "82623" DeclinedMasterCardMatch : "82622" DeclinedOFAC : "82621" DeclinedSsnInvalid : "82624" DeclinedSsnMatchesDeceased : "82625" EmailAddressIsInvalid : "82616" EmailAddressIsRequired : "82665" FirstNameIsInvalid : "82627" FirstNameIsRequired : "82609" LastNameIsInvalid : "82628" LastNameIsRequired : "82611" PhoneIsInvalid : "82636" RoutingNumberIsInvalid : "82635" RoutingNumberIsRequired : "82613" SsnIsInvalid : "82615" TaxIdIsInvalid : "82632" TaxIdIsRequiredWithCompanyName : "82634" TaxIdMustBeBlank : "82673" Individual: DateOfBirthIsInvalid : "82666" DateOfBirthIsRequired : "82639" EmailIsInvalid : "82643" EmailIsRequired : "82667" FirstNameIsInvalid : "82644" FirstNameIsRequired : "82637" LastNameIsInvalid : "82645" LastNameIsRequired : "82638" PhoneIsInvalid : "82656" SsnIsInvalid : "82642" Address: StreetAddressIsRequired : "82657" LocalityIsRequired : "82658" PostalCodeIsRequired : "82659" RegionIsRequired : "82660" StreetAddressIsInvalid : "82661" PostalCodeIsInvalid : "82662" RegionIsInvalid : "82668" Business: DbaNameIsInvalid : "82646" LegalNameIsInvalid : "82677" LegalNameIsRequiredWithTaxId : "82669" TaxIdIsInvalid : "82647" TaxIdIsRequiredWithLegalName : "82648" TaxIdMustBeBlank : "82672" Address: StreetAddressIsInvalid : "82685" PostalCodeIsInvalid : "82686" RegionIsInvalid : "82684" Funding: AccountNumberIsInvalid : "82671" AccountNumberIsRequired : "82641" DestinationIsInvalid : "82679" DestinationIsRequired : "82678" EmailIsInvalid : "82681" EmailIsRequired : "82680" MobilePhoneIsInvalid : "82683" MobilePhoneIsRequired : "82682" RoutingNumberIsInvalid : "82649" RoutingNumberIsRequired : "82640" CannotBeUpdated : "82674" IdCannotBeUpdated : "82675" IdFormatIsInvalid : "82603" IdIsInUse : "82604" IdIsNotAllowed : "82605" IdIsTooLong : "82602" MasterMerchantAccountIdCannotBeUpdated : "82676" MasterMerchantAccountIdIsInvalid : "82607" MasterMerchantAccountIdIsRequired : "82606" MasterMerchantAccountMustBeActive : "82608" TosAcceptedIsRequired : "82610" @PaymentMethod = CannotForwardPaymentMethodType : "93106" CustomerIdIsInvalid : "93105" CustomerIdIsRequired : "93104" NonceIsInvalid : "93102" NonceIsRequired : "93103" PaymentMethodParamsAreRequired : "93101" PaymentMethodNonceConsumed : "93107" PaymentMethodNonceUnknown : "93108" PaymentMethodNonceLocked : "93109" @PayPalAccount = ConsentCodeOrAccessTokenIsRequired : "82901" CannotVaultOneTimeUsePayPalAccount : "82902" CannotHaveBothAccessTokenAndConsentCode : "82903" PayPalAccountsAreNotAccepted : "82904" CustomerIdIsRequiredForVaulting : "82905" TokenIsInUse : "9<KEY>" PaymentMethodNonceConsumed : "92907" PaymentMethodNonceUnknown : "92908" PaymentMethodNonceLocked : "92909" PayPalCommunicationError : "92910" AuthExpired : "92911" CannotHaveFundingSourceWithoutAccessToken : "92912" InvalidFundingSourceSelection : "92913" CannotUpdatePayPalAccountUsingPaymentMethodNonce : "92914" @SEPABankAccount = IBANIsRequired : "93001" BICIsRequired : "93002" AccountHolderNameIsRequired : "93003" @SEPAMandate = AccountHolderNameIsRequired : "83301" BICIsRequired : "83302" IBANIsRequired : "83303" TypeIsRequired : "93304" IBANInvalidCharacter : "83305" BICInvalidCharacter : "83306" BICLengthIsInvalid : "83307" BICUnsupportedCountry : "83308" IBANUnsupportedCountry : "83309" IBANInvalidFormat : "83310" BillingAddressConflict : "93311" BillingAddressIdIsInvalid : "93312" TypeIsInvalid : "93313" @SettlementBatchSummary = SettlementDateIsInvalid : "82302" SettlementDateIsRequired : "82301" CustomFieldIsInvalid : "82303" @Subscription = BillingDayOfMonthCannotBeUpdated : "91918" BillingDayOfMonthIsInvalid : "91914" BillingDayOfMonthMustBeNumeric : "91913" CannotAddDuplicateAddonOrDiscount : "91911" CannotEditCanceledSubscription : "81901" CannotEditExpiredSubscription : "81910" CannotEditPriceChangingFieldsOnPastDueSubscription : "91920" FirstBillingDateCannotBeInThePast : "91916" FirstBillingDateCannotBeUpdated : "91919" FirstBillingDateIsInvalid : "91915" IdIsInUse : "81902" InconsistentNumberOfBillingCycles : "91908" InconsistentStartDate : "91917" InvalidRequestFormat : "91921" MerchantAccountIdIsInvalid : "91901" MismatchCurrencyISOCode : "91923" NumberOfBillingCyclesCannotBeBlank : "91912" NumberOfBillingCyclesIsTooSmall : "91909" NumberOfBillingCyclesMustBeGreaterThanZero : "91907" NumberOfBillingCyclesMustBeNumeric : "91906" PaymentMethodNonceCardTypeIsNotAccepted : "91924" PaymentMethodNonceIsInvalid : "91925" PaymentMethodNonceNotAssociatedWithCustomer : "91926" PaymentMethodNonceUnvaultedCardIsNotAccepted : "91927" PaymentMethodTokenCardTypeIsNotAccepted : "91902" PaymentMethodTokenIsInvalid : "<PASSWORD>" PaymentMethodTokenNotAssociatedWithCustomer : "<PASSWORD>" PlanBillingFrequencyCannotBeUpdated : "91922" PlanIdIsInvalid : "91904" PriceCannotBeBlank : "81903" PriceFormatIsInvalid : "81904" PriceIsTooLarge : "81923" StatusIsCanceled : "81905" TokenFormatIsInvalid : "<PASSWORD>" TrialDurationFormatIsInvalid : "81907" TrialDurationIsRequired : "81908" TrialDurationUnitIsInvalid : "81909" Modification: AmountCannotBeBlank : "92003" AmountIsInvalid : "92002" AmountIsTooLarge : "92023" CannotEditModificationsOnPastDueSubscription : "92022" CannotUpdateAndRemove : "92015" ExistingIdIsIncorrectKind : "92020" ExistingIdIsInvalid : "92011" ExistingIdIsRequired : "92012" IdToRemoveIsIncorrectKind : "92021" IdToRemoveIsInvalid : "92025" IdToRemoveIsNotPresent : "92016" InconsistentNumberOfBillingCycles : "92018" InheritedFromIdIsInvalid : "92013" InheritedFromIdIsRequired : "92014" Missing : "92024" NumberOfBillingCyclesCannotBeBlank : "92017" NumberOfBillingCyclesIsInvalid : "92005" NumberOfBillingCyclesMustBeGreaterThanZero : "92019" QuantityCannotBeBlank : "92004" QuantityIsInvalid : "92001" QuantityMustBeGreaterThanZero : "92010" @Transaction = AmountCannotBeNegative : "81501" AmountFormatIsInvalid : "81503" AmountIsRequired : "81502" AmountIsTooLarge : "81528" AmountMustBeGreaterThanZero : "81531" BillingAddressConflict : "91530" CannotBeVoided : "91504" CannotCancelRelease : "91562" CannotCloneCredit : "91543" CannotCloneTransactionWithPayPalAccount : "91573" CannotCloneTransactionWithVaultCreditCard : "91540" CannotCloneUnsuccessfulTransaction : "91542" CannotCloneVoiceAuthorizations : "91541" CannotHoldInEscrow : "91560" CannotPartiallyRefundEscrowedTransaction : "91563" CannotRefundCredit : "91505" CannotRefundUnlessSettled : "91506" CannotRefundWithPendingMerchantAccount : "91559" CannotRefundWithSuspendedMerchantAccount : "91538" CannotReleaseFromEscrow : "91561" CannotSubmitForSettlement : "91507" ChannelIsTooLong : "91550" CreditCardIsRequired : "91508" CustomFieldIsInvalid : "91526" CustomFieldIsTooLong : "81527" CustomerDefaultPaymentMethodCardTypeIsNotAccepted : "81509" CustomerDoesNotHaveCreditCard : "91511" CustomerIdIsInvalid : "91510" HasAlreadyBeenRefunded : "91512" MerchantAccountDoesNotSupportMOTO : "91558" MerchantAccountDoesNotSupportRefunds : "91547" MerchantAccountIdIsInvalid : "91513" MerchantAccountIsSuspended : "91514" Options: SubmitForSettlementIsRequiredForCloning : "91544" UseBillingForShippingDisabled : "91572" VaultIsDisabled : "91525" PayPal: CustomFieldTooLong : "91580" OrderIdIsTooLong : "91501" PaymentMethodConflict : "91515" PaymentMethodConflictWithVenmoSDK : "91549" PaymentMethodDoesNotBelongToCustomer : "91516" PaymentMethodDoesNotBelongToSubscription : "91527" PaymentMethodNonceCardTypeIsNotAccepted : "91567" PaymentMethodNonceConsumed : "91564" PaymentMethodNonceLocked : "91566" PaymentMethodNonceUnknown : "91565" PaymentMethodTokenCardTypeIsNotAccepted : "91517" PaymentMethodTokenIsInvalid : "<PASSWORD>" ProcessorAuthorizationCodeCannotBeSet : "91519" ProcessorAuthorizationCodeIsInvalid : "81520" ProcessorDoesNotSupportCredits : "91546" ProcessorDoesNotSupportVoiceAuthorizations : "91545" PurchaseOrderNumberIsInvalid : "91548" PurchaseOrderNumberIsTooLong : "91537" RefundAmountIsTooLarge : "91521" ServiceFeeAmountCannotBeNegative : "91554" ServiceFeeAmountFormatIsInvalid : "91555" ServiceFeeAmountIsTooLarge : "91556" ServiceFeeAmountNotAllowedOnMasterMerchantAccount : "91557" ServiceFeeIsNotAllowedOnCredits : "91552" ServiceFeeNotAcceptedForPayPal : "91578" SettlementAmountIsLessThanServiceFeeAmount : "91551" SettlementAmountIsTooLarge : "91522" ShippingAddressDoesntMatchCustomer : "91581" SubMerchantAccountRequiresServiceFeeAmount : "91553" SubscriptionDoesNotBelongToCustomer : "91529" SubscriptionIdIsInvalid : "91528" SubscriptionStatusMustBePastDue : "91531" TaxAmountCannotBeNegative : "81534" TaxAmountFormatIsInvalid : "81535" TaxAmountIsTooLarge : "81536" ThreeDSecureTokenIsInvalid : "<PASSWORD>" ThreeDSecureTransactionDataDoesntMatchVerify : "91570" TransactionSettlementAmountIsLessThanServiceFeeAmount : "91551" TypeIsInvalid : "91523" TypeIsRequired : "91524" UnsupportedVoiceAuthorization : "91539" CannotRefundSettlingTransaction : "91574" CannotSimulateSettlement : "91575" PaymentInstrumentNotSupportedByMerchantAccount : "91577" PayPalNotEnabled : "91576" PayPalAuthExpired : "91579" ThreeDSecureAuthenticationFailed : "81571" IndustryData: IndustryTypeIsInvalid : "93401" Lodging: EmptyData : "93402" FolioNumberIsInvalid : "93403" CheckInDateIsInvalid : "93404" CheckOutDateIsInvalid : "93405" CheckOutDateMustFollowCheckInDate : "93406" UnknownDataField : "93407" TravelCruise: EmptyData : "93408" UnknownDataField : "93409" TravelPackageIsInvalid : "93410" DepartureDateIsInvalid : "93411" CheckInDateIsInvalid : "93412" CheckOutDateIsInvalid : "93413" exports.ValidationErrorCodes = ValidationErrorCodes
true
class ValidationErrorCodes @Address = CannotBeBlank : "81801" CompanyIsInvalid : "91821" CompanyIsTooLong : "81802" CountryCodeAlpha2IsNotAccepted : "91814" CountryCodeAlpha3IsNotAccepted : "91816" CountryCodeNumericIsNotAccepted : "91817" CountryNameIsNotAccepted : "91803" ExtendedAddressIsInvalid : "91823" ExtendedAddressIsTooLong : "81804" FirstNameIsInvalid : "91819" FirstNameIsTooLong : "81805" InconsistentCountry : "91815" LastNameIsInvalid : "91820" LastNameIsTooLong : "81806" LocalityIsInvalid : "91824" LocalityIsTooLong : "81807" PostalCodeInvalidCharacters : "81813" PostalCodeIsInvalid : "91826" PostalCodeIsRequired : "81808" PostalCodeIsTooLong : "81809" RegionIsInvalid : "91825" RegionIsTooLong : "81810" StreetAddressIsInvalid : "91822" StreetAddressIsRequired : "81811" StreetAddressIsTooLong : "81812" TooManyAddressesPerCustomer : "91818" @ApplePayCard = ApplePayCardsAreNotAccepted : "83501" CustomerIdIsRequiredForVaulting : "83502" TokenIsInUse : "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI" PaymentMethodNonceConsumed : "93504" PaymentMethodNonceUnknown : "93505" PaymentMethodNonceLocked : "93506" PaymentMethodNonceCardTypeIsNotAccepted : "83518" CannotUpdateApplePayCardUsingPaymentMethodNonce : "93507" NumberIsRequired : "93508" ExpirationMonthIsRequired : "93509" ExpirationYearIsRequired : "93PI:KEY:<KEY>END_PI0" CryptogramIsRequired : "93511" DecryptionFailed : "83512" Disabled : "93513" MerchantNotConfigured : "93514" MerchantKeysAlreadyConfigured : "93515" MerchantKeysNotConfigured : "93516" CertificateInvalid : "93517" CertificateMismatch : "93519" InvalidToken : "PI:PASSWORD:<PASSWORD>END_PI" PrivateKeyMismatch : "93521" KeyMismatchStoringCertificate : "93522" @AuthorizationFingerprint = InvalidCreatedAt : "93204" InvalidFormat : "93202" InvalidPublicKey : "PI:KEY:<KEY>END_PI" InvalidSignature : "93206" MissingFingerprint : "93201" OptionsNotAllowedWithoutCustomer : "93207" SignatureRevoked : "93203" @ClientToken = CustomerDoesNotExist : "92804" FailOnDuplicatePaymentMethodRequiresCustomerId : "92803" MakeDefaultRequiresCustomerId : "92801" ProxyMerchantDoesNotExist : "92805" VerifyCardRequiresCustomerId : "92802" MerchantAccountDoesNotExist : "92807" UnsupportedVersion : "92806" @CreditCard = BillingAddressConflict : "91701" BillingAddressIdIsInvalid : "91702" CannotUpdateCardUsingPaymentMethodNonce : "91735" CardholderNameIsTooLong : "81723" CannotUpdateCardUsingPaymentMethodNonce : "91735" PaymentMethodNonceCardTypeIsNotAccepted : "91734" PaymentMethodNonceConsumed : "91731" PaymentMethodNonceLocked : "91733" PaymentMethodNonceUnknown : "91732" CreditCardTypeIsNotAccepted : "81703" CreditCardTypeIsNotAcceptedBySubscriptionMerchantAccount : "81718" CustomerIdIsInvalid : "91705" CustomerIdIsRequired : "91704" CvvIsInvalid : "81707" CvvIsRequired : "81706" CvvVerificationFailed : "81736" DuplicateCardExists : "81724" ExpirationDateConflict : "91708" ExpirationDateIsInvalid : "81710" ExpirationDateIsRequired : "81709" ExpirationDateYearIsInvalid : "81711" ExpirationMonthIsInvalid : "81712" ExpirationYearIsInvalid : "81713" InvalidVenmoSDKPaymentMethodCode : "91727" NumberHasInvalidLength : "81716" NumberIsInvalid : "81715" NumberIsRequired : "81714" NumberLengthIsInvalid : "81716" NumberMustBeTestNumber : "81717" PaymentMethodConflict : "81725" PaymentMethodIsNotACreditCard : "91738" PaymentMethodNonceCardTypeIsNotAccepted : "91734" PaymentMethodNonceConsumed : "91731" PaymentMethodNonceLocked : "91733" PaymentMethodNonceUnknown : "91732" PostalCodeVerificationFailed : "81737" TokenFormatIsInvalid : "PI:PASSWORD:<PASSWORD>END_PI" TokenInvalid : "PI:PASSWORD:<PASSWORD>END_PI" TokenIsInUse : "PI:PASSWORD:<PASSWORD>END_PI" TokenIsNotAllowed : "PI:PASSWORD:<PASSWORD>END_PI" TokenIsRequired : "9PI:PASSWORD:<PASSWORD>END_PI2" TokenIsTooLong : "PI:PASSWORD:<PASSWORD>END_PI" VenmoSDKPaymentMethodCodeCardTypeIsNotAccepted : "91726" VerificationNotSupportedOnThisMerchantAccount : "91730" Options: UpdateExistingTokenIsInvalid : "9PI:PASSWORD:<PASSWORD>END_PI" UpdateExistingTokenNotAllowed : "PI:PASSWORD:<PASSWORD>END_PI" VerificationMerchantAccountIdIsInvalid : "91728" VerificationAmountCannotBeNegative : "91739" VerificationAmountFormatIsInvalid : "91740" VerificationAmountNotSupportedByProcessor : "91741" @Customer = CompanyIsTooLong : "81601" CustomFieldIsInvalid : "91602" CustomFieldIsTooLong : "81603" EmailFormatIsInvalid : "81604" EmailIsRequired : "81606" EmailIsTooLong : "81605" FaxIsTooLong : "81607" FirstNameIsTooLong : "81608" IdIsInUse : "91609" IdIsInvalid : "91610" IdIsNotAllowed : "91611" IdIsRequired : "91613" IdIsTooLong : "91612" LastNameIsTooLong : "PI:NAME:<NAME>END_PI1613" PhoneIsTooLong : "81614" WebsiteFormatIsInvalid : "81616" WebsiteIsTooLong : "81615" @Descriptor = InternationalNameFormatIsInvalid : "92204" PhoneFormatIsInvalid : "92202" DynamicDescriptorsDisabled : "92203" NameFormatIsInvalid : "92201" InternationalPhoneFormatIsInvalid : "92205" UrlFormatIsInvalid : "92206" @MerchantAccount = ApplicantDetails: AccountNumberIsInvalid : "82670" AccountNumberIsRequired : "82614" Address: LocalityIsRequired : "82618" PostalCodeIsInvalid : "82630" PostalCodeIsRequired : "82619" RegionIsInvalid : "82664" RegionIsRequired : "82620" StreetAddressIsInvalid : "82629" StreetAddressIsRequired : "82617" CompanyNameIsInvalid : "82631" CompanyNameIsRequiredWithTaxId : "82633" DateOfBirthIsInvalid : "82663" DateOfBirthIsRequired : "82612" Declined : "82626" DeclinedFailedKYC : "82623" DeclinedMasterCardMatch : "82622" DeclinedOFAC : "82621" DeclinedSsnInvalid : "82624" DeclinedSsnMatchesDeceased : "82625" EmailAddressIsInvalid : "82616" EmailAddressIsRequired : "82665" FirstNameIsInvalid : "82627" FirstNameIsRequired : "82609" LastNameIsInvalid : "82628" LastNameIsRequired : "82611" PhoneIsInvalid : "82636" RoutingNumberIsInvalid : "82635" RoutingNumberIsRequired : "82613" SsnIsInvalid : "82615" TaxIdIsInvalid : "82632" TaxIdIsRequiredWithCompanyName : "82634" TaxIdMustBeBlank : "82673" Individual: DateOfBirthIsInvalid : "82666" DateOfBirthIsRequired : "82639" EmailIsInvalid : "82643" EmailIsRequired : "82667" FirstNameIsInvalid : "82644" FirstNameIsRequired : "82637" LastNameIsInvalid : "82645" LastNameIsRequired : "82638" PhoneIsInvalid : "82656" SsnIsInvalid : "82642" Address: StreetAddressIsRequired : "82657" LocalityIsRequired : "82658" PostalCodeIsRequired : "82659" RegionIsRequired : "82660" StreetAddressIsInvalid : "82661" PostalCodeIsInvalid : "82662" RegionIsInvalid : "82668" Business: DbaNameIsInvalid : "82646" LegalNameIsInvalid : "82677" LegalNameIsRequiredWithTaxId : "82669" TaxIdIsInvalid : "82647" TaxIdIsRequiredWithLegalName : "82648" TaxIdMustBeBlank : "82672" Address: StreetAddressIsInvalid : "82685" PostalCodeIsInvalid : "82686" RegionIsInvalid : "82684" Funding: AccountNumberIsInvalid : "82671" AccountNumberIsRequired : "82641" DestinationIsInvalid : "82679" DestinationIsRequired : "82678" EmailIsInvalid : "82681" EmailIsRequired : "82680" MobilePhoneIsInvalid : "82683" MobilePhoneIsRequired : "82682" RoutingNumberIsInvalid : "82649" RoutingNumberIsRequired : "82640" CannotBeUpdated : "82674" IdCannotBeUpdated : "82675" IdFormatIsInvalid : "82603" IdIsInUse : "82604" IdIsNotAllowed : "82605" IdIsTooLong : "82602" MasterMerchantAccountIdCannotBeUpdated : "82676" MasterMerchantAccountIdIsInvalid : "82607" MasterMerchantAccountIdIsRequired : "82606" MasterMerchantAccountMustBeActive : "82608" TosAcceptedIsRequired : "82610" @PaymentMethod = CannotForwardPaymentMethodType : "93106" CustomerIdIsInvalid : "93105" CustomerIdIsRequired : "93104" NonceIsInvalid : "93102" NonceIsRequired : "93103" PaymentMethodParamsAreRequired : "93101" PaymentMethodNonceConsumed : "93107" PaymentMethodNonceUnknown : "93108" PaymentMethodNonceLocked : "93109" @PayPalAccount = ConsentCodeOrAccessTokenIsRequired : "82901" CannotVaultOneTimeUsePayPalAccount : "82902" CannotHaveBothAccessTokenAndConsentCode : "82903" PayPalAccountsAreNotAccepted : "82904" CustomerIdIsRequiredForVaulting : "82905" TokenIsInUse : "9PI:KEY:<KEY>END_PI" PaymentMethodNonceConsumed : "92907" PaymentMethodNonceUnknown : "92908" PaymentMethodNonceLocked : "92909" PayPalCommunicationError : "92910" AuthExpired : "92911" CannotHaveFundingSourceWithoutAccessToken : "92912" InvalidFundingSourceSelection : "92913" CannotUpdatePayPalAccountUsingPaymentMethodNonce : "92914" @SEPABankAccount = IBANIsRequired : "93001" BICIsRequired : "93002" AccountHolderNameIsRequired : "93003" @SEPAMandate = AccountHolderNameIsRequired : "83301" BICIsRequired : "83302" IBANIsRequired : "83303" TypeIsRequired : "93304" IBANInvalidCharacter : "83305" BICInvalidCharacter : "83306" BICLengthIsInvalid : "83307" BICUnsupportedCountry : "83308" IBANUnsupportedCountry : "83309" IBANInvalidFormat : "83310" BillingAddressConflict : "93311" BillingAddressIdIsInvalid : "93312" TypeIsInvalid : "93313" @SettlementBatchSummary = SettlementDateIsInvalid : "82302" SettlementDateIsRequired : "82301" CustomFieldIsInvalid : "82303" @Subscription = BillingDayOfMonthCannotBeUpdated : "91918" BillingDayOfMonthIsInvalid : "91914" BillingDayOfMonthMustBeNumeric : "91913" CannotAddDuplicateAddonOrDiscount : "91911" CannotEditCanceledSubscription : "81901" CannotEditExpiredSubscription : "81910" CannotEditPriceChangingFieldsOnPastDueSubscription : "91920" FirstBillingDateCannotBeInThePast : "91916" FirstBillingDateCannotBeUpdated : "91919" FirstBillingDateIsInvalid : "91915" IdIsInUse : "81902" InconsistentNumberOfBillingCycles : "91908" InconsistentStartDate : "91917" InvalidRequestFormat : "91921" MerchantAccountIdIsInvalid : "91901" MismatchCurrencyISOCode : "91923" NumberOfBillingCyclesCannotBeBlank : "91912" NumberOfBillingCyclesIsTooSmall : "91909" NumberOfBillingCyclesMustBeGreaterThanZero : "91907" NumberOfBillingCyclesMustBeNumeric : "91906" PaymentMethodNonceCardTypeIsNotAccepted : "91924" PaymentMethodNonceIsInvalid : "91925" PaymentMethodNonceNotAssociatedWithCustomer : "91926" PaymentMethodNonceUnvaultedCardIsNotAccepted : "91927" PaymentMethodTokenCardTypeIsNotAccepted : "91902" PaymentMethodTokenIsInvalid : "PI:PASSWORD:<PASSWORD>END_PI" PaymentMethodTokenNotAssociatedWithCustomer : "PI:PASSWORD:<PASSWORD>END_PI" PlanBillingFrequencyCannotBeUpdated : "91922" PlanIdIsInvalid : "91904" PriceCannotBeBlank : "81903" PriceFormatIsInvalid : "81904" PriceIsTooLarge : "81923" StatusIsCanceled : "81905" TokenFormatIsInvalid : "PI:PASSWORD:<PASSWORD>END_PI" TrialDurationFormatIsInvalid : "81907" TrialDurationIsRequired : "81908" TrialDurationUnitIsInvalid : "81909" Modification: AmountCannotBeBlank : "92003" AmountIsInvalid : "92002" AmountIsTooLarge : "92023" CannotEditModificationsOnPastDueSubscription : "92022" CannotUpdateAndRemove : "92015" ExistingIdIsIncorrectKind : "92020" ExistingIdIsInvalid : "92011" ExistingIdIsRequired : "92012" IdToRemoveIsIncorrectKind : "92021" IdToRemoveIsInvalid : "92025" IdToRemoveIsNotPresent : "92016" InconsistentNumberOfBillingCycles : "92018" InheritedFromIdIsInvalid : "92013" InheritedFromIdIsRequired : "92014" Missing : "92024" NumberOfBillingCyclesCannotBeBlank : "92017" NumberOfBillingCyclesIsInvalid : "92005" NumberOfBillingCyclesMustBeGreaterThanZero : "92019" QuantityCannotBeBlank : "92004" QuantityIsInvalid : "92001" QuantityMustBeGreaterThanZero : "92010" @Transaction = AmountCannotBeNegative : "81501" AmountFormatIsInvalid : "81503" AmountIsRequired : "81502" AmountIsTooLarge : "81528" AmountMustBeGreaterThanZero : "81531" BillingAddressConflict : "91530" CannotBeVoided : "91504" CannotCancelRelease : "91562" CannotCloneCredit : "91543" CannotCloneTransactionWithPayPalAccount : "91573" CannotCloneTransactionWithVaultCreditCard : "91540" CannotCloneUnsuccessfulTransaction : "91542" CannotCloneVoiceAuthorizations : "91541" CannotHoldInEscrow : "91560" CannotPartiallyRefundEscrowedTransaction : "91563" CannotRefundCredit : "91505" CannotRefundUnlessSettled : "91506" CannotRefundWithPendingMerchantAccount : "91559" CannotRefundWithSuspendedMerchantAccount : "91538" CannotReleaseFromEscrow : "91561" CannotSubmitForSettlement : "91507" ChannelIsTooLong : "91550" CreditCardIsRequired : "91508" CustomFieldIsInvalid : "91526" CustomFieldIsTooLong : "81527" CustomerDefaultPaymentMethodCardTypeIsNotAccepted : "81509" CustomerDoesNotHaveCreditCard : "91511" CustomerIdIsInvalid : "91510" HasAlreadyBeenRefunded : "91512" MerchantAccountDoesNotSupportMOTO : "91558" MerchantAccountDoesNotSupportRefunds : "91547" MerchantAccountIdIsInvalid : "91513" MerchantAccountIsSuspended : "91514" Options: SubmitForSettlementIsRequiredForCloning : "91544" UseBillingForShippingDisabled : "91572" VaultIsDisabled : "91525" PayPal: CustomFieldTooLong : "91580" OrderIdIsTooLong : "91501" PaymentMethodConflict : "91515" PaymentMethodConflictWithVenmoSDK : "91549" PaymentMethodDoesNotBelongToCustomer : "91516" PaymentMethodDoesNotBelongToSubscription : "91527" PaymentMethodNonceCardTypeIsNotAccepted : "91567" PaymentMethodNonceConsumed : "91564" PaymentMethodNonceLocked : "91566" PaymentMethodNonceUnknown : "91565" PaymentMethodTokenCardTypeIsNotAccepted : "91517" PaymentMethodTokenIsInvalid : "PI:PASSWORD:<PASSWORD>END_PI" ProcessorAuthorizationCodeCannotBeSet : "91519" ProcessorAuthorizationCodeIsInvalid : "81520" ProcessorDoesNotSupportCredits : "91546" ProcessorDoesNotSupportVoiceAuthorizations : "91545" PurchaseOrderNumberIsInvalid : "91548" PurchaseOrderNumberIsTooLong : "91537" RefundAmountIsTooLarge : "91521" ServiceFeeAmountCannotBeNegative : "91554" ServiceFeeAmountFormatIsInvalid : "91555" ServiceFeeAmountIsTooLarge : "91556" ServiceFeeAmountNotAllowedOnMasterMerchantAccount : "91557" ServiceFeeIsNotAllowedOnCredits : "91552" ServiceFeeNotAcceptedForPayPal : "91578" SettlementAmountIsLessThanServiceFeeAmount : "91551" SettlementAmountIsTooLarge : "91522" ShippingAddressDoesntMatchCustomer : "91581" SubMerchantAccountRequiresServiceFeeAmount : "91553" SubscriptionDoesNotBelongToCustomer : "91529" SubscriptionIdIsInvalid : "91528" SubscriptionStatusMustBePastDue : "91531" TaxAmountCannotBeNegative : "81534" TaxAmountFormatIsInvalid : "81535" TaxAmountIsTooLarge : "81536" ThreeDSecureTokenIsInvalid : "PI:PASSWORD:<PASSWORD>END_PI" ThreeDSecureTransactionDataDoesntMatchVerify : "91570" TransactionSettlementAmountIsLessThanServiceFeeAmount : "91551" TypeIsInvalid : "91523" TypeIsRequired : "91524" UnsupportedVoiceAuthorization : "91539" CannotRefundSettlingTransaction : "91574" CannotSimulateSettlement : "91575" PaymentInstrumentNotSupportedByMerchantAccount : "91577" PayPalNotEnabled : "91576" PayPalAuthExpired : "91579" ThreeDSecureAuthenticationFailed : "81571" IndustryData: IndustryTypeIsInvalid : "93401" Lodging: EmptyData : "93402" FolioNumberIsInvalid : "93403" CheckInDateIsInvalid : "93404" CheckOutDateIsInvalid : "93405" CheckOutDateMustFollowCheckInDate : "93406" UnknownDataField : "93407" TravelCruise: EmptyData : "93408" UnknownDataField : "93409" TravelPackageIsInvalid : "93410" DepartureDateIsInvalid : "93411" CheckInDateIsInvalid : "93412" CheckOutDateIsInvalid : "93413" exports.ValidationErrorCodes = ValidationErrorCodes
[ { "context": "y: \"test\"\n source_password: \"abc123\"\n root_route: true\n seconds: ", "end": 245, "score": 0.9975334405899048, "start": 239, "tag": "PASSWORD", "value": "abc123" }, { "context": ": \"_test\"\n source_password: \"abc123\"\n root_route: true\n seconds: ", "end": 421, "score": 0.9980131983757019, "start": 415, "tag": "PASSWORD", "value": "abc123" }, { "context": "ormat: \"mp3\"\n stream_key: \"mp3-44100-64-s\"\n ffmpeg_args: \"-c:a libmp3lame -b:a 64", "end": 553, "score": 0.9996490478515625, "start": 539, "tag": "KEY", "value": "mp3-44100-64-s" }, { "context": ": \"_test\"\n source_password: \"abc123\"\n root_route: true\n seconds: ", "end": 689, "score": 0.9977148175239563, "start": 683, "tag": "PASSWORD", "value": "abc123" }, { "context": "ormat: \"aac\"\n stream_key: \"aac-44100-2-2\"\n ffmpeg_args: \"-c:a libfdk_aac|-b:a 64", "end": 820, "score": 0.9996557235717773, "start": 807, "tag": "KEY", "value": "aac-44100-2-2" } ]
test/sources/transcoding.coffee
firebrandv2/FirebrandNetwork.ga
342
_ = require "underscore" FileSource = $src "sources/file" TransSource = $src "sources/transcoding" AAC = $src "parsers/aac" Logger = $src "logger" FILE_STREAM = key: "test" source_password: "abc123" root_route: true seconds: 60*60*4 format: "mp3" TRANS_MP3_STREAM = key: "_test" source_password: "abc123" root_route: true seconds: 60*60*4 format: "mp3" stream_key: "mp3-44100-64-s" ffmpeg_args: "-c:a libmp3lame -b:a 64k" TRANS_AAC_STREAM = key: "_test" source_password: "abc123" root_route: true seconds: 60*60*4 format: "aac" stream_key: "aac-44100-2-2" ffmpeg_args: "-c:a libfdk_aac|-b:a 64k|-f:a adts" in_file = $file "aac-256.aac" describe "Transcoding Source", -> return true if process.env['SKIP_TRANSCODING'] logger = new Logger {stdout:false} file_source = null trans_source = null before (done) -> file_source = new FileSource format:"aac", filePath:in_file, chunkDuration:0.1 done() beforeEach (done) -> trans_source = new TransSource stream: file_source ffmpeg_args: TRANS_AAC_STREAM.ffmpeg_args format: "aac" stream_key: "test" discontinuityTimeout: 150 logger: logger done() afterEach (done) -> file_source.stop() trans_source.removeAllListeners("disconnect") trans_source.disconnect() done() it "emits a chunk of data", (done) -> this.timeout(4000) trans_source.once "disconnect", -> done new Error("Source disconnected. FFMPEG missing?") trans_source.once "data", (chunk) -> done() file_source.start() it "detects a discontinuity", (done) -> this.timeout(4000) trans_source.once "disconnect", -> done new Error("Source disconnected. FFMPEG missing?") # Once we get first data, stop and start the stream. We should # get events for each occasion, and we should get the stop within # the 100ms we set as our discontinuityTimeout above trans_source.once "data", (chunk) -> first_data = Number(new Date()) trans_source.once "discontinuity_begin", -> stopped = Number(new Date()) expect(stopped-first_data).to.be.below(200) trans_source.once "discontinuity_end", -> done() file_source.start() file_source.stop() file_source.start()
171133
_ = require "underscore" FileSource = $src "sources/file" TransSource = $src "sources/transcoding" AAC = $src "parsers/aac" Logger = $src "logger" FILE_STREAM = key: "test" source_password: "<PASSWORD>" root_route: true seconds: 60*60*4 format: "mp3" TRANS_MP3_STREAM = key: "_test" source_password: "<PASSWORD>" root_route: true seconds: 60*60*4 format: "mp3" stream_key: "<KEY>" ffmpeg_args: "-c:a libmp3lame -b:a 64k" TRANS_AAC_STREAM = key: "_test" source_password: "<PASSWORD>" root_route: true seconds: 60*60*4 format: "aac" stream_key: "<KEY>" ffmpeg_args: "-c:a libfdk_aac|-b:a 64k|-f:a adts" in_file = $file "aac-256.aac" describe "Transcoding Source", -> return true if process.env['SKIP_TRANSCODING'] logger = new Logger {stdout:false} file_source = null trans_source = null before (done) -> file_source = new FileSource format:"aac", filePath:in_file, chunkDuration:0.1 done() beforeEach (done) -> trans_source = new TransSource stream: file_source ffmpeg_args: TRANS_AAC_STREAM.ffmpeg_args format: "aac" stream_key: "test" discontinuityTimeout: 150 logger: logger done() afterEach (done) -> file_source.stop() trans_source.removeAllListeners("disconnect") trans_source.disconnect() done() it "emits a chunk of data", (done) -> this.timeout(4000) trans_source.once "disconnect", -> done new Error("Source disconnected. FFMPEG missing?") trans_source.once "data", (chunk) -> done() file_source.start() it "detects a discontinuity", (done) -> this.timeout(4000) trans_source.once "disconnect", -> done new Error("Source disconnected. FFMPEG missing?") # Once we get first data, stop and start the stream. We should # get events for each occasion, and we should get the stop within # the 100ms we set as our discontinuityTimeout above trans_source.once "data", (chunk) -> first_data = Number(new Date()) trans_source.once "discontinuity_begin", -> stopped = Number(new Date()) expect(stopped-first_data).to.be.below(200) trans_source.once "discontinuity_end", -> done() file_source.start() file_source.stop() file_source.start()
true
_ = require "underscore" FileSource = $src "sources/file" TransSource = $src "sources/transcoding" AAC = $src "parsers/aac" Logger = $src "logger" FILE_STREAM = key: "test" source_password: "PI:PASSWORD:<PASSWORD>END_PI" root_route: true seconds: 60*60*4 format: "mp3" TRANS_MP3_STREAM = key: "_test" source_password: "PI:PASSWORD:<PASSWORD>END_PI" root_route: true seconds: 60*60*4 format: "mp3" stream_key: "PI:KEY:<KEY>END_PI" ffmpeg_args: "-c:a libmp3lame -b:a 64k" TRANS_AAC_STREAM = key: "_test" source_password: "PI:PASSWORD:<PASSWORD>END_PI" root_route: true seconds: 60*60*4 format: "aac" stream_key: "PI:KEY:<KEY>END_PI" ffmpeg_args: "-c:a libfdk_aac|-b:a 64k|-f:a adts" in_file = $file "aac-256.aac" describe "Transcoding Source", -> return true if process.env['SKIP_TRANSCODING'] logger = new Logger {stdout:false} file_source = null trans_source = null before (done) -> file_source = new FileSource format:"aac", filePath:in_file, chunkDuration:0.1 done() beforeEach (done) -> trans_source = new TransSource stream: file_source ffmpeg_args: TRANS_AAC_STREAM.ffmpeg_args format: "aac" stream_key: "test" discontinuityTimeout: 150 logger: logger done() afterEach (done) -> file_source.stop() trans_source.removeAllListeners("disconnect") trans_source.disconnect() done() it "emits a chunk of data", (done) -> this.timeout(4000) trans_source.once "disconnect", -> done new Error("Source disconnected. FFMPEG missing?") trans_source.once "data", (chunk) -> done() file_source.start() it "detects a discontinuity", (done) -> this.timeout(4000) trans_source.once "disconnect", -> done new Error("Source disconnected. FFMPEG missing?") # Once we get first data, stop and start the stream. We should # get events for each occasion, and we should get the stop within # the 100ms we set as our discontinuityTimeout above trans_source.once "data", (chunk) -> first_data = Number(new Date()) trans_source.once "discontinuity_begin", -> stopped = Number(new Date()) expect(stopped-first_data).to.be.below(200) trans_source.once "discontinuity_end", -> done() file_source.start() file_source.stop() file_source.start()
[ { "context": "###\n\tFlexNav.js 1.3.3\n\n\tCreated by Jason Weaver http://jasonweaver.name\n\tReleased under http://un", "end": 47, "score": 0.9998155832290649, "start": 35, "tag": "NAME", "value": "Jason Weaver" } ]
coffeescripts/jquery.flexnav.coffee
Demoncheg28011989/flexnav
316
### FlexNav.js 1.3.3 Created by Jason Weaver http://jasonweaver.name Released under http://unlicense.org/ // ### # Use local alias for $.noConflict() compatibility $ = jQuery $.fn.flexNav = (options) -> settings = $.extend 'animationSpeed': 250, 'transitionOpacity': true, 'buttonSelector': '.menu-button', 'hoverIntent': false, 'hoverIntentTimeout': 150, 'calcItemWidths': false, 'hover': true options $nav = $(@) # Set some classes in the markup $nav.addClass('with-js') if settings.transitionOpacity is true $nav.addClass('opacity') $nav.find("li").each -> if $(@).has("ul").length $(@).addClass("item-with-ul").find("ul").hide() # Find the number of top level nav items and set widths if settings.calcItemWidths is true $top_nav_items = $nav.find('>li') count = $top_nav_items.length nav_width = 100 / count nav_percent = nav_width+"%" # Get the breakpoint set with data-breakpoint if $nav.data('breakpoint') then breakpoint = $nav.data('breakpoint') # Functions for hover support showMenu = -> if $nav.hasClass('lg-screen') is true and settings.hover is true if settings.transitionOpacity is true $(@).find('>ul') .addClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .addClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) resetMenu = -> if $nav.hasClass('lg-screen') is true and $(@).find('>ul').hasClass('flexnav-show') is true and settings.hover is true if settings.transitionOpacity is true $(@).find('>ul') .removeClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .removeClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) # Changing classes depending on viewport width and adding in hover support resizer = -> if $(window).width() <= breakpoint $nav.removeClass("lg-screen").addClass("sm-screen") if settings.calcItemWidths is true $top_nav_items.css('width','100%') selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button' $(selector).removeClass('active') # Toggle nav menu closed for one pager after anchor clicked $('.one-page li a').on( 'click', -> $nav.removeClass('flexnav-show') ) else if $(window).width() > breakpoint $nav.removeClass("sm-screen").addClass("lg-screen") if settings.calcItemWidths is true $top_nav_items.css('width',nav_percent) # Make sure navigation is closed when going back to large screens $nav.removeClass('flexnav-show').find('.item-with-ul').on() $('.item-with-ul').find('ul').removeClass('flexnav-show') resetMenu() if settings.hoverIntent is true # Requires hoverIntent jquery plugin http://cherne.net/brian/resources/jquery.hoverIntent.html $('.item-with-ul').hoverIntent( over: showMenu, out: resetMenu, timeout: settings.hoverIntentTimeout ) else if settings.hoverIntent is false $('.item-with-ul').on('mouseenter', showMenu).on('mouseleave', resetMenu) # Set navigation element for this instantiation $(settings['buttonSelector']).data('navEl', $nav) # Add in touch buttons touch_selector = '.item-with-ul, ' + settings['buttonSelector'] $(touch_selector).append('<span class="touch-button"><i class="navicon">&#9660;</i></span>') # Toggle touch for nav menu toggle_selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button' $(toggle_selector).on('click', (e) -> $(toggle_selector).toggleClass('active') e.preventDefault() e.stopPropagation() bs = settings['buttonSelector'] $btnParent = if ($(@).is(bs)) then $(@) else $(@).parent(bs) $thisNav = $btnParent.data('navEl') $thisNav.toggleClass('flexnav-show') ) # Toggle for sub-menus $('.touch-button').on('click', (e) -> $sub = $(@).parent('.item-with-ul').find('>ul') $touchButton = $(@).parent('.item-with-ul').find('>span.touch-button') # remove class of flexnav-show from all elements that are not current if $nav.hasClass('lg-screen') is true $(@).parent('.item-with-ul').siblings().find('ul.flexnav-show').removeClass('flexnav-show').hide() # add class of flexnav-show to current if $sub.hasClass('flexnav-show') is true $sub.removeClass('flexnav-show').slideUp(settings.animationSpeed) $touchButton.removeClass('active') else if $sub.hasClass('flexnav-show') is false $sub.addClass('flexnav-show').slideDown(settings.animationSpeed) $touchButton.addClass('active') ) # Sub ul's should have a class of 'open' if an element has focus $nav.find('.item-with-ul *').focus -> # remove class of open from all elements that are not focused $(@).parent('.item-with-ul').parent().find(".open").not(@).removeClass("open").hide() # add class of open to focused ul $(@).parent('.item-with-ul').find('>ul').addClass("open").show() # Call once to set resizer() # Call on browser resize $(window).on('resize', resizer)
126749
### FlexNav.js 1.3.3 Created by <NAME> http://jasonweaver.name Released under http://unlicense.org/ // ### # Use local alias for $.noConflict() compatibility $ = jQuery $.fn.flexNav = (options) -> settings = $.extend 'animationSpeed': 250, 'transitionOpacity': true, 'buttonSelector': '.menu-button', 'hoverIntent': false, 'hoverIntentTimeout': 150, 'calcItemWidths': false, 'hover': true options $nav = $(@) # Set some classes in the markup $nav.addClass('with-js') if settings.transitionOpacity is true $nav.addClass('opacity') $nav.find("li").each -> if $(@).has("ul").length $(@).addClass("item-with-ul").find("ul").hide() # Find the number of top level nav items and set widths if settings.calcItemWidths is true $top_nav_items = $nav.find('>li') count = $top_nav_items.length nav_width = 100 / count nav_percent = nav_width+"%" # Get the breakpoint set with data-breakpoint if $nav.data('breakpoint') then breakpoint = $nav.data('breakpoint') # Functions for hover support showMenu = -> if $nav.hasClass('lg-screen') is true and settings.hover is true if settings.transitionOpacity is true $(@).find('>ul') .addClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .addClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) resetMenu = -> if $nav.hasClass('lg-screen') is true and $(@).find('>ul').hasClass('flexnav-show') is true and settings.hover is true if settings.transitionOpacity is true $(@).find('>ul') .removeClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .removeClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) # Changing classes depending on viewport width and adding in hover support resizer = -> if $(window).width() <= breakpoint $nav.removeClass("lg-screen").addClass("sm-screen") if settings.calcItemWidths is true $top_nav_items.css('width','100%') selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button' $(selector).removeClass('active') # Toggle nav menu closed for one pager after anchor clicked $('.one-page li a').on( 'click', -> $nav.removeClass('flexnav-show') ) else if $(window).width() > breakpoint $nav.removeClass("sm-screen").addClass("lg-screen") if settings.calcItemWidths is true $top_nav_items.css('width',nav_percent) # Make sure navigation is closed when going back to large screens $nav.removeClass('flexnav-show').find('.item-with-ul').on() $('.item-with-ul').find('ul').removeClass('flexnav-show') resetMenu() if settings.hoverIntent is true # Requires hoverIntent jquery plugin http://cherne.net/brian/resources/jquery.hoverIntent.html $('.item-with-ul').hoverIntent( over: showMenu, out: resetMenu, timeout: settings.hoverIntentTimeout ) else if settings.hoverIntent is false $('.item-with-ul').on('mouseenter', showMenu).on('mouseleave', resetMenu) # Set navigation element for this instantiation $(settings['buttonSelector']).data('navEl', $nav) # Add in touch buttons touch_selector = '.item-with-ul, ' + settings['buttonSelector'] $(touch_selector).append('<span class="touch-button"><i class="navicon">&#9660;</i></span>') # Toggle touch for nav menu toggle_selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button' $(toggle_selector).on('click', (e) -> $(toggle_selector).toggleClass('active') e.preventDefault() e.stopPropagation() bs = settings['buttonSelector'] $btnParent = if ($(@).is(bs)) then $(@) else $(@).parent(bs) $thisNav = $btnParent.data('navEl') $thisNav.toggleClass('flexnav-show') ) # Toggle for sub-menus $('.touch-button').on('click', (e) -> $sub = $(@).parent('.item-with-ul').find('>ul') $touchButton = $(@).parent('.item-with-ul').find('>span.touch-button') # remove class of flexnav-show from all elements that are not current if $nav.hasClass('lg-screen') is true $(@).parent('.item-with-ul').siblings().find('ul.flexnav-show').removeClass('flexnav-show').hide() # add class of flexnav-show to current if $sub.hasClass('flexnav-show') is true $sub.removeClass('flexnav-show').slideUp(settings.animationSpeed) $touchButton.removeClass('active') else if $sub.hasClass('flexnav-show') is false $sub.addClass('flexnav-show').slideDown(settings.animationSpeed) $touchButton.addClass('active') ) # Sub ul's should have a class of 'open' if an element has focus $nav.find('.item-with-ul *').focus -> # remove class of open from all elements that are not focused $(@).parent('.item-with-ul').parent().find(".open").not(@).removeClass("open").hide() # add class of open to focused ul $(@).parent('.item-with-ul').find('>ul').addClass("open").show() # Call once to set resizer() # Call on browser resize $(window).on('resize', resizer)
true
### FlexNav.js 1.3.3 Created by PI:NAME:<NAME>END_PI http://jasonweaver.name Released under http://unlicense.org/ // ### # Use local alias for $.noConflict() compatibility $ = jQuery $.fn.flexNav = (options) -> settings = $.extend 'animationSpeed': 250, 'transitionOpacity': true, 'buttonSelector': '.menu-button', 'hoverIntent': false, 'hoverIntentTimeout': 150, 'calcItemWidths': false, 'hover': true options $nav = $(@) # Set some classes in the markup $nav.addClass('with-js') if settings.transitionOpacity is true $nav.addClass('opacity') $nav.find("li").each -> if $(@).has("ul").length $(@).addClass("item-with-ul").find("ul").hide() # Find the number of top level nav items and set widths if settings.calcItemWidths is true $top_nav_items = $nav.find('>li') count = $top_nav_items.length nav_width = 100 / count nav_percent = nav_width+"%" # Get the breakpoint set with data-breakpoint if $nav.data('breakpoint') then breakpoint = $nav.data('breakpoint') # Functions for hover support showMenu = -> if $nav.hasClass('lg-screen') is true and settings.hover is true if settings.transitionOpacity is true $(@).find('>ul') .addClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .addClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) resetMenu = -> if $nav.hasClass('lg-screen') is true and $(@).find('>ul').hasClass('flexnav-show') is true and settings.hover is true if settings.transitionOpacity is true $(@).find('>ul') .removeClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .removeClass('flexnav-show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) # Changing classes depending on viewport width and adding in hover support resizer = -> if $(window).width() <= breakpoint $nav.removeClass("lg-screen").addClass("sm-screen") if settings.calcItemWidths is true $top_nav_items.css('width','100%') selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button' $(selector).removeClass('active') # Toggle nav menu closed for one pager after anchor clicked $('.one-page li a').on( 'click', -> $nav.removeClass('flexnav-show') ) else if $(window).width() > breakpoint $nav.removeClass("sm-screen").addClass("lg-screen") if settings.calcItemWidths is true $top_nav_items.css('width',nav_percent) # Make sure navigation is closed when going back to large screens $nav.removeClass('flexnav-show').find('.item-with-ul').on() $('.item-with-ul').find('ul').removeClass('flexnav-show') resetMenu() if settings.hoverIntent is true # Requires hoverIntent jquery plugin http://cherne.net/brian/resources/jquery.hoverIntent.html $('.item-with-ul').hoverIntent( over: showMenu, out: resetMenu, timeout: settings.hoverIntentTimeout ) else if settings.hoverIntent is false $('.item-with-ul').on('mouseenter', showMenu).on('mouseleave', resetMenu) # Set navigation element for this instantiation $(settings['buttonSelector']).data('navEl', $nav) # Add in touch buttons touch_selector = '.item-with-ul, ' + settings['buttonSelector'] $(touch_selector).append('<span class="touch-button"><i class="navicon">&#9660;</i></span>') # Toggle touch for nav menu toggle_selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button' $(toggle_selector).on('click', (e) -> $(toggle_selector).toggleClass('active') e.preventDefault() e.stopPropagation() bs = settings['buttonSelector'] $btnParent = if ($(@).is(bs)) then $(@) else $(@).parent(bs) $thisNav = $btnParent.data('navEl') $thisNav.toggleClass('flexnav-show') ) # Toggle for sub-menus $('.touch-button').on('click', (e) -> $sub = $(@).parent('.item-with-ul').find('>ul') $touchButton = $(@).parent('.item-with-ul').find('>span.touch-button') # remove class of flexnav-show from all elements that are not current if $nav.hasClass('lg-screen') is true $(@).parent('.item-with-ul').siblings().find('ul.flexnav-show').removeClass('flexnav-show').hide() # add class of flexnav-show to current if $sub.hasClass('flexnav-show') is true $sub.removeClass('flexnav-show').slideUp(settings.animationSpeed) $touchButton.removeClass('active') else if $sub.hasClass('flexnav-show') is false $sub.addClass('flexnav-show').slideDown(settings.animationSpeed) $touchButton.addClass('active') ) # Sub ul's should have a class of 'open' if an element has focus $nav.find('.item-with-ul *').focus -> # remove class of open from all elements that are not focused $(@).parent('.item-with-ul').parent().find(".open").not(@).removeClass("open").hide() # add class of open to focused ul $(@).parent('.item-with-ul').find('>ul').addClass("open").show() # Call once to set resizer() # Call on browser resize $(window).on('resize', resizer)
[ { "context": "join} = require 'path'\n\nmodule.exports =\n name: 'Claru'\n debug: true\n apiPrefix: '/v1'\n", "end": 56, "score": 0.9977871179580688, "start": 51, "tag": "NAME", "value": "Claru" } ]
server/config/default.coffee
stevelacy/claru
0
{join} = require 'path' module.exports = name: 'Claru' debug: true apiPrefix: '/v1'
160075
{join} = require 'path' module.exports = name: '<NAME>' debug: true apiPrefix: '/v1'
true
{join} = require 'path' module.exports = name: 'PI:NAME:<NAME>END_PI' debug: true apiPrefix: '/v1'
[ { "context": "SendInvites\n teamsHelpers.inviteUser browser, 'admin', null, yes\n browser.pause 1000, callback\n\n\n ", "end": 9435, "score": 0.8499637842178345, "start": 9430, "tag": "USERNAME", "value": "admin" }, { "context": "sswordSelector\n .setValue passwordSelector, '1234'\n .click confirmButton\n .waitForElement", "end": 11743, "score": 0.9990484118461609, "start": 11739, "tag": "PASSWORD", "value": "1234" }, { "context": "passwordSelector\n .setValue passwordSelector, targetUser1.password\n .click confirmButton\n .assert.urlConta", "end": 12115, "score": 0.9789186716079712, "start": 12095, "tag": "PASSWORD", "value": "targetUser1.password" } ]
client/test/lib/helpers/myteamhelpers.coffee
lionheart1022/koding
0
utils = require '../utils/utils.js' helpers = require '../helpers/helpers.js' teamsHelpers = require '../helpers/teamshelpers.js' myTeamLink = "#{helpers.getUrl(yes)}/Home/my-team" welcomeLink = "#{helpers.getUrl(yes)}/Welcome" sectionSelector = '.HomeAppView--section.team-settings' sectionSendInvites = '.HomeAppView--section.send-invites' 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' logo = '.HomeAppView--uploadLogo .teamLogo-wrapper' defaultLogoPath = "#{helpers.getUrl(yes)}/a/images/logos/sidebar_footer_logo.svg" localImage = "#{__dirname}/koding.jpeg" localImage = require('path').resolve(localImage) imagePath = require('path').resolve('sidebar_footer_logo.svg') teamLogo = '.HomeAppView--uploadLogo .uploadInputWrapper .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' closeModal = '.close-icon.closeModal' welcomeView = '.WelcomeStacksView' leaveTeamButton = '.HomeAppView--button' passwordSelector = 'input[name=password]' forgotPasswordButton = '.kdbutton.cancel' confirmButton = 'button[type=submit]' notification = '.kdnotification.main' proceedButton = '[testpath=proceed]' mainSideBar = '.main-sidebar' 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 # uploadAndRemoveLogo: (browser, callback) -> # aaa = require('path').resolve("#{__dirname}", 'koding.jpeg') # console.log(imagePath); # console.log(aaa) # browser # .waitForElementVisible logo, 20000 # .setValue '.HomeAppView--uploadLogo .uploadInputWrapper', aaa inviteAndJoinToTeam: (browser, host, callback) -> browser .url welcomeLink .pause 2000 { invitations, index } = utils.getInvitationData() index = if index is 0 then 0 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' user = utils.getUser no, 1 lastPendingInvitationIndex = 0 pendingInvitations = [] invitations.forEach (invitation, i) -> unless invitation.accepted if invitation.email isnt user.email pendingInvitations.push i lastPendingInvitationIndex = i browser .url myTeamLink .waitForElementVisible sectionSelector, 20000 .scrollToElement "#{teammateSectionSelector} .ListView" .waitForElementVisible selector(pendingInvitations[0] + 1), 20000 .click selector(pendingInvitations[0] + 1), -> teamsHelpers.checkTeammates browser, invitations[pendingInvitations[0]], nthItem(1), nthItem(2), selector(1), no, -> #resend invitation browser.waitForElementVisible selector(pendingInvitations[0] + 1), 20000 browser.click selector(indexOfTargetUser1 + 1), -> teamsHelpers.checkTeammates browser, invitations[indexOfTargetUser1], nthItem(1), nthItem(2), selector(indexOfTargetUser1 + 1), no, -> #make admin then member browser.click selector(indexOfTargetUser2 + 1), -> #make admin 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, 'InvalidUserName', -> 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) -> browser .url myTeamLink .waitForElementVisible sectionSelector, 20000 .scrollToElement '.HomeAppView--section.send-invites' teamsHelpers.fillInviteInputByIndex browser, 2, invitations[indexOfTargetUser1].email browser .waitForElementVisible sendInvitesButton, 5000 .click sendInvitesButton browser .waitForElementVisible '.ContentModal', 20000 .assert.containsText '.ContentModal.content-modal main', "#{invitations[indexOfTargetUser1].email} is already a member of your team" .click proceedButton teamsHelpers.clearInviteInputByIndex browser, 2 browser.pause 2000, callback sendAlreadyAdminInvite: (browser, callback) -> browser.refresh() browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.fillInviteInputByIndex browser, 1, invitations[indexOfTargetUser2].email browser .waitForElementVisible sendInvitesButton, 30000 .click sendInvitesButton browser .waitForElementVisible '.ContentModal', 20000 .assert.containsText '.ContentModal.content-modal header', "You're adding an admin" .waitForElementVisible proceedButton, 20000 .click proceedButton .waitForElementVisible '.ContentModal', 20000 .assert.containsText '.ContentModal.content-modal main', "#{invitations[indexOfTargetUser2].email} is already a member of your team" .click proceedButton browser.pause 3000, callback sendInviteToPendingMember: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'member', invitations[indexOfTargetUser1 + 1].email, no browser.pause 1000, callback sendNewAdminInvite: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'admin', null, yes browser.pause 1000, callback sendNewMemberInvite: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'member', null, yes browser.pause 1000, callback sendInviteAll: (browser, callback) -> teamsHelpers.inviteAll browser browser.pause 3000, callback #Member can not change team name and team logo changeTeamName: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 targetUser1 = invitations[indexOfTargetUser3] teamsHelpers.logoutTeam browser, (res) -> teamsHelpers.loginToTeam browser, targetUser1 , no, '', -> browser .waitForElementVisible welcomeView, 60000 .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[indexOfTargetUser3] 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) teamsHelpers.loginToTeam browser, targetUser1 , yes, 'NotAllowedEmail', -> browser .pause 1000, callback checkAdmin: (browser, callback) -> user = invitations[indexOfTargetUser2] teamsHelpers.logoutTeam browser, (res) -> teamsHelpers.loginToTeam browser, user, no, '', -> browser.pause 2000 browser.element 'css selector', closeModal, (result) -> if result.status is 0 browser.waitForElementVisible closeModal, 30000 browser.click closeModal browser .click '#main-sidebar' .waitForElementVisible '#kdmaincontainer.with-sidebar #main-sidebar .logo-wrapper .team-name', 20000 .click '#kdmaincontainer.with-sidebar #main-sidebar .logo-wrapper .team-name' .waitForElementVisible '.HomeAppView-Nav--role', 30000 .assert.containsText '.HomeAppView-Nav--role', 'Admin' .pause 1000, callback sendInviteToRegisteredUser: (browser, callback) -> registeredUser = utils.getUser no, 9 browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'member', registeredUser.email, yes browser.pause 1000, callback selector = (index) -> ".HomeApp-Teammate--ListItem:nth-of-type(#{index}) .dropdown " nthItem = (index) -> ".ButtonWithMenuItemsList li:nth-of-type(#{index})"
122601
utils = require '../utils/utils.js' helpers = require '../helpers/helpers.js' teamsHelpers = require '../helpers/teamshelpers.js' myTeamLink = "#{helpers.getUrl(yes)}/Home/my-team" welcomeLink = "#{helpers.getUrl(yes)}/Welcome" sectionSelector = '.HomeAppView--section.team-settings' sectionSendInvites = '.HomeAppView--section.send-invites' 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' logo = '.HomeAppView--uploadLogo .teamLogo-wrapper' defaultLogoPath = "#{helpers.getUrl(yes)}/a/images/logos/sidebar_footer_logo.svg" localImage = "#{__dirname}/koding.jpeg" localImage = require('path').resolve(localImage) imagePath = require('path').resolve('sidebar_footer_logo.svg') teamLogo = '.HomeAppView--uploadLogo .uploadInputWrapper .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' closeModal = '.close-icon.closeModal' welcomeView = '.WelcomeStacksView' leaveTeamButton = '.HomeAppView--button' passwordSelector = 'input[name=password]' forgotPasswordButton = '.kdbutton.cancel' confirmButton = 'button[type=submit]' notification = '.kdnotification.main' proceedButton = '[testpath=proceed]' mainSideBar = '.main-sidebar' 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 # uploadAndRemoveLogo: (browser, callback) -> # aaa = require('path').resolve("#{__dirname}", 'koding.jpeg') # console.log(imagePath); # console.log(aaa) # browser # .waitForElementVisible logo, 20000 # .setValue '.HomeAppView--uploadLogo .uploadInputWrapper', aaa inviteAndJoinToTeam: (browser, host, callback) -> browser .url welcomeLink .pause 2000 { invitations, index } = utils.getInvitationData() index = if index is 0 then 0 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' user = utils.getUser no, 1 lastPendingInvitationIndex = 0 pendingInvitations = [] invitations.forEach (invitation, i) -> unless invitation.accepted if invitation.email isnt user.email pendingInvitations.push i lastPendingInvitationIndex = i browser .url myTeamLink .waitForElementVisible sectionSelector, 20000 .scrollToElement "#{teammateSectionSelector} .ListView" .waitForElementVisible selector(pendingInvitations[0] + 1), 20000 .click selector(pendingInvitations[0] + 1), -> teamsHelpers.checkTeammates browser, invitations[pendingInvitations[0]], nthItem(1), nthItem(2), selector(1), no, -> #resend invitation browser.waitForElementVisible selector(pendingInvitations[0] + 1), 20000 browser.click selector(indexOfTargetUser1 + 1), -> teamsHelpers.checkTeammates browser, invitations[indexOfTargetUser1], nthItem(1), nthItem(2), selector(indexOfTargetUser1 + 1), no, -> #make admin then member browser.click selector(indexOfTargetUser2 + 1), -> #make admin 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, 'InvalidUserName', -> 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) -> browser .url myTeamLink .waitForElementVisible sectionSelector, 20000 .scrollToElement '.HomeAppView--section.send-invites' teamsHelpers.fillInviteInputByIndex browser, 2, invitations[indexOfTargetUser1].email browser .waitForElementVisible sendInvitesButton, 5000 .click sendInvitesButton browser .waitForElementVisible '.ContentModal', 20000 .assert.containsText '.ContentModal.content-modal main', "#{invitations[indexOfTargetUser1].email} is already a member of your team" .click proceedButton teamsHelpers.clearInviteInputByIndex browser, 2 browser.pause 2000, callback sendAlreadyAdminInvite: (browser, callback) -> browser.refresh() browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.fillInviteInputByIndex browser, 1, invitations[indexOfTargetUser2].email browser .waitForElementVisible sendInvitesButton, 30000 .click sendInvitesButton browser .waitForElementVisible '.ContentModal', 20000 .assert.containsText '.ContentModal.content-modal header', "You're adding an admin" .waitForElementVisible proceedButton, 20000 .click proceedButton .waitForElementVisible '.ContentModal', 20000 .assert.containsText '.ContentModal.content-modal main', "#{invitations[indexOfTargetUser2].email} is already a member of your team" .click proceedButton browser.pause 3000, callback sendInviteToPendingMember: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'member', invitations[indexOfTargetUser1 + 1].email, no browser.pause 1000, callback sendNewAdminInvite: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'admin', null, yes browser.pause 1000, callback sendNewMemberInvite: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'member', null, yes browser.pause 1000, callback sendInviteAll: (browser, callback) -> teamsHelpers.inviteAll browser browser.pause 3000, callback #Member can not change team name and team logo changeTeamName: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 targetUser1 = invitations[indexOfTargetUser3] teamsHelpers.logoutTeam browser, (res) -> teamsHelpers.loginToTeam browser, targetUser1 , no, '', -> browser .waitForElementVisible welcomeView, 60000 .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[indexOfTargetUser3] 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) teamsHelpers.loginToTeam browser, targetUser1 , yes, 'NotAllowedEmail', -> browser .pause 1000, callback checkAdmin: (browser, callback) -> user = invitations[indexOfTargetUser2] teamsHelpers.logoutTeam browser, (res) -> teamsHelpers.loginToTeam browser, user, no, '', -> browser.pause 2000 browser.element 'css selector', closeModal, (result) -> if result.status is 0 browser.waitForElementVisible closeModal, 30000 browser.click closeModal browser .click '#main-sidebar' .waitForElementVisible '#kdmaincontainer.with-sidebar #main-sidebar .logo-wrapper .team-name', 20000 .click '#kdmaincontainer.with-sidebar #main-sidebar .logo-wrapper .team-name' .waitForElementVisible '.HomeAppView-Nav--role', 30000 .assert.containsText '.HomeAppView-Nav--role', 'Admin' .pause 1000, callback sendInviteToRegisteredUser: (browser, callback) -> registeredUser = utils.getUser no, 9 browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'member', registeredUser.email, yes browser.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" welcomeLink = "#{helpers.getUrl(yes)}/Welcome" sectionSelector = '.HomeAppView--section.team-settings' sectionSendInvites = '.HomeAppView--section.send-invites' 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' logo = '.HomeAppView--uploadLogo .teamLogo-wrapper' defaultLogoPath = "#{helpers.getUrl(yes)}/a/images/logos/sidebar_footer_logo.svg" localImage = "#{__dirname}/koding.jpeg" localImage = require('path').resolve(localImage) imagePath = require('path').resolve('sidebar_footer_logo.svg') teamLogo = '.HomeAppView--uploadLogo .uploadInputWrapper .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' closeModal = '.close-icon.closeModal' welcomeView = '.WelcomeStacksView' leaveTeamButton = '.HomeAppView--button' passwordSelector = 'input[name=password]' forgotPasswordButton = '.kdbutton.cancel' confirmButton = 'button[type=submit]' notification = '.kdnotification.main' proceedButton = '[testpath=proceed]' mainSideBar = '.main-sidebar' 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 # uploadAndRemoveLogo: (browser, callback) -> # aaa = require('path').resolve("#{__dirname}", 'koding.jpeg') # console.log(imagePath); # console.log(aaa) # browser # .waitForElementVisible logo, 20000 # .setValue '.HomeAppView--uploadLogo .uploadInputWrapper', aaa inviteAndJoinToTeam: (browser, host, callback) -> browser .url welcomeLink .pause 2000 { invitations, index } = utils.getInvitationData() index = if index is 0 then 0 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' user = utils.getUser no, 1 lastPendingInvitationIndex = 0 pendingInvitations = [] invitations.forEach (invitation, i) -> unless invitation.accepted if invitation.email isnt user.email pendingInvitations.push i lastPendingInvitationIndex = i browser .url myTeamLink .waitForElementVisible sectionSelector, 20000 .scrollToElement "#{teammateSectionSelector} .ListView" .waitForElementVisible selector(pendingInvitations[0] + 1), 20000 .click selector(pendingInvitations[0] + 1), -> teamsHelpers.checkTeammates browser, invitations[pendingInvitations[0]], nthItem(1), nthItem(2), selector(1), no, -> #resend invitation browser.waitForElementVisible selector(pendingInvitations[0] + 1), 20000 browser.click selector(indexOfTargetUser1 + 1), -> teamsHelpers.checkTeammates browser, invitations[indexOfTargetUser1], nthItem(1), nthItem(2), selector(indexOfTargetUser1 + 1), no, -> #make admin then member browser.click selector(indexOfTargetUser2 + 1), -> #make admin 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, 'InvalidUserName', -> 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) -> browser .url myTeamLink .waitForElementVisible sectionSelector, 20000 .scrollToElement '.HomeAppView--section.send-invites' teamsHelpers.fillInviteInputByIndex browser, 2, invitations[indexOfTargetUser1].email browser .waitForElementVisible sendInvitesButton, 5000 .click sendInvitesButton browser .waitForElementVisible '.ContentModal', 20000 .assert.containsText '.ContentModal.content-modal main', "#{invitations[indexOfTargetUser1].email} is already a member of your team" .click proceedButton teamsHelpers.clearInviteInputByIndex browser, 2 browser.pause 2000, callback sendAlreadyAdminInvite: (browser, callback) -> browser.refresh() browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.fillInviteInputByIndex browser, 1, invitations[indexOfTargetUser2].email browser .waitForElementVisible sendInvitesButton, 30000 .click sendInvitesButton browser .waitForElementVisible '.ContentModal', 20000 .assert.containsText '.ContentModal.content-modal header', "You're adding an admin" .waitForElementVisible proceedButton, 20000 .click proceedButton .waitForElementVisible '.ContentModal', 20000 .assert.containsText '.ContentModal.content-modal main', "#{invitations[indexOfTargetUser2].email} is already a member of your team" .click proceedButton browser.pause 3000, callback sendInviteToPendingMember: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'member', invitations[indexOfTargetUser1 + 1].email, no browser.pause 1000, callback sendNewAdminInvite: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'admin', null, yes browser.pause 1000, callback sendNewMemberInvite: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'member', null, yes browser.pause 1000, callback sendInviteAll: (browser, callback) -> teamsHelpers.inviteAll browser browser.pause 3000, callback #Member can not change team name and team logo changeTeamName: (browser, callback) -> browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 targetUser1 = invitations[indexOfTargetUser3] teamsHelpers.logoutTeam browser, (res) -> teamsHelpers.loginToTeam browser, targetUser1 , no, '', -> browser .waitForElementVisible welcomeView, 60000 .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[indexOfTargetUser3] 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) teamsHelpers.loginToTeam browser, targetUser1 , yes, 'NotAllowedEmail', -> browser .pause 1000, callback checkAdmin: (browser, callback) -> user = invitations[indexOfTargetUser2] teamsHelpers.logoutTeam browser, (res) -> teamsHelpers.loginToTeam browser, user, no, '', -> browser.pause 2000 browser.element 'css selector', closeModal, (result) -> if result.status is 0 browser.waitForElementVisible closeModal, 30000 browser.click closeModal browser .click '#main-sidebar' .waitForElementVisible '#kdmaincontainer.with-sidebar #main-sidebar .logo-wrapper .team-name', 20000 .click '#kdmaincontainer.with-sidebar #main-sidebar .logo-wrapper .team-name' .waitForElementVisible '.HomeAppView-Nav--role', 30000 .assert.containsText '.HomeAppView-Nav--role', 'Admin' .pause 1000, callback sendInviteToRegisteredUser: (browser, callback) -> registeredUser = utils.getUser no, 9 browser.url myTeamLink browser .waitForElementVisible sectionSelector, 20000 .scrollToElement sectionSendInvites teamsHelpers.inviteUser browser, 'member', registeredUser.email, yes browser.pause 1000, callback selector = (index) -> ".HomeApp-Teammate--ListItem:nth-of-type(#{index}) .dropdown " nthItem = (index) -> ".ButtonWithMenuItemsList li:nth-of-type(#{index})"
[ { "context": "ser.name is process.env.LOCAL_USER && user.pass is process.env.LOCAL_PASSWORD\n return next()\n else\n return unauthorized(", "end": 376, "score": 0.9133318662643433, "start": 350, "tag": "PASSWORD", "value": "process.env.LOCAL_PASSWORD" } ]
lib/auth.coffee
arenahq/surround-audience
0
basicAuth = require 'basic-auth' module.exports = (req, res, next) -> unauthorized = (res) -> res.set 'WWW-Authenticate', 'Basic realm=Authorization Required' return res.sendStatus(401) user = basicAuth(req) if !user or !user.name or !user.pass return unauthorized(res) if user.name is process.env.LOCAL_USER && user.pass is process.env.LOCAL_PASSWORD return next() else return unauthorized(res)
147300
basicAuth = require 'basic-auth' module.exports = (req, res, next) -> unauthorized = (res) -> res.set 'WWW-Authenticate', 'Basic realm=Authorization Required' return res.sendStatus(401) user = basicAuth(req) if !user or !user.name or !user.pass return unauthorized(res) if user.name is process.env.LOCAL_USER && user.pass is <PASSWORD> return next() else return unauthorized(res)
true
basicAuth = require 'basic-auth' module.exports = (req, res, next) -> unauthorized = (res) -> res.set 'WWW-Authenticate', 'Basic realm=Authorization Required' return res.sendStatus(401) user = basicAuth(req) if !user or !user.name or !user.pass return unauthorized(res) if user.name is process.env.LOCAL_USER && user.pass is PI:PASSWORD:<PASSWORD>END_PI return next() else return unauthorized(res)
[ { "context": "v class=\"form-group\">\n <label for=\"username\">Username</label>\n <input type=\"te", "end": 626, "score": 0.9986538290977478, "start": 618, "tag": "USERNAME", "value": "username" }, { "context": "orm-group\">\n <label for=\"username\">Username</label>\n <input type=\"text\" class=", "end": 636, "score": 0.9891058802604675, "start": 628, "tag": "USERNAME", "value": "Username" }, { "context": " <input type=\"text\" class=\"form-control\" id=\"username\" placeholder=\"Username\" ng-model=\"user.username\">", "end": 713, "score": 0.9969212412834167, "start": 705, "tag": "USERNAME", "value": "username" }, { "context": "\" class=\"form-control\" id=\"username\" placeholder=\"Username\" ng-model=\"user.username\">\n </div>\n ", "end": 736, "score": 0.9979315996170044, "start": 728, "tag": "USERNAME", "value": "Username" }, { "context": "=\"username\" placeholder=\"Username\" ng-model=\"user.username\">\n </div>\n <div class=\"", "end": 761, "score": 0.9650569558143616, "start": 753, "tag": "USERNAME", "value": "username" }, { "context": "v class=\"form-group\">\n <label for=\"password\">Password</label>\n <input type=\"pa", "end": 860, "score": 0.6900317072868347, "start": 852, "tag": "PASSWORD", "value": "password" }, { "context": "rd\">Password</label>\n <input type=\"password\" class=\"form-control\" id=\"password\" placeholder=\"", "end": 916, "score": 0.9810742139816284, "start": 908, "tag": "PASSWORD", "value": "password" }, { "context": "\" class=\"form-control\" id=\"password\" placeholder=\"Password\" ng-model=\"user.password\">\n </div>\n ", "end": 974, "score": 0.9965787529945374, "start": 966, "tag": "PASSWORD", "value": "Password" } ]
ModelCatalogueCorePlugin/grails-app/assets/javascripts/modelcatalogue/core/ui/bs/modalPromptLogin.coffee
tumtumtree/tumtumtree
0
angular.module('mc.core.ui.bs.modalPromptLogin', ['mc.util.messages', 'ngCookies']).config ['messagesProvider', (messagesProvider)-> factory = [ '$modal', '$q', 'messages', 'security', ($modal, $q, messages, security) -> -> dialog = $modal.open { windowClass: 'login-modal-prompt' template: ''' <div class="modal-header"> <h4>Login</h4> </div> <div class="modal-body"> <messages-panel messages="messages"></messages-panel> <form role="form" ng-submit="login()"> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" placeholder="Username" ng-model="user.username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" placeholder="Password" ng-model="user.password"> </div> <div class="checkbox"> <label> <input type="checkbox" ng-model="user.rememberMe"> Remember Me </label> </div> <button type="submit" class="hide" ng-click="login()"></button> </form> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success" ng-click="login()" ng-disabled="!user.username || !user.password"><span class="glyphicon glyphicon-ok"></span> Login</button> <button class="btn btn-warning" ng-click="$dismiss()">Cancel</button> </div> ''' controller: ['$scope', '$cookies', 'messages', 'security', '$modalInstance', '$log', ($scope, $cookies, messages, security, $modalInstance) -> $scope.user = {rememberMe: $cookies.mc_remember_me == "true"} $scope.messages = messages.createNewMessages() $scope.login = -> security.login($scope.user.username, $scope.user.password, $scope.user.rememberMe).then (success)-> if success.data.error $scope.messages.error success.data.error else if success.data.errors for error in success.data.errors $scope.messages.error error else $cookies.mc_remember_me = $scope.user.rememberMe $modalInstance.close success ] } dialog.result ] messagesProvider.setPromptFactory 'login', factory ]
42926
angular.module('mc.core.ui.bs.modalPromptLogin', ['mc.util.messages', 'ngCookies']).config ['messagesProvider', (messagesProvider)-> factory = [ '$modal', '$q', 'messages', 'security', ($modal, $q, messages, security) -> -> dialog = $modal.open { windowClass: 'login-modal-prompt' template: ''' <div class="modal-header"> <h4>Login</h4> </div> <div class="modal-body"> <messages-panel messages="messages"></messages-panel> <form role="form" ng-submit="login()"> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" placeholder="Username" ng-model="user.username"> </div> <div class="form-group"> <label for="<PASSWORD>">Password</label> <input type="<PASSWORD>" class="form-control" id="password" placeholder="<PASSWORD>" ng-model="user.password"> </div> <div class="checkbox"> <label> <input type="checkbox" ng-model="user.rememberMe"> Remember Me </label> </div> <button type="submit" class="hide" ng-click="login()"></button> </form> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success" ng-click="login()" ng-disabled="!user.username || !user.password"><span class="glyphicon glyphicon-ok"></span> Login</button> <button class="btn btn-warning" ng-click="$dismiss()">Cancel</button> </div> ''' controller: ['$scope', '$cookies', 'messages', 'security', '$modalInstance', '$log', ($scope, $cookies, messages, security, $modalInstance) -> $scope.user = {rememberMe: $cookies.mc_remember_me == "true"} $scope.messages = messages.createNewMessages() $scope.login = -> security.login($scope.user.username, $scope.user.password, $scope.user.rememberMe).then (success)-> if success.data.error $scope.messages.error success.data.error else if success.data.errors for error in success.data.errors $scope.messages.error error else $cookies.mc_remember_me = $scope.user.rememberMe $modalInstance.close success ] } dialog.result ] messagesProvider.setPromptFactory 'login', factory ]
true
angular.module('mc.core.ui.bs.modalPromptLogin', ['mc.util.messages', 'ngCookies']).config ['messagesProvider', (messagesProvider)-> factory = [ '$modal', '$q', 'messages', 'security', ($modal, $q, messages, security) -> -> dialog = $modal.open { windowClass: 'login-modal-prompt' template: ''' <div class="modal-header"> <h4>Login</h4> </div> <div class="modal-body"> <messages-panel messages="messages"></messages-panel> <form role="form" ng-submit="login()"> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" placeholder="Username" ng-model="user.username"> </div> <div class="form-group"> <label for="PI:PASSWORD:<PASSWORD>END_PI">Password</label> <input type="PI:PASSWORD:<PASSWORD>END_PI" class="form-control" id="password" placeholder="PI:PASSWORD:<PASSWORD>END_PI" ng-model="user.password"> </div> <div class="checkbox"> <label> <input type="checkbox" ng-model="user.rememberMe"> Remember Me </label> </div> <button type="submit" class="hide" ng-click="login()"></button> </form> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success" ng-click="login()" ng-disabled="!user.username || !user.password"><span class="glyphicon glyphicon-ok"></span> Login</button> <button class="btn btn-warning" ng-click="$dismiss()">Cancel</button> </div> ''' controller: ['$scope', '$cookies', 'messages', 'security', '$modalInstance', '$log', ($scope, $cookies, messages, security, $modalInstance) -> $scope.user = {rememberMe: $cookies.mc_remember_me == "true"} $scope.messages = messages.createNewMessages() $scope.login = -> security.login($scope.user.username, $scope.user.password, $scope.user.rememberMe).then (success)-> if success.data.error $scope.messages.error success.data.error else if success.data.errors for error in success.data.errors $scope.messages.error error else $cookies.mc_remember_me = $scope.user.rememberMe $modalInstance.close success ] } dialog.result ] messagesProvider.setPromptFactory 'login', factory ]
[ { "context": "s['breve'] =\n\tglyphName: 'breve'\n\tcharacterName: 'BREVE ACCENT'\n\tanchors:\n\t\t0:\n\t\t\tx: parentAnchors[0].x\n\t\t\ty: pa", "end": 75, "score": 0.9930568933486938, "start": 63, "tag": "NAME", "value": "BREVE ACCENT" } ]
src/glyphs/components/breve.coffee
byte-foundry/john-fell
1
exports.glyphs['breve'] = glyphName: 'breve' characterName: 'BREVE ACCENT' anchors: 0: x: parentAnchors[0].x y: parentAnchors[0].y + 70 tags: [ 'component', 'diacritic' ] contours: 0: skeleton: true closed: false nodes: 0: x: anchors[0].x - 110 * width - ( 20 / 85 ) * thickness y: anchors[0].y + 115 dirOut: - 90 + ( 5 / 85 ) * thickness + 'deg' expand: Object({ width: thickness * ( 18 / 85 ) angle: 8 + 'deg' distr: 0.25 }) 1: x: anchors[0].x y: anchors[0].y + 45 - overshoot dirOut: 0 + 'deg' type: 'smooth' expand: Object({ width: thickness * ( 60 / 85 ) angle: 90 + 'deg' distr: 0.75 }) 2: x: anchors[0].x + ( anchors[0].x - contours[0].nodes[0].expandedTo[1].x ) y: contours[0].nodes[0].y dirIn: - 90 - ( 5 / 85 ) * thickness + 'deg' expand: Object({ width: thickness * ( 18 / 85 ) angle: 172 + 'deg' distr: 1 })
184736
exports.glyphs['breve'] = glyphName: 'breve' characterName: '<NAME>' anchors: 0: x: parentAnchors[0].x y: parentAnchors[0].y + 70 tags: [ 'component', 'diacritic' ] contours: 0: skeleton: true closed: false nodes: 0: x: anchors[0].x - 110 * width - ( 20 / 85 ) * thickness y: anchors[0].y + 115 dirOut: - 90 + ( 5 / 85 ) * thickness + 'deg' expand: Object({ width: thickness * ( 18 / 85 ) angle: 8 + 'deg' distr: 0.25 }) 1: x: anchors[0].x y: anchors[0].y + 45 - overshoot dirOut: 0 + 'deg' type: 'smooth' expand: Object({ width: thickness * ( 60 / 85 ) angle: 90 + 'deg' distr: 0.75 }) 2: x: anchors[0].x + ( anchors[0].x - contours[0].nodes[0].expandedTo[1].x ) y: contours[0].nodes[0].y dirIn: - 90 - ( 5 / 85 ) * thickness + 'deg' expand: Object({ width: thickness * ( 18 / 85 ) angle: 172 + 'deg' distr: 1 })
true
exports.glyphs['breve'] = glyphName: 'breve' characterName: 'PI:NAME:<NAME>END_PI' anchors: 0: x: parentAnchors[0].x y: parentAnchors[0].y + 70 tags: [ 'component', 'diacritic' ] contours: 0: skeleton: true closed: false nodes: 0: x: anchors[0].x - 110 * width - ( 20 / 85 ) * thickness y: anchors[0].y + 115 dirOut: - 90 + ( 5 / 85 ) * thickness + 'deg' expand: Object({ width: thickness * ( 18 / 85 ) angle: 8 + 'deg' distr: 0.25 }) 1: x: anchors[0].x y: anchors[0].y + 45 - overshoot dirOut: 0 + 'deg' type: 'smooth' expand: Object({ width: thickness * ( 60 / 85 ) angle: 90 + 'deg' distr: 0.75 }) 2: x: anchors[0].x + ( anchors[0].x - contours[0].nodes[0].expandedTo[1].x ) y: contours[0].nodes[0].y dirIn: - 90 - ( 5 / 85 ) * thickness + 'deg' expand: Object({ width: thickness * ( 18 / 85 ) angle: 172 + 'deg' distr: 1 })
[ { "context": "ee: Github organization class\n#\n# Copyright ยฉ 2011 Pavan Kumar Sunkara. All rights reserved\n#\n\n# Requiring modules\n\n# In", "end": 82, "score": 0.9998349547386169, "start": 63, "tag": "NAME", "value": "Pavan Kumar Sunkara" }, { "context": " GET\n members: (cb) ->\n @client.get \"/orgs/#{@name}/members\", (err, s, b) ->\n return cb(err) i", "end": 1649, "score": 0.5455758571624756, "start": 1645, "tag": "USERNAME", "value": "name" }, { "context": "rganization's member.\n # '/orgs/flatiron/members/pksunkara' GET\n member: (user, cb) ->\n @client.getNoFol", "end": 1855, "score": 0.9985464811325073, "start": 1846, "tag": "USERNAME", "value": "pksunkara" } ]
src/octonode/org.coffee
troupe/octonode
0
# # org.coffee: Github organization class # # Copyright ยฉ 2011 Pavan Kumar Sunkara. All rights reserved # # Requiring modules # Initiate class class Org constructor: (@name, @client) -> # Get an organization # '/orgs/flatiron' GET info: (cb) -> @client.get "/orgs/#{@name}", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org info error')) else cb null, b # Edit an organization # '/orgs/flatiron' POST update: (info, cb) -> @client.post "/orgs/#{@name}", info, (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org update error')) else cb null, b # List organization repositories # '/orgs/flatiron/repos' GET repos: (cbOrRepo, cb) -> if typeof cb is 'function' and typeof cbOrRepo is 'object' @createRepo cbOrRepo, cb else cb = cbOrRepo @client.get "/orgs/#{@name}/repos", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org repos error')) else cb null, b # Create an organisation repository # '/orgs/flatiron/repos' POST createRepo: (repo, cb) -> @client.post "/orgs/#{@name}/repos", repo, (err, s, b) -> return cb(err) if err if s isnt 201 then cb(new Error('Org createRepo error')) else cb null, b # Get an organization's teams. # '/orgs/flatiron/teams' GET teams: (cb) -> @client.get "/orgs/#{@name}/teams", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org teams error')) else cb null, b # Get an organization's members. # '/orgs/flatiron/members' GET members: (cb) -> @client.get "/orgs/#{@name}/members", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org members error')) else cb null, b # Check an organization's member. # '/orgs/flatiron/members/pksunkara' GET member: (user, cb) -> @client.getNoFollow "/orgs/#{@name}/members/#{user}", (err, s, b) -> return cb(err) if err cb null, s is 204 # Export module module.exports = Org
108335
# # org.coffee: Github organization class # # Copyright ยฉ 2011 <NAME>. All rights reserved # # Requiring modules # Initiate class class Org constructor: (@name, @client) -> # Get an organization # '/orgs/flatiron' GET info: (cb) -> @client.get "/orgs/#{@name}", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org info error')) else cb null, b # Edit an organization # '/orgs/flatiron' POST update: (info, cb) -> @client.post "/orgs/#{@name}", info, (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org update error')) else cb null, b # List organization repositories # '/orgs/flatiron/repos' GET repos: (cbOrRepo, cb) -> if typeof cb is 'function' and typeof cbOrRepo is 'object' @createRepo cbOrRepo, cb else cb = cbOrRepo @client.get "/orgs/#{@name}/repos", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org repos error')) else cb null, b # Create an organisation repository # '/orgs/flatiron/repos' POST createRepo: (repo, cb) -> @client.post "/orgs/#{@name}/repos", repo, (err, s, b) -> return cb(err) if err if s isnt 201 then cb(new Error('Org createRepo error')) else cb null, b # Get an organization's teams. # '/orgs/flatiron/teams' GET teams: (cb) -> @client.get "/orgs/#{@name}/teams", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org teams error')) else cb null, b # Get an organization's members. # '/orgs/flatiron/members' GET members: (cb) -> @client.get "/orgs/#{@name}/members", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org members error')) else cb null, b # Check an organization's member. # '/orgs/flatiron/members/pksunkara' GET member: (user, cb) -> @client.getNoFollow "/orgs/#{@name}/members/#{user}", (err, s, b) -> return cb(err) if err cb null, s is 204 # Export module module.exports = Org
true
# # org.coffee: Github organization class # # Copyright ยฉ 2011 PI:NAME:<NAME>END_PI. All rights reserved # # Requiring modules # Initiate class class Org constructor: (@name, @client) -> # Get an organization # '/orgs/flatiron' GET info: (cb) -> @client.get "/orgs/#{@name}", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org info error')) else cb null, b # Edit an organization # '/orgs/flatiron' POST update: (info, cb) -> @client.post "/orgs/#{@name}", info, (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org update error')) else cb null, b # List organization repositories # '/orgs/flatiron/repos' GET repos: (cbOrRepo, cb) -> if typeof cb is 'function' and typeof cbOrRepo is 'object' @createRepo cbOrRepo, cb else cb = cbOrRepo @client.get "/orgs/#{@name}/repos", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org repos error')) else cb null, b # Create an organisation repository # '/orgs/flatiron/repos' POST createRepo: (repo, cb) -> @client.post "/orgs/#{@name}/repos", repo, (err, s, b) -> return cb(err) if err if s isnt 201 then cb(new Error('Org createRepo error')) else cb null, b # Get an organization's teams. # '/orgs/flatiron/teams' GET teams: (cb) -> @client.get "/orgs/#{@name}/teams", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org teams error')) else cb null, b # Get an organization's members. # '/orgs/flatiron/members' GET members: (cb) -> @client.get "/orgs/#{@name}/members", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Org members error')) else cb null, b # Check an organization's member. # '/orgs/flatiron/members/pksunkara' GET member: (user, cb) -> @client.getNoFollow "/orgs/#{@name}/members/#{user}", (err, s, b) -> return cb(err) if err cb null, s is 204 # Export module module.exports = Org
[ { "context": "class @Zahlen\n @language: 'en'\n @locales:\n en:\n error", "end": 13, "score": 0.9694592952728271, "start": 6, "tag": "USERNAME", "value": "@Zahlen" }, { "context": "invalido.'\n card_holdername: \"El nombre del titular es invalido.\"\n rejected: 'ยกLo sentimos", "end": 1154, "score": 0.6254279613494873, "start": 1151, "tag": "NAME", "value": "tit" } ]
app/assets/javascripts/zahlen/zahlen.js.coffee
Actiun/zahlen
1
class @Zahlen @language: 'en' @locales: en: errors: not_valid: 'The card information is not a valid. Please check the errors marked on red.' card_number: 'Credit card number is invalid.' card_exp: 'The expiration date is invalid.' card_exp_month: 'The expiration month is invalid.' card_exp_year: 'The expiration year is invalid.' card_cvc: 'The cvc is invalid.' card_holdername: "The cardholder's name is invalid." rejected: 'Sorry! Your payment data was declined. Please try again or try a new card.' timeout: 'This seems to be taking too long. Please contact support and give them transaction ID: ' es: errors: not_valid: 'La informaciรณn de la tarjeta es invalida. Por favor revisa los campos marcados en rojo.' card_number: 'El nรบmero de la tarjeta es invalido.' card_exp: 'La fecha de expiraciรณn es invalida.' card_exp_month: 'El mes de expiraciรณn es invalido.' card_exp_year: 'El aรฑo de expiraciรณn es invalido.' card_cvc: 'El cรณdigo de seguridad es invalido.' card_holdername: "El nombre del titular es invalido." rejected: 'ยกLo sentimos! Pero tu pago fue decliado por la instituciรณn bancaria. Por favor intentalo de nuevo' timeout: 'Al parecer ha tomado mucho tiempo validar tu transaciรณn. Por favor contacta a nuestro equipo de soporte y proporcionales el siguiente identificador de transacciรณn: ' @locale: -> Zahlen.locales[@language]
125817
class @Zahlen @language: 'en' @locales: en: errors: not_valid: 'The card information is not a valid. Please check the errors marked on red.' card_number: 'Credit card number is invalid.' card_exp: 'The expiration date is invalid.' card_exp_month: 'The expiration month is invalid.' card_exp_year: 'The expiration year is invalid.' card_cvc: 'The cvc is invalid.' card_holdername: "The cardholder's name is invalid." rejected: 'Sorry! Your payment data was declined. Please try again or try a new card.' timeout: 'This seems to be taking too long. Please contact support and give them transaction ID: ' es: errors: not_valid: 'La informaciรณn de la tarjeta es invalida. Por favor revisa los campos marcados en rojo.' card_number: 'El nรบmero de la tarjeta es invalido.' card_exp: 'La fecha de expiraciรณn es invalida.' card_exp_month: 'El mes de expiraciรณn es invalido.' card_exp_year: 'El aรฑo de expiraciรณn es invalido.' card_cvc: 'El cรณdigo de seguridad es invalido.' card_holdername: "El nombre del <NAME>ular es invalido." rejected: 'ยกLo sentimos! Pero tu pago fue decliado por la instituciรณn bancaria. Por favor intentalo de nuevo' timeout: 'Al parecer ha tomado mucho tiempo validar tu transaciรณn. Por favor contacta a nuestro equipo de soporte y proporcionales el siguiente identificador de transacciรณn: ' @locale: -> Zahlen.locales[@language]
true
class @Zahlen @language: 'en' @locales: en: errors: not_valid: 'The card information is not a valid. Please check the errors marked on red.' card_number: 'Credit card number is invalid.' card_exp: 'The expiration date is invalid.' card_exp_month: 'The expiration month is invalid.' card_exp_year: 'The expiration year is invalid.' card_cvc: 'The cvc is invalid.' card_holdername: "The cardholder's name is invalid." rejected: 'Sorry! Your payment data was declined. Please try again or try a new card.' timeout: 'This seems to be taking too long. Please contact support and give them transaction ID: ' es: errors: not_valid: 'La informaciรณn de la tarjeta es invalida. Por favor revisa los campos marcados en rojo.' card_number: 'El nรบmero de la tarjeta es invalido.' card_exp: 'La fecha de expiraciรณn es invalida.' card_exp_month: 'El mes de expiraciรณn es invalido.' card_exp_year: 'El aรฑo de expiraciรณn es invalido.' card_cvc: 'El cรณdigo de seguridad es invalido.' card_holdername: "El nombre del PI:NAME:<NAME>END_PIular es invalido." rejected: 'ยกLo sentimos! Pero tu pago fue decliado por la instituciรณn bancaria. Por favor intentalo de nuevo' timeout: 'Al parecer ha tomado mucho tiempo validar tu transaciรณn. Por favor contacta a nuestro equipo de soporte y proporcionales el siguiente identificador de transacciรณn: ' @locale: -> Zahlen.locales[@language]
[ { "context": "settings: number_of_shards: 9\nP.src.oadoi._key = 'doi'\nP.src.oadoi._prefix = false\n\nP.src.oadoi.hybrid ", "end": 386, "score": 0.9605943560600281, "start": 383, "tag": "KEY", "value": "doi" } ]
worker/src/src/oadoi.coffee
oaworks/paradigm
1
S.src.oadoi ?= {} try S.src.oadoi = JSON.parse SECRETS_OADOI P.src.oadoi = (doi) -> doi ?= @params?.oadoi ? @params?.doi if typeof doi is 'string' and doi.startsWith '10.' await @sleep 900 url = 'https://api.oadoi.org/v2/' + doi + '?email=' + S.mail.to return @fetch url else return P.src.oadoi._index = settings: number_of_shards: 9 P.src.oadoi._key = 'doi' P.src.oadoi._prefix = false P.src.oadoi.hybrid = (issns) -> # there is a concern OADOI sometimes says a journal is closed on a particular # record when it is actually a hybrid. So check if at least 1% of records for # a given journal are hybrid, and if so the whole journal is hybrid. issns ?= @params.hybrid ? @params.issn ? @params.issns if typeof issns is 'object' and not Array.isArray issns issns = issns.journal_issns ? issns.ISSN issns = issns.replace(/\s/g, '').split(',') if typeof issns is 'string' if Array.isArray(issns) and issns.length q = 'journal_issns:"' + issns.join('" OR journals_issns:"') + '"' closed = await @src.oadoi.count q + ' AND oa_status:"closed"' q = '(' + q + ')' if q.includes ' OR ' hybrid = await @src.oadoi.count q + ' AND oa_status:"hybrid"' if closed and hybrid / closed > .001 return true else return false else return #ย if we ever decide to use title search on oadoi (only covers crossref anyway so no additional benefit to us at the moment): # https://support.unpaywall.org/support/solutions/articles/44001977396-how-do-i-use-the-title-search-api-
190953
S.src.oadoi ?= {} try S.src.oadoi = JSON.parse SECRETS_OADOI P.src.oadoi = (doi) -> doi ?= @params?.oadoi ? @params?.doi if typeof doi is 'string' and doi.startsWith '10.' await @sleep 900 url = 'https://api.oadoi.org/v2/' + doi + '?email=' + S.mail.to return @fetch url else return P.src.oadoi._index = settings: number_of_shards: 9 P.src.oadoi._key = '<KEY>' P.src.oadoi._prefix = false P.src.oadoi.hybrid = (issns) -> # there is a concern OADOI sometimes says a journal is closed on a particular # record when it is actually a hybrid. So check if at least 1% of records for # a given journal are hybrid, and if so the whole journal is hybrid. issns ?= @params.hybrid ? @params.issn ? @params.issns if typeof issns is 'object' and not Array.isArray issns issns = issns.journal_issns ? issns.ISSN issns = issns.replace(/\s/g, '').split(',') if typeof issns is 'string' if Array.isArray(issns) and issns.length q = 'journal_issns:"' + issns.join('" OR journals_issns:"') + '"' closed = await @src.oadoi.count q + ' AND oa_status:"closed"' q = '(' + q + ')' if q.includes ' OR ' hybrid = await @src.oadoi.count q + ' AND oa_status:"hybrid"' if closed and hybrid / closed > .001 return true else return false else return #ย if we ever decide to use title search on oadoi (only covers crossref anyway so no additional benefit to us at the moment): # https://support.unpaywall.org/support/solutions/articles/44001977396-how-do-i-use-the-title-search-api-
true
S.src.oadoi ?= {} try S.src.oadoi = JSON.parse SECRETS_OADOI P.src.oadoi = (doi) -> doi ?= @params?.oadoi ? @params?.doi if typeof doi is 'string' and doi.startsWith '10.' await @sleep 900 url = 'https://api.oadoi.org/v2/' + doi + '?email=' + S.mail.to return @fetch url else return P.src.oadoi._index = settings: number_of_shards: 9 P.src.oadoi._key = 'PI:KEY:<KEY>END_PI' P.src.oadoi._prefix = false P.src.oadoi.hybrid = (issns) -> # there is a concern OADOI sometimes says a journal is closed on a particular # record when it is actually a hybrid. So check if at least 1% of records for # a given journal are hybrid, and if so the whole journal is hybrid. issns ?= @params.hybrid ? @params.issn ? @params.issns if typeof issns is 'object' and not Array.isArray issns issns = issns.journal_issns ? issns.ISSN issns = issns.replace(/\s/g, '').split(',') if typeof issns is 'string' if Array.isArray(issns) and issns.length q = 'journal_issns:"' + issns.join('" OR journals_issns:"') + '"' closed = await @src.oadoi.count q + ' AND oa_status:"closed"' q = '(' + q + ')' if q.includes ' OR ' hybrid = await @src.oadoi.count q + ' AND oa_status:"hybrid"' if closed and hybrid / closed > .001 return true else return false else return #ย if we ever decide to use title search on oadoi (only covers crossref anyway so no additional benefit to us at the moment): # https://support.unpaywall.org/support/solutions/articles/44001977396-how-do-i-use-the-title-search-api-
[ { "context": "ap = null\n\nwindow.fn.sensors =\n \"1002\": { name: 'ะœะธะปะฐะดะธะฝะพะฒั†ะธ' }\n \"11888f3a-bc5e-4a0c-9f27-702984decedf\": { na", "end": 103, "score": 0.9992879033088684, "start": 92, "tag": "NAME", "value": "ะœะธะปะฐะดะธะฝะพะฒั†ะธ" }, { "context": " \"11888f3a-bc5e-4a0c-9f27-702984decedf\": { name: 'ะœะ—ะข' }\n \"01440b05-255d-4764-be87-bdf135f32289\": { na", "end": 161, "score": 0.9863445162773132, "start": 158, "tag": "NAME", "value": "ะœะ—ะข" }, { "context": " \"01440b05-255d-4764-be87-bdf135f32289\": { name: 'ะ‘ะฐั€ะดะพะฒั†ะธ' }\n \"bb948861-3fd7-47dd-b986-cb13c9732725\": { na", "end": 224, "score": 0.998824417591095, "start": 216, "tag": "NAME", "value": "ะ‘ะฐั€ะดะพะฒั†ะธ" }, { "context": " \"bb948861-3fd7-47dd-b986-cb13c9732725\": { name: 'ะ‘ะธัะตั€' }\n \"cec29ba1-5414-4cf3-bbcc-8ce4db1da5d0\": { na", "end": 284, "score": 0.9970125555992126, "start": 279, "tag": "NAME", "value": "ะ‘ะธัะตั€" }, { "context": " \"cec29ba1-5414-4cf3-bbcc-8ce4db1da5d0\": { name: 'ะะปัƒะผะธะฝะบะฐ' }\n \"1005\": { name: 'ะ ะตะบั‚ะพั€ะฐั‚' }\n \"bc9f31ea-bf3", "end": 347, "score": 0.9973844289779663, "start": 339, "tag": "NAME", "value": "ะะปัƒะผะธะฝะบะฐ" }, { "context": "b1da5d0\": { name: 'ะะปัƒะผะธะฝะบะฐ' }\n \"1005\": { name: 'ะ ะตะบั‚ะพั€ะฐั‚' }\n \"bc9f31ea-bf3d-416c-86b5-ecba6e98bb24\": { na", "end": 378, "score": 0.9923564195632935, "start": 370, "tag": "NAME", "value": "ะ ะตะบั‚ะพั€ะฐั‚" }, { "context": " \"bc9f31ea-bf3d-416c-86b5-ecba6e98bb24\": { name: 'ะคะพะฝั‚ะฐะฝะฐ' }\n \"66710fdc-cdfc-4bbe-93a8-7e796fb8a88d\": { na", "end": 440, "score": 0.9961207509040833, "start": 433, "tag": "NAME", "value": "ะคะพะฝั‚ะฐะฝะฐ" }, { "context": " \"66710fdc-cdfc-4bbe-93a8-7e796fb8a88d\": { name: 'ะšะพะทะปะต' }\n \"24eaebc2-ca62-49ff-8b22-880bc131b69f\": { na", "end": 500, "score": 0.9806832671165466, "start": 495, "tag": "NAME", "value": "ะšะพะทะปะต" }, { "context": " \"24eaebc2-ca62-49ff-8b22-880bc131b69f\": { name: 'ะฆั€ะฝะธั‡ะต' }\n \"b79604bb-0bea-454f-a474-849156e418ea\": { na", "end": 561, "score": 0.8675186038017273, "start": 555, "tag": "NAME", "value": "ะฆั€ะฝะธั‡ะต" }, { "context": " \"b79604bb-0bea-454f-a474-849156e418ea\": { name: 'ะ”ั€ะฐั‡ะตะฒะพ' }\n \"1004\": { name: 'ะ“ะฐะทะธะฑะฐะฑะฐ' }\n \"fc4bfa77-f79", "end": 623, "score": 0.9917769432067871, "start": 616, "tag": "NAME", "value": "ะ”ั€ะฐั‡ะตะฒะพ" }, { "context": "56e418ea\": { name: 'ะ”ั€ะฐั‡ะตะฒะพ' }\n \"1004\": { name: 'ะ“ะฐะทะธะฑะฐะฑะฐ' }\n \"fc4bfa77-f791-4f93-8c0c-62d8306c599c\": { na", "end": 654, "score": 0.9985273480415344, "start": 646, "tag": "NAME", "value": "ะ“ะฐะทะธะฑะฐะฑะฐ" }, { "context": " \"fc4bfa77-f791-4f93-8c0c-62d8306c599c\": { name: 'ะะตั€ะตะทะธ' }\n \"cfb0a034-6e29-4803-be02-9215dcac17a8\": { na", "end": 715, "score": 0.9444172978401184, "start": 709, "tag": "NAME", "value": "ะะตั€ะตะทะธ" }, { "context": " \"cfb0a034-6e29-4803-be02-9215dcac17a8\": { name: 'ะƒะพั€ั‡ะต ะŸะตั‚ั€ะพะฒ' }\n \"1003\": { name: 'ะšะฐั€ะฟะพัˆ' }\n \"200cdb67-8dc5-", "end": 782, "score": 0.9989885091781616, "start": 770, "tag": "NAME", "value": "ะƒะพั€ั‡ะต ะŸะตั‚ั€ะพะฒ" }, { "context": "7a8\": { name: 'ะƒะพั€ั‡ะต ะŸะตั‚ั€ะพะฒ' }\n \"1003\": { name: 'ะšะฐั€ะฟะพัˆ' }\n \"200cdb67-8dc5-4dcf-ac62-748db636e04e\": { na", "end": 811, "score": 0.9906498193740845, "start": 805, "tag": "NAME", "value": "ะšะฐั€ะฟะพัˆ" }, { "context": " \"200cdb67-8dc5-4dcf-ac62-748db636e04e\": { name: '11ั‚ะธ ะžะบั‚ะพะผะฒั€ะธ' }\n \"8d415fa0-77dc-4cb3-8460-a9159800917f\": { na", "end": 879, "score": 0.9750887751579285, "start": 866, "tag": "NAME", "value": "11ั‚ะธ ะžะบั‚ะพะผะฒั€ะธ" }, { "context": "d415fa0-77dc-4cb3-8460-a9159800917f\": { name: 'ะกะ” ะ“ะพั†ะต ะ”ะตะปั‡ะตะฒ' }\n \"b80e5cd2-76cb-40bf-b784-2a0a312e6264\": { na", "end": 948, "score": 0.6522433757781982, "start": 937, "tag": "NAME", "value": "ะ“ะพั†ะต ะ”ะตะปั‡ะตะฒ" }, { "context": "5cd2-76cb-40bf-b784-2a0a312e6264\": { name: 'ะกั‚ะฐะฝะธั†ะฐ ะƒะพั€ั‡ะต' }\n \"6380c7cc-df23-4512-ad10-f2b363000579\"", "end": 1010, "score": 0.5875617861747742, "start": 1009, "tag": "NAME", "value": "ะฐ" }, { "context": "d2-76cb-40bf-b784-2a0a312e6264\": { name: 'ะกั‚ะฐะฝะธั†ะฐ ะƒะพั€ั‡ะต' }\n \"6380c7cc-df23-4512-ad10-f2b363000579\": { na", "end": 1016, "score": 0.8085969090461731, "start": 1011, "tag": "NAME", "value": "ะƒะพั€ั‡ะต" }, { "context": " \"6380c7cc-df23-4512-ad10-f2b363000579\": { name: 'ะกะพะฟะธัˆั‚ะต' }\n \"eaae3b5f-bd71-46f9-85d5-8d3a19c96322\"", "end": 1072, "score": 0.6269584894180298, "start": 1071, "tag": "NAME", "value": "ะก" }, { "context": "380c7cc-df23-4512-ad10-f2b363000579\": { name: 'ะกะพะฟะธัˆั‚ะต' }\n \"eaae3b5f-bd71-46f9-85d5-8d3a19c96322\": { na", "end": 1078, "score": 0.7005588412284851, "start": 1074, "tag": "NAME", "value": "ะธัˆั‚ะต" }, { "context": "\"eaae3b5f-bd71-46f9-85d5-8d3a19c96322\": { name: 'ะšะฐั€ะฟะพัˆ 2' }\n \"7c497bfd-36b6-4eed-9172-37fd70f17c48\": { ", "end": 1139, "score": 0.6081220507621765, "start": 1134, "tag": "NAME", "value": "ะฐั€ะฟะพัˆ" }, { "context": " \"7c497bfd-36b6-4eed-9172-37fd70f17c48\": { name: 'ะ–ะตะปะตะทะฐั€ะฐ' }\n \"1000\": { name: 'ะฆะตะฝั‚ะฐั€' }\n \"3d7bd712-24a9-", "end": 1204, "score": 0.9861214756965637, "start": 1196, "tag": "NAME", "value": "ะ–ะตะปะตะทะฐั€ะฐ" }, { "context": "0f17c48\": { name: 'ะ–ะตะปะตะทะฐั€ะฐ' }\n \"1000\": { name: 'ะฆะตะฝั‚ะฐั€' }\n \"3d7bd712-24a9-482c-b387-a8168b12d3f4\": { na", "end": 1233, "score": 0.9909624457359314, "start": 1227, "tag": "NAME", "value": "ะฆะตะฝั‚ะฐั€" }, { "context": " \"3d7bd712-24a9-482c-b387-a8168b12d3f4\": { name: 'ะ‘ัƒั‚ะตะป 1' }\n \"5f718e32-5491-4c3c-98ff-45dc9e287df4\": { na", "end": 1295, "score": 0.8704212307929993, "start": 1288, "tag": "NAME", "value": "ะ‘ัƒั‚ะตะป 1" }, { "context": " \"5f718e32-5491-4c3c-98ff-45dc9e287df4\": { name: 'ะ’ะพะดะฝะพ' }\n \"e7a05c01-1d5c-479a-a5a5-419f28cebeef\": ", "end": 1351, "score": 0.7034516334533691, "start": 1350, "tag": "NAME", "value": "ะ’" }, { "context": "f718e32-5491-4c3c-98ff-45dc9e287df4\": { name: 'ะ’ะพะดะฝะพ' }\n \"e7a05c01-1d5c-479a-a5a5-419f28cebeef\": { na", "end": 1355, "score": 0.592768132686615, "start": 1353, "tag": "NAME", "value": "ะฝะพ" }, { "context": " \"e7a05c01-1d5c-479a-a5a5-419f28cebeef\": { name: 'ะ˜ะทะปะตั‚' }\n \"1001\": { name: 'ะ›ะธัะธั‡ะต'}\n \"8ad9e315-0e23-4", "end": 1415, "score": 0.8657245635986328, "start": 1410, "tag": "NAME", "value": "ะ˜ะทะปะตั‚" }, { "context": "9f28cebeef\": { name: 'ะ˜ะทะปะตั‚' }\n \"1001\": { name: 'ะ›ะธัะธั‡ะต'}\n \"8ad9e315-0e23-4dc0-a26f-ba5a17d4d7ed\": { nam", "end": 1444, "score": 0.9992138147354126, "start": 1438, "tag": "NAME", "value": "ะ›ะธัะธั‡ะต" }, { "context": " \"8ad9e315-0e23-4dc0-a26f-ba5a17d4d7ed\": { name: 'ะะตั€ะพะดั€ะพะผ'}\n \"680b0098-7c4d-44cf-acb1-dc4031e93d34\": { nam", "end": 1506, "score": 0.9997984766960144, "start": 1498, "tag": "NAME", "value": "ะะตั€ะพะดั€ะพะผ" }, { "context": " \"680b0098-7c4d-44cf-acb1-dc4031e93d34\": { name: 'ะ˜ะปะธะฝะดะตะฝ'}\n\nwindow.fn.loadSensors = () ->\n content = $('#", "end": 1567, "score": 0.9998291730880737, "start": 1560, "tag": "NAME", "value": "ะ˜ะปะธะฝะดะตะฝ" }, { "context": "98, 21.42361109 ]\n CITY = 'skopje'\n USERNAME = \"atonevski\"\n PASSWORD = \"pv1530kay\"\n\n parsePos = (s) ->\n ", "end": 3590, "score": 0.9996891617774963, "start": 3581, "tag": "USERNAME", "value": "atonevski" }, { "context": "= 'skopje'\n USERNAME = \"atonevski\"\n PASSWORD = \"pv1530kay\"\n\n parsePos = (s) ->\n s.split /\\s*,\\s*/\n ", "end": 3615, "score": 0.9992026686668396, "start": 3606, "tag": "PASSWORD", "value": "pv1530kay" }, { "context": "l: url\n method: 'GET'\n username: USERNAME\n password: PASSWORD\n dataType: ", "end": 4460, "score": 0.9996353387832642, "start": 4452, "tag": "USERNAME", "value": "USERNAME" }, { "context": "'\n username: USERNAME\n password: PASSWORD\n dataType: \"json\"\n headers:\n ", "end": 4489, "score": 0.999313473701477, "start": 4481, "tag": "PASSWORD", "value": "PASSWORD" }, { "context": "/rest/data24h\"\n method: 'GET'\n username: USERNAME\n password: PASSWORD\n .done (d) ->\n #", "end": 7796, "score": 0.9995962381362915, "start": 7788, "tag": "USERNAME", "value": "USERNAME" }, { "context": "od: 'GET'\n username: USERNAME\n password: PASSWORD\n .done (d) ->\n # console.log d\n # we", "end": 7821, "score": 0.9988940954208374, "start": 7813, "tag": "PASSWORD", "value": "PASSWORD" }, { "context": "o/rest/sensor\"\n method: 'GET'\n username: USERNAME\n password: PASSWORD\n .done (d) ->\n #", "end": 8697, "score": 0.9996196031570435, "start": 8689, "tag": "USERNAME", "value": "USERNAME" }, { "context": "od: 'GET'\n username: USERNAME\n password: PASSWORD\n .done (d) ->\n # console.log d\n for ", "end": 8722, "score": 0.997964084148407, "start": 8714, "tag": "PASSWORD", "value": "PASSWORD" } ]
www/coffee/sensors.coffee
atonevski/skp-ons
0
# # MAP # # Leaflet MAP window.fn.sensorMap = null window.fn.sensors = "1002": { name: 'ะœะธะปะฐะดะธะฝะพะฒั†ะธ' } "11888f3a-bc5e-4a0c-9f27-702984decedf": { name: 'ะœะ—ะข' } "01440b05-255d-4764-be87-bdf135f32289": { name: 'ะ‘ะฐั€ะดะพะฒั†ะธ' } "bb948861-3fd7-47dd-b986-cb13c9732725": { name: 'ะ‘ะธัะตั€' } "cec29ba1-5414-4cf3-bbcc-8ce4db1da5d0": { name: 'ะะปัƒะผะธะฝะบะฐ' } "1005": { name: 'ะ ะตะบั‚ะพั€ะฐั‚' } "bc9f31ea-bf3d-416c-86b5-ecba6e98bb24": { name: 'ะคะพะฝั‚ะฐะฝะฐ' } "66710fdc-cdfc-4bbe-93a8-7e796fb8a88d": { name: 'ะšะพะทะปะต' } "24eaebc2-ca62-49ff-8b22-880bc131b69f": { name: 'ะฆั€ะฝะธั‡ะต' } "b79604bb-0bea-454f-a474-849156e418ea": { name: 'ะ”ั€ะฐั‡ะตะฒะพ' } "1004": { name: 'ะ“ะฐะทะธะฑะฐะฑะฐ' } "fc4bfa77-f791-4f93-8c0c-62d8306c599c": { name: 'ะะตั€ะตะทะธ' } "cfb0a034-6e29-4803-be02-9215dcac17a8": { name: 'ะƒะพั€ั‡ะต ะŸะตั‚ั€ะพะฒ' } "1003": { name: 'ะšะฐั€ะฟะพัˆ' } "200cdb67-8dc5-4dcf-ac62-748db636e04e": { name: '11ั‚ะธ ะžะบั‚ะพะผะฒั€ะธ' } "8d415fa0-77dc-4cb3-8460-a9159800917f": { name: 'ะกะ” ะ“ะพั†ะต ะ”ะตะปั‡ะตะฒ' } "b80e5cd2-76cb-40bf-b784-2a0a312e6264": { name: 'ะกั‚ะฐะฝะธั†ะฐ ะƒะพั€ั‡ะต' } "6380c7cc-df23-4512-ad10-f2b363000579": { name: 'ะกะพะฟะธัˆั‚ะต' } "eaae3b5f-bd71-46f9-85d5-8d3a19c96322": { name: 'ะšะฐั€ะฟะพัˆ 2' } "7c497bfd-36b6-4eed-9172-37fd70f17c48": { name: 'ะ–ะตะปะตะทะฐั€ะฐ' } "1000": { name: 'ะฆะตะฝั‚ะฐั€' } "3d7bd712-24a9-482c-b387-a8168b12d3f4": { name: 'ะ‘ัƒั‚ะตะป 1' } "5f718e32-5491-4c3c-98ff-45dc9e287df4": { name: 'ะ’ะพะดะฝะพ' } "e7a05c01-1d5c-479a-a5a5-419f28cebeef": { name: 'ะ˜ะทะปะตั‚' } "1001": { name: 'ะ›ะธัะธั‡ะต'} "8ad9e315-0e23-4dc0-a26f-ba5a17d4d7ed": { name: 'ะะตั€ะพะดั€ะพะผ'} "680b0098-7c4d-44cf-acb1-dc4031e93d34": { name: 'ะ˜ะปะธะฝะดะตะฝ'} window.fn.loadSensors = () -> content = $('#content')[0] menu = $('#menu')[0] if window.fn.selected is 'sensors' menu.close.bind(menu)() return content.load 'views/sensors.html' .then menu.close.bind(menu) .then () -> renderSensors() getMarkerIcon = (level) -> level = Math.round level switch when 0 <= level < 50 1 when 50 <= level < 100 2 when 100 <= level < 250 3 when 250 <= level < 350 4 when 350 <= level < 430 5 when 430 <= level < 2000 5 else 0 window.fn.markerIcons = [ L.icon({ iconUrl: 'css/images/marker-icon-lgray.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-green.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-yellow.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-orange.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-red.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-violet.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) ] renderSensors = () -> window.fn.selected = 'sensors' CENTER = [ 41.99249998, 21.42361109 ] CITY = 'skopje' USERNAME = "atonevski" PASSWORD = "pv1530kay" parsePos = (s) -> s.split /\s*,\s*/ .map (v) -> parseFloat(v) toDTM = (d) -> throw "#{ d } is not Date()" unless d instanceof Date dd = (new Date(d - d.getTimezoneOffset()*1000*60)) ymd= dd.toISOString()[0..9] re = /(\d\d:\d\d:\d\d) GMT([-+]\d+)/gm s = re.exec d.toString() "#{ ymd }T#{ s[1] }#{ s[2][0..2] }:#{ s[2][3..4] }" getLast24h = () -> for id, s of window.fn.sensors do(id, s) => #... to = new Date() from = new Date to - 24*60*60*1000 url = "https://#{ CITY }.pulse.eco/rest/dataRaw?" + "sensorId=#{ id }&" + "from=#{ encodeURIComponent toDTM(from) }&" + "to=#{ encodeURIComponent toDTM(to) }" # console.log url $.ajax url: url method: 'GET' username: USERNAME password: PASSWORD dataType: "json" headers: "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD) .done (d) => # console.log s # window.fn.sensors[id].data = data s.data = d # here we should create the marker for sensor... pos = parsePos s.position # filter unique type/param values params = s.data .map (x) -> x.type .filter (v, i, self) -> self.indexOf(v) is i typeInfo = {} for p in params paramData = s.data .filter (v) -> v.type is p and v.value? .map (x) -> parseInt x.value # console.log p, paramData curr = paramData[-1..][0] min = paramData.reduce (a, v) -> unless v? a else if v < a then v else a , paramData[0] max = paramData.reduce (a, v) -> unless v? a else if v > a then v else a , paramData[0] acc = paramData.reduce (a, v) -> unless v? a else { sum: a.sum + v, count: a.count + 1 } , { sum: 0, count: 0} avg = if acc.count > 0 then acc.sum / acc.count else null typeInfo[p] = curr: curr, min: min, max: max, avg: avg, data: paramData s.params = params s.typeInfo = typeInfo # console.log s html = """ <table> <caption>#{ s.name }</captio> <thead><tr> <th>parameter</th> <th class='center'>current</th> <th class='center'>min</th> <th class='center'>max</th> <th class='center'>avg</th> <th class='center'>samples</th> </tr></thead> <tbody> """ for t, v of s.typeInfo html += """ <tr> <td align='left'>#{ t }</td> <td align='center'>#{ v.curr }</td> <td align='center'>#{ v.min }</td> <td align='center'>#{ v.max }</td> <td align='center'>#{ v.avg.toFixed 2 }</td> <td align='center'>#{ v.data.length }</td> </tr> """ html += """ </tbody> </table> """ if s.data.length > 0 html += """ <p> Interval: <span style='font-size: 75%'>#{ s.data[0].stamp[0..18] } &ndash; #{ s.data[-1..][0].stamp[0..18] }</span> </p> """ i = if s.typeInfo['pm10']? and s.typeInfo['pm10'].curr? getMarkerIcon s.typeInfo.pm10.curr else 0 marker = L.marker pos, { icon: window.fn.markerIcons[i] } .addTo window.fn.sensorMap .bindPopup html get24h = () -> # instead use loop over sensors & retreive data # when tested put this code in a separate function $.ajax url: "https://#{ CITY }.pulse.eco/rest/data24h" method: 'GET' username: USERNAME password: PASSWORD .done (d) -> # console.log d # we assume we have loaded sensors data for id, s of window.fn.sensors data = d.filter (x) -> x.sensorId is id window.fn.sensors[id].data = data # console.log window.fn.sensors # here we should create the marker for sensor... for id, s of window.fn.sensors pos = parsePos s.position # filter unique type/param values params = s.data .map (x) -> x.type .filter (v, i, self) -> self.indexOf(v) is i marker = L.marker pos .addTo window.fn.sensorMap .bindPopup """ <p>Sensor: #{ s.name }</p> <p>Parameters: #{ params.join(', ') }</p> """ getSensors = () -> $.ajax url: "https://#{ CITY }.pulse.eco/rest/sensor" method: 'GET' username: USERNAME password: PASSWORD .done (d) -> # console.log d for s in d if window.fn.sensors[s.sensorId]? window.fn.sensors[s.sensorId].position = s.position window.fn.sensors[s.sensorId].description = s.description window.fn.sensors[s.sensorId].coments = s.coments else window.fn.sensors[s.sensorId] = s window.fn.sensors[s.sensorId].name = s.description sensors = d # get24h() getLast24h() renderMap = () -> window.fn.sensorMap = L.map 'sensors-map-id' .setView CENTER, 12 # L.tileLayer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { } L.tileLayer 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', {} .addTo window.fn.sensorMap # added for lat/lngs window.fn.sensorMap.on 'click', (e) -> ons.notification.alert "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })" console.log "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })" getSensors() renderMap()
69720
# # MAP # # Leaflet MAP window.fn.sensorMap = null window.fn.sensors = "1002": { name: '<NAME>' } "11888f3a-bc5e-4a0c-9f27-702984decedf": { name: '<NAME>' } "01440b05-255d-4764-be87-bdf135f32289": { name: '<NAME>' } "bb948861-3fd7-47dd-b986-cb13c9732725": { name: '<NAME>' } "cec29ba1-5414-4cf3-bbcc-8ce4db1da5d0": { name: '<NAME>' } "1005": { name: '<NAME>' } "bc9f31ea-bf3d-416c-86b5-ecba6e98bb24": { name: '<NAME>' } "66710fdc-cdfc-4bbe-93a8-7e796fb8a88d": { name: '<NAME>' } "24eaebc2-ca62-49ff-8b22-880bc131b69f": { name: '<NAME>' } "b79604bb-0bea-454f-a474-849156e418ea": { name: '<NAME>' } "1004": { name: '<NAME>' } "fc4bfa77-f791-4f93-8c0c-62d8306c599c": { name: '<NAME>' } "cfb0a034-6e29-4803-be02-9215dcac17a8": { name: '<NAME>' } "1003": { name: '<NAME>' } "200cdb67-8dc5-4dcf-ac62-748db636e04e": { name: '<NAME>' } "8d415fa0-77dc-4cb3-8460-a9159800917f": { name: 'ะกะ” <NAME>' } "b80e5cd2-76cb-40bf-b784-2a0a312e6264": { name: 'ะกั‚ะฐะฝะธั†<NAME> <NAME>' } "6380c7cc-df23-4512-ad10-f2b363000579": { name: '<NAME>ะพะฟ<NAME>' } "eaae3b5f-bd71-46f9-85d5-8d3a19c96322": { name: 'ะš<NAME> 2' } "7c497bfd-36b6-4eed-9172-37fd70f17c48": { name: '<NAME>' } "1000": { name: '<NAME>' } "3d7bd712-24a9-482c-b387-a8168b12d3f4": { name: '<NAME>' } "5f718e32-5491-4c3c-98ff-45dc9e287df4": { name: '<NAME>ะพะด<NAME>' } "e7a05c01-1d5c-479a-a5a5-419f28cebeef": { name: '<NAME>' } "1001": { name: '<NAME>'} "8ad9e315-0e23-4dc0-a26f-ba5a17d4d7ed": { name: '<NAME>'} "680b0098-7c4d-44cf-acb1-dc4031e93d34": { name: '<NAME>'} window.fn.loadSensors = () -> content = $('#content')[0] menu = $('#menu')[0] if window.fn.selected is 'sensors' menu.close.bind(menu)() return content.load 'views/sensors.html' .then menu.close.bind(menu) .then () -> renderSensors() getMarkerIcon = (level) -> level = Math.round level switch when 0 <= level < 50 1 when 50 <= level < 100 2 when 100 <= level < 250 3 when 250 <= level < 350 4 when 350 <= level < 430 5 when 430 <= level < 2000 5 else 0 window.fn.markerIcons = [ L.icon({ iconUrl: 'css/images/marker-icon-lgray.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-green.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-yellow.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-orange.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-red.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-violet.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) ] renderSensors = () -> window.fn.selected = 'sensors' CENTER = [ 41.99249998, 21.42361109 ] CITY = 'skopje' USERNAME = "atonevski" PASSWORD = "<PASSWORD>" parsePos = (s) -> s.split /\s*,\s*/ .map (v) -> parseFloat(v) toDTM = (d) -> throw "#{ d } is not Date()" unless d instanceof Date dd = (new Date(d - d.getTimezoneOffset()*1000*60)) ymd= dd.toISOString()[0..9] re = /(\d\d:\d\d:\d\d) GMT([-+]\d+)/gm s = re.exec d.toString() "#{ ymd }T#{ s[1] }#{ s[2][0..2] }:#{ s[2][3..4] }" getLast24h = () -> for id, s of window.fn.sensors do(id, s) => #... to = new Date() from = new Date to - 24*60*60*1000 url = "https://#{ CITY }.pulse.eco/rest/dataRaw?" + "sensorId=#{ id }&" + "from=#{ encodeURIComponent toDTM(from) }&" + "to=#{ encodeURIComponent toDTM(to) }" # console.log url $.ajax url: url method: 'GET' username: USERNAME password: <PASSWORD> dataType: "json" headers: "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD) .done (d) => # console.log s # window.fn.sensors[id].data = data s.data = d # here we should create the marker for sensor... pos = parsePos s.position # filter unique type/param values params = s.data .map (x) -> x.type .filter (v, i, self) -> self.indexOf(v) is i typeInfo = {} for p in params paramData = s.data .filter (v) -> v.type is p and v.value? .map (x) -> parseInt x.value # console.log p, paramData curr = paramData[-1..][0] min = paramData.reduce (a, v) -> unless v? a else if v < a then v else a , paramData[0] max = paramData.reduce (a, v) -> unless v? a else if v > a then v else a , paramData[0] acc = paramData.reduce (a, v) -> unless v? a else { sum: a.sum + v, count: a.count + 1 } , { sum: 0, count: 0} avg = if acc.count > 0 then acc.sum / acc.count else null typeInfo[p] = curr: curr, min: min, max: max, avg: avg, data: paramData s.params = params s.typeInfo = typeInfo # console.log s html = """ <table> <caption>#{ s.name }</captio> <thead><tr> <th>parameter</th> <th class='center'>current</th> <th class='center'>min</th> <th class='center'>max</th> <th class='center'>avg</th> <th class='center'>samples</th> </tr></thead> <tbody> """ for t, v of s.typeInfo html += """ <tr> <td align='left'>#{ t }</td> <td align='center'>#{ v.curr }</td> <td align='center'>#{ v.min }</td> <td align='center'>#{ v.max }</td> <td align='center'>#{ v.avg.toFixed 2 }</td> <td align='center'>#{ v.data.length }</td> </tr> """ html += """ </tbody> </table> """ if s.data.length > 0 html += """ <p> Interval: <span style='font-size: 75%'>#{ s.data[0].stamp[0..18] } &ndash; #{ s.data[-1..][0].stamp[0..18] }</span> </p> """ i = if s.typeInfo['pm10']? and s.typeInfo['pm10'].curr? getMarkerIcon s.typeInfo.pm10.curr else 0 marker = L.marker pos, { icon: window.fn.markerIcons[i] } .addTo window.fn.sensorMap .bindPopup html get24h = () -> # instead use loop over sensors & retreive data # when tested put this code in a separate function $.ajax url: "https://#{ CITY }.pulse.eco/rest/data24h" method: 'GET' username: USERNAME password: <PASSWORD> .done (d) -> # console.log d # we assume we have loaded sensors data for id, s of window.fn.sensors data = d.filter (x) -> x.sensorId is id window.fn.sensors[id].data = data # console.log window.fn.sensors # here we should create the marker for sensor... for id, s of window.fn.sensors pos = parsePos s.position # filter unique type/param values params = s.data .map (x) -> x.type .filter (v, i, self) -> self.indexOf(v) is i marker = L.marker pos .addTo window.fn.sensorMap .bindPopup """ <p>Sensor: #{ s.name }</p> <p>Parameters: #{ params.join(', ') }</p> """ getSensors = () -> $.ajax url: "https://#{ CITY }.pulse.eco/rest/sensor" method: 'GET' username: USERNAME password: <PASSWORD> .done (d) -> # console.log d for s in d if window.fn.sensors[s.sensorId]? window.fn.sensors[s.sensorId].position = s.position window.fn.sensors[s.sensorId].description = s.description window.fn.sensors[s.sensorId].coments = s.coments else window.fn.sensors[s.sensorId] = s window.fn.sensors[s.sensorId].name = s.description sensors = d # get24h() getLast24h() renderMap = () -> window.fn.sensorMap = L.map 'sensors-map-id' .setView CENTER, 12 # L.tileLayer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { } L.tileLayer 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', {} .addTo window.fn.sensorMap # added for lat/lngs window.fn.sensorMap.on 'click', (e) -> ons.notification.alert "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })" console.log "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })" getSensors() renderMap()
true
# # MAP # # Leaflet MAP window.fn.sensorMap = null window.fn.sensors = "1002": { name: 'PI:NAME:<NAME>END_PI' } "11888f3a-bc5e-4a0c-9f27-702984decedf": { name: 'PI:NAME:<NAME>END_PI' } "01440b05-255d-4764-be87-bdf135f32289": { name: 'PI:NAME:<NAME>END_PI' } "bb948861-3fd7-47dd-b986-cb13c9732725": { name: 'PI:NAME:<NAME>END_PI' } "cec29ba1-5414-4cf3-bbcc-8ce4db1da5d0": { name: 'PI:NAME:<NAME>END_PI' } "1005": { name: 'PI:NAME:<NAME>END_PI' } "bc9f31ea-bf3d-416c-86b5-ecba6e98bb24": { name: 'PI:NAME:<NAME>END_PI' } "66710fdc-cdfc-4bbe-93a8-7e796fb8a88d": { name: 'PI:NAME:<NAME>END_PI' } "24eaebc2-ca62-49ff-8b22-880bc131b69f": { name: 'PI:NAME:<NAME>END_PI' } "b79604bb-0bea-454f-a474-849156e418ea": { name: 'PI:NAME:<NAME>END_PI' } "1004": { name: 'PI:NAME:<NAME>END_PI' } "fc4bfa77-f791-4f93-8c0c-62d8306c599c": { name: 'PI:NAME:<NAME>END_PI' } "cfb0a034-6e29-4803-be02-9215dcac17a8": { name: 'PI:NAME:<NAME>END_PI' } "1003": { name: 'PI:NAME:<NAME>END_PI' } "200cdb67-8dc5-4dcf-ac62-748db636e04e": { name: 'PI:NAME:<NAME>END_PI' } "8d415fa0-77dc-4cb3-8460-a9159800917f": { name: 'ะกะ” PI:NAME:<NAME>END_PI' } "b80e5cd2-76cb-40bf-b784-2a0a312e6264": { name: 'ะกั‚ะฐะฝะธั†PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' } "6380c7cc-df23-4512-ad10-f2b363000579": { name: 'PI:NAME:<NAME>END_PIะพะฟPI:NAME:<NAME>END_PI' } "eaae3b5f-bd71-46f9-85d5-8d3a19c96322": { name: 'ะšPI:NAME:<NAME>END_PI 2' } "7c497bfd-36b6-4eed-9172-37fd70f17c48": { name: 'PI:NAME:<NAME>END_PI' } "1000": { name: 'PI:NAME:<NAME>END_PI' } "3d7bd712-24a9-482c-b387-a8168b12d3f4": { name: 'PI:NAME:<NAME>END_PI' } "5f718e32-5491-4c3c-98ff-45dc9e287df4": { name: 'PI:NAME:<NAME>END_PIะพะดPI:NAME:<NAME>END_PI' } "e7a05c01-1d5c-479a-a5a5-419f28cebeef": { name: 'PI:NAME:<NAME>END_PI' } "1001": { name: 'PI:NAME:<NAME>END_PI'} "8ad9e315-0e23-4dc0-a26f-ba5a17d4d7ed": { name: 'PI:NAME:<NAME>END_PI'} "680b0098-7c4d-44cf-acb1-dc4031e93d34": { name: 'PI:NAME:<NAME>END_PI'} window.fn.loadSensors = () -> content = $('#content')[0] menu = $('#menu')[0] if window.fn.selected is 'sensors' menu.close.bind(menu)() return content.load 'views/sensors.html' .then menu.close.bind(menu) .then () -> renderSensors() getMarkerIcon = (level) -> level = Math.round level switch when 0 <= level < 50 1 when 50 <= level < 100 2 when 100 <= level < 250 3 when 250 <= level < 350 4 when 350 <= level < 430 5 when 430 <= level < 2000 5 else 0 window.fn.markerIcons = [ L.icon({ iconUrl: 'css/images/marker-icon-lgray.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-green.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-yellow.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-orange.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-red.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) , L.icon({ iconUrl: 'css/images/marker-icon-violet.png' shadowUrl: 'css/images/marker-shadow.png' iconSize: [25, 41] shadowSize: [41, 41] iconAnchor: [12, 41] popupAnchor: [0, -43]}) ] renderSensors = () -> window.fn.selected = 'sensors' CENTER = [ 41.99249998, 21.42361109 ] CITY = 'skopje' USERNAME = "atonevski" PASSWORD = "PI:PASSWORD:<PASSWORD>END_PI" parsePos = (s) -> s.split /\s*,\s*/ .map (v) -> parseFloat(v) toDTM = (d) -> throw "#{ d } is not Date()" unless d instanceof Date dd = (new Date(d - d.getTimezoneOffset()*1000*60)) ymd= dd.toISOString()[0..9] re = /(\d\d:\d\d:\d\d) GMT([-+]\d+)/gm s = re.exec d.toString() "#{ ymd }T#{ s[1] }#{ s[2][0..2] }:#{ s[2][3..4] }" getLast24h = () -> for id, s of window.fn.sensors do(id, s) => #... to = new Date() from = new Date to - 24*60*60*1000 url = "https://#{ CITY }.pulse.eco/rest/dataRaw?" + "sensorId=#{ id }&" + "from=#{ encodeURIComponent toDTM(from) }&" + "to=#{ encodeURIComponent toDTM(to) }" # console.log url $.ajax url: url method: 'GET' username: USERNAME password: PI:PASSWORD:<PASSWORD>END_PI dataType: "json" headers: "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD) .done (d) => # console.log s # window.fn.sensors[id].data = data s.data = d # here we should create the marker for sensor... pos = parsePos s.position # filter unique type/param values params = s.data .map (x) -> x.type .filter (v, i, self) -> self.indexOf(v) is i typeInfo = {} for p in params paramData = s.data .filter (v) -> v.type is p and v.value? .map (x) -> parseInt x.value # console.log p, paramData curr = paramData[-1..][0] min = paramData.reduce (a, v) -> unless v? a else if v < a then v else a , paramData[0] max = paramData.reduce (a, v) -> unless v? a else if v > a then v else a , paramData[0] acc = paramData.reduce (a, v) -> unless v? a else { sum: a.sum + v, count: a.count + 1 } , { sum: 0, count: 0} avg = if acc.count > 0 then acc.sum / acc.count else null typeInfo[p] = curr: curr, min: min, max: max, avg: avg, data: paramData s.params = params s.typeInfo = typeInfo # console.log s html = """ <table> <caption>#{ s.name }</captio> <thead><tr> <th>parameter</th> <th class='center'>current</th> <th class='center'>min</th> <th class='center'>max</th> <th class='center'>avg</th> <th class='center'>samples</th> </tr></thead> <tbody> """ for t, v of s.typeInfo html += """ <tr> <td align='left'>#{ t }</td> <td align='center'>#{ v.curr }</td> <td align='center'>#{ v.min }</td> <td align='center'>#{ v.max }</td> <td align='center'>#{ v.avg.toFixed 2 }</td> <td align='center'>#{ v.data.length }</td> </tr> """ html += """ </tbody> </table> """ if s.data.length > 0 html += """ <p> Interval: <span style='font-size: 75%'>#{ s.data[0].stamp[0..18] } &ndash; #{ s.data[-1..][0].stamp[0..18] }</span> </p> """ i = if s.typeInfo['pm10']? and s.typeInfo['pm10'].curr? getMarkerIcon s.typeInfo.pm10.curr else 0 marker = L.marker pos, { icon: window.fn.markerIcons[i] } .addTo window.fn.sensorMap .bindPopup html get24h = () -> # instead use loop over sensors & retreive data # when tested put this code in a separate function $.ajax url: "https://#{ CITY }.pulse.eco/rest/data24h" method: 'GET' username: USERNAME password: PI:PASSWORD:<PASSWORD>END_PI .done (d) -> # console.log d # we assume we have loaded sensors data for id, s of window.fn.sensors data = d.filter (x) -> x.sensorId is id window.fn.sensors[id].data = data # console.log window.fn.sensors # here we should create the marker for sensor... for id, s of window.fn.sensors pos = parsePos s.position # filter unique type/param values params = s.data .map (x) -> x.type .filter (v, i, self) -> self.indexOf(v) is i marker = L.marker pos .addTo window.fn.sensorMap .bindPopup """ <p>Sensor: #{ s.name }</p> <p>Parameters: #{ params.join(', ') }</p> """ getSensors = () -> $.ajax url: "https://#{ CITY }.pulse.eco/rest/sensor" method: 'GET' username: USERNAME password: PI:PASSWORD:<PASSWORD>END_PI .done (d) -> # console.log d for s in d if window.fn.sensors[s.sensorId]? window.fn.sensors[s.sensorId].position = s.position window.fn.sensors[s.sensorId].description = s.description window.fn.sensors[s.sensorId].coments = s.coments else window.fn.sensors[s.sensorId] = s window.fn.sensors[s.sensorId].name = s.description sensors = d # get24h() getLast24h() renderMap = () -> window.fn.sensorMap = L.map 'sensors-map-id' .setView CENTER, 12 # L.tileLayer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { } L.tileLayer 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', {} .addTo window.fn.sensorMap # added for lat/lngs window.fn.sensorMap.on 'click', (e) -> ons.notification.alert "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })" console.log "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })" getSensors() renderMap()
[ { "context": " API_URL: \"https://api.are.na/v2\"\n PUSHER_KEY: '19beda1f7e2ca403abab'\n S3_KEY: null\n S3_SECRET: null\n SESSION_SECRE", "end": 548, "score": 0.9995083212852478, "start": 528, "tag": "KEY", "value": "19beda1f7e2ca403abab" }, { "context": "S3_KEY: null\n S3_SECRET: null\n SESSION_SECRET: '3rv3ll-mAnd1ngo'\n SESSION_COOKIE_MAX_AGE: 31536000000\n SESSION_", "end": 617, "score": 0.5557377338409424, "start": 602, "tag": "KEY", "value": "3rv3ll-mAnd1ngo" }, { "context": "OOKIE_MAX_AGE: 31536000000\n SESSION_COOKIE_KEY: 'arena.session'\n BLOG_URL: 'http://posts.are.na'\n COOKIE_DOMAI", "end": 693, "score": 0.9520388245582581, "start": 680, "tag": "KEY", "value": "arena.session" }, { "context": "24,812,14,15,410,1036,7358,10465\"\n ADMIN_SLUGS: 'chris-sherron,charles-broskoski,damon-zucconi,daniel-pianetti,c", "end": 1201, "score": 0.9412686824798584, "start": 1188, "tag": "NAME", "value": "chris-sherron" }, { "context": "10,1036,7358,10465\"\n ADMIN_SLUGS: 'chris-sherron,charles-broskoski,damon-zucconi,daniel-pianetti,christopher-barley,", "end": 1219, "score": 0.9910778403282166, "start": 1202, "tag": "NAME", "value": "charles-broskoski" }, { "context": "\"\n ADMIN_SLUGS: 'chris-sherron,charles-broskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-", "end": 1223, "score": 0.7018072605133057, "start": 1220, "tag": "USERNAME", "value": "dam" }, { "context": " ADMIN_SLUGS: 'chris-sherron,charles-broskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-mi", "end": 1225, "score": 0.8540135622024536, "start": 1223, "tag": "NAME", "value": "on" }, { "context": "DMIN_SLUGS: 'chris-sherron,charles-broskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-mil", "end": 1225, "score": 0.8651443123817444, "start": 1225, "tag": "USERNAME", "value": "" }, { "context": "MIN_SLUGS: 'chris-sherron,charles-broskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo", "end": 1233, "score": 0.9719842672348022, "start": 1226, "tag": "NAME", "value": "zucconi" }, { "context": "S: 'chris-sherron,charles-broskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n ", "end": 1240, "score": 0.8741716146469116, "start": 1234, "tag": "USERNAME", "value": "daniel" }, { "context": "is-sherron,charles-broskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n AIRBRAK", "end": 1249, "score": 0.7552624940872192, "start": 1241, "tag": "NAME", "value": "pianetti" }, { "context": "n,charles-broskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n AIRBRAKE_PROJECT_ID", "end": 1261, "score": 0.9399095773696899, "start": 1250, "tag": "NAME", "value": "christopher" }, { "context": "roskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n AIRBRAKE_PROJECT_ID:", "end": 1261, "score": 0.9141243696212769, "start": 1261, "tag": "USERNAME", "value": "" }, { "context": "oskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n AIRBRAKE_PROJECT_ID: null\n", "end": 1268, "score": 0.9849444031715393, "start": 1262, "tag": "NAME", "value": "barley" }, { "context": ",damon-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n AIRBRAKE_PROJECT_ID: null\n AIR", "end": 1272, "score": 0.962448239326477, "start": 1269, "tag": "USERNAME", "value": "meg" }, { "context": "on-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n AIRBRAKE_PROJECT_ID: null\n AIRB", "end": 1274, "score": 0.7537711262702942, "start": 1273, "tag": "NAME", "value": "m" }, { "context": "n-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n AIRBRAKE_PROJECT_ID: null\n AIRBRAKE_", "end": 1279, "score": 0.6281841397285461, "start": 1274, "tag": "USERNAME", "value": "iller" }, { "context": "oni,daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n AIRBRAKE_PROJECT_ID: null\n AIRBRAKE_API_K", "end": 1283, "score": 0.9571300745010376, "start": 1280, "tag": "USERNAME", "value": "leo" }, { "context": "daniel-pianetti,christopher-barley,meg-miller,leo-shaw'\n AIRBRAKE_PROJECT_ID: null\n AIRBRAKE_API_KEY: ", "end": 1288, "score": 0.5338574647903442, "start": 1284, "tag": "NAME", "value": "shaw" } ]
src/config.coffee
jdsimcoe/ervell
0
# # Using ["The Twelve-Factor App"](http://12factor.net/) as a reference all # environment configuration will live in environment variables. This file # simply lays out all of those environment variables with sensible defaults # for development. # module.exports = NODE_ENV: "development" PORT: 4000 APP_URL: "http://localhost:4000" API_BASE: "https://api.are.na" GRAPHQL_ENDPOINT: "https://api.are.na/graphql" CLIENT_GRAPHQL_ENDPOINT: "https://api.are.na/graphql" API_URL: "https://api.are.na/v2" PUSHER_KEY: '19beda1f7e2ca403abab' S3_KEY: null S3_SECRET: null SESSION_SECRET: '3rv3ll-mAnd1ngo' SESSION_COOKIE_MAX_AGE: 31536000000 SESSION_COOKIE_KEY: 'arena.session' BLOG_URL: 'http://posts.are.na' COOKIE_DOMAIN: null ASSET_PATH: '/assets/' IMAGE_PATH: '/images/' IMAGE_PROXY_URL: 'http://images.are.na' REDIS_URL: null GOOGLE_ANALYTICS_ID: 'UA-XXXXX-Y' STRIPE_PUBLISHABLE_KEY: null X_APP_TOKEN: null IOS_APP_ID: 1299153149 ITUNES_LINK: null HOMEPAGE_EXPLORE_USER_IDS: "449,3630,11465,9040,52,14031,17886,12341,14364,4094,9935,8743,23,9039,4620,17,4840,10850,5831,128,2471,7249,8565,2424,812,14,15,410,1036,7358,10465" ADMIN_SLUGS: 'chris-sherron,charles-broskoski,damon-zucconi,daniel-pianetti,christopher-barley,meg-miller,leo-shaw' AIRBRAKE_PROJECT_ID: null AIRBRAKE_API_KEY: null CONTENTFUL_SPACE_ID: null CONTENTFUL_ACCESS_TOKEN: null BACKBONE_SUPER_SYNC_TIMEOUT: 25000 RECAPTCHA_SITE_KEY: null RECAPTCHA_SECRET_KEY: null RATE_LIMIT_LOGGED_IN_POINTS: 1 RATE_LIMIT_LOGGED_OUT_POINTS: 10 RATE_LIMIT_TOTAL_POINTS: 200 RATE_LIMIT_DURATION: 60 IP_DENYLIST: '' USE_CSP: false CSP_SRCS: '' # Override any values with env variables if they exist for key, val of module.exports val = (process.env[key] or val) module.exports[key] = try JSON.parse(val) catch then val
112184
# # Using ["The Twelve-Factor App"](http://12factor.net/) as a reference all # environment configuration will live in environment variables. This file # simply lays out all of those environment variables with sensible defaults # for development. # module.exports = NODE_ENV: "development" PORT: 4000 APP_URL: "http://localhost:4000" API_BASE: "https://api.are.na" GRAPHQL_ENDPOINT: "https://api.are.na/graphql" CLIENT_GRAPHQL_ENDPOINT: "https://api.are.na/graphql" API_URL: "https://api.are.na/v2" PUSHER_KEY: '<KEY>' S3_KEY: null S3_SECRET: null SESSION_SECRET: '<KEY>' SESSION_COOKIE_MAX_AGE: 31536000000 SESSION_COOKIE_KEY: '<KEY>' BLOG_URL: 'http://posts.are.na' COOKIE_DOMAIN: null ASSET_PATH: '/assets/' IMAGE_PATH: '/images/' IMAGE_PROXY_URL: 'http://images.are.na' REDIS_URL: null GOOGLE_ANALYTICS_ID: 'UA-XXXXX-Y' STRIPE_PUBLISHABLE_KEY: null X_APP_TOKEN: null IOS_APP_ID: 1299153149 ITUNES_LINK: null HOMEPAGE_EXPLORE_USER_IDS: "449,3630,11465,9040,52,14031,17886,12341,14364,4094,9935,8743,23,9039,4620,17,4840,10850,5831,128,2471,7249,8565,2424,812,14,15,410,1036,7358,10465" ADMIN_SLUGS: '<NAME>,<NAME>,dam<NAME>-<NAME>,daniel-<NAME>,<NAME>-<NAME>,meg-<NAME>iller,leo-<NAME>' AIRBRAKE_PROJECT_ID: null AIRBRAKE_API_KEY: null CONTENTFUL_SPACE_ID: null CONTENTFUL_ACCESS_TOKEN: null BACKBONE_SUPER_SYNC_TIMEOUT: 25000 RECAPTCHA_SITE_KEY: null RECAPTCHA_SECRET_KEY: null RATE_LIMIT_LOGGED_IN_POINTS: 1 RATE_LIMIT_LOGGED_OUT_POINTS: 10 RATE_LIMIT_TOTAL_POINTS: 200 RATE_LIMIT_DURATION: 60 IP_DENYLIST: '' USE_CSP: false CSP_SRCS: '' # Override any values with env variables if they exist for key, val of module.exports val = (process.env[key] or val) module.exports[key] = try JSON.parse(val) catch then val
true
# # Using ["The Twelve-Factor App"](http://12factor.net/) as a reference all # environment configuration will live in environment variables. This file # simply lays out all of those environment variables with sensible defaults # for development. # module.exports = NODE_ENV: "development" PORT: 4000 APP_URL: "http://localhost:4000" API_BASE: "https://api.are.na" GRAPHQL_ENDPOINT: "https://api.are.na/graphql" CLIENT_GRAPHQL_ENDPOINT: "https://api.are.na/graphql" API_URL: "https://api.are.na/v2" PUSHER_KEY: 'PI:KEY:<KEY>END_PI' S3_KEY: null S3_SECRET: null SESSION_SECRET: 'PI:KEY:<KEY>END_PI' SESSION_COOKIE_MAX_AGE: 31536000000 SESSION_COOKIE_KEY: 'PI:KEY:<KEY>END_PI' BLOG_URL: 'http://posts.are.na' COOKIE_DOMAIN: null ASSET_PATH: '/assets/' IMAGE_PATH: '/images/' IMAGE_PROXY_URL: 'http://images.are.na' REDIS_URL: null GOOGLE_ANALYTICS_ID: 'UA-XXXXX-Y' STRIPE_PUBLISHABLE_KEY: null X_APP_TOKEN: null IOS_APP_ID: 1299153149 ITUNES_LINK: null HOMEPAGE_EXPLORE_USER_IDS: "449,3630,11465,9040,52,14031,17886,12341,14364,4094,9935,8743,23,9039,4620,17,4840,10850,5831,128,2471,7249,8565,2424,812,14,15,410,1036,7358,10465" ADMIN_SLUGS: 'PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,damPI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI,daniel-PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI,meg-PI:NAME:<NAME>END_PIiller,leo-PI:NAME:<NAME>END_PI' AIRBRAKE_PROJECT_ID: null AIRBRAKE_API_KEY: null CONTENTFUL_SPACE_ID: null CONTENTFUL_ACCESS_TOKEN: null BACKBONE_SUPER_SYNC_TIMEOUT: 25000 RECAPTCHA_SITE_KEY: null RECAPTCHA_SECRET_KEY: null RATE_LIMIT_LOGGED_IN_POINTS: 1 RATE_LIMIT_LOGGED_OUT_POINTS: 10 RATE_LIMIT_TOTAL_POINTS: 200 RATE_LIMIT_DURATION: 60 IP_DENYLIST: '' USE_CSP: false CSP_SRCS: '' # Override any values with env variables if they exist for key, val of module.exports val = (process.env[key] or val) module.exports[key] = try JSON.parse(val) catch then val
[ { "context": "BROWSER\n\n\t\t\tTEST_SOURCE_URL = 'https://github.com/balena-io-projects/simple-server-node/archive/v1.0.0.tar.gz'\n\n\t\t\tit ", "end": 2327, "score": 0.9986866116523743, "start": 2309, "tag": "USERNAME", "value": "balena-io-projects" }, { "context": "omUrl(@application.id, { url: 'https://github.com/balena-io-projects/simple-server-node/archive/v0.0.0.tar.gz' })\n\t\t\t\t", "end": 3039, "score": 0.9992609620094299, "start": 3021, "tag": "USERNAME", "value": "balena-io-projects" }, { "context": "omUrl(@application.id, { url: 'https://github.com/balena-io-projects/simple-server-node' })\n\t\t\t\tm.chai.expect(promise)", "end": 3577, "score": 0.9961836934089661, "start": 3559, "tag": "USERNAME", "value": "balena-io-projects" }, { "context": "name: 'web' }\n\t\t\t\t\t\t]\n\t\t\t\t\t\tuser:\n\t\t\t\t\t\t\tusername: credentials.username\n\n\t\t\t\t\tm.chai.expect(release.images[0].build_log).", "end": 7084, "score": 0.9991097450256348, "start": 7064, "tag": "USERNAME", "value": "credentials.username" }, { "context": "name: 'web' }\n\t\t\t\t\t\t]\n\t\t\t\t\t\tuser:\n\t\t\t\t\t\t\tusername: credentials.username\n\n\t\t\t\t\tm.chai.expect(release.images[0].build_log).", "end": 7578, "score": 0.9993054270744324, "start": 7558, "tag": "USERNAME", "value": "credentials.username" }, { "context": "name: 'web' }\n\t\t\t\t\t\t]\n\t\t\t\t\t\tuser:\n\t\t\t\t\t\t\tusername: credentials.username\n\n\t\t\t\t\tm.chai.expect(release.images[0].build_log).", "end": 8092, "score": 0.9990987777709961, "start": 8072, "tag": "USERNAME", "value": "credentials.username" }, { "context": "\t\t\t\t\tis_created_by__user: userId\n\t\t\t\t\tcommit: 'feb2361230dc40dba6dca9a18f2c19dc8f2c19dc'\n\t\t\t\t\tstatus: 'success'\n\t\t\t\t\tsource: 'cloud'\n\t\t\t\t", "end": 8911, "score": 0.8459214568138123, "start": 8874, "tag": "KEY", "value": "2361230dc40dba6dca9a18f2c19dc8f2c19dc" }, { "context": "ull commit', ->\n\t\t\t\tbalena.models.release.get('feb2361230dc40dba6dca9a18f2c19dc8f2c19dc')\n\t\t\t\t.then (", "end": 9715, "score": 0.5255877375602722, "start": 9714, "tag": "KEY", "value": "2" }, { "context": "l commit', ->\n\t\t\t\tbalena.models.release.get('feb2361230dc40dba6dca9a18f2c19dc8f2c19dc')\n\t\t\t\t.then (release) ->\n\t\t\t\t\tm.chai.expect(relea", "end": 9751, "score": 0.854113757610321, "start": 9716, "tag": "KEY", "value": "61230dc40dba6dca9a18f2c19dc8f2c19dc" }, { "context": "i.expect(release).to.deep.match\n\t\t\t\t\t\tcommit: 'feb2361230dc40dba6dca9a18f2c19dc8f2c19dc'\n\t\t\t\t\t\tstatus", "end": 9838, "score": 0.5021105408668518, "start": 9837, "tag": "KEY", "value": "2" }, { "context": "xpect(release).to.deep.match\n\t\t\t\t\t\tcommit: 'feb2361230dc40dba6dca9a18f2c19dc8f2c19dc'\n\t\t\t\t\t\tstatus: 'success'\n\t\t\t\t\t\tsource: 'cloud'\n\n\t", "end": 9874, "score": 0.8548548817634583, "start": 9840, "tag": "KEY", "value": "1230dc40dba6dca9a18f2c19dc8f2c19dc" } ]
tests/integration/models/release.spec.coffee
josecoelho/balena-sdk
1
m = require('mochainon') _ = require('lodash') { balena credentials givenAnApplication givenLoggedInUser givenMulticontainerApplication IS_BROWSER } = require('../setup') { itShouldSetGetAndRemoveTags itShouldGetAllTagsByResource } = require('./tags') describe 'Release Model', -> givenLoggedInUser(before) describe 'given an application with no releases', -> givenAnApplication(before) describe 'balena.models.release.get()', -> it 'should be rejected if the release id does not exist by id', -> promise = balena.models.release.get(123) m.chai.expect(promise).to.be.rejectedWith('Release not found: 123') it 'should be rejected if the release id does not exist by commit', -> promise = balena.models.release.get('7cf02a6') m.chai.expect(promise).to.be.rejectedWith('Release not found: 7cf02a6') describe 'balena.models.release.getWithImageDetails()', -> it 'should be rejected if the release id does not exist by id', -> promise = balena.models.release.getWithImageDetails(123) m.chai.expect(promise).to.be.rejectedWith('Release not found: 123') it 'should be rejected if the release id does not exist by commit', -> promise = balena.models.release.getWithImageDetails('7cf02a6') m.chai.expect(promise).to.be.rejectedWith('Release not found: 7cf02a6') describe 'balena.models.release.getAllByApplication()', -> [ 'id' 'app_name' 'slug' ].forEach (prop) -> it "should eventually become an empty array given an application #{prop}", -> promise = balena.models.release.getAllByApplication(@application[prop]) m.chai.expect(promise).to.become([]) it 'should be rejected if the application name does not exist', -> promise = balena.models.release.getAllByApplication('HelloWorldApp') m.chai.expect(promise).to.be.rejectedWith('Application not found: HelloWorldApp') it 'should be rejected if the application id does not exist', -> promise = balena.models.release.getAllByApplication(999999) m.chai.expect(promise).to.be.rejectedWith('Application not found: 999999') describe 'balena.models.release.createFromUrl()', -> # There is a CORS header that only allows us to run this from dashboard.balena-cloud.com return if IS_BROWSER TEST_SOURCE_URL = 'https://github.com/balena-io-projects/simple-server-node/archive/v1.0.0.tar.gz' it 'should be rejected if the application name does not exist', -> promise = balena.models.release.createFromUrl('HelloWorldApp', { url: TEST_SOURCE_URL }) m.chai.expect(promise).to.be.rejectedWith('Application not found: HelloWorldApp') it 'should be rejected if the application id does not exist', -> promise = balena.models.release.createFromUrl(999999, { url: TEST_SOURCE_URL }) m.chai.expect(promise).to.be.rejectedWith('Application not found: 999999') it 'should be rejected when the provided tarball url is not found', -> promise = balena.models.release.createFromUrl(@application.id, { url: 'https://github.com/balena-io-projects/simple-server-node/archive/v0.0.0.tar.gz' }) m.chai.expect(promise).to.be.rejected .then (error) -> m.chai.expect(error).to.have.property('code', 'BalenaRequestError') m.chai.expect(error).to.have.property('statusCode', 404) m.chai.expect(error).to.have.property('message').that.contains('Failed to fetch tarball from passed URL') it 'should be rejected when the provided url is not a tarball', -> promise = balena.models.release.createFromUrl(@application.id, { url: 'https://github.com/balena-io-projects/simple-server-node' }) m.chai.expect(promise).to.be.rejected .then (error) -> m.chai.expect(error).to.have.property('code', 'BalenaError') m.chai.expect(error).to.have.property('message').that.contains('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') describe '[mutating operations]', -> afterEach -> balena.pine.delete resource: 'release' options: $filter: belongs_to__application: @application.id [ 'id' 'app_name' 'slug' ].forEach (prop) -> it "should be able to create a release using a tarball url given an application #{prop}", -> balena.models.release.createFromUrl(@application[prop], { url: TEST_SOURCE_URL }) .then (releaseId) => m.chai.expect(releaseId).to.be.a('number') balena.models.release.get(releaseId) .then (release) => m.chai.expect(release).to.deep.match status: 'running', source: 'cloud', id: releaseId belongs_to__application: __id: @application.id m.chai.expect(release).to.have.property('commit').that.is.a('string') describe 'given a multicontainer application with two releases', -> givenMulticontainerApplication(before) describe 'balena.models.release.get()', -> it 'should get the requested release by id', -> balena.models.release.get(@currentRelease.id) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'new-release-commit', id: @currentRelease.id belongs_to__application: __id: @application.id it 'should get the requested release by commit', -> balena.models.release.get(@currentRelease.commit) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'new-release-commit', id: @currentRelease.id belongs_to__application: __id: @application.id it 'should get the requested release by shorter commit', -> balena.models.release.get(@currentRelease.commit.slice(0, 7)) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'new-release-commit', id: @currentRelease.id belongs_to__application: __id: @application.id describe 'balena.models.release.getAllByApplication()', -> it 'should load both releases', -> balena.models.release.getAllByApplication(@application.id) .then (releases) -> m.chai.expect(releases).to.have.lengthOf(2) # Need to sort explicitly because releases were both created # at almost exactly the same time (just now, in test setup) sortedReleases = _.sortBy releases, (release) -> release.start_timestamp m.chai.expect(sortedReleases).to.deep.match [ status: 'success', source: 'cloud', commit: 'old-release-commit' , status: 'success', source: 'cloud', commit: 'new-release-commit' ] describe 'balena.models.release.getWithImageDetails()', -> it 'should get the release with associated images attached by id', -> balena.models.release.getWithImageDetails(@currentRelease.id) .then (release) -> m.chai.expect(release).to.deep.match commit: 'new-release-commit' status: 'success' source: 'cloud' images: [ { service_name: 'db' } { service_name: 'web' } ] user: username: credentials.username m.chai.expect(release.images[0].build_log).to.be.undefined it 'should get the release with associated images attached by commit', -> balena.models.release.getWithImageDetails(@currentRelease.commit) .then (release) -> m.chai.expect(release).to.deep.match commit: 'new-release-commit' status: 'success' source: 'cloud' images: [ { service_name: 'db' } { service_name: 'web' } ] user: username: credentials.username m.chai.expect(release.images[0].build_log).to.be.undefined it 'should get the release with associated images attached by shorter commit', -> balena.models.release.getWithImageDetails(@currentRelease.commit.slice(0, 7)) .then (release) -> m.chai.expect(release).to.deep.match commit: 'new-release-commit' status: 'success' source: 'cloud' images: [ { service_name: 'db' } { service_name: 'web' } ] user: username: credentials.username m.chai.expect(release.images[0].build_log).to.be.undefined it 'should allow extra options to also get the build log', -> balena.models.release.getWithImageDetails @currentRelease.id, image: $select: 'build_log' .then (release) -> m.chai.expect(release).to.deep.match images: [ service_name: 'db' build_log: 'db log' , service_name: 'web' build_log: 'web log' ] describe 'given an application with two releases that share the same commit root', -> givenAnApplication(before) before -> application = @application userId = @application.user.__id balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'feb2361230dc40dba6dca9a18f2c19dc8f2c19dc' status: 'success' source: 'cloud' composition: {} start_timestamp: 64321 .then -> balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'feb236123bf740d48900c19027d4a02127d4a021' status: 'success' source: 'cloud' composition: {} start_timestamp: 74321 describe 'balena.models.release.get()', -> it 'should be rejected with an error if there is an ambiguation between shorter commits', -> promise = balena.models.release.get('feb23612') m.chai.expect(promise).to.be.rejected .and.eventually.have.property('code', 'BalenaAmbiguousRelease') it 'should get the requested release by the full commit', -> balena.models.release.get('feb2361230dc40dba6dca9a18f2c19dc8f2c19dc') .then (release) -> m.chai.expect(release).to.deep.match commit: 'feb2361230dc40dba6dca9a18f2c19dc8f2c19dc' status: 'success' source: 'cloud' describe 'balena.models.release.getWithImageDetails()', -> it 'should be rejected with an error if there is an ambiguation between shorter commits', -> promise = balena.models.release.getWithImageDetails('feb23612') m.chai.expect(promise).to.be.rejected .and.eventually.have.property('code', 'BalenaAmbiguousRelease') it 'should get the release with associated images attached by the full commit', -> balena.models.release.getWithImageDetails('feb2361230dc40dba6dca9a18f2c19dc8f2c19dc') .then (release) -> m.chai.expect(release).to.deep.match commit: 'feb2361230dc40dba6dca9a18f2c19dc8f2c19dc' status: 'success' source: 'cloud' describe 'given a multicontainer application with successful & failed releases', -> describe 'balena.models.release.getLatestByApplication()', -> givenMulticontainerApplication(before) before -> application = @application userId = @application.user.__id balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'errored-then-fixed-release-commit' status: 'error' source: 'cloud' composition: {} start_timestamp: 64321 .then -> balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'errored-then-fixed-release-commit' status: 'success' source: 'cloud' composition: {} start_timestamp: 74321 .then -> balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'failed-release-commit' status: 'failed' source: 'cloud' composition: {} start_timestamp: 84321 [ 'id' 'app_name' 'slug' ].forEach (prop) -> it "should get the latest release by application #{prop}", -> balena.models.release.getLatestByApplication(@application[prop]) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'errored-then-fixed-release-commit', belongs_to__application: __id: @application.id describe 'balena.models.release.tags', -> givenMulticontainerApplication(before) appTagTestOptions = model: balena.models.release.tags modelNamespace: 'balena.models.release.tags' resourceName: 'application' uniquePropertyNames: ['app_name', 'slug'] releaseTagTestOptions = model: balena.models.release.tags modelNamespace: 'balena.models.release.tags' resourceName: 'release' uniquePropertyNames: ['commit'] beforeEach -> appTagTestOptions.resourceProvider = => @application releaseTagTestOptions.resourceProvider = => @currentRelease # used for tag creation during the # release.tags.getAllByApplication() test appTagTestOptions.setTagResourceProvider = => @currentRelease itShouldSetGetAndRemoveTags(releaseTagTestOptions) describe 'balena.models.release.tags.getAllByApplication()', -> itShouldGetAllTagsByResource(appTagTestOptions) describe 'balena.models.release.tags.getAllByRelease()', -> itShouldGetAllTagsByResource(releaseTagTestOptions)
167953
m = require('mochainon') _ = require('lodash') { balena credentials givenAnApplication givenLoggedInUser givenMulticontainerApplication IS_BROWSER } = require('../setup') { itShouldSetGetAndRemoveTags itShouldGetAllTagsByResource } = require('./tags') describe 'Release Model', -> givenLoggedInUser(before) describe 'given an application with no releases', -> givenAnApplication(before) describe 'balena.models.release.get()', -> it 'should be rejected if the release id does not exist by id', -> promise = balena.models.release.get(123) m.chai.expect(promise).to.be.rejectedWith('Release not found: 123') it 'should be rejected if the release id does not exist by commit', -> promise = balena.models.release.get('7cf02a6') m.chai.expect(promise).to.be.rejectedWith('Release not found: 7cf02a6') describe 'balena.models.release.getWithImageDetails()', -> it 'should be rejected if the release id does not exist by id', -> promise = balena.models.release.getWithImageDetails(123) m.chai.expect(promise).to.be.rejectedWith('Release not found: 123') it 'should be rejected if the release id does not exist by commit', -> promise = balena.models.release.getWithImageDetails('7cf02a6') m.chai.expect(promise).to.be.rejectedWith('Release not found: 7cf02a6') describe 'balena.models.release.getAllByApplication()', -> [ 'id' 'app_name' 'slug' ].forEach (prop) -> it "should eventually become an empty array given an application #{prop}", -> promise = balena.models.release.getAllByApplication(@application[prop]) m.chai.expect(promise).to.become([]) it 'should be rejected if the application name does not exist', -> promise = balena.models.release.getAllByApplication('HelloWorldApp') m.chai.expect(promise).to.be.rejectedWith('Application not found: HelloWorldApp') it 'should be rejected if the application id does not exist', -> promise = balena.models.release.getAllByApplication(999999) m.chai.expect(promise).to.be.rejectedWith('Application not found: 999999') describe 'balena.models.release.createFromUrl()', -> # There is a CORS header that only allows us to run this from dashboard.balena-cloud.com return if IS_BROWSER TEST_SOURCE_URL = 'https://github.com/balena-io-projects/simple-server-node/archive/v1.0.0.tar.gz' it 'should be rejected if the application name does not exist', -> promise = balena.models.release.createFromUrl('HelloWorldApp', { url: TEST_SOURCE_URL }) m.chai.expect(promise).to.be.rejectedWith('Application not found: HelloWorldApp') it 'should be rejected if the application id does not exist', -> promise = balena.models.release.createFromUrl(999999, { url: TEST_SOURCE_URL }) m.chai.expect(promise).to.be.rejectedWith('Application not found: 999999') it 'should be rejected when the provided tarball url is not found', -> promise = balena.models.release.createFromUrl(@application.id, { url: 'https://github.com/balena-io-projects/simple-server-node/archive/v0.0.0.tar.gz' }) m.chai.expect(promise).to.be.rejected .then (error) -> m.chai.expect(error).to.have.property('code', 'BalenaRequestError') m.chai.expect(error).to.have.property('statusCode', 404) m.chai.expect(error).to.have.property('message').that.contains('Failed to fetch tarball from passed URL') it 'should be rejected when the provided url is not a tarball', -> promise = balena.models.release.createFromUrl(@application.id, { url: 'https://github.com/balena-io-projects/simple-server-node' }) m.chai.expect(promise).to.be.rejected .then (error) -> m.chai.expect(error).to.have.property('code', 'BalenaError') m.chai.expect(error).to.have.property('message').that.contains('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') describe '[mutating operations]', -> afterEach -> balena.pine.delete resource: 'release' options: $filter: belongs_to__application: @application.id [ 'id' 'app_name' 'slug' ].forEach (prop) -> it "should be able to create a release using a tarball url given an application #{prop}", -> balena.models.release.createFromUrl(@application[prop], { url: TEST_SOURCE_URL }) .then (releaseId) => m.chai.expect(releaseId).to.be.a('number') balena.models.release.get(releaseId) .then (release) => m.chai.expect(release).to.deep.match status: 'running', source: 'cloud', id: releaseId belongs_to__application: __id: @application.id m.chai.expect(release).to.have.property('commit').that.is.a('string') describe 'given a multicontainer application with two releases', -> givenMulticontainerApplication(before) describe 'balena.models.release.get()', -> it 'should get the requested release by id', -> balena.models.release.get(@currentRelease.id) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'new-release-commit', id: @currentRelease.id belongs_to__application: __id: @application.id it 'should get the requested release by commit', -> balena.models.release.get(@currentRelease.commit) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'new-release-commit', id: @currentRelease.id belongs_to__application: __id: @application.id it 'should get the requested release by shorter commit', -> balena.models.release.get(@currentRelease.commit.slice(0, 7)) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'new-release-commit', id: @currentRelease.id belongs_to__application: __id: @application.id describe 'balena.models.release.getAllByApplication()', -> it 'should load both releases', -> balena.models.release.getAllByApplication(@application.id) .then (releases) -> m.chai.expect(releases).to.have.lengthOf(2) # Need to sort explicitly because releases were both created # at almost exactly the same time (just now, in test setup) sortedReleases = _.sortBy releases, (release) -> release.start_timestamp m.chai.expect(sortedReleases).to.deep.match [ status: 'success', source: 'cloud', commit: 'old-release-commit' , status: 'success', source: 'cloud', commit: 'new-release-commit' ] describe 'balena.models.release.getWithImageDetails()', -> it 'should get the release with associated images attached by id', -> balena.models.release.getWithImageDetails(@currentRelease.id) .then (release) -> m.chai.expect(release).to.deep.match commit: 'new-release-commit' status: 'success' source: 'cloud' images: [ { service_name: 'db' } { service_name: 'web' } ] user: username: credentials.username m.chai.expect(release.images[0].build_log).to.be.undefined it 'should get the release with associated images attached by commit', -> balena.models.release.getWithImageDetails(@currentRelease.commit) .then (release) -> m.chai.expect(release).to.deep.match commit: 'new-release-commit' status: 'success' source: 'cloud' images: [ { service_name: 'db' } { service_name: 'web' } ] user: username: credentials.username m.chai.expect(release.images[0].build_log).to.be.undefined it 'should get the release with associated images attached by shorter commit', -> balena.models.release.getWithImageDetails(@currentRelease.commit.slice(0, 7)) .then (release) -> m.chai.expect(release).to.deep.match commit: 'new-release-commit' status: 'success' source: 'cloud' images: [ { service_name: 'db' } { service_name: 'web' } ] user: username: credentials.username m.chai.expect(release.images[0].build_log).to.be.undefined it 'should allow extra options to also get the build log', -> balena.models.release.getWithImageDetails @currentRelease.id, image: $select: 'build_log' .then (release) -> m.chai.expect(release).to.deep.match images: [ service_name: 'db' build_log: 'db log' , service_name: 'web' build_log: 'web log' ] describe 'given an application with two releases that share the same commit root', -> givenAnApplication(before) before -> application = @application userId = @application.user.__id balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'feb<KEY>' status: 'success' source: 'cloud' composition: {} start_timestamp: 64321 .then -> balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'feb236123bf740d48900c19027d4a02127d4a021' status: 'success' source: 'cloud' composition: {} start_timestamp: 74321 describe 'balena.models.release.get()', -> it 'should be rejected with an error if there is an ambiguation between shorter commits', -> promise = balena.models.release.get('feb23612') m.chai.expect(promise).to.be.rejected .and.eventually.have.property('code', 'BalenaAmbiguousRelease') it 'should get the requested release by the full commit', -> balena.models.release.get('feb<KEY>3<KEY>') .then (release) -> m.chai.expect(release).to.deep.match commit: 'feb<KEY>36<KEY>' status: 'success' source: 'cloud' describe 'balena.models.release.getWithImageDetails()', -> it 'should be rejected with an error if there is an ambiguation between shorter commits', -> promise = balena.models.release.getWithImageDetails('feb23612') m.chai.expect(promise).to.be.rejected .and.eventually.have.property('code', 'BalenaAmbiguousRelease') it 'should get the release with associated images attached by the full commit', -> balena.models.release.getWithImageDetails('feb2361230dc40dba6dca9a18f2c19dc8f2c19dc') .then (release) -> m.chai.expect(release).to.deep.match commit: 'feb2361230dc40dba6dca9a18f2c19dc8f2c19dc' status: 'success' source: 'cloud' describe 'given a multicontainer application with successful & failed releases', -> describe 'balena.models.release.getLatestByApplication()', -> givenMulticontainerApplication(before) before -> application = @application userId = @application.user.__id balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'errored-then-fixed-release-commit' status: 'error' source: 'cloud' composition: {} start_timestamp: 64321 .then -> balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'errored-then-fixed-release-commit' status: 'success' source: 'cloud' composition: {} start_timestamp: 74321 .then -> balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'failed-release-commit' status: 'failed' source: 'cloud' composition: {} start_timestamp: 84321 [ 'id' 'app_name' 'slug' ].forEach (prop) -> it "should get the latest release by application #{prop}", -> balena.models.release.getLatestByApplication(@application[prop]) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'errored-then-fixed-release-commit', belongs_to__application: __id: @application.id describe 'balena.models.release.tags', -> givenMulticontainerApplication(before) appTagTestOptions = model: balena.models.release.tags modelNamespace: 'balena.models.release.tags' resourceName: 'application' uniquePropertyNames: ['app_name', 'slug'] releaseTagTestOptions = model: balena.models.release.tags modelNamespace: 'balena.models.release.tags' resourceName: 'release' uniquePropertyNames: ['commit'] beforeEach -> appTagTestOptions.resourceProvider = => @application releaseTagTestOptions.resourceProvider = => @currentRelease # used for tag creation during the # release.tags.getAllByApplication() test appTagTestOptions.setTagResourceProvider = => @currentRelease itShouldSetGetAndRemoveTags(releaseTagTestOptions) describe 'balena.models.release.tags.getAllByApplication()', -> itShouldGetAllTagsByResource(appTagTestOptions) describe 'balena.models.release.tags.getAllByRelease()', -> itShouldGetAllTagsByResource(releaseTagTestOptions)
true
m = require('mochainon') _ = require('lodash') { balena credentials givenAnApplication givenLoggedInUser givenMulticontainerApplication IS_BROWSER } = require('../setup') { itShouldSetGetAndRemoveTags itShouldGetAllTagsByResource } = require('./tags') describe 'Release Model', -> givenLoggedInUser(before) describe 'given an application with no releases', -> givenAnApplication(before) describe 'balena.models.release.get()', -> it 'should be rejected if the release id does not exist by id', -> promise = balena.models.release.get(123) m.chai.expect(promise).to.be.rejectedWith('Release not found: 123') it 'should be rejected if the release id does not exist by commit', -> promise = balena.models.release.get('7cf02a6') m.chai.expect(promise).to.be.rejectedWith('Release not found: 7cf02a6') describe 'balena.models.release.getWithImageDetails()', -> it 'should be rejected if the release id does not exist by id', -> promise = balena.models.release.getWithImageDetails(123) m.chai.expect(promise).to.be.rejectedWith('Release not found: 123') it 'should be rejected if the release id does not exist by commit', -> promise = balena.models.release.getWithImageDetails('7cf02a6') m.chai.expect(promise).to.be.rejectedWith('Release not found: 7cf02a6') describe 'balena.models.release.getAllByApplication()', -> [ 'id' 'app_name' 'slug' ].forEach (prop) -> it "should eventually become an empty array given an application #{prop}", -> promise = balena.models.release.getAllByApplication(@application[prop]) m.chai.expect(promise).to.become([]) it 'should be rejected if the application name does not exist', -> promise = balena.models.release.getAllByApplication('HelloWorldApp') m.chai.expect(promise).to.be.rejectedWith('Application not found: HelloWorldApp') it 'should be rejected if the application id does not exist', -> promise = balena.models.release.getAllByApplication(999999) m.chai.expect(promise).to.be.rejectedWith('Application not found: 999999') describe 'balena.models.release.createFromUrl()', -> # There is a CORS header that only allows us to run this from dashboard.balena-cloud.com return if IS_BROWSER TEST_SOURCE_URL = 'https://github.com/balena-io-projects/simple-server-node/archive/v1.0.0.tar.gz' it 'should be rejected if the application name does not exist', -> promise = balena.models.release.createFromUrl('HelloWorldApp', { url: TEST_SOURCE_URL }) m.chai.expect(promise).to.be.rejectedWith('Application not found: HelloWorldApp') it 'should be rejected if the application id does not exist', -> promise = balena.models.release.createFromUrl(999999, { url: TEST_SOURCE_URL }) m.chai.expect(promise).to.be.rejectedWith('Application not found: 999999') it 'should be rejected when the provided tarball url is not found', -> promise = balena.models.release.createFromUrl(@application.id, { url: 'https://github.com/balena-io-projects/simple-server-node/archive/v0.0.0.tar.gz' }) m.chai.expect(promise).to.be.rejected .then (error) -> m.chai.expect(error).to.have.property('code', 'BalenaRequestError') m.chai.expect(error).to.have.property('statusCode', 404) m.chai.expect(error).to.have.property('message').that.contains('Failed to fetch tarball from passed URL') it 'should be rejected when the provided url is not a tarball', -> promise = balena.models.release.createFromUrl(@application.id, { url: 'https://github.com/balena-io-projects/simple-server-node' }) m.chai.expect(promise).to.be.rejected .then (error) -> m.chai.expect(error).to.have.property('code', 'BalenaError') m.chai.expect(error).to.have.property('message').that.contains('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') describe '[mutating operations]', -> afterEach -> balena.pine.delete resource: 'release' options: $filter: belongs_to__application: @application.id [ 'id' 'app_name' 'slug' ].forEach (prop) -> it "should be able to create a release using a tarball url given an application #{prop}", -> balena.models.release.createFromUrl(@application[prop], { url: TEST_SOURCE_URL }) .then (releaseId) => m.chai.expect(releaseId).to.be.a('number') balena.models.release.get(releaseId) .then (release) => m.chai.expect(release).to.deep.match status: 'running', source: 'cloud', id: releaseId belongs_to__application: __id: @application.id m.chai.expect(release).to.have.property('commit').that.is.a('string') describe 'given a multicontainer application with two releases', -> givenMulticontainerApplication(before) describe 'balena.models.release.get()', -> it 'should get the requested release by id', -> balena.models.release.get(@currentRelease.id) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'new-release-commit', id: @currentRelease.id belongs_to__application: __id: @application.id it 'should get the requested release by commit', -> balena.models.release.get(@currentRelease.commit) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'new-release-commit', id: @currentRelease.id belongs_to__application: __id: @application.id it 'should get the requested release by shorter commit', -> balena.models.release.get(@currentRelease.commit.slice(0, 7)) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'new-release-commit', id: @currentRelease.id belongs_to__application: __id: @application.id describe 'balena.models.release.getAllByApplication()', -> it 'should load both releases', -> balena.models.release.getAllByApplication(@application.id) .then (releases) -> m.chai.expect(releases).to.have.lengthOf(2) # Need to sort explicitly because releases were both created # at almost exactly the same time (just now, in test setup) sortedReleases = _.sortBy releases, (release) -> release.start_timestamp m.chai.expect(sortedReleases).to.deep.match [ status: 'success', source: 'cloud', commit: 'old-release-commit' , status: 'success', source: 'cloud', commit: 'new-release-commit' ] describe 'balena.models.release.getWithImageDetails()', -> it 'should get the release with associated images attached by id', -> balena.models.release.getWithImageDetails(@currentRelease.id) .then (release) -> m.chai.expect(release).to.deep.match commit: 'new-release-commit' status: 'success' source: 'cloud' images: [ { service_name: 'db' } { service_name: 'web' } ] user: username: credentials.username m.chai.expect(release.images[0].build_log).to.be.undefined it 'should get the release with associated images attached by commit', -> balena.models.release.getWithImageDetails(@currentRelease.commit) .then (release) -> m.chai.expect(release).to.deep.match commit: 'new-release-commit' status: 'success' source: 'cloud' images: [ { service_name: 'db' } { service_name: 'web' } ] user: username: credentials.username m.chai.expect(release.images[0].build_log).to.be.undefined it 'should get the release with associated images attached by shorter commit', -> balena.models.release.getWithImageDetails(@currentRelease.commit.slice(0, 7)) .then (release) -> m.chai.expect(release).to.deep.match commit: 'new-release-commit' status: 'success' source: 'cloud' images: [ { service_name: 'db' } { service_name: 'web' } ] user: username: credentials.username m.chai.expect(release.images[0].build_log).to.be.undefined it 'should allow extra options to also get the build log', -> balena.models.release.getWithImageDetails @currentRelease.id, image: $select: 'build_log' .then (release) -> m.chai.expect(release).to.deep.match images: [ service_name: 'db' build_log: 'db log' , service_name: 'web' build_log: 'web log' ] describe 'given an application with two releases that share the same commit root', -> givenAnApplication(before) before -> application = @application userId = @application.user.__id balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'febPI:KEY:<KEY>END_PI' status: 'success' source: 'cloud' composition: {} start_timestamp: 64321 .then -> balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'feb236123bf740d48900c19027d4a02127d4a021' status: 'success' source: 'cloud' composition: {} start_timestamp: 74321 describe 'balena.models.release.get()', -> it 'should be rejected with an error if there is an ambiguation between shorter commits', -> promise = balena.models.release.get('feb23612') m.chai.expect(promise).to.be.rejected .and.eventually.have.property('code', 'BalenaAmbiguousRelease') it 'should get the requested release by the full commit', -> balena.models.release.get('febPI:KEY:<KEY>END_PI3PI:KEY:<KEY>END_PI') .then (release) -> m.chai.expect(release).to.deep.match commit: 'febPI:KEY:<KEY>END_PI36PI:KEY:<KEY>END_PI' status: 'success' source: 'cloud' describe 'balena.models.release.getWithImageDetails()', -> it 'should be rejected with an error if there is an ambiguation between shorter commits', -> promise = balena.models.release.getWithImageDetails('feb23612') m.chai.expect(promise).to.be.rejected .and.eventually.have.property('code', 'BalenaAmbiguousRelease') it 'should get the release with associated images attached by the full commit', -> balena.models.release.getWithImageDetails('feb2361230dc40dba6dca9a18f2c19dc8f2c19dc') .then (release) -> m.chai.expect(release).to.deep.match commit: 'feb2361230dc40dba6dca9a18f2c19dc8f2c19dc' status: 'success' source: 'cloud' describe 'given a multicontainer application with successful & failed releases', -> describe 'balena.models.release.getLatestByApplication()', -> givenMulticontainerApplication(before) before -> application = @application userId = @application.user.__id balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'errored-then-fixed-release-commit' status: 'error' source: 'cloud' composition: {} start_timestamp: 64321 .then -> balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'errored-then-fixed-release-commit' status: 'success' source: 'cloud' composition: {} start_timestamp: 74321 .then -> balena.pine.post resource: 'release' body: belongs_to__application: application.id is_created_by__user: userId commit: 'failed-release-commit' status: 'failed' source: 'cloud' composition: {} start_timestamp: 84321 [ 'id' 'app_name' 'slug' ].forEach (prop) -> it "should get the latest release by application #{prop}", -> balena.models.release.getLatestByApplication(@application[prop]) .then (release) => m.chai.expect(release).to.deep.match status: 'success', source: 'cloud', commit: 'errored-then-fixed-release-commit', belongs_to__application: __id: @application.id describe 'balena.models.release.tags', -> givenMulticontainerApplication(before) appTagTestOptions = model: balena.models.release.tags modelNamespace: 'balena.models.release.tags' resourceName: 'application' uniquePropertyNames: ['app_name', 'slug'] releaseTagTestOptions = model: balena.models.release.tags modelNamespace: 'balena.models.release.tags' resourceName: 'release' uniquePropertyNames: ['commit'] beforeEach -> appTagTestOptions.resourceProvider = => @application releaseTagTestOptions.resourceProvider = => @currentRelease # used for tag creation during the # release.tags.getAllByApplication() test appTagTestOptions.setTagResourceProvider = => @currentRelease itShouldSetGetAndRemoveTags(releaseTagTestOptions) describe 'balena.models.release.tags.getAllByApplication()', -> itShouldGetAllTagsByResource(appTagTestOptions) describe 'balena.models.release.tags.getAllByRelease()', -> itShouldGetAllTagsByResource(releaseTagTestOptions)
[ { "context": "dd\n , 'numChildViews', 'itemViewClass'\n\n # TODO(Peter): Consider making this a computed... binding logi", "end": 1366, "score": 0.9588140249252319, "start": 1361, "tag": "NAME", "value": "Peter" } ]
src/utils/lazy_container_view.coffee
FellowMD/ember-table
0
Ember.LazyContainerView = Ember.ContainerView.extend Ember.AddeparMixins.StyleBindingsMixin, classNames: 'lazy-list-container' styleBindings: ['height'] content: null itemViewClass: null rowHeight: null scrollTop: null startIndex: null init: -> @_super() @onNumChildViewsDidChange() height: Ember.computed -> @get('content.length') * @get('rowHeight') .property 'content.length', 'rowHeight' numChildViews: Ember.computed -> @get('numItemsShowing') + 2 .property 'numItemsShowing' onNumChildViewsDidChange: Ember.observer -> view = this # We are getting the class from a string e.g. "Ember.Table.Row" itemViewClass = Ember.get @get('itemViewClass') newNumViews = @get 'numChildViews' return unless itemViewClass and newNumViews oldNumViews = @get('length') numViewsToInsert = newNumViews - oldNumViews # if newNumViews < oldNumViews we need to remove some views if numViewsToInsert < 0 viewsToRemove = this.slice(newNumViews, oldNumViews) this.removeObjects viewsToRemove # if oldNumViews < newNumViews we need to add more views else if numViewsToInsert > 0 viewsToAdd = [0...numViewsToInsert].map -> view.createChildView(itemViewClass) this.pushObjects viewsToAdd , 'numChildViews', 'itemViewClass' # TODO(Peter): Consider making this a computed... binding logic will go # into the LazyItemMixin viewportDidChange: Ember.observer -> content = @get('content') or [] clength = content.get('length') numShownViews = Math.min this.get('length'), clength startIndex = @get 'startIndex' # this is a necessary check otherwise we are trying to access an object # that doesn't exists if startIndex + numShownViews >= clength startIndex = clength - numShownViews if startIndex < 0 then startIndex = 0 this.forEach (childView, i) -> # for all views that we are not using... just remove content # this makes them invisble if i >= numShownViews childView = this.objectAt(i) childView.set 'content', null return itemIndex = startIndex + i childView = this.objectAt(itemIndex % numShownViews) item = content.objectAt(itemIndex) if item isnt childView.get('content') childView.teardownContent() childView.set 'itemIndex', itemIndex childView.set 'content', item childView.prepareContent() , this , 'content.length', 'length', 'startIndex' ###* * Lazy Item View * @class * @alias Ember.LazyItemView ### Ember.LazyItemView = Ember.View.extend Ember.AddeparMixins.StyleBindingsMixin, itemIndex: null prepareContent: Ember.K teardownContent: Ember.K rowHeightBinding: 'parentView.rowHeight' styleBindings: ['width', 'top', 'display'] top: Ember.computed -> @get('itemIndex') * @get('rowHeight') .property 'itemIndex', 'rowHeight' display: Ember.computed -> 'none' if not @get('content') .property 'content'
35832
Ember.LazyContainerView = Ember.ContainerView.extend Ember.AddeparMixins.StyleBindingsMixin, classNames: 'lazy-list-container' styleBindings: ['height'] content: null itemViewClass: null rowHeight: null scrollTop: null startIndex: null init: -> @_super() @onNumChildViewsDidChange() height: Ember.computed -> @get('content.length') * @get('rowHeight') .property 'content.length', 'rowHeight' numChildViews: Ember.computed -> @get('numItemsShowing') + 2 .property 'numItemsShowing' onNumChildViewsDidChange: Ember.observer -> view = this # We are getting the class from a string e.g. "Ember.Table.Row" itemViewClass = Ember.get @get('itemViewClass') newNumViews = @get 'numChildViews' return unless itemViewClass and newNumViews oldNumViews = @get('length') numViewsToInsert = newNumViews - oldNumViews # if newNumViews < oldNumViews we need to remove some views if numViewsToInsert < 0 viewsToRemove = this.slice(newNumViews, oldNumViews) this.removeObjects viewsToRemove # if oldNumViews < newNumViews we need to add more views else if numViewsToInsert > 0 viewsToAdd = [0...numViewsToInsert].map -> view.createChildView(itemViewClass) this.pushObjects viewsToAdd , 'numChildViews', 'itemViewClass' # TODO(<NAME>): Consider making this a computed... binding logic will go # into the LazyItemMixin viewportDidChange: Ember.observer -> content = @get('content') or [] clength = content.get('length') numShownViews = Math.min this.get('length'), clength startIndex = @get 'startIndex' # this is a necessary check otherwise we are trying to access an object # that doesn't exists if startIndex + numShownViews >= clength startIndex = clength - numShownViews if startIndex < 0 then startIndex = 0 this.forEach (childView, i) -> # for all views that we are not using... just remove content # this makes them invisble if i >= numShownViews childView = this.objectAt(i) childView.set 'content', null return itemIndex = startIndex + i childView = this.objectAt(itemIndex % numShownViews) item = content.objectAt(itemIndex) if item isnt childView.get('content') childView.teardownContent() childView.set 'itemIndex', itemIndex childView.set 'content', item childView.prepareContent() , this , 'content.length', 'length', 'startIndex' ###* * Lazy Item View * @class * @alias Ember.LazyItemView ### Ember.LazyItemView = Ember.View.extend Ember.AddeparMixins.StyleBindingsMixin, itemIndex: null prepareContent: Ember.K teardownContent: Ember.K rowHeightBinding: 'parentView.rowHeight' styleBindings: ['width', 'top', 'display'] top: Ember.computed -> @get('itemIndex') * @get('rowHeight') .property 'itemIndex', 'rowHeight' display: Ember.computed -> 'none' if not @get('content') .property 'content'
true
Ember.LazyContainerView = Ember.ContainerView.extend Ember.AddeparMixins.StyleBindingsMixin, classNames: 'lazy-list-container' styleBindings: ['height'] content: null itemViewClass: null rowHeight: null scrollTop: null startIndex: null init: -> @_super() @onNumChildViewsDidChange() height: Ember.computed -> @get('content.length') * @get('rowHeight') .property 'content.length', 'rowHeight' numChildViews: Ember.computed -> @get('numItemsShowing') + 2 .property 'numItemsShowing' onNumChildViewsDidChange: Ember.observer -> view = this # We are getting the class from a string e.g. "Ember.Table.Row" itemViewClass = Ember.get @get('itemViewClass') newNumViews = @get 'numChildViews' return unless itemViewClass and newNumViews oldNumViews = @get('length') numViewsToInsert = newNumViews - oldNumViews # if newNumViews < oldNumViews we need to remove some views if numViewsToInsert < 0 viewsToRemove = this.slice(newNumViews, oldNumViews) this.removeObjects viewsToRemove # if oldNumViews < newNumViews we need to add more views else if numViewsToInsert > 0 viewsToAdd = [0...numViewsToInsert].map -> view.createChildView(itemViewClass) this.pushObjects viewsToAdd , 'numChildViews', 'itemViewClass' # TODO(PI:NAME:<NAME>END_PI): Consider making this a computed... binding logic will go # into the LazyItemMixin viewportDidChange: Ember.observer -> content = @get('content') or [] clength = content.get('length') numShownViews = Math.min this.get('length'), clength startIndex = @get 'startIndex' # this is a necessary check otherwise we are trying to access an object # that doesn't exists if startIndex + numShownViews >= clength startIndex = clength - numShownViews if startIndex < 0 then startIndex = 0 this.forEach (childView, i) -> # for all views that we are not using... just remove content # this makes them invisble if i >= numShownViews childView = this.objectAt(i) childView.set 'content', null return itemIndex = startIndex + i childView = this.objectAt(itemIndex % numShownViews) item = content.objectAt(itemIndex) if item isnt childView.get('content') childView.teardownContent() childView.set 'itemIndex', itemIndex childView.set 'content', item childView.prepareContent() , this , 'content.length', 'length', 'startIndex' ###* * Lazy Item View * @class * @alias Ember.LazyItemView ### Ember.LazyItemView = Ember.View.extend Ember.AddeparMixins.StyleBindingsMixin, itemIndex: null prepareContent: Ember.K teardownContent: Ember.K rowHeightBinding: 'parentView.rowHeight' styleBindings: ['width', 'top', 'display'] top: Ember.computed -> @get('itemIndex') * @get('rowHeight') .property 'itemIndex', 'rowHeight' display: Ember.computed -> 'none' if not @get('content') .property 'content'
[ { "context": "\n\nGenerate the Colors modal for WolfCage.\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@l", "end": 68, "score": 0.9998831748962402, "start": 54, "tag": "NAME", "value": "Destin Moulton" }, { "context": ".\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@license MIT\n\nComponent of the Wolfram C", "end": 106, "score": 0.9831504821777344, "start": 93, "tag": "USERNAME", "value": "destinmoulton" } ]
src/modals/ColorsModal.coffee
destinmoulton/cagen
0
### Generate the Colors modal for WolfCage. @author Destin Moulton @git https://github.com/destinmoulton/wolfcage @license MIT Component of the Wolfram Cellular Automata Generator (WolfCage) ### DOM = require("../DOM.coffee") Modal = require("./Modal.coffee") Templates = require("../Templates.coffee") colors = require("../lib/colors.coffee") class ColorsModal constructor: (BUS)-> @BUS = BUS @modal = new Modal() open: (broadcastChannel)-> @modal.open("Choose a Color", Templates.colorsmodalContainer) elContainer = DOM.elemById("COLORSMODAL", "CONTAINER") colorBlocks = Templates.colorsmodalColorBlocks(colors) elContainer.innerHTML = colorBlocks elBlocks = DOM.elemsByClass("COLORSMODAL", "BLOCK") for block in elBlocks block.addEventListener("click", (e)=> @BUS.broadcast(broadcastChannel, e.target.getAttribute("data-color")) @modal.close() ) module.exports = ColorsModal
153523
### Generate the Colors modal for WolfCage. @author <NAME> @git https://github.com/destinmoulton/wolfcage @license MIT Component of the Wolfram Cellular Automata Generator (WolfCage) ### DOM = require("../DOM.coffee") Modal = require("./Modal.coffee") Templates = require("../Templates.coffee") colors = require("../lib/colors.coffee") class ColorsModal constructor: (BUS)-> @BUS = BUS @modal = new Modal() open: (broadcastChannel)-> @modal.open("Choose a Color", Templates.colorsmodalContainer) elContainer = DOM.elemById("COLORSMODAL", "CONTAINER") colorBlocks = Templates.colorsmodalColorBlocks(colors) elContainer.innerHTML = colorBlocks elBlocks = DOM.elemsByClass("COLORSMODAL", "BLOCK") for block in elBlocks block.addEventListener("click", (e)=> @BUS.broadcast(broadcastChannel, e.target.getAttribute("data-color")) @modal.close() ) module.exports = ColorsModal
true
### Generate the Colors modal for WolfCage. @author PI:NAME:<NAME>END_PI @git https://github.com/destinmoulton/wolfcage @license MIT Component of the Wolfram Cellular Automata Generator (WolfCage) ### DOM = require("../DOM.coffee") Modal = require("./Modal.coffee") Templates = require("../Templates.coffee") colors = require("../lib/colors.coffee") class ColorsModal constructor: (BUS)-> @BUS = BUS @modal = new Modal() open: (broadcastChannel)-> @modal.open("Choose a Color", Templates.colorsmodalContainer) elContainer = DOM.elemById("COLORSMODAL", "CONTAINER") colorBlocks = Templates.colorsmodalColorBlocks(colors) elContainer.innerHTML = colorBlocks elBlocks = DOM.elemsByClass("COLORSMODAL", "BLOCK") for block in elBlocks block.addEventListener("click", (e)=> @BUS.broadcast(broadcastChannel, e.target.getAttribute("data-color")) @modal.close() ) module.exports = ColorsModal
[ { "context": "eoverview Tests for no-unreachable rule.\n# @author Joel Feenstra\n###\n\n'use strict'\n\n#-----------------------------", "end": 75, "score": 0.9998404383659363, "start": 62, "tag": "NAME", "value": "Joel Feenstra" } ]
src/tests/rules/no-unreachable.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-unreachable rule. # @author Joel Feenstra ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-unreachable' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-unreachable', rule, valid: [ ''' -> bar = -> return 1 return bar() ''' ''' -> x = 1 y = 2 ''' ''' foo = -> x = 1 y = 2 return ''' ''' while yes switch foo when 1 x = 1 x = 2 ''' ''' while true continue ''' ''' -> x = 1 return if x x = 2 ''' ''' -> x = 1 if x else return x = 2 ''' ''' -> x = 1 switch x when 0 break else return x = 2 ''' ''' -> x = 1 while x return x = 2 ''' ''' x = 1 for x of {} return x = 2 ''' ''' x = 1 for x in [1, 2, 3] when foo x return x = 2 ''' ''' -> x = 1 try return finally x = 2 ''' ''' -> x = 1 loop if x break x = 2 ''' ] invalid: [ code: ''' -> return x x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' until yes continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' loop continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> return x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> throw error x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes break x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' switch foo when 1 return x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' switch foo when 1 throw e x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes switch foo when 1 break x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes switch foo when 1 continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' x = 1 throw 'uh oh' y = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 if x return else throw e x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 if x return else throw -1 x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 try return finally x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 try finally return x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' x = 1 while x if x break else continue x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 loop continue if x x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 while true ; x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 loop ; x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 for item in list continue foo() x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 for key, val of obj break foo() x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , # Merge the warnings of continuous unreachable nodes. code: ''' -> return a() # โ† ERROR: Unreachable code. (no-unreachable) b() # โ†‘ ';' token is included in the unreachable code, so this statement will be merged. # comment c() # โ†‘ ')' token is included in the unreachable code, so this statement will be merged. ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 3 endLine: 8 endColumn: 6 ] , code: ''' -> return a() if b() c() else d() ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 3 endLine: 9 endColumn: 8 ] , code: ''' -> if a return b() c() else throw err d() ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 5 endLine: 5 endColumn: 8 , message: 'Unreachable code.' type: 'ExpressionStatement' line: 8 column: 5 endLine: 8 endColumn: 8 ] , code: ''' -> if a return b() c() else throw err d() e() ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 5 endLine: 5 endColumn: 8 , message: 'Unreachable code.' type: 'ExpressionStatement' line: 8 column: 5 endLine: 9 endColumn: 6 ] ]
52702
###* # @fileoverview Tests for no-unreachable rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-unreachable' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-unreachable', rule, valid: [ ''' -> bar = -> return 1 return bar() ''' ''' -> x = 1 y = 2 ''' ''' foo = -> x = 1 y = 2 return ''' ''' while yes switch foo when 1 x = 1 x = 2 ''' ''' while true continue ''' ''' -> x = 1 return if x x = 2 ''' ''' -> x = 1 if x else return x = 2 ''' ''' -> x = 1 switch x when 0 break else return x = 2 ''' ''' -> x = 1 while x return x = 2 ''' ''' x = 1 for x of {} return x = 2 ''' ''' x = 1 for x in [1, 2, 3] when foo x return x = 2 ''' ''' -> x = 1 try return finally x = 2 ''' ''' -> x = 1 loop if x break x = 2 ''' ] invalid: [ code: ''' -> return x x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' until yes continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' loop continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> return x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> throw error x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes break x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' switch foo when 1 return x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' switch foo when 1 throw e x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes switch foo when 1 break x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes switch foo when 1 continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' x = 1 throw 'uh oh' y = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 if x return else throw e x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 if x return else throw -1 x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 try return finally x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 try finally return x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' x = 1 while x if x break else continue x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 loop continue if x x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 while true ; x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 loop ; x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 for item in list continue foo() x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 for key, val of obj break foo() x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , # Merge the warnings of continuous unreachable nodes. code: ''' -> return a() # โ† ERROR: Unreachable code. (no-unreachable) b() # โ†‘ ';' token is included in the unreachable code, so this statement will be merged. # comment c() # โ†‘ ')' token is included in the unreachable code, so this statement will be merged. ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 3 endLine: 8 endColumn: 6 ] , code: ''' -> return a() if b() c() else d() ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 3 endLine: 9 endColumn: 8 ] , code: ''' -> if a return b() c() else throw err d() ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 5 endLine: 5 endColumn: 8 , message: 'Unreachable code.' type: 'ExpressionStatement' line: 8 column: 5 endLine: 8 endColumn: 8 ] , code: ''' -> if a return b() c() else throw err d() e() ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 5 endLine: 5 endColumn: 8 , message: 'Unreachable code.' type: 'ExpressionStatement' line: 8 column: 5 endLine: 9 endColumn: 6 ] ]
true
###* # @fileoverview Tests for no-unreachable rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-unreachable' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-unreachable', rule, valid: [ ''' -> bar = -> return 1 return bar() ''' ''' -> x = 1 y = 2 ''' ''' foo = -> x = 1 y = 2 return ''' ''' while yes switch foo when 1 x = 1 x = 2 ''' ''' while true continue ''' ''' -> x = 1 return if x x = 2 ''' ''' -> x = 1 if x else return x = 2 ''' ''' -> x = 1 switch x when 0 break else return x = 2 ''' ''' -> x = 1 while x return x = 2 ''' ''' x = 1 for x of {} return x = 2 ''' ''' x = 1 for x in [1, 2, 3] when foo x return x = 2 ''' ''' -> x = 1 try return finally x = 2 ''' ''' -> x = 1 loop if x break x = 2 ''' ] invalid: [ code: ''' -> return x x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' until yes continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' loop continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> return x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> throw error x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes break x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' switch foo when 1 return x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' switch foo when 1 throw e x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes switch foo when 1 break x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' while yes switch foo when 1 continue x = 1 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' x = 1 throw 'uh oh' y = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 if x return else throw e x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 if x return else throw -1 x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 try return finally x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 try finally return x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' x = 1 while x if x break else continue x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 loop continue if x x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 while true ; x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 loop ; x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 for item in list continue foo() x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , code: ''' -> x = 1 for key, val of obj break foo() x = 2 ''' errors: [message: 'Unreachable code.', type: 'ExpressionStatement'] , # Merge the warnings of continuous unreachable nodes. code: ''' -> return a() # โ† ERROR: Unreachable code. (no-unreachable) b() # โ†‘ ';' token is included in the unreachable code, so this statement will be merged. # comment c() # โ†‘ ')' token is included in the unreachable code, so this statement will be merged. ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 3 endLine: 8 endColumn: 6 ] , code: ''' -> return a() if b() c() else d() ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 3 endLine: 9 endColumn: 8 ] , code: ''' -> if a return b() c() else throw err d() ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 5 endLine: 5 endColumn: 8 , message: 'Unreachable code.' type: 'ExpressionStatement' line: 8 column: 5 endLine: 8 endColumn: 8 ] , code: ''' -> if a return b() c() else throw err d() e() ''' errors: [ message: 'Unreachable code.' type: 'ExpressionStatement' line: 4 column: 5 endLine: 5 endColumn: 8 , message: 'Unreachable code.' type: 'ExpressionStatement' line: 8 column: 5 endLine: 9 endColumn: 6 ] ]
[ { "context": "refix': 'MAGENTA'\n 'body': 'MAGENTA'\n\n 'Ray White':\n 'prefix': 'RAYWHITE'\n 'body': 'R", "end": 1720, "score": 0.9715961813926697, "start": 1711, "tag": "NAME", "value": "Ray White" } ]
snippets/python.cson
HamdyElzonqali/raylib-python-snippets-atom
0
'.source.python': 'Light Gray': 'prefix': 'LIGHTGRAY' 'body': 'LIGHTGRAY' 'Gray': 'prefix': 'GRAY' 'body': 'GRAY' 'Dark Gray': 'prefix': 'DARKGRAY' 'body': 'DARKGRAY' 'Yellow': 'prefix': 'YELLOW' 'body': 'YELLOW' 'Gold': 'prefix': 'GOLD' 'body': 'GOLD' 'Orange': 'prefix': 'ORANGE' 'body': 'ORANGE' 'Pink': 'prefix': 'PINK' 'body': 'PINK' 'Red': 'prefix': 'RED' 'body': 'RED' 'Maroon': 'prefix': 'MAROON' 'body': 'MAROON' 'Green': 'prefix': 'GREEN' 'body': 'GREEN' 'Lime': 'prefix': 'LIME' 'body': 'LIME' 'Dark Green': 'prefix': 'DARKGREEN' 'body': 'DARKGREEN' 'Sky Blue': 'prefix': 'SKYBLUE' 'body': 'SKYBLUE' 'Blue': 'prefix': 'BLUE' 'body': 'BLUE' 'Dark Blue': 'prefix': 'DARKBLUE' 'body': 'DARKBLUE' 'Purple': 'prefix': 'PURPLE' 'body': 'PURPLE' 'Violet': 'prefix': 'VIOLET' 'body': 'VIOLET' 'Dark Purple': 'prefix': 'DARKPURPLE' 'body': 'DARKPURPLE' 'Beige': 'prefix': 'BEIGE' 'body': 'BEIGE' 'Brown': 'prefix': 'BROWN' 'body': 'BROWN' 'Dark Brown': 'prefix': 'DARKBROWN' 'body': 'DARKBROWN' 'White': 'prefix': 'WHITE' 'body': 'WHITE' 'Black': 'prefix': 'BLACK' 'body': 'BLACK' 'Transparent': 'prefix': 'BLANK' 'body': 'BLANK' 'Magenta': 'prefix': 'MAGENTA' 'body': 'MAGENTA' 'Ray White': 'prefix': 'RAYWHITE' 'body': 'RAYWHITE' 'Initialize window and OpenGL context': 'prefix': 'InitWindow()' 'body': 'InitWindow($1)' 'description': 'InitWindow(int width, int height, const char title)' 'Check if KEY_ESCAPE pressed or Close icon pressed': 'prefix': 'WindowShouldClose()' 'body': 'WindowShouldClose()' 'description': 'WindowShouldClose(void)' 'Close window and unload OpenGL context': 'prefix': 'CloseWindow()' 'body': 'CloseWindow()' 'description': 'CloseWindow(void)' 'Check if window has been initialized successfully': 'prefix': 'IsWindowReady()' 'body': 'IsWindowReady()' 'description': 'IsWindowReady(void)' 'Check if window has been minimized (or lost focus)': 'prefix': 'IsWindowMinimized()' 'body': 'IsWindowMinimized()' 'description': 'IsWindowMinimized(void)' 'Check if window has been resized': 'prefix': 'IsWindowResized()' 'body': 'IsWindowResized()' 'description': 'IsWindowResized(void)' 'Check if window is currently hidden': 'prefix': 'IsWindowHidden()' 'body': 'IsWindowHidden()' 'description': 'IsWindowHidden(void)' 'Check if window is currently fullscreen': 'prefix': 'IsWindowFullscreen()' 'body': 'IsWindowFullscreen()' 'description': 'IsWindowFullscreen(void)' 'Toggle fullscreen mode (only PLATFORM_DESKTOP)': 'prefix': 'ToggleFullscreen()' 'body': 'ToggleFullscreen()' 'description': 'ToggleFullscreen(void)' 'Show the window': 'prefix': 'UnhideWindow()' 'body': 'UnhideWindow()' 'description': 'UnhideWindow(void)' 'Hide the window': 'prefix': 'HideWindow()' 'body': 'HideWindow()' 'description': 'HideWindow(void)' 'Set icon for window (only PLATFORM_DESKTOP)': 'prefix': 'SetWindowIcon()' 'body': 'SetWindowIcon($1)' 'description': 'SetWindowIcon(Image image)' 'Set title for window (only PLATFORM_DESKTOP)': 'prefix': 'SetWindowTitle()' 'body': 'SetWindowTitle($1)' 'description': 'SetWindowTitle(const char title)' 'Set window position on screen (only PLATFORM_DESKTOP)': 'prefix': 'SetWindowPosition()' 'body': 'SetWindowPosition($1)' 'description': 'SetWindowPosition(int x, int y)' 'Set monitor for the current window (fullscreen mode)': 'prefix': 'SetWindowMonitor()' 'body': 'SetWindowMonitor($1)' 'description': 'SetWindowMonitor(int monitor)' 'Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE)': 'prefix': 'SetWindowMinSize()' 'body': 'SetWindowMinSize($1)' 'description': 'SetWindowMinSize(int width, int height)' 'Set window dimensions': 'prefix': 'SetWindowSize()' 'body': 'SetWindowSize($1)' 'description': 'SetWindowSize(int width, int height)' 'Get native window handle': 'prefix': 'GetWindowHandle()' 'body': 'GetWindowHandle()' 'description': 'GetWindowHandle(void)' 'Get current screen width': 'prefix': 'GetScreenWidth()' 'body': 'GetScreenWidth()' 'description': 'GetScreenWidth(void)' 'Get current screen height': 'prefix': 'GetScreenHeight()' 'body': 'GetScreenHeight()' 'description': 'GetScreenHeight(void)' 'Get number of connected monitors': 'prefix': 'GetMonitorCount()' 'body': 'GetMonitorCount()' 'description': 'GetMonitorCount(void)' 'Get primary monitor width': 'prefix': 'GetMonitorWidth()' 'body': 'GetMonitorWidth($1)' 'description': 'GetMonitorWidth(int monitor)' 'Get primary monitor height': 'prefix': 'GetMonitorHeight()' 'body': 'GetMonitorHeight($1)' 'description': 'GetMonitorHeight(int monitor)' 'Get primary monitor physical width in millimetres': 'prefix': 'GetMonitorPhysicalWidth()' 'body': 'GetMonitorPhysicalWidth($1)' 'description': 'GetMonitorPhysicalWidth(int monitor)' 'Get primary monitor physical height in millimetres': 'prefix': 'GetMonitorPhysicalHeight()' 'body': 'GetMonitorPhysicalHeight($1)' 'description': 'GetMonitorPhysicalHeight(int monitor)' 'Get window position XY on monitor': 'prefix': 'GetWindowPosition()' 'body': 'GetWindowPosition()' 'description': 'GetWindowPosition(void)' 'Set clipboard text content': 'prefix': 'SetClipboardText()' 'body': 'SetClipboardText($1)' 'description': 'SetClipboardText(const char text)' 'Shows cursor': 'prefix': 'ShowCursor()' 'body': 'ShowCursor()' 'description': 'ShowCursor(void)' 'Hides cursor': 'prefix': 'HideCursor()' 'body': 'HideCursor()' 'description': 'HideCursor(void)' 'Check if cursor is not visible': 'prefix': 'IsCursorHidden()' 'body': 'IsCursorHidden()' 'description': 'IsCursorHidden(void)' 'Enables cursor (unlock cursor)': 'prefix': 'EnableCursor()' 'body': 'EnableCursor()' 'description': 'EnableCursor(void)' 'Disables cursor (lock cursor)': 'prefix': 'DisableCursor()' 'body': 'DisableCursor()' 'description': 'DisableCursor(void)' 'Set background color (framebuffer clear color)': 'prefix': 'ClearBackground()' 'body': 'ClearBackground($1)' 'description': 'ClearBackground(Color color)' 'Setup canvas (framebuffer) to start drawing': 'prefix': 'BeginDrawing()' 'body': 'BeginDrawing()' 'description': 'BeginDrawing(void)' 'End canvas drawing and swap buffers (double buffering)': 'prefix': 'EndDrawing()' 'body': 'EndDrawing()' 'description': 'EndDrawing(void)' 'Initialize 2D mode with custom camera (2D)': 'prefix': 'BeginMode2D()' 'body': 'BeginMode2D($1)' 'description': 'BeginMode2D(Camera2D camera)' 'Ends 2D mode with custom camera': 'prefix': 'EndMode2D()' 'body': 'EndMode2D()' 'description': 'EndMode2D(void)' 'Initializes 3D mode with custom camera (3D)': 'prefix': 'BeginMode3D()' 'body': 'BeginMode3D($1)' 'description': 'BeginMode3D(Camera3D camera)' 'Ends 3D mode and returns to default 2D orthographic mode': 'prefix': 'EndMode3D()' 'body': 'EndMode3D()' 'description': 'EndMode3D(void)' 'Initializes render texture for drawing': 'prefix': 'BeginTextureMode()' 'body': 'BeginTextureMode($1)' 'description': 'BeginTextureMode(RenderTexture2D target)' 'Ends drawing to render texture': 'prefix': 'EndTextureMode()' 'body': 'EndTextureMode()' 'description': 'EndTextureMode(void)' 'Begin scissor mode (define screen area for following drawing)': 'prefix': 'BeginScissorMode()' 'body': 'BeginScissorMode($1)' 'description': 'BeginScissorMode(int x, int y, int width, int height)' 'End scissor mode': 'prefix': 'EndScissorMode()' 'body': 'EndScissorMode()' 'description': 'EndScissorMode(void)' 'Returns a ray trace from mouse position': 'prefix': 'GetMouseRay()' 'body': 'GetMouseRay($1)' 'description': 'GetMouseRay(Vector2 mousePosition, Camera camera)' 'Returns camera transform matrix (view matrix)': 'prefix': 'GetCameraMatrix()' 'body': 'GetCameraMatrix($1)' 'description': 'GetCameraMatrix(Camera camera)' 'Returns camera 2d transform matrix': 'prefix': 'GetCameraMatrix2D()' 'body': 'GetCameraMatrix2D($1)' 'description': 'GetCameraMatrix2D(Camera2D camera)' 'Returns the screen space position for a 3d world space position': 'prefix': 'GetWorldToScreen()' 'body': 'GetWorldToScreen($1)' 'description': 'GetWorldToScreen(Vector3 position, Camera camera)' 'Returns size position for a 3d world space position': 'prefix': 'GetWorldToScreenEx()' 'body': 'GetWorldToScreenEx($1)' 'description': 'GetWorldToScreenEx(Vector3 position, Camera camera,int width, int height)' 'Returns the screen space position for a 2d camera world space position': 'prefix': 'GetWorldToScreen2D()' 'body': 'GetWorldToScreen2D($1)' 'description': 'GetWorldToScreen2D(Vector2 position, Camera2D camera)' 'Returns the world space position for a 2d camera screen space position': 'prefix': 'GetScreenToWorld2D()' 'body': 'GetScreenToWorld2D($1)' 'description': 'GetScreenToWorld2D(Vector2 position, Camera2D camera)' 'Set target FPS (maximum)': 'prefix': 'SetTargetFPS()' 'body': 'SetTargetFPS($1)' 'description': 'SetTargetFPS(int fps)' 'Returns current FPS': 'prefix': 'GetFPS()' 'body': 'GetFPS()' 'description': 'GetFPS(void)' 'Returns time in seconds for last frame drawn': 'prefix': 'GetFrameTime()' 'body': 'GetFrameTime()' 'description': 'GetFrameTime(void)' 'Returns elapsed time in seconds since InitWindow()': 'prefix': 'GetTime()' 'body': 'GetTime()' 'description': 'GetTime(void)' 'Returns hexadecimal value for a Color': 'prefix': 'ColorToInt()' 'body': 'ColorToInt($1)' 'description': 'ColorToInt(Color color)' 'Returns color normalized as float [0..1]': 'prefix': 'ColorNormalize()' 'body': 'ColorNormalize($1)' 'description': 'ColorNormalize(Color color)' 'Returns color from normalized values [0..1]': 'prefix': 'ColorFromNormalized()' 'body': 'ColorFromNormalized($1)' 'description': 'ColorFromNormalized(Vector4 normalized)' 'Returns HSV values for a Color': 'prefix': 'ColorToHSV()' 'body': 'ColorToHSV($1)' 'description': 'ColorToHSV(Color color)' 'Returns a Color from HSV values': 'prefix': 'ColorFromHSV()' 'body': 'ColorFromHSV($1)' 'description': 'ColorFromHSV(Vector3 hsv)' 'Returns a Color struct from hexadecimal value': 'prefix': 'GetColor()' 'body': 'GetColor($1)' 'description': 'GetColor(int hexValue)' 'Color fade-in or fade-out, alpha goes from 0.0f to 1.0f': 'prefix': 'Fade()' 'body': 'Fade($1)' 'description': 'Fade(Color color, float alpha)' 'Setup window configuration flags (view FLAGS)': 'prefix': 'SetConfigFlags()' 'body': 'SetConfigFlags($1)' 'description': 'SetConfigFlags(unsigned int flags)' 'Set the current threshold (minimum) log level': 'prefix': 'SetTraceLogLevel()' 'body': 'SetTraceLogLevel($1)' 'description': 'SetTraceLogLevel(int logType)' 'Set the exit threshold (minimum) log level': 'prefix': 'SetTraceLogExit()' 'body': 'SetTraceLogExit($1)' 'description': 'SetTraceLogExit(int logType)' 'Set a trace log callback to enable custom logging': 'prefix': 'SetTraceLogCallback()' 'body': 'SetTraceLogCallback($1)' 'description': 'SetTraceLogCallback(TraceLogCallback callback)' 'Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR)': 'prefix': 'TraceLog()' 'body': 'TraceLog($1)' 'description': 'TraceLog(int logType, const char text, ...)' 'Takes a screenshot of current screen (saved a .png)': 'prefix': 'TakeScreenshot()' 'body': 'TakeScreenshot($1)' 'description': 'TakeScreenshot(const char fileName)' 'Returns a random value between min and max (both included)': 'prefix': 'GetRandomValue()' 'body': 'GetRandomValue($1)' 'description': 'GetRandomValue(int min, int max)' 'Save data to file from byte array (write)': 'prefix': 'SaveFileData()' 'body': 'SaveFileData($1)' 'description': 'SaveFileData(const char fileName, void data, int bytesToWrite)' 'Save text data to file (write), string must be \' \' terminated': 'prefix': 'SaveFileText()' 'body': 'SaveFileText($1)' 'description': 'SaveFileText(const char fileName, char text)' 'Check if file exists': 'prefix': 'FileExists()' 'body': 'FileExists($1)' 'description': 'FileExists(const char fileName)' 'Check file extension': 'prefix': 'IsFileExtension()' 'body': 'IsFileExtension($1)' 'description': 'IsFileExtension(const char fileName, const char ext)' 'Check if a directory path exists': 'prefix': 'DirectoryExists()' 'body': 'DirectoryExists($1)' 'description': 'DirectoryExists(const char dirPath)' 'Clear directory files paths buffers (free memory)': 'prefix': 'ClearDirectoryFiles()' 'body': 'ClearDirectoryFiles()' 'description': 'ClearDirectoryFiles(void)' 'Change working directory, returns true if success': 'prefix': 'ChangeDirectory()' 'body': 'ChangeDirectory($1)' 'description': 'ChangeDirectory(const char dir)' 'Check if a file has been dropped into window': 'prefix': 'IsFileDropped()' 'body': 'IsFileDropped()' 'description': 'IsFileDropped(void)' 'Clear dropped files paths buffer (free memory)': 'prefix': 'ClearDroppedFiles()' 'body': 'ClearDroppedFiles()' 'description': 'ClearDroppedFiles(void)' 'Load integer value from storage file (from defined position)': 'prefix': 'LoadStorageValue()' 'body': 'LoadStorageValue($1)' 'description': 'LoadStorageValue(int position)' 'Save integer value to storage file (to defined position)': 'prefix': 'SaveStorageValue()' 'body': 'SaveStorageValue($1)' 'description': 'SaveStorageValue(int position, int value)' 'Open URL with default system browser (if available)': 'prefix': 'OpenURL()' 'body': 'OpenURL($1)' 'description': 'OpenURL(const char url)' 'Detect if a key has been pressed once': 'prefix': 'IsKeyPressed()' 'body': 'IsKeyPressed($1)' 'description': 'IsKeyPressed(int key)' 'Detect if a key is being pressed': 'prefix': 'IsKeyDown()' 'body': 'IsKeyDown($1)' 'description': 'IsKeyDown(int key)' 'Detect if a key has been released once': 'prefix': 'IsKeyReleased()' 'body': 'IsKeyReleased($1)' 'description': 'IsKeyReleased(int key)' 'Detect if a key is NOT being pressed': 'prefix': 'IsKeyUp()' 'body': 'IsKeyUp($1)' 'description': 'IsKeyUp(int key)' 'Get latest key pressed': 'prefix': 'GetKeyPressed()' 'body': 'GetKeyPressed()' 'description': 'GetKeyPressed(void)' 'Set a custom key to exit program (default is ESC)': 'prefix': 'SetExitKey()' 'body': 'SetExitKey($1)' 'description': 'SetExitKey(int key)' 'Detect if a gamepad is available': 'prefix': 'IsGamepadAvailable()' 'body': 'IsGamepadAvailable($1)' 'description': 'IsGamepadAvailable(int gamepad)' 'Check gamepad name (if available)': 'prefix': 'IsGamepadName()' 'body': 'IsGamepadName($1)' 'description': 'IsGamepadName(int gamepad, const char name)' 'Detect if a gamepad button has been pressed once': 'prefix': 'IsGamepadButtonPressed()' 'body': 'IsGamepadButtonPressed($1)' 'description': 'IsGamepadButtonPressed(int gamepad, int button)' 'Detect if a gamepad button is being pressed': 'prefix': 'IsGamepadButtonDown()' 'body': 'IsGamepadButtonDown($1)' 'description': 'IsGamepadButtonDown(int gamepad, int button)' 'Detect if a gamepad button has been released once': 'prefix': 'IsGamepadButtonReleased()' 'body': 'IsGamepadButtonReleased($1)' 'description': 'IsGamepadButtonReleased(int gamepad, int button)' 'Detect if a gamepad button is NOT being pressed': 'prefix': 'IsGamepadButtonUp()' 'body': 'IsGamepadButtonUp($1)' 'description': 'IsGamepadButtonUp(int gamepad, int button)' 'Get the last gamepad button pressed': 'prefix': 'GetGamepadButtonPressed()' 'body': 'GetGamepadButtonPressed()' 'description': 'GetGamepadButtonPressed(void)' 'Return gamepad axis count for a gamepad': 'prefix': 'GetGamepadAxisCount()' 'body': 'GetGamepadAxisCount($1)' 'description': 'GetGamepadAxisCount(int gamepad)' 'Return axis movement value for a gamepad axis': 'prefix': 'GetGamepadAxisMovement()' 'body': 'GetGamepadAxisMovement($1)' 'description': 'GetGamepadAxisMovement(int gamepad, int axis)' 'Detect if a mouse button has been pressed once': 'prefix': 'IsMouseButtonPressed()' 'body': 'IsMouseButtonPressed($1)' 'description': 'IsMouseButtonPressed(int button)' 'Detect if a mouse button is being pressed': 'prefix': 'IsMouseButtonDown()' 'body': 'IsMouseButtonDown($1)' 'description': 'IsMouseButtonDown(int button)' 'Detect if a mouse button has been released once': 'prefix': 'IsMouseButtonReleased()' 'body': 'IsMouseButtonReleased($1)' 'description': 'IsMouseButtonReleased(int button)' 'Detect if a mouse button is NOT being pressed': 'prefix': 'IsMouseButtonUp()' 'body': 'IsMouseButtonUp($1)' 'description': 'IsMouseButtonUp(int button)' 'Returns mouse position X': 'prefix': 'GetMouseX()' 'body': 'GetMouseX()' 'description': 'GetMouseX(void)' 'Returns mouse position Y': 'prefix': 'GetMouseY()' 'body': 'GetMouseY()' 'description': 'GetMouseY(void)' 'Returns mouse position XY': 'prefix': 'GetMousePosition()' 'body': 'GetMousePosition()' 'description': 'GetMousePosition(void)' 'Set mouse position XY': 'prefix': 'SetMousePosition()' 'body': 'SetMousePosition($1)' 'description': 'SetMousePosition(int x, int y)' 'Set mouse offset': 'prefix': 'SetMouseOffset()' 'body': 'SetMouseOffset($1)' 'description': 'SetMouseOffset(int offsetX, int offsetY)' 'Set mouse scaling': 'prefix': 'SetMouseScale()' 'body': 'SetMouseScale($1)' 'description': 'SetMouseScale(float scaleX, float scaleY)' 'Returns mouse wheel movement Y': 'prefix': 'GetMouseWheelMove()' 'body': 'GetMouseWheelMove()' 'description': 'GetMouseWheelMove(void)' 'Returns touch position X for touch point 0 (relative to screen size)': 'prefix': 'GetTouchX()' 'body': 'GetTouchX()' 'description': 'GetTouchX(void)' 'Returns touch position Y for touch point 0 (relative to screen size)': 'prefix': 'GetTouchY()' 'body': 'GetTouchY()' 'description': 'GetTouchY(void)' 'Returns touch position XY for a touch point index (relative to screen size)': 'prefix': 'GetTouchPosition()' 'body': 'GetTouchPosition($1)' 'description': 'GetTouchPosition(int index)' 'Enable a set of gestures using flags': 'prefix': 'SetGesturesEnabled()' 'body': 'SetGesturesEnabled($1)' 'description': 'SetGesturesEnabled(unsigned int gestureFlags)' 'Check if a gesture have been detected': 'prefix': 'IsGestureDetected()' 'body': 'IsGestureDetected($1)' 'description': 'IsGestureDetected(int gesture)' 'Get latest detected gesture': 'prefix': 'GetGestureDetected()' 'body': 'GetGestureDetected()' 'description': 'GetGestureDetected(void)' 'Get touch points count': 'prefix': 'GetTouchPointsCount()' 'body': 'GetTouchPointsCount()' 'description': 'GetTouchPointsCount(void)' 'Get gesture hold time in milliseconds': 'prefix': 'GetGestureHoldDuration()' 'body': 'GetGestureHoldDuration()' 'description': 'GetGestureHoldDuration(void)' 'Get gesture drag vector': 'prefix': 'GetGestureDragVector()' 'body': 'GetGestureDragVector()' 'description': 'GetGestureDragVector(void)' 'Get gesture drag angle': 'prefix': 'GetGestureDragAngle()' 'body': 'GetGestureDragAngle()' 'description': 'GetGestureDragAngle(void)' 'Get gesture pinch delta': 'prefix': 'GetGesturePinchVector()' 'body': 'GetGesturePinchVector()' 'description': 'GetGesturePinchVector(void)' 'Get gesture pinch angle': 'prefix': 'GetGesturePinchAngle()' 'body': 'GetGesturePinchAngle()' 'description': 'GetGesturePinchAngle(void)' 'Set camera mode (multiple camera modes available)': 'prefix': 'SetCameraMode()' 'body': 'SetCameraMode($1)' 'description': 'SetCameraMode(Camera camera, int mode)' 'Update camera position for selected mode': 'prefix': 'UpdateCamera()' 'body': 'UpdateCamera($1)' 'description': 'UpdateCamera(Camera camera)' 'Set camera pan key to combine with mouse movement (free camera)': 'prefix': 'SetCameraPanControl()' 'body': 'SetCameraPanControl($1)' 'description': 'SetCameraPanControl(int panKey)' 'Set camera alt key to combine with mouse movement (free camera)': 'prefix': 'SetCameraAltControl()' 'body': 'SetCameraAltControl($1)' 'description': 'SetCameraAltControl(int altKey)' 'Set camera smooth zoom key to combine with mouse (free camera)': 'prefix': 'SetCameraSmoothZoomControl()' 'body': 'SetCameraSmoothZoomControl($1)' 'description': 'SetCameraSmoothZoomControl(int szKey)' 'Set camera move controls (1st person and 3rd person cameras)': 'prefix': 'SetCameraMoveControls()' 'body': 'SetCameraMoveControls($1)' 'description': 'SetCameraMoveControls(int frontKey, int backKey, int rightKey, int leftKey, int upKey, int downKey)' 'Draw a pixel': 'prefix': 'DrawPixel()' 'body': 'DrawPixel($1)' 'description': 'DrawPixel(int posX, int posY, Color color)' 'Draw a pixel (Vector version)': 'prefix': 'DrawPixelV()' 'body': 'DrawPixelV($1)' 'description': 'DrawPixelV(Vector2 position, Color color)' 'Draw a line': 'prefix': 'DrawLine()' 'body': 'DrawLine($1)' 'description': 'DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color)' 'Draw a line (Vector version)': 'prefix': 'DrawLineV()' 'body': 'DrawLineV($1)' 'description': 'DrawLineV(Vector2 startPos, Vector2 endPos, Color color)' 'Draw a line defining thickness': 'prefix': 'DrawLineEx()' 'body': 'DrawLineEx($1)' 'description': 'DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color)' 'Draw a line using cubic-bezier curves in-out': 'prefix': 'DrawLineBezier()' 'body': 'DrawLineBezier($1)' 'description': 'DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color)' 'Draw lines sequence': 'prefix': 'DrawLineStrip()' 'body': 'DrawLineStrip($1)' 'description': 'DrawLineStrip(Vector2 points, int numPoints, Color color)' 'Draw a color-filled circle': 'prefix': 'DrawCircle()' 'body': 'DrawCircle($1)' 'description': 'DrawCircle(int centerX, int centerY, float radius, Color color)' 'Draw a piece of a circle': 'prefix': 'DrawCircleSector()' 'body': 'DrawCircleSector($1)' 'description': 'DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color)' 'Draw circle sector outline': 'prefix': 'DrawCircleSectorLines()' 'body': 'DrawCircleSectorLines($1)' 'description': 'DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color)' 'Draw a gradient-filled circle': 'prefix': 'DrawCircleGradient()' 'body': 'DrawCircleGradient($1)' 'description': 'DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2)' 'Draw a color-filled circle (Vector version)': 'prefix': 'DrawCircleV()' 'body': 'DrawCircleV($1)' 'description': 'DrawCircleV(Vector2 center, float radius, Color color)' 'Draw circle outline': 'prefix': 'DrawCircleLines()' 'body': 'DrawCircleLines($1)' 'description': 'DrawCircleLines(int centerX, int centerY, float radius, Color color)' 'Draw ellipse': 'prefix': 'DrawEllipse()' 'body': 'DrawEllipse($1)' 'description': 'DrawEllipse(int centerX, int centerY, float radiusH, float radiusV, Color color)' 'Draw ellipse outline': 'prefix': 'DrawEllipseLines()' 'body': 'DrawEllipseLines($1)' 'description': 'DrawEllipseLines(int centerX, int centerY, float radiusH, float radiusV, Color color)' 'Draw ring': 'prefix': 'DrawRing()' 'body': 'DrawRing($1)' 'description': 'DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color)' 'Draw ring outline': 'prefix': 'DrawRingLines()' 'body': 'DrawRingLines($1)' 'description': 'DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color)' 'Draw a color-filled rectangle': 'prefix': 'DrawRectangle()' 'body': 'DrawRectangle($1)' 'description': 'DrawRectangle(int posX, int posY, int width, int height, Color color)' 'Draw a color-filled rectangle (Vector version)': 'prefix': 'DrawRectangleV()' 'body': 'DrawRectangleV($1)' 'description': 'DrawRectangleV(Vector2 position, Vector2 size, Color color)' 'Draw a defined color-filled rectangle': 'prefix': 'DrawRectangleRec()' 'body': 'DrawRectangleRec($1)' 'description': 'DrawRectangleRec(Rectangle rec, Color color)' 'Draw a color-filled rectangle with pro parameters': 'prefix': 'DrawRectanglePro()' 'body': 'DrawRectanglePro($1)' 'description': 'DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color)' 'Draw a vertical-gradient-filled rectangle': 'prefix': 'DrawRectangleGradientV()' 'body': 'DrawRectangleGradientV($1)' 'description': 'DrawRectangleGradientV(int posX, int posY, int width, int height, Color color1, Color color2)' 'Draw a horizontal-gradient-filled rectangle': 'prefix': 'DrawRectangleGradientH()' 'body': 'DrawRectangleGradientH($1)' 'description': 'DrawRectangleGradientH(int posX, int posY, int width, int height, Color color1, Color color2)' 'Draw a gradient-filled rectangle with custom vertex colors': 'prefix': 'DrawRectangleGradientEx()' 'body': 'DrawRectangleGradientEx($1)' 'description': 'DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4)' 'Draw rectangle outline': 'prefix': 'DrawRectangleLines()' 'body': 'DrawRectangleLines($1)' 'description': 'DrawRectangleLines(int posX, int posY, int width, int height, Color color)' 'Draw rectangle outline with extended parameters': 'prefix': 'DrawRectangleLinesEx()' 'body': 'DrawRectangleLinesEx($1)' 'description': 'DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color)' 'Draw rectangle with rounded edges': 'prefix': 'DrawRectangleRounded()' 'body': 'DrawRectangleRounded($1)' 'description': 'DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color)' 'Draw rectangle with rounded edges outline': 'prefix': 'DrawRectangleRoundedLines()' 'body': 'DrawRectangleRoundedLines($1)' 'description': 'DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int lineThick, Color color)' 'Draw a color-filled triangle (vertex in counter-clockwise order!)': 'prefix': 'DrawTriangle()' 'body': 'DrawTriangle($1)' 'description': 'DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color)' 'Draw triangle outline (vertex in counter-clockwise order!)': 'prefix': 'DrawTriangleLines()' 'body': 'DrawTriangleLines($1)' 'description': 'DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color)' 'Draw a triangle fan defined by points (first vertex is the center)': 'prefix': 'DrawTriangleFan()' 'body': 'DrawTriangleFan($1)' 'description': 'DrawTriangleFan(Vector2 points, int numPoints, Color color)' 'Draw a triangle strip defined by points': 'prefix': 'DrawTriangleStrip()' 'body': 'DrawTriangleStrip($1)' 'description': 'DrawTriangleStrip(Vector2 points, int pointsCount, Color color)' 'Draw a regular polygon (Vector version)': 'prefix': 'DrawPoly()' 'body': 'DrawPoly($1)' 'description': 'DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color)' 'Draw a polygon outline of n sides': 'prefix': 'DrawPolyLines()' 'body': 'DrawPolyLines($1)' 'description': 'DrawPolyLines(Vector2 center, int sides, float radius, float rotation, Color color)' 'Check collision between two rectangles': 'prefix': 'CheckCollisionRecs()' 'body': 'CheckCollisionRecs($1)' 'description': 'CheckCollisionRecs(Rectangle rec1, Rectangle rec2)' 'Check collision between two circles': 'prefix': 'CheckCollisionCircles()' 'body': 'CheckCollisionCircles($1)' 'description': 'CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2)' 'Check collision between circle and rectangle': 'prefix': 'CheckCollisionCircleRec()' 'body': 'CheckCollisionCircleRec($1)' 'description': 'CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec)' 'Get collision rectangle for two rectangles collision': 'prefix': 'GetCollisionRec()' 'body': 'GetCollisionRec($1)' 'description': 'GetCollisionRec(Rectangle rec1, Rectangle rec2)' 'Check if point is inside rectangle': 'prefix': 'CheckCollisionPointRec()' 'body': 'CheckCollisionPointRec($1)' 'description': 'CheckCollisionPointRec(Vector2 point, Rectangle rec)' 'Check if point is inside circle': 'prefix': 'CheckCollisionPointCircle()' 'body': 'CheckCollisionPointCircle($1)' 'description': 'CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius)' 'Check if point is inside a triangle': 'prefix': 'CheckCollisionPointTriangle()' 'body': 'CheckCollisionPointTriangle($1)' 'description': 'CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3)' 'Load image from file into CPU memory (RAM)': 'prefix': 'LoadImage()' 'body': 'LoadImage($1)' 'description': 'LoadImage(const char fileName)' 'Load image from Color array data (RGBA - 32bit)': 'prefix': 'LoadImageEx()' 'body': 'LoadImageEx($1)' 'description': 'LoadImageEx(Color pixels, int width, int height)' 'Load image from raw data with parameters': 'prefix': 'LoadImagePro()' 'body': 'LoadImagePro($1)' 'description': 'LoadImagePro(void data, int width, int height, int format)' 'Load image from RAW file data': 'prefix': 'LoadImageRaw()' 'body': 'LoadImageRaw($1)' 'description': 'LoadImageRaw(const char fileName, int width, int height, int format, int headerSize)' 'Unload image from CPU memory (RAM)': 'prefix': 'UnloadImage()' 'body': 'UnloadImage($1)' 'description': 'UnloadImage(Image image)' 'Export image data to file': 'prefix': 'ExportImage()' 'body': 'ExportImage($1)' 'description': 'ExportImage(Image image, const char fileName)' 'Export image as code file defining an array of bytes': 'prefix': 'ExportImageAsCode()' 'body': 'ExportImageAsCode($1)' 'description': 'ExportImageAsCode(Image image, const char fileName)' 'Get pixel data from image as a Color struct array': 'prefix': 'GetImageData()' 'body': 'GetImageData($1)' 'description': 'GetImageData(Image image)' 'Get pixel data from image as Vector4 array (float normalized)': 'prefix': 'GetImageDataNormalized()' 'body': 'GetImageDataNormalized($1)' 'description': 'GetImageDataNormalized(Image image)' 'Generate image: plain color': 'prefix': 'GenImageColor()' 'body': 'GenImageColor($1)' 'description': 'GenImageColor(int width, int height, Color color)' 'Generate image: vertical gradient': 'prefix': 'GenImageGradientV()' 'body': 'GenImageGradientV($1)' 'description': 'GenImageGradientV(int width, int height, Color top, Color bottom)' 'Generate image: horizontal gradient': 'prefix': 'GenImageGradientH()' 'body': 'GenImageGradientH($1)' 'description': 'GenImageGradientH(int width, int height, Color left, Color right)' 'Generate image: radial gradient': 'prefix': 'GenImageGradientRadial()' 'body': 'GenImageGradientRadial($1)' 'description': 'GenImageGradientRadial(int width, int height, float density, Color inner, Color outer)' 'Generate image: checked': 'prefix': 'GenImageChecked()' 'body': 'GenImageChecked($1)' 'description': 'GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2)' 'Generate image: white noise': 'prefix': 'GenImageWhiteNoise()' 'body': 'GenImageWhiteNoise($1)' 'description': 'GenImageWhiteNoise(int width, int height, float factor)' 'Generate image: perlin noise': 'prefix': 'GenImagePerlinNoise()' 'body': 'GenImagePerlinNoise($1)' 'description': 'GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale)' 'Generate image: cellular algorithm. Bigger tileSize means bigger cells': 'prefix': 'GenImageCellular()' 'body': 'GenImageCellular($1)' 'description': 'GenImageCellular(int width, int height, int tileSize)' 'Create an image duplicate (useful for transformations)': 'prefix': 'ImageCopy()' 'body': 'ImageCopy($1)' 'description': 'ImageCopy(Image image)' 'Create an image from another image piece': 'prefix': 'ImageFromImage()' 'body': 'ImageFromImage($1)' 'description': 'ImageFromImage(Image image, Rectangle rec)' 'Create an image from text (default font)': 'prefix': 'ImageText()' 'body': 'ImageText($1)' 'description': 'ImageText(const char text, int fontSize, Color color)' 'Create an image from text (custom sprite font)': 'prefix': 'ImageTextEx()' 'body': 'ImageTextEx($1)' 'description': 'ImageTextEx(Font font, const char text, float fontSize, float spacing, Color tint)' 'Convert image to POT (power-of-two)': 'prefix': 'ImageToPOT()' 'body': 'ImageToPOT($1)' 'description': 'ImageToPOT(Image image, Color fillColor)' 'Convert image data to desired format': 'prefix': 'ImageFormat()' 'body': 'ImageFormat($1)' 'description': 'ImageFormat(Image image, int newFormat)' 'Apply alpha mask to image': 'prefix': 'ImageAlphaMask()' 'body': 'ImageAlphaMask($1)' 'description': 'ImageAlphaMask(Image image, Image alphaMask)' 'Clear alpha channel to desired color': 'prefix': 'ImageAlphaClear()' 'body': 'ImageAlphaClear($1)' 'description': 'ImageAlphaClear(Image image, Color color, float threshold)' 'Crop image depending on alpha value': 'prefix': 'ImageAlphaCrop()' 'body': 'ImageAlphaCrop($1)' 'description': 'ImageAlphaCrop(Image image, float threshold)' 'Premultiply alpha channel': 'prefix': 'ImageAlphaPremultiply()' 'body': 'ImageAlphaPremultiply($1)' 'description': 'ImageAlphaPremultiply(Image image)' 'Crop an image to a defined rectangle': 'prefix': 'ImageCrop()' 'body': 'ImageCrop($1)' 'description': 'ImageCrop(Image image, Rectangle crop)' 'Resize image (Bicubic scaling algorithm)': 'prefix': 'ImageResize()' 'body': 'ImageResize($1)' 'description': 'ImageResize(Image image, int newWidth, int newHeight)' 'Resize image (Nearest-Neighbor scaling algorithm)': 'prefix': 'ImageResizeNN()' 'body': 'ImageResizeNN($1)' 'description': 'ImageResizeNN(Image image, int newWidth,int newHeight)' 'Resize canvas and fill with color': 'prefix': 'ImageResizeCanvas()' 'body': 'ImageResizeCanvas($1)' 'description': 'ImageResizeCanvas(Image image, int newWidth, int newHeight, int offsetX, int offsetY, Color color)' 'Generate all mipmap levels for a provided image': 'prefix': 'ImageMipmaps()' 'body': 'ImageMipmaps($1)' 'description': 'ImageMipmaps(Image image)' 'Dither image data to 16bpp or lower (Floyd-Steinberg dithering)': 'prefix': 'ImageDither()' 'body': 'ImageDither($1)' 'description': 'ImageDither(Image image, int rBpp, int gBpp, int bBpp, int aBpp)' 'Flip image vertically': 'prefix': 'ImageFlipVertical()' 'body': 'ImageFlipVertical($1)' 'description': 'ImageFlipVertical(Image image)' 'Flip image horizontally': 'prefix': 'ImageFlipHorizontal()' 'body': 'ImageFlipHorizontal($1)' 'description': 'ImageFlipHorizontal(Image image)' 'Rotate image clockwise 90deg': 'prefix': 'ImageRotateCW()' 'body': 'ImageRotateCW($1)' 'description': 'ImageRotateCW(Image image)' 'Rotate image counter-clockwise 90deg': 'prefix': 'ImageRotateCCW()' 'body': 'ImageRotateCCW($1)' 'description': 'ImageRotateCCW(Image image)' 'Modify image color: tint': 'prefix': 'ImageColorTint()' 'body': 'ImageColorTint($1)' 'description': 'ImageColorTint(Image image, Color color)' 'Modify image color: invert': 'prefix': 'ImageColorInvert()' 'body': 'ImageColorInvert($1)' 'description': 'ImageColorInvert(Image image)' 'Modify image color: grayscale': 'prefix': 'ImageColorGrayscale()' 'body': 'ImageColorGrayscale($1)' 'description': 'ImageColorGrayscale(Image image)' 'Modify image color: contrast (-100 to 100)': 'prefix': 'ImageColorContrast()' 'body': 'ImageColorContrast($1)' 'description': 'ImageColorContrast(Image image, float contrast)' 'Modify image color: brightness (-255 to 255)': 'prefix': 'ImageColorBrightness()' 'body': 'ImageColorBrightness($1)' 'description': 'ImageColorBrightness(Image image, int brightness)' 'Modify image color: replace color': 'prefix': 'ImageColorReplace()' 'body': 'ImageColorReplace($1)' 'description': 'ImageColorReplace(Image image, Color color, Color replace)' 'Extract color palette from image to maximum size (memory should be freed)': 'prefix': 'ImageExtractPalette()' 'body': 'ImageExtractPalette($1)' 'description': 'ImageExtractPalette(Image image, int maxPaletteSize, int extractCount)' 'Get image alpha border rectangle': 'prefix': 'GetImageAlphaBorder()' 'body': 'GetImageAlphaBorder($1)' 'description': 'GetImageAlphaBorder(Image image, float threshold)' 'Clear image background with given color': 'prefix': 'ImageClearBackground()' 'body': 'ImageClearBackground($1)' 'description': 'ImageClearBackground(Image dst, Color color)' 'Draw pixel within an image': 'prefix': 'ImageDrawPixel()' 'body': 'ImageDrawPixel($1)' 'description': 'ImageDrawPixel(Image dst, int posX, int posY, Color color)' 'Draw pixel within an image (Vector version)': 'prefix': 'ImageDrawPixelV()' 'body': 'ImageDrawPixelV($1)' 'description': 'ImageDrawPixelV(Image dst, Vector2 position, Color color)' 'Draw line within an image': 'prefix': 'ImageDrawLine()' 'body': 'ImageDrawLine($1)' 'description': 'ImageDrawLine(Image dst, int startPosX, int startPosY, int endPosX, int endPosY, Color color)' 'Draw line within an image (Vector version)': 'prefix': 'ImageDrawLineV()' 'body': 'ImageDrawLineV($1)' 'description': 'ImageDrawLineV(Image dst, Vector2 start, Vector2 end, Color color)' 'Draw circle within an image': 'prefix': 'ImageDrawCircle()' 'body': 'ImageDrawCircle($1)' 'description': 'ImageDrawCircle(Image dst, int centerX, int centerY, int radius, Color color)' 'Draw circle within an image (Vector version)': 'prefix': 'ImageDrawCircleV()' 'body': 'ImageDrawCircleV($1)' 'description': 'ImageDrawCircleV(Image dst, Vector2 center, int radius, Color color)' 'Draw rectangle within an image': 'prefix': 'ImageDrawRectangle()' 'body': 'ImageDrawRectangle($1)' 'description': 'ImageDrawRectangle(Image dst, int posX, int posY, int width, int height, Color color)' 'Draw rectangle within an image (Vector version)': 'prefix': 'ImageDrawRectangleV()' 'body': 'ImageDrawRectangleV($1)' 'description': 'ImageDrawRectangleV(Image dst, Vector2 position, Vector2 size, Color color)' 'Draw defined rectangle within an image': 'prefix': 'ImageDrawRectangleRec()' 'body': 'ImageDrawRectangleRec($1)' 'description': 'ImageDrawRectangleRec(Image dst, Rectangle rec, Color color)' 'Draw rectangle lines within an image': 'prefix': 'ImageDrawRectangleLines()' 'body': 'ImageDrawRectangleLines($1)' 'description': 'ImageDrawRectangleLines(Image dst, Rectangle rec, int thick, Color color)' 'Draw a source image within a destination image (tint applied to source)': 'prefix': 'ImageDraw()' 'body': 'ImageDraw($1)' 'description': 'ImageDraw(Image dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint)' 'Draw text (default font) within an image (destination)': 'prefix': 'ImageDrawText()' 'body': 'ImageDrawText($1)' 'description': 'ImageDrawText(Image dst, Vector2 position, const char text, int fontSize, Color color)' 'Draw text (custom sprite font) within an image (destination)': 'prefix': 'ImageDrawTextEx()' 'body': 'ImageDrawTextEx($1)' 'description': 'ImageDrawTextEx(Image dst, Vector2 position, Font font, const char text, float fontSize, float spacing, Color color)' 'Unload texture from GPU memory (VRAM)': 'prefix': 'UnloadTexture()' 'body': 'UnloadTexture($1)' 'description': 'UnloadTexture(Texture2D texture)' 'Unload render texture from GPU memory (VRAM)': 'prefix': 'UnloadRenderTexture()' 'body': 'UnloadRenderTexture($1)' 'description': 'UnloadRenderTexture(RenderTexture2D target)' 'Update GPU texture with new data': 'prefix': 'UpdateTexture()' 'body': 'UpdateTexture($1)' 'description': 'UpdateTexture(Texture2D texture, const void pixels)' 'Get pixel data from GPU texture and return an Image': 'prefix': 'GetTextureData()' 'body': 'GetTextureData($1)' 'description': 'GetTextureData(Texture2D texture)' 'Get pixel data from screen buffer and return an Image (screenshot)': 'prefix': 'GetScreenData()' 'body': 'GetScreenData()' 'description': 'GetScreenData(void)' 'Generate GPU mipmaps for a texture': 'prefix': 'GenTextureMipmaps()' 'body': 'GenTextureMipmaps($1)' 'description': 'GenTextureMipmaps(Texture2D texture)' 'Set texture scaling filter mode': 'prefix': 'SetTextureFilter()' 'body': 'SetTextureFilter($1)' 'description': 'SetTextureFilter(Texture2D texture, int filterMode)' 'Set texture wrapping mode': 'prefix': 'SetTextureWrap()' 'body': 'SetTextureWrap($1)' 'description': 'SetTextureWrap(Texture2D texture, int wrapMode)' 'Draw a Texture2D': 'prefix': 'DrawTexture()' 'body': 'DrawTexture($1)' 'description': 'DrawTexture(Texture2D texture, int posX, int posY, Color tint)' 'Draw a Texture2D with position defined as Vector2': 'prefix': 'DrawTextureV()' 'body': 'DrawTextureV($1)' 'description': 'DrawTextureV(Texture2D texture, Vector2 position, Color tint)' 'Draw a Texture2D with extended parameters': 'prefix': 'DrawTextureEx()' 'body': 'DrawTextureEx($1)' 'description': 'DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint)' 'Draw a part of a texture defined by a rectangle': 'prefix': 'DrawTextureRec()' 'body': 'DrawTextureRec($1)' 'description': 'DrawTextureRec(Texture2D texture, Rectangle sourceRec, Vector2 position, Color tint)' 'Draw texture quad with tiling and offset parameters': 'prefix': 'DrawTextureQuad()' 'body': 'DrawTextureQuad($1)' 'description': 'DrawTextureQuad(Texture2D texture, Vector2 tiling, Vector2 offset, Rectangle quad, Color tint)' 'Draw a part of a texture defined by a rectangle with \'pro\' parameters': 'prefix': 'DrawTexturePro()' 'body': 'DrawTexturePro($1)' 'description': 'DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, Vector2 origin, float rotation, Color tint)' 'Draws a texture (or part of it) that stretches or shrinks nicely': 'prefix': 'DrawTextureNPatch()' 'body': 'DrawTextureNPatch($1)' 'description': 'DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle destRec, Vector2 origin, float rotation, Color tint)' 'Get pixel data size in bytes (image or texture)': 'prefix': 'GetPixelDataSize()' 'body': 'GetPixelDataSize($1)' 'description': 'GetPixelDataSize(int width, int height, int format)' 'Get the default Font': 'prefix': 'GetFontDefault()' 'body': 'GetFontDefault()' 'description': 'GetFontDefault(void)' 'Load font from file into GPU memory (VRAM)': 'prefix': 'LoadFont()' 'body': 'LoadFont($1)' 'description': 'LoadFont(const char fileName)' 'Load font from file with extended parameters': 'prefix': 'LoadFontEx()' 'body': 'LoadFontEx($1)' 'description': 'LoadFontEx(const char fileName, int fontSize, int fontChars, int charsCount)' 'Load font from Image (XNA style)': 'prefix': 'LoadFontFromImage()' 'body': 'LoadFontFromImage($1)' 'description': 'LoadFontFromImage(Image image, Color key, int firstChar)' 'Load font data for further use': 'prefix': 'LoadFontData()' 'body': 'LoadFontData($1)' 'description': 'LoadFontData(const char fileName, int fontSize, int fontChars, int charsCount, int type)' 'Generate image font atlas using chars info': 'prefix': 'GenImageFontAtlas()' 'body': 'GenImageFontAtlas($1)' 'description': 'GenImageFontAtlas(const CharInfo chars, Rectangle recs, int charsCount, int fontSize, int padding, int packMethod)' 'Unload Font from GPU memory (VRAM)': 'prefix': 'UnloadFont()' 'body': 'UnloadFont($1)' 'description': 'UnloadFont(Font font)' 'Shows current FPS': 'prefix': 'DrawFPS()' 'body': 'DrawFPS($1)' 'description': 'DrawFPS(int posX, int posY)' 'Draw text (using default font)': 'prefix': 'DrawText()' 'body': 'DrawText($1)' 'description': 'DrawText(const char text, int posX, int posY, int fontSize, Color color)' 'Draw text using font and additional parameters': 'prefix': 'DrawTextEx()' 'body': 'DrawTextEx($1)' 'description': 'DrawTextEx(Font font, const char text, Vector2 position, float fontSize, float spacing, Color tint)' 'Draw text using font inside rectangle limits': 'prefix': 'DrawTextRec()' 'body': 'DrawTextRec($1)' 'description': 'DrawTextRec(Font font, const char text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint)' 'Draw text using font inside rectangle limits with support for text selection': 'prefix': 'DrawTextRecEx()' 'body': 'DrawTextRecEx($1)' 'description': 'DrawTextRecEx(Font font, const char text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, int selectStart, int selectLength, Color selectTint, Color selectBackTint)' 'Draw one character (codepoint)': 'prefix': 'DrawTextCodepoint()' 'body': 'DrawTextCodepoint($1)' 'description': 'DrawTextCodepoint(Font font, int codepoint, Vector2 position, float scale, Color tint)' 'Measure string width for default font': 'prefix': 'MeasureText()' 'body': 'MeasureText($1)' 'description': 'MeasureText(const char text, int fontSize)' 'Measure string size for Font': 'prefix': 'MeasureTextEx()' 'body': 'MeasureTextEx($1)' 'description': 'MeasureTextEx(Font font, const char text, float fontSize, float spacing)' 'Get index position for a unicode character on font': 'prefix': 'GetGlyphIndex()' 'body': 'GetGlyphIndex($1)' 'description': 'GetGlyphIndex(Font font, int codepoint)' 'Copy one string to another, returns bytes copied': 'prefix': 'TextCopy()' 'body': 'TextCopy($1)' 'description': 'TextCopy(char dst, const char src)' 'Check if two text string are equal': 'prefix': 'TextIsEqual()' 'body': 'TextIsEqual($1)' 'description': 'TextIsEqual(const char text1, const char text2)' 'Append text at specific position and move cursor!': 'prefix': 'TextAppend()' 'body': 'TextAppend($1)' 'description': 'TextAppend(char text, const char append, int position)' 'Find first text occurrence within a string': 'prefix': 'TextFindIndex()' 'body': 'TextFindIndex($1)' 'description': 'TextFindIndex(const char text, const char find)' 'Get integer value from text (negative values not supported)': 'prefix': 'TextToInteger()' 'body': 'TextToInteger($1)' 'description': 'TextToInteger(const char text)' 'Get all codepoints in a string, codepoints count returned by parameters': 'prefix': 'GetCodepoints()' 'body': 'GetCodepoints($1)' 'description': 'GetCodepoints(const char text, int count)' 'Get total number of characters (codepoints) in a UTF8 encoded string': 'prefix': 'GetCodepointsCount()' 'body': 'GetCodepointsCount($1)' 'description': 'GetCodepointsCount(const char text)' 'Returns next codepoint in a UTF8 encoded string; 0x3f(\'?\') is returned on failure': 'prefix': 'GetNextCodepoint()' 'body': 'GetNextCodepoint($1)' 'description': 'GetNextCodepoint(const char text, int bytesProcessed)' 'Draw a line in 3D world space': 'prefix': 'DrawLine3D()' 'body': 'DrawLine3D($1)' 'description': 'DrawLine3D(Vector3 startPos, Vector3 endPos, Color color)' 'Draw a point in 3D space, actually a small line': 'prefix': 'DrawPoint3D()' 'body': 'DrawPoint3D($1)' 'description': 'DrawPoint3D(Vector3 position, Color color)' 'Draw a circle in 3D world space': 'prefix': 'DrawCircle3D()' 'body': 'DrawCircle3D($1)' 'description': 'DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color)' 'Draw cube': 'prefix': 'DrawCube()' 'body': 'DrawCube($1)' 'description': 'DrawCube(Vector3 position, float width, float height, float length, Color color)' 'Draw cube (Vector version)': 'prefix': 'DrawCubeV()' 'body': 'DrawCubeV($1)' 'description': 'DrawCubeV(Vector3 position, Vector3 size, Color color)' 'Draw cube wires': 'prefix': 'DrawCubeWires()' 'body': 'DrawCubeWires($1)' 'description': 'DrawCubeWires(Vector3 position, float width, float height, float length, Color color)' 'Draw cube wires (Vector version)': 'prefix': 'DrawCubeWiresV()' 'body': 'DrawCubeWiresV($1)' 'description': 'DrawCubeWiresV(Vector3 position, Vector3 size, Color color)' 'Draw cube textured': 'prefix': 'DrawCubeTexture()' 'body': 'DrawCubeTexture($1)' 'description': 'DrawCubeTexture(Texture2D texture, Vector3 position, float width, float height, float length, Color color)' 'Draw sphere': 'prefix': 'DrawSphere()' 'body': 'DrawSphere($1)' 'description': 'DrawSphere(Vector3 centerPos, float radius, Color color)' 'Draw sphere with extended parameters': 'prefix': 'DrawSphereEx()' 'body': 'DrawSphereEx($1)' 'description': 'DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color)' 'Draw sphere wires': 'prefix': 'DrawSphereWires()' 'body': 'DrawSphereWires($1)' 'description': 'DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color)' 'Draw a cylinder/cone': 'prefix': 'DrawCylinder()' 'body': 'DrawCylinder($1)' 'description': 'DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color)' 'Draw a cylinder/cone wires': 'prefix': 'DrawCylinderWires()' 'body': 'DrawCylinderWires($1)' 'description': 'DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color)' 'Draw a plane XZ': 'prefix': 'DrawPlane()' 'body': 'DrawPlane($1)' 'description': 'DrawPlane(Vector3 centerPos, Vector2 size, Color color)' 'Draw a ray line': 'prefix': 'DrawRay()' 'body': 'DrawRay($1)' 'description': 'DrawRay(Ray ray, Color color)' 'Draw a grid (centered at (0, 0, 0))': 'prefix': 'DrawGrid()' 'body': 'DrawGrid($1)' 'description': 'DrawGrid(int slices, float spacing)' 'Draw simple gizmo': 'prefix': 'DrawGizmo()' 'body': 'DrawGizmo($1)' 'description': 'DrawGizmo(Vector3 position)' 'Load model from files (meshes and materials)': 'prefix': 'LoadModel()' 'body': 'LoadModel($1)' 'description': 'LoadModel(const char fileName)' 'Load model from generated mesh (default material)': 'prefix': 'LoadModelFromMesh()' 'body': 'LoadModelFromMesh($1)' 'description': 'LoadModelFromMesh(Mesh mesh)' 'Unload model from memory (RAM and/or VRAM)': 'prefix': 'UnloadModel()' 'body': 'UnloadModel($1)' 'description': 'UnloadModel(Model model)' 'Load meshes from model file': 'prefix': 'LoadMeshes()' 'body': 'LoadMeshes($1)' 'description': 'LoadMeshes(const char fileName, int meshCount)' 'Export mesh data to file': 'prefix': 'ExportMesh()' 'body': 'ExportMesh($1)' 'description': 'ExportMesh(Mesh mesh, const char fileName)' 'Unload mesh from memory (RAM and/or VRAM)': 'prefix': 'UnloadMesh()' 'body': 'UnloadMesh($1)' 'description': 'UnloadMesh(Mesh mesh)' 'Load materials from model file': 'prefix': 'LoadMaterials()' 'body': 'LoadMaterials($1)' 'description': 'LoadMaterials(const char fileName, int materialCount)' 'Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps)': 'prefix': 'LoadMaterialDefault()' 'body': 'LoadMaterialDefault()' 'description': 'LoadMaterialDefault(void)' 'Unload material from GPU memory (VRAM)': 'prefix': 'UnloadMaterial()' 'body': 'UnloadMaterial($1)' 'description': 'UnloadMaterial(Material material)' 'Set texture for a material map type (MAP_DIFFUSE, MAP_SPECULAR...)': 'prefix': 'SetMaterialTexture()' 'body': 'SetMaterialTexture($1)' 'description': 'SetMaterialTexture(Material material, int mapType, Texture2D texture)' 'Set material for a mesh': 'prefix': 'SetModelMeshMaterial()' 'body': 'SetModelMeshMaterial($1)' 'description': 'SetModelMeshMaterial(Model model, int meshId, int materialId)' 'Load model animations from file': 'prefix': 'LoadModelAnimations()' 'body': 'LoadModelAnimations($1)' 'description': 'LoadModelAnimations(const char fileName, int animsCount)' 'Update model animation pose': 'prefix': 'UpdateModelAnimation()' 'body': 'UpdateModelAnimation($1)' 'description': 'UpdateModelAnimation(Model model, ModelAnimation anim, int frame)' 'Unload animation data': 'prefix': 'UnloadModelAnimation()' 'body': 'UnloadModelAnimation($1)' 'description': 'UnloadModelAnimation(ModelAnimation anim)' 'Check model animation skeleton match': 'prefix': 'IsModelAnimationValid()' 'body': 'IsModelAnimationValid($1)' 'description': 'IsModelAnimationValid(Model model, ModelAnimation anim)' 'Generate polygonal mesh': 'prefix': 'GenMeshPoly()' 'body': 'GenMeshPoly($1)' 'description': 'GenMeshPoly(int sides, float radius)' 'Generate plane mesh (with subdivisions)': 'prefix': 'GenMeshPlane()' 'body': 'GenMeshPlane($1)' 'description': 'GenMeshPlane(float width, float length, int resX, int resZ)' 'Generate cuboid mesh': 'prefix': 'GenMeshCube()' 'body': 'GenMeshCube($1)' 'description': 'GenMeshCube(float width, float height, float length)' 'Generate sphere mesh (standard sphere)': 'prefix': 'GenMeshSphere()' 'body': 'GenMeshSphere($1)' 'description': 'GenMeshSphere(float radius, int rings, int slices)' 'Generate half-sphere mesh (no bottom cap)': 'prefix': 'GenMeshHemiSphere()' 'body': 'GenMeshHemiSphere($1)' 'description': 'GenMeshHemiSphere(float radius, int rings, int slices)' 'Generate cylinder mesh': 'prefix': 'GenMeshCylinder()' 'body': 'GenMeshCylinder($1)' 'description': 'GenMeshCylinder(float radius, float height, int slices)' 'Generate torus mesh': 'prefix': 'GenMeshTorus()' 'body': 'GenMeshTorus($1)' 'description': 'GenMeshTorus(float radius, float size, int radSeg, int sides)' 'Generate trefoil knot mesh': 'prefix': 'GenMeshKnot()' 'body': 'GenMeshKnot($1)' 'description': 'GenMeshKnot(float radius, float size, int radSeg, int sides)' 'Generate heightmap mesh from image data': 'prefix': 'GenMeshHeightmap()' 'body': 'GenMeshHeightmap($1)' 'description': 'GenMeshHeightmap(Image heightmap, Vector3 size)' 'Generate cubes-based map mesh from image data': 'prefix': 'GenMeshCubicmap()' 'body': 'GenMeshCubicmap($1)' 'description': 'GenMeshCubicmap(Image cubicmap, Vector3 cubeSize)' 'Compute mesh bounding box limits': 'prefix': 'MeshBoundingBox()' 'body': 'MeshBoundingBox($1)' 'description': 'MeshBoundingBox(Mesh mesh)' 'Compute mesh tangents': 'prefix': 'MeshTangents()' 'body': 'MeshTangents($1)' 'description': 'MeshTangents(Mesh mesh)' 'Compute mesh binormals': 'prefix': 'MeshBinormals()' 'body': 'MeshBinormals($1)' 'description': 'MeshBinormals(Mesh mesh)' 'Draw a model (with texture if set)': 'prefix': 'DrawModel()' 'body': 'DrawModel($1)' 'description': 'DrawModel(Model model, Vector3 position, float scale, Color tint)' 'Draw a model with extended parameters': 'prefix': 'DrawModelEx()' 'body': 'DrawModelEx($1)' 'description': 'DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint)' 'Draw a model wires (with texture if set)': 'prefix': 'DrawModelWires()' 'body': 'DrawModelWires($1)' 'description': 'DrawModelWires(Model model, Vector3 position, float scale, Color tint)' 'Draw a model wires (with texture if set) with extended parameters': 'prefix': 'DrawModelWiresEx()' 'body': 'DrawModelWiresEx($1)' 'description': 'DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint)' 'Draw bounding box (wires)': 'prefix': 'DrawBoundingBox()' 'body': 'DrawBoundingBox($1)' 'description': 'DrawBoundingBox(BoundingBox box, Color color)' 'Draw a billboard texture': 'prefix': 'DrawBillboard()' 'body': 'DrawBillboard($1)' 'description': 'DrawBillboard(Camera camera, Texture2D texture, Vector3 center, float size, Color tint)' 'Draw a billboard texture defined by sourceRec': 'prefix': 'DrawBillboardRec()' 'body': 'DrawBillboardRec($1)' 'description': 'DrawBillboardRec(Camera camera, Texture2D texture, Rectangle sourceRec, Vector3 center, float size, Color tint)' 'Detect collision between two spheres': 'prefix': 'CheckCollisionSpheres()' 'body': 'CheckCollisionSpheres($1)' 'description': 'CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB)' 'Detect collision between two bounding boxes': 'prefix': 'CheckCollisionBoxes()' 'body': 'CheckCollisionBoxes($1)' 'description': 'CheckCollisionBoxes(BoundingBox box1, BoundingBox box2)' 'Detect collision between box and sphere': 'prefix': 'CheckCollisionBoxSphere()' 'body': 'CheckCollisionBoxSphere($1)' 'description': 'CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius)' 'Detect collision between ray and sphere': 'prefix': 'CheckCollisionRaySphere()' 'body': 'CheckCollisionRaySphere($1)' 'description': 'CheckCollisionRaySphere(Ray ray, Vector3 center, float radius)' 'Detect collision between ray and sphere, returns collision point': 'prefix': 'CheckCollisionRaySphereEx()' 'body': 'CheckCollisionRaySphereEx($1)' 'description': 'CheckCollisionRaySphereEx(Ray ray, Vector3 center, float radius, Vector3 collisionPoint)' 'Detect collision between ray and box': 'prefix': 'CheckCollisionRayBox()' 'body': 'CheckCollisionRayBox($1)' 'description': 'CheckCollisionRayBox(Ray ray, BoundingBox box)' 'Get collision info between ray and model': 'prefix': 'GetCollisionRayModel()' 'body': 'GetCollisionRayModel($1)' 'description': 'GetCollisionRayModel(Ray ray, Model model)' 'Get collision info between ray and triangle': 'prefix': 'GetCollisionRayTriangle()' 'body': 'GetCollisionRayTriangle($1)' 'description': 'GetCollisionRayTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3)' 'Get collision info between ray and ground plane (Y-normal plane)': 'prefix': 'GetCollisionRayGround()' 'body': 'GetCollisionRayGround($1)' 'description': 'GetCollisionRayGround(Ray ray, float groundHeight)' 'Load shader from files and bind default locations': 'prefix': 'LoadShader()' 'body': 'LoadShader($1)' 'description': 'LoadShader(const char vsFileName, const char fsFileName)' 'Load shader from code strings and bind default locations': 'prefix': 'LoadShaderCode()' 'body': 'LoadShaderCode($1)' 'description': 'LoadShaderCode(char vsCode, char fsCode)' 'Unload shader from GPU memory (VRAM)': 'prefix': 'UnloadShader()' 'body': 'UnloadShader($1)' 'description': 'UnloadShader(Shader shader)' 'Get default shader': 'prefix': 'GetShaderDefault()' 'body': 'GetShaderDefault()' 'description': 'GetShaderDefault(void)' 'Get texture rectangle to draw shapes': 'prefix': 'GetShapesTextureRec()' 'body': 'GetShapesTextureRec()' 'description': 'GetShapesTextureRec(void)' 'Define default texture used to draw shapes': 'prefix': 'SetShapesTexture()' 'body': 'SetShapesTexture($1)' 'description': 'SetShapesTexture(Texture2D texture, Rectangle source)' 'Get shader uniform location': 'prefix': 'GetShaderLocation()' 'body': 'GetShaderLocation($1)' 'description': 'GetShaderLocation(Shader shader, const char uniformName)' 'Set shader uniform value': 'prefix': 'SetShaderValue()' 'body': 'SetShaderValue($1)' 'description': 'SetShaderValue(Shader shader, int uniformLoc, const void value, int uniformType)' 'Set shader uniform value vector': 'prefix': 'SetShaderValueV()' 'body': 'SetShaderValueV($1)' 'description': 'SetShaderValueV(Shader shader, int uniformLoc, const void value, int uniformType, int count)' 'Set shader uniform value (matrix 4x4)': 'prefix': 'SetShaderValueMatrix()' 'body': 'SetShaderValueMatrix($1)' 'description': 'SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat)' 'Set shader uniform value for texture': 'prefix': 'SetShaderValueTexture()' 'body': 'SetShaderValueTexture($1)' 'description': 'SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D texture)' 'Set a custom projection matrix (replaces internal projection matrix)': 'prefix': 'SetMatrixProjection()' 'body': 'SetMatrixProjection($1)' 'description': 'SetMatrixProjection(Matrix proj)' 'Set a custom modelview matrix (replaces internal modelview matrix)': 'prefix': 'SetMatrixModelview()' 'body': 'SetMatrixModelview($1)' 'description': 'SetMatrixModelview(Matrix view)' 'Get internal modelview matrix': 'prefix': 'GetMatrixModelview()' 'body': 'GetMatrixModelview($1)' 'description': 'GetMatrixModelview()' 'Get internal projection matrix': 'prefix': 'GetMatrixProjection()' 'body': 'GetMatrixProjection()' 'description': 'GetMatrixProjection(void)' 'Begin custom shader drawing': 'prefix': 'BeginShaderMode()' 'body': 'BeginShaderMode($1)' 'description': 'BeginShaderMode(Shader shader)' 'End custom shader drawing (use default shader)': 'prefix': 'EndShaderMode()' 'body': 'EndShaderMode()' 'description': 'EndShaderMode(void)' 'Begin blending mode (alpha, additive, multiplied)': 'prefix': 'BeginBlendMode()' 'body': 'BeginBlendMode($1)' 'description': 'BeginBlendMode(int mode)' 'End blending mode (reset to default: alpha blending)': 'prefix': 'EndBlendMode()' 'body': 'EndBlendMode()' 'description': 'EndBlendMode(void)' 'Init VR simulator for selected device parameters': 'prefix': 'InitVrSimulator()' 'body': 'InitVrSimulator()' 'description': 'InitVrSimulator(void)' 'Close VR simulator for current device': 'prefix': 'CloseVrSimulator()' 'body': 'CloseVrSimulator()' 'description': 'CloseVrSimulator(void)' 'Update VR tracking (position and orientation) and camera': 'prefix': 'UpdateVrTracking()' 'body': 'UpdateVrTracking($1)' 'description': 'UpdateVrTracking(Camera camera)' 'Set stereo rendering configuration parameters': 'prefix': 'SetVrConfiguration()' 'body': 'SetVrConfiguration($1)' 'description': 'SetVrConfiguration(VrDeviceInfo info, Shader distortion)' 'Detect if VR simulator is ready': 'prefix': 'IsVrSimulatorReady()' 'body': 'IsVrSimulatorReady()' 'description': 'IsVrSimulatorReady(void)' 'Enable/Disable VR experience': 'prefix': 'ToggleVrMode()' 'body': 'ToggleVrMode()' 'description': 'ToggleVrMode(void)' 'Begin VR simulator stereo rendering': 'prefix': 'BeginVrDrawing()' 'body': 'BeginVrDrawing()' 'description': 'BeginVrDrawing(void)' 'End VR simulator stereo rendering': 'prefix': 'EndVrDrawing()' 'body': 'EndVrDrawing()' 'description': 'EndVrDrawing(void)' 'Initialize audio device and context': 'prefix': 'InitAudioDevice()' 'body': 'InitAudioDevice()' 'description': 'InitAudioDevice(void)' 'Close the audio device and context (and music stream)': 'prefix': 'CloseAudioDevice()' 'body': 'CloseAudioDevice()' 'description': 'CloseAudioDevice(void)' 'Check if audio device is ready': 'prefix': 'IsAudioDeviceReady()' 'body': 'IsAudioDeviceReady()' 'description': 'IsAudioDeviceReady(void)' 'Set master volume (listener)': 'prefix': 'SetMasterVolume()' 'body': 'SetMasterVolume($1)' 'description': 'SetMasterVolume(float volume)' 'Load wave data from file': 'prefix': 'LoadWave()' 'body': 'LoadWave($1)' 'description': 'LoadWave(const char fileName)' 'Load wave data from raw array data': 'prefix': 'LoadWaveEx()' 'body': 'LoadWaveEx($1)' 'description': 'LoadWaveEx(void data, int sampleCount, int sampleRate, int sampleSize, int channels)' 'Load sound from file': 'prefix': 'LoadSound()' 'body': 'LoadSound($1)' 'description': 'LoadSound(const char fileName)' 'Load sound from wave data': 'prefix': 'LoadSoundFromWave()' 'body': 'LoadSoundFromWave($1)' 'description': 'LoadSoundFromWave(Wave wave)' 'Update sound buffer with new data': 'prefix': 'UpdateSound()' 'body': 'UpdateSound($1)' 'description': 'UpdateSound(Sound sound, const void data, int samplesCount)' 'Unload wave data': 'prefix': 'UnloadWave()' 'body': 'UnloadWave($1)' 'description': 'UnloadWave(Wave wave)' 'Unload sound': 'prefix': 'UnloadSound()' 'body': 'UnloadSound($1)' 'description': 'UnloadSound(Sound sound)' 'Export wave data to file': 'prefix': 'ExportWave()' 'body': 'ExportWave($1)' 'description': 'ExportWave(Wave wave, const char fileName)' 'Export wave sample data to code (.h)': 'prefix': 'ExportWaveAsCode()' 'body': 'ExportWaveAsCode($1)' 'description': 'ExportWaveAsCode(Wave wave, const char fileName)' 'Play a sound': 'prefix': 'PlaySound()' 'body': 'PlaySound($1)' 'description': 'PlaySound(Sound sound)' 'Stop playing a sound': 'prefix': 'StopSound()' 'body': 'StopSound($1)' 'description': 'StopSound(Sound sound)' 'Pause a sound': 'prefix': 'PauseSound()' 'body': 'PauseSound($1)' 'description': 'PauseSound(Sound sound)' 'Resume a paused sound': 'prefix': 'ResumeSound()' 'body': 'ResumeSound($1)' 'description': 'ResumeSound(Sound sound)' 'Play a sound (using multichannel buffer pool)': 'prefix': 'PlaySoundMulti()' 'body': 'PlaySoundMulti($1)' 'description': 'PlaySoundMulti(Sound sound)' 'Stop any sound playing (using multichannel buffer pool)': 'prefix': 'StopSoundMulti()' 'body': 'StopSoundMulti()' 'description': 'StopSoundMulti(void)' 'Get number of sounds playing in the multichannel': 'prefix': 'GetSoundsPlaying()' 'body': 'GetSoundsPlaying()' 'description': 'GetSoundsPlaying(void)' 'Check if a sound is currently playing': 'prefix': 'IsSoundPlaying()' 'body': 'IsSoundPlaying($1)' 'description': 'IsSoundPlaying(Sound sound)' 'Set volume for a sound (1.0 is max level)': 'prefix': 'SetSoundVolume()' 'body': 'SetSoundVolume($1)' 'description': 'SetSoundVolume(Sound sound, float volume)' 'Set pitch for a sound (1.0 is base level)': 'prefix': 'SetSoundPitch()' 'body': 'SetSoundPitch($1)' 'description': 'SetSoundPitch(Sound sound, float pitch)' 'Convert wave data to desired format': 'prefix': 'WaveFormat()' 'body': 'WaveFormat($1)' 'description': 'WaveFormat(Wave wave, int sampleRate, int sampleSize, int channels)' 'Copy a wave to a new wave': 'prefix': 'WaveCopy()' 'body': 'WaveCopy($1)' 'description': 'WaveCopy(Wave wave)' 'Crop a wave to defined samples range': 'prefix': 'WaveCrop()' 'body': 'WaveCrop($1)' 'description': 'WaveCrop(Wave wave, int initSample, int finalSample)' 'Get samples data from wave as a floats array': 'prefix': 'GetWaveData()' 'body': 'GetWaveData($1)' 'description': 'GetWaveData(Wave wave)' 'Load music stream from file': 'prefix': 'LoadMusicStream()' 'body': 'LoadMusicStream($1)' 'description': 'LoadMusicStream(const char fileName)' 'Unload music stream': 'prefix': 'UnloadMusicStream()' 'body': 'UnloadMusicStream($1)' 'description': 'UnloadMusicStream(Music music)' 'Start music playing': 'prefix': 'PlayMusicStream()' 'body': 'PlayMusicStream($1)' 'description': 'PlayMusicStream(Music music)' 'Updates buffers for music streaming': 'prefix': 'UpdateMusicStream()' 'body': 'UpdateMusicStream($1)' 'description': 'UpdateMusicStream(Music music)' 'Stop music playing': 'prefix': 'StopMusicStream()' 'body': 'StopMusicStream($1)' 'description': 'StopMusicStream(Music music)' 'Pause music playing': 'prefix': 'PauseMusicStream()' 'body': 'PauseMusicStream($1)' 'description': 'PauseMusicStream(Music music)' 'Resume playing paused music': 'prefix': 'ResumeMusicStream()' 'body': 'ResumeMusicStream($1)' 'description': 'ResumeMusicStream(Music music)' 'Check if music is playing': 'prefix': 'IsMusicPlaying()' 'body': 'IsMusicPlaying($1)' 'description': 'IsMusicPlaying(Music music)' 'Set volume for music (1.0 is max level)': 'prefix': 'SetMusicVolume()' 'body': 'SetMusicVolume($1)' 'description': 'SetMusicVolume(Music music, float volume)' 'Set pitch for a music (1.0 is base level)': 'prefix': 'SetMusicPitch()' 'body': 'SetMusicPitch($1)' 'description': 'SetMusicPitch(Music music, float pitch)' 'Set music loop count (loop repeats)': 'prefix': 'SetMusicLoopCount()' 'body': 'SetMusicLoopCount($1)' 'description': 'SetMusicLoopCount(Music music, int count)' 'Get music time length (in seconds)': 'prefix': 'GetMusicTimeLength()' 'body': 'GetMusicTimeLength($1)' 'description': 'GetMusicTimeLength(Music music)' 'Get current music time played (in seconds)': 'prefix': 'GetMusicTimePlayed()' 'body': 'GetMusicTimePlayed($1)' 'description': 'GetMusicTimePlayed(Music music)' 'Init audio stream (to stream raw audio pcm data)': 'prefix': 'InitAudioStream()' 'body': 'InitAudioStream($1)' 'description': 'InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels)' 'Update audio stream buffers with data': 'prefix': 'UpdateAudioStream()' 'body': 'UpdateAudioStream($1)' 'description': 'UpdateAudioStream(AudioStream stream, const void data, int samplesCount)' 'Close audio stream and free memory': 'prefix': 'CloseAudioStream()' 'body': 'CloseAudioStream($1)' 'description': 'CloseAudioStream(AudioStream stream)' 'Check if any audio stream buffers requires refill': 'prefix': 'IsAudioBufferProcessed()' 'body': 'IsAudioBufferProcessed($1)' 'description': 'IsAudioBufferProcessed(AudioStream stream)' 'Play audio stream': 'prefix': 'PlayAudioStream()' 'body': 'PlayAudioStream($1)' 'description': 'PlayAudioStream(AudioStream stream)' 'Pause audio stream': 'prefix': 'PauseAudioStream()' 'body': 'PauseAudioStream($1)' 'description': 'PauseAudioStream(AudioStream stream)' 'Resume audio stream': 'prefix': 'ResumeAudioStream()' 'body': 'ResumeAudioStream($1)' 'description': 'ResumeAudioStream(AudioStream stream)' 'Check if audio stream is playing': 'prefix': 'IsAudioStreamPlaying()' 'body': 'IsAudioStreamPlaying($1)' 'description': 'IsAudioStreamPlaying(AudioStream stream)' 'Stop audio stream': 'prefix': 'StopAudioStream()' 'body': 'StopAudioStream($1)' 'description': 'StopAudioStream(AudioStream stream)' 'Set volume for audio stream (1.0 is max level)': 'prefix': 'SetAudioStreamVolume()' 'body': 'SetAudioStreamVolume($1)' 'description': 'SetAudioStreamVolume(AudioStream stream, float volume)' 'Set pitch for audio stream (1.0 is base level)': 'prefix': 'SetAudioStreamPitch()' 'body': 'SetAudioStreamPitch($1)' 'description': 'SetAudioStreamPitch(AudioStream stream, float pitch)'
3359
'.source.python': 'Light Gray': 'prefix': 'LIGHTGRAY' 'body': 'LIGHTGRAY' 'Gray': 'prefix': 'GRAY' 'body': 'GRAY' 'Dark Gray': 'prefix': 'DARKGRAY' 'body': 'DARKGRAY' 'Yellow': 'prefix': 'YELLOW' 'body': 'YELLOW' 'Gold': 'prefix': 'GOLD' 'body': 'GOLD' 'Orange': 'prefix': 'ORANGE' 'body': 'ORANGE' 'Pink': 'prefix': 'PINK' 'body': 'PINK' 'Red': 'prefix': 'RED' 'body': 'RED' 'Maroon': 'prefix': 'MAROON' 'body': 'MAROON' 'Green': 'prefix': 'GREEN' 'body': 'GREEN' 'Lime': 'prefix': 'LIME' 'body': 'LIME' 'Dark Green': 'prefix': 'DARKGREEN' 'body': 'DARKGREEN' 'Sky Blue': 'prefix': 'SKYBLUE' 'body': 'SKYBLUE' 'Blue': 'prefix': 'BLUE' 'body': 'BLUE' 'Dark Blue': 'prefix': 'DARKBLUE' 'body': 'DARKBLUE' 'Purple': 'prefix': 'PURPLE' 'body': 'PURPLE' 'Violet': 'prefix': 'VIOLET' 'body': 'VIOLET' 'Dark Purple': 'prefix': 'DARKPURPLE' 'body': 'DARKPURPLE' 'Beige': 'prefix': 'BEIGE' 'body': 'BEIGE' 'Brown': 'prefix': 'BROWN' 'body': 'BROWN' 'Dark Brown': 'prefix': 'DARKBROWN' 'body': 'DARKBROWN' 'White': 'prefix': 'WHITE' 'body': 'WHITE' 'Black': 'prefix': 'BLACK' 'body': 'BLACK' 'Transparent': 'prefix': 'BLANK' 'body': 'BLANK' 'Magenta': 'prefix': 'MAGENTA' 'body': 'MAGENTA' '<NAME>': 'prefix': 'RAYWHITE' 'body': 'RAYWHITE' 'Initialize window and OpenGL context': 'prefix': 'InitWindow()' 'body': 'InitWindow($1)' 'description': 'InitWindow(int width, int height, const char title)' 'Check if KEY_ESCAPE pressed or Close icon pressed': 'prefix': 'WindowShouldClose()' 'body': 'WindowShouldClose()' 'description': 'WindowShouldClose(void)' 'Close window and unload OpenGL context': 'prefix': 'CloseWindow()' 'body': 'CloseWindow()' 'description': 'CloseWindow(void)' 'Check if window has been initialized successfully': 'prefix': 'IsWindowReady()' 'body': 'IsWindowReady()' 'description': 'IsWindowReady(void)' 'Check if window has been minimized (or lost focus)': 'prefix': 'IsWindowMinimized()' 'body': 'IsWindowMinimized()' 'description': 'IsWindowMinimized(void)' 'Check if window has been resized': 'prefix': 'IsWindowResized()' 'body': 'IsWindowResized()' 'description': 'IsWindowResized(void)' 'Check if window is currently hidden': 'prefix': 'IsWindowHidden()' 'body': 'IsWindowHidden()' 'description': 'IsWindowHidden(void)' 'Check if window is currently fullscreen': 'prefix': 'IsWindowFullscreen()' 'body': 'IsWindowFullscreen()' 'description': 'IsWindowFullscreen(void)' 'Toggle fullscreen mode (only PLATFORM_DESKTOP)': 'prefix': 'ToggleFullscreen()' 'body': 'ToggleFullscreen()' 'description': 'ToggleFullscreen(void)' 'Show the window': 'prefix': 'UnhideWindow()' 'body': 'UnhideWindow()' 'description': 'UnhideWindow(void)' 'Hide the window': 'prefix': 'HideWindow()' 'body': 'HideWindow()' 'description': 'HideWindow(void)' 'Set icon for window (only PLATFORM_DESKTOP)': 'prefix': 'SetWindowIcon()' 'body': 'SetWindowIcon($1)' 'description': 'SetWindowIcon(Image image)' 'Set title for window (only PLATFORM_DESKTOP)': 'prefix': 'SetWindowTitle()' 'body': 'SetWindowTitle($1)' 'description': 'SetWindowTitle(const char title)' 'Set window position on screen (only PLATFORM_DESKTOP)': 'prefix': 'SetWindowPosition()' 'body': 'SetWindowPosition($1)' 'description': 'SetWindowPosition(int x, int y)' 'Set monitor for the current window (fullscreen mode)': 'prefix': 'SetWindowMonitor()' 'body': 'SetWindowMonitor($1)' 'description': 'SetWindowMonitor(int monitor)' 'Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE)': 'prefix': 'SetWindowMinSize()' 'body': 'SetWindowMinSize($1)' 'description': 'SetWindowMinSize(int width, int height)' 'Set window dimensions': 'prefix': 'SetWindowSize()' 'body': 'SetWindowSize($1)' 'description': 'SetWindowSize(int width, int height)' 'Get native window handle': 'prefix': 'GetWindowHandle()' 'body': 'GetWindowHandle()' 'description': 'GetWindowHandle(void)' 'Get current screen width': 'prefix': 'GetScreenWidth()' 'body': 'GetScreenWidth()' 'description': 'GetScreenWidth(void)' 'Get current screen height': 'prefix': 'GetScreenHeight()' 'body': 'GetScreenHeight()' 'description': 'GetScreenHeight(void)' 'Get number of connected monitors': 'prefix': 'GetMonitorCount()' 'body': 'GetMonitorCount()' 'description': 'GetMonitorCount(void)' 'Get primary monitor width': 'prefix': 'GetMonitorWidth()' 'body': 'GetMonitorWidth($1)' 'description': 'GetMonitorWidth(int monitor)' 'Get primary monitor height': 'prefix': 'GetMonitorHeight()' 'body': 'GetMonitorHeight($1)' 'description': 'GetMonitorHeight(int monitor)' 'Get primary monitor physical width in millimetres': 'prefix': 'GetMonitorPhysicalWidth()' 'body': 'GetMonitorPhysicalWidth($1)' 'description': 'GetMonitorPhysicalWidth(int monitor)' 'Get primary monitor physical height in millimetres': 'prefix': 'GetMonitorPhysicalHeight()' 'body': 'GetMonitorPhysicalHeight($1)' 'description': 'GetMonitorPhysicalHeight(int monitor)' 'Get window position XY on monitor': 'prefix': 'GetWindowPosition()' 'body': 'GetWindowPosition()' 'description': 'GetWindowPosition(void)' 'Set clipboard text content': 'prefix': 'SetClipboardText()' 'body': 'SetClipboardText($1)' 'description': 'SetClipboardText(const char text)' 'Shows cursor': 'prefix': 'ShowCursor()' 'body': 'ShowCursor()' 'description': 'ShowCursor(void)' 'Hides cursor': 'prefix': 'HideCursor()' 'body': 'HideCursor()' 'description': 'HideCursor(void)' 'Check if cursor is not visible': 'prefix': 'IsCursorHidden()' 'body': 'IsCursorHidden()' 'description': 'IsCursorHidden(void)' 'Enables cursor (unlock cursor)': 'prefix': 'EnableCursor()' 'body': 'EnableCursor()' 'description': 'EnableCursor(void)' 'Disables cursor (lock cursor)': 'prefix': 'DisableCursor()' 'body': 'DisableCursor()' 'description': 'DisableCursor(void)' 'Set background color (framebuffer clear color)': 'prefix': 'ClearBackground()' 'body': 'ClearBackground($1)' 'description': 'ClearBackground(Color color)' 'Setup canvas (framebuffer) to start drawing': 'prefix': 'BeginDrawing()' 'body': 'BeginDrawing()' 'description': 'BeginDrawing(void)' 'End canvas drawing and swap buffers (double buffering)': 'prefix': 'EndDrawing()' 'body': 'EndDrawing()' 'description': 'EndDrawing(void)' 'Initialize 2D mode with custom camera (2D)': 'prefix': 'BeginMode2D()' 'body': 'BeginMode2D($1)' 'description': 'BeginMode2D(Camera2D camera)' 'Ends 2D mode with custom camera': 'prefix': 'EndMode2D()' 'body': 'EndMode2D()' 'description': 'EndMode2D(void)' 'Initializes 3D mode with custom camera (3D)': 'prefix': 'BeginMode3D()' 'body': 'BeginMode3D($1)' 'description': 'BeginMode3D(Camera3D camera)' 'Ends 3D mode and returns to default 2D orthographic mode': 'prefix': 'EndMode3D()' 'body': 'EndMode3D()' 'description': 'EndMode3D(void)' 'Initializes render texture for drawing': 'prefix': 'BeginTextureMode()' 'body': 'BeginTextureMode($1)' 'description': 'BeginTextureMode(RenderTexture2D target)' 'Ends drawing to render texture': 'prefix': 'EndTextureMode()' 'body': 'EndTextureMode()' 'description': 'EndTextureMode(void)' 'Begin scissor mode (define screen area for following drawing)': 'prefix': 'BeginScissorMode()' 'body': 'BeginScissorMode($1)' 'description': 'BeginScissorMode(int x, int y, int width, int height)' 'End scissor mode': 'prefix': 'EndScissorMode()' 'body': 'EndScissorMode()' 'description': 'EndScissorMode(void)' 'Returns a ray trace from mouse position': 'prefix': 'GetMouseRay()' 'body': 'GetMouseRay($1)' 'description': 'GetMouseRay(Vector2 mousePosition, Camera camera)' 'Returns camera transform matrix (view matrix)': 'prefix': 'GetCameraMatrix()' 'body': 'GetCameraMatrix($1)' 'description': 'GetCameraMatrix(Camera camera)' 'Returns camera 2d transform matrix': 'prefix': 'GetCameraMatrix2D()' 'body': 'GetCameraMatrix2D($1)' 'description': 'GetCameraMatrix2D(Camera2D camera)' 'Returns the screen space position for a 3d world space position': 'prefix': 'GetWorldToScreen()' 'body': 'GetWorldToScreen($1)' 'description': 'GetWorldToScreen(Vector3 position, Camera camera)' 'Returns size position for a 3d world space position': 'prefix': 'GetWorldToScreenEx()' 'body': 'GetWorldToScreenEx($1)' 'description': 'GetWorldToScreenEx(Vector3 position, Camera camera,int width, int height)' 'Returns the screen space position for a 2d camera world space position': 'prefix': 'GetWorldToScreen2D()' 'body': 'GetWorldToScreen2D($1)' 'description': 'GetWorldToScreen2D(Vector2 position, Camera2D camera)' 'Returns the world space position for a 2d camera screen space position': 'prefix': 'GetScreenToWorld2D()' 'body': 'GetScreenToWorld2D($1)' 'description': 'GetScreenToWorld2D(Vector2 position, Camera2D camera)' 'Set target FPS (maximum)': 'prefix': 'SetTargetFPS()' 'body': 'SetTargetFPS($1)' 'description': 'SetTargetFPS(int fps)' 'Returns current FPS': 'prefix': 'GetFPS()' 'body': 'GetFPS()' 'description': 'GetFPS(void)' 'Returns time in seconds for last frame drawn': 'prefix': 'GetFrameTime()' 'body': 'GetFrameTime()' 'description': 'GetFrameTime(void)' 'Returns elapsed time in seconds since InitWindow()': 'prefix': 'GetTime()' 'body': 'GetTime()' 'description': 'GetTime(void)' 'Returns hexadecimal value for a Color': 'prefix': 'ColorToInt()' 'body': 'ColorToInt($1)' 'description': 'ColorToInt(Color color)' 'Returns color normalized as float [0..1]': 'prefix': 'ColorNormalize()' 'body': 'ColorNormalize($1)' 'description': 'ColorNormalize(Color color)' 'Returns color from normalized values [0..1]': 'prefix': 'ColorFromNormalized()' 'body': 'ColorFromNormalized($1)' 'description': 'ColorFromNormalized(Vector4 normalized)' 'Returns HSV values for a Color': 'prefix': 'ColorToHSV()' 'body': 'ColorToHSV($1)' 'description': 'ColorToHSV(Color color)' 'Returns a Color from HSV values': 'prefix': 'ColorFromHSV()' 'body': 'ColorFromHSV($1)' 'description': 'ColorFromHSV(Vector3 hsv)' 'Returns a Color struct from hexadecimal value': 'prefix': 'GetColor()' 'body': 'GetColor($1)' 'description': 'GetColor(int hexValue)' 'Color fade-in or fade-out, alpha goes from 0.0f to 1.0f': 'prefix': 'Fade()' 'body': 'Fade($1)' 'description': 'Fade(Color color, float alpha)' 'Setup window configuration flags (view FLAGS)': 'prefix': 'SetConfigFlags()' 'body': 'SetConfigFlags($1)' 'description': 'SetConfigFlags(unsigned int flags)' 'Set the current threshold (minimum) log level': 'prefix': 'SetTraceLogLevel()' 'body': 'SetTraceLogLevel($1)' 'description': 'SetTraceLogLevel(int logType)' 'Set the exit threshold (minimum) log level': 'prefix': 'SetTraceLogExit()' 'body': 'SetTraceLogExit($1)' 'description': 'SetTraceLogExit(int logType)' 'Set a trace log callback to enable custom logging': 'prefix': 'SetTraceLogCallback()' 'body': 'SetTraceLogCallback($1)' 'description': 'SetTraceLogCallback(TraceLogCallback callback)' 'Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR)': 'prefix': 'TraceLog()' 'body': 'TraceLog($1)' 'description': 'TraceLog(int logType, const char text, ...)' 'Takes a screenshot of current screen (saved a .png)': 'prefix': 'TakeScreenshot()' 'body': 'TakeScreenshot($1)' 'description': 'TakeScreenshot(const char fileName)' 'Returns a random value between min and max (both included)': 'prefix': 'GetRandomValue()' 'body': 'GetRandomValue($1)' 'description': 'GetRandomValue(int min, int max)' 'Save data to file from byte array (write)': 'prefix': 'SaveFileData()' 'body': 'SaveFileData($1)' 'description': 'SaveFileData(const char fileName, void data, int bytesToWrite)' 'Save text data to file (write), string must be \' \' terminated': 'prefix': 'SaveFileText()' 'body': 'SaveFileText($1)' 'description': 'SaveFileText(const char fileName, char text)' 'Check if file exists': 'prefix': 'FileExists()' 'body': 'FileExists($1)' 'description': 'FileExists(const char fileName)' 'Check file extension': 'prefix': 'IsFileExtension()' 'body': 'IsFileExtension($1)' 'description': 'IsFileExtension(const char fileName, const char ext)' 'Check if a directory path exists': 'prefix': 'DirectoryExists()' 'body': 'DirectoryExists($1)' 'description': 'DirectoryExists(const char dirPath)' 'Clear directory files paths buffers (free memory)': 'prefix': 'ClearDirectoryFiles()' 'body': 'ClearDirectoryFiles()' 'description': 'ClearDirectoryFiles(void)' 'Change working directory, returns true if success': 'prefix': 'ChangeDirectory()' 'body': 'ChangeDirectory($1)' 'description': 'ChangeDirectory(const char dir)' 'Check if a file has been dropped into window': 'prefix': 'IsFileDropped()' 'body': 'IsFileDropped()' 'description': 'IsFileDropped(void)' 'Clear dropped files paths buffer (free memory)': 'prefix': 'ClearDroppedFiles()' 'body': 'ClearDroppedFiles()' 'description': 'ClearDroppedFiles(void)' 'Load integer value from storage file (from defined position)': 'prefix': 'LoadStorageValue()' 'body': 'LoadStorageValue($1)' 'description': 'LoadStorageValue(int position)' 'Save integer value to storage file (to defined position)': 'prefix': 'SaveStorageValue()' 'body': 'SaveStorageValue($1)' 'description': 'SaveStorageValue(int position, int value)' 'Open URL with default system browser (if available)': 'prefix': 'OpenURL()' 'body': 'OpenURL($1)' 'description': 'OpenURL(const char url)' 'Detect if a key has been pressed once': 'prefix': 'IsKeyPressed()' 'body': 'IsKeyPressed($1)' 'description': 'IsKeyPressed(int key)' 'Detect if a key is being pressed': 'prefix': 'IsKeyDown()' 'body': 'IsKeyDown($1)' 'description': 'IsKeyDown(int key)' 'Detect if a key has been released once': 'prefix': 'IsKeyReleased()' 'body': 'IsKeyReleased($1)' 'description': 'IsKeyReleased(int key)' 'Detect if a key is NOT being pressed': 'prefix': 'IsKeyUp()' 'body': 'IsKeyUp($1)' 'description': 'IsKeyUp(int key)' 'Get latest key pressed': 'prefix': 'GetKeyPressed()' 'body': 'GetKeyPressed()' 'description': 'GetKeyPressed(void)' 'Set a custom key to exit program (default is ESC)': 'prefix': 'SetExitKey()' 'body': 'SetExitKey($1)' 'description': 'SetExitKey(int key)' 'Detect if a gamepad is available': 'prefix': 'IsGamepadAvailable()' 'body': 'IsGamepadAvailable($1)' 'description': 'IsGamepadAvailable(int gamepad)' 'Check gamepad name (if available)': 'prefix': 'IsGamepadName()' 'body': 'IsGamepadName($1)' 'description': 'IsGamepadName(int gamepad, const char name)' 'Detect if a gamepad button has been pressed once': 'prefix': 'IsGamepadButtonPressed()' 'body': 'IsGamepadButtonPressed($1)' 'description': 'IsGamepadButtonPressed(int gamepad, int button)' 'Detect if a gamepad button is being pressed': 'prefix': 'IsGamepadButtonDown()' 'body': 'IsGamepadButtonDown($1)' 'description': 'IsGamepadButtonDown(int gamepad, int button)' 'Detect if a gamepad button has been released once': 'prefix': 'IsGamepadButtonReleased()' 'body': 'IsGamepadButtonReleased($1)' 'description': 'IsGamepadButtonReleased(int gamepad, int button)' 'Detect if a gamepad button is NOT being pressed': 'prefix': 'IsGamepadButtonUp()' 'body': 'IsGamepadButtonUp($1)' 'description': 'IsGamepadButtonUp(int gamepad, int button)' 'Get the last gamepad button pressed': 'prefix': 'GetGamepadButtonPressed()' 'body': 'GetGamepadButtonPressed()' 'description': 'GetGamepadButtonPressed(void)' 'Return gamepad axis count for a gamepad': 'prefix': 'GetGamepadAxisCount()' 'body': 'GetGamepadAxisCount($1)' 'description': 'GetGamepadAxisCount(int gamepad)' 'Return axis movement value for a gamepad axis': 'prefix': 'GetGamepadAxisMovement()' 'body': 'GetGamepadAxisMovement($1)' 'description': 'GetGamepadAxisMovement(int gamepad, int axis)' 'Detect if a mouse button has been pressed once': 'prefix': 'IsMouseButtonPressed()' 'body': 'IsMouseButtonPressed($1)' 'description': 'IsMouseButtonPressed(int button)' 'Detect if a mouse button is being pressed': 'prefix': 'IsMouseButtonDown()' 'body': 'IsMouseButtonDown($1)' 'description': 'IsMouseButtonDown(int button)' 'Detect if a mouse button has been released once': 'prefix': 'IsMouseButtonReleased()' 'body': 'IsMouseButtonReleased($1)' 'description': 'IsMouseButtonReleased(int button)' 'Detect if a mouse button is NOT being pressed': 'prefix': 'IsMouseButtonUp()' 'body': 'IsMouseButtonUp($1)' 'description': 'IsMouseButtonUp(int button)' 'Returns mouse position X': 'prefix': 'GetMouseX()' 'body': 'GetMouseX()' 'description': 'GetMouseX(void)' 'Returns mouse position Y': 'prefix': 'GetMouseY()' 'body': 'GetMouseY()' 'description': 'GetMouseY(void)' 'Returns mouse position XY': 'prefix': 'GetMousePosition()' 'body': 'GetMousePosition()' 'description': 'GetMousePosition(void)' 'Set mouse position XY': 'prefix': 'SetMousePosition()' 'body': 'SetMousePosition($1)' 'description': 'SetMousePosition(int x, int y)' 'Set mouse offset': 'prefix': 'SetMouseOffset()' 'body': 'SetMouseOffset($1)' 'description': 'SetMouseOffset(int offsetX, int offsetY)' 'Set mouse scaling': 'prefix': 'SetMouseScale()' 'body': 'SetMouseScale($1)' 'description': 'SetMouseScale(float scaleX, float scaleY)' 'Returns mouse wheel movement Y': 'prefix': 'GetMouseWheelMove()' 'body': 'GetMouseWheelMove()' 'description': 'GetMouseWheelMove(void)' 'Returns touch position X for touch point 0 (relative to screen size)': 'prefix': 'GetTouchX()' 'body': 'GetTouchX()' 'description': 'GetTouchX(void)' 'Returns touch position Y for touch point 0 (relative to screen size)': 'prefix': 'GetTouchY()' 'body': 'GetTouchY()' 'description': 'GetTouchY(void)' 'Returns touch position XY for a touch point index (relative to screen size)': 'prefix': 'GetTouchPosition()' 'body': 'GetTouchPosition($1)' 'description': 'GetTouchPosition(int index)' 'Enable a set of gestures using flags': 'prefix': 'SetGesturesEnabled()' 'body': 'SetGesturesEnabled($1)' 'description': 'SetGesturesEnabled(unsigned int gestureFlags)' 'Check if a gesture have been detected': 'prefix': 'IsGestureDetected()' 'body': 'IsGestureDetected($1)' 'description': 'IsGestureDetected(int gesture)' 'Get latest detected gesture': 'prefix': 'GetGestureDetected()' 'body': 'GetGestureDetected()' 'description': 'GetGestureDetected(void)' 'Get touch points count': 'prefix': 'GetTouchPointsCount()' 'body': 'GetTouchPointsCount()' 'description': 'GetTouchPointsCount(void)' 'Get gesture hold time in milliseconds': 'prefix': 'GetGestureHoldDuration()' 'body': 'GetGestureHoldDuration()' 'description': 'GetGestureHoldDuration(void)' 'Get gesture drag vector': 'prefix': 'GetGestureDragVector()' 'body': 'GetGestureDragVector()' 'description': 'GetGestureDragVector(void)' 'Get gesture drag angle': 'prefix': 'GetGestureDragAngle()' 'body': 'GetGestureDragAngle()' 'description': 'GetGestureDragAngle(void)' 'Get gesture pinch delta': 'prefix': 'GetGesturePinchVector()' 'body': 'GetGesturePinchVector()' 'description': 'GetGesturePinchVector(void)' 'Get gesture pinch angle': 'prefix': 'GetGesturePinchAngle()' 'body': 'GetGesturePinchAngle()' 'description': 'GetGesturePinchAngle(void)' 'Set camera mode (multiple camera modes available)': 'prefix': 'SetCameraMode()' 'body': 'SetCameraMode($1)' 'description': 'SetCameraMode(Camera camera, int mode)' 'Update camera position for selected mode': 'prefix': 'UpdateCamera()' 'body': 'UpdateCamera($1)' 'description': 'UpdateCamera(Camera camera)' 'Set camera pan key to combine with mouse movement (free camera)': 'prefix': 'SetCameraPanControl()' 'body': 'SetCameraPanControl($1)' 'description': 'SetCameraPanControl(int panKey)' 'Set camera alt key to combine with mouse movement (free camera)': 'prefix': 'SetCameraAltControl()' 'body': 'SetCameraAltControl($1)' 'description': 'SetCameraAltControl(int altKey)' 'Set camera smooth zoom key to combine with mouse (free camera)': 'prefix': 'SetCameraSmoothZoomControl()' 'body': 'SetCameraSmoothZoomControl($1)' 'description': 'SetCameraSmoothZoomControl(int szKey)' 'Set camera move controls (1st person and 3rd person cameras)': 'prefix': 'SetCameraMoveControls()' 'body': 'SetCameraMoveControls($1)' 'description': 'SetCameraMoveControls(int frontKey, int backKey, int rightKey, int leftKey, int upKey, int downKey)' 'Draw a pixel': 'prefix': 'DrawPixel()' 'body': 'DrawPixel($1)' 'description': 'DrawPixel(int posX, int posY, Color color)' 'Draw a pixel (Vector version)': 'prefix': 'DrawPixelV()' 'body': 'DrawPixelV($1)' 'description': 'DrawPixelV(Vector2 position, Color color)' 'Draw a line': 'prefix': 'DrawLine()' 'body': 'DrawLine($1)' 'description': 'DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color)' 'Draw a line (Vector version)': 'prefix': 'DrawLineV()' 'body': 'DrawLineV($1)' 'description': 'DrawLineV(Vector2 startPos, Vector2 endPos, Color color)' 'Draw a line defining thickness': 'prefix': 'DrawLineEx()' 'body': 'DrawLineEx($1)' 'description': 'DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color)' 'Draw a line using cubic-bezier curves in-out': 'prefix': 'DrawLineBezier()' 'body': 'DrawLineBezier($1)' 'description': 'DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color)' 'Draw lines sequence': 'prefix': 'DrawLineStrip()' 'body': 'DrawLineStrip($1)' 'description': 'DrawLineStrip(Vector2 points, int numPoints, Color color)' 'Draw a color-filled circle': 'prefix': 'DrawCircle()' 'body': 'DrawCircle($1)' 'description': 'DrawCircle(int centerX, int centerY, float radius, Color color)' 'Draw a piece of a circle': 'prefix': 'DrawCircleSector()' 'body': 'DrawCircleSector($1)' 'description': 'DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color)' 'Draw circle sector outline': 'prefix': 'DrawCircleSectorLines()' 'body': 'DrawCircleSectorLines($1)' 'description': 'DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color)' 'Draw a gradient-filled circle': 'prefix': 'DrawCircleGradient()' 'body': 'DrawCircleGradient($1)' 'description': 'DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2)' 'Draw a color-filled circle (Vector version)': 'prefix': 'DrawCircleV()' 'body': 'DrawCircleV($1)' 'description': 'DrawCircleV(Vector2 center, float radius, Color color)' 'Draw circle outline': 'prefix': 'DrawCircleLines()' 'body': 'DrawCircleLines($1)' 'description': 'DrawCircleLines(int centerX, int centerY, float radius, Color color)' 'Draw ellipse': 'prefix': 'DrawEllipse()' 'body': 'DrawEllipse($1)' 'description': 'DrawEllipse(int centerX, int centerY, float radiusH, float radiusV, Color color)' 'Draw ellipse outline': 'prefix': 'DrawEllipseLines()' 'body': 'DrawEllipseLines($1)' 'description': 'DrawEllipseLines(int centerX, int centerY, float radiusH, float radiusV, Color color)' 'Draw ring': 'prefix': 'DrawRing()' 'body': 'DrawRing($1)' 'description': 'DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color)' 'Draw ring outline': 'prefix': 'DrawRingLines()' 'body': 'DrawRingLines($1)' 'description': 'DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color)' 'Draw a color-filled rectangle': 'prefix': 'DrawRectangle()' 'body': 'DrawRectangle($1)' 'description': 'DrawRectangle(int posX, int posY, int width, int height, Color color)' 'Draw a color-filled rectangle (Vector version)': 'prefix': 'DrawRectangleV()' 'body': 'DrawRectangleV($1)' 'description': 'DrawRectangleV(Vector2 position, Vector2 size, Color color)' 'Draw a defined color-filled rectangle': 'prefix': 'DrawRectangleRec()' 'body': 'DrawRectangleRec($1)' 'description': 'DrawRectangleRec(Rectangle rec, Color color)' 'Draw a color-filled rectangle with pro parameters': 'prefix': 'DrawRectanglePro()' 'body': 'DrawRectanglePro($1)' 'description': 'DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color)' 'Draw a vertical-gradient-filled rectangle': 'prefix': 'DrawRectangleGradientV()' 'body': 'DrawRectangleGradientV($1)' 'description': 'DrawRectangleGradientV(int posX, int posY, int width, int height, Color color1, Color color2)' 'Draw a horizontal-gradient-filled rectangle': 'prefix': 'DrawRectangleGradientH()' 'body': 'DrawRectangleGradientH($1)' 'description': 'DrawRectangleGradientH(int posX, int posY, int width, int height, Color color1, Color color2)' 'Draw a gradient-filled rectangle with custom vertex colors': 'prefix': 'DrawRectangleGradientEx()' 'body': 'DrawRectangleGradientEx($1)' 'description': 'DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4)' 'Draw rectangle outline': 'prefix': 'DrawRectangleLines()' 'body': 'DrawRectangleLines($1)' 'description': 'DrawRectangleLines(int posX, int posY, int width, int height, Color color)' 'Draw rectangle outline with extended parameters': 'prefix': 'DrawRectangleLinesEx()' 'body': 'DrawRectangleLinesEx($1)' 'description': 'DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color)' 'Draw rectangle with rounded edges': 'prefix': 'DrawRectangleRounded()' 'body': 'DrawRectangleRounded($1)' 'description': 'DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color)' 'Draw rectangle with rounded edges outline': 'prefix': 'DrawRectangleRoundedLines()' 'body': 'DrawRectangleRoundedLines($1)' 'description': 'DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int lineThick, Color color)' 'Draw a color-filled triangle (vertex in counter-clockwise order!)': 'prefix': 'DrawTriangle()' 'body': 'DrawTriangle($1)' 'description': 'DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color)' 'Draw triangle outline (vertex in counter-clockwise order!)': 'prefix': 'DrawTriangleLines()' 'body': 'DrawTriangleLines($1)' 'description': 'DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color)' 'Draw a triangle fan defined by points (first vertex is the center)': 'prefix': 'DrawTriangleFan()' 'body': 'DrawTriangleFan($1)' 'description': 'DrawTriangleFan(Vector2 points, int numPoints, Color color)' 'Draw a triangle strip defined by points': 'prefix': 'DrawTriangleStrip()' 'body': 'DrawTriangleStrip($1)' 'description': 'DrawTriangleStrip(Vector2 points, int pointsCount, Color color)' 'Draw a regular polygon (Vector version)': 'prefix': 'DrawPoly()' 'body': 'DrawPoly($1)' 'description': 'DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color)' 'Draw a polygon outline of n sides': 'prefix': 'DrawPolyLines()' 'body': 'DrawPolyLines($1)' 'description': 'DrawPolyLines(Vector2 center, int sides, float radius, float rotation, Color color)' 'Check collision between two rectangles': 'prefix': 'CheckCollisionRecs()' 'body': 'CheckCollisionRecs($1)' 'description': 'CheckCollisionRecs(Rectangle rec1, Rectangle rec2)' 'Check collision between two circles': 'prefix': 'CheckCollisionCircles()' 'body': 'CheckCollisionCircles($1)' 'description': 'CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2)' 'Check collision between circle and rectangle': 'prefix': 'CheckCollisionCircleRec()' 'body': 'CheckCollisionCircleRec($1)' 'description': 'CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec)' 'Get collision rectangle for two rectangles collision': 'prefix': 'GetCollisionRec()' 'body': 'GetCollisionRec($1)' 'description': 'GetCollisionRec(Rectangle rec1, Rectangle rec2)' 'Check if point is inside rectangle': 'prefix': 'CheckCollisionPointRec()' 'body': 'CheckCollisionPointRec($1)' 'description': 'CheckCollisionPointRec(Vector2 point, Rectangle rec)' 'Check if point is inside circle': 'prefix': 'CheckCollisionPointCircle()' 'body': 'CheckCollisionPointCircle($1)' 'description': 'CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius)' 'Check if point is inside a triangle': 'prefix': 'CheckCollisionPointTriangle()' 'body': 'CheckCollisionPointTriangle($1)' 'description': 'CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3)' 'Load image from file into CPU memory (RAM)': 'prefix': 'LoadImage()' 'body': 'LoadImage($1)' 'description': 'LoadImage(const char fileName)' 'Load image from Color array data (RGBA - 32bit)': 'prefix': 'LoadImageEx()' 'body': 'LoadImageEx($1)' 'description': 'LoadImageEx(Color pixels, int width, int height)' 'Load image from raw data with parameters': 'prefix': 'LoadImagePro()' 'body': 'LoadImagePro($1)' 'description': 'LoadImagePro(void data, int width, int height, int format)' 'Load image from RAW file data': 'prefix': 'LoadImageRaw()' 'body': 'LoadImageRaw($1)' 'description': 'LoadImageRaw(const char fileName, int width, int height, int format, int headerSize)' 'Unload image from CPU memory (RAM)': 'prefix': 'UnloadImage()' 'body': 'UnloadImage($1)' 'description': 'UnloadImage(Image image)' 'Export image data to file': 'prefix': 'ExportImage()' 'body': 'ExportImage($1)' 'description': 'ExportImage(Image image, const char fileName)' 'Export image as code file defining an array of bytes': 'prefix': 'ExportImageAsCode()' 'body': 'ExportImageAsCode($1)' 'description': 'ExportImageAsCode(Image image, const char fileName)' 'Get pixel data from image as a Color struct array': 'prefix': 'GetImageData()' 'body': 'GetImageData($1)' 'description': 'GetImageData(Image image)' 'Get pixel data from image as Vector4 array (float normalized)': 'prefix': 'GetImageDataNormalized()' 'body': 'GetImageDataNormalized($1)' 'description': 'GetImageDataNormalized(Image image)' 'Generate image: plain color': 'prefix': 'GenImageColor()' 'body': 'GenImageColor($1)' 'description': 'GenImageColor(int width, int height, Color color)' 'Generate image: vertical gradient': 'prefix': 'GenImageGradientV()' 'body': 'GenImageGradientV($1)' 'description': 'GenImageGradientV(int width, int height, Color top, Color bottom)' 'Generate image: horizontal gradient': 'prefix': 'GenImageGradientH()' 'body': 'GenImageGradientH($1)' 'description': 'GenImageGradientH(int width, int height, Color left, Color right)' 'Generate image: radial gradient': 'prefix': 'GenImageGradientRadial()' 'body': 'GenImageGradientRadial($1)' 'description': 'GenImageGradientRadial(int width, int height, float density, Color inner, Color outer)' 'Generate image: checked': 'prefix': 'GenImageChecked()' 'body': 'GenImageChecked($1)' 'description': 'GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2)' 'Generate image: white noise': 'prefix': 'GenImageWhiteNoise()' 'body': 'GenImageWhiteNoise($1)' 'description': 'GenImageWhiteNoise(int width, int height, float factor)' 'Generate image: perlin noise': 'prefix': 'GenImagePerlinNoise()' 'body': 'GenImagePerlinNoise($1)' 'description': 'GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale)' 'Generate image: cellular algorithm. Bigger tileSize means bigger cells': 'prefix': 'GenImageCellular()' 'body': 'GenImageCellular($1)' 'description': 'GenImageCellular(int width, int height, int tileSize)' 'Create an image duplicate (useful for transformations)': 'prefix': 'ImageCopy()' 'body': 'ImageCopy($1)' 'description': 'ImageCopy(Image image)' 'Create an image from another image piece': 'prefix': 'ImageFromImage()' 'body': 'ImageFromImage($1)' 'description': 'ImageFromImage(Image image, Rectangle rec)' 'Create an image from text (default font)': 'prefix': 'ImageText()' 'body': 'ImageText($1)' 'description': 'ImageText(const char text, int fontSize, Color color)' 'Create an image from text (custom sprite font)': 'prefix': 'ImageTextEx()' 'body': 'ImageTextEx($1)' 'description': 'ImageTextEx(Font font, const char text, float fontSize, float spacing, Color tint)' 'Convert image to POT (power-of-two)': 'prefix': 'ImageToPOT()' 'body': 'ImageToPOT($1)' 'description': 'ImageToPOT(Image image, Color fillColor)' 'Convert image data to desired format': 'prefix': 'ImageFormat()' 'body': 'ImageFormat($1)' 'description': 'ImageFormat(Image image, int newFormat)' 'Apply alpha mask to image': 'prefix': 'ImageAlphaMask()' 'body': 'ImageAlphaMask($1)' 'description': 'ImageAlphaMask(Image image, Image alphaMask)' 'Clear alpha channel to desired color': 'prefix': 'ImageAlphaClear()' 'body': 'ImageAlphaClear($1)' 'description': 'ImageAlphaClear(Image image, Color color, float threshold)' 'Crop image depending on alpha value': 'prefix': 'ImageAlphaCrop()' 'body': 'ImageAlphaCrop($1)' 'description': 'ImageAlphaCrop(Image image, float threshold)' 'Premultiply alpha channel': 'prefix': 'ImageAlphaPremultiply()' 'body': 'ImageAlphaPremultiply($1)' 'description': 'ImageAlphaPremultiply(Image image)' 'Crop an image to a defined rectangle': 'prefix': 'ImageCrop()' 'body': 'ImageCrop($1)' 'description': 'ImageCrop(Image image, Rectangle crop)' 'Resize image (Bicubic scaling algorithm)': 'prefix': 'ImageResize()' 'body': 'ImageResize($1)' 'description': 'ImageResize(Image image, int newWidth, int newHeight)' 'Resize image (Nearest-Neighbor scaling algorithm)': 'prefix': 'ImageResizeNN()' 'body': 'ImageResizeNN($1)' 'description': 'ImageResizeNN(Image image, int newWidth,int newHeight)' 'Resize canvas and fill with color': 'prefix': 'ImageResizeCanvas()' 'body': 'ImageResizeCanvas($1)' 'description': 'ImageResizeCanvas(Image image, int newWidth, int newHeight, int offsetX, int offsetY, Color color)' 'Generate all mipmap levels for a provided image': 'prefix': 'ImageMipmaps()' 'body': 'ImageMipmaps($1)' 'description': 'ImageMipmaps(Image image)' 'Dither image data to 16bpp or lower (Floyd-Steinberg dithering)': 'prefix': 'ImageDither()' 'body': 'ImageDither($1)' 'description': 'ImageDither(Image image, int rBpp, int gBpp, int bBpp, int aBpp)' 'Flip image vertically': 'prefix': 'ImageFlipVertical()' 'body': 'ImageFlipVertical($1)' 'description': 'ImageFlipVertical(Image image)' 'Flip image horizontally': 'prefix': 'ImageFlipHorizontal()' 'body': 'ImageFlipHorizontal($1)' 'description': 'ImageFlipHorizontal(Image image)' 'Rotate image clockwise 90deg': 'prefix': 'ImageRotateCW()' 'body': 'ImageRotateCW($1)' 'description': 'ImageRotateCW(Image image)' 'Rotate image counter-clockwise 90deg': 'prefix': 'ImageRotateCCW()' 'body': 'ImageRotateCCW($1)' 'description': 'ImageRotateCCW(Image image)' 'Modify image color: tint': 'prefix': 'ImageColorTint()' 'body': 'ImageColorTint($1)' 'description': 'ImageColorTint(Image image, Color color)' 'Modify image color: invert': 'prefix': 'ImageColorInvert()' 'body': 'ImageColorInvert($1)' 'description': 'ImageColorInvert(Image image)' 'Modify image color: grayscale': 'prefix': 'ImageColorGrayscale()' 'body': 'ImageColorGrayscale($1)' 'description': 'ImageColorGrayscale(Image image)' 'Modify image color: contrast (-100 to 100)': 'prefix': 'ImageColorContrast()' 'body': 'ImageColorContrast($1)' 'description': 'ImageColorContrast(Image image, float contrast)' 'Modify image color: brightness (-255 to 255)': 'prefix': 'ImageColorBrightness()' 'body': 'ImageColorBrightness($1)' 'description': 'ImageColorBrightness(Image image, int brightness)' 'Modify image color: replace color': 'prefix': 'ImageColorReplace()' 'body': 'ImageColorReplace($1)' 'description': 'ImageColorReplace(Image image, Color color, Color replace)' 'Extract color palette from image to maximum size (memory should be freed)': 'prefix': 'ImageExtractPalette()' 'body': 'ImageExtractPalette($1)' 'description': 'ImageExtractPalette(Image image, int maxPaletteSize, int extractCount)' 'Get image alpha border rectangle': 'prefix': 'GetImageAlphaBorder()' 'body': 'GetImageAlphaBorder($1)' 'description': 'GetImageAlphaBorder(Image image, float threshold)' 'Clear image background with given color': 'prefix': 'ImageClearBackground()' 'body': 'ImageClearBackground($1)' 'description': 'ImageClearBackground(Image dst, Color color)' 'Draw pixel within an image': 'prefix': 'ImageDrawPixel()' 'body': 'ImageDrawPixel($1)' 'description': 'ImageDrawPixel(Image dst, int posX, int posY, Color color)' 'Draw pixel within an image (Vector version)': 'prefix': 'ImageDrawPixelV()' 'body': 'ImageDrawPixelV($1)' 'description': 'ImageDrawPixelV(Image dst, Vector2 position, Color color)' 'Draw line within an image': 'prefix': 'ImageDrawLine()' 'body': 'ImageDrawLine($1)' 'description': 'ImageDrawLine(Image dst, int startPosX, int startPosY, int endPosX, int endPosY, Color color)' 'Draw line within an image (Vector version)': 'prefix': 'ImageDrawLineV()' 'body': 'ImageDrawLineV($1)' 'description': 'ImageDrawLineV(Image dst, Vector2 start, Vector2 end, Color color)' 'Draw circle within an image': 'prefix': 'ImageDrawCircle()' 'body': 'ImageDrawCircle($1)' 'description': 'ImageDrawCircle(Image dst, int centerX, int centerY, int radius, Color color)' 'Draw circle within an image (Vector version)': 'prefix': 'ImageDrawCircleV()' 'body': 'ImageDrawCircleV($1)' 'description': 'ImageDrawCircleV(Image dst, Vector2 center, int radius, Color color)' 'Draw rectangle within an image': 'prefix': 'ImageDrawRectangle()' 'body': 'ImageDrawRectangle($1)' 'description': 'ImageDrawRectangle(Image dst, int posX, int posY, int width, int height, Color color)' 'Draw rectangle within an image (Vector version)': 'prefix': 'ImageDrawRectangleV()' 'body': 'ImageDrawRectangleV($1)' 'description': 'ImageDrawRectangleV(Image dst, Vector2 position, Vector2 size, Color color)' 'Draw defined rectangle within an image': 'prefix': 'ImageDrawRectangleRec()' 'body': 'ImageDrawRectangleRec($1)' 'description': 'ImageDrawRectangleRec(Image dst, Rectangle rec, Color color)' 'Draw rectangle lines within an image': 'prefix': 'ImageDrawRectangleLines()' 'body': 'ImageDrawRectangleLines($1)' 'description': 'ImageDrawRectangleLines(Image dst, Rectangle rec, int thick, Color color)' 'Draw a source image within a destination image (tint applied to source)': 'prefix': 'ImageDraw()' 'body': 'ImageDraw($1)' 'description': 'ImageDraw(Image dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint)' 'Draw text (default font) within an image (destination)': 'prefix': 'ImageDrawText()' 'body': 'ImageDrawText($1)' 'description': 'ImageDrawText(Image dst, Vector2 position, const char text, int fontSize, Color color)' 'Draw text (custom sprite font) within an image (destination)': 'prefix': 'ImageDrawTextEx()' 'body': 'ImageDrawTextEx($1)' 'description': 'ImageDrawTextEx(Image dst, Vector2 position, Font font, const char text, float fontSize, float spacing, Color color)' 'Unload texture from GPU memory (VRAM)': 'prefix': 'UnloadTexture()' 'body': 'UnloadTexture($1)' 'description': 'UnloadTexture(Texture2D texture)' 'Unload render texture from GPU memory (VRAM)': 'prefix': 'UnloadRenderTexture()' 'body': 'UnloadRenderTexture($1)' 'description': 'UnloadRenderTexture(RenderTexture2D target)' 'Update GPU texture with new data': 'prefix': 'UpdateTexture()' 'body': 'UpdateTexture($1)' 'description': 'UpdateTexture(Texture2D texture, const void pixels)' 'Get pixel data from GPU texture and return an Image': 'prefix': 'GetTextureData()' 'body': 'GetTextureData($1)' 'description': 'GetTextureData(Texture2D texture)' 'Get pixel data from screen buffer and return an Image (screenshot)': 'prefix': 'GetScreenData()' 'body': 'GetScreenData()' 'description': 'GetScreenData(void)' 'Generate GPU mipmaps for a texture': 'prefix': 'GenTextureMipmaps()' 'body': 'GenTextureMipmaps($1)' 'description': 'GenTextureMipmaps(Texture2D texture)' 'Set texture scaling filter mode': 'prefix': 'SetTextureFilter()' 'body': 'SetTextureFilter($1)' 'description': 'SetTextureFilter(Texture2D texture, int filterMode)' 'Set texture wrapping mode': 'prefix': 'SetTextureWrap()' 'body': 'SetTextureWrap($1)' 'description': 'SetTextureWrap(Texture2D texture, int wrapMode)' 'Draw a Texture2D': 'prefix': 'DrawTexture()' 'body': 'DrawTexture($1)' 'description': 'DrawTexture(Texture2D texture, int posX, int posY, Color tint)' 'Draw a Texture2D with position defined as Vector2': 'prefix': 'DrawTextureV()' 'body': 'DrawTextureV($1)' 'description': 'DrawTextureV(Texture2D texture, Vector2 position, Color tint)' 'Draw a Texture2D with extended parameters': 'prefix': 'DrawTextureEx()' 'body': 'DrawTextureEx($1)' 'description': 'DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint)' 'Draw a part of a texture defined by a rectangle': 'prefix': 'DrawTextureRec()' 'body': 'DrawTextureRec($1)' 'description': 'DrawTextureRec(Texture2D texture, Rectangle sourceRec, Vector2 position, Color tint)' 'Draw texture quad with tiling and offset parameters': 'prefix': 'DrawTextureQuad()' 'body': 'DrawTextureQuad($1)' 'description': 'DrawTextureQuad(Texture2D texture, Vector2 tiling, Vector2 offset, Rectangle quad, Color tint)' 'Draw a part of a texture defined by a rectangle with \'pro\' parameters': 'prefix': 'DrawTexturePro()' 'body': 'DrawTexturePro($1)' 'description': 'DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, Vector2 origin, float rotation, Color tint)' 'Draws a texture (or part of it) that stretches or shrinks nicely': 'prefix': 'DrawTextureNPatch()' 'body': 'DrawTextureNPatch($1)' 'description': 'DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle destRec, Vector2 origin, float rotation, Color tint)' 'Get pixel data size in bytes (image or texture)': 'prefix': 'GetPixelDataSize()' 'body': 'GetPixelDataSize($1)' 'description': 'GetPixelDataSize(int width, int height, int format)' 'Get the default Font': 'prefix': 'GetFontDefault()' 'body': 'GetFontDefault()' 'description': 'GetFontDefault(void)' 'Load font from file into GPU memory (VRAM)': 'prefix': 'LoadFont()' 'body': 'LoadFont($1)' 'description': 'LoadFont(const char fileName)' 'Load font from file with extended parameters': 'prefix': 'LoadFontEx()' 'body': 'LoadFontEx($1)' 'description': 'LoadFontEx(const char fileName, int fontSize, int fontChars, int charsCount)' 'Load font from Image (XNA style)': 'prefix': 'LoadFontFromImage()' 'body': 'LoadFontFromImage($1)' 'description': 'LoadFontFromImage(Image image, Color key, int firstChar)' 'Load font data for further use': 'prefix': 'LoadFontData()' 'body': 'LoadFontData($1)' 'description': 'LoadFontData(const char fileName, int fontSize, int fontChars, int charsCount, int type)' 'Generate image font atlas using chars info': 'prefix': 'GenImageFontAtlas()' 'body': 'GenImageFontAtlas($1)' 'description': 'GenImageFontAtlas(const CharInfo chars, Rectangle recs, int charsCount, int fontSize, int padding, int packMethod)' 'Unload Font from GPU memory (VRAM)': 'prefix': 'UnloadFont()' 'body': 'UnloadFont($1)' 'description': 'UnloadFont(Font font)' 'Shows current FPS': 'prefix': 'DrawFPS()' 'body': 'DrawFPS($1)' 'description': 'DrawFPS(int posX, int posY)' 'Draw text (using default font)': 'prefix': 'DrawText()' 'body': 'DrawText($1)' 'description': 'DrawText(const char text, int posX, int posY, int fontSize, Color color)' 'Draw text using font and additional parameters': 'prefix': 'DrawTextEx()' 'body': 'DrawTextEx($1)' 'description': 'DrawTextEx(Font font, const char text, Vector2 position, float fontSize, float spacing, Color tint)' 'Draw text using font inside rectangle limits': 'prefix': 'DrawTextRec()' 'body': 'DrawTextRec($1)' 'description': 'DrawTextRec(Font font, const char text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint)' 'Draw text using font inside rectangle limits with support for text selection': 'prefix': 'DrawTextRecEx()' 'body': 'DrawTextRecEx($1)' 'description': 'DrawTextRecEx(Font font, const char text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, int selectStart, int selectLength, Color selectTint, Color selectBackTint)' 'Draw one character (codepoint)': 'prefix': 'DrawTextCodepoint()' 'body': 'DrawTextCodepoint($1)' 'description': 'DrawTextCodepoint(Font font, int codepoint, Vector2 position, float scale, Color tint)' 'Measure string width for default font': 'prefix': 'MeasureText()' 'body': 'MeasureText($1)' 'description': 'MeasureText(const char text, int fontSize)' 'Measure string size for Font': 'prefix': 'MeasureTextEx()' 'body': 'MeasureTextEx($1)' 'description': 'MeasureTextEx(Font font, const char text, float fontSize, float spacing)' 'Get index position for a unicode character on font': 'prefix': 'GetGlyphIndex()' 'body': 'GetGlyphIndex($1)' 'description': 'GetGlyphIndex(Font font, int codepoint)' 'Copy one string to another, returns bytes copied': 'prefix': 'TextCopy()' 'body': 'TextCopy($1)' 'description': 'TextCopy(char dst, const char src)' 'Check if two text string are equal': 'prefix': 'TextIsEqual()' 'body': 'TextIsEqual($1)' 'description': 'TextIsEqual(const char text1, const char text2)' 'Append text at specific position and move cursor!': 'prefix': 'TextAppend()' 'body': 'TextAppend($1)' 'description': 'TextAppend(char text, const char append, int position)' 'Find first text occurrence within a string': 'prefix': 'TextFindIndex()' 'body': 'TextFindIndex($1)' 'description': 'TextFindIndex(const char text, const char find)' 'Get integer value from text (negative values not supported)': 'prefix': 'TextToInteger()' 'body': 'TextToInteger($1)' 'description': 'TextToInteger(const char text)' 'Get all codepoints in a string, codepoints count returned by parameters': 'prefix': 'GetCodepoints()' 'body': 'GetCodepoints($1)' 'description': 'GetCodepoints(const char text, int count)' 'Get total number of characters (codepoints) in a UTF8 encoded string': 'prefix': 'GetCodepointsCount()' 'body': 'GetCodepointsCount($1)' 'description': 'GetCodepointsCount(const char text)' 'Returns next codepoint in a UTF8 encoded string; 0x3f(\'?\') is returned on failure': 'prefix': 'GetNextCodepoint()' 'body': 'GetNextCodepoint($1)' 'description': 'GetNextCodepoint(const char text, int bytesProcessed)' 'Draw a line in 3D world space': 'prefix': 'DrawLine3D()' 'body': 'DrawLine3D($1)' 'description': 'DrawLine3D(Vector3 startPos, Vector3 endPos, Color color)' 'Draw a point in 3D space, actually a small line': 'prefix': 'DrawPoint3D()' 'body': 'DrawPoint3D($1)' 'description': 'DrawPoint3D(Vector3 position, Color color)' 'Draw a circle in 3D world space': 'prefix': 'DrawCircle3D()' 'body': 'DrawCircle3D($1)' 'description': 'DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color)' 'Draw cube': 'prefix': 'DrawCube()' 'body': 'DrawCube($1)' 'description': 'DrawCube(Vector3 position, float width, float height, float length, Color color)' 'Draw cube (Vector version)': 'prefix': 'DrawCubeV()' 'body': 'DrawCubeV($1)' 'description': 'DrawCubeV(Vector3 position, Vector3 size, Color color)' 'Draw cube wires': 'prefix': 'DrawCubeWires()' 'body': 'DrawCubeWires($1)' 'description': 'DrawCubeWires(Vector3 position, float width, float height, float length, Color color)' 'Draw cube wires (Vector version)': 'prefix': 'DrawCubeWiresV()' 'body': 'DrawCubeWiresV($1)' 'description': 'DrawCubeWiresV(Vector3 position, Vector3 size, Color color)' 'Draw cube textured': 'prefix': 'DrawCubeTexture()' 'body': 'DrawCubeTexture($1)' 'description': 'DrawCubeTexture(Texture2D texture, Vector3 position, float width, float height, float length, Color color)' 'Draw sphere': 'prefix': 'DrawSphere()' 'body': 'DrawSphere($1)' 'description': 'DrawSphere(Vector3 centerPos, float radius, Color color)' 'Draw sphere with extended parameters': 'prefix': 'DrawSphereEx()' 'body': 'DrawSphereEx($1)' 'description': 'DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color)' 'Draw sphere wires': 'prefix': 'DrawSphereWires()' 'body': 'DrawSphereWires($1)' 'description': 'DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color)' 'Draw a cylinder/cone': 'prefix': 'DrawCylinder()' 'body': 'DrawCylinder($1)' 'description': 'DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color)' 'Draw a cylinder/cone wires': 'prefix': 'DrawCylinderWires()' 'body': 'DrawCylinderWires($1)' 'description': 'DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color)' 'Draw a plane XZ': 'prefix': 'DrawPlane()' 'body': 'DrawPlane($1)' 'description': 'DrawPlane(Vector3 centerPos, Vector2 size, Color color)' 'Draw a ray line': 'prefix': 'DrawRay()' 'body': 'DrawRay($1)' 'description': 'DrawRay(Ray ray, Color color)' 'Draw a grid (centered at (0, 0, 0))': 'prefix': 'DrawGrid()' 'body': 'DrawGrid($1)' 'description': 'DrawGrid(int slices, float spacing)' 'Draw simple gizmo': 'prefix': 'DrawGizmo()' 'body': 'DrawGizmo($1)' 'description': 'DrawGizmo(Vector3 position)' 'Load model from files (meshes and materials)': 'prefix': 'LoadModel()' 'body': 'LoadModel($1)' 'description': 'LoadModel(const char fileName)' 'Load model from generated mesh (default material)': 'prefix': 'LoadModelFromMesh()' 'body': 'LoadModelFromMesh($1)' 'description': 'LoadModelFromMesh(Mesh mesh)' 'Unload model from memory (RAM and/or VRAM)': 'prefix': 'UnloadModel()' 'body': 'UnloadModel($1)' 'description': 'UnloadModel(Model model)' 'Load meshes from model file': 'prefix': 'LoadMeshes()' 'body': 'LoadMeshes($1)' 'description': 'LoadMeshes(const char fileName, int meshCount)' 'Export mesh data to file': 'prefix': 'ExportMesh()' 'body': 'ExportMesh($1)' 'description': 'ExportMesh(Mesh mesh, const char fileName)' 'Unload mesh from memory (RAM and/or VRAM)': 'prefix': 'UnloadMesh()' 'body': 'UnloadMesh($1)' 'description': 'UnloadMesh(Mesh mesh)' 'Load materials from model file': 'prefix': 'LoadMaterials()' 'body': 'LoadMaterials($1)' 'description': 'LoadMaterials(const char fileName, int materialCount)' 'Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps)': 'prefix': 'LoadMaterialDefault()' 'body': 'LoadMaterialDefault()' 'description': 'LoadMaterialDefault(void)' 'Unload material from GPU memory (VRAM)': 'prefix': 'UnloadMaterial()' 'body': 'UnloadMaterial($1)' 'description': 'UnloadMaterial(Material material)' 'Set texture for a material map type (MAP_DIFFUSE, MAP_SPECULAR...)': 'prefix': 'SetMaterialTexture()' 'body': 'SetMaterialTexture($1)' 'description': 'SetMaterialTexture(Material material, int mapType, Texture2D texture)' 'Set material for a mesh': 'prefix': 'SetModelMeshMaterial()' 'body': 'SetModelMeshMaterial($1)' 'description': 'SetModelMeshMaterial(Model model, int meshId, int materialId)' 'Load model animations from file': 'prefix': 'LoadModelAnimations()' 'body': 'LoadModelAnimations($1)' 'description': 'LoadModelAnimations(const char fileName, int animsCount)' 'Update model animation pose': 'prefix': 'UpdateModelAnimation()' 'body': 'UpdateModelAnimation($1)' 'description': 'UpdateModelAnimation(Model model, ModelAnimation anim, int frame)' 'Unload animation data': 'prefix': 'UnloadModelAnimation()' 'body': 'UnloadModelAnimation($1)' 'description': 'UnloadModelAnimation(ModelAnimation anim)' 'Check model animation skeleton match': 'prefix': 'IsModelAnimationValid()' 'body': 'IsModelAnimationValid($1)' 'description': 'IsModelAnimationValid(Model model, ModelAnimation anim)' 'Generate polygonal mesh': 'prefix': 'GenMeshPoly()' 'body': 'GenMeshPoly($1)' 'description': 'GenMeshPoly(int sides, float radius)' 'Generate plane mesh (with subdivisions)': 'prefix': 'GenMeshPlane()' 'body': 'GenMeshPlane($1)' 'description': 'GenMeshPlane(float width, float length, int resX, int resZ)' 'Generate cuboid mesh': 'prefix': 'GenMeshCube()' 'body': 'GenMeshCube($1)' 'description': 'GenMeshCube(float width, float height, float length)' 'Generate sphere mesh (standard sphere)': 'prefix': 'GenMeshSphere()' 'body': 'GenMeshSphere($1)' 'description': 'GenMeshSphere(float radius, int rings, int slices)' 'Generate half-sphere mesh (no bottom cap)': 'prefix': 'GenMeshHemiSphere()' 'body': 'GenMeshHemiSphere($1)' 'description': 'GenMeshHemiSphere(float radius, int rings, int slices)' 'Generate cylinder mesh': 'prefix': 'GenMeshCylinder()' 'body': 'GenMeshCylinder($1)' 'description': 'GenMeshCylinder(float radius, float height, int slices)' 'Generate torus mesh': 'prefix': 'GenMeshTorus()' 'body': 'GenMeshTorus($1)' 'description': 'GenMeshTorus(float radius, float size, int radSeg, int sides)' 'Generate trefoil knot mesh': 'prefix': 'GenMeshKnot()' 'body': 'GenMeshKnot($1)' 'description': 'GenMeshKnot(float radius, float size, int radSeg, int sides)' 'Generate heightmap mesh from image data': 'prefix': 'GenMeshHeightmap()' 'body': 'GenMeshHeightmap($1)' 'description': 'GenMeshHeightmap(Image heightmap, Vector3 size)' 'Generate cubes-based map mesh from image data': 'prefix': 'GenMeshCubicmap()' 'body': 'GenMeshCubicmap($1)' 'description': 'GenMeshCubicmap(Image cubicmap, Vector3 cubeSize)' 'Compute mesh bounding box limits': 'prefix': 'MeshBoundingBox()' 'body': 'MeshBoundingBox($1)' 'description': 'MeshBoundingBox(Mesh mesh)' 'Compute mesh tangents': 'prefix': 'MeshTangents()' 'body': 'MeshTangents($1)' 'description': 'MeshTangents(Mesh mesh)' 'Compute mesh binormals': 'prefix': 'MeshBinormals()' 'body': 'MeshBinormals($1)' 'description': 'MeshBinormals(Mesh mesh)' 'Draw a model (with texture if set)': 'prefix': 'DrawModel()' 'body': 'DrawModel($1)' 'description': 'DrawModel(Model model, Vector3 position, float scale, Color tint)' 'Draw a model with extended parameters': 'prefix': 'DrawModelEx()' 'body': 'DrawModelEx($1)' 'description': 'DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint)' 'Draw a model wires (with texture if set)': 'prefix': 'DrawModelWires()' 'body': 'DrawModelWires($1)' 'description': 'DrawModelWires(Model model, Vector3 position, float scale, Color tint)' 'Draw a model wires (with texture if set) with extended parameters': 'prefix': 'DrawModelWiresEx()' 'body': 'DrawModelWiresEx($1)' 'description': 'DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint)' 'Draw bounding box (wires)': 'prefix': 'DrawBoundingBox()' 'body': 'DrawBoundingBox($1)' 'description': 'DrawBoundingBox(BoundingBox box, Color color)' 'Draw a billboard texture': 'prefix': 'DrawBillboard()' 'body': 'DrawBillboard($1)' 'description': 'DrawBillboard(Camera camera, Texture2D texture, Vector3 center, float size, Color tint)' 'Draw a billboard texture defined by sourceRec': 'prefix': 'DrawBillboardRec()' 'body': 'DrawBillboardRec($1)' 'description': 'DrawBillboardRec(Camera camera, Texture2D texture, Rectangle sourceRec, Vector3 center, float size, Color tint)' 'Detect collision between two spheres': 'prefix': 'CheckCollisionSpheres()' 'body': 'CheckCollisionSpheres($1)' 'description': 'CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB)' 'Detect collision between two bounding boxes': 'prefix': 'CheckCollisionBoxes()' 'body': 'CheckCollisionBoxes($1)' 'description': 'CheckCollisionBoxes(BoundingBox box1, BoundingBox box2)' 'Detect collision between box and sphere': 'prefix': 'CheckCollisionBoxSphere()' 'body': 'CheckCollisionBoxSphere($1)' 'description': 'CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius)' 'Detect collision between ray and sphere': 'prefix': 'CheckCollisionRaySphere()' 'body': 'CheckCollisionRaySphere($1)' 'description': 'CheckCollisionRaySphere(Ray ray, Vector3 center, float radius)' 'Detect collision between ray and sphere, returns collision point': 'prefix': 'CheckCollisionRaySphereEx()' 'body': 'CheckCollisionRaySphereEx($1)' 'description': 'CheckCollisionRaySphereEx(Ray ray, Vector3 center, float radius, Vector3 collisionPoint)' 'Detect collision between ray and box': 'prefix': 'CheckCollisionRayBox()' 'body': 'CheckCollisionRayBox($1)' 'description': 'CheckCollisionRayBox(Ray ray, BoundingBox box)' 'Get collision info between ray and model': 'prefix': 'GetCollisionRayModel()' 'body': 'GetCollisionRayModel($1)' 'description': 'GetCollisionRayModel(Ray ray, Model model)' 'Get collision info between ray and triangle': 'prefix': 'GetCollisionRayTriangle()' 'body': 'GetCollisionRayTriangle($1)' 'description': 'GetCollisionRayTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3)' 'Get collision info between ray and ground plane (Y-normal plane)': 'prefix': 'GetCollisionRayGround()' 'body': 'GetCollisionRayGround($1)' 'description': 'GetCollisionRayGround(Ray ray, float groundHeight)' 'Load shader from files and bind default locations': 'prefix': 'LoadShader()' 'body': 'LoadShader($1)' 'description': 'LoadShader(const char vsFileName, const char fsFileName)' 'Load shader from code strings and bind default locations': 'prefix': 'LoadShaderCode()' 'body': 'LoadShaderCode($1)' 'description': 'LoadShaderCode(char vsCode, char fsCode)' 'Unload shader from GPU memory (VRAM)': 'prefix': 'UnloadShader()' 'body': 'UnloadShader($1)' 'description': 'UnloadShader(Shader shader)' 'Get default shader': 'prefix': 'GetShaderDefault()' 'body': 'GetShaderDefault()' 'description': 'GetShaderDefault(void)' 'Get texture rectangle to draw shapes': 'prefix': 'GetShapesTextureRec()' 'body': 'GetShapesTextureRec()' 'description': 'GetShapesTextureRec(void)' 'Define default texture used to draw shapes': 'prefix': 'SetShapesTexture()' 'body': 'SetShapesTexture($1)' 'description': 'SetShapesTexture(Texture2D texture, Rectangle source)' 'Get shader uniform location': 'prefix': 'GetShaderLocation()' 'body': 'GetShaderLocation($1)' 'description': 'GetShaderLocation(Shader shader, const char uniformName)' 'Set shader uniform value': 'prefix': 'SetShaderValue()' 'body': 'SetShaderValue($1)' 'description': 'SetShaderValue(Shader shader, int uniformLoc, const void value, int uniformType)' 'Set shader uniform value vector': 'prefix': 'SetShaderValueV()' 'body': 'SetShaderValueV($1)' 'description': 'SetShaderValueV(Shader shader, int uniformLoc, const void value, int uniformType, int count)' 'Set shader uniform value (matrix 4x4)': 'prefix': 'SetShaderValueMatrix()' 'body': 'SetShaderValueMatrix($1)' 'description': 'SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat)' 'Set shader uniform value for texture': 'prefix': 'SetShaderValueTexture()' 'body': 'SetShaderValueTexture($1)' 'description': 'SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D texture)' 'Set a custom projection matrix (replaces internal projection matrix)': 'prefix': 'SetMatrixProjection()' 'body': 'SetMatrixProjection($1)' 'description': 'SetMatrixProjection(Matrix proj)' 'Set a custom modelview matrix (replaces internal modelview matrix)': 'prefix': 'SetMatrixModelview()' 'body': 'SetMatrixModelview($1)' 'description': 'SetMatrixModelview(Matrix view)' 'Get internal modelview matrix': 'prefix': 'GetMatrixModelview()' 'body': 'GetMatrixModelview($1)' 'description': 'GetMatrixModelview()' 'Get internal projection matrix': 'prefix': 'GetMatrixProjection()' 'body': 'GetMatrixProjection()' 'description': 'GetMatrixProjection(void)' 'Begin custom shader drawing': 'prefix': 'BeginShaderMode()' 'body': 'BeginShaderMode($1)' 'description': 'BeginShaderMode(Shader shader)' 'End custom shader drawing (use default shader)': 'prefix': 'EndShaderMode()' 'body': 'EndShaderMode()' 'description': 'EndShaderMode(void)' 'Begin blending mode (alpha, additive, multiplied)': 'prefix': 'BeginBlendMode()' 'body': 'BeginBlendMode($1)' 'description': 'BeginBlendMode(int mode)' 'End blending mode (reset to default: alpha blending)': 'prefix': 'EndBlendMode()' 'body': 'EndBlendMode()' 'description': 'EndBlendMode(void)' 'Init VR simulator for selected device parameters': 'prefix': 'InitVrSimulator()' 'body': 'InitVrSimulator()' 'description': 'InitVrSimulator(void)' 'Close VR simulator for current device': 'prefix': 'CloseVrSimulator()' 'body': 'CloseVrSimulator()' 'description': 'CloseVrSimulator(void)' 'Update VR tracking (position and orientation) and camera': 'prefix': 'UpdateVrTracking()' 'body': 'UpdateVrTracking($1)' 'description': 'UpdateVrTracking(Camera camera)' 'Set stereo rendering configuration parameters': 'prefix': 'SetVrConfiguration()' 'body': 'SetVrConfiguration($1)' 'description': 'SetVrConfiguration(VrDeviceInfo info, Shader distortion)' 'Detect if VR simulator is ready': 'prefix': 'IsVrSimulatorReady()' 'body': 'IsVrSimulatorReady()' 'description': 'IsVrSimulatorReady(void)' 'Enable/Disable VR experience': 'prefix': 'ToggleVrMode()' 'body': 'ToggleVrMode()' 'description': 'ToggleVrMode(void)' 'Begin VR simulator stereo rendering': 'prefix': 'BeginVrDrawing()' 'body': 'BeginVrDrawing()' 'description': 'BeginVrDrawing(void)' 'End VR simulator stereo rendering': 'prefix': 'EndVrDrawing()' 'body': 'EndVrDrawing()' 'description': 'EndVrDrawing(void)' 'Initialize audio device and context': 'prefix': 'InitAudioDevice()' 'body': 'InitAudioDevice()' 'description': 'InitAudioDevice(void)' 'Close the audio device and context (and music stream)': 'prefix': 'CloseAudioDevice()' 'body': 'CloseAudioDevice()' 'description': 'CloseAudioDevice(void)' 'Check if audio device is ready': 'prefix': 'IsAudioDeviceReady()' 'body': 'IsAudioDeviceReady()' 'description': 'IsAudioDeviceReady(void)' 'Set master volume (listener)': 'prefix': 'SetMasterVolume()' 'body': 'SetMasterVolume($1)' 'description': 'SetMasterVolume(float volume)' 'Load wave data from file': 'prefix': 'LoadWave()' 'body': 'LoadWave($1)' 'description': 'LoadWave(const char fileName)' 'Load wave data from raw array data': 'prefix': 'LoadWaveEx()' 'body': 'LoadWaveEx($1)' 'description': 'LoadWaveEx(void data, int sampleCount, int sampleRate, int sampleSize, int channels)' 'Load sound from file': 'prefix': 'LoadSound()' 'body': 'LoadSound($1)' 'description': 'LoadSound(const char fileName)' 'Load sound from wave data': 'prefix': 'LoadSoundFromWave()' 'body': 'LoadSoundFromWave($1)' 'description': 'LoadSoundFromWave(Wave wave)' 'Update sound buffer with new data': 'prefix': 'UpdateSound()' 'body': 'UpdateSound($1)' 'description': 'UpdateSound(Sound sound, const void data, int samplesCount)' 'Unload wave data': 'prefix': 'UnloadWave()' 'body': 'UnloadWave($1)' 'description': 'UnloadWave(Wave wave)' 'Unload sound': 'prefix': 'UnloadSound()' 'body': 'UnloadSound($1)' 'description': 'UnloadSound(Sound sound)' 'Export wave data to file': 'prefix': 'ExportWave()' 'body': 'ExportWave($1)' 'description': 'ExportWave(Wave wave, const char fileName)' 'Export wave sample data to code (.h)': 'prefix': 'ExportWaveAsCode()' 'body': 'ExportWaveAsCode($1)' 'description': 'ExportWaveAsCode(Wave wave, const char fileName)' 'Play a sound': 'prefix': 'PlaySound()' 'body': 'PlaySound($1)' 'description': 'PlaySound(Sound sound)' 'Stop playing a sound': 'prefix': 'StopSound()' 'body': 'StopSound($1)' 'description': 'StopSound(Sound sound)' 'Pause a sound': 'prefix': 'PauseSound()' 'body': 'PauseSound($1)' 'description': 'PauseSound(Sound sound)' 'Resume a paused sound': 'prefix': 'ResumeSound()' 'body': 'ResumeSound($1)' 'description': 'ResumeSound(Sound sound)' 'Play a sound (using multichannel buffer pool)': 'prefix': 'PlaySoundMulti()' 'body': 'PlaySoundMulti($1)' 'description': 'PlaySoundMulti(Sound sound)' 'Stop any sound playing (using multichannel buffer pool)': 'prefix': 'StopSoundMulti()' 'body': 'StopSoundMulti()' 'description': 'StopSoundMulti(void)' 'Get number of sounds playing in the multichannel': 'prefix': 'GetSoundsPlaying()' 'body': 'GetSoundsPlaying()' 'description': 'GetSoundsPlaying(void)' 'Check if a sound is currently playing': 'prefix': 'IsSoundPlaying()' 'body': 'IsSoundPlaying($1)' 'description': 'IsSoundPlaying(Sound sound)' 'Set volume for a sound (1.0 is max level)': 'prefix': 'SetSoundVolume()' 'body': 'SetSoundVolume($1)' 'description': 'SetSoundVolume(Sound sound, float volume)' 'Set pitch for a sound (1.0 is base level)': 'prefix': 'SetSoundPitch()' 'body': 'SetSoundPitch($1)' 'description': 'SetSoundPitch(Sound sound, float pitch)' 'Convert wave data to desired format': 'prefix': 'WaveFormat()' 'body': 'WaveFormat($1)' 'description': 'WaveFormat(Wave wave, int sampleRate, int sampleSize, int channels)' 'Copy a wave to a new wave': 'prefix': 'WaveCopy()' 'body': 'WaveCopy($1)' 'description': 'WaveCopy(Wave wave)' 'Crop a wave to defined samples range': 'prefix': 'WaveCrop()' 'body': 'WaveCrop($1)' 'description': 'WaveCrop(Wave wave, int initSample, int finalSample)' 'Get samples data from wave as a floats array': 'prefix': 'GetWaveData()' 'body': 'GetWaveData($1)' 'description': 'GetWaveData(Wave wave)' 'Load music stream from file': 'prefix': 'LoadMusicStream()' 'body': 'LoadMusicStream($1)' 'description': 'LoadMusicStream(const char fileName)' 'Unload music stream': 'prefix': 'UnloadMusicStream()' 'body': 'UnloadMusicStream($1)' 'description': 'UnloadMusicStream(Music music)' 'Start music playing': 'prefix': 'PlayMusicStream()' 'body': 'PlayMusicStream($1)' 'description': 'PlayMusicStream(Music music)' 'Updates buffers for music streaming': 'prefix': 'UpdateMusicStream()' 'body': 'UpdateMusicStream($1)' 'description': 'UpdateMusicStream(Music music)' 'Stop music playing': 'prefix': 'StopMusicStream()' 'body': 'StopMusicStream($1)' 'description': 'StopMusicStream(Music music)' 'Pause music playing': 'prefix': 'PauseMusicStream()' 'body': 'PauseMusicStream($1)' 'description': 'PauseMusicStream(Music music)' 'Resume playing paused music': 'prefix': 'ResumeMusicStream()' 'body': 'ResumeMusicStream($1)' 'description': 'ResumeMusicStream(Music music)' 'Check if music is playing': 'prefix': 'IsMusicPlaying()' 'body': 'IsMusicPlaying($1)' 'description': 'IsMusicPlaying(Music music)' 'Set volume for music (1.0 is max level)': 'prefix': 'SetMusicVolume()' 'body': 'SetMusicVolume($1)' 'description': 'SetMusicVolume(Music music, float volume)' 'Set pitch for a music (1.0 is base level)': 'prefix': 'SetMusicPitch()' 'body': 'SetMusicPitch($1)' 'description': 'SetMusicPitch(Music music, float pitch)' 'Set music loop count (loop repeats)': 'prefix': 'SetMusicLoopCount()' 'body': 'SetMusicLoopCount($1)' 'description': 'SetMusicLoopCount(Music music, int count)' 'Get music time length (in seconds)': 'prefix': 'GetMusicTimeLength()' 'body': 'GetMusicTimeLength($1)' 'description': 'GetMusicTimeLength(Music music)' 'Get current music time played (in seconds)': 'prefix': 'GetMusicTimePlayed()' 'body': 'GetMusicTimePlayed($1)' 'description': 'GetMusicTimePlayed(Music music)' 'Init audio stream (to stream raw audio pcm data)': 'prefix': 'InitAudioStream()' 'body': 'InitAudioStream($1)' 'description': 'InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels)' 'Update audio stream buffers with data': 'prefix': 'UpdateAudioStream()' 'body': 'UpdateAudioStream($1)' 'description': 'UpdateAudioStream(AudioStream stream, const void data, int samplesCount)' 'Close audio stream and free memory': 'prefix': 'CloseAudioStream()' 'body': 'CloseAudioStream($1)' 'description': 'CloseAudioStream(AudioStream stream)' 'Check if any audio stream buffers requires refill': 'prefix': 'IsAudioBufferProcessed()' 'body': 'IsAudioBufferProcessed($1)' 'description': 'IsAudioBufferProcessed(AudioStream stream)' 'Play audio stream': 'prefix': 'PlayAudioStream()' 'body': 'PlayAudioStream($1)' 'description': 'PlayAudioStream(AudioStream stream)' 'Pause audio stream': 'prefix': 'PauseAudioStream()' 'body': 'PauseAudioStream($1)' 'description': 'PauseAudioStream(AudioStream stream)' 'Resume audio stream': 'prefix': 'ResumeAudioStream()' 'body': 'ResumeAudioStream($1)' 'description': 'ResumeAudioStream(AudioStream stream)' 'Check if audio stream is playing': 'prefix': 'IsAudioStreamPlaying()' 'body': 'IsAudioStreamPlaying($1)' 'description': 'IsAudioStreamPlaying(AudioStream stream)' 'Stop audio stream': 'prefix': 'StopAudioStream()' 'body': 'StopAudioStream($1)' 'description': 'StopAudioStream(AudioStream stream)' 'Set volume for audio stream (1.0 is max level)': 'prefix': 'SetAudioStreamVolume()' 'body': 'SetAudioStreamVolume($1)' 'description': 'SetAudioStreamVolume(AudioStream stream, float volume)' 'Set pitch for audio stream (1.0 is base level)': 'prefix': 'SetAudioStreamPitch()' 'body': 'SetAudioStreamPitch($1)' 'description': 'SetAudioStreamPitch(AudioStream stream, float pitch)'
true
'.source.python': 'Light Gray': 'prefix': 'LIGHTGRAY' 'body': 'LIGHTGRAY' 'Gray': 'prefix': 'GRAY' 'body': 'GRAY' 'Dark Gray': 'prefix': 'DARKGRAY' 'body': 'DARKGRAY' 'Yellow': 'prefix': 'YELLOW' 'body': 'YELLOW' 'Gold': 'prefix': 'GOLD' 'body': 'GOLD' 'Orange': 'prefix': 'ORANGE' 'body': 'ORANGE' 'Pink': 'prefix': 'PINK' 'body': 'PINK' 'Red': 'prefix': 'RED' 'body': 'RED' 'Maroon': 'prefix': 'MAROON' 'body': 'MAROON' 'Green': 'prefix': 'GREEN' 'body': 'GREEN' 'Lime': 'prefix': 'LIME' 'body': 'LIME' 'Dark Green': 'prefix': 'DARKGREEN' 'body': 'DARKGREEN' 'Sky Blue': 'prefix': 'SKYBLUE' 'body': 'SKYBLUE' 'Blue': 'prefix': 'BLUE' 'body': 'BLUE' 'Dark Blue': 'prefix': 'DARKBLUE' 'body': 'DARKBLUE' 'Purple': 'prefix': 'PURPLE' 'body': 'PURPLE' 'Violet': 'prefix': 'VIOLET' 'body': 'VIOLET' 'Dark Purple': 'prefix': 'DARKPURPLE' 'body': 'DARKPURPLE' 'Beige': 'prefix': 'BEIGE' 'body': 'BEIGE' 'Brown': 'prefix': 'BROWN' 'body': 'BROWN' 'Dark Brown': 'prefix': 'DARKBROWN' 'body': 'DARKBROWN' 'White': 'prefix': 'WHITE' 'body': 'WHITE' 'Black': 'prefix': 'BLACK' 'body': 'BLACK' 'Transparent': 'prefix': 'BLANK' 'body': 'BLANK' 'Magenta': 'prefix': 'MAGENTA' 'body': 'MAGENTA' 'PI:NAME:<NAME>END_PI': 'prefix': 'RAYWHITE' 'body': 'RAYWHITE' 'Initialize window and OpenGL context': 'prefix': 'InitWindow()' 'body': 'InitWindow($1)' 'description': 'InitWindow(int width, int height, const char title)' 'Check if KEY_ESCAPE pressed or Close icon pressed': 'prefix': 'WindowShouldClose()' 'body': 'WindowShouldClose()' 'description': 'WindowShouldClose(void)' 'Close window and unload OpenGL context': 'prefix': 'CloseWindow()' 'body': 'CloseWindow()' 'description': 'CloseWindow(void)' 'Check if window has been initialized successfully': 'prefix': 'IsWindowReady()' 'body': 'IsWindowReady()' 'description': 'IsWindowReady(void)' 'Check if window has been minimized (or lost focus)': 'prefix': 'IsWindowMinimized()' 'body': 'IsWindowMinimized()' 'description': 'IsWindowMinimized(void)' 'Check if window has been resized': 'prefix': 'IsWindowResized()' 'body': 'IsWindowResized()' 'description': 'IsWindowResized(void)' 'Check if window is currently hidden': 'prefix': 'IsWindowHidden()' 'body': 'IsWindowHidden()' 'description': 'IsWindowHidden(void)' 'Check if window is currently fullscreen': 'prefix': 'IsWindowFullscreen()' 'body': 'IsWindowFullscreen()' 'description': 'IsWindowFullscreen(void)' 'Toggle fullscreen mode (only PLATFORM_DESKTOP)': 'prefix': 'ToggleFullscreen()' 'body': 'ToggleFullscreen()' 'description': 'ToggleFullscreen(void)' 'Show the window': 'prefix': 'UnhideWindow()' 'body': 'UnhideWindow()' 'description': 'UnhideWindow(void)' 'Hide the window': 'prefix': 'HideWindow()' 'body': 'HideWindow()' 'description': 'HideWindow(void)' 'Set icon for window (only PLATFORM_DESKTOP)': 'prefix': 'SetWindowIcon()' 'body': 'SetWindowIcon($1)' 'description': 'SetWindowIcon(Image image)' 'Set title for window (only PLATFORM_DESKTOP)': 'prefix': 'SetWindowTitle()' 'body': 'SetWindowTitle($1)' 'description': 'SetWindowTitle(const char title)' 'Set window position on screen (only PLATFORM_DESKTOP)': 'prefix': 'SetWindowPosition()' 'body': 'SetWindowPosition($1)' 'description': 'SetWindowPosition(int x, int y)' 'Set monitor for the current window (fullscreen mode)': 'prefix': 'SetWindowMonitor()' 'body': 'SetWindowMonitor($1)' 'description': 'SetWindowMonitor(int monitor)' 'Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE)': 'prefix': 'SetWindowMinSize()' 'body': 'SetWindowMinSize($1)' 'description': 'SetWindowMinSize(int width, int height)' 'Set window dimensions': 'prefix': 'SetWindowSize()' 'body': 'SetWindowSize($1)' 'description': 'SetWindowSize(int width, int height)' 'Get native window handle': 'prefix': 'GetWindowHandle()' 'body': 'GetWindowHandle()' 'description': 'GetWindowHandle(void)' 'Get current screen width': 'prefix': 'GetScreenWidth()' 'body': 'GetScreenWidth()' 'description': 'GetScreenWidth(void)' 'Get current screen height': 'prefix': 'GetScreenHeight()' 'body': 'GetScreenHeight()' 'description': 'GetScreenHeight(void)' 'Get number of connected monitors': 'prefix': 'GetMonitorCount()' 'body': 'GetMonitorCount()' 'description': 'GetMonitorCount(void)' 'Get primary monitor width': 'prefix': 'GetMonitorWidth()' 'body': 'GetMonitorWidth($1)' 'description': 'GetMonitorWidth(int monitor)' 'Get primary monitor height': 'prefix': 'GetMonitorHeight()' 'body': 'GetMonitorHeight($1)' 'description': 'GetMonitorHeight(int monitor)' 'Get primary monitor physical width in millimetres': 'prefix': 'GetMonitorPhysicalWidth()' 'body': 'GetMonitorPhysicalWidth($1)' 'description': 'GetMonitorPhysicalWidth(int monitor)' 'Get primary monitor physical height in millimetres': 'prefix': 'GetMonitorPhysicalHeight()' 'body': 'GetMonitorPhysicalHeight($1)' 'description': 'GetMonitorPhysicalHeight(int monitor)' 'Get window position XY on monitor': 'prefix': 'GetWindowPosition()' 'body': 'GetWindowPosition()' 'description': 'GetWindowPosition(void)' 'Set clipboard text content': 'prefix': 'SetClipboardText()' 'body': 'SetClipboardText($1)' 'description': 'SetClipboardText(const char text)' 'Shows cursor': 'prefix': 'ShowCursor()' 'body': 'ShowCursor()' 'description': 'ShowCursor(void)' 'Hides cursor': 'prefix': 'HideCursor()' 'body': 'HideCursor()' 'description': 'HideCursor(void)' 'Check if cursor is not visible': 'prefix': 'IsCursorHidden()' 'body': 'IsCursorHidden()' 'description': 'IsCursorHidden(void)' 'Enables cursor (unlock cursor)': 'prefix': 'EnableCursor()' 'body': 'EnableCursor()' 'description': 'EnableCursor(void)' 'Disables cursor (lock cursor)': 'prefix': 'DisableCursor()' 'body': 'DisableCursor()' 'description': 'DisableCursor(void)' 'Set background color (framebuffer clear color)': 'prefix': 'ClearBackground()' 'body': 'ClearBackground($1)' 'description': 'ClearBackground(Color color)' 'Setup canvas (framebuffer) to start drawing': 'prefix': 'BeginDrawing()' 'body': 'BeginDrawing()' 'description': 'BeginDrawing(void)' 'End canvas drawing and swap buffers (double buffering)': 'prefix': 'EndDrawing()' 'body': 'EndDrawing()' 'description': 'EndDrawing(void)' 'Initialize 2D mode with custom camera (2D)': 'prefix': 'BeginMode2D()' 'body': 'BeginMode2D($1)' 'description': 'BeginMode2D(Camera2D camera)' 'Ends 2D mode with custom camera': 'prefix': 'EndMode2D()' 'body': 'EndMode2D()' 'description': 'EndMode2D(void)' 'Initializes 3D mode with custom camera (3D)': 'prefix': 'BeginMode3D()' 'body': 'BeginMode3D($1)' 'description': 'BeginMode3D(Camera3D camera)' 'Ends 3D mode and returns to default 2D orthographic mode': 'prefix': 'EndMode3D()' 'body': 'EndMode3D()' 'description': 'EndMode3D(void)' 'Initializes render texture for drawing': 'prefix': 'BeginTextureMode()' 'body': 'BeginTextureMode($1)' 'description': 'BeginTextureMode(RenderTexture2D target)' 'Ends drawing to render texture': 'prefix': 'EndTextureMode()' 'body': 'EndTextureMode()' 'description': 'EndTextureMode(void)' 'Begin scissor mode (define screen area for following drawing)': 'prefix': 'BeginScissorMode()' 'body': 'BeginScissorMode($1)' 'description': 'BeginScissorMode(int x, int y, int width, int height)' 'End scissor mode': 'prefix': 'EndScissorMode()' 'body': 'EndScissorMode()' 'description': 'EndScissorMode(void)' 'Returns a ray trace from mouse position': 'prefix': 'GetMouseRay()' 'body': 'GetMouseRay($1)' 'description': 'GetMouseRay(Vector2 mousePosition, Camera camera)' 'Returns camera transform matrix (view matrix)': 'prefix': 'GetCameraMatrix()' 'body': 'GetCameraMatrix($1)' 'description': 'GetCameraMatrix(Camera camera)' 'Returns camera 2d transform matrix': 'prefix': 'GetCameraMatrix2D()' 'body': 'GetCameraMatrix2D($1)' 'description': 'GetCameraMatrix2D(Camera2D camera)' 'Returns the screen space position for a 3d world space position': 'prefix': 'GetWorldToScreen()' 'body': 'GetWorldToScreen($1)' 'description': 'GetWorldToScreen(Vector3 position, Camera camera)' 'Returns size position for a 3d world space position': 'prefix': 'GetWorldToScreenEx()' 'body': 'GetWorldToScreenEx($1)' 'description': 'GetWorldToScreenEx(Vector3 position, Camera camera,int width, int height)' 'Returns the screen space position for a 2d camera world space position': 'prefix': 'GetWorldToScreen2D()' 'body': 'GetWorldToScreen2D($1)' 'description': 'GetWorldToScreen2D(Vector2 position, Camera2D camera)' 'Returns the world space position for a 2d camera screen space position': 'prefix': 'GetScreenToWorld2D()' 'body': 'GetScreenToWorld2D($1)' 'description': 'GetScreenToWorld2D(Vector2 position, Camera2D camera)' 'Set target FPS (maximum)': 'prefix': 'SetTargetFPS()' 'body': 'SetTargetFPS($1)' 'description': 'SetTargetFPS(int fps)' 'Returns current FPS': 'prefix': 'GetFPS()' 'body': 'GetFPS()' 'description': 'GetFPS(void)' 'Returns time in seconds for last frame drawn': 'prefix': 'GetFrameTime()' 'body': 'GetFrameTime()' 'description': 'GetFrameTime(void)' 'Returns elapsed time in seconds since InitWindow()': 'prefix': 'GetTime()' 'body': 'GetTime()' 'description': 'GetTime(void)' 'Returns hexadecimal value for a Color': 'prefix': 'ColorToInt()' 'body': 'ColorToInt($1)' 'description': 'ColorToInt(Color color)' 'Returns color normalized as float [0..1]': 'prefix': 'ColorNormalize()' 'body': 'ColorNormalize($1)' 'description': 'ColorNormalize(Color color)' 'Returns color from normalized values [0..1]': 'prefix': 'ColorFromNormalized()' 'body': 'ColorFromNormalized($1)' 'description': 'ColorFromNormalized(Vector4 normalized)' 'Returns HSV values for a Color': 'prefix': 'ColorToHSV()' 'body': 'ColorToHSV($1)' 'description': 'ColorToHSV(Color color)' 'Returns a Color from HSV values': 'prefix': 'ColorFromHSV()' 'body': 'ColorFromHSV($1)' 'description': 'ColorFromHSV(Vector3 hsv)' 'Returns a Color struct from hexadecimal value': 'prefix': 'GetColor()' 'body': 'GetColor($1)' 'description': 'GetColor(int hexValue)' 'Color fade-in or fade-out, alpha goes from 0.0f to 1.0f': 'prefix': 'Fade()' 'body': 'Fade($1)' 'description': 'Fade(Color color, float alpha)' 'Setup window configuration flags (view FLAGS)': 'prefix': 'SetConfigFlags()' 'body': 'SetConfigFlags($1)' 'description': 'SetConfigFlags(unsigned int flags)' 'Set the current threshold (minimum) log level': 'prefix': 'SetTraceLogLevel()' 'body': 'SetTraceLogLevel($1)' 'description': 'SetTraceLogLevel(int logType)' 'Set the exit threshold (minimum) log level': 'prefix': 'SetTraceLogExit()' 'body': 'SetTraceLogExit($1)' 'description': 'SetTraceLogExit(int logType)' 'Set a trace log callback to enable custom logging': 'prefix': 'SetTraceLogCallback()' 'body': 'SetTraceLogCallback($1)' 'description': 'SetTraceLogCallback(TraceLogCallback callback)' 'Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR)': 'prefix': 'TraceLog()' 'body': 'TraceLog($1)' 'description': 'TraceLog(int logType, const char text, ...)' 'Takes a screenshot of current screen (saved a .png)': 'prefix': 'TakeScreenshot()' 'body': 'TakeScreenshot($1)' 'description': 'TakeScreenshot(const char fileName)' 'Returns a random value between min and max (both included)': 'prefix': 'GetRandomValue()' 'body': 'GetRandomValue($1)' 'description': 'GetRandomValue(int min, int max)' 'Save data to file from byte array (write)': 'prefix': 'SaveFileData()' 'body': 'SaveFileData($1)' 'description': 'SaveFileData(const char fileName, void data, int bytesToWrite)' 'Save text data to file (write), string must be \' \' terminated': 'prefix': 'SaveFileText()' 'body': 'SaveFileText($1)' 'description': 'SaveFileText(const char fileName, char text)' 'Check if file exists': 'prefix': 'FileExists()' 'body': 'FileExists($1)' 'description': 'FileExists(const char fileName)' 'Check file extension': 'prefix': 'IsFileExtension()' 'body': 'IsFileExtension($1)' 'description': 'IsFileExtension(const char fileName, const char ext)' 'Check if a directory path exists': 'prefix': 'DirectoryExists()' 'body': 'DirectoryExists($1)' 'description': 'DirectoryExists(const char dirPath)' 'Clear directory files paths buffers (free memory)': 'prefix': 'ClearDirectoryFiles()' 'body': 'ClearDirectoryFiles()' 'description': 'ClearDirectoryFiles(void)' 'Change working directory, returns true if success': 'prefix': 'ChangeDirectory()' 'body': 'ChangeDirectory($1)' 'description': 'ChangeDirectory(const char dir)' 'Check if a file has been dropped into window': 'prefix': 'IsFileDropped()' 'body': 'IsFileDropped()' 'description': 'IsFileDropped(void)' 'Clear dropped files paths buffer (free memory)': 'prefix': 'ClearDroppedFiles()' 'body': 'ClearDroppedFiles()' 'description': 'ClearDroppedFiles(void)' 'Load integer value from storage file (from defined position)': 'prefix': 'LoadStorageValue()' 'body': 'LoadStorageValue($1)' 'description': 'LoadStorageValue(int position)' 'Save integer value to storage file (to defined position)': 'prefix': 'SaveStorageValue()' 'body': 'SaveStorageValue($1)' 'description': 'SaveStorageValue(int position, int value)' 'Open URL with default system browser (if available)': 'prefix': 'OpenURL()' 'body': 'OpenURL($1)' 'description': 'OpenURL(const char url)' 'Detect if a key has been pressed once': 'prefix': 'IsKeyPressed()' 'body': 'IsKeyPressed($1)' 'description': 'IsKeyPressed(int key)' 'Detect if a key is being pressed': 'prefix': 'IsKeyDown()' 'body': 'IsKeyDown($1)' 'description': 'IsKeyDown(int key)' 'Detect if a key has been released once': 'prefix': 'IsKeyReleased()' 'body': 'IsKeyReleased($1)' 'description': 'IsKeyReleased(int key)' 'Detect if a key is NOT being pressed': 'prefix': 'IsKeyUp()' 'body': 'IsKeyUp($1)' 'description': 'IsKeyUp(int key)' 'Get latest key pressed': 'prefix': 'GetKeyPressed()' 'body': 'GetKeyPressed()' 'description': 'GetKeyPressed(void)' 'Set a custom key to exit program (default is ESC)': 'prefix': 'SetExitKey()' 'body': 'SetExitKey($1)' 'description': 'SetExitKey(int key)' 'Detect if a gamepad is available': 'prefix': 'IsGamepadAvailable()' 'body': 'IsGamepadAvailable($1)' 'description': 'IsGamepadAvailable(int gamepad)' 'Check gamepad name (if available)': 'prefix': 'IsGamepadName()' 'body': 'IsGamepadName($1)' 'description': 'IsGamepadName(int gamepad, const char name)' 'Detect if a gamepad button has been pressed once': 'prefix': 'IsGamepadButtonPressed()' 'body': 'IsGamepadButtonPressed($1)' 'description': 'IsGamepadButtonPressed(int gamepad, int button)' 'Detect if a gamepad button is being pressed': 'prefix': 'IsGamepadButtonDown()' 'body': 'IsGamepadButtonDown($1)' 'description': 'IsGamepadButtonDown(int gamepad, int button)' 'Detect if a gamepad button has been released once': 'prefix': 'IsGamepadButtonReleased()' 'body': 'IsGamepadButtonReleased($1)' 'description': 'IsGamepadButtonReleased(int gamepad, int button)' 'Detect if a gamepad button is NOT being pressed': 'prefix': 'IsGamepadButtonUp()' 'body': 'IsGamepadButtonUp($1)' 'description': 'IsGamepadButtonUp(int gamepad, int button)' 'Get the last gamepad button pressed': 'prefix': 'GetGamepadButtonPressed()' 'body': 'GetGamepadButtonPressed()' 'description': 'GetGamepadButtonPressed(void)' 'Return gamepad axis count for a gamepad': 'prefix': 'GetGamepadAxisCount()' 'body': 'GetGamepadAxisCount($1)' 'description': 'GetGamepadAxisCount(int gamepad)' 'Return axis movement value for a gamepad axis': 'prefix': 'GetGamepadAxisMovement()' 'body': 'GetGamepadAxisMovement($1)' 'description': 'GetGamepadAxisMovement(int gamepad, int axis)' 'Detect if a mouse button has been pressed once': 'prefix': 'IsMouseButtonPressed()' 'body': 'IsMouseButtonPressed($1)' 'description': 'IsMouseButtonPressed(int button)' 'Detect if a mouse button is being pressed': 'prefix': 'IsMouseButtonDown()' 'body': 'IsMouseButtonDown($1)' 'description': 'IsMouseButtonDown(int button)' 'Detect if a mouse button has been released once': 'prefix': 'IsMouseButtonReleased()' 'body': 'IsMouseButtonReleased($1)' 'description': 'IsMouseButtonReleased(int button)' 'Detect if a mouse button is NOT being pressed': 'prefix': 'IsMouseButtonUp()' 'body': 'IsMouseButtonUp($1)' 'description': 'IsMouseButtonUp(int button)' 'Returns mouse position X': 'prefix': 'GetMouseX()' 'body': 'GetMouseX()' 'description': 'GetMouseX(void)' 'Returns mouse position Y': 'prefix': 'GetMouseY()' 'body': 'GetMouseY()' 'description': 'GetMouseY(void)' 'Returns mouse position XY': 'prefix': 'GetMousePosition()' 'body': 'GetMousePosition()' 'description': 'GetMousePosition(void)' 'Set mouse position XY': 'prefix': 'SetMousePosition()' 'body': 'SetMousePosition($1)' 'description': 'SetMousePosition(int x, int y)' 'Set mouse offset': 'prefix': 'SetMouseOffset()' 'body': 'SetMouseOffset($1)' 'description': 'SetMouseOffset(int offsetX, int offsetY)' 'Set mouse scaling': 'prefix': 'SetMouseScale()' 'body': 'SetMouseScale($1)' 'description': 'SetMouseScale(float scaleX, float scaleY)' 'Returns mouse wheel movement Y': 'prefix': 'GetMouseWheelMove()' 'body': 'GetMouseWheelMove()' 'description': 'GetMouseWheelMove(void)' 'Returns touch position X for touch point 0 (relative to screen size)': 'prefix': 'GetTouchX()' 'body': 'GetTouchX()' 'description': 'GetTouchX(void)' 'Returns touch position Y for touch point 0 (relative to screen size)': 'prefix': 'GetTouchY()' 'body': 'GetTouchY()' 'description': 'GetTouchY(void)' 'Returns touch position XY for a touch point index (relative to screen size)': 'prefix': 'GetTouchPosition()' 'body': 'GetTouchPosition($1)' 'description': 'GetTouchPosition(int index)' 'Enable a set of gestures using flags': 'prefix': 'SetGesturesEnabled()' 'body': 'SetGesturesEnabled($1)' 'description': 'SetGesturesEnabled(unsigned int gestureFlags)' 'Check if a gesture have been detected': 'prefix': 'IsGestureDetected()' 'body': 'IsGestureDetected($1)' 'description': 'IsGestureDetected(int gesture)' 'Get latest detected gesture': 'prefix': 'GetGestureDetected()' 'body': 'GetGestureDetected()' 'description': 'GetGestureDetected(void)' 'Get touch points count': 'prefix': 'GetTouchPointsCount()' 'body': 'GetTouchPointsCount()' 'description': 'GetTouchPointsCount(void)' 'Get gesture hold time in milliseconds': 'prefix': 'GetGestureHoldDuration()' 'body': 'GetGestureHoldDuration()' 'description': 'GetGestureHoldDuration(void)' 'Get gesture drag vector': 'prefix': 'GetGestureDragVector()' 'body': 'GetGestureDragVector()' 'description': 'GetGestureDragVector(void)' 'Get gesture drag angle': 'prefix': 'GetGestureDragAngle()' 'body': 'GetGestureDragAngle()' 'description': 'GetGestureDragAngle(void)' 'Get gesture pinch delta': 'prefix': 'GetGesturePinchVector()' 'body': 'GetGesturePinchVector()' 'description': 'GetGesturePinchVector(void)' 'Get gesture pinch angle': 'prefix': 'GetGesturePinchAngle()' 'body': 'GetGesturePinchAngle()' 'description': 'GetGesturePinchAngle(void)' 'Set camera mode (multiple camera modes available)': 'prefix': 'SetCameraMode()' 'body': 'SetCameraMode($1)' 'description': 'SetCameraMode(Camera camera, int mode)' 'Update camera position for selected mode': 'prefix': 'UpdateCamera()' 'body': 'UpdateCamera($1)' 'description': 'UpdateCamera(Camera camera)' 'Set camera pan key to combine with mouse movement (free camera)': 'prefix': 'SetCameraPanControl()' 'body': 'SetCameraPanControl($1)' 'description': 'SetCameraPanControl(int panKey)' 'Set camera alt key to combine with mouse movement (free camera)': 'prefix': 'SetCameraAltControl()' 'body': 'SetCameraAltControl($1)' 'description': 'SetCameraAltControl(int altKey)' 'Set camera smooth zoom key to combine with mouse (free camera)': 'prefix': 'SetCameraSmoothZoomControl()' 'body': 'SetCameraSmoothZoomControl($1)' 'description': 'SetCameraSmoothZoomControl(int szKey)' 'Set camera move controls (1st person and 3rd person cameras)': 'prefix': 'SetCameraMoveControls()' 'body': 'SetCameraMoveControls($1)' 'description': 'SetCameraMoveControls(int frontKey, int backKey, int rightKey, int leftKey, int upKey, int downKey)' 'Draw a pixel': 'prefix': 'DrawPixel()' 'body': 'DrawPixel($1)' 'description': 'DrawPixel(int posX, int posY, Color color)' 'Draw a pixel (Vector version)': 'prefix': 'DrawPixelV()' 'body': 'DrawPixelV($1)' 'description': 'DrawPixelV(Vector2 position, Color color)' 'Draw a line': 'prefix': 'DrawLine()' 'body': 'DrawLine($1)' 'description': 'DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color)' 'Draw a line (Vector version)': 'prefix': 'DrawLineV()' 'body': 'DrawLineV($1)' 'description': 'DrawLineV(Vector2 startPos, Vector2 endPos, Color color)' 'Draw a line defining thickness': 'prefix': 'DrawLineEx()' 'body': 'DrawLineEx($1)' 'description': 'DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color)' 'Draw a line using cubic-bezier curves in-out': 'prefix': 'DrawLineBezier()' 'body': 'DrawLineBezier($1)' 'description': 'DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color)' 'Draw lines sequence': 'prefix': 'DrawLineStrip()' 'body': 'DrawLineStrip($1)' 'description': 'DrawLineStrip(Vector2 points, int numPoints, Color color)' 'Draw a color-filled circle': 'prefix': 'DrawCircle()' 'body': 'DrawCircle($1)' 'description': 'DrawCircle(int centerX, int centerY, float radius, Color color)' 'Draw a piece of a circle': 'prefix': 'DrawCircleSector()' 'body': 'DrawCircleSector($1)' 'description': 'DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color)' 'Draw circle sector outline': 'prefix': 'DrawCircleSectorLines()' 'body': 'DrawCircleSectorLines($1)' 'description': 'DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color)' 'Draw a gradient-filled circle': 'prefix': 'DrawCircleGradient()' 'body': 'DrawCircleGradient($1)' 'description': 'DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2)' 'Draw a color-filled circle (Vector version)': 'prefix': 'DrawCircleV()' 'body': 'DrawCircleV($1)' 'description': 'DrawCircleV(Vector2 center, float radius, Color color)' 'Draw circle outline': 'prefix': 'DrawCircleLines()' 'body': 'DrawCircleLines($1)' 'description': 'DrawCircleLines(int centerX, int centerY, float radius, Color color)' 'Draw ellipse': 'prefix': 'DrawEllipse()' 'body': 'DrawEllipse($1)' 'description': 'DrawEllipse(int centerX, int centerY, float radiusH, float radiusV, Color color)' 'Draw ellipse outline': 'prefix': 'DrawEllipseLines()' 'body': 'DrawEllipseLines($1)' 'description': 'DrawEllipseLines(int centerX, int centerY, float radiusH, float radiusV, Color color)' 'Draw ring': 'prefix': 'DrawRing()' 'body': 'DrawRing($1)' 'description': 'DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color)' 'Draw ring outline': 'prefix': 'DrawRingLines()' 'body': 'DrawRingLines($1)' 'description': 'DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color)' 'Draw a color-filled rectangle': 'prefix': 'DrawRectangle()' 'body': 'DrawRectangle($1)' 'description': 'DrawRectangle(int posX, int posY, int width, int height, Color color)' 'Draw a color-filled rectangle (Vector version)': 'prefix': 'DrawRectangleV()' 'body': 'DrawRectangleV($1)' 'description': 'DrawRectangleV(Vector2 position, Vector2 size, Color color)' 'Draw a defined color-filled rectangle': 'prefix': 'DrawRectangleRec()' 'body': 'DrawRectangleRec($1)' 'description': 'DrawRectangleRec(Rectangle rec, Color color)' 'Draw a color-filled rectangle with pro parameters': 'prefix': 'DrawRectanglePro()' 'body': 'DrawRectanglePro($1)' 'description': 'DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color)' 'Draw a vertical-gradient-filled rectangle': 'prefix': 'DrawRectangleGradientV()' 'body': 'DrawRectangleGradientV($1)' 'description': 'DrawRectangleGradientV(int posX, int posY, int width, int height, Color color1, Color color2)' 'Draw a horizontal-gradient-filled rectangle': 'prefix': 'DrawRectangleGradientH()' 'body': 'DrawRectangleGradientH($1)' 'description': 'DrawRectangleGradientH(int posX, int posY, int width, int height, Color color1, Color color2)' 'Draw a gradient-filled rectangle with custom vertex colors': 'prefix': 'DrawRectangleGradientEx()' 'body': 'DrawRectangleGradientEx($1)' 'description': 'DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4)' 'Draw rectangle outline': 'prefix': 'DrawRectangleLines()' 'body': 'DrawRectangleLines($1)' 'description': 'DrawRectangleLines(int posX, int posY, int width, int height, Color color)' 'Draw rectangle outline with extended parameters': 'prefix': 'DrawRectangleLinesEx()' 'body': 'DrawRectangleLinesEx($1)' 'description': 'DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color)' 'Draw rectangle with rounded edges': 'prefix': 'DrawRectangleRounded()' 'body': 'DrawRectangleRounded($1)' 'description': 'DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color)' 'Draw rectangle with rounded edges outline': 'prefix': 'DrawRectangleRoundedLines()' 'body': 'DrawRectangleRoundedLines($1)' 'description': 'DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int lineThick, Color color)' 'Draw a color-filled triangle (vertex in counter-clockwise order!)': 'prefix': 'DrawTriangle()' 'body': 'DrawTriangle($1)' 'description': 'DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color)' 'Draw triangle outline (vertex in counter-clockwise order!)': 'prefix': 'DrawTriangleLines()' 'body': 'DrawTriangleLines($1)' 'description': 'DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color)' 'Draw a triangle fan defined by points (first vertex is the center)': 'prefix': 'DrawTriangleFan()' 'body': 'DrawTriangleFan($1)' 'description': 'DrawTriangleFan(Vector2 points, int numPoints, Color color)' 'Draw a triangle strip defined by points': 'prefix': 'DrawTriangleStrip()' 'body': 'DrawTriangleStrip($1)' 'description': 'DrawTriangleStrip(Vector2 points, int pointsCount, Color color)' 'Draw a regular polygon (Vector version)': 'prefix': 'DrawPoly()' 'body': 'DrawPoly($1)' 'description': 'DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color)' 'Draw a polygon outline of n sides': 'prefix': 'DrawPolyLines()' 'body': 'DrawPolyLines($1)' 'description': 'DrawPolyLines(Vector2 center, int sides, float radius, float rotation, Color color)' 'Check collision between two rectangles': 'prefix': 'CheckCollisionRecs()' 'body': 'CheckCollisionRecs($1)' 'description': 'CheckCollisionRecs(Rectangle rec1, Rectangle rec2)' 'Check collision between two circles': 'prefix': 'CheckCollisionCircles()' 'body': 'CheckCollisionCircles($1)' 'description': 'CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2)' 'Check collision between circle and rectangle': 'prefix': 'CheckCollisionCircleRec()' 'body': 'CheckCollisionCircleRec($1)' 'description': 'CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec)' 'Get collision rectangle for two rectangles collision': 'prefix': 'GetCollisionRec()' 'body': 'GetCollisionRec($1)' 'description': 'GetCollisionRec(Rectangle rec1, Rectangle rec2)' 'Check if point is inside rectangle': 'prefix': 'CheckCollisionPointRec()' 'body': 'CheckCollisionPointRec($1)' 'description': 'CheckCollisionPointRec(Vector2 point, Rectangle rec)' 'Check if point is inside circle': 'prefix': 'CheckCollisionPointCircle()' 'body': 'CheckCollisionPointCircle($1)' 'description': 'CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius)' 'Check if point is inside a triangle': 'prefix': 'CheckCollisionPointTriangle()' 'body': 'CheckCollisionPointTriangle($1)' 'description': 'CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3)' 'Load image from file into CPU memory (RAM)': 'prefix': 'LoadImage()' 'body': 'LoadImage($1)' 'description': 'LoadImage(const char fileName)' 'Load image from Color array data (RGBA - 32bit)': 'prefix': 'LoadImageEx()' 'body': 'LoadImageEx($1)' 'description': 'LoadImageEx(Color pixels, int width, int height)' 'Load image from raw data with parameters': 'prefix': 'LoadImagePro()' 'body': 'LoadImagePro($1)' 'description': 'LoadImagePro(void data, int width, int height, int format)' 'Load image from RAW file data': 'prefix': 'LoadImageRaw()' 'body': 'LoadImageRaw($1)' 'description': 'LoadImageRaw(const char fileName, int width, int height, int format, int headerSize)' 'Unload image from CPU memory (RAM)': 'prefix': 'UnloadImage()' 'body': 'UnloadImage($1)' 'description': 'UnloadImage(Image image)' 'Export image data to file': 'prefix': 'ExportImage()' 'body': 'ExportImage($1)' 'description': 'ExportImage(Image image, const char fileName)' 'Export image as code file defining an array of bytes': 'prefix': 'ExportImageAsCode()' 'body': 'ExportImageAsCode($1)' 'description': 'ExportImageAsCode(Image image, const char fileName)' 'Get pixel data from image as a Color struct array': 'prefix': 'GetImageData()' 'body': 'GetImageData($1)' 'description': 'GetImageData(Image image)' 'Get pixel data from image as Vector4 array (float normalized)': 'prefix': 'GetImageDataNormalized()' 'body': 'GetImageDataNormalized($1)' 'description': 'GetImageDataNormalized(Image image)' 'Generate image: plain color': 'prefix': 'GenImageColor()' 'body': 'GenImageColor($1)' 'description': 'GenImageColor(int width, int height, Color color)' 'Generate image: vertical gradient': 'prefix': 'GenImageGradientV()' 'body': 'GenImageGradientV($1)' 'description': 'GenImageGradientV(int width, int height, Color top, Color bottom)' 'Generate image: horizontal gradient': 'prefix': 'GenImageGradientH()' 'body': 'GenImageGradientH($1)' 'description': 'GenImageGradientH(int width, int height, Color left, Color right)' 'Generate image: radial gradient': 'prefix': 'GenImageGradientRadial()' 'body': 'GenImageGradientRadial($1)' 'description': 'GenImageGradientRadial(int width, int height, float density, Color inner, Color outer)' 'Generate image: checked': 'prefix': 'GenImageChecked()' 'body': 'GenImageChecked($1)' 'description': 'GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2)' 'Generate image: white noise': 'prefix': 'GenImageWhiteNoise()' 'body': 'GenImageWhiteNoise($1)' 'description': 'GenImageWhiteNoise(int width, int height, float factor)' 'Generate image: perlin noise': 'prefix': 'GenImagePerlinNoise()' 'body': 'GenImagePerlinNoise($1)' 'description': 'GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale)' 'Generate image: cellular algorithm. Bigger tileSize means bigger cells': 'prefix': 'GenImageCellular()' 'body': 'GenImageCellular($1)' 'description': 'GenImageCellular(int width, int height, int tileSize)' 'Create an image duplicate (useful for transformations)': 'prefix': 'ImageCopy()' 'body': 'ImageCopy($1)' 'description': 'ImageCopy(Image image)' 'Create an image from another image piece': 'prefix': 'ImageFromImage()' 'body': 'ImageFromImage($1)' 'description': 'ImageFromImage(Image image, Rectangle rec)' 'Create an image from text (default font)': 'prefix': 'ImageText()' 'body': 'ImageText($1)' 'description': 'ImageText(const char text, int fontSize, Color color)' 'Create an image from text (custom sprite font)': 'prefix': 'ImageTextEx()' 'body': 'ImageTextEx($1)' 'description': 'ImageTextEx(Font font, const char text, float fontSize, float spacing, Color tint)' 'Convert image to POT (power-of-two)': 'prefix': 'ImageToPOT()' 'body': 'ImageToPOT($1)' 'description': 'ImageToPOT(Image image, Color fillColor)' 'Convert image data to desired format': 'prefix': 'ImageFormat()' 'body': 'ImageFormat($1)' 'description': 'ImageFormat(Image image, int newFormat)' 'Apply alpha mask to image': 'prefix': 'ImageAlphaMask()' 'body': 'ImageAlphaMask($1)' 'description': 'ImageAlphaMask(Image image, Image alphaMask)' 'Clear alpha channel to desired color': 'prefix': 'ImageAlphaClear()' 'body': 'ImageAlphaClear($1)' 'description': 'ImageAlphaClear(Image image, Color color, float threshold)' 'Crop image depending on alpha value': 'prefix': 'ImageAlphaCrop()' 'body': 'ImageAlphaCrop($1)' 'description': 'ImageAlphaCrop(Image image, float threshold)' 'Premultiply alpha channel': 'prefix': 'ImageAlphaPremultiply()' 'body': 'ImageAlphaPremultiply($1)' 'description': 'ImageAlphaPremultiply(Image image)' 'Crop an image to a defined rectangle': 'prefix': 'ImageCrop()' 'body': 'ImageCrop($1)' 'description': 'ImageCrop(Image image, Rectangle crop)' 'Resize image (Bicubic scaling algorithm)': 'prefix': 'ImageResize()' 'body': 'ImageResize($1)' 'description': 'ImageResize(Image image, int newWidth, int newHeight)' 'Resize image (Nearest-Neighbor scaling algorithm)': 'prefix': 'ImageResizeNN()' 'body': 'ImageResizeNN($1)' 'description': 'ImageResizeNN(Image image, int newWidth,int newHeight)' 'Resize canvas and fill with color': 'prefix': 'ImageResizeCanvas()' 'body': 'ImageResizeCanvas($1)' 'description': 'ImageResizeCanvas(Image image, int newWidth, int newHeight, int offsetX, int offsetY, Color color)' 'Generate all mipmap levels for a provided image': 'prefix': 'ImageMipmaps()' 'body': 'ImageMipmaps($1)' 'description': 'ImageMipmaps(Image image)' 'Dither image data to 16bpp or lower (Floyd-Steinberg dithering)': 'prefix': 'ImageDither()' 'body': 'ImageDither($1)' 'description': 'ImageDither(Image image, int rBpp, int gBpp, int bBpp, int aBpp)' 'Flip image vertically': 'prefix': 'ImageFlipVertical()' 'body': 'ImageFlipVertical($1)' 'description': 'ImageFlipVertical(Image image)' 'Flip image horizontally': 'prefix': 'ImageFlipHorizontal()' 'body': 'ImageFlipHorizontal($1)' 'description': 'ImageFlipHorizontal(Image image)' 'Rotate image clockwise 90deg': 'prefix': 'ImageRotateCW()' 'body': 'ImageRotateCW($1)' 'description': 'ImageRotateCW(Image image)' 'Rotate image counter-clockwise 90deg': 'prefix': 'ImageRotateCCW()' 'body': 'ImageRotateCCW($1)' 'description': 'ImageRotateCCW(Image image)' 'Modify image color: tint': 'prefix': 'ImageColorTint()' 'body': 'ImageColorTint($1)' 'description': 'ImageColorTint(Image image, Color color)' 'Modify image color: invert': 'prefix': 'ImageColorInvert()' 'body': 'ImageColorInvert($1)' 'description': 'ImageColorInvert(Image image)' 'Modify image color: grayscale': 'prefix': 'ImageColorGrayscale()' 'body': 'ImageColorGrayscale($1)' 'description': 'ImageColorGrayscale(Image image)' 'Modify image color: contrast (-100 to 100)': 'prefix': 'ImageColorContrast()' 'body': 'ImageColorContrast($1)' 'description': 'ImageColorContrast(Image image, float contrast)' 'Modify image color: brightness (-255 to 255)': 'prefix': 'ImageColorBrightness()' 'body': 'ImageColorBrightness($1)' 'description': 'ImageColorBrightness(Image image, int brightness)' 'Modify image color: replace color': 'prefix': 'ImageColorReplace()' 'body': 'ImageColorReplace($1)' 'description': 'ImageColorReplace(Image image, Color color, Color replace)' 'Extract color palette from image to maximum size (memory should be freed)': 'prefix': 'ImageExtractPalette()' 'body': 'ImageExtractPalette($1)' 'description': 'ImageExtractPalette(Image image, int maxPaletteSize, int extractCount)' 'Get image alpha border rectangle': 'prefix': 'GetImageAlphaBorder()' 'body': 'GetImageAlphaBorder($1)' 'description': 'GetImageAlphaBorder(Image image, float threshold)' 'Clear image background with given color': 'prefix': 'ImageClearBackground()' 'body': 'ImageClearBackground($1)' 'description': 'ImageClearBackground(Image dst, Color color)' 'Draw pixel within an image': 'prefix': 'ImageDrawPixel()' 'body': 'ImageDrawPixel($1)' 'description': 'ImageDrawPixel(Image dst, int posX, int posY, Color color)' 'Draw pixel within an image (Vector version)': 'prefix': 'ImageDrawPixelV()' 'body': 'ImageDrawPixelV($1)' 'description': 'ImageDrawPixelV(Image dst, Vector2 position, Color color)' 'Draw line within an image': 'prefix': 'ImageDrawLine()' 'body': 'ImageDrawLine($1)' 'description': 'ImageDrawLine(Image dst, int startPosX, int startPosY, int endPosX, int endPosY, Color color)' 'Draw line within an image (Vector version)': 'prefix': 'ImageDrawLineV()' 'body': 'ImageDrawLineV($1)' 'description': 'ImageDrawLineV(Image dst, Vector2 start, Vector2 end, Color color)' 'Draw circle within an image': 'prefix': 'ImageDrawCircle()' 'body': 'ImageDrawCircle($1)' 'description': 'ImageDrawCircle(Image dst, int centerX, int centerY, int radius, Color color)' 'Draw circle within an image (Vector version)': 'prefix': 'ImageDrawCircleV()' 'body': 'ImageDrawCircleV($1)' 'description': 'ImageDrawCircleV(Image dst, Vector2 center, int radius, Color color)' 'Draw rectangle within an image': 'prefix': 'ImageDrawRectangle()' 'body': 'ImageDrawRectangle($1)' 'description': 'ImageDrawRectangle(Image dst, int posX, int posY, int width, int height, Color color)' 'Draw rectangle within an image (Vector version)': 'prefix': 'ImageDrawRectangleV()' 'body': 'ImageDrawRectangleV($1)' 'description': 'ImageDrawRectangleV(Image dst, Vector2 position, Vector2 size, Color color)' 'Draw defined rectangle within an image': 'prefix': 'ImageDrawRectangleRec()' 'body': 'ImageDrawRectangleRec($1)' 'description': 'ImageDrawRectangleRec(Image dst, Rectangle rec, Color color)' 'Draw rectangle lines within an image': 'prefix': 'ImageDrawRectangleLines()' 'body': 'ImageDrawRectangleLines($1)' 'description': 'ImageDrawRectangleLines(Image dst, Rectangle rec, int thick, Color color)' 'Draw a source image within a destination image (tint applied to source)': 'prefix': 'ImageDraw()' 'body': 'ImageDraw($1)' 'description': 'ImageDraw(Image dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint)' 'Draw text (default font) within an image (destination)': 'prefix': 'ImageDrawText()' 'body': 'ImageDrawText($1)' 'description': 'ImageDrawText(Image dst, Vector2 position, const char text, int fontSize, Color color)' 'Draw text (custom sprite font) within an image (destination)': 'prefix': 'ImageDrawTextEx()' 'body': 'ImageDrawTextEx($1)' 'description': 'ImageDrawTextEx(Image dst, Vector2 position, Font font, const char text, float fontSize, float spacing, Color color)' 'Unload texture from GPU memory (VRAM)': 'prefix': 'UnloadTexture()' 'body': 'UnloadTexture($1)' 'description': 'UnloadTexture(Texture2D texture)' 'Unload render texture from GPU memory (VRAM)': 'prefix': 'UnloadRenderTexture()' 'body': 'UnloadRenderTexture($1)' 'description': 'UnloadRenderTexture(RenderTexture2D target)' 'Update GPU texture with new data': 'prefix': 'UpdateTexture()' 'body': 'UpdateTexture($1)' 'description': 'UpdateTexture(Texture2D texture, const void pixels)' 'Get pixel data from GPU texture and return an Image': 'prefix': 'GetTextureData()' 'body': 'GetTextureData($1)' 'description': 'GetTextureData(Texture2D texture)' 'Get pixel data from screen buffer and return an Image (screenshot)': 'prefix': 'GetScreenData()' 'body': 'GetScreenData()' 'description': 'GetScreenData(void)' 'Generate GPU mipmaps for a texture': 'prefix': 'GenTextureMipmaps()' 'body': 'GenTextureMipmaps($1)' 'description': 'GenTextureMipmaps(Texture2D texture)' 'Set texture scaling filter mode': 'prefix': 'SetTextureFilter()' 'body': 'SetTextureFilter($1)' 'description': 'SetTextureFilter(Texture2D texture, int filterMode)' 'Set texture wrapping mode': 'prefix': 'SetTextureWrap()' 'body': 'SetTextureWrap($1)' 'description': 'SetTextureWrap(Texture2D texture, int wrapMode)' 'Draw a Texture2D': 'prefix': 'DrawTexture()' 'body': 'DrawTexture($1)' 'description': 'DrawTexture(Texture2D texture, int posX, int posY, Color tint)' 'Draw a Texture2D with position defined as Vector2': 'prefix': 'DrawTextureV()' 'body': 'DrawTextureV($1)' 'description': 'DrawTextureV(Texture2D texture, Vector2 position, Color tint)' 'Draw a Texture2D with extended parameters': 'prefix': 'DrawTextureEx()' 'body': 'DrawTextureEx($1)' 'description': 'DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint)' 'Draw a part of a texture defined by a rectangle': 'prefix': 'DrawTextureRec()' 'body': 'DrawTextureRec($1)' 'description': 'DrawTextureRec(Texture2D texture, Rectangle sourceRec, Vector2 position, Color tint)' 'Draw texture quad with tiling and offset parameters': 'prefix': 'DrawTextureQuad()' 'body': 'DrawTextureQuad($1)' 'description': 'DrawTextureQuad(Texture2D texture, Vector2 tiling, Vector2 offset, Rectangle quad, Color tint)' 'Draw a part of a texture defined by a rectangle with \'pro\' parameters': 'prefix': 'DrawTexturePro()' 'body': 'DrawTexturePro($1)' 'description': 'DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, Vector2 origin, float rotation, Color tint)' 'Draws a texture (or part of it) that stretches or shrinks nicely': 'prefix': 'DrawTextureNPatch()' 'body': 'DrawTextureNPatch($1)' 'description': 'DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle destRec, Vector2 origin, float rotation, Color tint)' 'Get pixel data size in bytes (image or texture)': 'prefix': 'GetPixelDataSize()' 'body': 'GetPixelDataSize($1)' 'description': 'GetPixelDataSize(int width, int height, int format)' 'Get the default Font': 'prefix': 'GetFontDefault()' 'body': 'GetFontDefault()' 'description': 'GetFontDefault(void)' 'Load font from file into GPU memory (VRAM)': 'prefix': 'LoadFont()' 'body': 'LoadFont($1)' 'description': 'LoadFont(const char fileName)' 'Load font from file with extended parameters': 'prefix': 'LoadFontEx()' 'body': 'LoadFontEx($1)' 'description': 'LoadFontEx(const char fileName, int fontSize, int fontChars, int charsCount)' 'Load font from Image (XNA style)': 'prefix': 'LoadFontFromImage()' 'body': 'LoadFontFromImage($1)' 'description': 'LoadFontFromImage(Image image, Color key, int firstChar)' 'Load font data for further use': 'prefix': 'LoadFontData()' 'body': 'LoadFontData($1)' 'description': 'LoadFontData(const char fileName, int fontSize, int fontChars, int charsCount, int type)' 'Generate image font atlas using chars info': 'prefix': 'GenImageFontAtlas()' 'body': 'GenImageFontAtlas($1)' 'description': 'GenImageFontAtlas(const CharInfo chars, Rectangle recs, int charsCount, int fontSize, int padding, int packMethod)' 'Unload Font from GPU memory (VRAM)': 'prefix': 'UnloadFont()' 'body': 'UnloadFont($1)' 'description': 'UnloadFont(Font font)' 'Shows current FPS': 'prefix': 'DrawFPS()' 'body': 'DrawFPS($1)' 'description': 'DrawFPS(int posX, int posY)' 'Draw text (using default font)': 'prefix': 'DrawText()' 'body': 'DrawText($1)' 'description': 'DrawText(const char text, int posX, int posY, int fontSize, Color color)' 'Draw text using font and additional parameters': 'prefix': 'DrawTextEx()' 'body': 'DrawTextEx($1)' 'description': 'DrawTextEx(Font font, const char text, Vector2 position, float fontSize, float spacing, Color tint)' 'Draw text using font inside rectangle limits': 'prefix': 'DrawTextRec()' 'body': 'DrawTextRec($1)' 'description': 'DrawTextRec(Font font, const char text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint)' 'Draw text using font inside rectangle limits with support for text selection': 'prefix': 'DrawTextRecEx()' 'body': 'DrawTextRecEx($1)' 'description': 'DrawTextRecEx(Font font, const char text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, int selectStart, int selectLength, Color selectTint, Color selectBackTint)' 'Draw one character (codepoint)': 'prefix': 'DrawTextCodepoint()' 'body': 'DrawTextCodepoint($1)' 'description': 'DrawTextCodepoint(Font font, int codepoint, Vector2 position, float scale, Color tint)' 'Measure string width for default font': 'prefix': 'MeasureText()' 'body': 'MeasureText($1)' 'description': 'MeasureText(const char text, int fontSize)' 'Measure string size for Font': 'prefix': 'MeasureTextEx()' 'body': 'MeasureTextEx($1)' 'description': 'MeasureTextEx(Font font, const char text, float fontSize, float spacing)' 'Get index position for a unicode character on font': 'prefix': 'GetGlyphIndex()' 'body': 'GetGlyphIndex($1)' 'description': 'GetGlyphIndex(Font font, int codepoint)' 'Copy one string to another, returns bytes copied': 'prefix': 'TextCopy()' 'body': 'TextCopy($1)' 'description': 'TextCopy(char dst, const char src)' 'Check if two text string are equal': 'prefix': 'TextIsEqual()' 'body': 'TextIsEqual($1)' 'description': 'TextIsEqual(const char text1, const char text2)' 'Append text at specific position and move cursor!': 'prefix': 'TextAppend()' 'body': 'TextAppend($1)' 'description': 'TextAppend(char text, const char append, int position)' 'Find first text occurrence within a string': 'prefix': 'TextFindIndex()' 'body': 'TextFindIndex($1)' 'description': 'TextFindIndex(const char text, const char find)' 'Get integer value from text (negative values not supported)': 'prefix': 'TextToInteger()' 'body': 'TextToInteger($1)' 'description': 'TextToInteger(const char text)' 'Get all codepoints in a string, codepoints count returned by parameters': 'prefix': 'GetCodepoints()' 'body': 'GetCodepoints($1)' 'description': 'GetCodepoints(const char text, int count)' 'Get total number of characters (codepoints) in a UTF8 encoded string': 'prefix': 'GetCodepointsCount()' 'body': 'GetCodepointsCount($1)' 'description': 'GetCodepointsCount(const char text)' 'Returns next codepoint in a UTF8 encoded string; 0x3f(\'?\') is returned on failure': 'prefix': 'GetNextCodepoint()' 'body': 'GetNextCodepoint($1)' 'description': 'GetNextCodepoint(const char text, int bytesProcessed)' 'Draw a line in 3D world space': 'prefix': 'DrawLine3D()' 'body': 'DrawLine3D($1)' 'description': 'DrawLine3D(Vector3 startPos, Vector3 endPos, Color color)' 'Draw a point in 3D space, actually a small line': 'prefix': 'DrawPoint3D()' 'body': 'DrawPoint3D($1)' 'description': 'DrawPoint3D(Vector3 position, Color color)' 'Draw a circle in 3D world space': 'prefix': 'DrawCircle3D()' 'body': 'DrawCircle3D($1)' 'description': 'DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color)' 'Draw cube': 'prefix': 'DrawCube()' 'body': 'DrawCube($1)' 'description': 'DrawCube(Vector3 position, float width, float height, float length, Color color)' 'Draw cube (Vector version)': 'prefix': 'DrawCubeV()' 'body': 'DrawCubeV($1)' 'description': 'DrawCubeV(Vector3 position, Vector3 size, Color color)' 'Draw cube wires': 'prefix': 'DrawCubeWires()' 'body': 'DrawCubeWires($1)' 'description': 'DrawCubeWires(Vector3 position, float width, float height, float length, Color color)' 'Draw cube wires (Vector version)': 'prefix': 'DrawCubeWiresV()' 'body': 'DrawCubeWiresV($1)' 'description': 'DrawCubeWiresV(Vector3 position, Vector3 size, Color color)' 'Draw cube textured': 'prefix': 'DrawCubeTexture()' 'body': 'DrawCubeTexture($1)' 'description': 'DrawCubeTexture(Texture2D texture, Vector3 position, float width, float height, float length, Color color)' 'Draw sphere': 'prefix': 'DrawSphere()' 'body': 'DrawSphere($1)' 'description': 'DrawSphere(Vector3 centerPos, float radius, Color color)' 'Draw sphere with extended parameters': 'prefix': 'DrawSphereEx()' 'body': 'DrawSphereEx($1)' 'description': 'DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color)' 'Draw sphere wires': 'prefix': 'DrawSphereWires()' 'body': 'DrawSphereWires($1)' 'description': 'DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color)' 'Draw a cylinder/cone': 'prefix': 'DrawCylinder()' 'body': 'DrawCylinder($1)' 'description': 'DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color)' 'Draw a cylinder/cone wires': 'prefix': 'DrawCylinderWires()' 'body': 'DrawCylinderWires($1)' 'description': 'DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color)' 'Draw a plane XZ': 'prefix': 'DrawPlane()' 'body': 'DrawPlane($1)' 'description': 'DrawPlane(Vector3 centerPos, Vector2 size, Color color)' 'Draw a ray line': 'prefix': 'DrawRay()' 'body': 'DrawRay($1)' 'description': 'DrawRay(Ray ray, Color color)' 'Draw a grid (centered at (0, 0, 0))': 'prefix': 'DrawGrid()' 'body': 'DrawGrid($1)' 'description': 'DrawGrid(int slices, float spacing)' 'Draw simple gizmo': 'prefix': 'DrawGizmo()' 'body': 'DrawGizmo($1)' 'description': 'DrawGizmo(Vector3 position)' 'Load model from files (meshes and materials)': 'prefix': 'LoadModel()' 'body': 'LoadModel($1)' 'description': 'LoadModel(const char fileName)' 'Load model from generated mesh (default material)': 'prefix': 'LoadModelFromMesh()' 'body': 'LoadModelFromMesh($1)' 'description': 'LoadModelFromMesh(Mesh mesh)' 'Unload model from memory (RAM and/or VRAM)': 'prefix': 'UnloadModel()' 'body': 'UnloadModel($1)' 'description': 'UnloadModel(Model model)' 'Load meshes from model file': 'prefix': 'LoadMeshes()' 'body': 'LoadMeshes($1)' 'description': 'LoadMeshes(const char fileName, int meshCount)' 'Export mesh data to file': 'prefix': 'ExportMesh()' 'body': 'ExportMesh($1)' 'description': 'ExportMesh(Mesh mesh, const char fileName)' 'Unload mesh from memory (RAM and/or VRAM)': 'prefix': 'UnloadMesh()' 'body': 'UnloadMesh($1)' 'description': 'UnloadMesh(Mesh mesh)' 'Load materials from model file': 'prefix': 'LoadMaterials()' 'body': 'LoadMaterials($1)' 'description': 'LoadMaterials(const char fileName, int materialCount)' 'Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps)': 'prefix': 'LoadMaterialDefault()' 'body': 'LoadMaterialDefault()' 'description': 'LoadMaterialDefault(void)' 'Unload material from GPU memory (VRAM)': 'prefix': 'UnloadMaterial()' 'body': 'UnloadMaterial($1)' 'description': 'UnloadMaterial(Material material)' 'Set texture for a material map type (MAP_DIFFUSE, MAP_SPECULAR...)': 'prefix': 'SetMaterialTexture()' 'body': 'SetMaterialTexture($1)' 'description': 'SetMaterialTexture(Material material, int mapType, Texture2D texture)' 'Set material for a mesh': 'prefix': 'SetModelMeshMaterial()' 'body': 'SetModelMeshMaterial($1)' 'description': 'SetModelMeshMaterial(Model model, int meshId, int materialId)' 'Load model animations from file': 'prefix': 'LoadModelAnimations()' 'body': 'LoadModelAnimations($1)' 'description': 'LoadModelAnimations(const char fileName, int animsCount)' 'Update model animation pose': 'prefix': 'UpdateModelAnimation()' 'body': 'UpdateModelAnimation($1)' 'description': 'UpdateModelAnimation(Model model, ModelAnimation anim, int frame)' 'Unload animation data': 'prefix': 'UnloadModelAnimation()' 'body': 'UnloadModelAnimation($1)' 'description': 'UnloadModelAnimation(ModelAnimation anim)' 'Check model animation skeleton match': 'prefix': 'IsModelAnimationValid()' 'body': 'IsModelAnimationValid($1)' 'description': 'IsModelAnimationValid(Model model, ModelAnimation anim)' 'Generate polygonal mesh': 'prefix': 'GenMeshPoly()' 'body': 'GenMeshPoly($1)' 'description': 'GenMeshPoly(int sides, float radius)' 'Generate plane mesh (with subdivisions)': 'prefix': 'GenMeshPlane()' 'body': 'GenMeshPlane($1)' 'description': 'GenMeshPlane(float width, float length, int resX, int resZ)' 'Generate cuboid mesh': 'prefix': 'GenMeshCube()' 'body': 'GenMeshCube($1)' 'description': 'GenMeshCube(float width, float height, float length)' 'Generate sphere mesh (standard sphere)': 'prefix': 'GenMeshSphere()' 'body': 'GenMeshSphere($1)' 'description': 'GenMeshSphere(float radius, int rings, int slices)' 'Generate half-sphere mesh (no bottom cap)': 'prefix': 'GenMeshHemiSphere()' 'body': 'GenMeshHemiSphere($1)' 'description': 'GenMeshHemiSphere(float radius, int rings, int slices)' 'Generate cylinder mesh': 'prefix': 'GenMeshCylinder()' 'body': 'GenMeshCylinder($1)' 'description': 'GenMeshCylinder(float radius, float height, int slices)' 'Generate torus mesh': 'prefix': 'GenMeshTorus()' 'body': 'GenMeshTorus($1)' 'description': 'GenMeshTorus(float radius, float size, int radSeg, int sides)' 'Generate trefoil knot mesh': 'prefix': 'GenMeshKnot()' 'body': 'GenMeshKnot($1)' 'description': 'GenMeshKnot(float radius, float size, int radSeg, int sides)' 'Generate heightmap mesh from image data': 'prefix': 'GenMeshHeightmap()' 'body': 'GenMeshHeightmap($1)' 'description': 'GenMeshHeightmap(Image heightmap, Vector3 size)' 'Generate cubes-based map mesh from image data': 'prefix': 'GenMeshCubicmap()' 'body': 'GenMeshCubicmap($1)' 'description': 'GenMeshCubicmap(Image cubicmap, Vector3 cubeSize)' 'Compute mesh bounding box limits': 'prefix': 'MeshBoundingBox()' 'body': 'MeshBoundingBox($1)' 'description': 'MeshBoundingBox(Mesh mesh)' 'Compute mesh tangents': 'prefix': 'MeshTangents()' 'body': 'MeshTangents($1)' 'description': 'MeshTangents(Mesh mesh)' 'Compute mesh binormals': 'prefix': 'MeshBinormals()' 'body': 'MeshBinormals($1)' 'description': 'MeshBinormals(Mesh mesh)' 'Draw a model (with texture if set)': 'prefix': 'DrawModel()' 'body': 'DrawModel($1)' 'description': 'DrawModel(Model model, Vector3 position, float scale, Color tint)' 'Draw a model with extended parameters': 'prefix': 'DrawModelEx()' 'body': 'DrawModelEx($1)' 'description': 'DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint)' 'Draw a model wires (with texture if set)': 'prefix': 'DrawModelWires()' 'body': 'DrawModelWires($1)' 'description': 'DrawModelWires(Model model, Vector3 position, float scale, Color tint)' 'Draw a model wires (with texture if set) with extended parameters': 'prefix': 'DrawModelWiresEx()' 'body': 'DrawModelWiresEx($1)' 'description': 'DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint)' 'Draw bounding box (wires)': 'prefix': 'DrawBoundingBox()' 'body': 'DrawBoundingBox($1)' 'description': 'DrawBoundingBox(BoundingBox box, Color color)' 'Draw a billboard texture': 'prefix': 'DrawBillboard()' 'body': 'DrawBillboard($1)' 'description': 'DrawBillboard(Camera camera, Texture2D texture, Vector3 center, float size, Color tint)' 'Draw a billboard texture defined by sourceRec': 'prefix': 'DrawBillboardRec()' 'body': 'DrawBillboardRec($1)' 'description': 'DrawBillboardRec(Camera camera, Texture2D texture, Rectangle sourceRec, Vector3 center, float size, Color tint)' 'Detect collision between two spheres': 'prefix': 'CheckCollisionSpheres()' 'body': 'CheckCollisionSpheres($1)' 'description': 'CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB)' 'Detect collision between two bounding boxes': 'prefix': 'CheckCollisionBoxes()' 'body': 'CheckCollisionBoxes($1)' 'description': 'CheckCollisionBoxes(BoundingBox box1, BoundingBox box2)' 'Detect collision between box and sphere': 'prefix': 'CheckCollisionBoxSphere()' 'body': 'CheckCollisionBoxSphere($1)' 'description': 'CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius)' 'Detect collision between ray and sphere': 'prefix': 'CheckCollisionRaySphere()' 'body': 'CheckCollisionRaySphere($1)' 'description': 'CheckCollisionRaySphere(Ray ray, Vector3 center, float radius)' 'Detect collision between ray and sphere, returns collision point': 'prefix': 'CheckCollisionRaySphereEx()' 'body': 'CheckCollisionRaySphereEx($1)' 'description': 'CheckCollisionRaySphereEx(Ray ray, Vector3 center, float radius, Vector3 collisionPoint)' 'Detect collision between ray and box': 'prefix': 'CheckCollisionRayBox()' 'body': 'CheckCollisionRayBox($1)' 'description': 'CheckCollisionRayBox(Ray ray, BoundingBox box)' 'Get collision info between ray and model': 'prefix': 'GetCollisionRayModel()' 'body': 'GetCollisionRayModel($1)' 'description': 'GetCollisionRayModel(Ray ray, Model model)' 'Get collision info between ray and triangle': 'prefix': 'GetCollisionRayTriangle()' 'body': 'GetCollisionRayTriangle($1)' 'description': 'GetCollisionRayTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3)' 'Get collision info between ray and ground plane (Y-normal plane)': 'prefix': 'GetCollisionRayGround()' 'body': 'GetCollisionRayGround($1)' 'description': 'GetCollisionRayGround(Ray ray, float groundHeight)' 'Load shader from files and bind default locations': 'prefix': 'LoadShader()' 'body': 'LoadShader($1)' 'description': 'LoadShader(const char vsFileName, const char fsFileName)' 'Load shader from code strings and bind default locations': 'prefix': 'LoadShaderCode()' 'body': 'LoadShaderCode($1)' 'description': 'LoadShaderCode(char vsCode, char fsCode)' 'Unload shader from GPU memory (VRAM)': 'prefix': 'UnloadShader()' 'body': 'UnloadShader($1)' 'description': 'UnloadShader(Shader shader)' 'Get default shader': 'prefix': 'GetShaderDefault()' 'body': 'GetShaderDefault()' 'description': 'GetShaderDefault(void)' 'Get texture rectangle to draw shapes': 'prefix': 'GetShapesTextureRec()' 'body': 'GetShapesTextureRec()' 'description': 'GetShapesTextureRec(void)' 'Define default texture used to draw shapes': 'prefix': 'SetShapesTexture()' 'body': 'SetShapesTexture($1)' 'description': 'SetShapesTexture(Texture2D texture, Rectangle source)' 'Get shader uniform location': 'prefix': 'GetShaderLocation()' 'body': 'GetShaderLocation($1)' 'description': 'GetShaderLocation(Shader shader, const char uniformName)' 'Set shader uniform value': 'prefix': 'SetShaderValue()' 'body': 'SetShaderValue($1)' 'description': 'SetShaderValue(Shader shader, int uniformLoc, const void value, int uniformType)' 'Set shader uniform value vector': 'prefix': 'SetShaderValueV()' 'body': 'SetShaderValueV($1)' 'description': 'SetShaderValueV(Shader shader, int uniformLoc, const void value, int uniformType, int count)' 'Set shader uniform value (matrix 4x4)': 'prefix': 'SetShaderValueMatrix()' 'body': 'SetShaderValueMatrix($1)' 'description': 'SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat)' 'Set shader uniform value for texture': 'prefix': 'SetShaderValueTexture()' 'body': 'SetShaderValueTexture($1)' 'description': 'SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D texture)' 'Set a custom projection matrix (replaces internal projection matrix)': 'prefix': 'SetMatrixProjection()' 'body': 'SetMatrixProjection($1)' 'description': 'SetMatrixProjection(Matrix proj)' 'Set a custom modelview matrix (replaces internal modelview matrix)': 'prefix': 'SetMatrixModelview()' 'body': 'SetMatrixModelview($1)' 'description': 'SetMatrixModelview(Matrix view)' 'Get internal modelview matrix': 'prefix': 'GetMatrixModelview()' 'body': 'GetMatrixModelview($1)' 'description': 'GetMatrixModelview()' 'Get internal projection matrix': 'prefix': 'GetMatrixProjection()' 'body': 'GetMatrixProjection()' 'description': 'GetMatrixProjection(void)' 'Begin custom shader drawing': 'prefix': 'BeginShaderMode()' 'body': 'BeginShaderMode($1)' 'description': 'BeginShaderMode(Shader shader)' 'End custom shader drawing (use default shader)': 'prefix': 'EndShaderMode()' 'body': 'EndShaderMode()' 'description': 'EndShaderMode(void)' 'Begin blending mode (alpha, additive, multiplied)': 'prefix': 'BeginBlendMode()' 'body': 'BeginBlendMode($1)' 'description': 'BeginBlendMode(int mode)' 'End blending mode (reset to default: alpha blending)': 'prefix': 'EndBlendMode()' 'body': 'EndBlendMode()' 'description': 'EndBlendMode(void)' 'Init VR simulator for selected device parameters': 'prefix': 'InitVrSimulator()' 'body': 'InitVrSimulator()' 'description': 'InitVrSimulator(void)' 'Close VR simulator for current device': 'prefix': 'CloseVrSimulator()' 'body': 'CloseVrSimulator()' 'description': 'CloseVrSimulator(void)' 'Update VR tracking (position and orientation) and camera': 'prefix': 'UpdateVrTracking()' 'body': 'UpdateVrTracking($1)' 'description': 'UpdateVrTracking(Camera camera)' 'Set stereo rendering configuration parameters': 'prefix': 'SetVrConfiguration()' 'body': 'SetVrConfiguration($1)' 'description': 'SetVrConfiguration(VrDeviceInfo info, Shader distortion)' 'Detect if VR simulator is ready': 'prefix': 'IsVrSimulatorReady()' 'body': 'IsVrSimulatorReady()' 'description': 'IsVrSimulatorReady(void)' 'Enable/Disable VR experience': 'prefix': 'ToggleVrMode()' 'body': 'ToggleVrMode()' 'description': 'ToggleVrMode(void)' 'Begin VR simulator stereo rendering': 'prefix': 'BeginVrDrawing()' 'body': 'BeginVrDrawing()' 'description': 'BeginVrDrawing(void)' 'End VR simulator stereo rendering': 'prefix': 'EndVrDrawing()' 'body': 'EndVrDrawing()' 'description': 'EndVrDrawing(void)' 'Initialize audio device and context': 'prefix': 'InitAudioDevice()' 'body': 'InitAudioDevice()' 'description': 'InitAudioDevice(void)' 'Close the audio device and context (and music stream)': 'prefix': 'CloseAudioDevice()' 'body': 'CloseAudioDevice()' 'description': 'CloseAudioDevice(void)' 'Check if audio device is ready': 'prefix': 'IsAudioDeviceReady()' 'body': 'IsAudioDeviceReady()' 'description': 'IsAudioDeviceReady(void)' 'Set master volume (listener)': 'prefix': 'SetMasterVolume()' 'body': 'SetMasterVolume($1)' 'description': 'SetMasterVolume(float volume)' 'Load wave data from file': 'prefix': 'LoadWave()' 'body': 'LoadWave($1)' 'description': 'LoadWave(const char fileName)' 'Load wave data from raw array data': 'prefix': 'LoadWaveEx()' 'body': 'LoadWaveEx($1)' 'description': 'LoadWaveEx(void data, int sampleCount, int sampleRate, int sampleSize, int channels)' 'Load sound from file': 'prefix': 'LoadSound()' 'body': 'LoadSound($1)' 'description': 'LoadSound(const char fileName)' 'Load sound from wave data': 'prefix': 'LoadSoundFromWave()' 'body': 'LoadSoundFromWave($1)' 'description': 'LoadSoundFromWave(Wave wave)' 'Update sound buffer with new data': 'prefix': 'UpdateSound()' 'body': 'UpdateSound($1)' 'description': 'UpdateSound(Sound sound, const void data, int samplesCount)' 'Unload wave data': 'prefix': 'UnloadWave()' 'body': 'UnloadWave($1)' 'description': 'UnloadWave(Wave wave)' 'Unload sound': 'prefix': 'UnloadSound()' 'body': 'UnloadSound($1)' 'description': 'UnloadSound(Sound sound)' 'Export wave data to file': 'prefix': 'ExportWave()' 'body': 'ExportWave($1)' 'description': 'ExportWave(Wave wave, const char fileName)' 'Export wave sample data to code (.h)': 'prefix': 'ExportWaveAsCode()' 'body': 'ExportWaveAsCode($1)' 'description': 'ExportWaveAsCode(Wave wave, const char fileName)' 'Play a sound': 'prefix': 'PlaySound()' 'body': 'PlaySound($1)' 'description': 'PlaySound(Sound sound)' 'Stop playing a sound': 'prefix': 'StopSound()' 'body': 'StopSound($1)' 'description': 'StopSound(Sound sound)' 'Pause a sound': 'prefix': 'PauseSound()' 'body': 'PauseSound($1)' 'description': 'PauseSound(Sound sound)' 'Resume a paused sound': 'prefix': 'ResumeSound()' 'body': 'ResumeSound($1)' 'description': 'ResumeSound(Sound sound)' 'Play a sound (using multichannel buffer pool)': 'prefix': 'PlaySoundMulti()' 'body': 'PlaySoundMulti($1)' 'description': 'PlaySoundMulti(Sound sound)' 'Stop any sound playing (using multichannel buffer pool)': 'prefix': 'StopSoundMulti()' 'body': 'StopSoundMulti()' 'description': 'StopSoundMulti(void)' 'Get number of sounds playing in the multichannel': 'prefix': 'GetSoundsPlaying()' 'body': 'GetSoundsPlaying()' 'description': 'GetSoundsPlaying(void)' 'Check if a sound is currently playing': 'prefix': 'IsSoundPlaying()' 'body': 'IsSoundPlaying($1)' 'description': 'IsSoundPlaying(Sound sound)' 'Set volume for a sound (1.0 is max level)': 'prefix': 'SetSoundVolume()' 'body': 'SetSoundVolume($1)' 'description': 'SetSoundVolume(Sound sound, float volume)' 'Set pitch for a sound (1.0 is base level)': 'prefix': 'SetSoundPitch()' 'body': 'SetSoundPitch($1)' 'description': 'SetSoundPitch(Sound sound, float pitch)' 'Convert wave data to desired format': 'prefix': 'WaveFormat()' 'body': 'WaveFormat($1)' 'description': 'WaveFormat(Wave wave, int sampleRate, int sampleSize, int channels)' 'Copy a wave to a new wave': 'prefix': 'WaveCopy()' 'body': 'WaveCopy($1)' 'description': 'WaveCopy(Wave wave)' 'Crop a wave to defined samples range': 'prefix': 'WaveCrop()' 'body': 'WaveCrop($1)' 'description': 'WaveCrop(Wave wave, int initSample, int finalSample)' 'Get samples data from wave as a floats array': 'prefix': 'GetWaveData()' 'body': 'GetWaveData($1)' 'description': 'GetWaveData(Wave wave)' 'Load music stream from file': 'prefix': 'LoadMusicStream()' 'body': 'LoadMusicStream($1)' 'description': 'LoadMusicStream(const char fileName)' 'Unload music stream': 'prefix': 'UnloadMusicStream()' 'body': 'UnloadMusicStream($1)' 'description': 'UnloadMusicStream(Music music)' 'Start music playing': 'prefix': 'PlayMusicStream()' 'body': 'PlayMusicStream($1)' 'description': 'PlayMusicStream(Music music)' 'Updates buffers for music streaming': 'prefix': 'UpdateMusicStream()' 'body': 'UpdateMusicStream($1)' 'description': 'UpdateMusicStream(Music music)' 'Stop music playing': 'prefix': 'StopMusicStream()' 'body': 'StopMusicStream($1)' 'description': 'StopMusicStream(Music music)' 'Pause music playing': 'prefix': 'PauseMusicStream()' 'body': 'PauseMusicStream($1)' 'description': 'PauseMusicStream(Music music)' 'Resume playing paused music': 'prefix': 'ResumeMusicStream()' 'body': 'ResumeMusicStream($1)' 'description': 'ResumeMusicStream(Music music)' 'Check if music is playing': 'prefix': 'IsMusicPlaying()' 'body': 'IsMusicPlaying($1)' 'description': 'IsMusicPlaying(Music music)' 'Set volume for music (1.0 is max level)': 'prefix': 'SetMusicVolume()' 'body': 'SetMusicVolume($1)' 'description': 'SetMusicVolume(Music music, float volume)' 'Set pitch for a music (1.0 is base level)': 'prefix': 'SetMusicPitch()' 'body': 'SetMusicPitch($1)' 'description': 'SetMusicPitch(Music music, float pitch)' 'Set music loop count (loop repeats)': 'prefix': 'SetMusicLoopCount()' 'body': 'SetMusicLoopCount($1)' 'description': 'SetMusicLoopCount(Music music, int count)' 'Get music time length (in seconds)': 'prefix': 'GetMusicTimeLength()' 'body': 'GetMusicTimeLength($1)' 'description': 'GetMusicTimeLength(Music music)' 'Get current music time played (in seconds)': 'prefix': 'GetMusicTimePlayed()' 'body': 'GetMusicTimePlayed($1)' 'description': 'GetMusicTimePlayed(Music music)' 'Init audio stream (to stream raw audio pcm data)': 'prefix': 'InitAudioStream()' 'body': 'InitAudioStream($1)' 'description': 'InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels)' 'Update audio stream buffers with data': 'prefix': 'UpdateAudioStream()' 'body': 'UpdateAudioStream($1)' 'description': 'UpdateAudioStream(AudioStream stream, const void data, int samplesCount)' 'Close audio stream and free memory': 'prefix': 'CloseAudioStream()' 'body': 'CloseAudioStream($1)' 'description': 'CloseAudioStream(AudioStream stream)' 'Check if any audio stream buffers requires refill': 'prefix': 'IsAudioBufferProcessed()' 'body': 'IsAudioBufferProcessed($1)' 'description': 'IsAudioBufferProcessed(AudioStream stream)' 'Play audio stream': 'prefix': 'PlayAudioStream()' 'body': 'PlayAudioStream($1)' 'description': 'PlayAudioStream(AudioStream stream)' 'Pause audio stream': 'prefix': 'PauseAudioStream()' 'body': 'PauseAudioStream($1)' 'description': 'PauseAudioStream(AudioStream stream)' 'Resume audio stream': 'prefix': 'ResumeAudioStream()' 'body': 'ResumeAudioStream($1)' 'description': 'ResumeAudioStream(AudioStream stream)' 'Check if audio stream is playing': 'prefix': 'IsAudioStreamPlaying()' 'body': 'IsAudioStreamPlaying($1)' 'description': 'IsAudioStreamPlaying(AudioStream stream)' 'Stop audio stream': 'prefix': 'StopAudioStream()' 'body': 'StopAudioStream($1)' 'description': 'StopAudioStream(AudioStream stream)' 'Set volume for audio stream (1.0 is max level)': 'prefix': 'SetAudioStreamVolume()' 'body': 'SetAudioStreamVolume($1)' 'description': 'SetAudioStreamVolume(AudioStream stream, float volume)' 'Set pitch for audio stream (1.0 is base level)': 'prefix': 'SetAudioStreamPitch()' 'body': 'SetAudioStreamPitch($1)' 'description': 'SetAudioStreamPitch(AudioStream stream, float pitch)'
[ { "context": "arter :\n repository : 'https://github.com/paulovitorwd/ionic-starter'\n name : 'ionic-start", "end": 78, "score": 0.8254033327102661, "start": 66, "tag": "USERNAME", "value": "paulovitorwd" }, { "context": "nicframework.ionicstarter'\n author : 'Paulo Campos'\n email : 'paulovitorwd@gmail.com'\n ", "end": 342, "score": 0.9998646974563599, "start": 330, "tag": "NAME", "value": "Paulo Campos" }, { "context": "thor : 'Paulo Campos'\n email : 'paulovitorwd@gmail.com'\n new :\n repository : '' # {string} En", "end": 389, "score": 0.9999098181724548, "start": 367, "tag": "EMAIL", "value": "paulovitorwd@gmail.com" } ]
gulp/settings/project.coffee
plastic/ionic-starter
0
project = starter : repository : 'https://github.com/paulovitorwd/ionic-starter' name : 'ionic-starter' description : 'This project aims to streamline starting an application in Ionic' version : '1.0.0' id : 'com.ionicframework.ionicstarter' author : 'Paulo Campos' email : 'paulovitorwd@gmail.com' new : repository : '' # {string} Enter with the repository of project name : '' # {string} Enter with the name of project description : '' # {string} Enter with the description of project version : '' # {string} Enter with the version of project id : '' # {string} Enter with the id of project author : '' # {string} Enter with the name of author email : '' # {string} Enter with the email of author exports.project = project
107711
project = starter : repository : 'https://github.com/paulovitorwd/ionic-starter' name : 'ionic-starter' description : 'This project aims to streamline starting an application in Ionic' version : '1.0.0' id : 'com.ionicframework.ionicstarter' author : '<NAME>' email : '<EMAIL>' new : repository : '' # {string} Enter with the repository of project name : '' # {string} Enter with the name of project description : '' # {string} Enter with the description of project version : '' # {string} Enter with the version of project id : '' # {string} Enter with the id of project author : '' # {string} Enter with the name of author email : '' # {string} Enter with the email of author exports.project = project
true
project = starter : repository : 'https://github.com/paulovitorwd/ionic-starter' name : 'ionic-starter' description : 'This project aims to streamline starting an application in Ionic' version : '1.0.0' id : 'com.ionicframework.ionicstarter' author : 'PI:NAME:<NAME>END_PI' email : 'PI:EMAIL:<EMAIL>END_PI' new : repository : '' # {string} Enter with the repository of project name : '' # {string} Enter with the name of project description : '' # {string} Enter with the description of project version : '' # {string} Enter with the version of project id : '' # {string} Enter with the id of project author : '' # {string} Enter with the name of author email : '' # {string} Enter with the email of author exports.project = project
[ { "context": "#\n# foundation-strength.js\n# Author: Alexander Egorov\n# Original author: Aaron Lumsden\n# Licensed under", "end": 53, "score": 0.9998679161071777, "start": 37, "tag": "NAME", "value": "Alexander Egorov" }, { "context": "h.js\n# Author: Alexander Egorov\n# Original author: Aaron Lumsden\n# Licensed under the MIT license\n#\n\ndo ($) ->\n d", "end": 86, "score": 0.9998118281364441, "start": 73, "tag": "NAME", "value": "Aaron Lumsden" } ]
src/foundation-strength.coffee
qatsi/foundation-strength.js
6
# # foundation-strength.js # Author: Alexander Egorov # Original author: Aaron Lumsden # Licensed under the MIT license # do ($) -> defaults = show_meter: true meterClasses: 'radius' show_messages: true classes: nopassword: 'nopassword' weak: 'password-weak' moderate: 'password-moderate' strong: 'password-strong' FoundationStrength = (form, options) -> @$form = $(form) @options = $.extend({}, defaults, options) @init() FoundationStrength.prototype = init: -> options = @options $appendee = undefined $form = @$form # Apped to which element $pass = $form.find('input[type=password]').first() # Whole form # 'Good passwords start to score around 60 scores' # http://stackoverflow.com/questions/948172/password-strength-meter get_password_score = (p) -> score = 0 if !p return score # Award every unique letter until 5 repetitions letters = new Object i = 0 while i < p.length letters[p[i]] = (letters[p[i]] or 0) + 1 score += 5.0 / letters[p[i]] i++ # Bonus points for mixing it up variations = digits: /\d/.test(p) lower: /[a-z]/.test(p) upper: /[A-Z]/.test(p) nonWords: /\W/.test(p) variationCount = 0 for check of variations variationCount += if variations[check] == true then 1 else 0 score += (variationCount - 1) * 10 parseInt score get_password_strength = (score) -> if score > 60 return 'strong' if score > 40 return 'moderate' 'weak' if @$form.prop('localName') != 'form' # Check if we work with form element console.error 'Foundation strength element should be \'form\'.' if $pass.parent().prop('localName') == 'label' # Check input's parent $appendee = $pass.parent() # append after label else $appendee = $pass # Meter if options.show_meter == true $appendee.after '<div class=\'strength-meter progress ' + options.meterClasses + '\'>' + '<span class=\'meter\'></span></div>' $meter = @$form.find('.strength-meter .meter') # Update function update = (l, s, p) -> # length, strength, points if l == 0 # don't have any password class_to_add = options.classes.nopassword else class_to_add = options.classes[s] classes_all = [] $.each options.classes, (k, v) -> classes_all.push v classes_to_remove = $.grep(classes_all, (c) -> c != class_to_add ) $form.addClass(class_to_add).removeClass classes_to_remove.join(' ') meter_width = if p < 100 then p else 100 $meter.width meter_width + '%' update_caps = (c) -> is_on = 'caps-on' is_off = 'caps-off' if c $form.addClass(is_on).removeClass(is_off) else $form.addClass(is_off).removeClass(is_on) update 0, 'weak', 0 update_caps false $inputs = $form.find('[type=text],[type=email],[type=password],:text') $inputs.each (event) -> $(this).bind 'keypress', (event) -> s = String.fromCharCode(event.which) # TODO: Bulletprof regexp for char if s.match(/[A-Za-zะ-ะฏะฐ-ั]/) if s.toUpperCase() == s and s.toLowerCase() != s and !event.shiftKey update_caps true else update_caps false $pass.bind 'keypress keyup change', (event) -> password = $(this).val() score = get_password_score(password) strength = get_password_strength(score) # console.log('Score ' + score + ' it\'s ' + strength + '!'); # console.log('Password value: ' + password); update password.length, strength, score # window.wtf = this; $.fn.extend strength: (options) -> # Wrapper around the constructor preventins multiple instantiations @each -> if !$.data(this, 'FoundationStrength') $.data this, 'FoundationStrength', new FoundationStrength(this, options)
23008
# # foundation-strength.js # Author: <NAME> # Original author: <NAME> # Licensed under the MIT license # do ($) -> defaults = show_meter: true meterClasses: 'radius' show_messages: true classes: nopassword: 'nopassword' weak: 'password-weak' moderate: 'password-moderate' strong: 'password-strong' FoundationStrength = (form, options) -> @$form = $(form) @options = $.extend({}, defaults, options) @init() FoundationStrength.prototype = init: -> options = @options $appendee = undefined $form = @$form # Apped to which element $pass = $form.find('input[type=password]').first() # Whole form # 'Good passwords start to score around 60 scores' # http://stackoverflow.com/questions/948172/password-strength-meter get_password_score = (p) -> score = 0 if !p return score # Award every unique letter until 5 repetitions letters = new Object i = 0 while i < p.length letters[p[i]] = (letters[p[i]] or 0) + 1 score += 5.0 / letters[p[i]] i++ # Bonus points for mixing it up variations = digits: /\d/.test(p) lower: /[a-z]/.test(p) upper: /[A-Z]/.test(p) nonWords: /\W/.test(p) variationCount = 0 for check of variations variationCount += if variations[check] == true then 1 else 0 score += (variationCount - 1) * 10 parseInt score get_password_strength = (score) -> if score > 60 return 'strong' if score > 40 return 'moderate' 'weak' if @$form.prop('localName') != 'form' # Check if we work with form element console.error 'Foundation strength element should be \'form\'.' if $pass.parent().prop('localName') == 'label' # Check input's parent $appendee = $pass.parent() # append after label else $appendee = $pass # Meter if options.show_meter == true $appendee.after '<div class=\'strength-meter progress ' + options.meterClasses + '\'>' + '<span class=\'meter\'></span></div>' $meter = @$form.find('.strength-meter .meter') # Update function update = (l, s, p) -> # length, strength, points if l == 0 # don't have any password class_to_add = options.classes.nopassword else class_to_add = options.classes[s] classes_all = [] $.each options.classes, (k, v) -> classes_all.push v classes_to_remove = $.grep(classes_all, (c) -> c != class_to_add ) $form.addClass(class_to_add).removeClass classes_to_remove.join(' ') meter_width = if p < 100 then p else 100 $meter.width meter_width + '%' update_caps = (c) -> is_on = 'caps-on' is_off = 'caps-off' if c $form.addClass(is_on).removeClass(is_off) else $form.addClass(is_off).removeClass(is_on) update 0, 'weak', 0 update_caps false $inputs = $form.find('[type=text],[type=email],[type=password],:text') $inputs.each (event) -> $(this).bind 'keypress', (event) -> s = String.fromCharCode(event.which) # TODO: Bulletprof regexp for char if s.match(/[A-Za-zะ-ะฏะฐ-ั]/) if s.toUpperCase() == s and s.toLowerCase() != s and !event.shiftKey update_caps true else update_caps false $pass.bind 'keypress keyup change', (event) -> password = $(this).val() score = get_password_score(password) strength = get_password_strength(score) # console.log('Score ' + score + ' it\'s ' + strength + '!'); # console.log('Password value: ' + password); update password.length, strength, score # window.wtf = this; $.fn.extend strength: (options) -> # Wrapper around the constructor preventins multiple instantiations @each -> if !$.data(this, 'FoundationStrength') $.data this, 'FoundationStrength', new FoundationStrength(this, options)
true
# # foundation-strength.js # Author: PI:NAME:<NAME>END_PI # Original author: PI:NAME:<NAME>END_PI # Licensed under the MIT license # do ($) -> defaults = show_meter: true meterClasses: 'radius' show_messages: true classes: nopassword: 'nopassword' weak: 'password-weak' moderate: 'password-moderate' strong: 'password-strong' FoundationStrength = (form, options) -> @$form = $(form) @options = $.extend({}, defaults, options) @init() FoundationStrength.prototype = init: -> options = @options $appendee = undefined $form = @$form # Apped to which element $pass = $form.find('input[type=password]').first() # Whole form # 'Good passwords start to score around 60 scores' # http://stackoverflow.com/questions/948172/password-strength-meter get_password_score = (p) -> score = 0 if !p return score # Award every unique letter until 5 repetitions letters = new Object i = 0 while i < p.length letters[p[i]] = (letters[p[i]] or 0) + 1 score += 5.0 / letters[p[i]] i++ # Bonus points for mixing it up variations = digits: /\d/.test(p) lower: /[a-z]/.test(p) upper: /[A-Z]/.test(p) nonWords: /\W/.test(p) variationCount = 0 for check of variations variationCount += if variations[check] == true then 1 else 0 score += (variationCount - 1) * 10 parseInt score get_password_strength = (score) -> if score > 60 return 'strong' if score > 40 return 'moderate' 'weak' if @$form.prop('localName') != 'form' # Check if we work with form element console.error 'Foundation strength element should be \'form\'.' if $pass.parent().prop('localName') == 'label' # Check input's parent $appendee = $pass.parent() # append after label else $appendee = $pass # Meter if options.show_meter == true $appendee.after '<div class=\'strength-meter progress ' + options.meterClasses + '\'>' + '<span class=\'meter\'></span></div>' $meter = @$form.find('.strength-meter .meter') # Update function update = (l, s, p) -> # length, strength, points if l == 0 # don't have any password class_to_add = options.classes.nopassword else class_to_add = options.classes[s] classes_all = [] $.each options.classes, (k, v) -> classes_all.push v classes_to_remove = $.grep(classes_all, (c) -> c != class_to_add ) $form.addClass(class_to_add).removeClass classes_to_remove.join(' ') meter_width = if p < 100 then p else 100 $meter.width meter_width + '%' update_caps = (c) -> is_on = 'caps-on' is_off = 'caps-off' if c $form.addClass(is_on).removeClass(is_off) else $form.addClass(is_off).removeClass(is_on) update 0, 'weak', 0 update_caps false $inputs = $form.find('[type=text],[type=email],[type=password],:text') $inputs.each (event) -> $(this).bind 'keypress', (event) -> s = String.fromCharCode(event.which) # TODO: Bulletprof regexp for char if s.match(/[A-Za-zะ-ะฏะฐ-ั]/) if s.toUpperCase() == s and s.toLowerCase() != s and !event.shiftKey update_caps true else update_caps false $pass.bind 'keypress keyup change', (event) -> password = $(this).val() score = get_password_score(password) strength = get_password_strength(score) # console.log('Score ' + score + ' it\'s ' + strength + '!'); # console.log('Password value: ' + password); update password.length, strength, score # window.wtf = this; $.fn.extend strength: (options) -> # Wrapper around the constructor preventins multiple instantiations @each -> if !$.data(this, 'FoundationStrength') $.data this, 'FoundationStrength', new FoundationStrength(this, options)
[ { "context": " address_components: [\n long_name: \"East Harlem\"\n short_name: \"East Harlem\"\n ", "end": 3331, "score": 0.8037349581718445, "start": 3320, "tag": "NAME", "value": "East Harlem" }, { "context": "ng_name: \"East Harlem\"\n short_name: \"East Harlem\"\n types: [\"neighborhood\", \"political", "end": 3371, "score": 0.9992710947990417, "start": 3360, "tag": "NAME", "value": "East Harlem" }, { "context": "b() }\n Listings.geocode { location: { name: 'foobar' } }, (err, listing) ->\n listing.location.", "end": 3834, "score": 0.740341067314148, "start": 3828, "tag": "NAME", "value": "foobar" }, { "context": " listing.location.neighborhood.should.equal 'East Harlem'\n done()\n Listings.gm.geocode.args[0]", "end": 4152, "score": 0.8000780940055847, "start": 4141, "tag": "NAME", "value": "East Harlem" }, { "context": " address_components: [\n long_name: \"East Harlem\"\n short_name: \"East Harlem\"\n ", "end": 4361, "score": 0.9989760518074036, "start": 4350, "tag": "NAME", "value": "East Harlem" }, { "context": "ng_name: \"East Harlem\"\n short_name: \"East Harlem\"\n types: [\"neighborhood\", \"political", "end": 4401, "score": 0.9992491602897644, "start": 4390, "tag": "NAME", "value": "East Harlem" }, { "context": "TS' }\n Listings.geocode { location: { name: 'foobar' } }, (err, listing) ->\n (err?).should.be.", "end": 4884, "score": 0.7653734087944031, "start": 4878, "tag": "NAME", "value": "foobar" }, { "context": "b() }\n Listings.geocode { location: { name: 'foobar' } }, (err, listing) ->\n listing.location.", "end": 5114, "score": 0.8839645981788635, "start": 5108, "tag": "NAME", "value": "foobar" }, { "context": "address_components: [\n long_name: \"East Harlem\"\n short_name: \"East Harlem\"\n ", "end": 5523, "score": 0.957505464553833, "start": 5512, "tag": "NAME", "value": "East Harlem" }, { "context": "_name: \"East Harlem\"\n short_name: \"East Harlem\"\n types: [\"neighborhood\", \"politic", "end": 5565, "score": 0.9863206744194031, "start": 5554, "tag": "NAME", "value": "East Harlem" }, { "context": "ollection.distinct.callsArgWith 1, null, ['UES', 'Clinton Hill']\n Listings.findNeighborhoods (err, groups) ", "end": 6986, "score": 0.99927818775177, "start": 6974, "tag": "NAME", "value": "Clinton Hill" }, { "context": " groups['South Brooklyn'][0].should.equal 'Clinton Hill'\n groups['Uptown'][0].should.equal 'UES'\n ", "end": 7101, "score": 0.9950450658798218, "start": 7089, "tag": "NAME", "value": "Clinton Hill" } ]
test/dal/listings.coffee
craigspaeth/nfd-api
0
Listings = require '../../dal/listings' sinon = require 'sinon' collectionStub = require '../helpers/collection-stub' _ = require 'underscore' describe 'listings', -> beforeEach -> Listings.collection = collectionStub() describe "#find", -> it 'limits by beds', -> Listings.find('bed-min': 2) Listings.collection.find.args[0][0].beds["$gte"].should.equal 2 it 'limits by baths', -> Listings.find('bath-min': 2) Listings.collection.find.args[0][0].baths["$gte"].should.equal 2 it 'limits by rent', -> Listings.find('rent-max': 2000) Listings.collection.find.args[0][0].rent["$lte"].should.equal 2000 it 'limits by size', -> Listings.find(size: 10, page: 1) Listings.collection.limit.args[0][0].should.equal 10 it 'accepts page params', -> Listings.find(size: 10, page: 1) Listings.collection.skip.args[0][0].should.equal 10 it 'filters by neighborhoods', -> Listings.find(neighborhoods: ['bar', 'foo']) _.isEqual( Listings.collection.find.args[0][0]['location.neighborhood'] { $in: ['bar', 'foo'] } ).should.be.ok it 'sorts by rent', -> Listings.find(sort: 'rent') Listings.collection.sort.args[0][0].rent.should.equal 1 it 'sorts by size', -> Listings.find(sort: 'size') Listings.collection.sort.args[0][0].beds.should.equal -1 Listings.collection.sort.args[0][0].baths.should.equal -1 it 'sorts by newest listings', -> Listings.find(sort: 'newest') Listings.collection.sort.args[0][0].dateScraped.should.equal -1 it 'can pull the latest listings', -> Listings.find 'date-scraped-start': new Date() Listings.collection.find.args[0][0].dateScraped.$gte.toString() .should.equal new Date().toString() describe '#count', -> it 'counts listings by params', -> Listings.count('bed-min': 2) Listings.collection.count.args[0][0].beds["$gte"].should.equal 2 describe '#upsert', -> it 'upserts restricting to urls', -> Listings.upsert [{ url: 'foo', foo: 'foo' }, { url: 'bar', bar: 'foo' }] Listings.collection.update.args[0][0].url.should.equal 'foo' Listings.collection.update.args[1][0].url.should.equal 'bar' it 'upserts each document', -> Listings.upsert [{ url: 'foo', foo: 'foo' }, { url: 'bar', bar: 'foo' }] Listings.collection.update.calledTwice.should.be.ok it 'updates the passed info', -> Listings.upsert [{ url: 'foo', foo: 'foo' }, { url: 'bar', bar: 'bar' }] Listings.collection.update.args[0][1].foo.should.equal 'foo' Listings.collection.update.args[1][1].bar.should.equal 'bar' describe '#geocode', -> beforeEach -> Listings.collection.update.callsArgWith 3, null it 'stores dateGeocoded', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.geocode { location: { name: 'foobar' } }, (err, listing) -> listing.dateGeocoded.toString().should.containEql new Date().getFullYear() done() Listings.gm.geocode.args[0][0].should.equal 'foobar' Listings.gm.geocode.args[0][1] null, results: [ address_components: [ long_name: "East Harlem" short_name: "East Harlem" types: ["neighborhood", "political"] ] formatted_address: "245 East 124th Street, New York, NY 10035, USA" geometry: location: lat: 40.802391 lng: -73.934573 ] it 'fetches the geocode data from google maps and injects it into the listing', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.geocode { location: { name: 'foobar' } }, (err, listing) -> listing.location.formattedAddress.should.equal( '245 East 124th Street, New York, NY 10035, USA' ) listing.location.lng.should.equal -73.934573 listing.location.lat.should.equal 40.802391 listing.location.neighborhood.should.equal 'East Harlem' done() Listings.gm.geocode.args[0][0].should.equal 'foobar' Listings.gm.geocode.args[0][1] null, results: [ address_components: [ long_name: "East Harlem" short_name: "East Harlem" types: ["neighborhood", "political"] ] formatted_address: "245 East 124th Street, New York, NY 10035, USA" geometry: location: lat: 40.802391 lng: -73.934573 ] it 'errs if there are no results', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.gm.geocode.callsArgWith 1, { status: 'ZERO RESULTS' } Listings.geocode { location: { name: 'foobar' } }, (err, listing) -> (err?).should.be.ok done() it 'does not geocode non-new york cities', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.geocode { location: { name: 'foobar' } }, (err, listing) -> listing.location.formattedAddress.should.equal 'Kewl York, New York, NY' done() Listings.gm.geocode.args[0][1] null, results: [ { address_components: [] formatted_address: "245 East 124th Street, Cincinnati OH" } { address_components: [ long_name: "East Harlem" short_name: "East Harlem" types: ["neighborhood", "political"] ] formatted_address: "Kewl York, New York, NY" geometry: location: lat: 40.802391 lng: -73.934573 } { address_components: [] formatted_address: "245 East 124th Street, Cincinnati OH" } ] describe '#findNeighborhoods', -> it 'distincts the neighborhoods and returns the results', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['foo', 'bar'] Listings.findNeighborhoods (err, groups) -> groups['Other'][0].should.equal 'bar' groups['Other'][1].should.equal 'foo' done() it 'ignores null neighborhoods', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['foo', 'bar', null] Listings.findNeighborhoods (err, groups) -> groups['Other'].length.should.equal 2 done() it 'sorts alphabetically', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['a', 'd', 'c', 'b'] Listings.findNeighborhoods (err, groups) -> groups['Other'].join('').should.equal 'abcd' done() it 'groups neighborhoods into their proper larger groups', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['UES', 'Clinton Hill'] Listings.findNeighborhoods (err, groups) -> groups['South Brooklyn'][0].should.equal 'Clinton Hill' groups['Uptown'][0].should.equal 'UES' done() describe '#countBad', -> it 'counts the number of bad listings', (done) -> Listings.countBad (err, badCount, total) -> badCount.should.equal 50 total.should.equal 100 done() Listings.collection.count.args[0][0] null, 100 Listings.collection.count.args[1][1] null, 50 describe '#badDataHash', -> it 'scans the database and maps it into a hash of bad data easy to parse' it 'splits the scraper name by a dash so it handles the nytimes-newyork scrapers'
44065
Listings = require '../../dal/listings' sinon = require 'sinon' collectionStub = require '../helpers/collection-stub' _ = require 'underscore' describe 'listings', -> beforeEach -> Listings.collection = collectionStub() describe "#find", -> it 'limits by beds', -> Listings.find('bed-min': 2) Listings.collection.find.args[0][0].beds["$gte"].should.equal 2 it 'limits by baths', -> Listings.find('bath-min': 2) Listings.collection.find.args[0][0].baths["$gte"].should.equal 2 it 'limits by rent', -> Listings.find('rent-max': 2000) Listings.collection.find.args[0][0].rent["$lte"].should.equal 2000 it 'limits by size', -> Listings.find(size: 10, page: 1) Listings.collection.limit.args[0][0].should.equal 10 it 'accepts page params', -> Listings.find(size: 10, page: 1) Listings.collection.skip.args[0][0].should.equal 10 it 'filters by neighborhoods', -> Listings.find(neighborhoods: ['bar', 'foo']) _.isEqual( Listings.collection.find.args[0][0]['location.neighborhood'] { $in: ['bar', 'foo'] } ).should.be.ok it 'sorts by rent', -> Listings.find(sort: 'rent') Listings.collection.sort.args[0][0].rent.should.equal 1 it 'sorts by size', -> Listings.find(sort: 'size') Listings.collection.sort.args[0][0].beds.should.equal -1 Listings.collection.sort.args[0][0].baths.should.equal -1 it 'sorts by newest listings', -> Listings.find(sort: 'newest') Listings.collection.sort.args[0][0].dateScraped.should.equal -1 it 'can pull the latest listings', -> Listings.find 'date-scraped-start': new Date() Listings.collection.find.args[0][0].dateScraped.$gte.toString() .should.equal new Date().toString() describe '#count', -> it 'counts listings by params', -> Listings.count('bed-min': 2) Listings.collection.count.args[0][0].beds["$gte"].should.equal 2 describe '#upsert', -> it 'upserts restricting to urls', -> Listings.upsert [{ url: 'foo', foo: 'foo' }, { url: 'bar', bar: 'foo' }] Listings.collection.update.args[0][0].url.should.equal 'foo' Listings.collection.update.args[1][0].url.should.equal 'bar' it 'upserts each document', -> Listings.upsert [{ url: 'foo', foo: 'foo' }, { url: 'bar', bar: 'foo' }] Listings.collection.update.calledTwice.should.be.ok it 'updates the passed info', -> Listings.upsert [{ url: 'foo', foo: 'foo' }, { url: 'bar', bar: 'bar' }] Listings.collection.update.args[0][1].foo.should.equal 'foo' Listings.collection.update.args[1][1].bar.should.equal 'bar' describe '#geocode', -> beforeEach -> Listings.collection.update.callsArgWith 3, null it 'stores dateGeocoded', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.geocode { location: { name: 'foobar' } }, (err, listing) -> listing.dateGeocoded.toString().should.containEql new Date().getFullYear() done() Listings.gm.geocode.args[0][0].should.equal 'foobar' Listings.gm.geocode.args[0][1] null, results: [ address_components: [ long_name: "<NAME>" short_name: "<NAME>" types: ["neighborhood", "political"] ] formatted_address: "245 East 124th Street, New York, NY 10035, USA" geometry: location: lat: 40.802391 lng: -73.934573 ] it 'fetches the geocode data from google maps and injects it into the listing', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.geocode { location: { name: '<NAME>' } }, (err, listing) -> listing.location.formattedAddress.should.equal( '245 East 124th Street, New York, NY 10035, USA' ) listing.location.lng.should.equal -73.934573 listing.location.lat.should.equal 40.802391 listing.location.neighborhood.should.equal '<NAME>' done() Listings.gm.geocode.args[0][0].should.equal 'foobar' Listings.gm.geocode.args[0][1] null, results: [ address_components: [ long_name: "<NAME>" short_name: "<NAME>" types: ["neighborhood", "political"] ] formatted_address: "245 East 124th Street, New York, NY 10035, USA" geometry: location: lat: 40.802391 lng: -73.934573 ] it 'errs if there are no results', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.gm.geocode.callsArgWith 1, { status: 'ZERO RESULTS' } Listings.geocode { location: { name: '<NAME>' } }, (err, listing) -> (err?).should.be.ok done() it 'does not geocode non-new york cities', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.geocode { location: { name: '<NAME>' } }, (err, listing) -> listing.location.formattedAddress.should.equal 'Kewl York, New York, NY' done() Listings.gm.geocode.args[0][1] null, results: [ { address_components: [] formatted_address: "245 East 124th Street, Cincinnati OH" } { address_components: [ long_name: "<NAME>" short_name: "<NAME>" types: ["neighborhood", "political"] ] formatted_address: "Kewl York, New York, NY" geometry: location: lat: 40.802391 lng: -73.934573 } { address_components: [] formatted_address: "245 East 124th Street, Cincinnati OH" } ] describe '#findNeighborhoods', -> it 'distincts the neighborhoods and returns the results', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['foo', 'bar'] Listings.findNeighborhoods (err, groups) -> groups['Other'][0].should.equal 'bar' groups['Other'][1].should.equal 'foo' done() it 'ignores null neighborhoods', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['foo', 'bar', null] Listings.findNeighborhoods (err, groups) -> groups['Other'].length.should.equal 2 done() it 'sorts alphabetically', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['a', 'd', 'c', 'b'] Listings.findNeighborhoods (err, groups) -> groups['Other'].join('').should.equal 'abcd' done() it 'groups neighborhoods into their proper larger groups', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['UES', '<NAME>'] Listings.findNeighborhoods (err, groups) -> groups['South Brooklyn'][0].should.equal '<NAME>' groups['Uptown'][0].should.equal 'UES' done() describe '#countBad', -> it 'counts the number of bad listings', (done) -> Listings.countBad (err, badCount, total) -> badCount.should.equal 50 total.should.equal 100 done() Listings.collection.count.args[0][0] null, 100 Listings.collection.count.args[1][1] null, 50 describe '#badDataHash', -> it 'scans the database and maps it into a hash of bad data easy to parse' it 'splits the scraper name by a dash so it handles the nytimes-newyork scrapers'
true
Listings = require '../../dal/listings' sinon = require 'sinon' collectionStub = require '../helpers/collection-stub' _ = require 'underscore' describe 'listings', -> beforeEach -> Listings.collection = collectionStub() describe "#find", -> it 'limits by beds', -> Listings.find('bed-min': 2) Listings.collection.find.args[0][0].beds["$gte"].should.equal 2 it 'limits by baths', -> Listings.find('bath-min': 2) Listings.collection.find.args[0][0].baths["$gte"].should.equal 2 it 'limits by rent', -> Listings.find('rent-max': 2000) Listings.collection.find.args[0][0].rent["$lte"].should.equal 2000 it 'limits by size', -> Listings.find(size: 10, page: 1) Listings.collection.limit.args[0][0].should.equal 10 it 'accepts page params', -> Listings.find(size: 10, page: 1) Listings.collection.skip.args[0][0].should.equal 10 it 'filters by neighborhoods', -> Listings.find(neighborhoods: ['bar', 'foo']) _.isEqual( Listings.collection.find.args[0][0]['location.neighborhood'] { $in: ['bar', 'foo'] } ).should.be.ok it 'sorts by rent', -> Listings.find(sort: 'rent') Listings.collection.sort.args[0][0].rent.should.equal 1 it 'sorts by size', -> Listings.find(sort: 'size') Listings.collection.sort.args[0][0].beds.should.equal -1 Listings.collection.sort.args[0][0].baths.should.equal -1 it 'sorts by newest listings', -> Listings.find(sort: 'newest') Listings.collection.sort.args[0][0].dateScraped.should.equal -1 it 'can pull the latest listings', -> Listings.find 'date-scraped-start': new Date() Listings.collection.find.args[0][0].dateScraped.$gte.toString() .should.equal new Date().toString() describe '#count', -> it 'counts listings by params', -> Listings.count('bed-min': 2) Listings.collection.count.args[0][0].beds["$gte"].should.equal 2 describe '#upsert', -> it 'upserts restricting to urls', -> Listings.upsert [{ url: 'foo', foo: 'foo' }, { url: 'bar', bar: 'foo' }] Listings.collection.update.args[0][0].url.should.equal 'foo' Listings.collection.update.args[1][0].url.should.equal 'bar' it 'upserts each document', -> Listings.upsert [{ url: 'foo', foo: 'foo' }, { url: 'bar', bar: 'foo' }] Listings.collection.update.calledTwice.should.be.ok it 'updates the passed info', -> Listings.upsert [{ url: 'foo', foo: 'foo' }, { url: 'bar', bar: 'bar' }] Listings.collection.update.args[0][1].foo.should.equal 'foo' Listings.collection.update.args[1][1].bar.should.equal 'bar' describe '#geocode', -> beforeEach -> Listings.collection.update.callsArgWith 3, null it 'stores dateGeocoded', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.geocode { location: { name: 'foobar' } }, (err, listing) -> listing.dateGeocoded.toString().should.containEql new Date().getFullYear() done() Listings.gm.geocode.args[0][0].should.equal 'foobar' Listings.gm.geocode.args[0][1] null, results: [ address_components: [ long_name: "PI:NAME:<NAME>END_PI" short_name: "PI:NAME:<NAME>END_PI" types: ["neighborhood", "political"] ] formatted_address: "245 East 124th Street, New York, NY 10035, USA" geometry: location: lat: 40.802391 lng: -73.934573 ] it 'fetches the geocode data from google maps and injects it into the listing', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.geocode { location: { name: 'PI:NAME:<NAME>END_PI' } }, (err, listing) -> listing.location.formattedAddress.should.equal( '245 East 124th Street, New York, NY 10035, USA' ) listing.location.lng.should.equal -73.934573 listing.location.lat.should.equal 40.802391 listing.location.neighborhood.should.equal 'PI:NAME:<NAME>END_PI' done() Listings.gm.geocode.args[0][0].should.equal 'foobar' Listings.gm.geocode.args[0][1] null, results: [ address_components: [ long_name: "PI:NAME:<NAME>END_PI" short_name: "PI:NAME:<NAME>END_PI" types: ["neighborhood", "political"] ] formatted_address: "245 East 124th Street, New York, NY 10035, USA" geometry: location: lat: 40.802391 lng: -73.934573 ] it 'errs if there are no results', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.gm.geocode.callsArgWith 1, { status: 'ZERO RESULTS' } Listings.geocode { location: { name: 'PI:NAME:<NAME>END_PI' } }, (err, listing) -> (err?).should.be.ok done() it 'does not geocode non-new york cities', (done) -> Listings.gm = { geocode: sinon.stub() } Listings.geocode { location: { name: 'PI:NAME:<NAME>END_PI' } }, (err, listing) -> listing.location.formattedAddress.should.equal 'Kewl York, New York, NY' done() Listings.gm.geocode.args[0][1] null, results: [ { address_components: [] formatted_address: "245 East 124th Street, Cincinnati OH" } { address_components: [ long_name: "PI:NAME:<NAME>END_PI" short_name: "PI:NAME:<NAME>END_PI" types: ["neighborhood", "political"] ] formatted_address: "Kewl York, New York, NY" geometry: location: lat: 40.802391 lng: -73.934573 } { address_components: [] formatted_address: "245 East 124th Street, Cincinnati OH" } ] describe '#findNeighborhoods', -> it 'distincts the neighborhoods and returns the results', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['foo', 'bar'] Listings.findNeighborhoods (err, groups) -> groups['Other'][0].should.equal 'bar' groups['Other'][1].should.equal 'foo' done() it 'ignores null neighborhoods', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['foo', 'bar', null] Listings.findNeighborhoods (err, groups) -> groups['Other'].length.should.equal 2 done() it 'sorts alphabetically', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['a', 'd', 'c', 'b'] Listings.findNeighborhoods (err, groups) -> groups['Other'].join('').should.equal 'abcd' done() it 'groups neighborhoods into their proper larger groups', (done) -> Listings.collection.distinct.callsArgWith 1, null, ['UES', 'PI:NAME:<NAME>END_PI'] Listings.findNeighborhoods (err, groups) -> groups['South Brooklyn'][0].should.equal 'PI:NAME:<NAME>END_PI' groups['Uptown'][0].should.equal 'UES' done() describe '#countBad', -> it 'counts the number of bad listings', (done) -> Listings.countBad (err, badCount, total) -> badCount.should.equal 50 total.should.equal 100 done() Listings.collection.count.args[0][0] null, 100 Listings.collection.count.args[1][1] null, 50 describe '#badDataHash', -> it 'scans the database and maps it into a hash of bad data easy to parse' it 'splits the scraper name by a dash so it handles the nytimes-newyork scrapers'
[ { "context": "lass IsyInsteonSwitchNode extends IsyNode\n key: 'insteonSwitch'\n types: [[2, 42], [2, 55]]\n\n aspects:", "end": 105, "score": 0.6604896187782288, "start": 101, "tag": "KEY", "value": "inst" } ]
lib/adapters/isy/IsyInsteonSwitchNode.coffee
monitron/jarvis-ha
1
IsyNode = require('./IsyNode') module.exports = class IsyInsteonSwitchNode extends IsyNode key: 'insteonSwitch' types: [[2, 42], [2, 55]] aspects: powerOnOff: commands: set: (node, value) -> command = if value then 'DON' else 'DOF' operative = value != node.getAspect('powerOnOff').getDatum('state') node.adapter.executeCommand node.id, command, [], operative processData: (data) -> if data.ST? then @getAspect('powerOnOff').setData state: (data.ST != '0')
40444
IsyNode = require('./IsyNode') module.exports = class IsyInsteonSwitchNode extends IsyNode key: '<KEY>eonSwitch' types: [[2, 42], [2, 55]] aspects: powerOnOff: commands: set: (node, value) -> command = if value then 'DON' else 'DOF' operative = value != node.getAspect('powerOnOff').getDatum('state') node.adapter.executeCommand node.id, command, [], operative processData: (data) -> if data.ST? then @getAspect('powerOnOff').setData state: (data.ST != '0')
true
IsyNode = require('./IsyNode') module.exports = class IsyInsteonSwitchNode extends IsyNode key: 'PI:KEY:<KEY>END_PIeonSwitch' types: [[2, 42], [2, 55]] aspects: powerOnOff: commands: set: (node, value) -> command = if value then 'DON' else 'DOF' operative = value != node.getAspect('powerOnOff').getDatum('state') node.adapter.executeCommand node.id, command, [], operative processData: (data) -> if data.ST? then @getAspect('powerOnOff').setData state: (data.ST != '0')
[ { "context": "ttp%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol&text=Andy Warhol on Artsy&url=http%3A%2F%2Fartsy.net%2Fartist%2Fan", "end": 1215, "score": 0.9994006156921387, "start": 1204, "tag": "NAME", "value": "Andy Warhol" } ]
src/desktop/components/share/test/mixin.coffee
kanaabe/force
1
fs = require 'fs' jade = require 'jade' path = require 'path' benv = require 'benv' render = (templateName) -> filename = path.resolve __dirname, "#{templateName}.jade" jade.compile fs.readFileSync(filename), filename: filename describe 'Share mixin', -> before (done) -> benv.setup -> benv.expose $: benv.require 'jquery' sd: APP_URL: 'http://artsy.net' CURRENT_PATH: '/artist/andy-warhol' done() after -> benv.teardown() beforeEach -> @$case1 = $ render('mixin')() .find('#case-1') afterEach -> @$case1.remove() it 'renders the appropriate link for sharing on Facebook', -> @$case1.find('.share-to-facebook').length .should.equal 1 @$case1.find('.share-to-facebook').attr 'href' .should.equal 'https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol' it 'renders the appropriate link for sharing on Twitter', -> @$case1.find '.share-to-twitter' .should.have.lengthOf 1 @$case1.find('.share-to-twitter').attr 'href' .should.equal 'https://twitter.com/intent/tweet?original_referer=http%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol&text=Andy Warhol on Artsy&url=http%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol&via=artsy'
125296
fs = require 'fs' jade = require 'jade' path = require 'path' benv = require 'benv' render = (templateName) -> filename = path.resolve __dirname, "#{templateName}.jade" jade.compile fs.readFileSync(filename), filename: filename describe 'Share mixin', -> before (done) -> benv.setup -> benv.expose $: benv.require 'jquery' sd: APP_URL: 'http://artsy.net' CURRENT_PATH: '/artist/andy-warhol' done() after -> benv.teardown() beforeEach -> @$case1 = $ render('mixin')() .find('#case-1') afterEach -> @$case1.remove() it 'renders the appropriate link for sharing on Facebook', -> @$case1.find('.share-to-facebook').length .should.equal 1 @$case1.find('.share-to-facebook').attr 'href' .should.equal 'https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol' it 'renders the appropriate link for sharing on Twitter', -> @$case1.find '.share-to-twitter' .should.have.lengthOf 1 @$case1.find('.share-to-twitter').attr 'href' .should.equal 'https://twitter.com/intent/tweet?original_referer=http%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol&text=<NAME> on Artsy&url=http%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol&via=artsy'
true
fs = require 'fs' jade = require 'jade' path = require 'path' benv = require 'benv' render = (templateName) -> filename = path.resolve __dirname, "#{templateName}.jade" jade.compile fs.readFileSync(filename), filename: filename describe 'Share mixin', -> before (done) -> benv.setup -> benv.expose $: benv.require 'jquery' sd: APP_URL: 'http://artsy.net' CURRENT_PATH: '/artist/andy-warhol' done() after -> benv.teardown() beforeEach -> @$case1 = $ render('mixin')() .find('#case-1') afterEach -> @$case1.remove() it 'renders the appropriate link for sharing on Facebook', -> @$case1.find('.share-to-facebook').length .should.equal 1 @$case1.find('.share-to-facebook').attr 'href' .should.equal 'https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol' it 'renders the appropriate link for sharing on Twitter', -> @$case1.find '.share-to-twitter' .should.have.lengthOf 1 @$case1.find('.share-to-twitter').attr 'href' .should.equal 'https://twitter.com/intent/tweet?original_referer=http%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol&text=PI:NAME:<NAME>END_PI on Artsy&url=http%3A%2F%2Fartsy.net%2Fartist%2Fandy-warhol&via=artsy'
[ { "context": "singers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\nkids =\n brother:\n na", "end": 17, "score": 0.9996140003204346, "start": 11, "tag": "NAME", "value": "Jagger" }, { "context": "singers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\nkids =\n brother:\n name: \"Ma", "end": 24, "score": 0.9860699772834778, "start": 20, "tag": "NAME", "value": "Rock" }, { "context": "singers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\nkids =\n brother:\n name: \"Max\"\n a", "end": 32, "score": 0.9993714690208435, "start": 27, "tag": "NAME", "value": "Elvis" }, { "context": "singers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\nkids =\n brother:\n name: \"Max\"\n age: 11", "end": 39, "score": 0.9713924527168274, "start": 35, "tag": "NAME", "value": "Roll" }, { "context": "ck\", Elvis: \"Roll\"}\n\nkids =\n brother:\n name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: ", "end": 75, "score": 0.9998695850372314, "start": 72, "tag": "NAME", "value": "Max" }, { "context": " name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: 9\n", "end": 114, "score": 0.9998279809951782, "start": 111, "tag": "NAME", "value": "Ida" } ]
src/test/resources/lexer/objects.coffee
consulo/consulo-coffeescript
8
singers = {Jagger: "Rock", Elvis: "Roll"} kids = brother: name: "Max" age: 11 sister: name: "Ida" age: 9
147534
singers = {<NAME>: "<NAME>", <NAME>: "<NAME>"} kids = brother: name: "<NAME>" age: 11 sister: name: "<NAME>" age: 9
true
singers = {PI:NAME:<NAME>END_PI: "PI:NAME:<NAME>END_PI", PI:NAME:<NAME>END_PI: "PI:NAME:<NAME>END_PI"} kids = brother: name: "PI:NAME:<NAME>END_PI" age: 11 sister: name: "PI:NAME:<NAME>END_PI" age: 9
[ { "context": " nodes: [\n {id: 2, name: 'Bob'}\n {id: 4, name: 'Dave'}\n ", "end": 1463, "score": 0.9998635053634644, "start": 1460, "tag": "NAME", "value": "Bob" }, { "context": ", name: 'Bob'}\n {id: 4, name: 'Dave'}\n {id: 1, name: 'Alice'}\n ", "end": 1505, "score": 0.9996435046195984, "start": 1501, "tag": "NAME", "value": "Dave" }, { "context": " name: 'Dave'}\n {id: 1, name: 'Alice'}\n {id: 3, name: 'Carol'}\n ", "end": 1548, "score": 0.9998679161071777, "start": 1543, "tag": "NAME", "value": "Alice" }, { "context": "name: 'Alice'}\n {id: 3, name: 'Carol'}\n ]\n , _\n\n expect(r", "end": 1591, "score": 0.9997636675834656, "start": 1586, "tag": "NAME", "value": "Carol" }, { "context": " 'node.id': 1\n 'node.name': 'Alice'\n '{count}': 3\n ,\n '", "end": 1714, "score": 0.9998674988746643, "start": 1709, "tag": "NAME", "value": "Alice" }, { "context": " 'node.id': 2\n 'node.name': 'Bob'\n '{count}': 3\n ,\n '", "end": 1805, "score": 0.9998642206192017, "start": 1802, "tag": "NAME", "value": "Bob" }, { "context": " 'node.id': 3\n 'node.name': 'Carol'\n '{count}': 3\n ]\n\n it 'shou", "end": 1898, "score": 0.9997202157974243, "start": 1893, "tag": "NAME", "value": "Carol" } ]
Lambda Functions/searchlocales/node_modules/neo4j/test-new/cypher._coffee
RussellPhipps/PilgrimAdminTools
0
# # Tests for the GraphDatabase `cypher` method, e.g. the ability to make queries, # parametrize them, have responses be auto-parsed for nodes & rels, etc. # {expect} = require 'chai' fixtures = require './fixtures' helpers = require './util/helpers' neo4j = require '../' ## SHARED STATE {DB} = fixtures [TEST_NODE_A, TEST_NODE_B, TEST_REL] = [] ## TESTS describe 'GraphDatabase::cypher', -> it 'should support simple queries and results', (_) -> results = DB.cypher 'RETURN "bar" AS foo', _ expect(results).to.be.an 'array' expect(results).to.have.length 1 [result] = results expect(result).to.be.an 'object' expect(result).to.contain.keys 'foo' # this is an exact/"only" check expect(result.foo).to.equal 'bar' it 'should support simple parameters', (_) -> [result] = DB.cypher query: 'RETURN {foo} AS foo' params: {foo: 'bar'} , _ expect(result).to.be.an 'object' expect(result.foo).to.equal 'bar' it 'should support complex queries, params, and results', (_) -> results = DB.cypher query: ''' UNWIND {nodes} AS node WITH node ORDER BY node.id LIMIT {count} RETURN node.id, node.name, {count} ''' params: count: 3 nodes: [ {id: 2, name: 'Bob'} {id: 4, name: 'Dave'} {id: 1, name: 'Alice'} {id: 3, name: 'Carol'} ] , _ expect(results).to.eql [ 'node.id': 1 'node.name': 'Alice' '{count}': 3 , 'node.id': 2 'node.name': 'Bob' '{count}': 3 , 'node.id': 3 'node.name': 'Carol' '{count}': 3 ] it 'should support queries that return nothing', (_) -> results = DB.cypher query: 'MATCH (n:FooBarBazThisLabelDoesntExist) RETURN n' params: {unused: 'param'} , _ expect(results).to.be.empty() it 'should reject empty/missing queries', -> fail = -> throw new Error 'Callback should not have been called' fn1 = -> DB.cypher '', fail fn2 = -> DB.cypher {}, fail expect(fn1).to.throw TypeError, /query/i expect(fn2).to.throw TypeError, /query/i it 'should properly parse and throw Neo4j errors', (done) -> DB.cypher 'RETURN {foo}', (err, results) -> expect(err).to.exist() helpers.expectError err, 'ClientError', 'Statement', 'ParameterMissing', 'Expected a parameter named foo' # Whether `results` are returned or not depends on the error; # Neo4j will return an array if the query could be executed, # and then it'll return whatever results it could manage to get # before the error. In this case, the query began execution, # so we expect an array, but no actual results. expect(results).to.be.an 'array' expect(results).to.be.empty() done() it 'should properly return null result on syntax errors', (done) -> DB.cypher '(syntax error)', (err, results) -> expect(err).to.exist() # Simplified error checking, since the message is complex: expect(err).to.be.an.instanceOf neo4j.ClientError expect(err.neo4j).to.be.an 'object' expect(err.neo4j.code).to.equal \ 'Neo.ClientError.Statement.InvalidSyntax' # Unlike the previous test case, since Neo4j could not be # executed, no results should have been returned at all: expect(results).to.not.exist() done() it '(create test graph)', (_) -> [TEST_NODE_A, TEST_REL, TEST_NODE_B] = fixtures.createTestGraph module, 2, _ it 'should properly parse nodes & relationships', (_) -> # We do a complex return to test nested/wrapped objects too. # NOTE: However, returning an array changes the order of the returned # results, no longer the deterministic order of [a, b, r]. # We overcome this by explicitly indexing and ordering. results = DB.cypher query: ''' START a = node({idA}) MATCH (a) -[r]-> (b) WITH [ {i: 0, elmt: a}, {i: 1, elmt: b}, {i: 2, elmt: r} ] AS array UNWIND array AS obj RETURN obj.i AS i, [{ inner: obj.elmt }] AS outer ORDER BY i ''' params: idA: TEST_NODE_A._id , _ expect(results).to.eql [ i: 0 outer: [ inner: TEST_NODE_A ] , i: 1 outer: [ inner: TEST_NODE_B ] , i: 2 outer: [ inner: TEST_REL ] ] # But also test that the returned objects are proper instances: expect(results[0].outer[0].inner).to.be.an.instanceOf neo4j.Node expect(results[1].outer[0].inner).to.be.an.instanceOf neo4j.Node expect(results[2].outer[0].inner).to.be.an.instanceOf neo4j.Relationship it 'should not parse nodes & relationships if lean', (_) -> results = DB.cypher query: ''' START a = node({idA}) MATCH (a) -[r]-> (b) RETURN a, b, r ''' params: idA: TEST_NODE_A._id lean: true , _ expect(results).to.eql [ a: TEST_NODE_A.properties b: TEST_NODE_B.properties r: TEST_REL.properties ] it 'should support simple batching', (_) -> results = DB.cypher [ query: ''' START a = node({idA}) RETURN a ''' params: idA: TEST_NODE_A._id , query: ''' START b = node({idB}) RETURN b ''' params: idB: TEST_NODE_B._id , query: ''' START r = rel({idR}) RETURN r ''' params: idR: TEST_REL._id ], _ expect(results).to.be.an 'array' expect(results).to.have.length 3 [resultsA, resultsB, resultsR] = results expect(resultsA).to.eql [ a: TEST_NODE_A ] expect(resultsB).to.eql [ b: TEST_NODE_B ] expect(resultsR).to.eql [ r: TEST_REL ] it 'should handle complex batching with errors', (done) -> DB.cypher queries: [ query: ''' START a = node({idA}) RETURN a ''' params: idA: TEST_NODE_A._id lean: true , 'RETURN {foo}' , query: ''' START r = rel({idR}) RETURN r ''' params: idR: TEST_REL._id ] , (err, results) -> expect(err).to.exist() helpers.expectError err, 'ClientError', 'Statement', 'ParameterMissing', 'Expected a parameter named foo' # NOTE: With batching, we *do* return any results that we # received before the error, in case of an open transaction. # This means that we'll always return an array here, and it'll # have just as many elements as queries that returned an array # before the error. In this case, a ParameterMissing error in # the second query means the second array *was* returned (since # Neo4j could begin executing the query; see note in the first # error handling test case in this suite), so two results. expect(results).to.be.an 'array' expect(results).to.have.length 2 [resultsA, resultsB] = results expect(resultsA).to.eql [ a: TEST_NODE_A.properties ] expect(resultsB).to.be.empty() done() it 'should support streaming (TODO)' it '(delete test graph)', (_) -> fixtures.deleteTestGraph module, _
144574
# # Tests for the GraphDatabase `cypher` method, e.g. the ability to make queries, # parametrize them, have responses be auto-parsed for nodes & rels, etc. # {expect} = require 'chai' fixtures = require './fixtures' helpers = require './util/helpers' neo4j = require '../' ## SHARED STATE {DB} = fixtures [TEST_NODE_A, TEST_NODE_B, TEST_REL] = [] ## TESTS describe 'GraphDatabase::cypher', -> it 'should support simple queries and results', (_) -> results = DB.cypher 'RETURN "bar" AS foo', _ expect(results).to.be.an 'array' expect(results).to.have.length 1 [result] = results expect(result).to.be.an 'object' expect(result).to.contain.keys 'foo' # this is an exact/"only" check expect(result.foo).to.equal 'bar' it 'should support simple parameters', (_) -> [result] = DB.cypher query: 'RETURN {foo} AS foo' params: {foo: 'bar'} , _ expect(result).to.be.an 'object' expect(result.foo).to.equal 'bar' it 'should support complex queries, params, and results', (_) -> results = DB.cypher query: ''' UNWIND {nodes} AS node WITH node ORDER BY node.id LIMIT {count} RETURN node.id, node.name, {count} ''' params: count: 3 nodes: [ {id: 2, name: '<NAME>'} {id: 4, name: '<NAME>'} {id: 1, name: '<NAME>'} {id: 3, name: '<NAME>'} ] , _ expect(results).to.eql [ 'node.id': 1 'node.name': '<NAME>' '{count}': 3 , 'node.id': 2 'node.name': '<NAME>' '{count}': 3 , 'node.id': 3 'node.name': '<NAME>' '{count}': 3 ] it 'should support queries that return nothing', (_) -> results = DB.cypher query: 'MATCH (n:FooBarBazThisLabelDoesntExist) RETURN n' params: {unused: 'param'} , _ expect(results).to.be.empty() it 'should reject empty/missing queries', -> fail = -> throw new Error 'Callback should not have been called' fn1 = -> DB.cypher '', fail fn2 = -> DB.cypher {}, fail expect(fn1).to.throw TypeError, /query/i expect(fn2).to.throw TypeError, /query/i it 'should properly parse and throw Neo4j errors', (done) -> DB.cypher 'RETURN {foo}', (err, results) -> expect(err).to.exist() helpers.expectError err, 'ClientError', 'Statement', 'ParameterMissing', 'Expected a parameter named foo' # Whether `results` are returned or not depends on the error; # Neo4j will return an array if the query could be executed, # and then it'll return whatever results it could manage to get # before the error. In this case, the query began execution, # so we expect an array, but no actual results. expect(results).to.be.an 'array' expect(results).to.be.empty() done() it 'should properly return null result on syntax errors', (done) -> DB.cypher '(syntax error)', (err, results) -> expect(err).to.exist() # Simplified error checking, since the message is complex: expect(err).to.be.an.instanceOf neo4j.ClientError expect(err.neo4j).to.be.an 'object' expect(err.neo4j.code).to.equal \ 'Neo.ClientError.Statement.InvalidSyntax' # Unlike the previous test case, since Neo4j could not be # executed, no results should have been returned at all: expect(results).to.not.exist() done() it '(create test graph)', (_) -> [TEST_NODE_A, TEST_REL, TEST_NODE_B] = fixtures.createTestGraph module, 2, _ it 'should properly parse nodes & relationships', (_) -> # We do a complex return to test nested/wrapped objects too. # NOTE: However, returning an array changes the order of the returned # results, no longer the deterministic order of [a, b, r]. # We overcome this by explicitly indexing and ordering. results = DB.cypher query: ''' START a = node({idA}) MATCH (a) -[r]-> (b) WITH [ {i: 0, elmt: a}, {i: 1, elmt: b}, {i: 2, elmt: r} ] AS array UNWIND array AS obj RETURN obj.i AS i, [{ inner: obj.elmt }] AS outer ORDER BY i ''' params: idA: TEST_NODE_A._id , _ expect(results).to.eql [ i: 0 outer: [ inner: TEST_NODE_A ] , i: 1 outer: [ inner: TEST_NODE_B ] , i: 2 outer: [ inner: TEST_REL ] ] # But also test that the returned objects are proper instances: expect(results[0].outer[0].inner).to.be.an.instanceOf neo4j.Node expect(results[1].outer[0].inner).to.be.an.instanceOf neo4j.Node expect(results[2].outer[0].inner).to.be.an.instanceOf neo4j.Relationship it 'should not parse nodes & relationships if lean', (_) -> results = DB.cypher query: ''' START a = node({idA}) MATCH (a) -[r]-> (b) RETURN a, b, r ''' params: idA: TEST_NODE_A._id lean: true , _ expect(results).to.eql [ a: TEST_NODE_A.properties b: TEST_NODE_B.properties r: TEST_REL.properties ] it 'should support simple batching', (_) -> results = DB.cypher [ query: ''' START a = node({idA}) RETURN a ''' params: idA: TEST_NODE_A._id , query: ''' START b = node({idB}) RETURN b ''' params: idB: TEST_NODE_B._id , query: ''' START r = rel({idR}) RETURN r ''' params: idR: TEST_REL._id ], _ expect(results).to.be.an 'array' expect(results).to.have.length 3 [resultsA, resultsB, resultsR] = results expect(resultsA).to.eql [ a: TEST_NODE_A ] expect(resultsB).to.eql [ b: TEST_NODE_B ] expect(resultsR).to.eql [ r: TEST_REL ] it 'should handle complex batching with errors', (done) -> DB.cypher queries: [ query: ''' START a = node({idA}) RETURN a ''' params: idA: TEST_NODE_A._id lean: true , 'RETURN {foo}' , query: ''' START r = rel({idR}) RETURN r ''' params: idR: TEST_REL._id ] , (err, results) -> expect(err).to.exist() helpers.expectError err, 'ClientError', 'Statement', 'ParameterMissing', 'Expected a parameter named foo' # NOTE: With batching, we *do* return any results that we # received before the error, in case of an open transaction. # This means that we'll always return an array here, and it'll # have just as many elements as queries that returned an array # before the error. In this case, a ParameterMissing error in # the second query means the second array *was* returned (since # Neo4j could begin executing the query; see note in the first # error handling test case in this suite), so two results. expect(results).to.be.an 'array' expect(results).to.have.length 2 [resultsA, resultsB] = results expect(resultsA).to.eql [ a: TEST_NODE_A.properties ] expect(resultsB).to.be.empty() done() it 'should support streaming (TODO)' it '(delete test graph)', (_) -> fixtures.deleteTestGraph module, _
true
# # Tests for the GraphDatabase `cypher` method, e.g. the ability to make queries, # parametrize them, have responses be auto-parsed for nodes & rels, etc. # {expect} = require 'chai' fixtures = require './fixtures' helpers = require './util/helpers' neo4j = require '../' ## SHARED STATE {DB} = fixtures [TEST_NODE_A, TEST_NODE_B, TEST_REL] = [] ## TESTS describe 'GraphDatabase::cypher', -> it 'should support simple queries and results', (_) -> results = DB.cypher 'RETURN "bar" AS foo', _ expect(results).to.be.an 'array' expect(results).to.have.length 1 [result] = results expect(result).to.be.an 'object' expect(result).to.contain.keys 'foo' # this is an exact/"only" check expect(result.foo).to.equal 'bar' it 'should support simple parameters', (_) -> [result] = DB.cypher query: 'RETURN {foo} AS foo' params: {foo: 'bar'} , _ expect(result).to.be.an 'object' expect(result.foo).to.equal 'bar' it 'should support complex queries, params, and results', (_) -> results = DB.cypher query: ''' UNWIND {nodes} AS node WITH node ORDER BY node.id LIMIT {count} RETURN node.id, node.name, {count} ''' params: count: 3 nodes: [ {id: 2, name: 'PI:NAME:<NAME>END_PI'} {id: 4, name: 'PI:NAME:<NAME>END_PI'} {id: 1, name: 'PI:NAME:<NAME>END_PI'} {id: 3, name: 'PI:NAME:<NAME>END_PI'} ] , _ expect(results).to.eql [ 'node.id': 1 'node.name': 'PI:NAME:<NAME>END_PI' '{count}': 3 , 'node.id': 2 'node.name': 'PI:NAME:<NAME>END_PI' '{count}': 3 , 'node.id': 3 'node.name': 'PI:NAME:<NAME>END_PI' '{count}': 3 ] it 'should support queries that return nothing', (_) -> results = DB.cypher query: 'MATCH (n:FooBarBazThisLabelDoesntExist) RETURN n' params: {unused: 'param'} , _ expect(results).to.be.empty() it 'should reject empty/missing queries', -> fail = -> throw new Error 'Callback should not have been called' fn1 = -> DB.cypher '', fail fn2 = -> DB.cypher {}, fail expect(fn1).to.throw TypeError, /query/i expect(fn2).to.throw TypeError, /query/i it 'should properly parse and throw Neo4j errors', (done) -> DB.cypher 'RETURN {foo}', (err, results) -> expect(err).to.exist() helpers.expectError err, 'ClientError', 'Statement', 'ParameterMissing', 'Expected a parameter named foo' # Whether `results` are returned or not depends on the error; # Neo4j will return an array if the query could be executed, # and then it'll return whatever results it could manage to get # before the error. In this case, the query began execution, # so we expect an array, but no actual results. expect(results).to.be.an 'array' expect(results).to.be.empty() done() it 'should properly return null result on syntax errors', (done) -> DB.cypher '(syntax error)', (err, results) -> expect(err).to.exist() # Simplified error checking, since the message is complex: expect(err).to.be.an.instanceOf neo4j.ClientError expect(err.neo4j).to.be.an 'object' expect(err.neo4j.code).to.equal \ 'Neo.ClientError.Statement.InvalidSyntax' # Unlike the previous test case, since Neo4j could not be # executed, no results should have been returned at all: expect(results).to.not.exist() done() it '(create test graph)', (_) -> [TEST_NODE_A, TEST_REL, TEST_NODE_B] = fixtures.createTestGraph module, 2, _ it 'should properly parse nodes & relationships', (_) -> # We do a complex return to test nested/wrapped objects too. # NOTE: However, returning an array changes the order of the returned # results, no longer the deterministic order of [a, b, r]. # We overcome this by explicitly indexing and ordering. results = DB.cypher query: ''' START a = node({idA}) MATCH (a) -[r]-> (b) WITH [ {i: 0, elmt: a}, {i: 1, elmt: b}, {i: 2, elmt: r} ] AS array UNWIND array AS obj RETURN obj.i AS i, [{ inner: obj.elmt }] AS outer ORDER BY i ''' params: idA: TEST_NODE_A._id , _ expect(results).to.eql [ i: 0 outer: [ inner: TEST_NODE_A ] , i: 1 outer: [ inner: TEST_NODE_B ] , i: 2 outer: [ inner: TEST_REL ] ] # But also test that the returned objects are proper instances: expect(results[0].outer[0].inner).to.be.an.instanceOf neo4j.Node expect(results[1].outer[0].inner).to.be.an.instanceOf neo4j.Node expect(results[2].outer[0].inner).to.be.an.instanceOf neo4j.Relationship it 'should not parse nodes & relationships if lean', (_) -> results = DB.cypher query: ''' START a = node({idA}) MATCH (a) -[r]-> (b) RETURN a, b, r ''' params: idA: TEST_NODE_A._id lean: true , _ expect(results).to.eql [ a: TEST_NODE_A.properties b: TEST_NODE_B.properties r: TEST_REL.properties ] it 'should support simple batching', (_) -> results = DB.cypher [ query: ''' START a = node({idA}) RETURN a ''' params: idA: TEST_NODE_A._id , query: ''' START b = node({idB}) RETURN b ''' params: idB: TEST_NODE_B._id , query: ''' START r = rel({idR}) RETURN r ''' params: idR: TEST_REL._id ], _ expect(results).to.be.an 'array' expect(results).to.have.length 3 [resultsA, resultsB, resultsR] = results expect(resultsA).to.eql [ a: TEST_NODE_A ] expect(resultsB).to.eql [ b: TEST_NODE_B ] expect(resultsR).to.eql [ r: TEST_REL ] it 'should handle complex batching with errors', (done) -> DB.cypher queries: [ query: ''' START a = node({idA}) RETURN a ''' params: idA: TEST_NODE_A._id lean: true , 'RETURN {foo}' , query: ''' START r = rel({idR}) RETURN r ''' params: idR: TEST_REL._id ] , (err, results) -> expect(err).to.exist() helpers.expectError err, 'ClientError', 'Statement', 'ParameterMissing', 'Expected a parameter named foo' # NOTE: With batching, we *do* return any results that we # received before the error, in case of an open transaction. # This means that we'll always return an array here, and it'll # have just as many elements as queries that returned an array # before the error. In this case, a ParameterMissing error in # the second query means the second array *was* returned (since # Neo4j could begin executing the query; see note in the first # error handling test case in this suite), so two results. expect(results).to.be.an 'array' expect(results).to.have.length 2 [resultsA, resultsB] = results expect(resultsA).to.eql [ a: TEST_NODE_A.properties ] expect(resultsB).to.be.empty() done() it 'should support streaming (TODO)' it '(delete test graph)', (_) -> fixtures.deleteTestGraph module, _
[ { "context": " Storage\")\n @site.use(session({\n secret: '9`hIi6Z89*0gMHfgh3sdsfdwerwrefd43',\n resave: false,\n saveUninitialized: t", "end": 2211, "score": 0.9903522729873657, "start": 2178, "tag": "KEY", "value": "9`hIi6Z89*0gMHfgh3sdsfdwerwrefd43" } ]
webserver.coffee
motorlatitude/MotorBot
4
morgan = require 'morgan' express = require "express" fs = require 'fs' nib = require 'nib' stylus = require 'stylus' compression = require 'compression' serveStatic = require 'serve-static' bodyParser = require('body-parser') cookieParser = require('cookie-parser') session = require('express-session') passport = require 'passport' RedisStore = require('connect-redis')(session) flash = require('connect-flash') class WebServer constructor: (@app) -> start: () -> self = @ @site = express() @site.use(morgan('\[DEBUG\]\['+new Date().getDate()+"\/"+(parseInt(new Date().getMonth())+1)+"\/"+new Date().getFullYear()+' \] :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms')) compile = (str, path) -> stylus(str).set('filename',path).set("compress",true).use(nib()) @app.debug("Setting Views Directory") @site.set('views', __dirname+'/views') @app.debug("Setting View Engine") @site.set('view engine', 'pug') @app.debug("Setting Stylus Middleware") @site.use(stylus.middleware({ src: __dirname + '/static', compile: compile }) ) @app.debug("Setting Static File Directory Location") @site.use(serveStatic(__dirname + '/static')) @site.use(serveStatic(__dirname + '/static/img', { maxAge: 86400000 })) @app.debug("Setting Response Headers") @site.use((req, res, next) -> res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, PATCH, PUT') res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type') res.setHeader('Access-Control-Allow-Credentials', true) res.setHeader('X-Cluster-Identifier', process.pid) next() ) @app.debug("Setting Compression") @site.use(compression()) @site.use(bodyParser.json({limit: "10mb"})); @site.use(bodyParser.urlencoded({ extended: false, limit: "10mb"})) @app.debug("Setting up Cookie Parser") @site.use(cookieParser("9`hIi6Z89*0gMHfYqLEJGfWMCK(d9YM0C")) @app.debug("Setting Up Session with Redis Storage") @site.use(session({ secret: '9`hIi6Z89*0gMHfgh3sdsfdwerwrefd43', resave: false, saveUninitialized: true, store: new RedisStore({ host: "localhost", port: 6379 }) })) @app.debug("Setting Up Connect-Flash") @site.use(flash()) @app.debug("Initializing Passport") @site.use(passport.initialize()) @app.debug("Initializing Passport Sessions") @site.use(passport.session()) @site.locals.motorbot = self.app #Express Routers @app.debug("Registering Route ./routes/playlistv2") @site.use("/", require('./routes/playlistv2')) @app.debug("Registering Route ./routes/loginflow") @site.use("/loginflow", require('./routes/loginflow')) @app.debug("Registering Route ./routes/api_routes/oauth2") @site.use("/api/oauth2", require('./routes/api_routes/oauth2')) @app.debug("Registering Route ./routes/api_routes/music") @site.use("/api/music", require('./routes/api_routes/music')) @app.debug("Registering Route ./routes/api_routes/playlist") @site.use("/api/playlist", require('./routes/api_routes/playlist')) @app.debug("Registering Route ./routes/api_routes/user") @site.use("/api/user", require('./routes/api_routes/user')) @app.debug("Registering Route ./routes/api_routes/queue") @site.use("/api/queue", require('./routes/api_routes/queue')) @app.debug("Registering Route ./routes/api_routes/motorbot") @site.use("/api/motorbot", require('./routes/api_routes/motorbot')) @app.debug("Registering Route ./routes/api_routes/browse") @site.use("/api/browse", require('./routes/api_routes/browse')) @app.debug("Registering Route ./routes/api_routes/spotify") @site.use("/api/spotify", require('./routes/api_routes/spotify')) @app.debug("Registering Route ./routes/api_routes/electron") @site.use("/api/electron", require('./routes/api_routes/electron')) @app.debug("Registering Route ./routes/api_routes/search") @site.use("/api/search", require('./routes/api_routes/search')) @app.debug("Registering Route ./routes/api_routes/message_history") @site.use("/api/message_history", require('./routes/api_routes/message_history')) @app.debug("Registering Route ./routes/api_routes/twitch") @site.use("/twitch", require('./routes/twitch')) @app.debug("Registering Route ./routes/api_routes/destiny2") @site.use("/destiny2", require('./routes/destiny2')) @app.debug("Registering Routes Complete") #redirect for when adding bot @site.get("/redirect", (req, res) -> #code = req.query.code guildId = req.query.guild_id #console.log req res.end(JSON.stringify({guildId: guildId, connected: true})) ) module.exports = WebServer
73057
morgan = require 'morgan' express = require "express" fs = require 'fs' nib = require 'nib' stylus = require 'stylus' compression = require 'compression' serveStatic = require 'serve-static' bodyParser = require('body-parser') cookieParser = require('cookie-parser') session = require('express-session') passport = require 'passport' RedisStore = require('connect-redis')(session) flash = require('connect-flash') class WebServer constructor: (@app) -> start: () -> self = @ @site = express() @site.use(morgan('\[DEBUG\]\['+new Date().getDate()+"\/"+(parseInt(new Date().getMonth())+1)+"\/"+new Date().getFullYear()+' \] :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms')) compile = (str, path) -> stylus(str).set('filename',path).set("compress",true).use(nib()) @app.debug("Setting Views Directory") @site.set('views', __dirname+'/views') @app.debug("Setting View Engine") @site.set('view engine', 'pug') @app.debug("Setting Stylus Middleware") @site.use(stylus.middleware({ src: __dirname + '/static', compile: compile }) ) @app.debug("Setting Static File Directory Location") @site.use(serveStatic(__dirname + '/static')) @site.use(serveStatic(__dirname + '/static/img', { maxAge: 86400000 })) @app.debug("Setting Response Headers") @site.use((req, res, next) -> res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, PATCH, PUT') res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type') res.setHeader('Access-Control-Allow-Credentials', true) res.setHeader('X-Cluster-Identifier', process.pid) next() ) @app.debug("Setting Compression") @site.use(compression()) @site.use(bodyParser.json({limit: "10mb"})); @site.use(bodyParser.urlencoded({ extended: false, limit: "10mb"})) @app.debug("Setting up Cookie Parser") @site.use(cookieParser("9`hIi6Z89*0gMHfYqLEJGfWMCK(d9YM0C")) @app.debug("Setting Up Session with Redis Storage") @site.use(session({ secret: '<KEY>', resave: false, saveUninitialized: true, store: new RedisStore({ host: "localhost", port: 6379 }) })) @app.debug("Setting Up Connect-Flash") @site.use(flash()) @app.debug("Initializing Passport") @site.use(passport.initialize()) @app.debug("Initializing Passport Sessions") @site.use(passport.session()) @site.locals.motorbot = self.app #Express Routers @app.debug("Registering Route ./routes/playlistv2") @site.use("/", require('./routes/playlistv2')) @app.debug("Registering Route ./routes/loginflow") @site.use("/loginflow", require('./routes/loginflow')) @app.debug("Registering Route ./routes/api_routes/oauth2") @site.use("/api/oauth2", require('./routes/api_routes/oauth2')) @app.debug("Registering Route ./routes/api_routes/music") @site.use("/api/music", require('./routes/api_routes/music')) @app.debug("Registering Route ./routes/api_routes/playlist") @site.use("/api/playlist", require('./routes/api_routes/playlist')) @app.debug("Registering Route ./routes/api_routes/user") @site.use("/api/user", require('./routes/api_routes/user')) @app.debug("Registering Route ./routes/api_routes/queue") @site.use("/api/queue", require('./routes/api_routes/queue')) @app.debug("Registering Route ./routes/api_routes/motorbot") @site.use("/api/motorbot", require('./routes/api_routes/motorbot')) @app.debug("Registering Route ./routes/api_routes/browse") @site.use("/api/browse", require('./routes/api_routes/browse')) @app.debug("Registering Route ./routes/api_routes/spotify") @site.use("/api/spotify", require('./routes/api_routes/spotify')) @app.debug("Registering Route ./routes/api_routes/electron") @site.use("/api/electron", require('./routes/api_routes/electron')) @app.debug("Registering Route ./routes/api_routes/search") @site.use("/api/search", require('./routes/api_routes/search')) @app.debug("Registering Route ./routes/api_routes/message_history") @site.use("/api/message_history", require('./routes/api_routes/message_history')) @app.debug("Registering Route ./routes/api_routes/twitch") @site.use("/twitch", require('./routes/twitch')) @app.debug("Registering Route ./routes/api_routes/destiny2") @site.use("/destiny2", require('./routes/destiny2')) @app.debug("Registering Routes Complete") #redirect for when adding bot @site.get("/redirect", (req, res) -> #code = req.query.code guildId = req.query.guild_id #console.log req res.end(JSON.stringify({guildId: guildId, connected: true})) ) module.exports = WebServer
true
morgan = require 'morgan' express = require "express" fs = require 'fs' nib = require 'nib' stylus = require 'stylus' compression = require 'compression' serveStatic = require 'serve-static' bodyParser = require('body-parser') cookieParser = require('cookie-parser') session = require('express-session') passport = require 'passport' RedisStore = require('connect-redis')(session) flash = require('connect-flash') class WebServer constructor: (@app) -> start: () -> self = @ @site = express() @site.use(morgan('\[DEBUG\]\['+new Date().getDate()+"\/"+(parseInt(new Date().getMonth())+1)+"\/"+new Date().getFullYear()+' \] :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms')) compile = (str, path) -> stylus(str).set('filename',path).set("compress",true).use(nib()) @app.debug("Setting Views Directory") @site.set('views', __dirname+'/views') @app.debug("Setting View Engine") @site.set('view engine', 'pug') @app.debug("Setting Stylus Middleware") @site.use(stylus.middleware({ src: __dirname + '/static', compile: compile }) ) @app.debug("Setting Static File Directory Location") @site.use(serveStatic(__dirname + '/static')) @site.use(serveStatic(__dirname + '/static/img', { maxAge: 86400000 })) @app.debug("Setting Response Headers") @site.use((req, res, next) -> res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, PATCH, PUT') res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type') res.setHeader('Access-Control-Allow-Credentials', true) res.setHeader('X-Cluster-Identifier', process.pid) next() ) @app.debug("Setting Compression") @site.use(compression()) @site.use(bodyParser.json({limit: "10mb"})); @site.use(bodyParser.urlencoded({ extended: false, limit: "10mb"})) @app.debug("Setting up Cookie Parser") @site.use(cookieParser("9`hIi6Z89*0gMHfYqLEJGfWMCK(d9YM0C")) @app.debug("Setting Up Session with Redis Storage") @site.use(session({ secret: 'PI:KEY:<KEY>END_PI', resave: false, saveUninitialized: true, store: new RedisStore({ host: "localhost", port: 6379 }) })) @app.debug("Setting Up Connect-Flash") @site.use(flash()) @app.debug("Initializing Passport") @site.use(passport.initialize()) @app.debug("Initializing Passport Sessions") @site.use(passport.session()) @site.locals.motorbot = self.app #Express Routers @app.debug("Registering Route ./routes/playlistv2") @site.use("/", require('./routes/playlistv2')) @app.debug("Registering Route ./routes/loginflow") @site.use("/loginflow", require('./routes/loginflow')) @app.debug("Registering Route ./routes/api_routes/oauth2") @site.use("/api/oauth2", require('./routes/api_routes/oauth2')) @app.debug("Registering Route ./routes/api_routes/music") @site.use("/api/music", require('./routes/api_routes/music')) @app.debug("Registering Route ./routes/api_routes/playlist") @site.use("/api/playlist", require('./routes/api_routes/playlist')) @app.debug("Registering Route ./routes/api_routes/user") @site.use("/api/user", require('./routes/api_routes/user')) @app.debug("Registering Route ./routes/api_routes/queue") @site.use("/api/queue", require('./routes/api_routes/queue')) @app.debug("Registering Route ./routes/api_routes/motorbot") @site.use("/api/motorbot", require('./routes/api_routes/motorbot')) @app.debug("Registering Route ./routes/api_routes/browse") @site.use("/api/browse", require('./routes/api_routes/browse')) @app.debug("Registering Route ./routes/api_routes/spotify") @site.use("/api/spotify", require('./routes/api_routes/spotify')) @app.debug("Registering Route ./routes/api_routes/electron") @site.use("/api/electron", require('./routes/api_routes/electron')) @app.debug("Registering Route ./routes/api_routes/search") @site.use("/api/search", require('./routes/api_routes/search')) @app.debug("Registering Route ./routes/api_routes/message_history") @site.use("/api/message_history", require('./routes/api_routes/message_history')) @app.debug("Registering Route ./routes/api_routes/twitch") @site.use("/twitch", require('./routes/twitch')) @app.debug("Registering Route ./routes/api_routes/destiny2") @site.use("/destiny2", require('./routes/destiny2')) @app.debug("Registering Routes Complete") #redirect for when adding bot @site.get("/redirect", (req, res) -> #code = req.query.code guildId = req.query.guild_id #console.log req res.end(JSON.stringify({guildId: guildId, connected: true})) ) module.exports = WebServer
[ { "context": "ture.hu':\n 'editor':\n 'completions': [\n 'Jellemzล‘:'\n 'Hรกttรฉr:'\n 'Pรฉlda:'\n 'Forgatรณkรถ", "end": 76, "score": 0.6974369287490845, "start": 68, "tag": "NAME", "value": "Jellemzล‘" }, { "context": " 'completions': [\n 'Jellemzล‘:'\n 'Hรกttรฉr:'\n 'Pรฉlda:'\n 'Forgatรณkรถnyv:'\n 'For", "end": 92, "score": 0.582495391368866, "start": 90, "tag": "NAME", "value": "รฉr" }, { "context": " 'Forgatรณkรถnyv vรกzlat:'\n 'Pรฉldรกk:'\n 'Amennyiben '\n 'Adott '\n 'Majd '\n 'Ha '\n ", "end": 194, "score": 0.9994519948959351, "start": 184, "tag": "NAME", "value": "Amennyiben" }, { "context": "zlat:'\n 'Pรฉldรกk:'\n 'Amennyiben '\n 'Adott '\n 'Majd '\n 'Ha '\n 'Amikor '\n ", "end": 209, "score": 0.9989820718765259, "start": 204, "tag": "NAME", "value": "Adott" }, { "context": "รฉldรกk:'\n 'Amennyiben '\n 'Adott '\n 'Majd '\n 'Ha '\n 'Amikor '\n 'Akkor '\n ", "end": 223, "score": 0.9993833899497986, "start": 219, "tag": "NAME", "value": "Majd" }, { "context": "'Amennyiben '\n 'Adott '\n 'Majd '\n 'Ha '\n 'Amikor '\n 'Akkor '\n 'De '\n ", "end": 235, "score": 0.5819997191429138, "start": 233, "tag": "NAME", "value": "Ha" }, { "context": "'\n 'Adott '\n 'Majd '\n 'Ha '\n 'Amikor '\n 'Akkor '\n 'De '\n 'ร‰s '\n ]\n ", "end": 251, "score": 0.9987831115722656, "start": 245, "tag": "NAME", "value": "Amikor" }, { "context": "\n 'Majd '\n 'Ha '\n 'Amikor '\n 'Akkor '\n 'De '\n 'ร‰s '\n ]\n 'increaseInde", "end": 266, "score": 0.6662402153015137, "start": 261, "tag": "NAME", "value": "Akkor" } ]
settings/language-gherkin_hu.cson
mackoj/language-gherkin-i18n
17
'.text.gherkin.feature.hu': 'editor': 'completions': [ 'Jellemzล‘:' 'Hรกttรฉr:' 'Pรฉlda:' 'Forgatรณkรถnyv:' 'Forgatรณkรถnyv vรกzlat:' 'Pรฉldรกk:' 'Amennyiben ' 'Adott ' 'Majd ' 'Ha ' 'Amikor ' 'Akkor ' 'De ' 'ร‰s ' ] 'increaseIndentPattern': 'Pรฉlda: .*' 'Forgatรณkรถnyv: .*' 'commentStart': '# '
41205
'.text.gherkin.feature.hu': 'editor': 'completions': [ '<NAME>:' 'Hรกtt<NAME>:' 'Pรฉlda:' 'Forgatรณkรถnyv:' 'Forgatรณkรถnyv vรกzlat:' 'Pรฉldรกk:' '<NAME> ' '<NAME> ' '<NAME> ' '<NAME> ' '<NAME> ' '<NAME> ' 'De ' 'ร‰s ' ] 'increaseIndentPattern': 'Pรฉlda: .*' 'Forgatรณkรถnyv: .*' 'commentStart': '# '
true
'.text.gherkin.feature.hu': 'editor': 'completions': [ 'PI:NAME:<NAME>END_PI:' 'HรกttPI:NAME:<NAME>END_PI:' 'Pรฉlda:' 'Forgatรณkรถnyv:' 'Forgatรณkรถnyv vรกzlat:' 'Pรฉldรกk:' '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 ' 'De ' 'ร‰s ' ] 'increaseIndentPattern': 'Pรฉlda: .*' 'Forgatรณkรถnyv: .*' 'commentStart': '# '
[ { "context": "exports =\n meta:\n name: \"speech\"\n author: \"Joseph\"\n version: \"0.0.1\"\n description: \"text to s", "end": 125, "score": 0.9991047978401184, "start": 119, "tag": "NAME", "value": "Joseph" } ]
node_modules/status/lib/plugins/speech.coffee
DORCAS12345/lamisplus-angular
0
{exec} = require "child_process" {which} = require "fractal" module.exports = meta: name: "speech" author: "Joseph" version: "0.0.1" description: "text to speech using festival" speak: (text)-> return @error 'Missing text argument' unless typeof text is 'string' return @error 'festival is not installed' unless which 'festival' return @error 'echo is not installed' unless which 'echo' exec "echo #{text} | festival --tts", (err, stdout) => return @error err if err @done {spoke: text}
81901
{exec} = require "child_process" {which} = require "fractal" module.exports = meta: name: "speech" author: "<NAME>" version: "0.0.1" description: "text to speech using festival" speak: (text)-> return @error 'Missing text argument' unless typeof text is 'string' return @error 'festival is not installed' unless which 'festival' return @error 'echo is not installed' unless which 'echo' exec "echo #{text} | festival --tts", (err, stdout) => return @error err if err @done {spoke: text}
true
{exec} = require "child_process" {which} = require "fractal" module.exports = meta: name: "speech" author: "PI:NAME:<NAME>END_PI" version: "0.0.1" description: "text to speech using festival" speak: (text)-> return @error 'Missing text argument' unless typeof text is 'string' return @error 'festival is not installed' unless which 'festival' return @error 'echo is not installed' unless which 'echo' exec "echo #{text} | festival --tts", (err, stdout) => return @error err if err @done {spoke: text}
[ { "context": " 'vanilla'\n name: 'Vanilla Bootstrap'\n author: 'Twitter'\n checksum: crypto.createHash('md5').update('').", "end": 411, "score": 0.7878953218460083, "start": 404, "tag": "NAME", "value": "Twitter" } ]
server/install-predefined-themes.coffee
TAPevents/Meteorstrap
5
@Meteorstrap = @Meteorstrap || {} fs = Npm.require 'fs' crypto = Npm.require 'crypto' # coffeescript import Themes = Meteorstrap.Themes predefinedThemes = [] Meteorstrap.registerPredefinedTheme = (theme) -> predefinedThemes.push theme # make vanilla the only default theme Meteorstrap.registerPredefinedTheme defaults: {} bootswatch: '' _id: 'vanilla' name: 'Vanilla Bootstrap' author: 'Twitter' checksum: crypto.createHash('md5').update('').digest("hex") #ย empty checksum Meteor.startup -> # check for new/updated themes on startup newThemes = 0 # loop through registered predefined themes for predefinedTheme in predefinedThemes # resolve variables if assetPath is passed if predefinedTheme.assetPath # check the assets path if fs.lstatSync("#{predefinedTheme.assetPath}").isDirectory() thisTheme = {} # get the theme less data for file in fs.readdirSync "#{predefinedTheme.assetPath}" thisTheme[file] = fs.readFileSync("#{predefinedTheme.assetPath}/#{file}").toString() # use a checksum to efficiently update only when theme has changed checksum = crypto.createHash('md5').update(thisTheme['bootswatch.less'] + thisTheme['variables.less']).digest("hex") unless Themes.findOne({_id: predefinedTheme._id, checksum: checksum}) # new/updated theme found, let's update it parsedLessDefaults = {} for line in thisTheme['variables.less'].split('\n') when line.indexOf("@") is 0 keyVar = line.trim().split(';')[0].split(':') parsedLessDefaults["#{keyVar[0].trim()}"] = keyVar[1].trim() # upsert (so we insert if new, update if a checksum is changed) newThemes++ Themes.upsert _id: predefinedTheme._id, name: predefinedTheme.name author: predefinedTheme.author defaults: parsedLessDefaults bootswatch: thisTheme['bootswatch.less'] checksum: checksum predefined: true # passing a theme without assetPath, assume it's already formatted # don't update if the checksum is the same else if !(predefinedTheme.checksum and Themes.findOne({_id: predefinedTheme._id, checksum: predefinedTheme.checksum})) # assume variables and theme are correct already newThemes++ Themes.upsert _id: predefinedTheme._id, name: predefinedTheme.name author: predefinedTheme.author defaults: predefinedTheme.defaults bootswatch: predefinedTheme.bootswatch checksum: predefinedTheme.checksum predefined: true if newThemes # user feedback console.log "Meteorstrap just installed/updated #{newThemes} themes! ๐Ÿ˜Ž" # check to see if we have any defaults set unless Themes.findOne {default: true} Themes.update 'vanilla', $set: default: true
61391
@Meteorstrap = @Meteorstrap || {} fs = Npm.require 'fs' crypto = Npm.require 'crypto' # coffeescript import Themes = Meteorstrap.Themes predefinedThemes = [] Meteorstrap.registerPredefinedTheme = (theme) -> predefinedThemes.push theme # make vanilla the only default theme Meteorstrap.registerPredefinedTheme defaults: {} bootswatch: '' _id: 'vanilla' name: 'Vanilla Bootstrap' author: '<NAME>' checksum: crypto.createHash('md5').update('').digest("hex") #ย empty checksum Meteor.startup -> # check for new/updated themes on startup newThemes = 0 # loop through registered predefined themes for predefinedTheme in predefinedThemes # resolve variables if assetPath is passed if predefinedTheme.assetPath # check the assets path if fs.lstatSync("#{predefinedTheme.assetPath}").isDirectory() thisTheme = {} # get the theme less data for file in fs.readdirSync "#{predefinedTheme.assetPath}" thisTheme[file] = fs.readFileSync("#{predefinedTheme.assetPath}/#{file}").toString() # use a checksum to efficiently update only when theme has changed checksum = crypto.createHash('md5').update(thisTheme['bootswatch.less'] + thisTheme['variables.less']).digest("hex") unless Themes.findOne({_id: predefinedTheme._id, checksum: checksum}) # new/updated theme found, let's update it parsedLessDefaults = {} for line in thisTheme['variables.less'].split('\n') when line.indexOf("@") is 0 keyVar = line.trim().split(';')[0].split(':') parsedLessDefaults["#{keyVar[0].trim()}"] = keyVar[1].trim() # upsert (so we insert if new, update if a checksum is changed) newThemes++ Themes.upsert _id: predefinedTheme._id, name: predefinedTheme.name author: predefinedTheme.author defaults: parsedLessDefaults bootswatch: thisTheme['bootswatch.less'] checksum: checksum predefined: true # passing a theme without assetPath, assume it's already formatted # don't update if the checksum is the same else if !(predefinedTheme.checksum and Themes.findOne({_id: predefinedTheme._id, checksum: predefinedTheme.checksum})) # assume variables and theme are correct already newThemes++ Themes.upsert _id: predefinedTheme._id, name: predefinedTheme.name author: predefinedTheme.author defaults: predefinedTheme.defaults bootswatch: predefinedTheme.bootswatch checksum: predefinedTheme.checksum predefined: true if newThemes # user feedback console.log "Meteorstrap just installed/updated #{newThemes} themes! ๐Ÿ˜Ž" # check to see if we have any defaults set unless Themes.findOne {default: true} Themes.update 'vanilla', $set: default: true
true
@Meteorstrap = @Meteorstrap || {} fs = Npm.require 'fs' crypto = Npm.require 'crypto' # coffeescript import Themes = Meteorstrap.Themes predefinedThemes = [] Meteorstrap.registerPredefinedTheme = (theme) -> predefinedThemes.push theme # make vanilla the only default theme Meteorstrap.registerPredefinedTheme defaults: {} bootswatch: '' _id: 'vanilla' name: 'Vanilla Bootstrap' author: 'PI:NAME:<NAME>END_PI' checksum: crypto.createHash('md5').update('').digest("hex") #ย empty checksum Meteor.startup -> # check for new/updated themes on startup newThemes = 0 # loop through registered predefined themes for predefinedTheme in predefinedThemes # resolve variables if assetPath is passed if predefinedTheme.assetPath # check the assets path if fs.lstatSync("#{predefinedTheme.assetPath}").isDirectory() thisTheme = {} # get the theme less data for file in fs.readdirSync "#{predefinedTheme.assetPath}" thisTheme[file] = fs.readFileSync("#{predefinedTheme.assetPath}/#{file}").toString() # use a checksum to efficiently update only when theme has changed checksum = crypto.createHash('md5').update(thisTheme['bootswatch.less'] + thisTheme['variables.less']).digest("hex") unless Themes.findOne({_id: predefinedTheme._id, checksum: checksum}) # new/updated theme found, let's update it parsedLessDefaults = {} for line in thisTheme['variables.less'].split('\n') when line.indexOf("@") is 0 keyVar = line.trim().split(';')[0].split(':') parsedLessDefaults["#{keyVar[0].trim()}"] = keyVar[1].trim() # upsert (so we insert if new, update if a checksum is changed) newThemes++ Themes.upsert _id: predefinedTheme._id, name: predefinedTheme.name author: predefinedTheme.author defaults: parsedLessDefaults bootswatch: thisTheme['bootswatch.less'] checksum: checksum predefined: true # passing a theme without assetPath, assume it's already formatted # don't update if the checksum is the same else if !(predefinedTheme.checksum and Themes.findOne({_id: predefinedTheme._id, checksum: predefinedTheme.checksum})) # assume variables and theme are correct already newThemes++ Themes.upsert _id: predefinedTheme._id, name: predefinedTheme.name author: predefinedTheme.author defaults: predefinedTheme.defaults bootswatch: predefinedTheme.bootswatch checksum: predefinedTheme.checksum predefined: true if newThemes # user feedback console.log "Meteorstrap just installed/updated #{newThemes} themes! ๐Ÿ˜Ž" # check to see if we have any defaults set unless Themes.findOne {default: true} Themes.update 'vanilla', $set: default: true
[ { "context": " : () ->\n [\n {\n name : \"Personality\"\n id : \"abc123\"\n defau", "end": 134, "score": 0.9942775964736938, "start": 123, "tag": "NAME", "value": "Personality" }, { "context": " provider:\n id:'do'\n name:\"Personal\"\n icon:'custom'\n endpoint ", "end": 288, "score": 0.621252715587616, "start": 280, "tag": "NAME", "value": "Personal" }, { "context": " {label:'API Key', key:'api_key', val:\"asdf12345asdf12344\" }\n {label:'User Name', key:'user', va", "end": 1002, "score": 0.9334409236907959, "start": 984, "tag": "KEY", "value": "asdf12345asdf12344" }, { "context": "\n {label:'User Name', key:'user', val:\"john\" }\n {label:'Password', key:'pass', val", "end": 1059, "score": 0.7673045992851257, "start": 1055, "tag": "NAME", "value": "john" }, { "context": "}\n {label:'Password', key:'pass', val:\"morovitch\" }\n ]\n meta:\n instru", "end": 1120, "score": 0.997124195098877, "start": 1111, "tag": "PASSWORD", "value": "morovitch" }, { "context": " : \"Work - Delorum\"\n id : \"xyz789\"\n defaultRegion : {\"New York 1\", id: \"ny", "end": 1871, "score": 0.7102537751197815, "start": 1868, "tag": "USERNAME", "value": "789" }, { "context": " getUnofficialProvider : () ->\n {\n name:\"Ted's Hosting\"\n icon:'digital-ocean'\n id:", "end": 2614, "score": 0.5684908628463745, "start": 2613, "tag": "NAME", "value": "T" }, { "context": " key:'user_name'}\n {label:'Password', key:'pass'}\n ]\n regions:[\n {name: \"Ted's H", "end": 2820, "score": 0.9979636669158936, "start": 2816, "tag": "PASSWORD", "value": "pass" } ]
stage/shim/providers.coffee
nanobox-io/nanobox-dash-ui-provider-manager
0
module.exports = class ProvidersShim constructor: () -> getAccounts : () -> [ { name : "Personality" id : "abc123" defaultRegion : {name:"Amsterdam 2", id:"am2"} provider: id:'do' name:"Personal" icon:'custom' endpoint : "http://some.endpoint.com/asdf" defaultRegion : {name: "New York 1", id: "nyc1"} regions: [ {name: "New York 1", id: "nyc1"} {name: "New York 2", id: "nyc2"} {name: "New York 3", id: "nyc3"} {name: "Amsterdam 2", id: "am2"} {name: "Amsterdam 3", id: "am3"} {name: "San Francisco", id: "sfo1"} {name: "Singapore", id: "s1"} {name: "London", id: "l1"} {name: "Frankfurt", id: "f1"} {name: "Toronto", id: "t1"} ] authFields : [ {label:'API Key', key:'api_key', val:"asdf12345asdf12344" } {label:'User Name', key:'user', val:"john" } {label:'Password', key:'pass', val:"morovitch" } ] meta: instructions:'Grab your credentials on <a href="#">Ted\'s main site</a> , or view Ted\'s<a href="#">full guide</a>.' apps : [ {name:"guides", managePath:"#", removePath:"#"} {name:"app 1", managePath:"#", removePath:"#"} {name:"app 2", managePath:"#", removePath:"#"} {name:"app 3", managePath:"#", removePath:"#"} {name:"app 4", managePath:"#", removePath:"#"} {name:"app 5", managePath:"#", removePath:"#"} ] meta:{ serverOrderConfig: foo : "bar" baz : "foo" } } , { name : "Work - Delorum" id : "xyz789" defaultRegion : {"New York 1", id: "nyc1"} provider : name:'Google Compute' icon:'packet' id:'linode' authFields:[ {label:'API Key', key:'api_key', val:"asdf" } ] regions:[ {name: "New York 1", id:"ASDF" } {name: "New York 2", id:"ASDF" } {name: "New York 3", id:"ASDF" } ] meta: instructions:'Create an API key on your <a href="#">Google Compute API page</a>, or view the <a href="//docs.nanobox.io">full guide</a>.' defaultRegion : {name:"Singapore", id:"s1"} apps : [ ] } ] getUnofficialProvider : () -> { name:"Ted's Hosting" icon:'digital-ocean' id:'do' authFields:[ {label:"Ted's Fav Color", key:'fav_color'} {label:'User Name', key:'user_name'} {label:'Password', key:'pass'} ] regions:[ {name: "Ted's House", id: "ted1"} {name: "Ted's Basement", id: "ted2"} {name: "Ted's Attic", id: "ted3"} ] meta: instructions:'Grab your credentials on <a href="#">Ted\'s main site</a> , or view Ted\'s<a href="#">full guide</a>.' }
204317
module.exports = class ProvidersShim constructor: () -> getAccounts : () -> [ { name : "<NAME>" id : "abc123" defaultRegion : {name:"Amsterdam 2", id:"am2"} provider: id:'do' name:"<NAME>" icon:'custom' endpoint : "http://some.endpoint.com/asdf" defaultRegion : {name: "New York 1", id: "nyc1"} regions: [ {name: "New York 1", id: "nyc1"} {name: "New York 2", id: "nyc2"} {name: "New York 3", id: "nyc3"} {name: "Amsterdam 2", id: "am2"} {name: "Amsterdam 3", id: "am3"} {name: "San Francisco", id: "sfo1"} {name: "Singapore", id: "s1"} {name: "London", id: "l1"} {name: "Frankfurt", id: "f1"} {name: "Toronto", id: "t1"} ] authFields : [ {label:'API Key', key:'api_key', val:"<KEY>" } {label:'User Name', key:'user', val:"<NAME>" } {label:'Password', key:'pass', val:"<PASSWORD>" } ] meta: instructions:'Grab your credentials on <a href="#">Ted\'s main site</a> , or view Ted\'s<a href="#">full guide</a>.' apps : [ {name:"guides", managePath:"#", removePath:"#"} {name:"app 1", managePath:"#", removePath:"#"} {name:"app 2", managePath:"#", removePath:"#"} {name:"app 3", managePath:"#", removePath:"#"} {name:"app 4", managePath:"#", removePath:"#"} {name:"app 5", managePath:"#", removePath:"#"} ] meta:{ serverOrderConfig: foo : "bar" baz : "foo" } } , { name : "Work - Delorum" id : "xyz789" defaultRegion : {"New York 1", id: "nyc1"} provider : name:'Google Compute' icon:'packet' id:'linode' authFields:[ {label:'API Key', key:'api_key', val:"asdf" } ] regions:[ {name: "New York 1", id:"ASDF" } {name: "New York 2", id:"ASDF" } {name: "New York 3", id:"ASDF" } ] meta: instructions:'Create an API key on your <a href="#">Google Compute API page</a>, or view the <a href="//docs.nanobox.io">full guide</a>.' defaultRegion : {name:"Singapore", id:"s1"} apps : [ ] } ] getUnofficialProvider : () -> { name:"<NAME>ed's Hosting" icon:'digital-ocean' id:'do' authFields:[ {label:"Ted's Fav Color", key:'fav_color'} {label:'User Name', key:'user_name'} {label:'Password', key:'<PASSWORD>'} ] regions:[ {name: "Ted's House", id: "ted1"} {name: "Ted's Basement", id: "ted2"} {name: "Ted's Attic", id: "ted3"} ] meta: instructions:'Grab your credentials on <a href="#">Ted\'s main site</a> , or view Ted\'s<a href="#">full guide</a>.' }
true
module.exports = class ProvidersShim constructor: () -> getAccounts : () -> [ { name : "PI:NAME:<NAME>END_PI" id : "abc123" defaultRegion : {name:"Amsterdam 2", id:"am2"} provider: id:'do' name:"PI:NAME:<NAME>END_PI" icon:'custom' endpoint : "http://some.endpoint.com/asdf" defaultRegion : {name: "New York 1", id: "nyc1"} regions: [ {name: "New York 1", id: "nyc1"} {name: "New York 2", id: "nyc2"} {name: "New York 3", id: "nyc3"} {name: "Amsterdam 2", id: "am2"} {name: "Amsterdam 3", id: "am3"} {name: "San Francisco", id: "sfo1"} {name: "Singapore", id: "s1"} {name: "London", id: "l1"} {name: "Frankfurt", id: "f1"} {name: "Toronto", id: "t1"} ] authFields : [ {label:'API Key', key:'api_key', val:"PI:KEY:<KEY>END_PI" } {label:'User Name', key:'user', val:"PI:NAME:<NAME>END_PI" } {label:'Password', key:'pass', val:"PI:PASSWORD:<PASSWORD>END_PI" } ] meta: instructions:'Grab your credentials on <a href="#">Ted\'s main site</a> , or view Ted\'s<a href="#">full guide</a>.' apps : [ {name:"guides", managePath:"#", removePath:"#"} {name:"app 1", managePath:"#", removePath:"#"} {name:"app 2", managePath:"#", removePath:"#"} {name:"app 3", managePath:"#", removePath:"#"} {name:"app 4", managePath:"#", removePath:"#"} {name:"app 5", managePath:"#", removePath:"#"} ] meta:{ serverOrderConfig: foo : "bar" baz : "foo" } } , { name : "Work - Delorum" id : "xyz789" defaultRegion : {"New York 1", id: "nyc1"} provider : name:'Google Compute' icon:'packet' id:'linode' authFields:[ {label:'API Key', key:'api_key', val:"asdf" } ] regions:[ {name: "New York 1", id:"ASDF" } {name: "New York 2", id:"ASDF" } {name: "New York 3", id:"ASDF" } ] meta: instructions:'Create an API key on your <a href="#">Google Compute API page</a>, or view the <a href="//docs.nanobox.io">full guide</a>.' defaultRegion : {name:"Singapore", id:"s1"} apps : [ ] } ] getUnofficialProvider : () -> { name:"PI:NAME:<NAME>END_PIed's Hosting" icon:'digital-ocean' id:'do' authFields:[ {label:"Ted's Fav Color", key:'fav_color'} {label:'User Name', key:'user_name'} {label:'Password', key:'PI:PASSWORD:<PASSWORD>END_PI'} ] regions:[ {name: "Ted's House", id: "ted1"} {name: "Ted's Basement", id: "ted2"} {name: "Ted's Attic", id: "ted3"} ] meta: instructions:'Grab your credentials on <a href="#">Ted\'s main site</a> , or view Ted\'s<a href="#">full guide</a>.' }
[ { "context": " code: \"\"\"\n // 'B rose' by Guy John (@rumblesan)\n // Mozilla Festiva", "end": 7232, "score": 0.9997563362121582, "start": 7224, "tag": "NAME", "value": "Guy John" }, { "context": "ode: \"\"\"\n // 'B rose' by Guy John (@rumblesan)\n // Mozilla Festival 2012\n ", "end": 7244, "score": 0.9995891451835632, "start": 7233, "tag": "USERNAME", "value": "(@rumblesan" }, { "context": "2012\n // adapted from 'A rose' by Lib4tech\n \n background r", "end": 7343, "score": 0.7164574265480042, "start": 7335, "tag": "USERNAME", "value": "Lib4tech" }, { "context": " // 'Cheese and olives' by\n // Davina Tirvengadum\n // Mozilla festival 2012\n ", "end": 7894, "score": 0.9998921155929565, "start": 7876, "tag": "NAME", "value": "Davina Tirvengadum" } ]
coffee/core/program-loader.coffee
xinaesthete/livecodelab
1
### ## ProgramLoader takes care of managing the URL and editor content ## when the user navigates through demos and examples - either by ## selecting menu entries, or by clicking back/forward arrow, or by ## landing on a URL with a hashtag. ### define [ 'Three.Detector' ], ( Detector ) -> class ProgramLoader constructor: (@eventRouter, @texteditor, @liveCodeLabCoreInstance) -> @lastHash = "" userWarnedAboutWebglExamples = false @programs = demos: {} tutorials: {} @programs.demos.aBoxTest = submenu: "Evolutionary" title: "Hello Box" code: """ // g() function declares a gene. First argument is required to give it a name. // I recommend using brackets to enclose arguments for this... box g('boxSize') // two more arguments can be passed to g() to define min & max values // otherwise they default to min=0, max=1. move g('moveX'), g('moveY', -0.5, 1.3) // if the same gene name is used more than once, the same value will be returned box g('boxSize') """ @programs.demos.repitition = submenu: "Evolutionary" title: "Some boxes..." code: """ 5 times -> โ–ถmove g('moveX'), g('moveY') โ–ถbox """ @programs.demos.functions = submenu: "Evolutionary" title: "Functions" code: """ //exercise: change this to draw a variable number of boxes... boxes = -> โ–ถ5 times -> โ–ถโ–ถmove g('moveX'), g('moveY') โ–ถโ–ถrotate g('rotX'), g('rotY') โ–ถโ–ถbox scale 0.2 boxes //notice that these transformations still encorporate the combined //effect of transforms from the boxes function... //resetMatrix //uncommenting this line will counter-act that... //...but it will also loose the initial scale... move 2, 0 boxes """ @programs.demos.feedback = submenu: "Evolutionary" title: "Feedback" code: """ // video feedback uses the image rendered in the previous frame // as source material for generating the current frame // ... interesting forms of chaos can result ... // ambientLight animSpeed 0.1 โœ“doOnce โ–ถmutate 0.5 move 0, -1 โ–ถbox 0.3, 1, 0.1 //note that the resulting image will be quite dependant on aspect ratio... //so tweak numbers to get something not blown out / too decayed... feedback rotate 0, 0, g('r1', -Math.PI, Math.PI) โ–ถbox 1.6 move 0.3, 0 rotate 0, 0, g('r2', -Math.PI, Math.PI) โ–ถbox 2.8, 2.6, 0.3 """ @programs.demos.feedback2 = submenu: "Evolutionary" title: "Feedback 2" code: """ ambientLight i = 0 noStroke fill g('r'+i)*255, g('g'+i)*255, g('b'+i)*255 move 0, -1 โ–ถball 0.3, 1, 0.1 feedback move 0.2, 0 rotate 0, 0, -0.6 โ–ถbox 1.6 30 times โ–ถscale 0.8 โ–ถi++ โ–ถfill g('r'+i)*255, g('g'+i)*255, g('b'+i)*255, g('a'+i, 150, 255) โ–ถmove g('m', 0.2, 0.5) โ–ถrotate time/2, 0, g('r2', -Math.PI, Math.PI) โ–ถbox 2.8, 2.6, 0.5 """ @programs.demos.tendrils = submenu: "Evolutionary" title: "Tendrils" code: """ //a thought/exercise: how about spiky tendrils? //or making this the head of a creature... ambientLight animSpeed 0.01 โœ“doOnce mutate 1 arm = (rx, ry) -> โ–ถscale 1 โ–ถโ–ถ15 times โ–ถโ–ถโ–ถ//notice that the g('m') will have the same value for all parts of all arms โ–ถโ–ถโ–ถmove g('m') โ–ถโ–ถโ–ถrotate rx, ry โ–ถโ–ถโ–ถscale 0.8 โ–ถโ–ถโ–ถball scale 0.2 nArms = (n, id) -> โ–ถi = 0 โ–ถn times โ–ถโ–ถi++ โ–ถโ–ถrotate 0, 0, 2*Math.PI/n โ–ถโ–ถ//each arm is given unique genes for rx & ry โ–ถโ–ถarm g('rx'+i+id), g('ry'+i+id) nArms(20, 'a') """ @programs.demos.parmlsys = submenu: "Evolutionary" title: "Parametric L-System" code: """ PI = Math.PI rule = "Fx-[[FX]+][+FX]+X" background white F = -> โ–ถrotate g('wx', -0.1, 0.1), g('wy', -0.1, 0.1), g('wz', -0.1, 0.1) โ–ถmove 0, 0.3 โ–ถfill black ball 0.03, 0.6, 0.03 โ–ถmove 0, 0.3 L = -> โ–ถscale g('Ls', 0.6, 1.02) โ–ถrotate 0, 0, -g('bendl') * PI/6 R = -> โ–ถscale g('Rs', 0.6, 1.02) โ–ถrotate g('brx')*PI/6, g('bry')*PI/6, g('brz')*PI/6 leaf = -> ball 0.1, 0.2, 0.1 limit = min(abs(8-time*10%16), 4.5) //n keeps track of recursion depth X = (n) -> โ–ถfraction = if n > limit - 1 then pow(limit - floor(limit), 0.3) else 1 โ–ถif n++ > limit then leaf โ–ถelse scale fraction, doOp c, n for c in rule animSpeed 0.01 โœ“doOnce โ–ถmutate 1 //sempre idem, sed non eodum modo //always the same, //but never in the same way if limit <0.2 then mutate 1 doOp = (c, n=0) -> โ–ถswitch c โ–ถโ–ถwhen 'F' then F โ–ถโ–ถwhen '-' then L โ–ถโ–ถwhen '+' then R โ–ถโ–ถwhen '[' then pushMatrix โ–ถโ–ถwhen ']' then popMatrix โ–ถโ–ถwhen 'X' then X n โ–ถโ–ถwhen '(' then stroke green, 100, fill cyan, 80, ball 0.5 rotate move 0, 2, ball 0.1, 0.2, 0.1 โ–ถโ–ถelse rotate 0, 0, PI, fill g('fr')*255, g('fg')*255, g('fb')*255, 200 feedback box 2, 2, 0.2 noStroke scale 0.7 3 times โ–ถpushMatrix โ–ถdoOp "X" โ–ถpopMatrix โ–ถrotate 0, 0, 2*PI/3 """ @programs.demos.roseDemo = submenu: "Basic" title: "Rose" code: """ // 'B rose' by Guy John (@rumblesan) // Mozilla Festival 2012 // adapted from 'A rose' by Lib4tech background red scale 1.5 animationStyle paintOver rotate frame/100 fill 255-((frame/2)%255),0,0 stroke 255-((frame/2)%255),0,0 scale 1-((frame/2)%255) / 255 box """ @programs.demos.cheeseAndOlivesDemo = submenu: "Basic" title: "Cheese and olives" code: """ // 'Cheese and olives' by // Davina Tirvengadum // Mozilla festival 2012 background white scale .3 move 0,-1 fill yellow stroke black rotate strokeSize 3 line 4 box rotate 2,3 move 0,3 scale .3 fill black stroke black ball rotate 3 move 5 scale 1 fill green stroke green ball rotate 1 move -3 scale 1 fill yellow stroke yellow ball """ @programs.demos.simpleCubeDemo = submenu: "Basic" title: "Simple cube" code: """ // there you go! // a simple cube! background yellow rotate 0,time/2,time/2 box """ @programs.demos.webgltwocubesDemo = submenu: "WebGL" title: "WebGL: Two cubes" code: """ background 155,255,255 2 times โ–ถrotate 0, 1, time/2 โ–ถbox """ @programs.demos.cubesAndSpikes = submenu: "Basic" title: "Cubes and spikes" code: """ simpleGradient fuchsia,color(100,200,200),yellow scale 2.1 5 times โ–ถrotate 0,1,time/5 โ–ถbox 0.1,0.1,0.1 โ–ถmove 0,0.1,0.1 โ–ถ3 times โ–ถโ–ถrotate 0,1,1 โ–ถโ–ถbox 0.01,0.01,1 """ @programs.demos.webglturbineDemo = submenu: "WebGL" title: "WebGL: Turbine" code: """ background 155,55,255 70 times โ–ถrotate time/100,1,time/100 โ–ถbox """ @programs.demos.webglzfightartDemo = submenu: "WebGL" title: "WebGL: Z-fight!" code: """ // Explore the artifacts // of your GPU! // Go Z-fighting, go! scale 5 rotate fill red box rotate 0.000001 fill yellow box """ @programs.demos.littleSpiralOfCubes = submenu: "Basic" title: "Little spiral" code: """ background orange scale 0.1 10 times โ–ถrotate 0,1,time โ–ถmove 1,1,1 โ–ถbox """ @programs.demos.tentacleDemo = submenu: "Basic" title: "Tentacle" code: """ background 155,255,155 scale 0.15 3 times โ–ถrotate 0,1,1 โ–ถ10 times โ–ถโ–ถrotate 0,1,time โ–ถโ–ถscale 0.9 โ–ถโ–ถmove 1,1,1 โ–ถโ–ถbox """ @programs.demos.lampDemo = submenu: "Basic" title: "Lamp" code: """ animationStyle motionBlur simpleGradient red,yellow,color(255,0,255) //animationStyle paintOver scale 2 rotate time/4, time/4, time/4 90 times โ–ถrotate time/200, time/200, time/200 โ–ถline โ–ถmove 0.5,0,0 โ–ถline โ–ถmove -0.5,0,0 โ–ถline """ @programs.demos.trillionfeathersDemo = submenu: "Basic" title: "A trillion feathers" code: """ animationStyle paintOver move 2,0,0 scale 2 rotate 20 times โ–ถrotate โ–ถmove 0.25,0,0 โ–ถline โ–ถmove -0.5,0,0 โ–ถline """ @programs.demos.monsterblobDemo = submenu: "Basic" title: "Monster blob" code: """ ballDetail 6 animationStyle motionBlur rotate time/5 simpleGradient fuchsia,aqua,yellow 5 times โ–ถrotate 0,1,time/5 โ–ถmove 0.2,0,0 โ–ถ3 times โ–ถโ–ถrotate 1 โ–ถโ–ถball -1 """ @programs.demos.industrialMusicDemo = submenu: "Sound" title: "Sound: Industrial" code: """ bpm 88 play 'alienBeep' ,'zzxz zzzz zzxz zzzz' play 'beepC' ,'zxzz zzzz xzzx xxxz' play 'beepA' ,'zzxz zzzz zzxz zzzz' play 'lowFlash' ,'zzxz zzzz zzzz zzzz' play 'beepB' ,'xzzx zzzz zxzz zxzz' play 'voltage' ,'xzxz zxzz xzxx xzxx' play 'tranceKick' ,'zxzx zzzx xzzz zzxx' """ @programs.demos.overScratch = submenu: "Sound" title: "Sound: Over-scratch" code: """ bpm 108 play 'tranceKick' ,'xzxz zx' play 'tranceKick1' ,'xzxzxzx' play 'scratch' + int(random(14)) ,'x' play 'scratch-med' + int(random(8)) ,'xz' play 'scratch-high' + int(random(2)) ,'xzzz' play 'scratch-rough' + int(random(4)) ,'xz' """ @programs.demos.trySoundsDemo = submenu: "Sound" title: "Sound: Try them all" code: """ bpm 88 // leave this one as base play 'tranceKick' ,'zxzx zzzx xzzz zzxx' // uncomment the sounds you want to try //play 'alienBeep' ,'zzxz zzzz zzxz zzzz' //play 'beep' ,'zzxz zzzz zzxz zzzz' //play 'beep0' ,'zzxz zzzz zzxz zzzz' //play 'beep1' ,'zzxz zzzz zzxz zzzz' //play 'beep2' ,'zzxz zzzz zzxz zzzz' //play 'beep3' ,'zzxz zzzz zzxz zzzz' //play 'bing' ,'zzxz zzzz zzxz zzzz' //play 'ciack' ,'zzxz zzzz zzxz zzzz' //play 'ciack0' ,'zzxz zzzz zzxz zzzz' //play 'ciack1' ,'zzxz zzzz zzxz zzzz' //play 'cosmos' ,'zzxz zzzz zzxz zzzz' //play 'crash' ,'zzxz zzzz zzxz zzzz' //play 'crash0' ,'zzxz zzzz zzxz zzzz' //play 'crash1' ,'zzxz zzzz zzxz zzzz' //play 'crash2' ,'zzxz zzzz zzxz zzzz' //play 'detune' ,'zzxz zzzz zzxz zzzz' //play 'dish' ,'zzxz zzzz zzxz zzzz' //play 'dish0' ,'zzxz zzzz zzxz zzzz' //play 'dish1' ,'zzxz zzzz zzxz zzzz' //play 'dish2' ,'zzxz zzzz zzxz zzzz' //play 'downstairs' ,'zzxz zzzz zzxz zzzz' //play 'glass' ,'zzxz zzzz zzxz zzzz' //play 'highHatClosed' ,'zzxz zzzz zzxz zzzz' //play 'highHatOpen' ,'zzxz zzzz zzxz zzzz' //play 'hiss' ,'zzxz zzzz zzxz zzzz' //play 'hiss0' ,'zzxz zzzz zzxz zzzz' //play 'hiss1' ,'zzxz zzzz zzxz zzzz' //play 'hiss2' ,'zzxz zzzz zzxz zzzz' //play 'lowFlash' ,'zzxz zzzz zzxz zzzz' //play 'lowFlash0' ,'zzxz zzzz zzxz zzzz' //play 'lowFlash1' ,'zzxz zzzz zzxz zzzz' //play 'mouth' ,'zzxz zzzz zzxz zzzz' //play 'mouth0' ,'zzxz zzzz zzxz zzzz' //play 'mouth1' ,'zzxz zzzz zzxz zzzz' //play 'mouth2' ,'zzxz zzzz zzxz zzzz' //play 'mouth3' ,'zzxz zzzz zzxz zzzz' //play 'mouth4' ,'zzxz zzzz zzxz zzzz' //play 'penta0' ,'zzxz zzzz zzxz zzzz' //play 'penta1' ,'zzxz zzzz zzxz zzzz' //play 'penta2' ,'zzxz zzzz zzxz zzzz' //play 'penta3' ,'zzxz zzzz zzxz zzzz' //play 'penta4' ,'zzxz zzzz zzxz zzzz' //play 'penta5' ,'zzxz zzzz zzxz zzzz' //play 'penta6' ,'zzxz zzzz zzxz zzzz' //play 'penta7' ,'zzxz zzzz zzxz zzzz' //play 'penta8' ,'zzxz zzzz zzxz zzzz' //play 'penta9' ,'zzxz zzzz zzxz zzzz' //play 'penta10' ,'zzxz zzzz zzxz zzzz' //play 'penta11' ,'zzxz zzzz zzxz zzzz' //play 'penta12' ,'zzxz zzzz zzxz zzzz' //play 'penta13' ,'zzxz zzzz zzxz zzzz' //play 'penta14' ,'zzxz zzzz zzxz zzzz' //play 'penta15' ,'zzxz zzzz zzxz zzzz' //play 'ride' ,'zzxz zzzz zzxz zzzz' //play 'snap' ,'zzxz zzzz zzxz zzzz' //play 'snap0' ,'zzxz zzzz zzxz zzzz' //play 'snap1' ,'zzxz zzzz zzxz zzzz' //play 'snare' ,'zzxz zzzz zzxz zzzz' //play 'snare0' ,'zzxz zzzz zzxz zzzz' //play 'snare1' ,'zzxz zzzz zzxz zzzz' //play 'snare2' ,'zzxz zzzz zzxz zzzz' //play 'thump' ,'zzxz zzzz zzxz zzzz' //play 'thump0' ,'zzxz zzzz zzxz zzzz' //play 'thump1' ,'zzxz zzzz zzxz zzzz' //play 'thump2' ,'zzxz zzzz zzxz zzzz' //play 'toc' ,'zzxz zzzz zzxz zzzz' //play 'toc0' ,'zzxz zzzz zzxz zzzz' //play 'toc1' ,'zzxz zzzz zzxz zzzz' //play 'tranceKick' ,'zzxz zzzz zzxz zzzz' //play 'tranceKick0' ,'zzxz zzzz zzxz zzzz' //play 'tranceKick1' ,'zzxz zzzz zzxz zzzz' //play 'voltage' ,'zzxz zzzz zzxz zzzz' //play 'warm' ,'zzxz zzzz zzxz zzzz' """ @programs.demos.springysquaresDemo = submenu: "Basic" title: "Springy squares" code: """ animationStyle motionBlur simpleGradient fuchsia,color(100,200,200),yellow scale 0.3 3 times โ–ถmove 0,0,0.5 โ–ถ5 times โ–ถโ–ถrotate time/2 โ–ถโ–ถmove 0.7,0,0 โ–ถโ–ถrect """ @programs.demos.diceDemo = submenu: "Basic" title: "Dice" code: """ animationStyle motionBlur simpleGradient color(255),moccasin,peachpuff stroke 255,100,100,255 fill red,155 move -0.5,0,0 scale 0.3 3 times โ–ถmove 0,0,0.5 โ–ถ1 times โ–ถโ–ถrotate time โ–ถโ–ถmove 2,0,0 โ–ถโ–ถbox """ @programs.demos.webglalmostvoronoiDemo = submenu: "WebGL" title: "WebGL: Almost Voronoi" code: """ scale 10 2 times โ–ถrotate 0,1,time/10 โ–ถball -1 """ @programs.demos.webglshardsDemo = submenu: "WebGL" title: "WebGL: Shards" code: """ scale 10 fill 0 strokeSize 7 5 times โ–ถrotate 0,1,time/20 โ–ถball โ–ถrotate 0,1,1 โ–ถball -1.01 """ @programs.demos.webglredthreadsDemo = submenu: "WebGL" title: "WebGL: Red threads" code: """ scale 10.5 background black stroke red noFill strokeSize 7 5 times โ–ถrotate time/20 โ–ถball โ–ถrotate 0,1,1 โ–ถball """ @programs.demos.webglribbon = submenu: "WebGL" title: "WebGL: Ribbon" code: """ turns = 1 // 1 = Mรถbius strip detail = 200 // try up to 400 or so speed = 0.5 ambientLight 255,0,0 // comment out to see the seam background black rotate time /5 scale 0.6 for i in [0...detail] โ–ถrotate 0,0,2*Math.PI/(detail) โ–ถmove 2,0,0 โ–ถโ–ถrotate 0,turns*i*Math.PI/(detail)+time*speed,0 โ–ถโ–ถrect 1,0.04+1/detail """ @programs.demos.theeye = submenu: "WebGL" title: "WebGL: The eye" code: """ turns = Math.floor(time/10)%6 detail = 100 speed = 3 if time%10 < 5 โ–ถambientLight 255,255,255 background black rotate time /5 for i in [0...detail] โ–ถrotate 0,0,2*Math.PI/(detail) โ–ถmove 2,0,0 โ–ถโ–ถrotate turns*i*Math.PI/(detail)+time*speed,0,0 โ–ถโ–ถrect 1 """ @programs.demos.webglnuclearOctopusDemo = submenu: "WebGL" title: "WebGL: Nuclear octopus" code: """ simpleGradient black,color(0,0,(time/.005)%255),black scale 0.2 move 5,0,0 animationStyle motionBlur //animationStyle paintOver stroke 255,0,0,120 fill (time*1000)%255,0,0 pushMatrix count = 0 3 times โ–ถcount++ โ–ถpushMatrix โ–ถrotate count+3+time,2+count + time,4+count โ–ถ120 times โ–ถโ–ถscale 0.9 โ–ถโ–ถmove 1,1,0 โ–ถโ–ถrotate time/.1 โ–ถโ–ถbox โ–ถpopMatrix """ @programs.tutorials.introTutorial = submenu: "Intro" title: "intro" code: """ // Lines beginning with two // slashes (like these) are just comments. // Everything else is run // about 30 to 60 times per second // in order to create an animation. // Click the link below to start the tutorial. // next-tutorial:hello_world """ @programs.tutorials.helloworldTutorial = submenu: "Intro" title: "hello world" code: """ // type these three letters // in one of these empty lines below: // 'b' and 'o' and 'x' // (you should then see a box facing you) // click below for the next tutorial // next-tutorial:some_notes """ @programs.tutorials.somenotesTutorial = submenu: "Intro" title: "some notes" code: """ // If this makes sense to you: // the syntax is similar to Coffeescript // and the commands are almost // like Processing. // If this doesn't make sense to you // don't worry. // next-tutorial:rotate """ @programs.tutorials.rotateTutorial = submenu: "Intro" title: "a taste of animation" code: """ // now that we have a box // let's rotate it: // type 'rotate 1' in the // line before the 'box' box // click for the next tutorial: // next-tutorial:frame """ @programs.tutorials.frameTutorial = submenu: "Animation" title: "frame" code: """ // make the box spin // by replacing '1' with 'frame' rotate 1 box // 'frame' contains a number // always incrementing as // the screen is re-drawn. // (use 'frame/100' to slow it down) // next-tutorial:time """ @programs.tutorials.timeTutorial = submenu: "Animation" title: "time" code: """ // 'frame/100' has one problem: // faster computers will make // the cube spin too fast. // Replace it with 'time/2'. rotate frame/100 box // 'time' counts the // number of seconds since // the program started, so it's // independent of how fast // the computer is at drawing. // next-tutorial:move """ @programs.tutorials.moveTutorial = submenu: "Placing things" title: "move" code: """ // you can move any object // by using 'move' box move 1,1,0 box // try to use a rotate before // the first box to see how the // scene changes. // next-tutorial:scale """ @programs.tutorials.scaleTutorial = submenu: "Placing things" title: "scale" code: """ // you can make an object bigger // or smaller by using 'scale' rotate 3 box move 1 scale 2 box // try to use scale or move before // the first box to see how the // scene changes. // next-tutorial:times """ @programs.tutorials.timesTutorial = submenu: "Repeating stuff" title: "times" code: """ // 'times' (not to be confused with // 'time'!) can be used to // repeat operations like so: rotate 1 3 times โ–ถmove 0.2,0.2,0.2 โ–ถbox // note how the tabs indicate // exactly the block of code // to be repeated. // next-tutorial:fill """ @programs.tutorials.fillTutorial = submenu: "Graphics" title: "fill" code: """ // 'fill' changes the // color of all the faces: rotate 1 fill 255,255,0 box // the three numbers indicate // red green and blue values. // You can also use color names such as 'indigo' // Try replacing the numbers with // 'angleColor' // next-tutorial:stroke """ @programs.tutorials.strokeTutorial = submenu: "Graphics" title: "stroke" code: """ // 'stroke' changes all the // edges: rotate 1 strokeSize 5 stroke 255,255,255 box // the three numbers are RGB // but you can also use the color names // or the special color 'angleColor' // Also you can use 'strokeSize' // to specify the thickness. // next-tutorial:color_names """ @programs.tutorials.colornamesTutorial = submenu: "Graphics" title: "color by name" code: """ // you can call colors by name // try to un-comment one line: //fill greenyellow //fill indigo //fill lemonchiffon // whaaaat? rotate 1 box // more color names here: // http://html-color-codes.info/color-names/ // (just use them in lower case) // next-tutorial:lights """ @programs.tutorials.lightsTutorial = submenu: "Graphics" title: "lights" code: """ // 'ambientLight' creates an // ambient light so things have // some sort of shading: ambientLight 0,255,255 rotate time box // you can turn that light on and // off while you build the scene // by using 'lights' and 'noLights' // next-tutorial:background """ @programs.tutorials.backgroundTutorial = submenu: "Graphics" title: "background" code: """ // 'background' creates a // solid background: background 0,0,255 rotate time box // next-tutorial:gradient """ @programs.tutorials.gradientTutorial = submenu: "Graphics" title: "gradient" code: """ // even nicer, you can paint a // background gradient: simpleGradient color(190,10,10),color(30,90,100),color(0) rotate time box // next-tutorial:line """ @programs.tutorials.lineTutorial = submenu: "Graphics" title: "line" code: """ // draw lines like this: 20 times โ–ถrotate time/9 โ–ถline // next-tutorial:ball """ @programs.tutorials.ballTutorial = submenu: "Graphics" title: "ball" code: """ // draw balls like this: ballDetail 10 3 times โ–ถmove 0.2,0.2,0.2 โ–ถball // ('ballDetail' is optional) // next-tutorial:pushpopMatrix """ @programs.tutorials.pushpopMatrixTutorial = submenu: "Graphics" title: "push and pop" code: """ // pushMatrix creates a bookmark of // the position, which you can // return to later by using popMatrix. // You can reset using 'resetMatrix'. rotate time pushMatrix // bookmark the position after the rotation line move 0.5,0,0 line popMatrix // go back to the bookmarked position move -0.5,0,0 line resetMatrix // resets the position line // not affected by initial rotation // next-tutorial:animation_style """ @programs.tutorials.animationstyleTutorial = submenu: "Graphics" title: "animation style" code: """ // try uncommenting either line // with the animationStyle background 255 //animationStyle motionBlur //animationStyle paintOver rotate frame/10 box // next-tutorial:do_once """ @programs.tutorials.doonceTutorial = submenu: "Controlling flow" title: "do once" code: """ // delete either check mark below rotate time โœ“doOnce โ–ถbackground 255 โ–ถfill 255,0,0 โœ“doOnce ball box // ...the line or block of code // are ran one time only, after that the // check marks immediately re-appear // P.S. keep hitting the delete button // on that first check mark for seizures. // next-tutorial:conditionals """ @programs.tutorials.conditionalsTutorial = submenu: "Controlling flow" title: "conditionals" code: """ // you can draw different things // (or in general do different things) // based on any // test condition you want: rotate if frame%3 == 0 โ–ถbox else if frame%3 == 1 โ–ถball else โ–ถpeg // next-tutorial:autocode """ @programs.tutorials.autocodeTutorial = submenu: "Others" title: "autocode" code: """ // the Autocode button invents random // variations for you. // You can interrupt the Autocoder at // any time by pressing the button again, // or you can press CTRL-Z // (or CMD-Z on Macs) to undo (or re-do) some of // the steps even WHILE the autocoder is running, // if you see that things got // boring down a particular path of changes. """ kickOff: -> setInterval( ()=> @pollHash() , 100) # Setup Event Listeners @eventRouter.addListener("url-hash-changed", (hash) => @loadAppropriateDemoOrTutorialBasedOnHash hash ) loadDemoOrTutorial: (demoName) -> if (not Detector.webgl or @liveCodeLabCoreInstance.threeJsSystem.forceCanvasRenderer) \ and not userWarnedAboutWebglExamples and demoName.indexOf("webgl") is 0 userWarnedAboutWebglExamples = true $("#exampleNeedsWebgl").modal() $("#simplemodal-container").height 200 # set the demo as a hash state # so that ideally people can link directly to # a specific demo they like. @eventRouter.emit("set-url-hash", "bookmark=" + demoName) @eventRouter.emit("big-cursor-hide") @eventRouter.emit("editor-undim") @liveCodeLabCoreInstance.graphicsCommands.doTheSpinThingy = false prependMessage = "" if (not Detector.webgl or @liveCodeLabCoreInstance.threeJsSystem.forceCanvasRenderer) \ and demoName.indexOf("webgl") is 0 prependMessage = """ // This drawing makes much more sense // in a WebGL-enabled browser. """ # Note that setting the value of the texteditor (texteditor.setValue below) # triggers the codeMirror onChange callback, which registers the new # code - so the next draw() will run the new demo code. But before doing # that will happen (when the timer for the next frame triggers), we'll # have cleared the screen with the code below. if @programs.demos[demoName] || @programs.tutorials[demoName] if @programs.demos[demoName] # the "replace" here is to change the arrows in tabs @texteditor.setValue prependMessage + @programs.demos[demoName].code.replace(/\u25B6/g, "\t") else if @programs.tutorials[demoName] # the "replace" here is to change the arrows in tabs @texteditor.setValue prependMessage + @programs.tutorials[demoName].code.replace(/\u25B6/g, "\t") # clear history. Why? Because we want to avoid the follwing: # user opens an example. User opens another example. # User performs undo. Result: previous example is open, but the hashtag # doesn't match the example. It's just confusing - we assume here that is # the user selects another tutorial and example then she is not expecting # the undo history to bring her back to previous demos/examples. # Note that, again, this is quite common in CodeMirror, the clearHistory # invokation below only works if slightly postponed. Not sure why. setTimeout((()=>@texteditor.clearHistory()),30) # bring the cursor to the top @texteditor.setCursor 0, 0 # we want to avoid that the selected example # or tutorial when started paints over a screen with a previous drawing # of the previous code. # So basically we draw an empty frame. # a) make sure that animationStyle is "normal" # b) apply the potentially new animationStyle # render the empty frame blendControls = @liveCodeLabCoreInstance.blendControls blendControls.animationStyle blendControls.animationStyles.normal blendControls.animationStyleUpdateIfChanged() @liveCodeLabCoreInstance.renderer.render @liveCodeLabCoreInstance.graphicsCommands loadAppropriateDemoOrTutorialBasedOnHash: (hash) -> matched = hash.match(/bookmark=(.*)/) if matched @loadDemoOrTutorial matched[1] else # user in on the root page without any hashes @texteditor.setValue "" # reset undo history setTimeout((()=>@texteditor.clearHistory()),30) # this paragraph from http://stackoverflow.com/a/629817 # there are more elegant ways to track back/forward history # but they are more complex than this. I don't mind having a bit of # polling for this, not too big of a problem. pollHash: -> if @lastHash isnt location.hash @lastHash = location.hash # hash has changed, so do stuff: @loadAppropriateDemoOrTutorialBasedOnHash @lastHash ProgramLoader
152632
### ## ProgramLoader takes care of managing the URL and editor content ## when the user navigates through demos and examples - either by ## selecting menu entries, or by clicking back/forward arrow, or by ## landing on a URL with a hashtag. ### define [ 'Three.Detector' ], ( Detector ) -> class ProgramLoader constructor: (@eventRouter, @texteditor, @liveCodeLabCoreInstance) -> @lastHash = "" userWarnedAboutWebglExamples = false @programs = demos: {} tutorials: {} @programs.demos.aBoxTest = submenu: "Evolutionary" title: "Hello Box" code: """ // g() function declares a gene. First argument is required to give it a name. // I recommend using brackets to enclose arguments for this... box g('boxSize') // two more arguments can be passed to g() to define min & max values // otherwise they default to min=0, max=1. move g('moveX'), g('moveY', -0.5, 1.3) // if the same gene name is used more than once, the same value will be returned box g('boxSize') """ @programs.demos.repitition = submenu: "Evolutionary" title: "Some boxes..." code: """ 5 times -> โ–ถmove g('moveX'), g('moveY') โ–ถbox """ @programs.demos.functions = submenu: "Evolutionary" title: "Functions" code: """ //exercise: change this to draw a variable number of boxes... boxes = -> โ–ถ5 times -> โ–ถโ–ถmove g('moveX'), g('moveY') โ–ถโ–ถrotate g('rotX'), g('rotY') โ–ถโ–ถbox scale 0.2 boxes //notice that these transformations still encorporate the combined //effect of transforms from the boxes function... //resetMatrix //uncommenting this line will counter-act that... //...but it will also loose the initial scale... move 2, 0 boxes """ @programs.demos.feedback = submenu: "Evolutionary" title: "Feedback" code: """ // video feedback uses the image rendered in the previous frame // as source material for generating the current frame // ... interesting forms of chaos can result ... // ambientLight animSpeed 0.1 โœ“doOnce โ–ถmutate 0.5 move 0, -1 โ–ถbox 0.3, 1, 0.1 //note that the resulting image will be quite dependant on aspect ratio... //so tweak numbers to get something not blown out / too decayed... feedback rotate 0, 0, g('r1', -Math.PI, Math.PI) โ–ถbox 1.6 move 0.3, 0 rotate 0, 0, g('r2', -Math.PI, Math.PI) โ–ถbox 2.8, 2.6, 0.3 """ @programs.demos.feedback2 = submenu: "Evolutionary" title: "Feedback 2" code: """ ambientLight i = 0 noStroke fill g('r'+i)*255, g('g'+i)*255, g('b'+i)*255 move 0, -1 โ–ถball 0.3, 1, 0.1 feedback move 0.2, 0 rotate 0, 0, -0.6 โ–ถbox 1.6 30 times โ–ถscale 0.8 โ–ถi++ โ–ถfill g('r'+i)*255, g('g'+i)*255, g('b'+i)*255, g('a'+i, 150, 255) โ–ถmove g('m', 0.2, 0.5) โ–ถrotate time/2, 0, g('r2', -Math.PI, Math.PI) โ–ถbox 2.8, 2.6, 0.5 """ @programs.demos.tendrils = submenu: "Evolutionary" title: "Tendrils" code: """ //a thought/exercise: how about spiky tendrils? //or making this the head of a creature... ambientLight animSpeed 0.01 โœ“doOnce mutate 1 arm = (rx, ry) -> โ–ถscale 1 โ–ถโ–ถ15 times โ–ถโ–ถโ–ถ//notice that the g('m') will have the same value for all parts of all arms โ–ถโ–ถโ–ถmove g('m') โ–ถโ–ถโ–ถrotate rx, ry โ–ถโ–ถโ–ถscale 0.8 โ–ถโ–ถโ–ถball scale 0.2 nArms = (n, id) -> โ–ถi = 0 โ–ถn times โ–ถโ–ถi++ โ–ถโ–ถrotate 0, 0, 2*Math.PI/n โ–ถโ–ถ//each arm is given unique genes for rx & ry โ–ถโ–ถarm g('rx'+i+id), g('ry'+i+id) nArms(20, 'a') """ @programs.demos.parmlsys = submenu: "Evolutionary" title: "Parametric L-System" code: """ PI = Math.PI rule = "Fx-[[FX]+][+FX]+X" background white F = -> โ–ถrotate g('wx', -0.1, 0.1), g('wy', -0.1, 0.1), g('wz', -0.1, 0.1) โ–ถmove 0, 0.3 โ–ถfill black ball 0.03, 0.6, 0.03 โ–ถmove 0, 0.3 L = -> โ–ถscale g('Ls', 0.6, 1.02) โ–ถrotate 0, 0, -g('bendl') * PI/6 R = -> โ–ถscale g('Rs', 0.6, 1.02) โ–ถrotate g('brx')*PI/6, g('bry')*PI/6, g('brz')*PI/6 leaf = -> ball 0.1, 0.2, 0.1 limit = min(abs(8-time*10%16), 4.5) //n keeps track of recursion depth X = (n) -> โ–ถfraction = if n > limit - 1 then pow(limit - floor(limit), 0.3) else 1 โ–ถif n++ > limit then leaf โ–ถelse scale fraction, doOp c, n for c in rule animSpeed 0.01 โœ“doOnce โ–ถmutate 1 //sempre idem, sed non eodum modo //always the same, //but never in the same way if limit <0.2 then mutate 1 doOp = (c, n=0) -> โ–ถswitch c โ–ถโ–ถwhen 'F' then F โ–ถโ–ถwhen '-' then L โ–ถโ–ถwhen '+' then R โ–ถโ–ถwhen '[' then pushMatrix โ–ถโ–ถwhen ']' then popMatrix โ–ถโ–ถwhen 'X' then X n โ–ถโ–ถwhen '(' then stroke green, 100, fill cyan, 80, ball 0.5 rotate move 0, 2, ball 0.1, 0.2, 0.1 โ–ถโ–ถelse rotate 0, 0, PI, fill g('fr')*255, g('fg')*255, g('fb')*255, 200 feedback box 2, 2, 0.2 noStroke scale 0.7 3 times โ–ถpushMatrix โ–ถdoOp "X" โ–ถpopMatrix โ–ถrotate 0, 0, 2*PI/3 """ @programs.demos.roseDemo = submenu: "Basic" title: "Rose" code: """ // 'B rose' by <NAME> (@rumblesan) // Mozilla Festival 2012 // adapted from 'A rose' by Lib4tech background red scale 1.5 animationStyle paintOver rotate frame/100 fill 255-((frame/2)%255),0,0 stroke 255-((frame/2)%255),0,0 scale 1-((frame/2)%255) / 255 box """ @programs.demos.cheeseAndOlivesDemo = submenu: "Basic" title: "Cheese and olives" code: """ // 'Cheese and olives' by // <NAME> // Mozilla festival 2012 background white scale .3 move 0,-1 fill yellow stroke black rotate strokeSize 3 line 4 box rotate 2,3 move 0,3 scale .3 fill black stroke black ball rotate 3 move 5 scale 1 fill green stroke green ball rotate 1 move -3 scale 1 fill yellow stroke yellow ball """ @programs.demos.simpleCubeDemo = submenu: "Basic" title: "Simple cube" code: """ // there you go! // a simple cube! background yellow rotate 0,time/2,time/2 box """ @programs.demos.webgltwocubesDemo = submenu: "WebGL" title: "WebGL: Two cubes" code: """ background 155,255,255 2 times โ–ถrotate 0, 1, time/2 โ–ถbox """ @programs.demos.cubesAndSpikes = submenu: "Basic" title: "Cubes and spikes" code: """ simpleGradient fuchsia,color(100,200,200),yellow scale 2.1 5 times โ–ถrotate 0,1,time/5 โ–ถbox 0.1,0.1,0.1 โ–ถmove 0,0.1,0.1 โ–ถ3 times โ–ถโ–ถrotate 0,1,1 โ–ถโ–ถbox 0.01,0.01,1 """ @programs.demos.webglturbineDemo = submenu: "WebGL" title: "WebGL: Turbine" code: """ background 155,55,255 70 times โ–ถrotate time/100,1,time/100 โ–ถbox """ @programs.demos.webglzfightartDemo = submenu: "WebGL" title: "WebGL: Z-fight!" code: """ // Explore the artifacts // of your GPU! // Go Z-fighting, go! scale 5 rotate fill red box rotate 0.000001 fill yellow box """ @programs.demos.littleSpiralOfCubes = submenu: "Basic" title: "Little spiral" code: """ background orange scale 0.1 10 times โ–ถrotate 0,1,time โ–ถmove 1,1,1 โ–ถbox """ @programs.demos.tentacleDemo = submenu: "Basic" title: "Tentacle" code: """ background 155,255,155 scale 0.15 3 times โ–ถrotate 0,1,1 โ–ถ10 times โ–ถโ–ถrotate 0,1,time โ–ถโ–ถscale 0.9 โ–ถโ–ถmove 1,1,1 โ–ถโ–ถbox """ @programs.demos.lampDemo = submenu: "Basic" title: "Lamp" code: """ animationStyle motionBlur simpleGradient red,yellow,color(255,0,255) //animationStyle paintOver scale 2 rotate time/4, time/4, time/4 90 times โ–ถrotate time/200, time/200, time/200 โ–ถline โ–ถmove 0.5,0,0 โ–ถline โ–ถmove -0.5,0,0 โ–ถline """ @programs.demos.trillionfeathersDemo = submenu: "Basic" title: "A trillion feathers" code: """ animationStyle paintOver move 2,0,0 scale 2 rotate 20 times โ–ถrotate โ–ถmove 0.25,0,0 โ–ถline โ–ถmove -0.5,0,0 โ–ถline """ @programs.demos.monsterblobDemo = submenu: "Basic" title: "Monster blob" code: """ ballDetail 6 animationStyle motionBlur rotate time/5 simpleGradient fuchsia,aqua,yellow 5 times โ–ถrotate 0,1,time/5 โ–ถmove 0.2,0,0 โ–ถ3 times โ–ถโ–ถrotate 1 โ–ถโ–ถball -1 """ @programs.demos.industrialMusicDemo = submenu: "Sound" title: "Sound: Industrial" code: """ bpm 88 play 'alienBeep' ,'zzxz zzzz zzxz zzzz' play 'beepC' ,'zxzz zzzz xzzx xxxz' play 'beepA' ,'zzxz zzzz zzxz zzzz' play 'lowFlash' ,'zzxz zzzz zzzz zzzz' play 'beepB' ,'xzzx zzzz zxzz zxzz' play 'voltage' ,'xzxz zxzz xzxx xzxx' play 'tranceKick' ,'zxzx zzzx xzzz zzxx' """ @programs.demos.overScratch = submenu: "Sound" title: "Sound: Over-scratch" code: """ bpm 108 play 'tranceKick' ,'xzxz zx' play 'tranceKick1' ,'xzxzxzx' play 'scratch' + int(random(14)) ,'x' play 'scratch-med' + int(random(8)) ,'xz' play 'scratch-high' + int(random(2)) ,'xzzz' play 'scratch-rough' + int(random(4)) ,'xz' """ @programs.demos.trySoundsDemo = submenu: "Sound" title: "Sound: Try them all" code: """ bpm 88 // leave this one as base play 'tranceKick' ,'zxzx zzzx xzzz zzxx' // uncomment the sounds you want to try //play 'alienBeep' ,'zzxz zzzz zzxz zzzz' //play 'beep' ,'zzxz zzzz zzxz zzzz' //play 'beep0' ,'zzxz zzzz zzxz zzzz' //play 'beep1' ,'zzxz zzzz zzxz zzzz' //play 'beep2' ,'zzxz zzzz zzxz zzzz' //play 'beep3' ,'zzxz zzzz zzxz zzzz' //play 'bing' ,'zzxz zzzz zzxz zzzz' //play 'ciack' ,'zzxz zzzz zzxz zzzz' //play 'ciack0' ,'zzxz zzzz zzxz zzzz' //play 'ciack1' ,'zzxz zzzz zzxz zzzz' //play 'cosmos' ,'zzxz zzzz zzxz zzzz' //play 'crash' ,'zzxz zzzz zzxz zzzz' //play 'crash0' ,'zzxz zzzz zzxz zzzz' //play 'crash1' ,'zzxz zzzz zzxz zzzz' //play 'crash2' ,'zzxz zzzz zzxz zzzz' //play 'detune' ,'zzxz zzzz zzxz zzzz' //play 'dish' ,'zzxz zzzz zzxz zzzz' //play 'dish0' ,'zzxz zzzz zzxz zzzz' //play 'dish1' ,'zzxz zzzz zzxz zzzz' //play 'dish2' ,'zzxz zzzz zzxz zzzz' //play 'downstairs' ,'zzxz zzzz zzxz zzzz' //play 'glass' ,'zzxz zzzz zzxz zzzz' //play 'highHatClosed' ,'zzxz zzzz zzxz zzzz' //play 'highHatOpen' ,'zzxz zzzz zzxz zzzz' //play 'hiss' ,'zzxz zzzz zzxz zzzz' //play 'hiss0' ,'zzxz zzzz zzxz zzzz' //play 'hiss1' ,'zzxz zzzz zzxz zzzz' //play 'hiss2' ,'zzxz zzzz zzxz zzzz' //play 'lowFlash' ,'zzxz zzzz zzxz zzzz' //play 'lowFlash0' ,'zzxz zzzz zzxz zzzz' //play 'lowFlash1' ,'zzxz zzzz zzxz zzzz' //play 'mouth' ,'zzxz zzzz zzxz zzzz' //play 'mouth0' ,'zzxz zzzz zzxz zzzz' //play 'mouth1' ,'zzxz zzzz zzxz zzzz' //play 'mouth2' ,'zzxz zzzz zzxz zzzz' //play 'mouth3' ,'zzxz zzzz zzxz zzzz' //play 'mouth4' ,'zzxz zzzz zzxz zzzz' //play 'penta0' ,'zzxz zzzz zzxz zzzz' //play 'penta1' ,'zzxz zzzz zzxz zzzz' //play 'penta2' ,'zzxz zzzz zzxz zzzz' //play 'penta3' ,'zzxz zzzz zzxz zzzz' //play 'penta4' ,'zzxz zzzz zzxz zzzz' //play 'penta5' ,'zzxz zzzz zzxz zzzz' //play 'penta6' ,'zzxz zzzz zzxz zzzz' //play 'penta7' ,'zzxz zzzz zzxz zzzz' //play 'penta8' ,'zzxz zzzz zzxz zzzz' //play 'penta9' ,'zzxz zzzz zzxz zzzz' //play 'penta10' ,'zzxz zzzz zzxz zzzz' //play 'penta11' ,'zzxz zzzz zzxz zzzz' //play 'penta12' ,'zzxz zzzz zzxz zzzz' //play 'penta13' ,'zzxz zzzz zzxz zzzz' //play 'penta14' ,'zzxz zzzz zzxz zzzz' //play 'penta15' ,'zzxz zzzz zzxz zzzz' //play 'ride' ,'zzxz zzzz zzxz zzzz' //play 'snap' ,'zzxz zzzz zzxz zzzz' //play 'snap0' ,'zzxz zzzz zzxz zzzz' //play 'snap1' ,'zzxz zzzz zzxz zzzz' //play 'snare' ,'zzxz zzzz zzxz zzzz' //play 'snare0' ,'zzxz zzzz zzxz zzzz' //play 'snare1' ,'zzxz zzzz zzxz zzzz' //play 'snare2' ,'zzxz zzzz zzxz zzzz' //play 'thump' ,'zzxz zzzz zzxz zzzz' //play 'thump0' ,'zzxz zzzz zzxz zzzz' //play 'thump1' ,'zzxz zzzz zzxz zzzz' //play 'thump2' ,'zzxz zzzz zzxz zzzz' //play 'toc' ,'zzxz zzzz zzxz zzzz' //play 'toc0' ,'zzxz zzzz zzxz zzzz' //play 'toc1' ,'zzxz zzzz zzxz zzzz' //play 'tranceKick' ,'zzxz zzzz zzxz zzzz' //play 'tranceKick0' ,'zzxz zzzz zzxz zzzz' //play 'tranceKick1' ,'zzxz zzzz zzxz zzzz' //play 'voltage' ,'zzxz zzzz zzxz zzzz' //play 'warm' ,'zzxz zzzz zzxz zzzz' """ @programs.demos.springysquaresDemo = submenu: "Basic" title: "Springy squares" code: """ animationStyle motionBlur simpleGradient fuchsia,color(100,200,200),yellow scale 0.3 3 times โ–ถmove 0,0,0.5 โ–ถ5 times โ–ถโ–ถrotate time/2 โ–ถโ–ถmove 0.7,0,0 โ–ถโ–ถrect """ @programs.demos.diceDemo = submenu: "Basic" title: "Dice" code: """ animationStyle motionBlur simpleGradient color(255),moccasin,peachpuff stroke 255,100,100,255 fill red,155 move -0.5,0,0 scale 0.3 3 times โ–ถmove 0,0,0.5 โ–ถ1 times โ–ถโ–ถrotate time โ–ถโ–ถmove 2,0,0 โ–ถโ–ถbox """ @programs.demos.webglalmostvoronoiDemo = submenu: "WebGL" title: "WebGL: Almost Voronoi" code: """ scale 10 2 times โ–ถrotate 0,1,time/10 โ–ถball -1 """ @programs.demos.webglshardsDemo = submenu: "WebGL" title: "WebGL: Shards" code: """ scale 10 fill 0 strokeSize 7 5 times โ–ถrotate 0,1,time/20 โ–ถball โ–ถrotate 0,1,1 โ–ถball -1.01 """ @programs.demos.webglredthreadsDemo = submenu: "WebGL" title: "WebGL: Red threads" code: """ scale 10.5 background black stroke red noFill strokeSize 7 5 times โ–ถrotate time/20 โ–ถball โ–ถrotate 0,1,1 โ–ถball """ @programs.demos.webglribbon = submenu: "WebGL" title: "WebGL: Ribbon" code: """ turns = 1 // 1 = Mรถbius strip detail = 200 // try up to 400 or so speed = 0.5 ambientLight 255,0,0 // comment out to see the seam background black rotate time /5 scale 0.6 for i in [0...detail] โ–ถrotate 0,0,2*Math.PI/(detail) โ–ถmove 2,0,0 โ–ถโ–ถrotate 0,turns*i*Math.PI/(detail)+time*speed,0 โ–ถโ–ถrect 1,0.04+1/detail """ @programs.demos.theeye = submenu: "WebGL" title: "WebGL: The eye" code: """ turns = Math.floor(time/10)%6 detail = 100 speed = 3 if time%10 < 5 โ–ถambientLight 255,255,255 background black rotate time /5 for i in [0...detail] โ–ถrotate 0,0,2*Math.PI/(detail) โ–ถmove 2,0,0 โ–ถโ–ถrotate turns*i*Math.PI/(detail)+time*speed,0,0 โ–ถโ–ถrect 1 """ @programs.demos.webglnuclearOctopusDemo = submenu: "WebGL" title: "WebGL: Nuclear octopus" code: """ simpleGradient black,color(0,0,(time/.005)%255),black scale 0.2 move 5,0,0 animationStyle motionBlur //animationStyle paintOver stroke 255,0,0,120 fill (time*1000)%255,0,0 pushMatrix count = 0 3 times โ–ถcount++ โ–ถpushMatrix โ–ถrotate count+3+time,2+count + time,4+count โ–ถ120 times โ–ถโ–ถscale 0.9 โ–ถโ–ถmove 1,1,0 โ–ถโ–ถrotate time/.1 โ–ถโ–ถbox โ–ถpopMatrix """ @programs.tutorials.introTutorial = submenu: "Intro" title: "intro" code: """ // Lines beginning with two // slashes (like these) are just comments. // Everything else is run // about 30 to 60 times per second // in order to create an animation. // Click the link below to start the tutorial. // next-tutorial:hello_world """ @programs.tutorials.helloworldTutorial = submenu: "Intro" title: "hello world" code: """ // type these three letters // in one of these empty lines below: // 'b' and 'o' and 'x' // (you should then see a box facing you) // click below for the next tutorial // next-tutorial:some_notes """ @programs.tutorials.somenotesTutorial = submenu: "Intro" title: "some notes" code: """ // If this makes sense to you: // the syntax is similar to Coffeescript // and the commands are almost // like Processing. // If this doesn't make sense to you // don't worry. // next-tutorial:rotate """ @programs.tutorials.rotateTutorial = submenu: "Intro" title: "a taste of animation" code: """ // now that we have a box // let's rotate it: // type 'rotate 1' in the // line before the 'box' box // click for the next tutorial: // next-tutorial:frame """ @programs.tutorials.frameTutorial = submenu: "Animation" title: "frame" code: """ // make the box spin // by replacing '1' with 'frame' rotate 1 box // 'frame' contains a number // always incrementing as // the screen is re-drawn. // (use 'frame/100' to slow it down) // next-tutorial:time """ @programs.tutorials.timeTutorial = submenu: "Animation" title: "time" code: """ // 'frame/100' has one problem: // faster computers will make // the cube spin too fast. // Replace it with 'time/2'. rotate frame/100 box // 'time' counts the // number of seconds since // the program started, so it's // independent of how fast // the computer is at drawing. // next-tutorial:move """ @programs.tutorials.moveTutorial = submenu: "Placing things" title: "move" code: """ // you can move any object // by using 'move' box move 1,1,0 box // try to use a rotate before // the first box to see how the // scene changes. // next-tutorial:scale """ @programs.tutorials.scaleTutorial = submenu: "Placing things" title: "scale" code: """ // you can make an object bigger // or smaller by using 'scale' rotate 3 box move 1 scale 2 box // try to use scale or move before // the first box to see how the // scene changes. // next-tutorial:times """ @programs.tutorials.timesTutorial = submenu: "Repeating stuff" title: "times" code: """ // 'times' (not to be confused with // 'time'!) can be used to // repeat operations like so: rotate 1 3 times โ–ถmove 0.2,0.2,0.2 โ–ถbox // note how the tabs indicate // exactly the block of code // to be repeated. // next-tutorial:fill """ @programs.tutorials.fillTutorial = submenu: "Graphics" title: "fill" code: """ // 'fill' changes the // color of all the faces: rotate 1 fill 255,255,0 box // the three numbers indicate // red green and blue values. // You can also use color names such as 'indigo' // Try replacing the numbers with // 'angleColor' // next-tutorial:stroke """ @programs.tutorials.strokeTutorial = submenu: "Graphics" title: "stroke" code: """ // 'stroke' changes all the // edges: rotate 1 strokeSize 5 stroke 255,255,255 box // the three numbers are RGB // but you can also use the color names // or the special color 'angleColor' // Also you can use 'strokeSize' // to specify the thickness. // next-tutorial:color_names """ @programs.tutorials.colornamesTutorial = submenu: "Graphics" title: "color by name" code: """ // you can call colors by name // try to un-comment one line: //fill greenyellow //fill indigo //fill lemonchiffon // whaaaat? rotate 1 box // more color names here: // http://html-color-codes.info/color-names/ // (just use them in lower case) // next-tutorial:lights """ @programs.tutorials.lightsTutorial = submenu: "Graphics" title: "lights" code: """ // 'ambientLight' creates an // ambient light so things have // some sort of shading: ambientLight 0,255,255 rotate time box // you can turn that light on and // off while you build the scene // by using 'lights' and 'noLights' // next-tutorial:background """ @programs.tutorials.backgroundTutorial = submenu: "Graphics" title: "background" code: """ // 'background' creates a // solid background: background 0,0,255 rotate time box // next-tutorial:gradient """ @programs.tutorials.gradientTutorial = submenu: "Graphics" title: "gradient" code: """ // even nicer, you can paint a // background gradient: simpleGradient color(190,10,10),color(30,90,100),color(0) rotate time box // next-tutorial:line """ @programs.tutorials.lineTutorial = submenu: "Graphics" title: "line" code: """ // draw lines like this: 20 times โ–ถrotate time/9 โ–ถline // next-tutorial:ball """ @programs.tutorials.ballTutorial = submenu: "Graphics" title: "ball" code: """ // draw balls like this: ballDetail 10 3 times โ–ถmove 0.2,0.2,0.2 โ–ถball // ('ballDetail' is optional) // next-tutorial:pushpopMatrix """ @programs.tutorials.pushpopMatrixTutorial = submenu: "Graphics" title: "push and pop" code: """ // pushMatrix creates a bookmark of // the position, which you can // return to later by using popMatrix. // You can reset using 'resetMatrix'. rotate time pushMatrix // bookmark the position after the rotation line move 0.5,0,0 line popMatrix // go back to the bookmarked position move -0.5,0,0 line resetMatrix // resets the position line // not affected by initial rotation // next-tutorial:animation_style """ @programs.tutorials.animationstyleTutorial = submenu: "Graphics" title: "animation style" code: """ // try uncommenting either line // with the animationStyle background 255 //animationStyle motionBlur //animationStyle paintOver rotate frame/10 box // next-tutorial:do_once """ @programs.tutorials.doonceTutorial = submenu: "Controlling flow" title: "do once" code: """ // delete either check mark below rotate time โœ“doOnce โ–ถbackground 255 โ–ถfill 255,0,0 โœ“doOnce ball box // ...the line or block of code // are ran one time only, after that the // check marks immediately re-appear // P.S. keep hitting the delete button // on that first check mark for seizures. // next-tutorial:conditionals """ @programs.tutorials.conditionalsTutorial = submenu: "Controlling flow" title: "conditionals" code: """ // you can draw different things // (or in general do different things) // based on any // test condition you want: rotate if frame%3 == 0 โ–ถbox else if frame%3 == 1 โ–ถball else โ–ถpeg // next-tutorial:autocode """ @programs.tutorials.autocodeTutorial = submenu: "Others" title: "autocode" code: """ // the Autocode button invents random // variations for you. // You can interrupt the Autocoder at // any time by pressing the button again, // or you can press CTRL-Z // (or CMD-Z on Macs) to undo (or re-do) some of // the steps even WHILE the autocoder is running, // if you see that things got // boring down a particular path of changes. """ kickOff: -> setInterval( ()=> @pollHash() , 100) # Setup Event Listeners @eventRouter.addListener("url-hash-changed", (hash) => @loadAppropriateDemoOrTutorialBasedOnHash hash ) loadDemoOrTutorial: (demoName) -> if (not Detector.webgl or @liveCodeLabCoreInstance.threeJsSystem.forceCanvasRenderer) \ and not userWarnedAboutWebglExamples and demoName.indexOf("webgl") is 0 userWarnedAboutWebglExamples = true $("#exampleNeedsWebgl").modal() $("#simplemodal-container").height 200 # set the demo as a hash state # so that ideally people can link directly to # a specific demo they like. @eventRouter.emit("set-url-hash", "bookmark=" + demoName) @eventRouter.emit("big-cursor-hide") @eventRouter.emit("editor-undim") @liveCodeLabCoreInstance.graphicsCommands.doTheSpinThingy = false prependMessage = "" if (not Detector.webgl or @liveCodeLabCoreInstance.threeJsSystem.forceCanvasRenderer) \ and demoName.indexOf("webgl") is 0 prependMessage = """ // This drawing makes much more sense // in a WebGL-enabled browser. """ # Note that setting the value of the texteditor (texteditor.setValue below) # triggers the codeMirror onChange callback, which registers the new # code - so the next draw() will run the new demo code. But before doing # that will happen (when the timer for the next frame triggers), we'll # have cleared the screen with the code below. if @programs.demos[demoName] || @programs.tutorials[demoName] if @programs.demos[demoName] # the "replace" here is to change the arrows in tabs @texteditor.setValue prependMessage + @programs.demos[demoName].code.replace(/\u25B6/g, "\t") else if @programs.tutorials[demoName] # the "replace" here is to change the arrows in tabs @texteditor.setValue prependMessage + @programs.tutorials[demoName].code.replace(/\u25B6/g, "\t") # clear history. Why? Because we want to avoid the follwing: # user opens an example. User opens another example. # User performs undo. Result: previous example is open, but the hashtag # doesn't match the example. It's just confusing - we assume here that is # the user selects another tutorial and example then she is not expecting # the undo history to bring her back to previous demos/examples. # Note that, again, this is quite common in CodeMirror, the clearHistory # invokation below only works if slightly postponed. Not sure why. setTimeout((()=>@texteditor.clearHistory()),30) # bring the cursor to the top @texteditor.setCursor 0, 0 # we want to avoid that the selected example # or tutorial when started paints over a screen with a previous drawing # of the previous code. # So basically we draw an empty frame. # a) make sure that animationStyle is "normal" # b) apply the potentially new animationStyle # render the empty frame blendControls = @liveCodeLabCoreInstance.blendControls blendControls.animationStyle blendControls.animationStyles.normal blendControls.animationStyleUpdateIfChanged() @liveCodeLabCoreInstance.renderer.render @liveCodeLabCoreInstance.graphicsCommands loadAppropriateDemoOrTutorialBasedOnHash: (hash) -> matched = hash.match(/bookmark=(.*)/) if matched @loadDemoOrTutorial matched[1] else # user in on the root page without any hashes @texteditor.setValue "" # reset undo history setTimeout((()=>@texteditor.clearHistory()),30) # this paragraph from http://stackoverflow.com/a/629817 # there are more elegant ways to track back/forward history # but they are more complex than this. I don't mind having a bit of # polling for this, not too big of a problem. pollHash: -> if @lastHash isnt location.hash @lastHash = location.hash # hash has changed, so do stuff: @loadAppropriateDemoOrTutorialBasedOnHash @lastHash ProgramLoader
true
### ## ProgramLoader takes care of managing the URL and editor content ## when the user navigates through demos and examples - either by ## selecting menu entries, or by clicking back/forward arrow, or by ## landing on a URL with a hashtag. ### define [ 'Three.Detector' ], ( Detector ) -> class ProgramLoader constructor: (@eventRouter, @texteditor, @liveCodeLabCoreInstance) -> @lastHash = "" userWarnedAboutWebglExamples = false @programs = demos: {} tutorials: {} @programs.demos.aBoxTest = submenu: "Evolutionary" title: "Hello Box" code: """ // g() function declares a gene. First argument is required to give it a name. // I recommend using brackets to enclose arguments for this... box g('boxSize') // two more arguments can be passed to g() to define min & max values // otherwise they default to min=0, max=1. move g('moveX'), g('moveY', -0.5, 1.3) // if the same gene name is used more than once, the same value will be returned box g('boxSize') """ @programs.demos.repitition = submenu: "Evolutionary" title: "Some boxes..." code: """ 5 times -> โ–ถmove g('moveX'), g('moveY') โ–ถbox """ @programs.demos.functions = submenu: "Evolutionary" title: "Functions" code: """ //exercise: change this to draw a variable number of boxes... boxes = -> โ–ถ5 times -> โ–ถโ–ถmove g('moveX'), g('moveY') โ–ถโ–ถrotate g('rotX'), g('rotY') โ–ถโ–ถbox scale 0.2 boxes //notice that these transformations still encorporate the combined //effect of transforms from the boxes function... //resetMatrix //uncommenting this line will counter-act that... //...but it will also loose the initial scale... move 2, 0 boxes """ @programs.demos.feedback = submenu: "Evolutionary" title: "Feedback" code: """ // video feedback uses the image rendered in the previous frame // as source material for generating the current frame // ... interesting forms of chaos can result ... // ambientLight animSpeed 0.1 โœ“doOnce โ–ถmutate 0.5 move 0, -1 โ–ถbox 0.3, 1, 0.1 //note that the resulting image will be quite dependant on aspect ratio... //so tweak numbers to get something not blown out / too decayed... feedback rotate 0, 0, g('r1', -Math.PI, Math.PI) โ–ถbox 1.6 move 0.3, 0 rotate 0, 0, g('r2', -Math.PI, Math.PI) โ–ถbox 2.8, 2.6, 0.3 """ @programs.demos.feedback2 = submenu: "Evolutionary" title: "Feedback 2" code: """ ambientLight i = 0 noStroke fill g('r'+i)*255, g('g'+i)*255, g('b'+i)*255 move 0, -1 โ–ถball 0.3, 1, 0.1 feedback move 0.2, 0 rotate 0, 0, -0.6 โ–ถbox 1.6 30 times โ–ถscale 0.8 โ–ถi++ โ–ถfill g('r'+i)*255, g('g'+i)*255, g('b'+i)*255, g('a'+i, 150, 255) โ–ถmove g('m', 0.2, 0.5) โ–ถrotate time/2, 0, g('r2', -Math.PI, Math.PI) โ–ถbox 2.8, 2.6, 0.5 """ @programs.demos.tendrils = submenu: "Evolutionary" title: "Tendrils" code: """ //a thought/exercise: how about spiky tendrils? //or making this the head of a creature... ambientLight animSpeed 0.01 โœ“doOnce mutate 1 arm = (rx, ry) -> โ–ถscale 1 โ–ถโ–ถ15 times โ–ถโ–ถโ–ถ//notice that the g('m') will have the same value for all parts of all arms โ–ถโ–ถโ–ถmove g('m') โ–ถโ–ถโ–ถrotate rx, ry โ–ถโ–ถโ–ถscale 0.8 โ–ถโ–ถโ–ถball scale 0.2 nArms = (n, id) -> โ–ถi = 0 โ–ถn times โ–ถโ–ถi++ โ–ถโ–ถrotate 0, 0, 2*Math.PI/n โ–ถโ–ถ//each arm is given unique genes for rx & ry โ–ถโ–ถarm g('rx'+i+id), g('ry'+i+id) nArms(20, 'a') """ @programs.demos.parmlsys = submenu: "Evolutionary" title: "Parametric L-System" code: """ PI = Math.PI rule = "Fx-[[FX]+][+FX]+X" background white F = -> โ–ถrotate g('wx', -0.1, 0.1), g('wy', -0.1, 0.1), g('wz', -0.1, 0.1) โ–ถmove 0, 0.3 โ–ถfill black ball 0.03, 0.6, 0.03 โ–ถmove 0, 0.3 L = -> โ–ถscale g('Ls', 0.6, 1.02) โ–ถrotate 0, 0, -g('bendl') * PI/6 R = -> โ–ถscale g('Rs', 0.6, 1.02) โ–ถrotate g('brx')*PI/6, g('bry')*PI/6, g('brz')*PI/6 leaf = -> ball 0.1, 0.2, 0.1 limit = min(abs(8-time*10%16), 4.5) //n keeps track of recursion depth X = (n) -> โ–ถfraction = if n > limit - 1 then pow(limit - floor(limit), 0.3) else 1 โ–ถif n++ > limit then leaf โ–ถelse scale fraction, doOp c, n for c in rule animSpeed 0.01 โœ“doOnce โ–ถmutate 1 //sempre idem, sed non eodum modo //always the same, //but never in the same way if limit <0.2 then mutate 1 doOp = (c, n=0) -> โ–ถswitch c โ–ถโ–ถwhen 'F' then F โ–ถโ–ถwhen '-' then L โ–ถโ–ถwhen '+' then R โ–ถโ–ถwhen '[' then pushMatrix โ–ถโ–ถwhen ']' then popMatrix โ–ถโ–ถwhen 'X' then X n โ–ถโ–ถwhen '(' then stroke green, 100, fill cyan, 80, ball 0.5 rotate move 0, 2, ball 0.1, 0.2, 0.1 โ–ถโ–ถelse rotate 0, 0, PI, fill g('fr')*255, g('fg')*255, g('fb')*255, 200 feedback box 2, 2, 0.2 noStroke scale 0.7 3 times โ–ถpushMatrix โ–ถdoOp "X" โ–ถpopMatrix โ–ถrotate 0, 0, 2*PI/3 """ @programs.demos.roseDemo = submenu: "Basic" title: "Rose" code: """ // 'B rose' by PI:NAME:<NAME>END_PI (@rumblesan) // Mozilla Festival 2012 // adapted from 'A rose' by Lib4tech background red scale 1.5 animationStyle paintOver rotate frame/100 fill 255-((frame/2)%255),0,0 stroke 255-((frame/2)%255),0,0 scale 1-((frame/2)%255) / 255 box """ @programs.demos.cheeseAndOlivesDemo = submenu: "Basic" title: "Cheese and olives" code: """ // 'Cheese and olives' by // PI:NAME:<NAME>END_PI // Mozilla festival 2012 background white scale .3 move 0,-1 fill yellow stroke black rotate strokeSize 3 line 4 box rotate 2,3 move 0,3 scale .3 fill black stroke black ball rotate 3 move 5 scale 1 fill green stroke green ball rotate 1 move -3 scale 1 fill yellow stroke yellow ball """ @programs.demos.simpleCubeDemo = submenu: "Basic" title: "Simple cube" code: """ // there you go! // a simple cube! background yellow rotate 0,time/2,time/2 box """ @programs.demos.webgltwocubesDemo = submenu: "WebGL" title: "WebGL: Two cubes" code: """ background 155,255,255 2 times โ–ถrotate 0, 1, time/2 โ–ถbox """ @programs.demos.cubesAndSpikes = submenu: "Basic" title: "Cubes and spikes" code: """ simpleGradient fuchsia,color(100,200,200),yellow scale 2.1 5 times โ–ถrotate 0,1,time/5 โ–ถbox 0.1,0.1,0.1 โ–ถmove 0,0.1,0.1 โ–ถ3 times โ–ถโ–ถrotate 0,1,1 โ–ถโ–ถbox 0.01,0.01,1 """ @programs.demos.webglturbineDemo = submenu: "WebGL" title: "WebGL: Turbine" code: """ background 155,55,255 70 times โ–ถrotate time/100,1,time/100 โ–ถbox """ @programs.demos.webglzfightartDemo = submenu: "WebGL" title: "WebGL: Z-fight!" code: """ // Explore the artifacts // of your GPU! // Go Z-fighting, go! scale 5 rotate fill red box rotate 0.000001 fill yellow box """ @programs.demos.littleSpiralOfCubes = submenu: "Basic" title: "Little spiral" code: """ background orange scale 0.1 10 times โ–ถrotate 0,1,time โ–ถmove 1,1,1 โ–ถbox """ @programs.demos.tentacleDemo = submenu: "Basic" title: "Tentacle" code: """ background 155,255,155 scale 0.15 3 times โ–ถrotate 0,1,1 โ–ถ10 times โ–ถโ–ถrotate 0,1,time โ–ถโ–ถscale 0.9 โ–ถโ–ถmove 1,1,1 โ–ถโ–ถbox """ @programs.demos.lampDemo = submenu: "Basic" title: "Lamp" code: """ animationStyle motionBlur simpleGradient red,yellow,color(255,0,255) //animationStyle paintOver scale 2 rotate time/4, time/4, time/4 90 times โ–ถrotate time/200, time/200, time/200 โ–ถline โ–ถmove 0.5,0,0 โ–ถline โ–ถmove -0.5,0,0 โ–ถline """ @programs.demos.trillionfeathersDemo = submenu: "Basic" title: "A trillion feathers" code: """ animationStyle paintOver move 2,0,0 scale 2 rotate 20 times โ–ถrotate โ–ถmove 0.25,0,0 โ–ถline โ–ถmove -0.5,0,0 โ–ถline """ @programs.demos.monsterblobDemo = submenu: "Basic" title: "Monster blob" code: """ ballDetail 6 animationStyle motionBlur rotate time/5 simpleGradient fuchsia,aqua,yellow 5 times โ–ถrotate 0,1,time/5 โ–ถmove 0.2,0,0 โ–ถ3 times โ–ถโ–ถrotate 1 โ–ถโ–ถball -1 """ @programs.demos.industrialMusicDemo = submenu: "Sound" title: "Sound: Industrial" code: """ bpm 88 play 'alienBeep' ,'zzxz zzzz zzxz zzzz' play 'beepC' ,'zxzz zzzz xzzx xxxz' play 'beepA' ,'zzxz zzzz zzxz zzzz' play 'lowFlash' ,'zzxz zzzz zzzz zzzz' play 'beepB' ,'xzzx zzzz zxzz zxzz' play 'voltage' ,'xzxz zxzz xzxx xzxx' play 'tranceKick' ,'zxzx zzzx xzzz zzxx' """ @programs.demos.overScratch = submenu: "Sound" title: "Sound: Over-scratch" code: """ bpm 108 play 'tranceKick' ,'xzxz zx' play 'tranceKick1' ,'xzxzxzx' play 'scratch' + int(random(14)) ,'x' play 'scratch-med' + int(random(8)) ,'xz' play 'scratch-high' + int(random(2)) ,'xzzz' play 'scratch-rough' + int(random(4)) ,'xz' """ @programs.demos.trySoundsDemo = submenu: "Sound" title: "Sound: Try them all" code: """ bpm 88 // leave this one as base play 'tranceKick' ,'zxzx zzzx xzzz zzxx' // uncomment the sounds you want to try //play 'alienBeep' ,'zzxz zzzz zzxz zzzz' //play 'beep' ,'zzxz zzzz zzxz zzzz' //play 'beep0' ,'zzxz zzzz zzxz zzzz' //play 'beep1' ,'zzxz zzzz zzxz zzzz' //play 'beep2' ,'zzxz zzzz zzxz zzzz' //play 'beep3' ,'zzxz zzzz zzxz zzzz' //play 'bing' ,'zzxz zzzz zzxz zzzz' //play 'ciack' ,'zzxz zzzz zzxz zzzz' //play 'ciack0' ,'zzxz zzzz zzxz zzzz' //play 'ciack1' ,'zzxz zzzz zzxz zzzz' //play 'cosmos' ,'zzxz zzzz zzxz zzzz' //play 'crash' ,'zzxz zzzz zzxz zzzz' //play 'crash0' ,'zzxz zzzz zzxz zzzz' //play 'crash1' ,'zzxz zzzz zzxz zzzz' //play 'crash2' ,'zzxz zzzz zzxz zzzz' //play 'detune' ,'zzxz zzzz zzxz zzzz' //play 'dish' ,'zzxz zzzz zzxz zzzz' //play 'dish0' ,'zzxz zzzz zzxz zzzz' //play 'dish1' ,'zzxz zzzz zzxz zzzz' //play 'dish2' ,'zzxz zzzz zzxz zzzz' //play 'downstairs' ,'zzxz zzzz zzxz zzzz' //play 'glass' ,'zzxz zzzz zzxz zzzz' //play 'highHatClosed' ,'zzxz zzzz zzxz zzzz' //play 'highHatOpen' ,'zzxz zzzz zzxz zzzz' //play 'hiss' ,'zzxz zzzz zzxz zzzz' //play 'hiss0' ,'zzxz zzzz zzxz zzzz' //play 'hiss1' ,'zzxz zzzz zzxz zzzz' //play 'hiss2' ,'zzxz zzzz zzxz zzzz' //play 'lowFlash' ,'zzxz zzzz zzxz zzzz' //play 'lowFlash0' ,'zzxz zzzz zzxz zzzz' //play 'lowFlash1' ,'zzxz zzzz zzxz zzzz' //play 'mouth' ,'zzxz zzzz zzxz zzzz' //play 'mouth0' ,'zzxz zzzz zzxz zzzz' //play 'mouth1' ,'zzxz zzzz zzxz zzzz' //play 'mouth2' ,'zzxz zzzz zzxz zzzz' //play 'mouth3' ,'zzxz zzzz zzxz zzzz' //play 'mouth4' ,'zzxz zzzz zzxz zzzz' //play 'penta0' ,'zzxz zzzz zzxz zzzz' //play 'penta1' ,'zzxz zzzz zzxz zzzz' //play 'penta2' ,'zzxz zzzz zzxz zzzz' //play 'penta3' ,'zzxz zzzz zzxz zzzz' //play 'penta4' ,'zzxz zzzz zzxz zzzz' //play 'penta5' ,'zzxz zzzz zzxz zzzz' //play 'penta6' ,'zzxz zzzz zzxz zzzz' //play 'penta7' ,'zzxz zzzz zzxz zzzz' //play 'penta8' ,'zzxz zzzz zzxz zzzz' //play 'penta9' ,'zzxz zzzz zzxz zzzz' //play 'penta10' ,'zzxz zzzz zzxz zzzz' //play 'penta11' ,'zzxz zzzz zzxz zzzz' //play 'penta12' ,'zzxz zzzz zzxz zzzz' //play 'penta13' ,'zzxz zzzz zzxz zzzz' //play 'penta14' ,'zzxz zzzz zzxz zzzz' //play 'penta15' ,'zzxz zzzz zzxz zzzz' //play 'ride' ,'zzxz zzzz zzxz zzzz' //play 'snap' ,'zzxz zzzz zzxz zzzz' //play 'snap0' ,'zzxz zzzz zzxz zzzz' //play 'snap1' ,'zzxz zzzz zzxz zzzz' //play 'snare' ,'zzxz zzzz zzxz zzzz' //play 'snare0' ,'zzxz zzzz zzxz zzzz' //play 'snare1' ,'zzxz zzzz zzxz zzzz' //play 'snare2' ,'zzxz zzzz zzxz zzzz' //play 'thump' ,'zzxz zzzz zzxz zzzz' //play 'thump0' ,'zzxz zzzz zzxz zzzz' //play 'thump1' ,'zzxz zzzz zzxz zzzz' //play 'thump2' ,'zzxz zzzz zzxz zzzz' //play 'toc' ,'zzxz zzzz zzxz zzzz' //play 'toc0' ,'zzxz zzzz zzxz zzzz' //play 'toc1' ,'zzxz zzzz zzxz zzzz' //play 'tranceKick' ,'zzxz zzzz zzxz zzzz' //play 'tranceKick0' ,'zzxz zzzz zzxz zzzz' //play 'tranceKick1' ,'zzxz zzzz zzxz zzzz' //play 'voltage' ,'zzxz zzzz zzxz zzzz' //play 'warm' ,'zzxz zzzz zzxz zzzz' """ @programs.demos.springysquaresDemo = submenu: "Basic" title: "Springy squares" code: """ animationStyle motionBlur simpleGradient fuchsia,color(100,200,200),yellow scale 0.3 3 times โ–ถmove 0,0,0.5 โ–ถ5 times โ–ถโ–ถrotate time/2 โ–ถโ–ถmove 0.7,0,0 โ–ถโ–ถrect """ @programs.demos.diceDemo = submenu: "Basic" title: "Dice" code: """ animationStyle motionBlur simpleGradient color(255),moccasin,peachpuff stroke 255,100,100,255 fill red,155 move -0.5,0,0 scale 0.3 3 times โ–ถmove 0,0,0.5 โ–ถ1 times โ–ถโ–ถrotate time โ–ถโ–ถmove 2,0,0 โ–ถโ–ถbox """ @programs.demos.webglalmostvoronoiDemo = submenu: "WebGL" title: "WebGL: Almost Voronoi" code: """ scale 10 2 times โ–ถrotate 0,1,time/10 โ–ถball -1 """ @programs.demos.webglshardsDemo = submenu: "WebGL" title: "WebGL: Shards" code: """ scale 10 fill 0 strokeSize 7 5 times โ–ถrotate 0,1,time/20 โ–ถball โ–ถrotate 0,1,1 โ–ถball -1.01 """ @programs.demos.webglredthreadsDemo = submenu: "WebGL" title: "WebGL: Red threads" code: """ scale 10.5 background black stroke red noFill strokeSize 7 5 times โ–ถrotate time/20 โ–ถball โ–ถrotate 0,1,1 โ–ถball """ @programs.demos.webglribbon = submenu: "WebGL" title: "WebGL: Ribbon" code: """ turns = 1 // 1 = Mรถbius strip detail = 200 // try up to 400 or so speed = 0.5 ambientLight 255,0,0 // comment out to see the seam background black rotate time /5 scale 0.6 for i in [0...detail] โ–ถrotate 0,0,2*Math.PI/(detail) โ–ถmove 2,0,0 โ–ถโ–ถrotate 0,turns*i*Math.PI/(detail)+time*speed,0 โ–ถโ–ถrect 1,0.04+1/detail """ @programs.demos.theeye = submenu: "WebGL" title: "WebGL: The eye" code: """ turns = Math.floor(time/10)%6 detail = 100 speed = 3 if time%10 < 5 โ–ถambientLight 255,255,255 background black rotate time /5 for i in [0...detail] โ–ถrotate 0,0,2*Math.PI/(detail) โ–ถmove 2,0,0 โ–ถโ–ถrotate turns*i*Math.PI/(detail)+time*speed,0,0 โ–ถโ–ถrect 1 """ @programs.demos.webglnuclearOctopusDemo = submenu: "WebGL" title: "WebGL: Nuclear octopus" code: """ simpleGradient black,color(0,0,(time/.005)%255),black scale 0.2 move 5,0,0 animationStyle motionBlur //animationStyle paintOver stroke 255,0,0,120 fill (time*1000)%255,0,0 pushMatrix count = 0 3 times โ–ถcount++ โ–ถpushMatrix โ–ถrotate count+3+time,2+count + time,4+count โ–ถ120 times โ–ถโ–ถscale 0.9 โ–ถโ–ถmove 1,1,0 โ–ถโ–ถrotate time/.1 โ–ถโ–ถbox โ–ถpopMatrix """ @programs.tutorials.introTutorial = submenu: "Intro" title: "intro" code: """ // Lines beginning with two // slashes (like these) are just comments. // Everything else is run // about 30 to 60 times per second // in order to create an animation. // Click the link below to start the tutorial. // next-tutorial:hello_world """ @programs.tutorials.helloworldTutorial = submenu: "Intro" title: "hello world" code: """ // type these three letters // in one of these empty lines below: // 'b' and 'o' and 'x' // (you should then see a box facing you) // click below for the next tutorial // next-tutorial:some_notes """ @programs.tutorials.somenotesTutorial = submenu: "Intro" title: "some notes" code: """ // If this makes sense to you: // the syntax is similar to Coffeescript // and the commands are almost // like Processing. // If this doesn't make sense to you // don't worry. // next-tutorial:rotate """ @programs.tutorials.rotateTutorial = submenu: "Intro" title: "a taste of animation" code: """ // now that we have a box // let's rotate it: // type 'rotate 1' in the // line before the 'box' box // click for the next tutorial: // next-tutorial:frame """ @programs.tutorials.frameTutorial = submenu: "Animation" title: "frame" code: """ // make the box spin // by replacing '1' with 'frame' rotate 1 box // 'frame' contains a number // always incrementing as // the screen is re-drawn. // (use 'frame/100' to slow it down) // next-tutorial:time """ @programs.tutorials.timeTutorial = submenu: "Animation" title: "time" code: """ // 'frame/100' has one problem: // faster computers will make // the cube spin too fast. // Replace it with 'time/2'. rotate frame/100 box // 'time' counts the // number of seconds since // the program started, so it's // independent of how fast // the computer is at drawing. // next-tutorial:move """ @programs.tutorials.moveTutorial = submenu: "Placing things" title: "move" code: """ // you can move any object // by using 'move' box move 1,1,0 box // try to use a rotate before // the first box to see how the // scene changes. // next-tutorial:scale """ @programs.tutorials.scaleTutorial = submenu: "Placing things" title: "scale" code: """ // you can make an object bigger // or smaller by using 'scale' rotate 3 box move 1 scale 2 box // try to use scale or move before // the first box to see how the // scene changes. // next-tutorial:times """ @programs.tutorials.timesTutorial = submenu: "Repeating stuff" title: "times" code: """ // 'times' (not to be confused with // 'time'!) can be used to // repeat operations like so: rotate 1 3 times โ–ถmove 0.2,0.2,0.2 โ–ถbox // note how the tabs indicate // exactly the block of code // to be repeated. // next-tutorial:fill """ @programs.tutorials.fillTutorial = submenu: "Graphics" title: "fill" code: """ // 'fill' changes the // color of all the faces: rotate 1 fill 255,255,0 box // the three numbers indicate // red green and blue values. // You can also use color names such as 'indigo' // Try replacing the numbers with // 'angleColor' // next-tutorial:stroke """ @programs.tutorials.strokeTutorial = submenu: "Graphics" title: "stroke" code: """ // 'stroke' changes all the // edges: rotate 1 strokeSize 5 stroke 255,255,255 box // the three numbers are RGB // but you can also use the color names // or the special color 'angleColor' // Also you can use 'strokeSize' // to specify the thickness. // next-tutorial:color_names """ @programs.tutorials.colornamesTutorial = submenu: "Graphics" title: "color by name" code: """ // you can call colors by name // try to un-comment one line: //fill greenyellow //fill indigo //fill lemonchiffon // whaaaat? rotate 1 box // more color names here: // http://html-color-codes.info/color-names/ // (just use them in lower case) // next-tutorial:lights """ @programs.tutorials.lightsTutorial = submenu: "Graphics" title: "lights" code: """ // 'ambientLight' creates an // ambient light so things have // some sort of shading: ambientLight 0,255,255 rotate time box // you can turn that light on and // off while you build the scene // by using 'lights' and 'noLights' // next-tutorial:background """ @programs.tutorials.backgroundTutorial = submenu: "Graphics" title: "background" code: """ // 'background' creates a // solid background: background 0,0,255 rotate time box // next-tutorial:gradient """ @programs.tutorials.gradientTutorial = submenu: "Graphics" title: "gradient" code: """ // even nicer, you can paint a // background gradient: simpleGradient color(190,10,10),color(30,90,100),color(0) rotate time box // next-tutorial:line """ @programs.tutorials.lineTutorial = submenu: "Graphics" title: "line" code: """ // draw lines like this: 20 times โ–ถrotate time/9 โ–ถline // next-tutorial:ball """ @programs.tutorials.ballTutorial = submenu: "Graphics" title: "ball" code: """ // draw balls like this: ballDetail 10 3 times โ–ถmove 0.2,0.2,0.2 โ–ถball // ('ballDetail' is optional) // next-tutorial:pushpopMatrix """ @programs.tutorials.pushpopMatrixTutorial = submenu: "Graphics" title: "push and pop" code: """ // pushMatrix creates a bookmark of // the position, which you can // return to later by using popMatrix. // You can reset using 'resetMatrix'. rotate time pushMatrix // bookmark the position after the rotation line move 0.5,0,0 line popMatrix // go back to the bookmarked position move -0.5,0,0 line resetMatrix // resets the position line // not affected by initial rotation // next-tutorial:animation_style """ @programs.tutorials.animationstyleTutorial = submenu: "Graphics" title: "animation style" code: """ // try uncommenting either line // with the animationStyle background 255 //animationStyle motionBlur //animationStyle paintOver rotate frame/10 box // next-tutorial:do_once """ @programs.tutorials.doonceTutorial = submenu: "Controlling flow" title: "do once" code: """ // delete either check mark below rotate time โœ“doOnce โ–ถbackground 255 โ–ถfill 255,0,0 โœ“doOnce ball box // ...the line or block of code // are ran one time only, after that the // check marks immediately re-appear // P.S. keep hitting the delete button // on that first check mark for seizures. // next-tutorial:conditionals """ @programs.tutorials.conditionalsTutorial = submenu: "Controlling flow" title: "conditionals" code: """ // you can draw different things // (or in general do different things) // based on any // test condition you want: rotate if frame%3 == 0 โ–ถbox else if frame%3 == 1 โ–ถball else โ–ถpeg // next-tutorial:autocode """ @programs.tutorials.autocodeTutorial = submenu: "Others" title: "autocode" code: """ // the Autocode button invents random // variations for you. // You can interrupt the Autocoder at // any time by pressing the button again, // or you can press CTRL-Z // (or CMD-Z on Macs) to undo (or re-do) some of // the steps even WHILE the autocoder is running, // if you see that things got // boring down a particular path of changes. """ kickOff: -> setInterval( ()=> @pollHash() , 100) # Setup Event Listeners @eventRouter.addListener("url-hash-changed", (hash) => @loadAppropriateDemoOrTutorialBasedOnHash hash ) loadDemoOrTutorial: (demoName) -> if (not Detector.webgl or @liveCodeLabCoreInstance.threeJsSystem.forceCanvasRenderer) \ and not userWarnedAboutWebglExamples and demoName.indexOf("webgl") is 0 userWarnedAboutWebglExamples = true $("#exampleNeedsWebgl").modal() $("#simplemodal-container").height 200 # set the demo as a hash state # so that ideally people can link directly to # a specific demo they like. @eventRouter.emit("set-url-hash", "bookmark=" + demoName) @eventRouter.emit("big-cursor-hide") @eventRouter.emit("editor-undim") @liveCodeLabCoreInstance.graphicsCommands.doTheSpinThingy = false prependMessage = "" if (not Detector.webgl or @liveCodeLabCoreInstance.threeJsSystem.forceCanvasRenderer) \ and demoName.indexOf("webgl") is 0 prependMessage = """ // This drawing makes much more sense // in a WebGL-enabled browser. """ # Note that setting the value of the texteditor (texteditor.setValue below) # triggers the codeMirror onChange callback, which registers the new # code - so the next draw() will run the new demo code. But before doing # that will happen (when the timer for the next frame triggers), we'll # have cleared the screen with the code below. if @programs.demos[demoName] || @programs.tutorials[demoName] if @programs.demos[demoName] # the "replace" here is to change the arrows in tabs @texteditor.setValue prependMessage + @programs.demos[demoName].code.replace(/\u25B6/g, "\t") else if @programs.tutorials[demoName] # the "replace" here is to change the arrows in tabs @texteditor.setValue prependMessage + @programs.tutorials[demoName].code.replace(/\u25B6/g, "\t") # clear history. Why? Because we want to avoid the follwing: # user opens an example. User opens another example. # User performs undo. Result: previous example is open, but the hashtag # doesn't match the example. It's just confusing - we assume here that is # the user selects another tutorial and example then she is not expecting # the undo history to bring her back to previous demos/examples. # Note that, again, this is quite common in CodeMirror, the clearHistory # invokation below only works if slightly postponed. Not sure why. setTimeout((()=>@texteditor.clearHistory()),30) # bring the cursor to the top @texteditor.setCursor 0, 0 # we want to avoid that the selected example # or tutorial when started paints over a screen with a previous drawing # of the previous code. # So basically we draw an empty frame. # a) make sure that animationStyle is "normal" # b) apply the potentially new animationStyle # render the empty frame blendControls = @liveCodeLabCoreInstance.blendControls blendControls.animationStyle blendControls.animationStyles.normal blendControls.animationStyleUpdateIfChanged() @liveCodeLabCoreInstance.renderer.render @liveCodeLabCoreInstance.graphicsCommands loadAppropriateDemoOrTutorialBasedOnHash: (hash) -> matched = hash.match(/bookmark=(.*)/) if matched @loadDemoOrTutorial matched[1] else # user in on the root page without any hashes @texteditor.setValue "" # reset undo history setTimeout((()=>@texteditor.clearHistory()),30) # this paragraph from http://stackoverflow.com/a/629817 # there are more elegant ways to track back/forward history # but they are more complex than this. I don't mind having a bit of # polling for this, not too big of a problem. pollHash: -> if @lastHash isnt location.hash @lastHash = location.hash # hash has changed, so do stuff: @loadAppropriateDemoOrTutorialBasedOnHash @lastHash ProgramLoader
[ { "context": "github\n headers = {\n 'User-Agent': 'Autocode <support@autocode.run> (https://autocode.run/autocode)'\n }\n \n # get ", "end": 1008, "score": 0.9998661875724792, "start": 988, "tag": "EMAIL", "value": "support@autocode.run" } ]
src/autocode/install.coffee
crystal/autocode-js
92
# load deps autocode = require '../autocode' colors = require 'colors' fs = require 'fs' mkdirp = require 'mkdirp' path = require 'path' request = require 'sync-request' semver = require 'semver' untar = require 'untar.js' userHome = require 'user-home' zlib = require 'zlib' install = (opts) -> # hardcoded host host = 'github.com' # get module name if typeof opts == 'object' && opts.name module_name = opts.name # get module version if typeof opts == 'object' && opts.version module_version = opts.version else if module_name.match '@' module_parse = module_name.split '@' module_name = module_parse[0] module_version = module_parse[1] else module_version = 'latest' # require module name if !module_name throw new Error "Module Name is required for `autocode install`." console.log "Loading module (#{module_name})...".blue # set headers for github headers = { 'User-Agent': 'Autocode <support@autocode.run> (https://autocode.run/autocode)' } # get access token url access_token_url = '' if process.env.GITHUB_ACCESS_TOKEN access_token_url += "?access_token=#{process.env.GITHUB_ACCESS_TOKEN}" if module_version == 'latest' module_is_lastest = true # get latest release release_url = "https://api.github.com/repos/#{module_name}/releases/latest#{access_token_url}" release_resp = request 'get', release_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if release_resp.statusCode != 200 throw new Error "Module (#{module_name}) does not exist on GitHub." release = JSON.parse release_resp.body if !release throw new Error "Unable to locate generator (#{name})." module_version = semver.clean release.tag_name tag_name = release.tag_name console.log "Latest version is #{release.tag_name}.".green else module_is_lastest = false # get releases release_url = "https://api.github.com/repos/#{module_name}/releases#{access_token_url}" release_resp = request 'get', release_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if release_resp.statusCode != 200 throw new Error "Module (#{module_name}) does not exist on GitHub." releases = JSON.parse release_resp.body if !releases throw new Error "Unable to locate generator (#{name})." release_i = 0 for release in releases release_version = semver.clean release.tag_name if semver.satisfies release_version, module_version if release_i == 0 module_is_lastest = true module_version = semver.clean release.tag_name tag_name = release.tag_name break release_i++ if !tag_name throw new Error "Unable to find version (#{module_version}) for module (#{module_name})." console.log "Found version (#{module_version}) with tag (#{tag_name}).".green # check if autocode config exists for project if opts.force != true config_url = "https://api.github.com/repos/#{module_name}/contents/.autocode/config.yml#{access_token_url}&ref=#{tag_name}" config_resp = request 'get', config_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if config_resp.statusCode != 200 throw new Error "Module (#{module_name}) has not implemented Autocode. Use -f to install anyways." # get module source url tarball_url = release.tarball_url console.log "Downloading from: #{tarball_url}".bold tarball_url += access_token_url tarball_response = request 'get', tarball_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if tarball_response.statusCode != 200 throw new Error "Unable to download module (#{module_name})." tarball = zlib.gunzipSync tarball_response.body if !tarball throw new Error "Unable to unzip module (#{module_name})." # get module path module_path = path.normalize "#{userHome}/.autocode/module/#{host}/#{module_name}/#{module_version}" if fs.existsSync(module_path) and opts.ignoreOverwrite return { name: module_name version: module_version } # untar module untar.untar(tarball).forEach (file) -> filename = file.filename.split('/').slice(1).join('/') file_path = path.dirname(filename) mkdirp.sync "#{module_path}/#{file_path}" buffer = new Buffer(file.fileData.length) i = 0 while i < file.fileData.length buffer.writeUInt8 file.fileData[i], i i++ fs.writeFileSync "#{module_path}/#{filename}", buffer if module_is_lastest link_path = path.normalize "#{userHome}/.autocode/module/#{host}/#{module_name}/latest" if fs.existsSync link_path fs.unlinkSync link_path fs.symlinkSync module_path, link_path project = new autocode module_path project.update() project.build { skipGeneration: true } console.log "Successfully installed #{module_name} at: #{module_path}".green { name: module_name version: module_version } module.exports = install
217093
# load deps autocode = require '../autocode' colors = require 'colors' fs = require 'fs' mkdirp = require 'mkdirp' path = require 'path' request = require 'sync-request' semver = require 'semver' untar = require 'untar.js' userHome = require 'user-home' zlib = require 'zlib' install = (opts) -> # hardcoded host host = 'github.com' # get module name if typeof opts == 'object' && opts.name module_name = opts.name # get module version if typeof opts == 'object' && opts.version module_version = opts.version else if module_name.match '@' module_parse = module_name.split '@' module_name = module_parse[0] module_version = module_parse[1] else module_version = 'latest' # require module name if !module_name throw new Error "Module Name is required for `autocode install`." console.log "Loading module (#{module_name})...".blue # set headers for github headers = { 'User-Agent': 'Autocode <<EMAIL>> (https://autocode.run/autocode)' } # get access token url access_token_url = '' if process.env.GITHUB_ACCESS_TOKEN access_token_url += "?access_token=#{process.env.GITHUB_ACCESS_TOKEN}" if module_version == 'latest' module_is_lastest = true # get latest release release_url = "https://api.github.com/repos/#{module_name}/releases/latest#{access_token_url}" release_resp = request 'get', release_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if release_resp.statusCode != 200 throw new Error "Module (#{module_name}) does not exist on GitHub." release = JSON.parse release_resp.body if !release throw new Error "Unable to locate generator (#{name})." module_version = semver.clean release.tag_name tag_name = release.tag_name console.log "Latest version is #{release.tag_name}.".green else module_is_lastest = false # get releases release_url = "https://api.github.com/repos/#{module_name}/releases#{access_token_url}" release_resp = request 'get', release_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if release_resp.statusCode != 200 throw new Error "Module (#{module_name}) does not exist on GitHub." releases = JSON.parse release_resp.body if !releases throw new Error "Unable to locate generator (#{name})." release_i = 0 for release in releases release_version = semver.clean release.tag_name if semver.satisfies release_version, module_version if release_i == 0 module_is_lastest = true module_version = semver.clean release.tag_name tag_name = release.tag_name break release_i++ if !tag_name throw new Error "Unable to find version (#{module_version}) for module (#{module_name})." console.log "Found version (#{module_version}) with tag (#{tag_name}).".green # check if autocode config exists for project if opts.force != true config_url = "https://api.github.com/repos/#{module_name}/contents/.autocode/config.yml#{access_token_url}&ref=#{tag_name}" config_resp = request 'get', config_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if config_resp.statusCode != 200 throw new Error "Module (#{module_name}) has not implemented Autocode. Use -f to install anyways." # get module source url tarball_url = release.tarball_url console.log "Downloading from: #{tarball_url}".bold tarball_url += access_token_url tarball_response = request 'get', tarball_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if tarball_response.statusCode != 200 throw new Error "Unable to download module (#{module_name})." tarball = zlib.gunzipSync tarball_response.body if !tarball throw new Error "Unable to unzip module (#{module_name})." # get module path module_path = path.normalize "#{userHome}/.autocode/module/#{host}/#{module_name}/#{module_version}" if fs.existsSync(module_path) and opts.ignoreOverwrite return { name: module_name version: module_version } # untar module untar.untar(tarball).forEach (file) -> filename = file.filename.split('/').slice(1).join('/') file_path = path.dirname(filename) mkdirp.sync "#{module_path}/#{file_path}" buffer = new Buffer(file.fileData.length) i = 0 while i < file.fileData.length buffer.writeUInt8 file.fileData[i], i i++ fs.writeFileSync "#{module_path}/#{filename}", buffer if module_is_lastest link_path = path.normalize "#{userHome}/.autocode/module/#{host}/#{module_name}/latest" if fs.existsSync link_path fs.unlinkSync link_path fs.symlinkSync module_path, link_path project = new autocode module_path project.update() project.build { skipGeneration: true } console.log "Successfully installed #{module_name} at: #{module_path}".green { name: module_name version: module_version } module.exports = install
true
# load deps autocode = require '../autocode' colors = require 'colors' fs = require 'fs' mkdirp = require 'mkdirp' path = require 'path' request = require 'sync-request' semver = require 'semver' untar = require 'untar.js' userHome = require 'user-home' zlib = require 'zlib' install = (opts) -> # hardcoded host host = 'github.com' # get module name if typeof opts == 'object' && opts.name module_name = opts.name # get module version if typeof opts == 'object' && opts.version module_version = opts.version else if module_name.match '@' module_parse = module_name.split '@' module_name = module_parse[0] module_version = module_parse[1] else module_version = 'latest' # require module name if !module_name throw new Error "Module Name is required for `autocode install`." console.log "Loading module (#{module_name})...".blue # set headers for github headers = { 'User-Agent': 'Autocode <PI:EMAIL:<EMAIL>END_PI> (https://autocode.run/autocode)' } # get access token url access_token_url = '' if process.env.GITHUB_ACCESS_TOKEN access_token_url += "?access_token=#{process.env.GITHUB_ACCESS_TOKEN}" if module_version == 'latest' module_is_lastest = true # get latest release release_url = "https://api.github.com/repos/#{module_name}/releases/latest#{access_token_url}" release_resp = request 'get', release_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if release_resp.statusCode != 200 throw new Error "Module (#{module_name}) does not exist on GitHub." release = JSON.parse release_resp.body if !release throw new Error "Unable to locate generator (#{name})." module_version = semver.clean release.tag_name tag_name = release.tag_name console.log "Latest version is #{release.tag_name}.".green else module_is_lastest = false # get releases release_url = "https://api.github.com/repos/#{module_name}/releases#{access_token_url}" release_resp = request 'get', release_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if release_resp.statusCode != 200 throw new Error "Module (#{module_name}) does not exist on GitHub." releases = JSON.parse release_resp.body if !releases throw new Error "Unable to locate generator (#{name})." release_i = 0 for release in releases release_version = semver.clean release.tag_name if semver.satisfies release_version, module_version if release_i == 0 module_is_lastest = true module_version = semver.clean release.tag_name tag_name = release.tag_name break release_i++ if !tag_name throw new Error "Unable to find version (#{module_version}) for module (#{module_name})." console.log "Found version (#{module_version}) with tag (#{tag_name}).".green # check if autocode config exists for project if opts.force != true config_url = "https://api.github.com/repos/#{module_name}/contents/.autocode/config.yml#{access_token_url}&ref=#{tag_name}" config_resp = request 'get', config_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if config_resp.statusCode != 200 throw new Error "Module (#{module_name}) has not implemented Autocode. Use -f to install anyways." # get module source url tarball_url = release.tarball_url console.log "Downloading from: #{tarball_url}".bold tarball_url += access_token_url tarball_response = request 'get', tarball_url, { headers: headers, allowRedirectHeaders: ['User-Agent'] } if tarball_response.statusCode != 200 throw new Error "Unable to download module (#{module_name})." tarball = zlib.gunzipSync tarball_response.body if !tarball throw new Error "Unable to unzip module (#{module_name})." # get module path module_path = path.normalize "#{userHome}/.autocode/module/#{host}/#{module_name}/#{module_version}" if fs.existsSync(module_path) and opts.ignoreOverwrite return { name: module_name version: module_version } # untar module untar.untar(tarball).forEach (file) -> filename = file.filename.split('/').slice(1).join('/') file_path = path.dirname(filename) mkdirp.sync "#{module_path}/#{file_path}" buffer = new Buffer(file.fileData.length) i = 0 while i < file.fileData.length buffer.writeUInt8 file.fileData[i], i i++ fs.writeFileSync "#{module_path}/#{filename}", buffer if module_is_lastest link_path = path.normalize "#{userHome}/.autocode/module/#{host}/#{module_name}/latest" if fs.existsSync link_path fs.unlinkSync link_path fs.symlinkSync module_path, link_path project = new autocode module_path project.update() project.build { skipGeneration: true } console.log "Successfully installed #{module_name} at: #{module_path}".green { name: module_name version: module_version } module.exports = install
[ { "context": "oad selected foods from localStorage\n saveKey = \"selectedFoods\"\n selectedFoods = window.localStorage.getItem(sa", "end": 1566, "score": 0.5784461498260498, "start": 1553, "tag": "KEY", "value": "selectedFoods" } ]
src/factories/ComparePage.coffee
ryanatkn/nutrients-per-calorie
17
module.exports = ($location, FoodData) -> data = query: text: "" includeFoodGroups: false selectedFoods: [] isSelected: (food) -> !!_.find data.selectedFoods, (f) -> f.NDB_No is food.NDB_No toggle: (food) -> if data.isSelected(food) data.deselect food else data.select food deselect: (food) -> data.selectedFoods = _.reject(data.selectedFoods, (f) -> f.NDB_No is food.NDB_No) save() select: (food) -> data.deselect food data.selectedFoods.push _.clone(food) save() clear: -> for food in data.selectedFoods.slice(1) FoodData.findFoodById(food.NDB_No).selected = false data.reset() reset: (foods) -> data.selectedFoods = if FoodData.benchmarkFood then [FoodData.benchmarkFood] else [] if foods data.selectedFoods = data.selectedFoods.concat(foods) save() basePath: "#/compare" updatePath: -> window.location.hash = data.getPath() getPath: (foods = data.selectedFoods.slice(1)) -> data.basePath + data.getSearch(foods) getSearch: (foods = data.selectedFoods.slice(1)) -> if foods.length "?foods=" + _.pluck(foods, "NDB_No").join(",") else "" getPathWithFoodAdded: (food) -> if food foods = _.clone(data.selectedFoods) if !_.find(foods, (f) -> f.NDB_No is food.NDB_No) foods.push food data.getPath foods else data.basePath # Try to load selected foods from localStorage saveKey = "selectedFoods" selectedFoods = window.localStorage.getItem(saveKey) if selectedFoods data.selectedFoods = JSON.parse(selectedFoods) save = -> window.localStorage.setItem saveKey, JSON.stringify(data.selectedFoods) data
19190
module.exports = ($location, FoodData) -> data = query: text: "" includeFoodGroups: false selectedFoods: [] isSelected: (food) -> !!_.find data.selectedFoods, (f) -> f.NDB_No is food.NDB_No toggle: (food) -> if data.isSelected(food) data.deselect food else data.select food deselect: (food) -> data.selectedFoods = _.reject(data.selectedFoods, (f) -> f.NDB_No is food.NDB_No) save() select: (food) -> data.deselect food data.selectedFoods.push _.clone(food) save() clear: -> for food in data.selectedFoods.slice(1) FoodData.findFoodById(food.NDB_No).selected = false data.reset() reset: (foods) -> data.selectedFoods = if FoodData.benchmarkFood then [FoodData.benchmarkFood] else [] if foods data.selectedFoods = data.selectedFoods.concat(foods) save() basePath: "#/compare" updatePath: -> window.location.hash = data.getPath() getPath: (foods = data.selectedFoods.slice(1)) -> data.basePath + data.getSearch(foods) getSearch: (foods = data.selectedFoods.slice(1)) -> if foods.length "?foods=" + _.pluck(foods, "NDB_No").join(",") else "" getPathWithFoodAdded: (food) -> if food foods = _.clone(data.selectedFoods) if !_.find(foods, (f) -> f.NDB_No is food.NDB_No) foods.push food data.getPath foods else data.basePath # Try to load selected foods from localStorage saveKey = "<KEY>" selectedFoods = window.localStorage.getItem(saveKey) if selectedFoods data.selectedFoods = JSON.parse(selectedFoods) save = -> window.localStorage.setItem saveKey, JSON.stringify(data.selectedFoods) data
true
module.exports = ($location, FoodData) -> data = query: text: "" includeFoodGroups: false selectedFoods: [] isSelected: (food) -> !!_.find data.selectedFoods, (f) -> f.NDB_No is food.NDB_No toggle: (food) -> if data.isSelected(food) data.deselect food else data.select food deselect: (food) -> data.selectedFoods = _.reject(data.selectedFoods, (f) -> f.NDB_No is food.NDB_No) save() select: (food) -> data.deselect food data.selectedFoods.push _.clone(food) save() clear: -> for food in data.selectedFoods.slice(1) FoodData.findFoodById(food.NDB_No).selected = false data.reset() reset: (foods) -> data.selectedFoods = if FoodData.benchmarkFood then [FoodData.benchmarkFood] else [] if foods data.selectedFoods = data.selectedFoods.concat(foods) save() basePath: "#/compare" updatePath: -> window.location.hash = data.getPath() getPath: (foods = data.selectedFoods.slice(1)) -> data.basePath + data.getSearch(foods) getSearch: (foods = data.selectedFoods.slice(1)) -> if foods.length "?foods=" + _.pluck(foods, "NDB_No").join(",") else "" getPathWithFoodAdded: (food) -> if food foods = _.clone(data.selectedFoods) if !_.find(foods, (f) -> f.NDB_No is food.NDB_No) foods.push food data.getPath foods else data.basePath # Try to load selected foods from localStorage saveKey = "PI:KEY:<KEY>END_PI" selectedFoods = window.localStorage.getItem(saveKey) if selectedFoods data.selectedFoods = JSON.parse(selectedFoods) save = -> window.localStorage.setItem saveKey, JSON.stringify(data.selectedFoods) data
[ { "context": " the dom-navigation methods\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\nElement.include\n #\n # Finds _all_ matching su", "end": 89, "score": 0.9998868703842163, "start": 72, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/dom/src/element/navigation.coffee
lovely-io/lovely.io-stl
2
# # This module keeps the dom-navigation methods # # Copyright (C) 2011 Nikolay Nemshilov # Element.include # # Finds _all_ matching sub-elements # # @param {String} css-rule # @param {Boolean} marker if you want an Array of raw dom-elements # @return {NodeList|Array} matching elements collection # find: (css_rule, needs_raw)-> result = @_.querySelectorAll(css_rule||'*') if needs_raw is true then result else new NodeList(result, true) # # Finds the _first_ matching sub-element, or just the first # element if no css-rule was specified # # @param {String} css-rule # @return {Element} matching element or `null` # first: (css_rule)-> if css_rule is undefined && @_.firstElementChild isnt undefined element = @_.firstElementChild else element = @_.querySelector(css_rule||'*') wrap(element) # # Checks if the element matches given css-rule # # NOTE: the element should be attached to the page # # @param {String} css-rule # @return {Boolean} check result # match: (css_rule) -> for element in @document().find(css_rule, true) if element is @_ return true return false # # Returns the parent element or the first parent # element that match the css-rule # # @param {String} optional css-rule # @return {Element} matching parent or `null` # parent: (css_rule) -> if css_rule @parents(css_rule)[0] else wrap(@_.parentNode) # # Finds all the parent elements of current element # optinally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # parents: (css_rule) -> Element_recursively_collect(@, 'parentNode', css_rule) # # Returns the list of immediate children of the element # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # children: (css_rule) -> @find(css_rule).filter (element)-> element._.parentNode is @_ , @ # # Returns a list of the element siblings # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # siblings: (css_rule) -> @previousSiblings(css_rule).reverse().concat(@nextSiblings(css_rule).toArray()) # # Returns a list of the next siblings of the element # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # nextSiblings: (css_rule)-> Element_recursively_collect(@, 'nextSibling', css_rule) # # Returns a list of the previous siblings of the element # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # previousSiblings: (css_rule)-> Element_recursively_collect(@, 'previousSibling', css_rule) # # Returns the next sibling element, optionally # the next sibling that matches a css-rule # # @param {String} optional css-rule # @return {Element} sibling element or `null` # nextSibling: (css_rule) -> if css_rule is undefined and @_.nextElementSibling isnt undefined wrap(@_.nextElementSibling) else @nextSiblings(css_rule)[0] # # Returns the next sibling element, optionally # the next sibling that matches a css-rule # # @param {String} optional css-rule # @return {Element} sibling element or `null` # previousSibling: (css_rule) -> if css_rule is undefined and @_.previousElementSibling isnt undefined wrap(@_.previousElementSibling) else @previousSiblings(css_rule)[0] # private # # Recursively collects stuff from the element # wraps them up with the {Element} instances # and returns as a standard {NodeList} result # # @param {Element} start point # @param {String} attribute # @param {String} css-rule # @return {NodeList} result # Element_recursively_collect = (element, attr, css_rule)-> result = []; node = element._; no_rule = css_rule is undefined css_rule = element.document().find(css_rule, true) unless no_rule match = (node)-> for element in css_rule if element is node return true return false while (node = node[attr]) isnt null if node.nodeType is 1 and (no_rule or match(node)) result.push(node) return new NodeList(result)
215672
# # This module keeps the dom-navigation methods # # Copyright (C) 2011 <NAME> # Element.include # # Finds _all_ matching sub-elements # # @param {String} css-rule # @param {Boolean} marker if you want an Array of raw dom-elements # @return {NodeList|Array} matching elements collection # find: (css_rule, needs_raw)-> result = @_.querySelectorAll(css_rule||'*') if needs_raw is true then result else new NodeList(result, true) # # Finds the _first_ matching sub-element, or just the first # element if no css-rule was specified # # @param {String} css-rule # @return {Element} matching element or `null` # first: (css_rule)-> if css_rule is undefined && @_.firstElementChild isnt undefined element = @_.firstElementChild else element = @_.querySelector(css_rule||'*') wrap(element) # # Checks if the element matches given css-rule # # NOTE: the element should be attached to the page # # @param {String} css-rule # @return {Boolean} check result # match: (css_rule) -> for element in @document().find(css_rule, true) if element is @_ return true return false # # Returns the parent element or the first parent # element that match the css-rule # # @param {String} optional css-rule # @return {Element} matching parent or `null` # parent: (css_rule) -> if css_rule @parents(css_rule)[0] else wrap(@_.parentNode) # # Finds all the parent elements of current element # optinally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # parents: (css_rule) -> Element_recursively_collect(@, 'parentNode', css_rule) # # Returns the list of immediate children of the element # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # children: (css_rule) -> @find(css_rule).filter (element)-> element._.parentNode is @_ , @ # # Returns a list of the element siblings # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # siblings: (css_rule) -> @previousSiblings(css_rule).reverse().concat(@nextSiblings(css_rule).toArray()) # # Returns a list of the next siblings of the element # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # nextSiblings: (css_rule)-> Element_recursively_collect(@, 'nextSibling', css_rule) # # Returns a list of the previous siblings of the element # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # previousSiblings: (css_rule)-> Element_recursively_collect(@, 'previousSibling', css_rule) # # Returns the next sibling element, optionally # the next sibling that matches a css-rule # # @param {String} optional css-rule # @return {Element} sibling element or `null` # nextSibling: (css_rule) -> if css_rule is undefined and @_.nextElementSibling isnt undefined wrap(@_.nextElementSibling) else @nextSiblings(css_rule)[0] # # Returns the next sibling element, optionally # the next sibling that matches a css-rule # # @param {String} optional css-rule # @return {Element} sibling element or `null` # previousSibling: (css_rule) -> if css_rule is undefined and @_.previousElementSibling isnt undefined wrap(@_.previousElementSibling) else @previousSiblings(css_rule)[0] # private # # Recursively collects stuff from the element # wraps them up with the {Element} instances # and returns as a standard {NodeList} result # # @param {Element} start point # @param {String} attribute # @param {String} css-rule # @return {NodeList} result # Element_recursively_collect = (element, attr, css_rule)-> result = []; node = element._; no_rule = css_rule is undefined css_rule = element.document().find(css_rule, true) unless no_rule match = (node)-> for element in css_rule if element is node return true return false while (node = node[attr]) isnt null if node.nodeType is 1 and (no_rule or match(node)) result.push(node) return new NodeList(result)
true
# # This module keeps the dom-navigation methods # # Copyright (C) 2011 PI:NAME:<NAME>END_PI # Element.include # # Finds _all_ matching sub-elements # # @param {String} css-rule # @param {Boolean} marker if you want an Array of raw dom-elements # @return {NodeList|Array} matching elements collection # find: (css_rule, needs_raw)-> result = @_.querySelectorAll(css_rule||'*') if needs_raw is true then result else new NodeList(result, true) # # Finds the _first_ matching sub-element, or just the first # element if no css-rule was specified # # @param {String} css-rule # @return {Element} matching element or `null` # first: (css_rule)-> if css_rule is undefined && @_.firstElementChild isnt undefined element = @_.firstElementChild else element = @_.querySelector(css_rule||'*') wrap(element) # # Checks if the element matches given css-rule # # NOTE: the element should be attached to the page # # @param {String} css-rule # @return {Boolean} check result # match: (css_rule) -> for element in @document().find(css_rule, true) if element is @_ return true return false # # Returns the parent element or the first parent # element that match the css-rule # # @param {String} optional css-rule # @return {Element} matching parent or `null` # parent: (css_rule) -> if css_rule @parents(css_rule)[0] else wrap(@_.parentNode) # # Finds all the parent elements of current element # optinally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # parents: (css_rule) -> Element_recursively_collect(@, 'parentNode', css_rule) # # Returns the list of immediate children of the element # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # children: (css_rule) -> @find(css_rule).filter (element)-> element._.parentNode is @_ , @ # # Returns a list of the element siblings # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # siblings: (css_rule) -> @previousSiblings(css_rule).reverse().concat(@nextSiblings(css_rule).toArray()) # # Returns a list of the next siblings of the element # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # nextSiblings: (css_rule)-> Element_recursively_collect(@, 'nextSibling', css_rule) # # Returns a list of the previous siblings of the element # optionally filtered by a css-rule # # @param {String} optional css-rule # @return {NodeList} list of matching elements # previousSiblings: (css_rule)-> Element_recursively_collect(@, 'previousSibling', css_rule) # # Returns the next sibling element, optionally # the next sibling that matches a css-rule # # @param {String} optional css-rule # @return {Element} sibling element or `null` # nextSibling: (css_rule) -> if css_rule is undefined and @_.nextElementSibling isnt undefined wrap(@_.nextElementSibling) else @nextSiblings(css_rule)[0] # # Returns the next sibling element, optionally # the next sibling that matches a css-rule # # @param {String} optional css-rule # @return {Element} sibling element or `null` # previousSibling: (css_rule) -> if css_rule is undefined and @_.previousElementSibling isnt undefined wrap(@_.previousElementSibling) else @previousSiblings(css_rule)[0] # private # # Recursively collects stuff from the element # wraps them up with the {Element} instances # and returns as a standard {NodeList} result # # @param {Element} start point # @param {String} attribute # @param {String} css-rule # @return {NodeList} result # Element_recursively_collect = (element, attr, css_rule)-> result = []; node = element._; no_rule = css_rule is undefined css_rule = element.document().find(css_rule, true) unless no_rule match = (node)-> for element in css_rule if element is node return true return false while (node = node[attr]) isnt null if node.nodeType is 1 and (no_rule or match(node)) result.push(node) return new NodeList(result)
[ { "context": "OFTWARE.\n\nangular-google-maps\nhttps://github.com/nlaplante/angular-google-maps\n\n@authors Bruno Queiroz, crea", "end": 1154, "score": 0.631291389465332, "start": 1146, "tag": "USERNAME", "value": "laplante" }, { "context": "github.com/nlaplante/angular-google-maps\n\n@authors Bruno Queiroz, creativelikeadog@gmail.com\n###\n\n###\nMarker label", "end": 1198, "score": 0.9998719692230225, "start": 1185, "tag": "NAME", "value": "Bruno Queiroz" }, { "context": "lante/angular-google-maps\n\n@authors Bruno Queiroz, creativelikeadog@gmail.com\n###\n\n###\nMarker label directive\n\nThis directive i", "end": 1226, "score": 0.9999005198478699, "start": 1200, "tag": "EMAIL", "value": "creativelikeadog@gmail.com" } ]
www/lib/js/angular-google-maps/src/coffee/directives/label.coffee
neilff/liqbo-cordova
1
### ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Bruno Queiroz, creativelikeadog@gmail.com ### ### Marker label directive This directive is used to create a marker label on an existing map. {attribute content required} content of the label {attribute anchor required} string that contains the x and y point position of the label {attribute class optional} class to DOM object {attribute style optional} style for the label ### angular.module("google-maps").directive "markerLabel", ["$log", "$timeout", ($log, $timeout) -> new directives.api.Label($timeout) ]
186828
### ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors <NAME>, <EMAIL> ### ### Marker label directive This directive is used to create a marker label on an existing map. {attribute content required} content of the label {attribute anchor required} string that contains the x and y point position of the label {attribute class optional} class to DOM object {attribute style optional} style for the label ### angular.module("google-maps").directive "markerLabel", ["$log", "$timeout", ($log, $timeout) -> new directives.api.Label($timeout) ]
true
### ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI ### ### Marker label directive This directive is used to create a marker label on an existing map. {attribute content required} content of the label {attribute anchor required} string that contains the x and y point position of the label {attribute class optional} class to DOM object {attribute style optional} style for the label ### angular.module("google-maps").directive "markerLabel", ["$log", "$timeout", ($log, $timeout) -> new directives.api.Label($timeout) ]
[ { "context": " grunt-hipchat-v2-notifier\n# * https://github.com/logankoester/grunt-hipchat-v2-notifier\n# *\n# * Copyright (c) 2", "end": 67, "score": 0.9990495443344116, "start": 55, "tag": "USERNAME", "value": "logankoester" }, { "context": "ipchat-v2-notifier\n# *\n# * Copyright (c) 2013-2014 Logan Koester\n# * Licensed under the MIT license.\n#\n\nmodule.exp", "end": 139, "score": 0.9998948574066162, "start": 126, "tag": "NAME", "value": "Logan Koester" } ]
Gruntfile.coffee
jasonmit/grunt-hipchat-v2-notifier
1
# # * grunt-hipchat-v2-notifier # * https://github.com/logankoester/grunt-hipchat-v2-notifier # * # * Copyright (c) 2013-2014 Logan Koester # * Licensed under the MIT license. # module.exports = (grunt) -> # Project configuration. grunt.initConfig clean: tasks: ['tasks'] tests: ['tmp'] coffee: tasks: expand: true cwd: 'src/tasks/' src: '**/*.coffee' dest: 'tasks/' ext: '.js' bump: options: commit: true commitMessage: 'Release v%VERSION%' commitFiles: ['package.json'] createTag: true tagName: 'v%VERSION%' tagMessage: 'Version %VERSION%' push: false grunt.loadTasks 'tasks' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-bump' grunt.registerTask 'build', ['clean', 'coffee'] grunt.registerTask 'default', ['build']
112332
# # * grunt-hipchat-v2-notifier # * https://github.com/logankoester/grunt-hipchat-v2-notifier # * # * Copyright (c) 2013-2014 <NAME> # * Licensed under the MIT license. # module.exports = (grunt) -> # Project configuration. grunt.initConfig clean: tasks: ['tasks'] tests: ['tmp'] coffee: tasks: expand: true cwd: 'src/tasks/' src: '**/*.coffee' dest: 'tasks/' ext: '.js' bump: options: commit: true commitMessage: 'Release v%VERSION%' commitFiles: ['package.json'] createTag: true tagName: 'v%VERSION%' tagMessage: 'Version %VERSION%' push: false grunt.loadTasks 'tasks' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-bump' grunt.registerTask 'build', ['clean', 'coffee'] grunt.registerTask 'default', ['build']
true
# # * grunt-hipchat-v2-notifier # * https://github.com/logankoester/grunt-hipchat-v2-notifier # * # * Copyright (c) 2013-2014 PI:NAME:<NAME>END_PI # * Licensed under the MIT license. # module.exports = (grunt) -> # Project configuration. grunt.initConfig clean: tasks: ['tasks'] tests: ['tmp'] coffee: tasks: expand: true cwd: 'src/tasks/' src: '**/*.coffee' dest: 'tasks/' ext: '.js' bump: options: commit: true commitMessage: 'Release v%VERSION%' commitFiles: ['package.json'] createTag: true tagName: 'v%VERSION%' tagMessage: 'Version %VERSION%' push: false grunt.loadTasks 'tasks' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-bump' grunt.registerTask 'build', ['clean', 'coffee'] grunt.registerTask 'default', ['build']
[ { "context": "# The ray tracer code in this file is written by Adam Burmister. It\n# is available in its original form from:\n#\n#", "end": 63, "score": 0.9998309016227722, "start": 49, "tag": "NAME", "value": "Adam Burmister" }, { "context": "avaScript framework, version 1.5.0\n# (c) 2005-2007 Sam Stephenson\n#\n# Prototype is freely distributable under the t", "end": 807, "score": 0.9998420476913452, "start": 793, "tag": "NAME", "value": "Sam Stephenson" }, { "context": "t of this file is the actual ray tracer written by Adam\n# Burmister. It's a concatenation of the followin", "end": 1174, "score": 0.9997222423553467, "start": 1170, "tag": "NAME", "value": "Adam" }, { "context": "is file is the actual ray tracer written by Adam\n# Burmister. It's a concatenation of the following files:\n#\n#", "end": 1186, "score": 0.999301016330719, "start": 1177, "tag": "NAME", "value": "Burmister" } ]
deps/v8/benchmarks/raytrace.coffee
lxe/io.coffee
0
# The ray tracer code in this file is written by Adam Burmister. It # is available in its original form from: # # http://labs.flog.nz.co/raytracer/ # # It has been modified slightly by Google to work as a standalone # benchmark, but the all the computational code remains # untouched. This file also contains a copy of parts of the Prototype # JavaScript framework which is used by the ray tracer. # Variable used to hold a number that can be used to verify that # the scene was ray traced correctly. # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # The following is a copy of parts of the Prototype JavaScript library: # Prototype JavaScript framework, version 1.5.0 # (c) 2005-2007 Sam Stephenson # # Prototype is freely distributable under the terms of an MIT-style license. # For details, see the Prototype web site: http://prototype.conio.net/ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # The rest of this file is the actual ray tracer written by Adam # Burmister. It's a concatenation of the following files: # # flog/color.js # flog/light.js # flog/vector.js # flog/ray.js # flog/scene.js # flog/material/basematerial.js # flog/material/solid.js # flog/material/chessboard.js # flog/shape/baseshape.js # flog/shape/sphere.js # flog/shape/plane.js # flog/intersectioninfo.js # flog/camera.js # flog/background.js # flog/engine.js # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # [0...infinity] 0 = matt # 0=opaque # [0...infinity] 0 = no reflection # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # intersection! # Fake a Flog.* namespace # no intersection # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # 2d context we can render to # TODO: dynamically include other scripts # print(x * pxW, y * pxH, pxW, pxH); # Get canvas # Calc ambient # Calc diffuse lighting # The greater the depth the more accurate the colours, but # this is exponentially (!) expensive # calculate reflection ray # Refraction # TODO # Render shadows and highlights #&& shadowInfo.shape.type != 'PLANE' # Phong specular highlights renderScene = -> scene = new Flog.RayTracer.Scene() scene.camera = new Flog.RayTracer.Camera(new Flog.RayTracer.Vector(0, 0, -15), new Flog.RayTracer.Vector(-0.2, 0, 5), new Flog.RayTracer.Vector(0, 1, 0)) scene.background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0.5, 0.5, 0.5), 0.4) sphere = new Flog.RayTracer.Shape.Sphere(new Flog.RayTracer.Vector(-1.5, 1.5, 2), 1.5, new Flog.RayTracer.Material.Solid(new Flog.RayTracer.Color(0, 0.5, 0.5), 0.3, 0.0, 0.0, 2.0)) sphere1 = new Flog.RayTracer.Shape.Sphere(new Flog.RayTracer.Vector(1, 0.25, 1), 0.5, new Flog.RayTracer.Material.Solid(new Flog.RayTracer.Color(0.9, 0.9, 0.9), 0.1, 0.0, 0.0, 1.5)) plane = new Flog.RayTracer.Shape.Plane(new Flog.RayTracer.Vector(0.1, 0.9, -0.5).normalize(), 1.2, new Flog.RayTracer.Material.Chessboard(new Flog.RayTracer.Color(1, 1, 1), new Flog.RayTracer.Color(0, 0, 0), 0.2, 0.0, 1.0, 0.7)) scene.shapes.push plane scene.shapes.push sphere scene.shapes.push sphere1 light = new Flog.RayTracer.Light(new Flog.RayTracer.Vector(5, 10, -1), new Flog.RayTracer.Color(0.8, 0.8, 0.8)) light1 = new Flog.RayTracer.Light(new Flog.RayTracer.Vector(-3, 5, -15), new Flog.RayTracer.Color(0.8, 0.8, 0.8), 100) scene.lights.push light scene.lights.push light1 imageWidth = 100 # $F('imageWidth'); imageHeight = 100 # $F('imageHeight'); pixelSize = "5,5".split(",") # $F('pixelSize').split(','); renderDiffuse = true # $F('renderDiffuse'); renderShadows = true # $F('renderShadows'); renderHighlights = true # $F('renderHighlights'); renderReflections = true # $F('renderReflections'); rayDepth = 2 #$F('rayDepth'); raytracer = new Flog.RayTracer.Engine( canvasWidth: imageWidth canvasHeight: imageHeight pixelWidth: pixelSize[0] pixelHeight: pixelSize[1] renderDiffuse: renderDiffuse renderHighlights: renderHighlights renderShadows: renderShadows renderReflections: renderReflections rayDepth: rayDepth ) raytracer.renderScene scene, null, 0 return RayTrace = new BenchmarkSuite("RayTrace", 739989, [new Benchmark("RayTrace", renderScene)]) checkNumber = undefined Class = create: -> -> @initialize.apply this, arguments return Object.extend = (destination, source) -> for property of source destination[property] = source[property] destination Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Color = Class.create() Flog.RayTracer.Color:: = red: 0.0 green: 0.0 blue: 0.0 initialize: (r, g, b) -> r = 0.0 unless r g = 0.0 unless g b = 0.0 unless b @red = r @green = g @blue = b return add: (c1, c2) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red + c2.red result.green = c1.green + c2.green result.blue = c1.blue + c2.blue result addScalar: (c1, s) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red + s result.green = c1.green + s result.blue = c1.blue + s result.limit() result subtract: (c1, c2) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red - c2.red result.green = c1.green - c2.green result.blue = c1.blue - c2.blue result multiply: (c1, c2) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red * c2.red result.green = c1.green * c2.green result.blue = c1.blue * c2.blue result multiplyScalar: (c1, f) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red * f result.green = c1.green * f result.blue = c1.blue * f result divideFactor: (c1, f) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red / f result.green = c1.green / f result.blue = c1.blue / f result limit: -> @red = (if (@red > 0.0) then ((if (@red > 1.0) then 1.0 else @red)) else 0.0) @green = (if (@green > 0.0) then ((if (@green > 1.0) then 1.0 else @green)) else 0.0) @blue = (if (@blue > 0.0) then ((if (@blue > 1.0) then 1.0 else @blue)) else 0.0) return distance: (color) -> d = Math.abs(@red - color.red) + Math.abs(@green - color.green) + Math.abs(@blue - color.blue) d blend: (c1, c2, w) -> result = new Flog.RayTracer.Color(0, 0, 0) result = Flog.RayTracer.Color::add(Flog.RayTracer.Color::multiplyScalar(c1, 1 - w), Flog.RayTracer.Color::multiplyScalar(c2, w)) result brightness: -> r = Math.floor(@red * 255) g = Math.floor(@green * 255) b = Math.floor(@blue * 255) (r * 77 + g * 150 + b * 29) >> 8 toString: -> r = Math.floor(@red * 255) g = Math.floor(@green * 255) b = Math.floor(@blue * 255) "rgb(" + r + "," + g + "," + b + ")" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Light = Class.create() Flog.RayTracer.Light:: = position: null color: null intensity: 10.0 initialize: (pos, color, intensity) -> @position = pos @color = color @intensity = ((if intensity then intensity else 10.0)) return toString: -> "Light [" + @position.x + "," + @position.y + "," + @position.z + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Vector = Class.create() Flog.RayTracer.Vector:: = x: 0.0 y: 0.0 z: 0.0 initialize: (x, y, z) -> @x = ((if x then x else 0)) @y = ((if y then y else 0)) @z = ((if z then z else 0)) return copy: (vector) -> @x = vector.x @y = vector.y @z = vector.z return normalize: -> m = @magnitude() new Flog.RayTracer.Vector(@x / m, @y / m, @z / m) magnitude: -> Math.sqrt (@x * @x) + (@y * @y) + (@z * @z) cross: (w) -> new Flog.RayTracer.Vector(-@z * w.y + @y * w.z, @z * w.x - @x * w.z, -@y * w.x + @x * w.y) dot: (w) -> @x * w.x + @y * w.y + @z * w.z add: (v, w) -> new Flog.RayTracer.Vector(w.x + v.x, w.y + v.y, w.z + v.z) subtract: (v, w) -> throw "Vectors must be defined [" + v + "," + w + "]" if not w or not v new Flog.RayTracer.Vector(v.x - w.x, v.y - w.y, v.z - w.z) multiplyVector: (v, w) -> new Flog.RayTracer.Vector(v.x * w.x, v.y * w.y, v.z * w.z) multiplyScalar: (v, w) -> new Flog.RayTracer.Vector(v.x * w, v.y * w, v.z * w) toString: -> "Vector [" + @x + "," + @y + "," + @z + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Ray = Class.create() Flog.RayTracer.Ray:: = position: null direction: null initialize: (pos, dir) -> @position = pos @direction = dir return toString: -> "Ray [" + @position + "," + @direction + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Scene = Class.create() Flog.RayTracer.Scene:: = camera: null shapes: [] lights: [] background: null initialize: -> @camera = new Flog.RayTracer.Camera(new Flog.RayTracer.Vector(0, 0, -5), new Flog.RayTracer.Vector(0, 0, 1), new Flog.RayTracer.Vector(0, 1, 0)) @shapes = new Array() @lights = new Array() @background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0, 0, 0.5), 0.2) return Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Material = {} if typeof (Flog.RayTracer.Material) is "undefined" Flog.RayTracer.Material.BaseMaterial = Class.create() Flog.RayTracer.Material.BaseMaterial:: = gloss: 2.0 transparency: 0.0 reflection: 0.0 refraction: 0.50 hasTexture: false initialize: -> getColor: (u, v) -> wrapUp: (t) -> t = t % 2.0 t += 2.0 if t < -1 t -= 2.0 if t >= 1 t toString: -> "Material [gloss=" + @gloss + ", transparency=" + @transparency + ", hasTexture=" + @hasTexture + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Material.Solid = Class.create() Flog.RayTracer.Material.Solid:: = Object.extend(new Flog.RayTracer.Material.BaseMaterial(), initialize: (color, reflection, refraction, transparency, gloss) -> @color = color @reflection = reflection @transparency = transparency @gloss = gloss @hasTexture = false return getColor: (u, v) -> @color toString: -> "SolidMaterial [gloss=" + @gloss + ", transparency=" + @transparency + ", hasTexture=" + @hasTexture + "]" ) Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Material.Chessboard = Class.create() Flog.RayTracer.Material.Chessboard:: = Object.extend(new Flog.RayTracer.Material.BaseMaterial(), colorEven: null colorOdd: null density: 0.5 initialize: (colorEven, colorOdd, reflection, transparency, gloss, density) -> @colorEven = colorEven @colorOdd = colorOdd @reflection = reflection @transparency = transparency @gloss = gloss @density = density @hasTexture = true return getColor: (u, v) -> t = @wrapUp(u * @density) * @wrapUp(v * @density) if t < 0.0 @colorEven else @colorOdd toString: -> "ChessMaterial [gloss=" + @gloss + ", transparency=" + @transparency + ", hasTexture=" + @hasTexture + "]" ) Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Shape = {} if typeof (Flog.RayTracer.Shape) is "undefined" Flog.RayTracer.Shape.Sphere = Class.create() Flog.RayTracer.Shape.Sphere:: = initialize: (pos, radius, material) -> @radius = radius @position = pos @material = material return intersect: (ray) -> info = new Flog.RayTracer.IntersectionInfo() info.shape = this dst = Flog.RayTracer.Vector::subtract(ray.position, @position) B = dst.dot(ray.direction) C = dst.dot(dst) - (@radius * @radius) D = (B * B) - C if D > 0 info.isHit = true info.distance = (-B) - Math.sqrt(D) info.position = Flog.RayTracer.Vector::add(ray.position, Flog.RayTracer.Vector::multiplyScalar(ray.direction, info.distance)) info.normal = Flog.RayTracer.Vector::subtract(info.position, @position).normalize() info.color = @material.getColor(0, 0) else info.isHit = false info toString: -> "Sphere [position=" + @position + ", radius=" + @radius + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Shape = {} if typeof (Flog.RayTracer.Shape) is "undefined" Flog.RayTracer.Shape.Plane = Class.create() Flog.RayTracer.Shape.Plane:: = d: 0.0 initialize: (pos, d, material) -> @position = pos @d = d @material = material return intersect: (ray) -> info = new Flog.RayTracer.IntersectionInfo() Vd = @position.dot(ray.direction) return info if Vd is 0 t = -(@position.dot(ray.position) + @d) / Vd return info if t <= 0 info.shape = this info.isHit = true info.position = Flog.RayTracer.Vector::add(ray.position, Flog.RayTracer.Vector::multiplyScalar(ray.direction, t)) info.normal = @position info.distance = t if @material.hasTexture vU = new Flog.RayTracer.Vector(@position.y, @position.z, -@position.x) vV = vU.cross(@position) u = info.position.dot(vU) v = info.position.dot(vV) info.color = @material.getColor(u, v) else info.color = @material.getColor(0, 0) info toString: -> "Plane [" + @position + ", d=" + @d + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.IntersectionInfo = Class.create() Flog.RayTracer.IntersectionInfo:: = isHit: false hitCount: 0 shape: null position: null normal: null color: null distance: null initialize: -> @color = new Flog.RayTracer.Color(0, 0, 0) return toString: -> "Intersection [" + @position + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Camera = Class.create() Flog.RayTracer.Camera:: = position: null lookAt: null equator: null up: null screen: null initialize: (pos, lookAt, up) -> @position = pos @lookAt = lookAt @up = up @equator = lookAt.normalize().cross(@up) @screen = Flog.RayTracer.Vector::add(@position, @lookAt) return getRay: (vx, vy) -> pos = Flog.RayTracer.Vector::subtract(@screen, Flog.RayTracer.Vector::subtract(Flog.RayTracer.Vector::multiplyScalar(@equator, vx), Flog.RayTracer.Vector::multiplyScalar(@up, vy))) pos.y = pos.y * -1 dir = Flog.RayTracer.Vector::subtract(pos, @position) ray = new Flog.RayTracer.Ray(pos, dir.normalize()) ray toString: -> "Ray []" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Background = Class.create() Flog.RayTracer.Background:: = color: null ambience: 0.0 initialize: (color, ambience) -> @color = color @ambience = ambience return Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Engine = Class.create() Flog.RayTracer.Engine:: = canvas: null initialize: (options) -> @options = Object.extend( canvasHeight: 100 canvasWidth: 100 pixelWidth: 2 pixelHeight: 2 renderDiffuse: false renderShadows: false renderHighlights: false renderReflections: false rayDepth: 2 , options or {}) @options.canvasHeight /= @options.pixelHeight @options.canvasWidth /= @options.pixelWidth return setPixel: (x, y, color) -> pxW = undefined pxH = undefined pxW = @options.pixelWidth pxH = @options.pixelHeight if @canvas @canvas.fillStyle = color.toString() @canvas.fillRect x * pxW, y * pxH, pxW, pxH else checkNumber += color.brightness() if x is y return renderScene: (scene, canvas) -> checkNumber = 0 if canvas @canvas = canvas.getContext("2d") else @canvas = null canvasHeight = @options.canvasHeight canvasWidth = @options.canvasWidth y = 0 while y < canvasHeight x = 0 while x < canvasWidth yp = y * 1.0 / canvasHeight * 2 - 1 xp = x * 1.0 / canvasWidth * 2 - 1 ray = scene.camera.getRay(xp, yp) color = @getPixelColor(ray, scene) @setPixel x, y, color x++ y++ throw new Error("Scene rendered incorrectly") if checkNumber isnt 2321 return getPixelColor: (ray, scene) -> info = @testIntersection(ray, scene, null) if info.isHit color = @rayTrace(info, ray, scene, 0) return color scene.background.color testIntersection: (ray, scene, exclude) -> hits = 0 best = new Flog.RayTracer.IntersectionInfo() best.distance = 2000 i = 0 while i < scene.shapes.length shape = scene.shapes[i] unless shape is exclude info = shape.intersect(ray) if info.isHit and info.distance >= 0 and info.distance < best.distance best = info hits++ i++ best.hitCount = hits best getReflectionRay: (P, N, V) -> c1 = -N.dot(V) R1 = Flog.RayTracer.Vector::add(Flog.RayTracer.Vector::multiplyScalar(N, 2 * c1), V) new Flog.RayTracer.Ray(P, R1) rayTrace: (info, ray, scene, depth) -> color = Flog.RayTracer.Color::multiplyScalar(info.color, scene.background.ambience) oldColor = color shininess = Math.pow(10, info.shape.material.gloss + 1) i = 0 while i < scene.lights.length light = scene.lights[i] v = Flog.RayTracer.Vector::subtract(light.position, info.position).normalize() if @options.renderDiffuse L = v.dot(info.normal) color = Flog.RayTracer.Color::add(color, Flog.RayTracer.Color::multiply(info.color, Flog.RayTracer.Color::multiplyScalar(light.color, L))) if L > 0.0 if depth <= @options.rayDepth if @options.renderReflections and info.shape.material.reflection > 0 reflectionRay = @getReflectionRay(info.position, info.normal, ray.direction) refl = @testIntersection(reflectionRay, scene, info.shape) if refl.isHit and refl.distance > 0 refl.color = @rayTrace(refl, reflectionRay, scene, depth + 1) else refl.color = scene.background.color color = Flog.RayTracer.Color::blend(color, refl.color, info.shape.material.reflection) shadowInfo = new Flog.RayTracer.IntersectionInfo() if @options.renderShadows shadowRay = new Flog.RayTracer.Ray(info.position, v) shadowInfo = @testIntersection(shadowRay, scene, info.shape) if shadowInfo.isHit and shadowInfo.shape isnt info.shape vA = Flog.RayTracer.Color::multiplyScalar(color, 0.5) dB = (0.5 * Math.pow(shadowInfo.shape.material.transparency, 0.5)) color = Flog.RayTracer.Color::addScalar(vA, dB) if @options.renderHighlights and not shadowInfo.isHit and info.shape.material.gloss > 0 Lv = Flog.RayTracer.Vector::subtract(info.shape.position, light.position).normalize() E = Flog.RayTracer.Vector::subtract(scene.camera.position, info.shape.position).normalize() H = Flog.RayTracer.Vector::subtract(E, Lv).normalize() glossWeight = Math.pow(Math.max(info.normal.dot(H), 0), shininess) color = Flog.RayTracer.Color::add(Flog.RayTracer.Color::multiplyScalar(light.color, glossWeight), color) i++ color.limit() color
7527
# The ray tracer code in this file is written by <NAME>. It # is available in its original form from: # # http://labs.flog.nz.co/raytracer/ # # It has been modified slightly by Google to work as a standalone # benchmark, but the all the computational code remains # untouched. This file also contains a copy of parts of the Prototype # JavaScript framework which is used by the ray tracer. # Variable used to hold a number that can be used to verify that # the scene was ray traced correctly. # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # The following is a copy of parts of the Prototype JavaScript library: # Prototype JavaScript framework, version 1.5.0 # (c) 2005-2007 <NAME> # # Prototype is freely distributable under the terms of an MIT-style license. # For details, see the Prototype web site: http://prototype.conio.net/ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # The rest of this file is the actual ray tracer written by <NAME> # <NAME>. It's a concatenation of the following files: # # flog/color.js # flog/light.js # flog/vector.js # flog/ray.js # flog/scene.js # flog/material/basematerial.js # flog/material/solid.js # flog/material/chessboard.js # flog/shape/baseshape.js # flog/shape/sphere.js # flog/shape/plane.js # flog/intersectioninfo.js # flog/camera.js # flog/background.js # flog/engine.js # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # [0...infinity] 0 = matt # 0=opaque # [0...infinity] 0 = no reflection # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # intersection! # Fake a Flog.* namespace # no intersection # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # 2d context we can render to # TODO: dynamically include other scripts # print(x * pxW, y * pxH, pxW, pxH); # Get canvas # Calc ambient # Calc diffuse lighting # The greater the depth the more accurate the colours, but # this is exponentially (!) expensive # calculate reflection ray # Refraction # TODO # Render shadows and highlights #&& shadowInfo.shape.type != 'PLANE' # Phong specular highlights renderScene = -> scene = new Flog.RayTracer.Scene() scene.camera = new Flog.RayTracer.Camera(new Flog.RayTracer.Vector(0, 0, -15), new Flog.RayTracer.Vector(-0.2, 0, 5), new Flog.RayTracer.Vector(0, 1, 0)) scene.background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0.5, 0.5, 0.5), 0.4) sphere = new Flog.RayTracer.Shape.Sphere(new Flog.RayTracer.Vector(-1.5, 1.5, 2), 1.5, new Flog.RayTracer.Material.Solid(new Flog.RayTracer.Color(0, 0.5, 0.5), 0.3, 0.0, 0.0, 2.0)) sphere1 = new Flog.RayTracer.Shape.Sphere(new Flog.RayTracer.Vector(1, 0.25, 1), 0.5, new Flog.RayTracer.Material.Solid(new Flog.RayTracer.Color(0.9, 0.9, 0.9), 0.1, 0.0, 0.0, 1.5)) plane = new Flog.RayTracer.Shape.Plane(new Flog.RayTracer.Vector(0.1, 0.9, -0.5).normalize(), 1.2, new Flog.RayTracer.Material.Chessboard(new Flog.RayTracer.Color(1, 1, 1), new Flog.RayTracer.Color(0, 0, 0), 0.2, 0.0, 1.0, 0.7)) scene.shapes.push plane scene.shapes.push sphere scene.shapes.push sphere1 light = new Flog.RayTracer.Light(new Flog.RayTracer.Vector(5, 10, -1), new Flog.RayTracer.Color(0.8, 0.8, 0.8)) light1 = new Flog.RayTracer.Light(new Flog.RayTracer.Vector(-3, 5, -15), new Flog.RayTracer.Color(0.8, 0.8, 0.8), 100) scene.lights.push light scene.lights.push light1 imageWidth = 100 # $F('imageWidth'); imageHeight = 100 # $F('imageHeight'); pixelSize = "5,5".split(",") # $F('pixelSize').split(','); renderDiffuse = true # $F('renderDiffuse'); renderShadows = true # $F('renderShadows'); renderHighlights = true # $F('renderHighlights'); renderReflections = true # $F('renderReflections'); rayDepth = 2 #$F('rayDepth'); raytracer = new Flog.RayTracer.Engine( canvasWidth: imageWidth canvasHeight: imageHeight pixelWidth: pixelSize[0] pixelHeight: pixelSize[1] renderDiffuse: renderDiffuse renderHighlights: renderHighlights renderShadows: renderShadows renderReflections: renderReflections rayDepth: rayDepth ) raytracer.renderScene scene, null, 0 return RayTrace = new BenchmarkSuite("RayTrace", 739989, [new Benchmark("RayTrace", renderScene)]) checkNumber = undefined Class = create: -> -> @initialize.apply this, arguments return Object.extend = (destination, source) -> for property of source destination[property] = source[property] destination Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Color = Class.create() Flog.RayTracer.Color:: = red: 0.0 green: 0.0 blue: 0.0 initialize: (r, g, b) -> r = 0.0 unless r g = 0.0 unless g b = 0.0 unless b @red = r @green = g @blue = b return add: (c1, c2) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red + c2.red result.green = c1.green + c2.green result.blue = c1.blue + c2.blue result addScalar: (c1, s) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red + s result.green = c1.green + s result.blue = c1.blue + s result.limit() result subtract: (c1, c2) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red - c2.red result.green = c1.green - c2.green result.blue = c1.blue - c2.blue result multiply: (c1, c2) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red * c2.red result.green = c1.green * c2.green result.blue = c1.blue * c2.blue result multiplyScalar: (c1, f) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red * f result.green = c1.green * f result.blue = c1.blue * f result divideFactor: (c1, f) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red / f result.green = c1.green / f result.blue = c1.blue / f result limit: -> @red = (if (@red > 0.0) then ((if (@red > 1.0) then 1.0 else @red)) else 0.0) @green = (if (@green > 0.0) then ((if (@green > 1.0) then 1.0 else @green)) else 0.0) @blue = (if (@blue > 0.0) then ((if (@blue > 1.0) then 1.0 else @blue)) else 0.0) return distance: (color) -> d = Math.abs(@red - color.red) + Math.abs(@green - color.green) + Math.abs(@blue - color.blue) d blend: (c1, c2, w) -> result = new Flog.RayTracer.Color(0, 0, 0) result = Flog.RayTracer.Color::add(Flog.RayTracer.Color::multiplyScalar(c1, 1 - w), Flog.RayTracer.Color::multiplyScalar(c2, w)) result brightness: -> r = Math.floor(@red * 255) g = Math.floor(@green * 255) b = Math.floor(@blue * 255) (r * 77 + g * 150 + b * 29) >> 8 toString: -> r = Math.floor(@red * 255) g = Math.floor(@green * 255) b = Math.floor(@blue * 255) "rgb(" + r + "," + g + "," + b + ")" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Light = Class.create() Flog.RayTracer.Light:: = position: null color: null intensity: 10.0 initialize: (pos, color, intensity) -> @position = pos @color = color @intensity = ((if intensity then intensity else 10.0)) return toString: -> "Light [" + @position.x + "," + @position.y + "," + @position.z + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Vector = Class.create() Flog.RayTracer.Vector:: = x: 0.0 y: 0.0 z: 0.0 initialize: (x, y, z) -> @x = ((if x then x else 0)) @y = ((if y then y else 0)) @z = ((if z then z else 0)) return copy: (vector) -> @x = vector.x @y = vector.y @z = vector.z return normalize: -> m = @magnitude() new Flog.RayTracer.Vector(@x / m, @y / m, @z / m) magnitude: -> Math.sqrt (@x * @x) + (@y * @y) + (@z * @z) cross: (w) -> new Flog.RayTracer.Vector(-@z * w.y + @y * w.z, @z * w.x - @x * w.z, -@y * w.x + @x * w.y) dot: (w) -> @x * w.x + @y * w.y + @z * w.z add: (v, w) -> new Flog.RayTracer.Vector(w.x + v.x, w.y + v.y, w.z + v.z) subtract: (v, w) -> throw "Vectors must be defined [" + v + "," + w + "]" if not w or not v new Flog.RayTracer.Vector(v.x - w.x, v.y - w.y, v.z - w.z) multiplyVector: (v, w) -> new Flog.RayTracer.Vector(v.x * w.x, v.y * w.y, v.z * w.z) multiplyScalar: (v, w) -> new Flog.RayTracer.Vector(v.x * w, v.y * w, v.z * w) toString: -> "Vector [" + @x + "," + @y + "," + @z + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Ray = Class.create() Flog.RayTracer.Ray:: = position: null direction: null initialize: (pos, dir) -> @position = pos @direction = dir return toString: -> "Ray [" + @position + "," + @direction + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Scene = Class.create() Flog.RayTracer.Scene:: = camera: null shapes: [] lights: [] background: null initialize: -> @camera = new Flog.RayTracer.Camera(new Flog.RayTracer.Vector(0, 0, -5), new Flog.RayTracer.Vector(0, 0, 1), new Flog.RayTracer.Vector(0, 1, 0)) @shapes = new Array() @lights = new Array() @background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0, 0, 0.5), 0.2) return Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Material = {} if typeof (Flog.RayTracer.Material) is "undefined" Flog.RayTracer.Material.BaseMaterial = Class.create() Flog.RayTracer.Material.BaseMaterial:: = gloss: 2.0 transparency: 0.0 reflection: 0.0 refraction: 0.50 hasTexture: false initialize: -> getColor: (u, v) -> wrapUp: (t) -> t = t % 2.0 t += 2.0 if t < -1 t -= 2.0 if t >= 1 t toString: -> "Material [gloss=" + @gloss + ", transparency=" + @transparency + ", hasTexture=" + @hasTexture + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Material.Solid = Class.create() Flog.RayTracer.Material.Solid:: = Object.extend(new Flog.RayTracer.Material.BaseMaterial(), initialize: (color, reflection, refraction, transparency, gloss) -> @color = color @reflection = reflection @transparency = transparency @gloss = gloss @hasTexture = false return getColor: (u, v) -> @color toString: -> "SolidMaterial [gloss=" + @gloss + ", transparency=" + @transparency + ", hasTexture=" + @hasTexture + "]" ) Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Material.Chessboard = Class.create() Flog.RayTracer.Material.Chessboard:: = Object.extend(new Flog.RayTracer.Material.BaseMaterial(), colorEven: null colorOdd: null density: 0.5 initialize: (colorEven, colorOdd, reflection, transparency, gloss, density) -> @colorEven = colorEven @colorOdd = colorOdd @reflection = reflection @transparency = transparency @gloss = gloss @density = density @hasTexture = true return getColor: (u, v) -> t = @wrapUp(u * @density) * @wrapUp(v * @density) if t < 0.0 @colorEven else @colorOdd toString: -> "ChessMaterial [gloss=" + @gloss + ", transparency=" + @transparency + ", hasTexture=" + @hasTexture + "]" ) Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Shape = {} if typeof (Flog.RayTracer.Shape) is "undefined" Flog.RayTracer.Shape.Sphere = Class.create() Flog.RayTracer.Shape.Sphere:: = initialize: (pos, radius, material) -> @radius = radius @position = pos @material = material return intersect: (ray) -> info = new Flog.RayTracer.IntersectionInfo() info.shape = this dst = Flog.RayTracer.Vector::subtract(ray.position, @position) B = dst.dot(ray.direction) C = dst.dot(dst) - (@radius * @radius) D = (B * B) - C if D > 0 info.isHit = true info.distance = (-B) - Math.sqrt(D) info.position = Flog.RayTracer.Vector::add(ray.position, Flog.RayTracer.Vector::multiplyScalar(ray.direction, info.distance)) info.normal = Flog.RayTracer.Vector::subtract(info.position, @position).normalize() info.color = @material.getColor(0, 0) else info.isHit = false info toString: -> "Sphere [position=" + @position + ", radius=" + @radius + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Shape = {} if typeof (Flog.RayTracer.Shape) is "undefined" Flog.RayTracer.Shape.Plane = Class.create() Flog.RayTracer.Shape.Plane:: = d: 0.0 initialize: (pos, d, material) -> @position = pos @d = d @material = material return intersect: (ray) -> info = new Flog.RayTracer.IntersectionInfo() Vd = @position.dot(ray.direction) return info if Vd is 0 t = -(@position.dot(ray.position) + @d) / Vd return info if t <= 0 info.shape = this info.isHit = true info.position = Flog.RayTracer.Vector::add(ray.position, Flog.RayTracer.Vector::multiplyScalar(ray.direction, t)) info.normal = @position info.distance = t if @material.hasTexture vU = new Flog.RayTracer.Vector(@position.y, @position.z, -@position.x) vV = vU.cross(@position) u = info.position.dot(vU) v = info.position.dot(vV) info.color = @material.getColor(u, v) else info.color = @material.getColor(0, 0) info toString: -> "Plane [" + @position + ", d=" + @d + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.IntersectionInfo = Class.create() Flog.RayTracer.IntersectionInfo:: = isHit: false hitCount: 0 shape: null position: null normal: null color: null distance: null initialize: -> @color = new Flog.RayTracer.Color(0, 0, 0) return toString: -> "Intersection [" + @position + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Camera = Class.create() Flog.RayTracer.Camera:: = position: null lookAt: null equator: null up: null screen: null initialize: (pos, lookAt, up) -> @position = pos @lookAt = lookAt @up = up @equator = lookAt.normalize().cross(@up) @screen = Flog.RayTracer.Vector::add(@position, @lookAt) return getRay: (vx, vy) -> pos = Flog.RayTracer.Vector::subtract(@screen, Flog.RayTracer.Vector::subtract(Flog.RayTracer.Vector::multiplyScalar(@equator, vx), Flog.RayTracer.Vector::multiplyScalar(@up, vy))) pos.y = pos.y * -1 dir = Flog.RayTracer.Vector::subtract(pos, @position) ray = new Flog.RayTracer.Ray(pos, dir.normalize()) ray toString: -> "Ray []" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Background = Class.create() Flog.RayTracer.Background:: = color: null ambience: 0.0 initialize: (color, ambience) -> @color = color @ambience = ambience return Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Engine = Class.create() Flog.RayTracer.Engine:: = canvas: null initialize: (options) -> @options = Object.extend( canvasHeight: 100 canvasWidth: 100 pixelWidth: 2 pixelHeight: 2 renderDiffuse: false renderShadows: false renderHighlights: false renderReflections: false rayDepth: 2 , options or {}) @options.canvasHeight /= @options.pixelHeight @options.canvasWidth /= @options.pixelWidth return setPixel: (x, y, color) -> pxW = undefined pxH = undefined pxW = @options.pixelWidth pxH = @options.pixelHeight if @canvas @canvas.fillStyle = color.toString() @canvas.fillRect x * pxW, y * pxH, pxW, pxH else checkNumber += color.brightness() if x is y return renderScene: (scene, canvas) -> checkNumber = 0 if canvas @canvas = canvas.getContext("2d") else @canvas = null canvasHeight = @options.canvasHeight canvasWidth = @options.canvasWidth y = 0 while y < canvasHeight x = 0 while x < canvasWidth yp = y * 1.0 / canvasHeight * 2 - 1 xp = x * 1.0 / canvasWidth * 2 - 1 ray = scene.camera.getRay(xp, yp) color = @getPixelColor(ray, scene) @setPixel x, y, color x++ y++ throw new Error("Scene rendered incorrectly") if checkNumber isnt 2321 return getPixelColor: (ray, scene) -> info = @testIntersection(ray, scene, null) if info.isHit color = @rayTrace(info, ray, scene, 0) return color scene.background.color testIntersection: (ray, scene, exclude) -> hits = 0 best = new Flog.RayTracer.IntersectionInfo() best.distance = 2000 i = 0 while i < scene.shapes.length shape = scene.shapes[i] unless shape is exclude info = shape.intersect(ray) if info.isHit and info.distance >= 0 and info.distance < best.distance best = info hits++ i++ best.hitCount = hits best getReflectionRay: (P, N, V) -> c1 = -N.dot(V) R1 = Flog.RayTracer.Vector::add(Flog.RayTracer.Vector::multiplyScalar(N, 2 * c1), V) new Flog.RayTracer.Ray(P, R1) rayTrace: (info, ray, scene, depth) -> color = Flog.RayTracer.Color::multiplyScalar(info.color, scene.background.ambience) oldColor = color shininess = Math.pow(10, info.shape.material.gloss + 1) i = 0 while i < scene.lights.length light = scene.lights[i] v = Flog.RayTracer.Vector::subtract(light.position, info.position).normalize() if @options.renderDiffuse L = v.dot(info.normal) color = Flog.RayTracer.Color::add(color, Flog.RayTracer.Color::multiply(info.color, Flog.RayTracer.Color::multiplyScalar(light.color, L))) if L > 0.0 if depth <= @options.rayDepth if @options.renderReflections and info.shape.material.reflection > 0 reflectionRay = @getReflectionRay(info.position, info.normal, ray.direction) refl = @testIntersection(reflectionRay, scene, info.shape) if refl.isHit and refl.distance > 0 refl.color = @rayTrace(refl, reflectionRay, scene, depth + 1) else refl.color = scene.background.color color = Flog.RayTracer.Color::blend(color, refl.color, info.shape.material.reflection) shadowInfo = new Flog.RayTracer.IntersectionInfo() if @options.renderShadows shadowRay = new Flog.RayTracer.Ray(info.position, v) shadowInfo = @testIntersection(shadowRay, scene, info.shape) if shadowInfo.isHit and shadowInfo.shape isnt info.shape vA = Flog.RayTracer.Color::multiplyScalar(color, 0.5) dB = (0.5 * Math.pow(shadowInfo.shape.material.transparency, 0.5)) color = Flog.RayTracer.Color::addScalar(vA, dB) if @options.renderHighlights and not shadowInfo.isHit and info.shape.material.gloss > 0 Lv = Flog.RayTracer.Vector::subtract(info.shape.position, light.position).normalize() E = Flog.RayTracer.Vector::subtract(scene.camera.position, info.shape.position).normalize() H = Flog.RayTracer.Vector::subtract(E, Lv).normalize() glossWeight = Math.pow(Math.max(info.normal.dot(H), 0), shininess) color = Flog.RayTracer.Color::add(Flog.RayTracer.Color::multiplyScalar(light.color, glossWeight), color) i++ color.limit() color
true
# The ray tracer code in this file is written by PI:NAME:<NAME>END_PI. It # is available in its original form from: # # http://labs.flog.nz.co/raytracer/ # # It has been modified slightly by Google to work as a standalone # benchmark, but the all the computational code remains # untouched. This file also contains a copy of parts of the Prototype # JavaScript framework which is used by the ray tracer. # Variable used to hold a number that can be used to verify that # the scene was ray traced correctly. # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # The following is a copy of parts of the Prototype JavaScript library: # Prototype JavaScript framework, version 1.5.0 # (c) 2005-2007 PI:NAME:<NAME>END_PI # # Prototype is freely distributable under the terms of an MIT-style license. # For details, see the Prototype web site: http://prototype.conio.net/ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # The rest of this file is the actual ray tracer written by PI:NAME:<NAME>END_PI # PI:NAME:<NAME>END_PI. It's a concatenation of the following files: # # flog/color.js # flog/light.js # flog/vector.js # flog/ray.js # flog/scene.js # flog/material/basematerial.js # flog/material/solid.js # flog/material/chessboard.js # flog/shape/baseshape.js # flog/shape/sphere.js # flog/shape/plane.js # flog/intersectioninfo.js # flog/camera.js # flog/background.js # flog/engine.js # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # [0...infinity] 0 = matt # 0=opaque # [0...infinity] 0 = no reflection # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # intersection! # Fake a Flog.* namespace # no intersection # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # Fake a Flog.* namespace # 2d context we can render to # TODO: dynamically include other scripts # print(x * pxW, y * pxH, pxW, pxH); # Get canvas # Calc ambient # Calc diffuse lighting # The greater the depth the more accurate the colours, but # this is exponentially (!) expensive # calculate reflection ray # Refraction # TODO # Render shadows and highlights #&& shadowInfo.shape.type != 'PLANE' # Phong specular highlights renderScene = -> scene = new Flog.RayTracer.Scene() scene.camera = new Flog.RayTracer.Camera(new Flog.RayTracer.Vector(0, 0, -15), new Flog.RayTracer.Vector(-0.2, 0, 5), new Flog.RayTracer.Vector(0, 1, 0)) scene.background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0.5, 0.5, 0.5), 0.4) sphere = new Flog.RayTracer.Shape.Sphere(new Flog.RayTracer.Vector(-1.5, 1.5, 2), 1.5, new Flog.RayTracer.Material.Solid(new Flog.RayTracer.Color(0, 0.5, 0.5), 0.3, 0.0, 0.0, 2.0)) sphere1 = new Flog.RayTracer.Shape.Sphere(new Flog.RayTracer.Vector(1, 0.25, 1), 0.5, new Flog.RayTracer.Material.Solid(new Flog.RayTracer.Color(0.9, 0.9, 0.9), 0.1, 0.0, 0.0, 1.5)) plane = new Flog.RayTracer.Shape.Plane(new Flog.RayTracer.Vector(0.1, 0.9, -0.5).normalize(), 1.2, new Flog.RayTracer.Material.Chessboard(new Flog.RayTracer.Color(1, 1, 1), new Flog.RayTracer.Color(0, 0, 0), 0.2, 0.0, 1.0, 0.7)) scene.shapes.push plane scene.shapes.push sphere scene.shapes.push sphere1 light = new Flog.RayTracer.Light(new Flog.RayTracer.Vector(5, 10, -1), new Flog.RayTracer.Color(0.8, 0.8, 0.8)) light1 = new Flog.RayTracer.Light(new Flog.RayTracer.Vector(-3, 5, -15), new Flog.RayTracer.Color(0.8, 0.8, 0.8), 100) scene.lights.push light scene.lights.push light1 imageWidth = 100 # $F('imageWidth'); imageHeight = 100 # $F('imageHeight'); pixelSize = "5,5".split(",") # $F('pixelSize').split(','); renderDiffuse = true # $F('renderDiffuse'); renderShadows = true # $F('renderShadows'); renderHighlights = true # $F('renderHighlights'); renderReflections = true # $F('renderReflections'); rayDepth = 2 #$F('rayDepth'); raytracer = new Flog.RayTracer.Engine( canvasWidth: imageWidth canvasHeight: imageHeight pixelWidth: pixelSize[0] pixelHeight: pixelSize[1] renderDiffuse: renderDiffuse renderHighlights: renderHighlights renderShadows: renderShadows renderReflections: renderReflections rayDepth: rayDepth ) raytracer.renderScene scene, null, 0 return RayTrace = new BenchmarkSuite("RayTrace", 739989, [new Benchmark("RayTrace", renderScene)]) checkNumber = undefined Class = create: -> -> @initialize.apply this, arguments return Object.extend = (destination, source) -> for property of source destination[property] = source[property] destination Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Color = Class.create() Flog.RayTracer.Color:: = red: 0.0 green: 0.0 blue: 0.0 initialize: (r, g, b) -> r = 0.0 unless r g = 0.0 unless g b = 0.0 unless b @red = r @green = g @blue = b return add: (c1, c2) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red + c2.red result.green = c1.green + c2.green result.blue = c1.blue + c2.blue result addScalar: (c1, s) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red + s result.green = c1.green + s result.blue = c1.blue + s result.limit() result subtract: (c1, c2) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red - c2.red result.green = c1.green - c2.green result.blue = c1.blue - c2.blue result multiply: (c1, c2) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red * c2.red result.green = c1.green * c2.green result.blue = c1.blue * c2.blue result multiplyScalar: (c1, f) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red * f result.green = c1.green * f result.blue = c1.blue * f result divideFactor: (c1, f) -> result = new Flog.RayTracer.Color(0, 0, 0) result.red = c1.red / f result.green = c1.green / f result.blue = c1.blue / f result limit: -> @red = (if (@red > 0.0) then ((if (@red > 1.0) then 1.0 else @red)) else 0.0) @green = (if (@green > 0.0) then ((if (@green > 1.0) then 1.0 else @green)) else 0.0) @blue = (if (@blue > 0.0) then ((if (@blue > 1.0) then 1.0 else @blue)) else 0.0) return distance: (color) -> d = Math.abs(@red - color.red) + Math.abs(@green - color.green) + Math.abs(@blue - color.blue) d blend: (c1, c2, w) -> result = new Flog.RayTracer.Color(0, 0, 0) result = Flog.RayTracer.Color::add(Flog.RayTracer.Color::multiplyScalar(c1, 1 - w), Flog.RayTracer.Color::multiplyScalar(c2, w)) result brightness: -> r = Math.floor(@red * 255) g = Math.floor(@green * 255) b = Math.floor(@blue * 255) (r * 77 + g * 150 + b * 29) >> 8 toString: -> r = Math.floor(@red * 255) g = Math.floor(@green * 255) b = Math.floor(@blue * 255) "rgb(" + r + "," + g + "," + b + ")" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Light = Class.create() Flog.RayTracer.Light:: = position: null color: null intensity: 10.0 initialize: (pos, color, intensity) -> @position = pos @color = color @intensity = ((if intensity then intensity else 10.0)) return toString: -> "Light [" + @position.x + "," + @position.y + "," + @position.z + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Vector = Class.create() Flog.RayTracer.Vector:: = x: 0.0 y: 0.0 z: 0.0 initialize: (x, y, z) -> @x = ((if x then x else 0)) @y = ((if y then y else 0)) @z = ((if z then z else 0)) return copy: (vector) -> @x = vector.x @y = vector.y @z = vector.z return normalize: -> m = @magnitude() new Flog.RayTracer.Vector(@x / m, @y / m, @z / m) magnitude: -> Math.sqrt (@x * @x) + (@y * @y) + (@z * @z) cross: (w) -> new Flog.RayTracer.Vector(-@z * w.y + @y * w.z, @z * w.x - @x * w.z, -@y * w.x + @x * w.y) dot: (w) -> @x * w.x + @y * w.y + @z * w.z add: (v, w) -> new Flog.RayTracer.Vector(w.x + v.x, w.y + v.y, w.z + v.z) subtract: (v, w) -> throw "Vectors must be defined [" + v + "," + w + "]" if not w or not v new Flog.RayTracer.Vector(v.x - w.x, v.y - w.y, v.z - w.z) multiplyVector: (v, w) -> new Flog.RayTracer.Vector(v.x * w.x, v.y * w.y, v.z * w.z) multiplyScalar: (v, w) -> new Flog.RayTracer.Vector(v.x * w, v.y * w, v.z * w) toString: -> "Vector [" + @x + "," + @y + "," + @z + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Ray = Class.create() Flog.RayTracer.Ray:: = position: null direction: null initialize: (pos, dir) -> @position = pos @direction = dir return toString: -> "Ray [" + @position + "," + @direction + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Scene = Class.create() Flog.RayTracer.Scene:: = camera: null shapes: [] lights: [] background: null initialize: -> @camera = new Flog.RayTracer.Camera(new Flog.RayTracer.Vector(0, 0, -5), new Flog.RayTracer.Vector(0, 0, 1), new Flog.RayTracer.Vector(0, 1, 0)) @shapes = new Array() @lights = new Array() @background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0, 0, 0.5), 0.2) return Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Material = {} if typeof (Flog.RayTracer.Material) is "undefined" Flog.RayTracer.Material.BaseMaterial = Class.create() Flog.RayTracer.Material.BaseMaterial:: = gloss: 2.0 transparency: 0.0 reflection: 0.0 refraction: 0.50 hasTexture: false initialize: -> getColor: (u, v) -> wrapUp: (t) -> t = t % 2.0 t += 2.0 if t < -1 t -= 2.0 if t >= 1 t toString: -> "Material [gloss=" + @gloss + ", transparency=" + @transparency + ", hasTexture=" + @hasTexture + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Material.Solid = Class.create() Flog.RayTracer.Material.Solid:: = Object.extend(new Flog.RayTracer.Material.BaseMaterial(), initialize: (color, reflection, refraction, transparency, gloss) -> @color = color @reflection = reflection @transparency = transparency @gloss = gloss @hasTexture = false return getColor: (u, v) -> @color toString: -> "SolidMaterial [gloss=" + @gloss + ", transparency=" + @transparency + ", hasTexture=" + @hasTexture + "]" ) Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Material.Chessboard = Class.create() Flog.RayTracer.Material.Chessboard:: = Object.extend(new Flog.RayTracer.Material.BaseMaterial(), colorEven: null colorOdd: null density: 0.5 initialize: (colorEven, colorOdd, reflection, transparency, gloss, density) -> @colorEven = colorEven @colorOdd = colorOdd @reflection = reflection @transparency = transparency @gloss = gloss @density = density @hasTexture = true return getColor: (u, v) -> t = @wrapUp(u * @density) * @wrapUp(v * @density) if t < 0.0 @colorEven else @colorOdd toString: -> "ChessMaterial [gloss=" + @gloss + ", transparency=" + @transparency + ", hasTexture=" + @hasTexture + "]" ) Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Shape = {} if typeof (Flog.RayTracer.Shape) is "undefined" Flog.RayTracer.Shape.Sphere = Class.create() Flog.RayTracer.Shape.Sphere:: = initialize: (pos, radius, material) -> @radius = radius @position = pos @material = material return intersect: (ray) -> info = new Flog.RayTracer.IntersectionInfo() info.shape = this dst = Flog.RayTracer.Vector::subtract(ray.position, @position) B = dst.dot(ray.direction) C = dst.dot(dst) - (@radius * @radius) D = (B * B) - C if D > 0 info.isHit = true info.distance = (-B) - Math.sqrt(D) info.position = Flog.RayTracer.Vector::add(ray.position, Flog.RayTracer.Vector::multiplyScalar(ray.direction, info.distance)) info.normal = Flog.RayTracer.Vector::subtract(info.position, @position).normalize() info.color = @material.getColor(0, 0) else info.isHit = false info toString: -> "Sphere [position=" + @position + ", radius=" + @radius + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Shape = {} if typeof (Flog.RayTracer.Shape) is "undefined" Flog.RayTracer.Shape.Plane = Class.create() Flog.RayTracer.Shape.Plane:: = d: 0.0 initialize: (pos, d, material) -> @position = pos @d = d @material = material return intersect: (ray) -> info = new Flog.RayTracer.IntersectionInfo() Vd = @position.dot(ray.direction) return info if Vd is 0 t = -(@position.dot(ray.position) + @d) / Vd return info if t <= 0 info.shape = this info.isHit = true info.position = Flog.RayTracer.Vector::add(ray.position, Flog.RayTracer.Vector::multiplyScalar(ray.direction, t)) info.normal = @position info.distance = t if @material.hasTexture vU = new Flog.RayTracer.Vector(@position.y, @position.z, -@position.x) vV = vU.cross(@position) u = info.position.dot(vU) v = info.position.dot(vV) info.color = @material.getColor(u, v) else info.color = @material.getColor(0, 0) info toString: -> "Plane [" + @position + ", d=" + @d + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.IntersectionInfo = Class.create() Flog.RayTracer.IntersectionInfo:: = isHit: false hitCount: 0 shape: null position: null normal: null color: null distance: null initialize: -> @color = new Flog.RayTracer.Color(0, 0, 0) return toString: -> "Intersection [" + @position + "]" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Camera = Class.create() Flog.RayTracer.Camera:: = position: null lookAt: null equator: null up: null screen: null initialize: (pos, lookAt, up) -> @position = pos @lookAt = lookAt @up = up @equator = lookAt.normalize().cross(@up) @screen = Flog.RayTracer.Vector::add(@position, @lookAt) return getRay: (vx, vy) -> pos = Flog.RayTracer.Vector::subtract(@screen, Flog.RayTracer.Vector::subtract(Flog.RayTracer.Vector::multiplyScalar(@equator, vx), Flog.RayTracer.Vector::multiplyScalar(@up, vy))) pos.y = pos.y * -1 dir = Flog.RayTracer.Vector::subtract(pos, @position) ray = new Flog.RayTracer.Ray(pos, dir.normalize()) ray toString: -> "Ray []" Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Background = Class.create() Flog.RayTracer.Background:: = color: null ambience: 0.0 initialize: (color, ambience) -> @color = color @ambience = ambience return Flog = {} if typeof (Flog) is "undefined" Flog.RayTracer = {} if typeof (Flog.RayTracer) is "undefined" Flog.RayTracer.Engine = Class.create() Flog.RayTracer.Engine:: = canvas: null initialize: (options) -> @options = Object.extend( canvasHeight: 100 canvasWidth: 100 pixelWidth: 2 pixelHeight: 2 renderDiffuse: false renderShadows: false renderHighlights: false renderReflections: false rayDepth: 2 , options or {}) @options.canvasHeight /= @options.pixelHeight @options.canvasWidth /= @options.pixelWidth return setPixel: (x, y, color) -> pxW = undefined pxH = undefined pxW = @options.pixelWidth pxH = @options.pixelHeight if @canvas @canvas.fillStyle = color.toString() @canvas.fillRect x * pxW, y * pxH, pxW, pxH else checkNumber += color.brightness() if x is y return renderScene: (scene, canvas) -> checkNumber = 0 if canvas @canvas = canvas.getContext("2d") else @canvas = null canvasHeight = @options.canvasHeight canvasWidth = @options.canvasWidth y = 0 while y < canvasHeight x = 0 while x < canvasWidth yp = y * 1.0 / canvasHeight * 2 - 1 xp = x * 1.0 / canvasWidth * 2 - 1 ray = scene.camera.getRay(xp, yp) color = @getPixelColor(ray, scene) @setPixel x, y, color x++ y++ throw new Error("Scene rendered incorrectly") if checkNumber isnt 2321 return getPixelColor: (ray, scene) -> info = @testIntersection(ray, scene, null) if info.isHit color = @rayTrace(info, ray, scene, 0) return color scene.background.color testIntersection: (ray, scene, exclude) -> hits = 0 best = new Flog.RayTracer.IntersectionInfo() best.distance = 2000 i = 0 while i < scene.shapes.length shape = scene.shapes[i] unless shape is exclude info = shape.intersect(ray) if info.isHit and info.distance >= 0 and info.distance < best.distance best = info hits++ i++ best.hitCount = hits best getReflectionRay: (P, N, V) -> c1 = -N.dot(V) R1 = Flog.RayTracer.Vector::add(Flog.RayTracer.Vector::multiplyScalar(N, 2 * c1), V) new Flog.RayTracer.Ray(P, R1) rayTrace: (info, ray, scene, depth) -> color = Flog.RayTracer.Color::multiplyScalar(info.color, scene.background.ambience) oldColor = color shininess = Math.pow(10, info.shape.material.gloss + 1) i = 0 while i < scene.lights.length light = scene.lights[i] v = Flog.RayTracer.Vector::subtract(light.position, info.position).normalize() if @options.renderDiffuse L = v.dot(info.normal) color = Flog.RayTracer.Color::add(color, Flog.RayTracer.Color::multiply(info.color, Flog.RayTracer.Color::multiplyScalar(light.color, L))) if L > 0.0 if depth <= @options.rayDepth if @options.renderReflections and info.shape.material.reflection > 0 reflectionRay = @getReflectionRay(info.position, info.normal, ray.direction) refl = @testIntersection(reflectionRay, scene, info.shape) if refl.isHit and refl.distance > 0 refl.color = @rayTrace(refl, reflectionRay, scene, depth + 1) else refl.color = scene.background.color color = Flog.RayTracer.Color::blend(color, refl.color, info.shape.material.reflection) shadowInfo = new Flog.RayTracer.IntersectionInfo() if @options.renderShadows shadowRay = new Flog.RayTracer.Ray(info.position, v) shadowInfo = @testIntersection(shadowRay, scene, info.shape) if shadowInfo.isHit and shadowInfo.shape isnt info.shape vA = Flog.RayTracer.Color::multiplyScalar(color, 0.5) dB = (0.5 * Math.pow(shadowInfo.shape.material.transparency, 0.5)) color = Flog.RayTracer.Color::addScalar(vA, dB) if @options.renderHighlights and not shadowInfo.isHit and info.shape.material.gloss > 0 Lv = Flog.RayTracer.Vector::subtract(info.shape.position, light.position).normalize() E = Flog.RayTracer.Vector::subtract(scene.camera.position, info.shape.position).normalize() H = Flog.RayTracer.Vector::subtract(E, Lv).normalize() glossWeight = Math.pow(Math.max(info.normal.dot(H), 0), shininess) color = Flog.RayTracer.Color::add(Flog.RayTracer.Color::multiplyScalar(light.color, glossWeight), color) i++ color.limit() color
[ { "context": ": the Shell.\"\n\n user = @userForId('1', {name: \"Shell\"})\n\n process.stdin.resume()\n process.stdin.", "end": 313, "score": 0.9928855299949646, "start": 308, "tag": "USERNAME", "value": "Shell" }, { "context": "Timeout =>\n user = @userForId('1', {name: \"Shell\"})\n atmos = @userForId('2', {name: \"atmos\"}", "end": 582, "score": 0.9763092398643494, "start": 577, "tag": "USERNAME", "value": "Shell" }, { "context": " \"Shell\"})\n atmos = @userForId('2', {name: \"atmos\"})\n holman = @userForId('3', {name: \"Zach Ho", "end": 630, "score": 0.9922987222671509, "start": 625, "tag": "USERNAME", "value": "atmos" }, { "context": " atmos = @userForId('2', {name: \"atmos\"})\n holman = @userForId('3', {name: \"Zach Holman\"})\n , 30", "end": 646, "score": 0.7837693691253662, "start": 640, "tag": "USERNAME", "value": "holman" }, { "context": " \"atmos\"})\n holman = @userForId('3', {name: \"Zach Holman\"})\n , 3000\n\nmodule.exports = Shell\n\n", "end": 684, "score": 0.9998784065246582, "start": 673, "tag": "NAME", "value": "Zach Holman" } ]
src/hubot/shell.coffee
lincolnloop/hubot
1
Robot = require '../robot' class Shell extends Robot send: (user, strings...) -> for str in strings console.log str reply: (user, strings...) -> for str in strings @send user, "#{user.name}: #{str}" run: -> console.log "Hubot: the Shell." user = @userForId('1', {name: "Shell"}) process.stdin.resume() process.stdin.on 'data', (txt) => txt.toString().split("\n").forEach (line) => return if line.length is 0 @receive new Robot.TextMessage user, line setTimeout => user = @userForId('1', {name: "Shell"}) atmos = @userForId('2', {name: "atmos"}) holman = @userForId('3', {name: "Zach Holman"}) , 3000 module.exports = Shell
44157
Robot = require '../robot' class Shell extends Robot send: (user, strings...) -> for str in strings console.log str reply: (user, strings...) -> for str in strings @send user, "#{user.name}: #{str}" run: -> console.log "Hubot: the Shell." user = @userForId('1', {name: "Shell"}) process.stdin.resume() process.stdin.on 'data', (txt) => txt.toString().split("\n").forEach (line) => return if line.length is 0 @receive new Robot.TextMessage user, line setTimeout => user = @userForId('1', {name: "Shell"}) atmos = @userForId('2', {name: "atmos"}) holman = @userForId('3', {name: "<NAME>"}) , 3000 module.exports = Shell
true
Robot = require '../robot' class Shell extends Robot send: (user, strings...) -> for str in strings console.log str reply: (user, strings...) -> for str in strings @send user, "#{user.name}: #{str}" run: -> console.log "Hubot: the Shell." user = @userForId('1', {name: "Shell"}) process.stdin.resume() process.stdin.on 'data', (txt) => txt.toString().split("\n").forEach (line) => return if line.length is 0 @receive new Robot.TextMessage user, line setTimeout => user = @userForId('1', {name: "Shell"}) atmos = @userForId('2', {name: "atmos"}) holman = @userForId('3', {name: "PI:NAME:<NAME>END_PI"}) , 3000 module.exports = Shell
[ { "context": "iew Tests for no-this-before-super rule.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------", "end": 82, "score": 0.9998738765716553, "start": 68, "tag": "NAME", "value": "Toru Nagashima" }, { "context": " this.a()\n '''\n\n # https://github.com/eslint/eslint/issues/5261\n '''\n class A extends ", "end": 3173, "score": 0.9989342093467712, "start": 3167, "tag": "USERNAME", "value": "eslint" }, { "context": " super()\n '''\n\n # https://github.com/eslint/eslint/issues/5319\n '''\n class A extends ", "end": 3454, "score": 0.9990479350090027, "start": 3448, "tag": "USERNAME", "value": "eslint" }, { "context": "d (->) and @foo\n '''\n\n # https://github.com/eslint/eslint/issues/5894\n '''\n class A\n ", "end": 3627, "score": 0.9989529252052307, "start": 3621, "tag": "USERNAME", "value": "eslint" }, { "context": " # this\n # '''\n\n # https://github.com/eslint/eslint/issues/8848\n '''\n class A extends ", "end": 3873, "score": 0.999055802822113, "start": 3867, "tag": "USERNAME", "value": "eslint" } ]
src/tests/rules/no-this-before-super.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-this-before-super rule. # @author Toru Nagashima ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-this-before-super' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-this-before-super', rule, valid: [ ### # if the class has no extends or `extends null`, just ignore. # those classes cannot call `super()`. ### 'class A' ''' class A constructor: -> ''' ''' class A constructor: -> @b = 0 ''' ''' class A constructor: -> @b() ''' 'class A extends null' ''' class A extends null constructor: -> ''' # allows `this`/`super` after `super()`. ''' class A extends B ''' ''' class A extends B constructor: -> super() ''' ''' class A extends B constructor: -> super() @c = @d ''' ''' class A extends B constructor: -> super() this.c() ''' ''' class A extends B constructor: -> super() super.c() ''' ''' class A extends B constructor: (@a) -> super() ''' ''' class A extends B constructor: -> if yes super() else super() this.c() ''' # allows `this`/`super` in nested executable scopes, even if before `super()`. ''' class A extends B constructor: -> class B extends C constructor: -> super() @d = 0 super() ''' ''' class A extends B constructor: -> B = class extends C constructor: -> super() this.d = 0 super() ''' ''' class A extends B constructor: -> c = -> @d() super() ''' # ''' # class A extends B # constructor: -> # c = => @d() # super() # ''' # ignores out of constructors. ''' class A b: -> @c = 0 ''' ''' class A extends B c: -> @d = 0 ''' ''' a = -> @b = 0 ''' # multi code path. ''' class A extends B constructor: -> if a super() this.a() else super() this.b() ''' ''' class A extends B constructor: -> if a super() else super() this.a() ''' ''' class A extends B constructor: -> try super() finally this.a() ''' # https://github.com/eslint/eslint/issues/5261 ''' class A extends B constructor: (a) -> super() @a() for b from a ''' ''' class A extends B constructor: (a) -> foo b for b from a super() ''' # https://github.com/eslint/eslint/issues/5319 ''' class A extends B constructor: (a) -> super() @a = a and (->) and @foo ''' # https://github.com/eslint/eslint/issues/5894 ''' class A constructor: -> return this ''' # ''' # class A extends B # constructor: -> # return # this # ''' # https://github.com/eslint/eslint/issues/8848 ''' class A extends B constructor: (props) -> super props try arr = [] for a from arr ; catch err ''' ''' class CoffeeClassWithDrinkOrder extends CoffeeClass constructor: (@size = 'grande') -> super() ''' ] invalid: [ # # disallows all `this`/`super` if `super()` is missing. # code: ''' # class A extends B # constructor: -> @c = 0 # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , # code: ''' # class A extends B # constructor: (@c) -> # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , # code: ''' # class A extends B # constructor: -> this.c() # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , code: ''' class A extends B constructor: -> super.c() ''' errors: [message: "'super' is not allowed before 'super()'.", type: 'Super'] , # , # # disallows `this`/`super` before `super()`. # code: ''' # class A extends B # constructor: -> # @c = 0 # super() # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , # code: ''' # class A extends B # constructor: -> # @c() # super() # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] code: ''' class A extends B constructor: -> super.c() super() ''' errors: [message: "'super' is not allowed before 'super()'.", type: 'Super'] , # , # # disallows `this`/`super` in arguments of `super()`. # code: ''' # class A extends B # constructor: -> super @c # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] code: ''' class A extends B constructor: -> super this.c() ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] , code: ''' class A extends B constructor: -> super super.c() ''' errors: [message: "'super' is not allowed before 'super()'.", type: 'Super'] # , # # even if is nested, reports correctly. # code: ''' # class A extends B # constructor: -> # class C extends D # constructor: -> # super() # @e() # @f() # super() # ''' # errors: [ # message: "'this' is not allowed before 'super()'." # type: 'ThisExpression' # line: 7 # ] # , # , # code: ''' # class A extends B # constructor: -> # class C extends D # constructor: -> # this.e() # super() # super() # this.f() # ''' # errors: [ # message: "'this' is not allowed before 'super()'." # type: 'ThisExpression' # line: 5 # ] # multi code path. code: ''' class A extends B constructor: -> if a then super() else @a() ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] , code: ''' class A extends B constructor: -> try super() finally this.a ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] , code: ''' class A extends B constructor: -> try super() catch err this.a ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] ]
207079
###* # @fileoverview Tests for no-this-before-super rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-this-before-super' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-this-before-super', rule, valid: [ ### # if the class has no extends or `extends null`, just ignore. # those classes cannot call `super()`. ### 'class A' ''' class A constructor: -> ''' ''' class A constructor: -> @b = 0 ''' ''' class A constructor: -> @b() ''' 'class A extends null' ''' class A extends null constructor: -> ''' # allows `this`/`super` after `super()`. ''' class A extends B ''' ''' class A extends B constructor: -> super() ''' ''' class A extends B constructor: -> super() @c = @d ''' ''' class A extends B constructor: -> super() this.c() ''' ''' class A extends B constructor: -> super() super.c() ''' ''' class A extends B constructor: (@a) -> super() ''' ''' class A extends B constructor: -> if yes super() else super() this.c() ''' # allows `this`/`super` in nested executable scopes, even if before `super()`. ''' class A extends B constructor: -> class B extends C constructor: -> super() @d = 0 super() ''' ''' class A extends B constructor: -> B = class extends C constructor: -> super() this.d = 0 super() ''' ''' class A extends B constructor: -> c = -> @d() super() ''' # ''' # class A extends B # constructor: -> # c = => @d() # super() # ''' # ignores out of constructors. ''' class A b: -> @c = 0 ''' ''' class A extends B c: -> @d = 0 ''' ''' a = -> @b = 0 ''' # multi code path. ''' class A extends B constructor: -> if a super() this.a() else super() this.b() ''' ''' class A extends B constructor: -> if a super() else super() this.a() ''' ''' class A extends B constructor: -> try super() finally this.a() ''' # https://github.com/eslint/eslint/issues/5261 ''' class A extends B constructor: (a) -> super() @a() for b from a ''' ''' class A extends B constructor: (a) -> foo b for b from a super() ''' # https://github.com/eslint/eslint/issues/5319 ''' class A extends B constructor: (a) -> super() @a = a and (->) and @foo ''' # https://github.com/eslint/eslint/issues/5894 ''' class A constructor: -> return this ''' # ''' # class A extends B # constructor: -> # return # this # ''' # https://github.com/eslint/eslint/issues/8848 ''' class A extends B constructor: (props) -> super props try arr = [] for a from arr ; catch err ''' ''' class CoffeeClassWithDrinkOrder extends CoffeeClass constructor: (@size = 'grande') -> super() ''' ] invalid: [ # # disallows all `this`/`super` if `super()` is missing. # code: ''' # class A extends B # constructor: -> @c = 0 # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , # code: ''' # class A extends B # constructor: (@c) -> # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , # code: ''' # class A extends B # constructor: -> this.c() # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , code: ''' class A extends B constructor: -> super.c() ''' errors: [message: "'super' is not allowed before 'super()'.", type: 'Super'] , # , # # disallows `this`/`super` before `super()`. # code: ''' # class A extends B # constructor: -> # @c = 0 # super() # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , # code: ''' # class A extends B # constructor: -> # @c() # super() # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] code: ''' class A extends B constructor: -> super.c() super() ''' errors: [message: "'super' is not allowed before 'super()'.", type: 'Super'] , # , # # disallows `this`/`super` in arguments of `super()`. # code: ''' # class A extends B # constructor: -> super @c # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] code: ''' class A extends B constructor: -> super this.c() ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] , code: ''' class A extends B constructor: -> super super.c() ''' errors: [message: "'super' is not allowed before 'super()'.", type: 'Super'] # , # # even if is nested, reports correctly. # code: ''' # class A extends B # constructor: -> # class C extends D # constructor: -> # super() # @e() # @f() # super() # ''' # errors: [ # message: "'this' is not allowed before 'super()'." # type: 'ThisExpression' # line: 7 # ] # , # , # code: ''' # class A extends B # constructor: -> # class C extends D # constructor: -> # this.e() # super() # super() # this.f() # ''' # errors: [ # message: "'this' is not allowed before 'super()'." # type: 'ThisExpression' # line: 5 # ] # multi code path. code: ''' class A extends B constructor: -> if a then super() else @a() ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] , code: ''' class A extends B constructor: -> try super() finally this.a ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] , code: ''' class A extends B constructor: -> try super() catch err this.a ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] ]
true
###* # @fileoverview Tests for no-this-before-super rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-this-before-super' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-this-before-super', rule, valid: [ ### # if the class has no extends or `extends null`, just ignore. # those classes cannot call `super()`. ### 'class A' ''' class A constructor: -> ''' ''' class A constructor: -> @b = 0 ''' ''' class A constructor: -> @b() ''' 'class A extends null' ''' class A extends null constructor: -> ''' # allows `this`/`super` after `super()`. ''' class A extends B ''' ''' class A extends B constructor: -> super() ''' ''' class A extends B constructor: -> super() @c = @d ''' ''' class A extends B constructor: -> super() this.c() ''' ''' class A extends B constructor: -> super() super.c() ''' ''' class A extends B constructor: (@a) -> super() ''' ''' class A extends B constructor: -> if yes super() else super() this.c() ''' # allows `this`/`super` in nested executable scopes, even if before `super()`. ''' class A extends B constructor: -> class B extends C constructor: -> super() @d = 0 super() ''' ''' class A extends B constructor: -> B = class extends C constructor: -> super() this.d = 0 super() ''' ''' class A extends B constructor: -> c = -> @d() super() ''' # ''' # class A extends B # constructor: -> # c = => @d() # super() # ''' # ignores out of constructors. ''' class A b: -> @c = 0 ''' ''' class A extends B c: -> @d = 0 ''' ''' a = -> @b = 0 ''' # multi code path. ''' class A extends B constructor: -> if a super() this.a() else super() this.b() ''' ''' class A extends B constructor: -> if a super() else super() this.a() ''' ''' class A extends B constructor: -> try super() finally this.a() ''' # https://github.com/eslint/eslint/issues/5261 ''' class A extends B constructor: (a) -> super() @a() for b from a ''' ''' class A extends B constructor: (a) -> foo b for b from a super() ''' # https://github.com/eslint/eslint/issues/5319 ''' class A extends B constructor: (a) -> super() @a = a and (->) and @foo ''' # https://github.com/eslint/eslint/issues/5894 ''' class A constructor: -> return this ''' # ''' # class A extends B # constructor: -> # return # this # ''' # https://github.com/eslint/eslint/issues/8848 ''' class A extends B constructor: (props) -> super props try arr = [] for a from arr ; catch err ''' ''' class CoffeeClassWithDrinkOrder extends CoffeeClass constructor: (@size = 'grande') -> super() ''' ] invalid: [ # # disallows all `this`/`super` if `super()` is missing. # code: ''' # class A extends B # constructor: -> @c = 0 # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , # code: ''' # class A extends B # constructor: (@c) -> # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , # code: ''' # class A extends B # constructor: -> this.c() # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , code: ''' class A extends B constructor: -> super.c() ''' errors: [message: "'super' is not allowed before 'super()'.", type: 'Super'] , # , # # disallows `this`/`super` before `super()`. # code: ''' # class A extends B # constructor: -> # @c = 0 # super() # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] # , # code: ''' # class A extends B # constructor: -> # @c() # super() # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] code: ''' class A extends B constructor: -> super.c() super() ''' errors: [message: "'super' is not allowed before 'super()'.", type: 'Super'] , # , # # disallows `this`/`super` in arguments of `super()`. # code: ''' # class A extends B # constructor: -> super @c # ''' # errors: [ # message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' # ] code: ''' class A extends B constructor: -> super this.c() ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] , code: ''' class A extends B constructor: -> super super.c() ''' errors: [message: "'super' is not allowed before 'super()'.", type: 'Super'] # , # # even if is nested, reports correctly. # code: ''' # class A extends B # constructor: -> # class C extends D # constructor: -> # super() # @e() # @f() # super() # ''' # errors: [ # message: "'this' is not allowed before 'super()'." # type: 'ThisExpression' # line: 7 # ] # , # , # code: ''' # class A extends B # constructor: -> # class C extends D # constructor: -> # this.e() # super() # super() # this.f() # ''' # errors: [ # message: "'this' is not allowed before 'super()'." # type: 'ThisExpression' # line: 5 # ] # multi code path. code: ''' class A extends B constructor: -> if a then super() else @a() ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] , code: ''' class A extends B constructor: -> try super() finally this.a ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] , code: ''' class A extends B constructor: -> try super() catch err this.a ''' errors: [ message: "'this' is not allowed before 'super()'.", type: 'ThisExpression' ] ]
[ { "context": " \n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) \n# ", "end": 824, "score": 0.9997811317443848, "start": 814, "tag": "NAME", "value": "Mark Masse" } ]
wrmldoc/js/app/config/backbone/sync.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 do (Backbone) -> _sync = Backbone.sync Backbone.sync = (method, entity, options = {}) -> _.defaults options, beforeSend: _.bind(methods.beforeSend, entity) complete: _.bind(methods.complete, entity) sync = _sync(method, entity, options) if !entity._fetch and method is "read" entity._fetch = sync methods = beforeSend: -> @trigger "sync:start", @ complete: -> @trigger "sync:stop", @
131975
# # 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 do (Backbone) -> _sync = Backbone.sync Backbone.sync = (method, entity, options = {}) -> _.defaults options, beforeSend: _.bind(methods.beforeSend, entity) complete: _.bind(methods.complete, entity) sync = _sync(method, entity, options) if !entity._fetch and method is "read" entity._fetch = sync methods = beforeSend: -> @trigger "sync:start", @ complete: -> @trigger "sync:stop", @
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 do (Backbone) -> _sync = Backbone.sync Backbone.sync = (method, entity, options = {}) -> _.defaults options, beforeSend: _.bind(methods.beforeSend, entity) complete: _.bind(methods.complete, entity) sync = _sync(method, entity, options) if !entity._fetch and method is "read" entity._fetch = sync methods = beforeSend: -> @trigger "sync:start", @ complete: -> @trigger "sync:stop", @
[ { "context": "')\n expect(connInfo.username).toEqual('foo')\n expect(connInfo.password).toEqual('", "end": 603, "score": 0.9972653388977051, "start": 600, "tag": "USERNAME", "value": "foo" }, { "context": "')\n expect(connInfo.password).toEqual('bar')\n expect(connInfo.hostname).toEqual('", "end": 656, "score": 0.9992815852165222, "start": 653, "tag": "PASSWORD", "value": "bar" } ]
spec/database_spec.coffee
monokrome/modelingclay
0
Database = require('../lib/database').Database MySqlAdapter = require('../lib/adapters/mysql').MySqlAdapter Query = require('../lib/query').Query describe 'Database', -> describe '#connect', -> it 'should accept a connection string and parse it correctly', -> db = new Database() db.connect('mysql://foo:bar@localhost:3306/test') expect(db.connectionInfo).toBeDefined() connInfo = db.connectionInfo expect(connInfo.engine).toEqual('mysql') expect(connInfo.username).toEqual('foo') expect(connInfo.password).toEqual('bar') expect(connInfo.hostname).toEqual('localhost') expect(connInfo.port).toEqual('3306') expect(connInfo.database).toEqual('test') it 'should accept a partial connection string and parse it correctly', -> db = new Database() db.connect('mysql://@localhost/test') expect(db.connectionInfo).toBeDefined() connInfo = db.connectionInfo expect(connInfo.engine).toEqual('mysql') expect(connInfo.username).toEqual(undefined) expect(connInfo.password).toEqual(undefined) expect(connInfo.hostname).toEqual('localhost') expect(connInfo.port).toEqual(undefined) expect(connInfo.database).toEqual('test') it 'should require at minimum the engine, hostname, and database', -> db = new Database() withoutDatabase = -> db.connect('mysql://@localhost') withoutHostname = -> db.connect('mysql://') withoutEngine = -> db.connect('@localhost/database') expect(withoutDatabase).toThrow('Connection string is invalid: engine, hostname, and database are required parameters.') expect(withoutHostname).toThrow('Connection string is invalid: engine, hostname, and database are required parameters.') expect(withoutEngine).toThrow('Connection string is invalid: engine, hostname, and database are required parameters.') it 'should choose the appropriate engine', -> spyOn(MySqlAdapter.prototype, 'connect') db = new Database() db.connect('mysql://@localhost/test') expect(db.adapter).toBeDefined() expect(db.adapter).toBeInstanceOf(MySqlAdapter) expect(MySqlAdapter.prototype.connect).toHaveBeenCalledWith('localhost', undefined, undefined, 'test') describe '#adapterFactory', -> it 'should return MySqlAdapter instance when "mysql" is passed', -> db = new Database() expect(db.adapterFactory("mysql")).toBeInstanceOf(MySqlAdapter) it 'should raise an error when the type is not understood', -> db = new Database() testUnknownEngineType = -> db.adapterFactory("unknown") expect(testUnknownEngineType).toThrow('Unknown engine type: unknown') describe '#query', -> it 'should return a new instance of Query', -> db = new Database() db.connect('mysql://localhost/test') expect(db.query()).toBeInstanceOf(Query) it 'should raise an error when not connected', -> db = new Database() testQueryRaisesError = -> db.query() expect(testQueryRaisesError).toThrow('An active connection is required for query().')
91736
Database = require('../lib/database').Database MySqlAdapter = require('../lib/adapters/mysql').MySqlAdapter Query = require('../lib/query').Query describe 'Database', -> describe '#connect', -> it 'should accept a connection string and parse it correctly', -> db = new Database() db.connect('mysql://foo:bar@localhost:3306/test') expect(db.connectionInfo).toBeDefined() connInfo = db.connectionInfo expect(connInfo.engine).toEqual('mysql') expect(connInfo.username).toEqual('foo') expect(connInfo.password).toEqual('<PASSWORD>') expect(connInfo.hostname).toEqual('localhost') expect(connInfo.port).toEqual('3306') expect(connInfo.database).toEqual('test') it 'should accept a partial connection string and parse it correctly', -> db = new Database() db.connect('mysql://@localhost/test') expect(db.connectionInfo).toBeDefined() connInfo = db.connectionInfo expect(connInfo.engine).toEqual('mysql') expect(connInfo.username).toEqual(undefined) expect(connInfo.password).toEqual(undefined) expect(connInfo.hostname).toEqual('localhost') expect(connInfo.port).toEqual(undefined) expect(connInfo.database).toEqual('test') it 'should require at minimum the engine, hostname, and database', -> db = new Database() withoutDatabase = -> db.connect('mysql://@localhost') withoutHostname = -> db.connect('mysql://') withoutEngine = -> db.connect('@localhost/database') expect(withoutDatabase).toThrow('Connection string is invalid: engine, hostname, and database are required parameters.') expect(withoutHostname).toThrow('Connection string is invalid: engine, hostname, and database are required parameters.') expect(withoutEngine).toThrow('Connection string is invalid: engine, hostname, and database are required parameters.') it 'should choose the appropriate engine', -> spyOn(MySqlAdapter.prototype, 'connect') db = new Database() db.connect('mysql://@localhost/test') expect(db.adapter).toBeDefined() expect(db.adapter).toBeInstanceOf(MySqlAdapter) expect(MySqlAdapter.prototype.connect).toHaveBeenCalledWith('localhost', undefined, undefined, 'test') describe '#adapterFactory', -> it 'should return MySqlAdapter instance when "mysql" is passed', -> db = new Database() expect(db.adapterFactory("mysql")).toBeInstanceOf(MySqlAdapter) it 'should raise an error when the type is not understood', -> db = new Database() testUnknownEngineType = -> db.adapterFactory("unknown") expect(testUnknownEngineType).toThrow('Unknown engine type: unknown') describe '#query', -> it 'should return a new instance of Query', -> db = new Database() db.connect('mysql://localhost/test') expect(db.query()).toBeInstanceOf(Query) it 'should raise an error when not connected', -> db = new Database() testQueryRaisesError = -> db.query() expect(testQueryRaisesError).toThrow('An active connection is required for query().')
true
Database = require('../lib/database').Database MySqlAdapter = require('../lib/adapters/mysql').MySqlAdapter Query = require('../lib/query').Query describe 'Database', -> describe '#connect', -> it 'should accept a connection string and parse it correctly', -> db = new Database() db.connect('mysql://foo:bar@localhost:3306/test') expect(db.connectionInfo).toBeDefined() connInfo = db.connectionInfo expect(connInfo.engine).toEqual('mysql') expect(connInfo.username).toEqual('foo') expect(connInfo.password).toEqual('PI:PASSWORD:<PASSWORD>END_PI') expect(connInfo.hostname).toEqual('localhost') expect(connInfo.port).toEqual('3306') expect(connInfo.database).toEqual('test') it 'should accept a partial connection string and parse it correctly', -> db = new Database() db.connect('mysql://@localhost/test') expect(db.connectionInfo).toBeDefined() connInfo = db.connectionInfo expect(connInfo.engine).toEqual('mysql') expect(connInfo.username).toEqual(undefined) expect(connInfo.password).toEqual(undefined) expect(connInfo.hostname).toEqual('localhost') expect(connInfo.port).toEqual(undefined) expect(connInfo.database).toEqual('test') it 'should require at minimum the engine, hostname, and database', -> db = new Database() withoutDatabase = -> db.connect('mysql://@localhost') withoutHostname = -> db.connect('mysql://') withoutEngine = -> db.connect('@localhost/database') expect(withoutDatabase).toThrow('Connection string is invalid: engine, hostname, and database are required parameters.') expect(withoutHostname).toThrow('Connection string is invalid: engine, hostname, and database are required parameters.') expect(withoutEngine).toThrow('Connection string is invalid: engine, hostname, and database are required parameters.') it 'should choose the appropriate engine', -> spyOn(MySqlAdapter.prototype, 'connect') db = new Database() db.connect('mysql://@localhost/test') expect(db.adapter).toBeDefined() expect(db.adapter).toBeInstanceOf(MySqlAdapter) expect(MySqlAdapter.prototype.connect).toHaveBeenCalledWith('localhost', undefined, undefined, 'test') describe '#adapterFactory', -> it 'should return MySqlAdapter instance when "mysql" is passed', -> db = new Database() expect(db.adapterFactory("mysql")).toBeInstanceOf(MySqlAdapter) it 'should raise an error when the type is not understood', -> db = new Database() testUnknownEngineType = -> db.adapterFactory("unknown") expect(testUnknownEngineType).toThrow('Unknown engine type: unknown') describe '#query', -> it 'should return a new instance of Query', -> db = new Database() db.connect('mysql://localhost/test') expect(db.query()).toBeInstanceOf(Query) it 'should raise an error when not connected', -> db = new Database() testQueryRaisesError = -> db.query() expect(testQueryRaisesError).toThrow('An active connection is required for query().')
[ { "context": "\n //- {\n custom: {\n name: {\n de: 'Hajo',\n en: 'Abi'\n }\n }\n }\n ###\n\n ma", "end": 2488, "score": 0.9995008707046509, "start": 2484, "tag": "NAME", "value": "Hajo" }, { "context": " {\n name: {\n de: 'Hajo',\n en: 'Abi'\n }\n }\n }\n ###\n\n mapLocalizedString: (", "end": 2507, "score": 0.9984041452407837, "start": 2504, "tag": "NAME", "value": "Abi" } ]
src/coffee/mappings.coffee
wkrugiolka/sphere-stock-import
0
_ = require 'underscore' csv = require 'csv' CONS = require './constants' class CustomFieldMappings constructor: (options = {}) -> @errors = [] mapFieldTypes: ({fieldDefinitions, typeDefinitionKey, rowIndex, key, value, langHeader}) -> result = undefined _.each fieldDefinitions, (fieldDefinition) => if fieldDefinition.name is key switch fieldDefinition.type.name when 'Number' then result = @mapNumber value, typeDefinitionKey, rowIndex when 'Boolean' then result = @mapBoolean value, typeDefinitionKey, rowIndex when 'Money' then result = @mapMoney value, typeDefinitionKey, rowIndex when 'LocalizedString' then result = @mapLocalizedString value, typeDefinitionKey, rowIndex, langHeader when 'Set' then result = @mapSet value, typeDefinitionKey, rowIndex, fieldDefinition.type.elementType when 'String', 'Enum', 'LocalizedEnum', 'Date', 'Time', 'DateTime', 'Reference' if (!_.isUndefined(value)) result = value else @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] The type '#{fieldDefinition.type.name}' is not supported." return result mapSet: (values, typeDefinitionKey, rowIndex, elementType) -> result = undefined values = values.split(',') result = _.map values, (value) => switch elementType.name when 'Number' then @mapNumber value, typeDefinitionKey, rowIndex when 'Boolean' then @mapBoolean value, typeDefinitionKey, rowIndex when 'Money' then @mapMoney value, typeDefinitionKey, rowIndex when 'String', 'Enum', 'LocalizedEnum', 'Date', 'Time', 'DateTime', 'Reference' if (!_.isUndefined(value)) value else @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] The type '#{elementType.name}' is not supported." return _.reject(result, _.isUndefined) isValidValue: (rawValue) -> return _.isString(rawValue) and rawValue.length > 0 mapNumber: (rawNumber, typeDefinitionKey, rowIndex, regEx = CONS.REGEX_INTEGER) -> return unless @isValidValue(rawNumber) matchedNumber = regEx.exec rawNumber unless matchedNumber @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] The number '#{rawNumber}' isn't valid!" return parseInt matchedNumber[0],10 ### custom,customField.name.de,customField.name.en my-type,Hajo,Abi //- { custom: { name: { de: 'Hajo', en: 'Abi' } } } ### mapLocalizedString: (value, typeDefinitionKey, rowIndex, langHeader, regEx = CONS.REGEX_LANGUAGE) -> if !regEx.test langHeader @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] localizedString header '#{langHeader}' format is not valid!" unless regEx.test langHeader return else "#{langHeader}": value mapBoolean: (rawBoolean, typeDefinitionKey, rowIndex) -> result = undefined if _.isUndefined(rawBoolean) or (_.isString(rawBoolean) and _.isEmpty(rawBoolean)) return errorMsg = "[row #{rowIndex}:#{typeDefinitionKey}] The value '#{rawBoolean}' isn't a valid boolean!" try b = JSON.parse(rawBoolean.toLowerCase()) if not _.isBoolean b @errors.push error return b catch @errors.push errorMsg return # EUR 300 # USD 999 mapMoney: (rawMoney, typeDefinitionKey, rowIndex) -> return unless @isValidValue(rawMoney) matchedMoney = CONS.REGEX_MONEY.exec rawMoney unless matchedMoney @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] Can not parse money '#{rawMoney}'!" return money = currencyCode: matchedMoney[1].toUpperCase() centAmount: parseInt matchedMoney[2],10 module.exports = CustomFieldMappings
82954
_ = require 'underscore' csv = require 'csv' CONS = require './constants' class CustomFieldMappings constructor: (options = {}) -> @errors = [] mapFieldTypes: ({fieldDefinitions, typeDefinitionKey, rowIndex, key, value, langHeader}) -> result = undefined _.each fieldDefinitions, (fieldDefinition) => if fieldDefinition.name is key switch fieldDefinition.type.name when 'Number' then result = @mapNumber value, typeDefinitionKey, rowIndex when 'Boolean' then result = @mapBoolean value, typeDefinitionKey, rowIndex when 'Money' then result = @mapMoney value, typeDefinitionKey, rowIndex when 'LocalizedString' then result = @mapLocalizedString value, typeDefinitionKey, rowIndex, langHeader when 'Set' then result = @mapSet value, typeDefinitionKey, rowIndex, fieldDefinition.type.elementType when 'String', 'Enum', 'LocalizedEnum', 'Date', 'Time', 'DateTime', 'Reference' if (!_.isUndefined(value)) result = value else @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] The type '#{fieldDefinition.type.name}' is not supported." return result mapSet: (values, typeDefinitionKey, rowIndex, elementType) -> result = undefined values = values.split(',') result = _.map values, (value) => switch elementType.name when 'Number' then @mapNumber value, typeDefinitionKey, rowIndex when 'Boolean' then @mapBoolean value, typeDefinitionKey, rowIndex when 'Money' then @mapMoney value, typeDefinitionKey, rowIndex when 'String', 'Enum', 'LocalizedEnum', 'Date', 'Time', 'DateTime', 'Reference' if (!_.isUndefined(value)) value else @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] The type '#{elementType.name}' is not supported." return _.reject(result, _.isUndefined) isValidValue: (rawValue) -> return _.isString(rawValue) and rawValue.length > 0 mapNumber: (rawNumber, typeDefinitionKey, rowIndex, regEx = CONS.REGEX_INTEGER) -> return unless @isValidValue(rawNumber) matchedNumber = regEx.exec rawNumber unless matchedNumber @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] The number '#{rawNumber}' isn't valid!" return parseInt matchedNumber[0],10 ### custom,customField.name.de,customField.name.en my-type,Hajo,Abi //- { custom: { name: { de: '<NAME>', en: '<NAME>' } } } ### mapLocalizedString: (value, typeDefinitionKey, rowIndex, langHeader, regEx = CONS.REGEX_LANGUAGE) -> if !regEx.test langHeader @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] localizedString header '#{langHeader}' format is not valid!" unless regEx.test langHeader return else "#{langHeader}": value mapBoolean: (rawBoolean, typeDefinitionKey, rowIndex) -> result = undefined if _.isUndefined(rawBoolean) or (_.isString(rawBoolean) and _.isEmpty(rawBoolean)) return errorMsg = "[row #{rowIndex}:#{typeDefinitionKey}] The value '#{rawBoolean}' isn't a valid boolean!" try b = JSON.parse(rawBoolean.toLowerCase()) if not _.isBoolean b @errors.push error return b catch @errors.push errorMsg return # EUR 300 # USD 999 mapMoney: (rawMoney, typeDefinitionKey, rowIndex) -> return unless @isValidValue(rawMoney) matchedMoney = CONS.REGEX_MONEY.exec rawMoney unless matchedMoney @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] Can not parse money '#{rawMoney}'!" return money = currencyCode: matchedMoney[1].toUpperCase() centAmount: parseInt matchedMoney[2],10 module.exports = CustomFieldMappings
true
_ = require 'underscore' csv = require 'csv' CONS = require './constants' class CustomFieldMappings constructor: (options = {}) -> @errors = [] mapFieldTypes: ({fieldDefinitions, typeDefinitionKey, rowIndex, key, value, langHeader}) -> result = undefined _.each fieldDefinitions, (fieldDefinition) => if fieldDefinition.name is key switch fieldDefinition.type.name when 'Number' then result = @mapNumber value, typeDefinitionKey, rowIndex when 'Boolean' then result = @mapBoolean value, typeDefinitionKey, rowIndex when 'Money' then result = @mapMoney value, typeDefinitionKey, rowIndex when 'LocalizedString' then result = @mapLocalizedString value, typeDefinitionKey, rowIndex, langHeader when 'Set' then result = @mapSet value, typeDefinitionKey, rowIndex, fieldDefinition.type.elementType when 'String', 'Enum', 'LocalizedEnum', 'Date', 'Time', 'DateTime', 'Reference' if (!_.isUndefined(value)) result = value else @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] The type '#{fieldDefinition.type.name}' is not supported." return result mapSet: (values, typeDefinitionKey, rowIndex, elementType) -> result = undefined values = values.split(',') result = _.map values, (value) => switch elementType.name when 'Number' then @mapNumber value, typeDefinitionKey, rowIndex when 'Boolean' then @mapBoolean value, typeDefinitionKey, rowIndex when 'Money' then @mapMoney value, typeDefinitionKey, rowIndex when 'String', 'Enum', 'LocalizedEnum', 'Date', 'Time', 'DateTime', 'Reference' if (!_.isUndefined(value)) value else @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] The type '#{elementType.name}' is not supported." return _.reject(result, _.isUndefined) isValidValue: (rawValue) -> return _.isString(rawValue) and rawValue.length > 0 mapNumber: (rawNumber, typeDefinitionKey, rowIndex, regEx = CONS.REGEX_INTEGER) -> return unless @isValidValue(rawNumber) matchedNumber = regEx.exec rawNumber unless matchedNumber @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] The number '#{rawNumber}' isn't valid!" return parseInt matchedNumber[0],10 ### custom,customField.name.de,customField.name.en my-type,Hajo,Abi //- { custom: { name: { de: 'PI:NAME:<NAME>END_PI', en: 'PI:NAME:<NAME>END_PI' } } } ### mapLocalizedString: (value, typeDefinitionKey, rowIndex, langHeader, regEx = CONS.REGEX_LANGUAGE) -> if !regEx.test langHeader @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] localizedString header '#{langHeader}' format is not valid!" unless regEx.test langHeader return else "#{langHeader}": value mapBoolean: (rawBoolean, typeDefinitionKey, rowIndex) -> result = undefined if _.isUndefined(rawBoolean) or (_.isString(rawBoolean) and _.isEmpty(rawBoolean)) return errorMsg = "[row #{rowIndex}:#{typeDefinitionKey}] The value '#{rawBoolean}' isn't a valid boolean!" try b = JSON.parse(rawBoolean.toLowerCase()) if not _.isBoolean b @errors.push error return b catch @errors.push errorMsg return # EUR 300 # USD 999 mapMoney: (rawMoney, typeDefinitionKey, rowIndex) -> return unless @isValidValue(rawMoney) matchedMoney = CONS.REGEX_MONEY.exec rawMoney unless matchedMoney @errors.push "[row #{rowIndex}:#{typeDefinitionKey}] Can not parse money '#{rawMoney}'!" return money = currencyCode: matchedMoney[1].toUpperCase() centAmount: parseInt matchedMoney[2],10 module.exports = CustomFieldMappings
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999120831489563, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/_classes/forum-topic-title.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @ForumTopicTitle constructor: -> @input = document.getElementsByClassName('js-forum-topic-title--input') @saveButton = document.getElementsByClassName('js-forum-topic-title--save') @title = document.getElementsByClassName('js-forum-topic-title--title') @toggleables = document.getElementsByClassName('js-forum-topic-title--toggleable') addEventListener 'turbolinks:before-cache', @abort $(document).on 'click', '.js-forum-topic-title--edit-start', @editShow $(document).on 'click', '.js-forum-topic-title--save', @save $(document).on 'keyup', '.js-forum-topic-title--input', @onKeyup $(document).on 'click', '.js-forum-topic-title--cancel', @cancel $(document).on 'input', '.js-forum-topic-title--input', @onInput abort: => @xhr?.abort() cancel: => @abort() $(@toggleables).removeAttr('data-title-edit') @input[0].value = @input[0].defaultValue editShow: => $(@toggleables).attr('data-title-edit', 1) @input[0].selectionStart = @input[0].value.length @input[0].focus() onInput: => @saveButton[0].disabled = !osu.present(@input[0].value) onKeyup: (e) => switch e.keyCode # enter when 13 then @save() # escape when 27 then @cancel() save: => input = @input[0] newTitle = input.value return if !osu.presence(newTitle)? return @cancel() if newTitle == input.defaultValue input.disabled = true @saveButton[0].disabled = true @abort() @xhr = $.ajax input.dataset.url, method: 'PUT' data: "#{input.name}": newTitle .done => # because page title is also changed =D osu.reloadPage() .fail (xhr) => input.disabled = false @saveButton[0].disabled = false osu.emitAjaxError() xhr
164944
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @ForumTopicTitle constructor: -> @input = document.getElementsByClassName('js-forum-topic-title--input') @saveButton = document.getElementsByClassName('js-forum-topic-title--save') @title = document.getElementsByClassName('js-forum-topic-title--title') @toggleables = document.getElementsByClassName('js-forum-topic-title--toggleable') addEventListener 'turbolinks:before-cache', @abort $(document).on 'click', '.js-forum-topic-title--edit-start', @editShow $(document).on 'click', '.js-forum-topic-title--save', @save $(document).on 'keyup', '.js-forum-topic-title--input', @onKeyup $(document).on 'click', '.js-forum-topic-title--cancel', @cancel $(document).on 'input', '.js-forum-topic-title--input', @onInput abort: => @xhr?.abort() cancel: => @abort() $(@toggleables).removeAttr('data-title-edit') @input[0].value = @input[0].defaultValue editShow: => $(@toggleables).attr('data-title-edit', 1) @input[0].selectionStart = @input[0].value.length @input[0].focus() onInput: => @saveButton[0].disabled = !osu.present(@input[0].value) onKeyup: (e) => switch e.keyCode # enter when 13 then @save() # escape when 27 then @cancel() save: => input = @input[0] newTitle = input.value return if !osu.presence(newTitle)? return @cancel() if newTitle == input.defaultValue input.disabled = true @saveButton[0].disabled = true @abort() @xhr = $.ajax input.dataset.url, method: 'PUT' data: "#{input.name}": newTitle .done => # because page title is also changed =D osu.reloadPage() .fail (xhr) => input.disabled = false @saveButton[0].disabled = false osu.emitAjaxError() xhr
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @ForumTopicTitle constructor: -> @input = document.getElementsByClassName('js-forum-topic-title--input') @saveButton = document.getElementsByClassName('js-forum-topic-title--save') @title = document.getElementsByClassName('js-forum-topic-title--title') @toggleables = document.getElementsByClassName('js-forum-topic-title--toggleable') addEventListener 'turbolinks:before-cache', @abort $(document).on 'click', '.js-forum-topic-title--edit-start', @editShow $(document).on 'click', '.js-forum-topic-title--save', @save $(document).on 'keyup', '.js-forum-topic-title--input', @onKeyup $(document).on 'click', '.js-forum-topic-title--cancel', @cancel $(document).on 'input', '.js-forum-topic-title--input', @onInput abort: => @xhr?.abort() cancel: => @abort() $(@toggleables).removeAttr('data-title-edit') @input[0].value = @input[0].defaultValue editShow: => $(@toggleables).attr('data-title-edit', 1) @input[0].selectionStart = @input[0].value.length @input[0].focus() onInput: => @saveButton[0].disabled = !osu.present(@input[0].value) onKeyup: (e) => switch e.keyCode # enter when 13 then @save() # escape when 27 then @cancel() save: => input = @input[0] newTitle = input.value return if !osu.presence(newTitle)? return @cancel() if newTitle == input.defaultValue input.disabled = true @saveButton[0].disabled = true @abort() @xhr = $.ajax input.dataset.url, method: 'PUT' data: "#{input.name}": newTitle .done => # because page title is also changed =D osu.reloadPage() .fail (xhr) => input.disabled = false @saveButton[0].disabled = false osu.emitAjaxError() xhr
[ { "context": "# **Author:** Peter Urbak<br/>\n# **Version:** 2013-01-29\n\n# ### Initializat", "end": 25, "score": 0.9998358488082886, "start": 14, "tag": "NAME", "value": "Peter Urbak" } ]
client_src/initialize.coffee
dragonwasrobot/gesture-recognition
2
# **Author:** Peter Urbak<br/> # **Version:** 2013-01-29 # ### Initialization # # Initializes the gesture recognition project. root = exports ? window $(document).ready () -> root.surface = $('#surface') # Wait a bit and load stuff setTimeout () => stylesheet = { objectSelectedColor : { red : 100, green : 45, blue : 214 }, objectFoldedColor : { red : 214, green : 135, blue : 45 }, objectUnfoldedColor : { red : 45, green : 214, blue : 24 } } # The `table` is our main data model while the `tuioInterpreter` is in # charge of inferring gestures from low-level sensor data and update the # data model according to object and cursor movement. Lastly, the # `gestureInterpreter` dispatches on gesture updates received from the # `tuioInterpreter` and manipulates the state of objects found in the data # model. tableModel = new App.TableModel(root.surface, stylesheet) tableApplication = new App.TableApplication(tableModel) tuioSubject = new App.TUIOSubject() singleTapObserver = new App.SingleTapObserver(tableApplication) doubleTapObserver = new App.DoubleTapObserver(tableApplication) flickObserver = new App.FlickObserver(tableApplication) holdFlickObserver = new App.HoldFlickObserver(tableApplication) objectShakeObserver = new App.ObjectShakeObserver(tableApplication) # Registration of Observers. tuioSubject.registerObserver(singleTapObserver) singleTapObserver.registerObserver(doubleTapObserver) tuioSubject.registerObserver(flickObserver) tuioSubject.registerObserver(holdFlickObserver) flickObserver.registerObserver(holdFlickObserver) tuioSubject.registerObserver(objectShakeObserver) tuioSubject.registerObserver(tableApplication) 2000
216243
# **Author:** <NAME><br/> # **Version:** 2013-01-29 # ### Initialization # # Initializes the gesture recognition project. root = exports ? window $(document).ready () -> root.surface = $('#surface') # Wait a bit and load stuff setTimeout () => stylesheet = { objectSelectedColor : { red : 100, green : 45, blue : 214 }, objectFoldedColor : { red : 214, green : 135, blue : 45 }, objectUnfoldedColor : { red : 45, green : 214, blue : 24 } } # The `table` is our main data model while the `tuioInterpreter` is in # charge of inferring gestures from low-level sensor data and update the # data model according to object and cursor movement. Lastly, the # `gestureInterpreter` dispatches on gesture updates received from the # `tuioInterpreter` and manipulates the state of objects found in the data # model. tableModel = new App.TableModel(root.surface, stylesheet) tableApplication = new App.TableApplication(tableModel) tuioSubject = new App.TUIOSubject() singleTapObserver = new App.SingleTapObserver(tableApplication) doubleTapObserver = new App.DoubleTapObserver(tableApplication) flickObserver = new App.FlickObserver(tableApplication) holdFlickObserver = new App.HoldFlickObserver(tableApplication) objectShakeObserver = new App.ObjectShakeObserver(tableApplication) # Registration of Observers. tuioSubject.registerObserver(singleTapObserver) singleTapObserver.registerObserver(doubleTapObserver) tuioSubject.registerObserver(flickObserver) tuioSubject.registerObserver(holdFlickObserver) flickObserver.registerObserver(holdFlickObserver) tuioSubject.registerObserver(objectShakeObserver) tuioSubject.registerObserver(tableApplication) 2000
true
# **Author:** PI:NAME:<NAME>END_PI<br/> # **Version:** 2013-01-29 # ### Initialization # # Initializes the gesture recognition project. root = exports ? window $(document).ready () -> root.surface = $('#surface') # Wait a bit and load stuff setTimeout () => stylesheet = { objectSelectedColor : { red : 100, green : 45, blue : 214 }, objectFoldedColor : { red : 214, green : 135, blue : 45 }, objectUnfoldedColor : { red : 45, green : 214, blue : 24 } } # The `table` is our main data model while the `tuioInterpreter` is in # charge of inferring gestures from low-level sensor data and update the # data model according to object and cursor movement. Lastly, the # `gestureInterpreter` dispatches on gesture updates received from the # `tuioInterpreter` and manipulates the state of objects found in the data # model. tableModel = new App.TableModel(root.surface, stylesheet) tableApplication = new App.TableApplication(tableModel) tuioSubject = new App.TUIOSubject() singleTapObserver = new App.SingleTapObserver(tableApplication) doubleTapObserver = new App.DoubleTapObserver(tableApplication) flickObserver = new App.FlickObserver(tableApplication) holdFlickObserver = new App.HoldFlickObserver(tableApplication) objectShakeObserver = new App.ObjectShakeObserver(tableApplication) # Registration of Observers. tuioSubject.registerObserver(singleTapObserver) singleTapObserver.registerObserver(doubleTapObserver) tuioSubject.registerObserver(flickObserver) tuioSubject.registerObserver(holdFlickObserver) flickObserver.registerObserver(holdFlickObserver) tuioSubject.registerObserver(objectShakeObserver) tuioSubject.registerObserver(tableApplication) 2000
[ { "context": "###\nThe MIT License\n\nCopyright (c) 2013-2014 Wilfred Springer, http://nxt.flotsam.nl/\n\nPermission is hereby gra", "end": 61, "score": 0.999862790107727, "start": 45, "tag": "NAME", "value": "Wilfred Springer" } ]
EHealthPouchDb/angular-pouchdb.coffee
inuwas/eHealthAfrica
43
### The MIT License Copyright (c) 2013-2014 Wilfred Springer, http://nxt.flotsam.nl/ 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. ### pouchdb = angular.module 'pouchdb', ['ng'] # Quick access to array functions slice = Array.prototype.slice concat = Array.prototype.concat # Copy of sortedIndex; returns position where we need to insert an element in order to preserver the sort order. sortedIndex = (array, value, callback) -> low = 0 high = if array? then array.length else low callback = callback or identity value = callback(value) while (low < high) mid = (low + high) >>> 1 if callback(array[mid]) < value low = mid + 1 else high = mid return low indexOf = (array, cond) -> pos = 0 while pos < array.length and !cond(array[pos]) pos = pos + 1 if pos < array.length then pos else -1 exists = (array, cond) -> indexOf(array, cond) >= 0 pouchdb.provider 'pouchdb', -> withAllDbsEnabled: -> PouchDB.enableAllDbs = true $get: ['$q', '$rootScope', '$timeout', ($q, $rootScope, $timeout) -> qify = (fn) -> () -> deferred = $q.defer() callback = (err, res) -> $timeout () -> if (err) deferred.reject err else deferred.resolve res args = if arguments? then slice.call(arguments) else [] args.push callback fn.apply this, args deferred.promise create: (name, options) -> db = new PouchDB(name, options) id: db.id put: qify db.put.bind(db) post: qify db.post.bind(db) get: qify db.get.bind(db) remove: qify db.remove.bind(db) bulkDocs: qify db.bulkDocs.bind(db) allDocs: qify db.allDocs.bind(db) changes: (options) -> clone = angular.copy options clone.onChange = (change) -> $rootScope.$apply () -> options.onChange change db.changes clone putAttachment: qify db.putAttachment.bind(db) getAttachment: qify db.getAttachment.bind(db) removeAttachment: qify db.removeAttachment.bind(db) query: qify db.query.bind(db) info: qify db.info.bind(db) compact: qify db.compact.bind(db) revsDiff: qify db.revsDiff.bind(db) replicate: to: db.replicate.to.bind(db) from: db.replicate.from.bind(db) sync: db.replicate.sync.bind(db) destroy: qify db.destroy.bind(db) ] # pouch-repeat="name in collection" pouchdb.directive 'pouchRepeat', ['$parse', '$animate', ($parse, $animate) -> transclude: 'element' priority: 10 compile: (elem, attrs, transclude) -> ($scope, $element, $attr) -> parent = $element.parent() top = angular.element(document.createElement('div')) parent.append(top) [cursor, collection, sort] = /^\s*([a-zA-Z0-9]+)\s*in\s*([a-zA-Z0-9]+)\s*(?:order by\s*([a-zA-Z0-9\.,]+))?$/.exec($attr.pouchRepeat).splice(1) # The blocks managed by this directive. blocks = [] vectorOf = if sort? getters = $parse(fld) for fld in sort.split(',') (doc) -> for getter in getters getter(doc) else null add = (doc) -> childScope = $scope.$new(); childScope[cursor] = doc transclude childScope, (clone) -> block = doc : doc clone : clone scope : childScope vector : if vectorOf? then vectorOf(doc) else null last = blocks[blocks.length - 1] if vectorOf? index = sortedIndex(blocks, block, (block) -> block.vector) preceding = if (index > 0) blocks[index - 1] else null $animate.enter(clone, parent, if preceding? then preceding.clone else top) blocks.splice(index, 0, block) else blocks.push(block) if last? $animate.enter(clone, parent, last.clone) else $animate.enter(clone, parent, top) modify = (doc) -> idx = indexOf(blocks, (block) -> block.doc._id == doc._id) block = blocks[idx] block.scope[cursor] = doc if vectorOf? block.vector = vectorOf(doc) blocks.splice(idx, 1) newidx = sortedIndex(blocks, block, (block) -> block.vector) blocks.splice(newidx, 0, block) $animate.move( block.clone, parent, if newidx > 0 then blocks[newidx - 1].clone else top ) remove = (id) -> idx = indexOf(blocks, (block) -> block.doc._id == id) block = blocks[idx] if block? $animate.leave block.clone, -> block.scope.$destroy() $scope.$watch collection , () -> # Not using query, since the map function doesn't accept emit as an argument just yet. process = (result) -> for row in result.rows add(row.doc) $scope[collection].allDocs({include_docs: true}).then(process) $scope[collection].info().then (info) -> $scope[collection].changes include_docs: true continuous: true since: info.update_seq onChange: (update) -> if update.deleted then remove(update.doc._id) else if exists(blocks, (block) -> block.doc._id == update.doc._id) modify(update.doc) else add(update.doc) return ]
118375
### The MIT License Copyright (c) 2013-2014 <NAME>, http://nxt.flotsam.nl/ 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. ### pouchdb = angular.module 'pouchdb', ['ng'] # Quick access to array functions slice = Array.prototype.slice concat = Array.prototype.concat # Copy of sortedIndex; returns position where we need to insert an element in order to preserver the sort order. sortedIndex = (array, value, callback) -> low = 0 high = if array? then array.length else low callback = callback or identity value = callback(value) while (low < high) mid = (low + high) >>> 1 if callback(array[mid]) < value low = mid + 1 else high = mid return low indexOf = (array, cond) -> pos = 0 while pos < array.length and !cond(array[pos]) pos = pos + 1 if pos < array.length then pos else -1 exists = (array, cond) -> indexOf(array, cond) >= 0 pouchdb.provider 'pouchdb', -> withAllDbsEnabled: -> PouchDB.enableAllDbs = true $get: ['$q', '$rootScope', '$timeout', ($q, $rootScope, $timeout) -> qify = (fn) -> () -> deferred = $q.defer() callback = (err, res) -> $timeout () -> if (err) deferred.reject err else deferred.resolve res args = if arguments? then slice.call(arguments) else [] args.push callback fn.apply this, args deferred.promise create: (name, options) -> db = new PouchDB(name, options) id: db.id put: qify db.put.bind(db) post: qify db.post.bind(db) get: qify db.get.bind(db) remove: qify db.remove.bind(db) bulkDocs: qify db.bulkDocs.bind(db) allDocs: qify db.allDocs.bind(db) changes: (options) -> clone = angular.copy options clone.onChange = (change) -> $rootScope.$apply () -> options.onChange change db.changes clone putAttachment: qify db.putAttachment.bind(db) getAttachment: qify db.getAttachment.bind(db) removeAttachment: qify db.removeAttachment.bind(db) query: qify db.query.bind(db) info: qify db.info.bind(db) compact: qify db.compact.bind(db) revsDiff: qify db.revsDiff.bind(db) replicate: to: db.replicate.to.bind(db) from: db.replicate.from.bind(db) sync: db.replicate.sync.bind(db) destroy: qify db.destroy.bind(db) ] # pouch-repeat="name in collection" pouchdb.directive 'pouchRepeat', ['$parse', '$animate', ($parse, $animate) -> transclude: 'element' priority: 10 compile: (elem, attrs, transclude) -> ($scope, $element, $attr) -> parent = $element.parent() top = angular.element(document.createElement('div')) parent.append(top) [cursor, collection, sort] = /^\s*([a-zA-Z0-9]+)\s*in\s*([a-zA-Z0-9]+)\s*(?:order by\s*([a-zA-Z0-9\.,]+))?$/.exec($attr.pouchRepeat).splice(1) # The blocks managed by this directive. blocks = [] vectorOf = if sort? getters = $parse(fld) for fld in sort.split(',') (doc) -> for getter in getters getter(doc) else null add = (doc) -> childScope = $scope.$new(); childScope[cursor] = doc transclude childScope, (clone) -> block = doc : doc clone : clone scope : childScope vector : if vectorOf? then vectorOf(doc) else null last = blocks[blocks.length - 1] if vectorOf? index = sortedIndex(blocks, block, (block) -> block.vector) preceding = if (index > 0) blocks[index - 1] else null $animate.enter(clone, parent, if preceding? then preceding.clone else top) blocks.splice(index, 0, block) else blocks.push(block) if last? $animate.enter(clone, parent, last.clone) else $animate.enter(clone, parent, top) modify = (doc) -> idx = indexOf(blocks, (block) -> block.doc._id == doc._id) block = blocks[idx] block.scope[cursor] = doc if vectorOf? block.vector = vectorOf(doc) blocks.splice(idx, 1) newidx = sortedIndex(blocks, block, (block) -> block.vector) blocks.splice(newidx, 0, block) $animate.move( block.clone, parent, if newidx > 0 then blocks[newidx - 1].clone else top ) remove = (id) -> idx = indexOf(blocks, (block) -> block.doc._id == id) block = blocks[idx] if block? $animate.leave block.clone, -> block.scope.$destroy() $scope.$watch collection , () -> # Not using query, since the map function doesn't accept emit as an argument just yet. process = (result) -> for row in result.rows add(row.doc) $scope[collection].allDocs({include_docs: true}).then(process) $scope[collection].info().then (info) -> $scope[collection].changes include_docs: true continuous: true since: info.update_seq onChange: (update) -> if update.deleted then remove(update.doc._id) else if exists(blocks, (block) -> block.doc._id == update.doc._id) modify(update.doc) else add(update.doc) return ]
true
### The MIT License Copyright (c) 2013-2014 PI:NAME:<NAME>END_PI, http://nxt.flotsam.nl/ 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. ### pouchdb = angular.module 'pouchdb', ['ng'] # Quick access to array functions slice = Array.prototype.slice concat = Array.prototype.concat # Copy of sortedIndex; returns position where we need to insert an element in order to preserver the sort order. sortedIndex = (array, value, callback) -> low = 0 high = if array? then array.length else low callback = callback or identity value = callback(value) while (low < high) mid = (low + high) >>> 1 if callback(array[mid]) < value low = mid + 1 else high = mid return low indexOf = (array, cond) -> pos = 0 while pos < array.length and !cond(array[pos]) pos = pos + 1 if pos < array.length then pos else -1 exists = (array, cond) -> indexOf(array, cond) >= 0 pouchdb.provider 'pouchdb', -> withAllDbsEnabled: -> PouchDB.enableAllDbs = true $get: ['$q', '$rootScope', '$timeout', ($q, $rootScope, $timeout) -> qify = (fn) -> () -> deferred = $q.defer() callback = (err, res) -> $timeout () -> if (err) deferred.reject err else deferred.resolve res args = if arguments? then slice.call(arguments) else [] args.push callback fn.apply this, args deferred.promise create: (name, options) -> db = new PouchDB(name, options) id: db.id put: qify db.put.bind(db) post: qify db.post.bind(db) get: qify db.get.bind(db) remove: qify db.remove.bind(db) bulkDocs: qify db.bulkDocs.bind(db) allDocs: qify db.allDocs.bind(db) changes: (options) -> clone = angular.copy options clone.onChange = (change) -> $rootScope.$apply () -> options.onChange change db.changes clone putAttachment: qify db.putAttachment.bind(db) getAttachment: qify db.getAttachment.bind(db) removeAttachment: qify db.removeAttachment.bind(db) query: qify db.query.bind(db) info: qify db.info.bind(db) compact: qify db.compact.bind(db) revsDiff: qify db.revsDiff.bind(db) replicate: to: db.replicate.to.bind(db) from: db.replicate.from.bind(db) sync: db.replicate.sync.bind(db) destroy: qify db.destroy.bind(db) ] # pouch-repeat="name in collection" pouchdb.directive 'pouchRepeat', ['$parse', '$animate', ($parse, $animate) -> transclude: 'element' priority: 10 compile: (elem, attrs, transclude) -> ($scope, $element, $attr) -> parent = $element.parent() top = angular.element(document.createElement('div')) parent.append(top) [cursor, collection, sort] = /^\s*([a-zA-Z0-9]+)\s*in\s*([a-zA-Z0-9]+)\s*(?:order by\s*([a-zA-Z0-9\.,]+))?$/.exec($attr.pouchRepeat).splice(1) # The blocks managed by this directive. blocks = [] vectorOf = if sort? getters = $parse(fld) for fld in sort.split(',') (doc) -> for getter in getters getter(doc) else null add = (doc) -> childScope = $scope.$new(); childScope[cursor] = doc transclude childScope, (clone) -> block = doc : doc clone : clone scope : childScope vector : if vectorOf? then vectorOf(doc) else null last = blocks[blocks.length - 1] if vectorOf? index = sortedIndex(blocks, block, (block) -> block.vector) preceding = if (index > 0) blocks[index - 1] else null $animate.enter(clone, parent, if preceding? then preceding.clone else top) blocks.splice(index, 0, block) else blocks.push(block) if last? $animate.enter(clone, parent, last.clone) else $animate.enter(clone, parent, top) modify = (doc) -> idx = indexOf(blocks, (block) -> block.doc._id == doc._id) block = blocks[idx] block.scope[cursor] = doc if vectorOf? block.vector = vectorOf(doc) blocks.splice(idx, 1) newidx = sortedIndex(blocks, block, (block) -> block.vector) blocks.splice(newidx, 0, block) $animate.move( block.clone, parent, if newidx > 0 then blocks[newidx - 1].clone else top ) remove = (id) -> idx = indexOf(blocks, (block) -> block.doc._id == id) block = blocks[idx] if block? $animate.leave block.clone, -> block.scope.$destroy() $scope.$watch collection , () -> # Not using query, since the map function doesn't accept emit as an argument just yet. process = (result) -> for row in result.rows add(row.doc) $scope[collection].allDocs({include_docs: true}).then(process) $scope[collection].info().then (info) -> $scope[collection].changes include_docs: true continuous: true since: info.update_seq onChange: (update) -> if update.deleted then remove(update.doc._id) else if exists(blocks, (block) -> block.doc._id == update.doc._id) modify(update.doc) else add(update.doc) return ]
[ { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 2297, "score": 0.9958194494247437, "start": 2289, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"LeftOpen\",\n \"context\" : \"Patient\",\n ", "end": 2974, "score": 0.9684891700744629, "start": 2970, "tag": "NAME", "value": "Left" }, { "context": " }\n }, {\n \"name\" : \"LeftOpen\",\n \"context\" : \"Patient\",\n ", "end": 2978, "score": 0.6046951413154602, "start": 2974, "tag": "USERNAME", "value": "Open" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 3214, "score": 0.998495876789093, "start": 3206, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 3900, "score": 0.9971019625663757, "start": 3892, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"RightOpen\",\n \"context\" : \"Patient\",\n ", "end": 4578, "score": 0.5267826914787292, "start": 4573, "tag": "NAME", "value": "Right" }, { "context": " }\n }, {\n \"name\" : \"RightOpen\",\n \"context\" : \"Patient\",\n ", "end": 4582, "score": 0.9857369661331177, "start": 4578, "tag": "USERNAME", "value": "Open" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 4818, "score": 0.9983416199684143, "start": 4810, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 5504, "score": 0.9977973699569702, "start": 5496, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"Closed\",\n \"context\" : \"Patient\",\n ", "end": 6183, "score": 0.9846011996269226, "start": 6177, "tag": "NAME", "value": "Closed" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 6418, "score": 0.9881976246833801, "start": 6410, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 7104, "score": 0.9850085377693176, "start": 7096, "tag": "NAME", "value": "DateTime" }, { "context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n \"schema", "end": 8895, "score": 0.9857177734375, "start": 8884, "tag": "USERNAME", "value": "TestSnippet" }, { "context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ", "end": 9249, "score": 0.9989791512489319, "start": 9242, "tag": "NAME", "value": "Patient" }, { "context": " }\n }, {\n \"name\" : \"EqualClosed\",\n \"context\" : \"Patient\",\n ", "end": 9607, "score": 0.6276030540466309, "start": 9602, "tag": "NAME", "value": "Equal" }, { "context": " }\n }, {\n \"name\" : \"EqualOpen\",\n \"context\" : \"Patient\",\n ", "end": 10874, "score": 0.6786807775497437, "start": 10869, "tag": "NAME", "value": "Equal" }, { "context": " }\n }, {\n \"name\" : \"UnequalOpen\",\n \"context\" : \"Patient\",\n ", "end": 14691, "score": 0.9786367416381836, "start": 14680, "tag": "USERNAME", "value": "UnequalOpen" }, { "context": "\n }, {\n \"name\" : \"UnequalClosedOpen\",\n \"context\" : \"Patient\",\n ", "end": 15968, "score": 0.5632078647613525, "start": 15964, "tag": "USERNAME", "value": "Open" }, { "context": " }\n }, {\n \"name\" : \"EqualDates\",\n \"context\" : \"Patient\",\n ", "end": 17231, "score": 0.6731988787651062, "start": 17226, "tag": "NAME", "value": "Equal" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 17551, "score": 0.9082058072090149, "start": 17543, "tag": "NAME", "value": "DateTime" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 20656, "score": 0.9777475595474243, "start": 20648, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 22141, "score": 0.9879133105278015, "start": 22133, "tag": "NAME", "value": "DateTime" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 23961, "score": 0.9406031370162964, "start": 23953, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"SameDays\",\n \"context\" : \"Patient\",\n ", "end": 30046, "score": 0.4974031150341034, "start": 30042, "tag": "NAME", "value": "Same" }, { "context": " }\n }, {\n \"name\" : \"SameDays\",\n \"context\" : \"Patient\",\n ", "end": 30050, "score": 0.9884089231491089, "start": 30046, "tag": "USERNAME", "value": "Days" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 30365, "score": 0.9988892674446106, "start": 30357, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 31102, "score": 0.9988769888877869, "start": 31094, "tag": "NAME", "value": "DateTime" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 31974, "score": 0.9949899315834045, "start": 31966, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 32711, "score": 0.9976639747619629, "start": 32703, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"DifferentDays\",\n \"context\" : \"Patient\",\n ", "end": 33457, "score": 0.9641017913818359, "start": 33448, "tag": "NAME", "value": "Different" }, { "context": " }\n }, {\n \"name\" : \"DifferentDays\",\n \"context\" : \"Patient\",\n ", "end": 33461, "score": 0.776567280292511, "start": 33457, "tag": "USERNAME", "value": "Days" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 33776, "score": 0.997573733329773, "start": 33768, "tag": "NAME", "value": "DateTime" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 35385, "score": 0.5378561019897461, "start": 35377, "tag": "NAME", "value": "DateTime" }, { "context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n \"schema", "end": 37993, "score": 0.6850249767303467, "start": 37982, "tag": "USERNAME", "value": "TestSnippet" }, { "context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ", "end": 38347, "score": 0.9910284876823425, "start": 38340, "tag": "NAME", "value": "Patient" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 46670, "score": 0.989947497844696, "start": 46662, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 48155, "score": 0.9935968518257141, "start": 48147, "tag": "NAME", "value": "DateTime" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 49775, "score": 0.9700613021850586, "start": 49767, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 51260, "score": 0.6706361174583435, "start": 51252, "tag": "NAME", "value": "DateTime" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 56187, "score": 0.8726421594619751, "start": 56179, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 57672, "score": 0.8297288417816162, "start": 57664, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"SameDays\",\n \"context\" : \"Patient\",\n ", "end": 59172, "score": 0.7516036033630371, "start": 59164, "tag": "USERNAME", "value": "SameDays" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 59490, "score": 0.9889933466911316, "start": 59482, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 60227, "score": 0.92696613073349, "start": 60219, "tag": "NAME", "value": "DateTime" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 61099, "score": 0.9860588908195496, "start": 61091, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 61836, "score": 0.9826271533966064, "start": 61828, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"DifferentDays\",\n \"context\" : \"Patient\",\n ", "end": 62586, "score": 0.9839181303977966, "start": 62573, "tag": "USERNAME", "value": "DifferentDays" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 62904, "score": 0.820758044719696, "start": 62896, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 63641, "score": 0.7045055627822876, "start": 63633, "tag": "NAME", "value": "DateTime" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 64513, "score": 0.7109992504119873, "start": 64505, "tag": "NAME", "value": "DateTime" }, { "context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n \"schema", "end": 67462, "score": 0.7478668689727783, "start": 67451, "tag": "USERNAME", "value": "TestSnippet" }, { "context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ", "end": 67816, "score": 0.9994663596153259, "start": 67809, "tag": "NAME", "value": "Patient" }, { "context": " }\n }, {\n \"name\" : \"ivlA\",\n \"context\" : \"Patient\",\n ", "end": 68173, "score": 0.9968522191047668, "start": 68169, "tag": "NAME", "value": "ivlA" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 68409, "score": 0.9995742440223694, "start": 68401, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 69795, "score": 0.9956728219985962, "start": 69787, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlB\",\n \"context\" : \"Patient\",\n ", "end": 71170, "score": 0.833918571472168, "start": 71168, "tag": "NAME", "value": "iv" }, { "context": " }\n }, {\n \"name\" : \"ivlB\",\n \"context\" : \"Patient\",\n ", "end": 71172, "score": 0.7802950143814087, "start": 71170, "tag": "USERNAME", "value": "lB" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 71408, "score": 0.9959307312965393, "start": 71400, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 72794, "score": 0.9631490111351013, "start": 72786, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlC\",\n \"context\" : \"Patient\",\n ", "end": 74171, "score": 0.9958841800689697, "start": 74167, "tag": "USERNAME", "value": "ivlC" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 74407, "score": 0.9180616140365601, "start": 74399, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 75793, "score": 0.5688007473945618, "start": 75785, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlD\",\n \"context\" : \"Patient\",\n ", "end": 77170, "score": 0.9787940382957458, "start": 77166, "tag": "NAME", "value": "ivlD" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 77406, "score": 0.9971885681152344, "start": 77398, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 78792, "score": 0.6056013107299805, "start": 78784, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlE\",\n \"context\" : \"Patient\",\n ", "end": 80169, "score": 0.633162796497345, "start": 80165, "tag": "NAME", "value": "ivlE" }, { "context": " }\n }, {\n \"name\" : \"ivlF\",\n \"context\" : \"Patient\",\n ", "end": 81067, "score": 0.619016706943512, "start": 81063, "tag": "USERNAME", "value": "ivlF" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 81302, "score": 0.9159398674964905, "start": 81294, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 81638, "score": 0.7108264565467834, "start": 81630, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlG\",\n \"context\" : \"Patient\",\n ", "end": 81965, "score": 0.7002758979797363, "start": 81961, "tag": "USERNAME", "value": "ivlG" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 82200, "score": 0.9250156283378601, "start": 82192, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"OverlapsContains\",\n \"context\" : \"Patient\",\n ", "end": 84047, "score": 0.506685733795166, "start": 84040, "tag": "NAME", "value": "Overlap" }, { "context": " }\n }, {\n \"name\" : \"ImpreciseOverlap\",\n \"context\" : \"Patient\",", "end": 84438, "score": 0.5905823707580566, "start": 84435, "tag": "NAME", "value": "Imp" }, { "context": " }\n }, {\n \"name\" : \"NoOverlap\",\n \"context\" : \"Patient\",\n ", "end": 84832, "score": 0.641412079334259, "start": 84830, "tag": "NAME", "value": "No" }, { "context": " }\n }, {\n \"name\" : \"NoImpreciseOverlap\",\n \"context\" : \"Patien", "end": 85220, "score": 0.55158531665802, "start": 85218, "tag": "NAME", "value": "No" }, { "context": " }\n }, {\n \"name\" : \"UnknownOverlap\",\n \"context\" : \"Patient\",\n ", "end": 85622, "score": 0.7951969504356384, "start": 85615, "tag": "NAME", "value": "Unknown" }, { "context": " }\n }, {\n \"name\" : \"OverlapsDate\",\n \"context\" : \"Patient\",\n ", "end": 86020, "score": 0.8352367281913757, "start": 86008, "tag": "NAME", "value": "OverlapsDate" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 86288, "score": 0.9515138268470764, "start": 86280, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"StartOverlapsDate\",\n \"context\" : \"Patient\",\n", "end": 87668, "score": 0.9613704681396484, "start": 87663, "tag": "NAME", "value": "Start" }, { "context": "}\n }, {\n \"name\" : \"StartOverlapsDate\",\n \"context\" : \"Patient\",\n ", "end": 87680, "score": 0.5887529850006104, "start": 87675, "tag": "NAME", "value": "sDate" }, { "context": " \"operand\" : [ {\n \"name\" : \"ivlC\",\n \"type\" : \"ExpressionRef\"\n ", "end": 87846, "score": 0.9676167368888855, "start": 87842, "tag": "NAME", "value": "ivlC" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 87948, "score": 0.9875807762145996, "start": 87940, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"EndOverlapsDate\",\n \"context\" : \"Patient\",\n", "end": 89326, "score": 0.6896701455116272, "start": 89323, "tag": "NAME", "value": "End" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 89606, "score": 0.7355265617370605, "start": 89598, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"NoOverlapsDate\",\n \"context\" : \"Patient\",\n", "end": 90990, "score": 0.5979999303817749, "start": 90988, "tag": "NAME", "value": "No" }, { "context": " \"operand\" : [ {\n \"name\" : \"ivlC\",\n \"type\" : \"ExpressionRef\"\n ", "end": 91166, "score": 0.5134158730506897, "start": 91164, "tag": "NAME", "value": "iv" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 91270, "score": 0.9731070399284363, "start": 91262, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"UnknownOverlapsDate\",\n \"context\" : \"Patient\",\n", "end": 92652, "score": 0.8893933892250061, "start": 92645, "tag": "NAME", "value": "Unknown" }, { "context": " }\n }, {\n \"name\" : \"UnknownOverlapsDate\",\n \"context\" : \"Patient\",\n ", "end": 92664, "score": 0.6999126076698303, "start": 92652, "tag": "USERNAME", "value": "OverlapsDate" }, { "context": " \"operand\" : [ {\n \"name\" : \"ivlE\",\n \"type\" : \"ExpressionRef\"\n ", "end": 92828, "score": 0.7402031421661377, "start": 92826, "tag": "NAME", "value": "iv" }, { "context": " \"operand\" : [ {\n \"name\" : \"ivlE\",\n \"type\" : \"ExpressionRef\"\n ", "end": 92830, "score": 0.6123351454734802, "start": 92828, "tag": "USERNAME", "value": "lE" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 92932, "score": 0.9765819311141968, "start": 92924, "tag": "NAME", "value": "DateTime" }, { "context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n \"schema", "end": 96550, "score": 0.8435167074203491, "start": 96539, "tag": "USERNAME", "value": "TestSnippet" }, { "context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ", "end": 96904, "score": 0.9996880292892456, "start": 96897, "tag": "NAME", "value": "Patient" }, { "context": " }\n }, {\n \"name\" : \"ivlA\",\n \"context\" : \"Patient\",\n ", "end": 97261, "score": 0.9896858334541321, "start": 97257, "tag": "NAME", "value": "ivlA" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 97497, "score": 0.9997239708900452, "start": 97489, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 98883, "score": 0.9541557431221008, "start": 98875, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlB\",\n \"context\" : \"Patient\",\n ", "end": 100260, "score": 0.8525106310844421, "start": 100256, "tag": "NAME", "value": "ivlB" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 100496, "score": 0.9723911285400391, "start": 100488, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 101882, "score": 0.9769682884216309, "start": 101874, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlC\",\n \"context\" : \"Patient\",\n ", "end": 103259, "score": 0.8816431164741516, "start": 103255, "tag": "NAME", "value": "ivlC" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 103495, "score": 0.9971829652786255, "start": 103487, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 104881, "score": 0.9669421315193176, "start": 104873, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlD\",\n \"context\" : \"Patient\",\n ", "end": 106256, "score": 0.5946190357208252, "start": 106254, "tag": "NAME", "value": "iv" }, { "context": " }\n }, {\n \"name\" : \"ivlD\",\n \"context\" : \"Patient\",\n ", "end": 106258, "score": 0.8836487531661987, "start": 106256, "tag": "USERNAME", "value": "lD" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 106494, "score": 0.9874905943870544, "start": 106486, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 107880, "score": 0.9668837189674377, "start": 107872, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlE\",\n \"context\" : \"Patient\",\n ", "end": 109257, "score": 0.9063534140586853, "start": 109253, "tag": "NAME", "value": "ivlE" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 109492, "score": 0.9656770825386047, "start": 109484, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 109828, "score": 0.9602546095848083, "start": 109820, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlF\",\n \"context\" : \"Patient\",\n ", "end": 110155, "score": 0.9408879280090332, "start": 110151, "tag": "NAME", "value": "ivlF" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 110390, "score": 0.9773623943328857, "start": 110382, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 110726, "score": 0.9483795762062073, "start": 110718, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlG\",\n \"context\" : \"Patient\",\n ", "end": 111053, "score": 0.8478792309761047, "start": 111049, "tag": "NAME", "value": "ivlG" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 111288, "score": 0.9858254790306091, "start": 111280, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 111624, "score": 0.9795727133750916, "start": 111616, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"OverlapsBefore\",\n \"context\" : \"Patient\",\n ", "end": 111961, "score": 0.9835693836212158, "start": 111947, "tag": "NAME", "value": "OverlapsBefore" }, { "context": " }\n }, {\n \"name\" : \"OverlapsAfter\",\n \"context\" : \"Patient\",\n ", "end": 112358, "score": 0.9858339428901672, "start": 112345, "tag": "NAME", "value": "OverlapsAfter" }, { "context": " }\n }, {\n \"name\" : \"OverlapsContained\",\n \"context\" : \"Patient\",\n ", "end": 112759, "score": 0.9493828415870667, "start": 112742, "tag": "NAME", "value": "OverlapsContained" }, { "context": " }\n }, {\n \"name\" : \"OverlapsContains\",\n \"context\" : \"Patient\",\n ", "end": 113159, "score": 0.8781530261039734, "start": 113143, "tag": "NAME", "value": "OverlapsContains" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 117497, "score": 0.5987746715545654, "start": 117489, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"EndOverlapsDate\",\n \"context\" : \"Patient\",\n", "end": 118875, "score": 0.8485152721405029, "start": 118872, "tag": "NAME", "value": "End" }, { "context": " }\n }, {\n \"name\" : \"EndOverlapsDate\",\n \"context\" : \"Patient\",\n ", "end": 118887, "score": 0.5949537754058838, "start": 118882, "tag": "NAME", "value": "sDate" }, { "context": " \"operand\" : [ {\n \"name\" : \"ivlC\",\n \"type\" : \"ExpressionRef\"\n ", "end": 119058, "score": 0.9098321795463562, "start": 119054, "tag": "NAME", "value": "ivlC" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 119160, "score": 0.970686674118042, "start": 119152, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"NoOverlapsDate\",\n \"context\" : \"Patient\",\n", "end": 120544, "score": 0.616200864315033, "start": 120542, "tag": "NAME", "value": "No" }, { "context": " }\n }, {\n \"name\" : \"NoOverlapsDate\",\n \"context\" : \"Patient\",\n ", "end": 120556, "score": 0.5260470509529114, "start": 120544, "tag": "USERNAME", "value": "OverlapsDate" }, { "context": " \"operand\" : [ {\n \"name\" : \"ivlC\",\n \"type\" : \"ExpressionRef\"\n ", "end": 120727, "score": 0.6939613223075867, "start": 120723, "tag": "NAME", "value": "ivlC" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 120829, "score": 0.8893743753433228, "start": 120821, "tag": "NAME", "value": "DateTime" }, { "context": " \"operand\" : [ {\n \"name\" : \"ivlE\",\n \"type\" : \"ExpressionRef\"\n ", "end": 122393, "score": 0.5373089909553528, "start": 122392, "tag": "NAME", "value": "l" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 122496, "score": 0.6962105631828308, "start": 122488, "tag": "NAME", "value": "DateTime" }, { "context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n ", "end": 126129, "score": 0.9479047060012817, "start": 126125, "tag": "NAME", "value": "Test" }, { "context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ", "end": 126490, "score": 0.6140744090080261, "start": 126483, "tag": "NAME", "value": "Patient" }, { "context": " }\n }, {\n \"name\" : \"ivlB\",\n \"context\" : \"Patient\",\n ", "end": 129846, "score": 0.7618514895439148, "start": 129842, "tag": "NAME", "value": "ivlB" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 130082, "score": 0.97392737865448, "start": 130074, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 131468, "score": 0.9954221844673157, "start": 131460, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlC\",\n \"context\" : \"Patient\",\n ", "end": 132843, "score": 0.8218271136283875, "start": 132841, "tag": "NAME", "value": "iv" }, { "context": " }\n }, {\n \"name\" : \"ivlC\",\n \"context\" : \"Patient\",\n ", "end": 132845, "score": 0.8762505054473877, "start": 132843, "tag": "USERNAME", "value": "lC" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 133081, "score": 0.9957707524299622, "start": 133073, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlD\",\n \"context\" : \"Patient\",\n ", "end": 135844, "score": 0.9564670920372009, "start": 135840, "tag": "USERNAME", "value": "ivlD" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 136080, "score": 0.9969509840011597, "start": 136072, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 137466, "score": 0.9947858452796936, "start": 137458, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlE\",\n \"context\" : \"Patient\",\n ", "end": 138843, "score": 0.8561303615570068, "start": 138839, "tag": "USERNAME", "value": "ivlE" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 139078, "score": 0.9368510842323303, "start": 139070, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 139414, "score": 0.8692547678947449, "start": 139406, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlF\",\n \"context\" : \"Patient\",\n ", "end": 139741, "score": 0.9954264760017395, "start": 139737, "tag": "NAME", "value": "ivlF" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 139976, "score": 0.7952733039855957, "start": 139968, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"ivlG\",\n \"context\" : \"Patient\",\n ", "end": 140639, "score": 0.9956275820732117, "start": 140635, "tag": "NAME", "value": "ivlG" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 140874, "score": 0.8242433667182922, "start": 140866, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 141210, "score": 0.7528035640716553, "start": 141202, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"OverlapsBefore\",\n \"context\" : \"Patient\",\n ", "end": 141547, "score": 0.9936912655830383, "start": 141533, "tag": "NAME", "value": "OverlapsBefore" }, { "context": "\"\n }, {\n \"name\" : \"ivlB\",\n \"type\" : \"ExpressionRef\"\n ", "end": 141815, "score": 0.7957990765571594, "start": 141813, "tag": "NAME", "value": "iv" }, { "context": " }\n }, {\n \"name\" : \"NoImpreciseOverlap\",\n \"context\" : \"Patien", "end": 144342, "score": 0.5742498636245728, "start": 144340, "tag": "NAME", "value": "No" }, { "context": " }\n }, {\n \"name\" : \"UnknownOverlap\",\n \"context\" : \"Patient\",\n ", "end": 144750, "score": 0.6525477170944214, "start": 144743, "tag": "NAME", "value": "Unknown" }, { "context": " }\n }, {\n \"name\" : \"OverlapsDate\",\n \"context\" : \"Patient\",\n ", "end": 145154, "score": 0.9124400615692139, "start": 145142, "tag": "NAME", "value": "OverlapsDate" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 145428, "score": 0.9485393762588501, "start": 145420, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"StartOverlapsDate\",\n \"context\" : \"Patient\",\n", "end": 146808, "score": 0.8506757616996765, "start": 146803, "tag": "NAME", "value": "Start" }, { "context": "}\n }, {\n \"name\" : \"StartOverlapsDate\",\n \"context\" : \"Patient\",\n ", "end": 146816, "score": 0.5290791988372803, "start": 146815, "tag": "NAME", "value": "s" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 147094, "score": 0.9670299887657166, "start": 147086, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"EndOverlapsDate\",\n \"context\" : \"Patient\",\n", "end": 148472, "score": 0.5763944983482361, "start": 148469, "tag": "NAME", "value": "End" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 148758, "score": 0.5838353037834167, "start": 148750, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"NoOverlapsDate\",\n \"context\" : \"Patient\",\n ", "end": 150154, "score": 0.9258007407188416, "start": 150142, "tag": "USERNAME", "value": "OverlapsDate" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 150428, "score": 0.6569197773933411, "start": 150420, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"UnknownOverlapsDate\",\n \"context\" : \"Patient\",\n", "end": 151810, "score": 0.5944491028785706, "start": 151803, "tag": "NAME", "value": "Unknown" }, { "context": " \"operand\" : [ {\n \"name\" : \"ivlE\",\n \"type\" : \"ExpressionRef\"\n ", "end": 151992, "score": 0.5385340452194214, "start": 151990, "tag": "NAME", "value": "iv" }, { "context": "\"\n }, {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 152096, "score": 0.882670521736145, "start": 152088, "tag": "NAME", "value": "DateTime" }, { "context": " }\n }, {\n \"name\" : \"Foo\",\n \"context\" : \"Patient\",\n ", "end": 155038, "score": 0.9994128942489624, "start": 155035, "tag": "NAME", "value": "Foo" }, { "context": " \"low\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 155350, "score": 0.9978367686271667, "start": 155342, "tag": "NAME", "value": "DateTime" }, { "context": " \"high\" : {\n \"name\" : \"DateTime\",\n \"type\" : \"FunctionRef\",\n ", "end": 156087, "score": 0.9960718154907227, "start": 156079, "tag": "NAME", "value": "DateTime" } ]
Src/coffeescript/cql-execution/test/elm/interval/data.coffee
esteban-aliverti/clinical_quality_language
0
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.coffee to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### Interval library TestSnippet version '1' using QUICK context Patient define Open = interval(DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define LeftOpen = interval(DateTime(2012, 1, 1), DateTime(2013, 1, 1)] define RightOpen = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define Closed = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)] ### module.exports['Interval'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "Open", "context" : "Patient", "expression" : { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "LeftOpen", "context" : "Patient", "expression" : { "lowClosed" : false, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "RightOpen", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "Closed", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } } ] } } } ### Equal library TestSnippet version '1' using QUICK context Patient define EqualClosed = interval[1, 5] = interval[1, 5] define EqualOpen = interval(1, 5) = interval(1, 5) define EqualOpenClosed = interval(1, 5) = interval[2, 4] define UnequalClosed = interval[1, 5] = interval[2, 4] define UnequalOpen = interval(1, 5) = interval(2, 4) define UnequalClosedOpen = interval[1, 5] = interval(2, 4) define EqualDates = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define EqualDatesOpenClosed = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 12, 31, 23, 59, 59, 999)] define SameDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define DifferentDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) = interval[DateTime(2012, 1, 1), DateTime(2012, 7, 1)) ### module.exports['Equal'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "EqualClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpen", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpenClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalOpen", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosedOpen", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "EqualDates", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } ] } }, { "name" : "EqualDatesOpenClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } } ] } }, { "name" : "SameDays", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } }, { "name" : "DifferentDays", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "7", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } } ] } } } ### NotEqual library TestSnippet version '1' using QUICK context Patient define EqualClosed = interval[1, 5] <> interval[1, 5] define EqualOpen = interval(1, 5) <> interval(1, 5) define EqualOpenClosed = interval(1, 5) <> interval[2, 4] define UnequalClosed = interval[1, 5] <> interval[2, 4] define UnequalOpen = interval(1, 5) <> interval(2, 4) define UnequalClosedOpen = interval[1, 5] <> interval(2, 4) define EqualDates = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) <> interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define EqualDatesOpenClosed = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) <> interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 12, 31, 23, 59, 59, 999)] define SameDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) <> interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define DifferentDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) <> interval[DateTime(2012, 1, 1), DateTime(2012, 7, 1)) ### module.exports['NotEqual'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "EqualClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpen", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpenClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalOpen", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosedOpen", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "EqualDates", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } ] } }, { "name" : "EqualDatesOpenClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } } ] } }, { "name" : "SameDays", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } }, { "name" : "DifferentDays", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "7", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } } ] } } } ### Overlaps library TestSnippet version '1' using QUICK context Patient define ivlA = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 6, 1, 0, 0, 0, 0)) define ivlB = interval[DateTime(2012, 3, 1, 0, 0, 0, 0), DateTime(2012, 9, 1, 0, 0, 0, 0)) define ivlC = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define ivlD = interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0)) define ivlE = interval[DateTime(2013), DateTime(2015)] define ivlF = interval[DateTime(2014), DateTime(2016)] define ivlG = interval[DateTime(2016), DateTime(2017)] define OverlapsBefore = ivlA overlaps ivlB define OverlapsAfter = ivlB overlaps ivlA define OverlapsContained = ivlB overlaps ivlC define OverlapsContains = ivlC overlaps ivlB define ImpreciseOverlap = ivlD overlaps ivlE define NoOverlap = ivlC overlaps ivlD define NoImpreciseOverlap = ivlE overlaps ivlG define UnknownOverlap = ivlF overlaps ivlG define OverlapsDate = ivlC overlaps DateTime(2012, 4, 1, 0, 0, 0, 0) define StartOverlapsDate = ivlC overlaps DateTime(2012, 1, 1, 0, 0, 0, 0) define EndOverlapsDate = ivlC overlaps DateTime(2012, 12, 31, 23, 59, 59, 999) define NoOverlapsDate = ivlC overlaps DateTime(2013, 4, 1, 0, 0, 0, 0) define UnknownOverlapsDate = ivlE overlaps DateTime(2013, 4, 1, 0, 0, 0, 0) define OverlapsUnknownDate = ivlB overlaps DateTime(2012) ### module.exports['Overlaps'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "ivlA", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "6", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlB", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "9", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlC", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlD", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlE", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2015", "type" : "Literal" } ] } } }, { "name" : "ivlF", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] } } }, { "name" : "ivlG", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2017", "type" : "Literal" } ] } } }, { "name" : "OverlapsBefore", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlA", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsAfter", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlA", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContained", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlC", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContains", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlD", "type" : "ExpressionRef" }, { "name" : "ivlE", "type" : "ExpressionRef" } ] } }, { "name" : "NoOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlD", "type" : "ExpressionRef" } ] } }, { "name" : "NoImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "UnknownOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "StartOverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "EndOverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } ] } }, { "name" : "NoOverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "UnknownOverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "OverlapsUnknownDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" } ] } ] } } ] } } } ### OverlapsAfter library TestSnippet version '1' using QUICK context Patient define ivlA = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 6, 1, 0, 0, 0, 0)) define ivlB = interval[DateTime(2012, 3, 1, 0, 0, 0, 0), DateTime(2012, 9, 1, 0, 0, 0, 0)) define ivlC = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define ivlD = interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0)) define ivlE = interval[DateTime(2013), DateTime(2015)] define ivlF = interval[DateTime(2014), DateTime(2016)] define ivlG = interval[DateTime(2016), DateTime(2017)] define OverlapsBefore = ivlA overlaps after ivlB define OverlapsAfter = ivlB overlaps after ivlA define OverlapsContained = ivlB overlaps after ivlC define OverlapsContains = ivlC overlaps after ivlB define ImpreciseOverlapBefore = ivlE overlaps after ivlF define ImpreciseOverlapAfter = ivlF overlaps after ivlE define NoOverlap = ivlC overlaps after ivlD define NoImpreciseOverlap = ivlE overlaps after ivlG define UnknownOverlap = ivlG overlaps after ivlF define OverlapsDate = ivlC overlaps after DateTime(2012, 4, 1, 0, 0, 0, 0) define StartOverlapsDate = ivlC overlaps after DateTime(2012, 1, 1, 0, 0, 0, 0) define EndOverlapsDate = ivlC overlaps after DateTime(2012, 12, 31, 23, 59, 59, 999) define NoOverlapsDate = ivlC overlaps after DateTime(2013, 4, 1, 0, 0, 0, 0) define UnknownOverlapsDate = ivlE overlaps after DateTime(2013, 4, 1, 0, 0, 0, 0) define OverlapsUnknownDate = ivlB overlaps after DateTime(2012) ### module.exports['OverlapsAfter'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "ivlA", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "6", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlB", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "9", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlC", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlD", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlE", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2015", "type" : "Literal" } ] } } }, { "name" : "ivlF", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] } } }, { "name" : "ivlG", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2017", "type" : "Literal" } ] } } }, { "name" : "OverlapsBefore", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlA", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsAfter", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlA", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContained", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlC", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContains", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapBefore", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlF", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapAfter", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlE", "type" : "ExpressionRef" } ] } }, { "name" : "NoOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlD", "type" : "ExpressionRef" } ] } }, { "name" : "NoImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "UnknownOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlG", "type" : "ExpressionRef" }, { "name" : "ivlF", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "StartOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "EndOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } ] } }, { "name" : "NoOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "UnknownOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "OverlapsUnknownDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" } ] } ] } } ] } } } ### OverlapsBefore library TestSnippet version '1' using QUICK context Patient define ivlA = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 6, 1, 0, 0, 0, 0)) define ivlB = interval[DateTime(2012, 3, 1, 0, 0, 0, 0), DateTime(2012, 9, 1, 0, 0, 0, 0)) define ivlC = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define ivlD = interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0)) define ivlE = interval[DateTime(2013), DateTime(2015)] define ivlF = interval[DateTime(2014), DateTime(2016)] define ivlG = interval[DateTime(2016), DateTime(2017)] define OverlapsBefore = ivlA overlaps before ivlB define OverlapsAfter = ivlB overlaps before ivlA define OverlapsContained = ivlB overlaps before ivlC define OverlapsContains = ivlC overlaps before ivlB define ImpreciseOverlapBefore = ivlE overlaps before ivlF define ImpreciseOverlapAfter = ivlF overlaps before ivlE define NoOverlap = ivlC overlaps before ivlD define NoImpreciseOverlap = ivlE overlaps before ivlG define UnknownOverlap = ivlF overlaps before ivlG define OverlapsDate = ivlC overlaps before DateTime(2012, 4, 1, 0, 0, 0, 0) define StartOverlapsDate = ivlC overlaps before DateTime(2012, 1, 1, 0, 0, 0, 0) define EndOverlapsDate = ivlC overlaps before DateTime(2012, 12, 31, 23, 59, 59, 999) define NoOverlapsDate = ivlC overlaps before DateTime(2013, 4, 1, 0, 0, 0, 0) define UnknownOverlapsDate = ivlE overlaps before DateTime(2013, 4, 1, 0, 0, 0, 0) define OverlapsUnknownDate = ivlB overlaps before DateTime(2012) ### module.exports['OverlapsBefore'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "ivlA", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "6", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlB", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "9", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlC", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlD", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlE", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2015", "type" : "Literal" } ] } } }, { "name" : "ivlF", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] } } }, { "name" : "ivlG", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2017", "type" : "Literal" } ] } } }, { "name" : "OverlapsBefore", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlA", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsAfter", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlA", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContained", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlC", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContains", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapBefore", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlF", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapAfter", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlE", "type" : "ExpressionRef" } ] } }, { "name" : "NoOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlD", "type" : "ExpressionRef" } ] } }, { "name" : "NoImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "UnknownOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "StartOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "EndOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } ] } }, { "name" : "NoOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "UnknownOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "OverlapsUnknownDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" } ] } ] } } ] } } } ### Start library TestSnippet version '1' using QUICK context Patient define Foo = start of interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)] ### module.exports['Start'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "Foo", "context" : "Patient", "expression" : { "type" : "Start", "operand" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } } } ] } } }
192303
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.coffee to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### Interval library TestSnippet version '1' using QUICK context Patient define Open = interval(DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define LeftOpen = interval(DateTime(2012, 1, 1), DateTime(2013, 1, 1)] define RightOpen = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define Closed = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)] ### module.exports['Interval'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "Open", "context" : "Patient", "expression" : { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "<NAME>Open", "context" : "Patient", "expression" : { "lowClosed" : false, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "<NAME>Open", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } } ] } } } ### Equal library TestSnippet version '1' using QUICK context Patient define EqualClosed = interval[1, 5] = interval[1, 5] define EqualOpen = interval(1, 5) = interval(1, 5) define EqualOpenClosed = interval(1, 5) = interval[2, 4] define UnequalClosed = interval[1, 5] = interval[2, 4] define UnequalOpen = interval(1, 5) = interval(2, 4) define UnequalClosedOpen = interval[1, 5] = interval(2, 4) define EqualDates = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define EqualDatesOpenClosed = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 12, 31, 23, 59, 59, 999)] define SameDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define DifferentDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) = interval[DateTime(2012, 1, 1), DateTime(2012, 7, 1)) ### module.exports['Equal'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>Closed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "<NAME>Open", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpenClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalOpen", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosedOpen", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "<NAME>Dates", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } ] } }, { "name" : "EqualDatesOpenClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } } ] } }, { "name" : "<NAME>Days", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } }, { "name" : "<NAME>Days", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "7", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } } ] } } } ### NotEqual library TestSnippet version '1' using QUICK context Patient define EqualClosed = interval[1, 5] <> interval[1, 5] define EqualOpen = interval(1, 5) <> interval(1, 5) define EqualOpenClosed = interval(1, 5) <> interval[2, 4] define UnequalClosed = interval[1, 5] <> interval[2, 4] define UnequalOpen = interval(1, 5) <> interval(2, 4) define UnequalClosedOpen = interval[1, 5] <> interval(2, 4) define EqualDates = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) <> interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define EqualDatesOpenClosed = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) <> interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 12, 31, 23, 59, 59, 999)] define SameDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) <> interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define DifferentDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) <> interval[DateTime(2012, 1, 1), DateTime(2012, 7, 1)) ### module.exports['NotEqual'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "EqualClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpen", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpenClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalOpen", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosedOpen", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "EqualDates", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } ] } }, { "name" : "EqualDatesOpenClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } } ] } }, { "name" : "SameDays", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } }, { "name" : "DifferentDays", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "7", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } } ] } } } ### Overlaps library TestSnippet version '1' using QUICK context Patient define ivlA = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 6, 1, 0, 0, 0, 0)) define ivlB = interval[DateTime(2012, 3, 1, 0, 0, 0, 0), DateTime(2012, 9, 1, 0, 0, 0, 0)) define ivlC = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define ivlD = interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0)) define ivlE = interval[DateTime(2013), DateTime(2015)] define ivlF = interval[DateTime(2014), DateTime(2016)] define ivlG = interval[DateTime(2016), DateTime(2017)] define OverlapsBefore = ivlA overlaps ivlB define OverlapsAfter = ivlB overlaps ivlA define OverlapsContained = ivlB overlaps ivlC define OverlapsContains = ivlC overlaps ivlB define ImpreciseOverlap = ivlD overlaps ivlE define NoOverlap = ivlC overlaps ivlD define NoImpreciseOverlap = ivlE overlaps ivlG define UnknownOverlap = ivlF overlaps ivlG define OverlapsDate = ivlC overlaps DateTime(2012, 4, 1, 0, 0, 0, 0) define StartOverlapsDate = ivlC overlaps DateTime(2012, 1, 1, 0, 0, 0, 0) define EndOverlapsDate = ivlC overlaps DateTime(2012, 12, 31, 23, 59, 59, 999) define NoOverlapsDate = ivlC overlaps DateTime(2013, 4, 1, 0, 0, 0, 0) define UnknownOverlapsDate = ivlE overlaps DateTime(2013, 4, 1, 0, 0, 0, 0) define OverlapsUnknownDate = ivlB overlaps DateTime(2012) ### module.exports['Overlaps'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "6", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "<NAME>lB", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "9", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlC", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2015", "type" : "Literal" } ] } } }, { "name" : "ivlF", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] } } }, { "name" : "ivlG", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2017", "type" : "Literal" } ] } } }, { "name" : "OverlapsBefore", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlA", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsAfter", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlA", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContained", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlC", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>sContains", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>reciseOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlD", "type" : "ExpressionRef" }, { "name" : "ivlE", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>Overlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlD", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>ImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>Overlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>Overlap<NAME>", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "<NAME>", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>OverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>OverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "<NAME>lC", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>OverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "<NAME>lE", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "OverlapsUnknownDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" } ] } ] } } ] } } } ### OverlapsAfter library TestSnippet version '1' using QUICK context Patient define ivlA = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 6, 1, 0, 0, 0, 0)) define ivlB = interval[DateTime(2012, 3, 1, 0, 0, 0, 0), DateTime(2012, 9, 1, 0, 0, 0, 0)) define ivlC = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define ivlD = interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0)) define ivlE = interval[DateTime(2013), DateTime(2015)] define ivlF = interval[DateTime(2014), DateTime(2016)] define ivlG = interval[DateTime(2016), DateTime(2017)] define OverlapsBefore = ivlA overlaps after ivlB define OverlapsAfter = ivlB overlaps after ivlA define OverlapsContained = ivlB overlaps after ivlC define OverlapsContains = ivlC overlaps after ivlB define ImpreciseOverlapBefore = ivlE overlaps after ivlF define ImpreciseOverlapAfter = ivlF overlaps after ivlE define NoOverlap = ivlC overlaps after ivlD define NoImpreciseOverlap = ivlE overlaps after ivlG define UnknownOverlap = ivlG overlaps after ivlF define OverlapsDate = ivlC overlaps after DateTime(2012, 4, 1, 0, 0, 0, 0) define StartOverlapsDate = ivlC overlaps after DateTime(2012, 1, 1, 0, 0, 0, 0) define EndOverlapsDate = ivlC overlaps after DateTime(2012, 12, 31, 23, 59, 59, 999) define NoOverlapsDate = ivlC overlaps after DateTime(2013, 4, 1, 0, 0, 0, 0) define UnknownOverlapsDate = ivlE overlaps after DateTime(2013, 4, 1, 0, 0, 0, 0) define OverlapsUnknownDate = ivlB overlaps after DateTime(2012) ### module.exports['OverlapsAfter'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "6", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "9", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "<NAME>lD", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2015", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2017", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlA", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlA", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlC", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapBefore", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlF", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapAfter", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlE", "type" : "ExpressionRef" } ] } }, { "name" : "NoOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlD", "type" : "ExpressionRef" } ] } }, { "name" : "NoImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "UnknownOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlG", "type" : "ExpressionRef" }, { "name" : "ivlF", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "StartOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>Overlap<NAME>", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "<NAME>", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>OverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "<NAME>", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "UnknownOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "iv<NAME>E", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "OverlapsUnknownDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" } ] } ] } } ] } } } ### OverlapsBefore library TestSnippet version '1' using QUICK context Patient define ivlA = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 6, 1, 0, 0, 0, 0)) define ivlB = interval[DateTime(2012, 3, 1, 0, 0, 0, 0), DateTime(2012, 9, 1, 0, 0, 0, 0)) define ivlC = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define ivlD = interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0)) define ivlE = interval[DateTime(2013), DateTime(2015)] define ivlF = interval[DateTime(2014), DateTime(2016)] define ivlG = interval[DateTime(2016), DateTime(2017)] define OverlapsBefore = ivlA overlaps before ivlB define OverlapsAfter = ivlB overlaps before ivlA define OverlapsContained = ivlB overlaps before ivlC define OverlapsContains = ivlC overlaps before ivlB define ImpreciseOverlapBefore = ivlE overlaps before ivlF define ImpreciseOverlapAfter = ivlF overlaps before ivlE define NoOverlap = ivlC overlaps before ivlD define NoImpreciseOverlap = ivlE overlaps before ivlG define UnknownOverlap = ivlF overlaps before ivlG define OverlapsDate = ivlC overlaps before DateTime(2012, 4, 1, 0, 0, 0, 0) define StartOverlapsDate = ivlC overlaps before DateTime(2012, 1, 1, 0, 0, 0, 0) define EndOverlapsDate = ivlC overlaps before DateTime(2012, 12, 31, 23, 59, 59, 999) define NoOverlapsDate = ivlC overlaps before DateTime(2013, 4, 1, 0, 0, 0, 0) define UnknownOverlapsDate = ivlE overlaps before DateTime(2013, 4, 1, 0, 0, 0, 0) define OverlapsUnknownDate = ivlB overlaps before DateTime(2012) ### module.exports['OverlapsBefore'] = { "library" : { "identifier" : { "id" : "<NAME>Snippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "ivlA", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "6", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "9", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "<NAME>lC", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlD", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlE", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2015", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2017", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlA", "type" : "ExpressionRef" }, { "name" : "<NAME>lB", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsAfter", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlA", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContained", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlC", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContains", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapBefore", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlF", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapAfter", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlE", "type" : "ExpressionRef" } ] } }, { "name" : "NoOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlD", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>ImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>Overlap", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>Overlap<NAME>Date", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>OverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } ] } }, { "name" : "NoOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>OverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "<NAME>lE", "type" : "ExpressionRef" }, { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "OverlapsUnknownDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" } ] } ] } } ] } } } ### Start library TestSnippet version '1' using QUICK context Patient define Foo = start of interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)] ### module.exports['Start'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "Start", "operand" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } } } ] } } }
true
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.coffee to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### Interval library TestSnippet version '1' using QUICK context Patient define Open = interval(DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define LeftOpen = interval(DateTime(2012, 1, 1), DateTime(2013, 1, 1)] define RightOpen = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define Closed = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)] ### module.exports['Interval'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "Open", "context" : "Patient", "expression" : { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PIOpen", "context" : "Patient", "expression" : { "lowClosed" : false, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PIOpen", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } } ] } } } ### Equal library TestSnippet version '1' using QUICK context Patient define EqualClosed = interval[1, 5] = interval[1, 5] define EqualOpen = interval(1, 5) = interval(1, 5) define EqualOpenClosed = interval(1, 5) = interval[2, 4] define UnequalClosed = interval[1, 5] = interval[2, 4] define UnequalOpen = interval(1, 5) = interval(2, 4) define UnequalClosedOpen = interval[1, 5] = interval(2, 4) define EqualDates = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define EqualDatesOpenClosed = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 12, 31, 23, 59, 59, 999)] define SameDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define DifferentDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) = interval[DateTime(2012, 1, 1), DateTime(2012, 7, 1)) ### module.exports['Equal'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PIClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "PI:NAME:<NAME>END_PIOpen", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpenClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalOpen", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosedOpen", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "PI:NAME:<NAME>END_PIDates", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } ] } }, { "name" : "EqualDatesOpenClosed", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } } ] } }, { "name" : "PI:NAME:<NAME>END_PIDays", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } }, { "name" : "PI:NAME:<NAME>END_PIDays", "context" : "Patient", "expression" : { "type" : "Equal", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "7", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } } ] } } } ### NotEqual library TestSnippet version '1' using QUICK context Patient define EqualClosed = interval[1, 5] <> interval[1, 5] define EqualOpen = interval(1, 5) <> interval(1, 5) define EqualOpenClosed = interval(1, 5) <> interval[2, 4] define UnequalClosed = interval[1, 5] <> interval[2, 4] define UnequalOpen = interval(1, 5) <> interval(2, 4) define UnequalClosedOpen = interval[1, 5] <> interval(2, 4) define EqualDates = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) <> interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define EqualDatesOpenClosed = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) <> interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 12, 31, 23, 59, 59, 999)] define SameDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) <> interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) define DifferentDays = interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)) <> interval[DateTime(2012, 1, 1), DateTime(2012, 7, 1)) ### module.exports['NotEqual'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "EqualClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpen", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } } ] } }, { "name" : "EqualOpenClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalOpen", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "UnequalClosedOpen", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "5", "type" : "Literal" } }, { "lowClosed" : false, "highClosed" : false, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" } } ] } }, { "name" : "EqualDates", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } ] } }, { "name" : "EqualDatesOpenClosed", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } } ] } }, { "name" : "SameDays", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } }, { "name" : "DifferentDays", "context" : "Patient", "expression" : { "type" : "NotEqual", "operand" : [ { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "7", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } ] } } ] } } } ### Overlaps library TestSnippet version '1' using QUICK context Patient define ivlA = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 6, 1, 0, 0, 0, 0)) define ivlB = interval[DateTime(2012, 3, 1, 0, 0, 0, 0), DateTime(2012, 9, 1, 0, 0, 0, 0)) define ivlC = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define ivlD = interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0)) define ivlE = interval[DateTime(2013), DateTime(2015)] define ivlF = interval[DateTime(2014), DateTime(2016)] define ivlG = interval[DateTime(2016), DateTime(2017)] define OverlapsBefore = ivlA overlaps ivlB define OverlapsAfter = ivlB overlaps ivlA define OverlapsContained = ivlB overlaps ivlC define OverlapsContains = ivlC overlaps ivlB define ImpreciseOverlap = ivlD overlaps ivlE define NoOverlap = ivlC overlaps ivlD define NoImpreciseOverlap = ivlE overlaps ivlG define UnknownOverlap = ivlF overlaps ivlG define OverlapsDate = ivlC overlaps DateTime(2012, 4, 1, 0, 0, 0, 0) define StartOverlapsDate = ivlC overlaps DateTime(2012, 1, 1, 0, 0, 0, 0) define EndOverlapsDate = ivlC overlaps DateTime(2012, 12, 31, 23, 59, 59, 999) define NoOverlapsDate = ivlC overlaps DateTime(2013, 4, 1, 0, 0, 0, 0) define UnknownOverlapsDate = ivlE overlaps DateTime(2013, 4, 1, 0, 0, 0, 0) define OverlapsUnknownDate = ivlB overlaps DateTime(2012) ### module.exports['Overlaps'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "6", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PIlB", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "9", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlC", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2015", "type" : "Literal" } ] } } }, { "name" : "ivlF", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] } } }, { "name" : "ivlG", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2017", "type" : "Literal" } ] } } }, { "name" : "OverlapsBefore", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlA", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsAfter", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlA", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContained", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlC", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PIsContains", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PIreciseOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlD", "type" : "ExpressionRef" }, { "name" : "ivlE", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlD", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PIImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlap", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlapPI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "PI:NAME:<NAME>END_PI", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "PI:NAME:<NAME>END_PIlC", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlapsDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "PI:NAME:<NAME>END_PIlE", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "OverlapsUnknownDate", "context" : "Patient", "expression" : { "type" : "Overlaps", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" } ] } ] } } ] } } } ### OverlapsAfter library TestSnippet version '1' using QUICK context Patient define ivlA = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 6, 1, 0, 0, 0, 0)) define ivlB = interval[DateTime(2012, 3, 1, 0, 0, 0, 0), DateTime(2012, 9, 1, 0, 0, 0, 0)) define ivlC = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define ivlD = interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0)) define ivlE = interval[DateTime(2013), DateTime(2015)] define ivlF = interval[DateTime(2014), DateTime(2016)] define ivlG = interval[DateTime(2016), DateTime(2017)] define OverlapsBefore = ivlA overlaps after ivlB define OverlapsAfter = ivlB overlaps after ivlA define OverlapsContained = ivlB overlaps after ivlC define OverlapsContains = ivlC overlaps after ivlB define ImpreciseOverlapBefore = ivlE overlaps after ivlF define ImpreciseOverlapAfter = ivlF overlaps after ivlE define NoOverlap = ivlC overlaps after ivlD define NoImpreciseOverlap = ivlE overlaps after ivlG define UnknownOverlap = ivlG overlaps after ivlF define OverlapsDate = ivlC overlaps after DateTime(2012, 4, 1, 0, 0, 0, 0) define StartOverlapsDate = ivlC overlaps after DateTime(2012, 1, 1, 0, 0, 0, 0) define EndOverlapsDate = ivlC overlaps after DateTime(2012, 12, 31, 23, 59, 59, 999) define NoOverlapsDate = ivlC overlaps after DateTime(2013, 4, 1, 0, 0, 0, 0) define UnknownOverlapsDate = ivlE overlaps after DateTime(2013, 4, 1, 0, 0, 0, 0) define OverlapsUnknownDate = ivlB overlaps after DateTime(2012) ### module.exports['OverlapsAfter'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "6", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "9", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PIlD", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2015", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2017", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlA", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlA", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlC", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapBefore", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlF", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapAfter", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlE", "type" : "ExpressionRef" } ] } }, { "name" : "NoOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlD", "type" : "ExpressionRef" } ] } }, { "name" : "NoImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "UnknownOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlG", "type" : "ExpressionRef" }, { "name" : "ivlF", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "StartOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlapPI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "PI:NAME:<NAME>END_PI", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "PI:NAME:<NAME>END_PI", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "UnknownOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivPI:NAME:<NAME>END_PIE", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "OverlapsUnknownDate", "context" : "Patient", "expression" : { "type" : "OverlapsAfter", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" } ] } ] } } ] } } } ### OverlapsBefore library TestSnippet version '1' using QUICK context Patient define ivlA = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2012, 6, 1, 0, 0, 0, 0)) define ivlB = interval[DateTime(2012, 3, 1, 0, 0, 0, 0), DateTime(2012, 9, 1, 0, 0, 0, 0)) define ivlC = interval[DateTime(2012, 1, 1, 0, 0, 0, 0), DateTime(2013, 1, 1, 0, 0, 0, 0)) define ivlD = interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0)) define ivlE = interval[DateTime(2013), DateTime(2015)] define ivlF = interval[DateTime(2014), DateTime(2016)] define ivlG = interval[DateTime(2016), DateTime(2017)] define OverlapsBefore = ivlA overlaps before ivlB define OverlapsAfter = ivlB overlaps before ivlA define OverlapsContained = ivlB overlaps before ivlC define OverlapsContains = ivlC overlaps before ivlB define ImpreciseOverlapBefore = ivlE overlaps before ivlF define ImpreciseOverlapAfter = ivlF overlaps before ivlE define NoOverlap = ivlC overlaps before ivlD define NoImpreciseOverlap = ivlE overlaps before ivlG define UnknownOverlap = ivlF overlaps before ivlG define OverlapsDate = ivlC overlaps before DateTime(2012, 4, 1, 0, 0, 0, 0) define StartOverlapsDate = ivlC overlaps before DateTime(2012, 1, 1, 0, 0, 0, 0) define EndOverlapsDate = ivlC overlaps before DateTime(2012, 12, 31, 23, 59, 59, 999) define NoOverlapsDate = ivlC overlaps before DateTime(2013, 4, 1, 0, 0, 0, 0) define UnknownOverlapsDate = ivlE overlaps before DateTime(2013, 4, 1, 0, 0, 0, 0) define OverlapsUnknownDate = ivlB overlaps before DateTime(2012) ### module.exports['OverlapsBefore'] = { "library" : { "identifier" : { "id" : "PI:NAME:<NAME>END_PISnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "ivlA", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "6", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "9", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PIlC", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlD", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } }, { "name" : "ivlE", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2015", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2016", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2017", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlA", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PIlB", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsAfter", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlA", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContained", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "ivlC", "type" : "ExpressionRef" } ] } }, { "name" : "OverlapsContains", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlB", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapBefore", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlF", "type" : "ExpressionRef" } ] } }, { "name" : "ImpreciseOverlapAfter", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlE", "type" : "ExpressionRef" } ] } }, { "name" : "NoOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "ivlD", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PIImpreciseOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlE", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlap", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlF", "type" : "ExpressionRef" }, { "name" : "ivlG", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlapPI:NAME:<NAME>END_PIDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "12", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "31", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "23", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "59", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "999", "type" : "Literal" } ] } ] } }, { "name" : "NoOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlC", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIOverlapsDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "PI:NAME:<NAME>END_PIlE", "type" : "ExpressionRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "4", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } ] } }, { "name" : "OverlapsUnknownDate", "context" : "Patient", "expression" : { "type" : "OverlapsBefore", "operand" : [ { "name" : "ivlB", "type" : "ExpressionRef" }, { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" } ] } ] } } ] } } } ### Start library TestSnippet version '1' using QUICK context Patient define Foo = start of interval[DateTime(2012, 1, 1), DateTime(2013, 1, 1)] ### module.exports['Start'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "Start", "operand" : { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2012", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] }, "high" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" } ] } } } } ] } } }
[ { "context": "tman()\n anotherNoName = Batman()\n nullName = Batman\n author: Batman\n name: null\n naNNa", "end": 764, "score": 0.9854929447174072, "start": 758, "tag": "NAME", "value": "Batman" }, { "context": "ame = Batman()\n nullName = Batman\n author: Batman\n name: null\n naNName = Batman\n aut", "end": 785, "score": 0.9933328628540039, "start": 779, "tag": "NAME", "value": "Batman" }, { "context": " author: Batman\n name: null\n naNName = Batman\n author: Batman\n name: NaN\n number", "end": 825, "score": 0.9824294447898865, "start": 819, "tag": "NAME", "value": "Batman" }, { "context": " name: null\n naNName = Batman\n author: Batman\n name: NaN\n numberedName = Batman\n ", "end": 846, "score": 0.9887563586235046, "start": 840, "tag": "NAME", "value": "Batman" }, { "context": "uthor: Batman\n name: NaN\n numberedName = Batman\n author: Batman\n name: 9\n anotherN", "end": 890, "score": 0.9355144500732422, "start": 884, "tag": "NAME", "value": "Batman" }, { "context": " name: NaN\n numberedName = Batman\n author: Batman\n name: 9\n anotherNumberedName = Batman\n", "end": 911, "score": 0.9856578707695007, "start": 905, "tag": "NAME", "value": "Batman" }, { "context": ": Batman\n name: 9\n anotherNumberedName = Batman\n author: Batman\n name: 80\n tr", "end": 955, "score": 0.5838181972503662, "start": 954, "tag": "NAME", "value": "B" }, { "context": ": 9\n anotherNumberedName = Batman\n author: Batman\n name: 80\n trueName = Batman\n auth", "end": 981, "score": 0.9398903846740723, "start": 975, "tag": "NAME", "value": "Batman" }, { "context": " author: Batman\n name: 80\n trueName = Batman\n author: Batman\n name: true\n false", "end": 1020, "score": 0.8507480621337891, "start": 1014, "tag": "NAME", "value": "Batman" }, { "context": " name: 80\n trueName = Batman\n author: Batman\n name: true\n falseName = Batman\n a", "end": 1041, "score": 0.9890518188476562, "start": 1035, "tag": "NAME", "value": "Batman" }, { "context": " author: Batman\n name: true\n falseName = Batman\n author: Batman\n name: false\n @", "end": 1080, "score": 0.7678207755088806, "start": 1077, "tag": "NAME", "value": "Bat" }, { "context": " name: true\n falseName = Batman\n author: Batman\n name: false\n @base.add noName\n @bas", "end": 1104, "score": 0.9883536696434021, "start": 1098, "tag": "NAME", "value": "Batman" }, { "context": "scending\", ->\n noName = Batman()\n nullName = Batman\n author: Batman\n name: null\n naNNa", "end": 1554, "score": 0.9591143727302551, "start": 1548, "tag": "NAME", "value": "Batman" }, { "context": "ame = Batman()\n nullName = Batman\n author: Batman\n name: null\n naNName = Batman\n aut", "end": 1575, "score": 0.9857466220855713, "start": 1569, "tag": "NAME", "value": "Batman" }, { "context": " author: Batman\n name: null\n naNName = Batman\n author: Batman\n name: NaN\n number", "end": 1615, "score": 0.834113597869873, "start": 1609, "tag": "NAME", "value": "Batman" }, { "context": " name: null\n naNName = Batman\n author: Batman\n name: NaN\n numberedName = Batman\n ", "end": 1636, "score": 0.9888689517974854, "start": 1630, "tag": "NAME", "value": "Batman" }, { "context": "uthor: Batman\n name: NaN\n numberedName = Batman\n author: Batman\n name: 9\n anoth", "end": 1677, "score": 0.7506455779075623, "start": 1674, "tag": "NAME", "value": "Bat" }, { "context": " name: NaN\n numberedName = Batman\n author: Batman\n name: 9\n anotherNumberedName = Batman\n", "end": 1701, "score": 0.9422974586486816, "start": 1695, "tag": "NAME", "value": "Batman" }, { "context": ": 9\n anotherNumberedName = Batman\n author: Batman\n name: 80\n trueName = Batman\n auth", "end": 1771, "score": 0.980911910533905, "start": 1765, "tag": "NAME", "value": "Batman" }, { "context": " author: Batman\n name: 80\n trueName = Batman\n author: Batman\n name: true\n false", "end": 1810, "score": 0.9987759590148926, "start": 1804, "tag": "NAME", "value": "Batman" }, { "context": " name: 80\n trueName = Batman\n author: Batman\n name: true\n falseName = Batman\n a", "end": 1831, "score": 0.9991639256477356, "start": 1825, "tag": "NAME", "value": "Batman" }, { "context": " author: Batman\n name: true\n falseName = Batman\n author: Batman\n name: false\n @bas", "end": 1873, "score": 0.9992373585700989, "start": 1867, "tag": "NAME", "value": "Batman" }, { "context": " name: true\n falseName = Batman\n author: Batman\n name: false\n @base.add noName\n @bas", "end": 1894, "score": 0.9994771480560303, "start": 1888, "tag": "NAME", "value": "Batman" }, { "context": "the correct order\", ->\n expect 4\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n @authorNam", "end": 2529, "score": 0.9127763509750366, "start": 2521, "tag": "USERNAME", "value": "[@byFred" }, { "context": "order\", ->\n expect 4\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n @authorNameSort.forE", "end": 2539, "score": 0.5395335555076599, "start": 2532, "tag": "USERNAME", "value": "another" }, { "context": ">\n expect 4\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n @authorNameSort.forEach", "end": 2542, "score": 0.8702457547187805, "start": 2541, "tag": "USERNAME", "value": "F" }, { "context": "\n expect 4\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n @authorNameSort.forEach (i", "end": 2545, "score": 0.6072011590003967, "start": 2542, "tag": "NAME", "value": "red" }, { "context": "ct 4\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n @authorNameSort.forEach (item, i) -", "end": 2554, "score": 0.587883710861206, "start": 2551, "tag": "NAME", "value": "ary" }, { "context": "ay() returns the correct order\", ->\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n deepEqual ", "end": 2806, "score": 0.9326205253601074, "start": 2798, "tag": "USERNAME", "value": "[@byFred" }, { "context": " the correct order\", ->\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n deepEqual @authorNam", "end": 2816, "score": 0.7454480528831482, "start": 2809, "tag": "USERNAME", "value": "another" }, { "context": "ect order\", ->\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n deepEqual @authorNameSo", "end": 2819, "score": 0.9035405516624451, "start": 2818, "tag": "USERNAME", "value": "F" }, { "context": "ct order\", ->\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n deepEqual @authorNameSort.", "end": 2822, "score": 0.5462173819541931, "start": 2819, "tag": "NAME", "value": "red" }, { "context": ", ->\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n deepEqual @authorNameSort.toArray()", "end": 2831, "score": 0.48189103603363037, "start": 2828, "tag": "NAME", "value": "ary" }, { "context": "are added to the underlying set\", ->\n @base.add @byJill\n equal @authorNameSort.get('length'), 5\n", "end": 3036, "score": 0.6149419546127319, "start": 3036, "tag": "USERNAME", "value": "" }, { "context": "e added to the underlying set\", ->\n @base.add @byJill\n equal @authorNameSort.get('length'), 5\n\n tes", "end": 3044, "score": 0.7629191875457764, "start": 3038, "tag": "USERNAME", "value": "byJill" }, { "context": "oved from the underlying set\", ->\n @base.remove @byFred\n equal @authorNameSort.get('length'), 3\n", "end": 3206, "score": 0.6405822038650513, "start": 3206, "tag": "USERNAME", "value": "" }, { "context": "ed from the underlying set\", ->\n @base.remove @byFred\n equal @authorNameSort.get('length'), 3\n\n tes", "end": 3214, "score": 0.8420848250389099, "start": 3208, "tag": "USERNAME", "value": "byFred" }, { "context": "ia the set sort proxy\", ->\n @authorNameSort.add @byJill\n equal @authorNameSort.get('length'), 5\n", "end": 3391, "score": 0.7278987765312195, "start": 3391, "tag": "USERNAME", "value": "" }, { "context": " the set sort proxy\", ->\n @authorNameSort.add @byJill\n equal @authorNameSort.get('length'), 5\n\n tes", "end": 3399, "score": 0.7853139042854309, "start": 3393, "tag": "USERNAME", "value": "byJill" }, { "context": "the set sort proxy\", ->\n @authorNameSort.remove @byFred\n equal @authorNameSort.get('length'), 3\n", "end": 3579, "score": 0.5464259386062622, "start": 3579, "tag": "USERNAME", "value": "" }, { "context": "e set sort proxy\", ->\n @authorNameSort.remove @byFred\n equal @authorNameSort.get('length'), 3\n\n ", "end": 3584, "score": 0.7060515284538269, "start": 3581, "tag": "USERNAME", "value": "byF" }, { "context": "et sort proxy\", ->\n @authorNameSort.remove @byFred\n equal @authorNameSort.get('length'), 3\n\n tes", "end": 3587, "score": 0.5261343121528625, "start": 3584, "tag": "NAME", "value": "red" }, { "context": "items in the correct order\", ->\n @base.add @byJill\n expected = ['Fred', 'Fred', 'Jill', 'Mary', '", "end": 3724, "score": 0.5764994621276855, "start": 3721, "tag": "USERNAME", "value": "ill" }, { "context": "order\", ->\n @base.add @byJill\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke']\n deepEqual @", "end": 3746, "score": 0.999852180480957, "start": 3742, "tag": "NAME", "value": "Fred" }, { "context": "->\n @base.add @byJill\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke']\n deepEqual @authorNa", "end": 3754, "score": 0.9997771382331848, "start": 3750, "tag": "NAME", "value": "Fred" }, { "context": "base.add @byJill\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke']\n deepEqual @authorNameSort.m", "end": 3762, "score": 0.9997214078903198, "start": 3758, "tag": "NAME", "value": "Jill" }, { "context": " @byJill\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke']\n deepEqual @authorNameSort.mapToProp", "end": 3770, "score": 0.9997332096099854, "start": 3766, "tag": "NAME", "value": "Mary" }, { "context": "\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke']\n deepEqual @authorNameSort.mapToProperty('au", "end": 3778, "score": 0.9985319972038269, "start": 3774, "tag": "NAME", "value": "Zeke" }, { "context": "ed\n\n @base.add @anotherByZeke\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke', 'Zeke']\n dee", "end": 3901, "score": 0.9998610019683838, "start": 3897, "tag": "NAME", "value": "Fred" }, { "context": "@base.add @anotherByZeke\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke', 'Zeke']\n deepEqual @", "end": 3909, "score": 0.999824583530426, "start": 3905, "tag": "NAME", "value": "Fred" }, { "context": "d @anotherByZeke\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke', 'Zeke']\n deepEqual @authorNa", "end": 3917, "score": 0.9996883869171143, "start": 3913, "tag": "NAME", "value": "Jill" }, { "context": "erByZeke\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke', 'Zeke']\n deepEqual @authorNameSort.m", "end": 3925, "score": 0.9997372627258301, "start": 3921, "tag": "NAME", "value": "Mary" }, { "context": "\n expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke', 'Zeke']\n deepEqual @authorNameSort.mapToProp", "end": 3933, "score": 0.9993809461593628, "start": 3929, "tag": "NAME", "value": "Zeke" }, { "context": "ected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke', 'Zeke']\n deepEqual @authorNameSort.mapToProperty('au", "end": 3941, "score": 0.9944103956222534, "start": 3937, "tag": "NAME", "value": "Zeke" }, { "context": "have been removed\", ->\n @base.remove @anotherByFred\n expected = [@byFred, @byMary, @byZeke]\n eq", "end": 4115, "score": 0.5491009950637817, "start": 4111, "tag": "USERNAME", "value": "Fred" }, { "context": "\n @base.remove @anotherByFred\n expected = [@byFred, @byMary, @byZeke]\n equal @authorNameSort.toAr", "end": 4139, "score": 0.8808414340019226, "start": 4133, "tag": "USERNAME", "value": "byFred" }, { "context": "remove @anotherByFred\n expected = [@byFred, @byMary, @byZeke]\n equal @authorNameSort.toArray().len", "end": 4148, "score": 0.9151432514190674, "start": 4144, "tag": "USERNAME", "value": "Mary" }, { "context": "notherByFred\n expected = [@byFred, @byMary, @byZeke]\n equal @authorNameSort.toArray().length, 3\n ", "end": 4157, "score": 0.739639401435852, "start": 4153, "tag": "USERNAME", "value": "Zeke" }, { "context": " expected\n\n @base.remove @byZeke\n expected = [@byFred, @byMary]\n equal @authorNameSort.toArray().len", "end": 4304, "score": 0.9252879619598389, "start": 4296, "tag": "USERNAME", "value": "[@byFred" }, { "context": " @base.remove @byZeke\n expected = [@byFred, @byMary]\n equal @authorNameSort.toArray().length, 2\n ", "end": 4313, "score": 0.9389256238937378, "start": 4309, "tag": "USERNAME", "value": "Mary" }, { "context": "deepEqual @authorNameSort.get('firstTwoNames'), [\"Fred\", \"Fred\"], \"it starts with the first two\"\n @ba", "end": 4678, "score": 0.999863862991333, "start": 4674, "tag": "NAME", "value": "Fred" }, { "context": "l @authorNameSort.get('firstTwoNames'), [\"Fred\", \"Fred\"], \"it starts with the first two\"\n @base.remov", "end": 4686, "score": 0.9998530149459839, "start": 4682, "tag": "NAME", "value": "Fred" }, { "context": "], \"it starts with the first two\"\n @base.remove(@byFred)\n deepEqual @authorNameSort.get('firstTwoNames", "end": 4745, "score": 0.8402937054634094, "start": 4738, "tag": "USERNAME", "value": "@byFred" }, { "context": "deepEqual @authorNameSort.get('firstTwoNames'), [\"Fred\", \"Mary\"], \"Removal causes an update\"\n @base.a", "end": 4805, "score": 0.9998681545257568, "start": 4801, "tag": "NAME", "value": "Fred" }, { "context": "l @authorNameSort.get('firstTwoNames'), [\"Fred\", \"Mary\"], \"Removal causes an update\"\n @base.add(Batma", "end": 4813, "score": 0.9998370409011841, "start": 4809, "tag": "NAME", "value": "Mary" }, { "context": "deepEqual @authorNameSort.get('firstTwoNames'), [\"Bobs\", \"Fred\"], \"Addition causes an update\"\n @byZek", "end": 4939, "score": 0.9981845617294312, "start": 4935, "tag": "NAME", "value": "Bobs" }, { "context": "l @authorNameSort.get('firstTwoNames'), [\"Bobs\", \"Fred\"], \"Addition causes an update\"\n @byZeke.set('a", "end": 4947, "score": 0.9998612403869629, "start": 4943, "tag": "NAME", "value": "Fred" }, { "context": "causes an update\"\n @byZeke.set('author.name', \"Aaron\")\n deepEqual @authorNameSort.get('firstTwoName", "end": 5016, "score": 0.99978107213974, "start": 5011, "tag": "NAME", "value": "Aaron" }, { "context": "deepEqual @authorNameSort.get('firstTwoNames'), [\"Aaron\", \"Bobs\"], \"Modification causes an update\"\n\n tes", "end": 5078, "score": 0.9998707175254822, "start": 5073, "tag": "NAME", "value": "Aaron" }, { "context": " @authorNameSort.get('firstTwoNames'), [\"Aaron\", \"Bobs\"], \"Modification causes an update\"\n\n test \"setti", "end": 5086, "score": 0.9231105446815491, "start": 5082, "tag": "NAME", "value": "Bobs" }, { "context": "triggers an update\", ->\n switchedAuthorToBobs = @anotherByFred\n switchedAuthorToBobs.set('author', @bob", "end": 5253, "score": 0.6629625558853149, "start": 5245, "tag": "USERNAME", "value": "@another" }, { "context": " update\", ->\n switchedAuthorToBobs = @anotherByFred\n switchedAuthorToBobs.set('author', @bobs)\n ", "end": 5259, "score": 0.8287471532821655, "start": 5255, "tag": "USERNAME", "value": "Fred" }, { "context": "otherByFred\n switchedAuthorToBobs.set('author', @bobs)\n expected = [switchedAuthorToBobs, @byFred, @", "end": 5304, "score": 0.8530358672142029, "start": 5299, "tag": "USERNAME", "value": "@bobs" }, { "context": " expected = [switchedAuthorToBobs, @byFred, @byMary, @byZeke]\n deepEqual @authorNameSort.toArra", "end": 5357, "score": 0.8301149606704712, "start": 5356, "tag": "USERNAME", "value": "M" }, { "context": " expected = [switchedAuthorToBobs, @byFred, @byMary, @byZeke]\n deepEqual @authorNameSort.toArray()", "end": 5360, "score": 0.8350591063499451, "start": 5357, "tag": "NAME", "value": "ary" }, { "context": "ted = [switchedAuthorToBobs, @byFred, @byMary, @byZeke]\n deepEqual @authorNameSort.toArray(), expecte", "end": 5369, "score": 0.9683282375335693, "start": 5365, "tag": "USERNAME", "value": "Zeke" }, { "context": "should not trigger an update\", ->\n @base.remove @anotherByFred\n reIndex = spyOn(@authorNameSort, \"_reIndex\")\n", "end": 5572, "score": 0.9092041254043579, "start": 5558, "tag": "USERNAME", "value": "@anotherByFred" }, { "context": "ort, \"_reIndex\")\n\n @anotherByFred.set('author', @mary)\n\n equal reIndex.called, false\n expected = ", "end": 5661, "score": 0.9700855016708374, "start": 5656, "tag": "USERNAME", "value": "@mary" }, { "context": "\n equal reIndex.called, false\n expected = [@byFred, @byMary, @byZeke]\n deepEqual @authorNameSort.", "end": 5719, "score": 0.9899601340293884, "start": 5713, "tag": "USERNAME", "value": "byFred" }, { "context": "reIndex.called, false\n expected = [@byFred, @byMary, @byZeke]\n deepEqual @authorNameSort.toArray()", "end": 5728, "score": 0.9830642938613892, "start": 5724, "tag": "USERNAME", "value": "Mary" }, { "context": "alled, false\n expected = [@byFred, @byMary, @byZeke]\n deepEqual @authorNameSort.toArray(), expecte", "end": 5737, "score": 0.9709751605987549, "start": 5733, "tag": "USERNAME", "value": "Zeke" }, { "context": "d never _reIndex()\", ->\n @authorNameSort.remove @anotherByFred\n reIndex = spyOn(@authorNameSort, \"_reIndex\")\n", "end": 5903, "score": 0.8823399543762207, "start": 5889, "tag": "USERNAME", "value": "@anotherByFred" }, { "context": "thorNameSort, \"_reIndex\")\n\n @authorNameSort.add(@anotherByFred)\n equal reIndex.callCount, 0\n\n @authorNameS", "end": 5992, "score": 0.9942137002944946, "start": 5978, "tag": "USERNAME", "value": "@anotherByFred" }, { "context": "qual reIndex.callCount, 0\n\n @authorNameSort.add(@byJill, @anotherByZeke)\n equal reIndex.callCount, 0\n\n", "end": 6057, "score": 0.9954202771186829, "start": 6050, "tag": "USERNAME", "value": "@byJill" }, { "context": "x.callCount, 0\n\n @authorNameSort.add(@byJill, @anotherByZeke)\n equal reIndex.callCount, 0\n\n test \"stopObse", "end": 6073, "score": 0.9799931049346924, "start": 6060, "tag": "USERNAME", "value": "anotherByZeke" }, { "context": " @authorNameSort.stopObserving()\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n\n @base.add", "end": 6217, "score": 0.9414207935333252, "start": 6209, "tag": "USERNAME", "value": "[@byFred" }, { "context": "ameSort.stopObserving()\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n\n @base.add @byJill\n dee", "end": 6233, "score": 0.9549619555473328, "start": 6220, "tag": "USERNAME", "value": "anotherByFred" }, { "context": "rving()\n expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n\n @base.add @byJill\n deepEqual @a", "end": 6242, "score": 0.8784117698669434, "start": 6236, "tag": "USERNAME", "value": "byMary" }, { "context": " expected = [@byFred, @anotherByFred, @byMary, @byZeke]\n\n @base.add @byJill\n deepEqual @authorName", "end": 6251, "score": 0.9574280977249146, "start": 6247, "tag": "USERNAME", "value": "Zeke" }, { "context": ", @anotherByFred, @byMary, @byZeke]\n\n @base.add @byJill\n deepEqual @authorNameSort.toArray(), expected", "end": 6275, "score": 0.729814350605011, "start": 6268, "tag": "USERNAME", "value": "@byJill" }, { "context": "NameSort.toArray(), expected\n\n @base.remove @byZeke\n deepEqual @authorNameSort.toArray(), expected", "end": 6351, "score": 0.8711377382278442, "start": 6347, "tag": "USERNAME", "value": "Zeke" }, { "context": "ort.toArray(), expected\n\n @byFred.set('author', @mary)\n deepEqual @authorNameSort.toArray(), expecte", "end": 6434, "score": 0.9634479284286499, "start": 6429, "tag": "USERNAME", "value": "@mary" }, { "context": "ppedTo returns a SetMapping', ->\n expected = [\"Fred\", \"Mary\", \"Zeke\"]\n mapping = @authorNameSort.m", "end": 6551, "score": 0.9996678233146667, "start": 6547, "tag": "NAME", "value": "Fred" }, { "context": "eturns a SetMapping', ->\n expected = [\"Fred\", \"Mary\", \"Zeke\"]\n mapping = @authorNameSort.mappedTo(", "end": 6559, "score": 0.9995549917221069, "start": 6555, "tag": "NAME", "value": "Mary" }, { "context": " SetMapping', ->\n expected = [\"Fred\", \"Mary\", \"Zeke\"]\n mapping = @authorNameSort.mappedTo('author.", "end": 6567, "score": 0.9959717392921448, "start": 6563, "tag": "NAME", "value": "Zeke" }, { "context": "pected\n ok mapping.has(name)\n @base.remove(@byMary)\n ok !mapping.has('Mary')\n @base.remove(@by", "end": 6735, "score": 0.9926592707633972, "start": 6728, "tag": "USERNAME", "value": "@byMary" }, { "context": ")\n @base.remove(@byMary)\n ok !mapping.has('Mary')\n @base.remove(@byFred, @anotherByFred)\n o", "end": 6762, "score": 0.8293083906173706, "start": 6759, "tag": "NAME", "value": "ary" }, { "context": "Mary)\n ok !mapping.has('Mary')\n @base.remove(@byFred, @anotherByFred)\n ok !mapping.has('Fred')\n ", "end": 6789, "score": 0.9762144088745117, "start": 6782, "tag": "USERNAME", "value": "@byFred" }, { "context": "k !mapping.has('Mary')\n @base.remove(@byFred, @anotherByFred)\n ok !mapping.has('Fred')\n @base.add(@byMar", "end": 6805, "score": 0.9520843625068665, "start": 6792, "tag": "USERNAME", "value": "anotherByFred" }, { "context": "ove(@byFred, @anotherByFred)\n ok !mapping.has('Fred')\n @base.add(@byMary)\n ok mapping.has('Mary", "end": 6832, "score": 0.8780727386474609, "start": 6828, "tag": "NAME", "value": "Fred" }, { "context": "rByFred)\n ok !mapping.has('Fred')\n @base.add(@byMary)\n ok mapping.has('Mary')\n\n test 'at(i) return", "end": 6856, "score": 0.9759073257446289, "start": 6849, "tag": "USERNAME", "value": "@byMary" }, { "context": "Fred')\n @base.add(@byMary)\n ok mapping.has('Mary')\n\n test 'at(i) returns the item according to th", "end": 6882, "score": 0.9883073568344116, "start": 6878, "tag": "NAME", "value": "Mary" }, { "context": " equal @authorNameSort.at(0).get('author.name'), \"Fred\"\n equal @authorNameSort.at(3).get('author.name", "end": 7001, "score": 0.9994584321975708, "start": 6997, "tag": "NAME", "value": "Fred" }, { "context": " equal @authorNameSort.at(3).get('author.name'), \"Zeke\"\n @base.add(Batman(author: @bobs))\n equal @", "end": 7060, "score": 0.9988926649093628, "start": 7056, "tag": "NAME", "value": "Zeke" }, { "context": "thor.name'), \"Zeke\"\n @base.add(Batman(author: @bobs))\n equal @authorNameSort.at(0).get('author.nam", "end": 7096, "score": 0.9053089618682861, "start": 7092, "tag": "USERNAME", "value": "bobs" }, { "context": " equal @authorNameSort.at(0).get('author.name'), \"Bobs\"\n\n test 'at accessor returns the item according ", "end": 7156, "score": 0.8972249627113342, "start": 7152, "tag": "NAME", "value": "Bobs" }, { "context": " equal @authorNameSort.get('at.0.author.name'), \"Fred\"\n equal @authorNameSort.get('at.3.author.name'", "end": 7279, "score": 0.9996368885040283, "start": 7275, "tag": "NAME", "value": "Fred" }, { "context": " equal @authorNameSort.get('at.3.author.name'), \"Zeke\"\n @base.add(Batman(author: @bobs))\n equal @", "end": 7337, "score": 0.9978969693183899, "start": 7333, "tag": "NAME", "value": "Zeke" }, { "context": "thor.name'), \"Zeke\"\n @base.add(Batman(author: @bobs))\n equal @authorNameSort.get('at.0.author.name", "end": 7373, "score": 0.8414150476455688, "start": 7369, "tag": "USERNAME", "value": "bobs" }, { "context": " equal @authorNameSort.get('at.0.author.name'), \"Bobs\", \"Adding causes update\"\n @byMary.set('author.", "end": 7432, "score": 0.5001928210258484, "start": 7429, "tag": "NAME", "value": "obs" }, { "context": "ng causes update\"\n @byMary.set('author.name', \"Aaron\")\n equal @authorNameSort.get('at.0.author.name", "end": 7495, "score": 0.9996647238731384, "start": 7490, "tag": "NAME", "value": "Aaron" }, { "context": " equal @authorNameSort.get('at.0.author.name'), \"Aaron\", \"Update causes update\"\n @base.remove(@byMary", "end": 7555, "score": 0.9995597004890442, "start": 7550, "tag": "NAME", "value": "Aaron" }, { "context": "ron\", \"Update causes update\"\n @base.remove(@byMary)\n equal @authorNameSort.get('at.0.author.name'", "end": 7605, "score": 0.5109845399856567, "start": 7602, "tag": "USERNAME", "value": "ary" }, { "context": "s\", \"Removal causes update\"\n\nfixtureSetup = ->\n @zeke = Batman name: 'Zeke'\n @mary = Batman name: 'Mar", "end": 7716, "score": 0.7367353439331055, "start": 7712, "tag": "USERNAME", "value": "zeke" }, { "context": "pdate\"\n\nfixtureSetup = ->\n @zeke = Batman name: 'Zeke'\n @mary = Batman name: 'Mary'\n @fred = Batman n", "end": 7737, "score": 0.9892767071723938, "start": 7733, "tag": "NAME", "value": "Zeke" }, { "context": "eke = Batman name: 'Zeke'\n @mary = Batman name: 'Mary'\n @fred = Batman name: 'Fred'\n @jill = Batman n", "end": 7767, "score": 0.9994897842407227, "start": 7763, "tag": "NAME", "value": "Mary" }, { "context": "ary = Batman name: 'Mary'\n @fred = Batman name: 'Fred'\n @jill = Batman name: 'Jill'\n @bobs = Batman n", "end": 7797, "score": 0.9996297359466553, "start": 7793, "tag": "NAME", "value": "Fred" }, { "context": "red = Batman name: 'Fred'\n @jill = Batman name: 'Jill'\n @bobs = Batman name: 'Bobs'\n\n @byZeke = Batma", "end": 7827, "score": 0.9972915649414062, "start": 7823, "tag": "NAME", "value": "Jill" }, { "context": "ill = Batman name: 'Jill'\n @bobs = Batman name: 'Bobs'\n\n @byZeke = Batman author: @zeke\n @byMary = Ba", "end": 7857, "score": 0.9585961103439331, "start": 7853, "tag": "NAME", "value": "Bobs" }, { "context": " name: 'Jill'\n @bobs = Batman name: 'Bobs'\n\n @byZeke = Batman author: @zeke\n @byMary = Batman author:", "end": 7869, "score": 0.8291471004486084, "start": 7865, "tag": "USERNAME", "value": "Zeke" }, { "context": " = Batman name: 'Bobs'\n\n @byZeke = Batman author: @zeke\n @byMary = Batman author: @mary\n @byFred = Batm", "end": 7892, "score": 0.9586305022239685, "start": 7887, "tag": "USERNAME", "value": "@zeke" }, { "context": "e: 'Bobs'\n\n @byZeke = Batman author: @zeke\n @byMary = Batman author: @mary\n @byFred = Batman author:", "end": 7902, "score": 0.5878153443336487, "start": 7899, "tag": "USERNAME", "value": "ary" }, { "context": " = Batman author: @zeke\n @byMary = Batman author: @mary\n @byFred = Batman author: @fred, prop: \"byFred\"\n", "end": 7925, "score": 0.7672020196914673, "start": 7920, "tag": "USERNAME", "value": "@mary" }, { "context": " = Batman author: @mary\n @byFred = Batman author: @fred, prop: \"byFred\"\n @anotherByFred = Batman author:", "end": 7958, "score": 0.9727402329444885, "start": 7953, "tag": "USERNAME", "value": "@fred" }, { "context": ", prop: \"byFred\"\n @anotherByFred = Batman author: @fred, prop: \"anotherByFred\"\n\n # not yet in the set:\n ", "end": 8014, "score": 0.9725063443183899, "start": 8009, "tag": "USERNAME", "value": "@fred" }, { "context": " # not yet in the set:\n @byJill = Batman author: @jill\n @anotherByZeke = Batman author: @zeke\n\nQUnit.mo", "end": 8095, "score": 0.9896475672721863, "start": 8090, "tag": "USERNAME", "value": "@jill" }, { "context": "an author: @jill\n @anotherByZeke = Batman author: @zeke\n\nQUnit.module 'Batman.SetSort on a Batman.Set',\n ", "end": 8135, "score": 0.9165360927581787, "start": 8130, "tag": "USERNAME", "value": "@zeke" }, { "context": "tureSetup.call(@)\n\n @base = new Batman.Set([@byMary, @byFred, @byZeke, @anotherByFred])\n @authorNa", "end": 8257, "score": 0.6779831647872925, "start": 8253, "tag": "USERNAME", "value": "Mary" }, { "context": "tup.call(@)\n\n @base = new Batman.SimpleSet([@byMary, @byFred, @byZeke, @anotherByFred])\n @authorNa", "end": 8536, "score": 0.8569144010543823, "start": 8532, "tag": "NAME", "value": "Mary" }, { "context": "@)\n\n @base = new Batman.SimpleSet([@byMary, @byFred, @byZeke, @anotherByFred])\n @authorNameSort = ", "end": 8545, "score": 0.9911819696426392, "start": 8541, "tag": "NAME", "value": "Fred" }, { "context": "base = new Batman.SimpleSet([@byMary, @byFred, @byZeke, @anotherByFred])\n @authorNameSort = new Batma", "end": 8554, "score": 0.8717957735061646, "start": 8550, "tag": "USERNAME", "value": "Zeke" }, { "context": "n.SimpleSet([@byMary, @byFred, @byZeke, @anotherByFred])\n @authorNameSort = new Batman.SetSort(@ba", "end": 8567, "score": 0.8503880500793457, "start": 8566, "tag": "NAME", "value": "F" } ]
tests/batman/set/set_sort_test.coffee
nickjs/batman.js
3
assertSorted = (array, compareFunction) -> last = null for item, i in array if last ok compareFunction(last, item) < 1 last = item setSortSuite = -> test "new Batman.SetSort(set, key) constructs a sort on the set for that keypath", -> equal @authorNameSort.base, @base equal @authorNameSort.key, 'author.name' equal @authorNameSort.descending, no test "new Batman.SetSort(set, key, 'desc') constructs a reversed sort", -> reversedSort = new Batman.SetSort(@base, 'author.name', 'desc') equal reversedSort.base, @base equal reversedSort.key, 'author.name' equal reversedSort.descending, yes test "toArray() returns the sorted items", -> noName = Batman() anotherNoName = Batman() nullName = Batman author: Batman name: null naNName = Batman author: Batman name: NaN numberedName = Batman author: Batman name: 9 anotherNumberedName = Batman author: Batman name: 80 trueName = Batman author: Batman name: true falseName = Batman author: Batman name: false @base.add noName @base.add nullName @base.add anotherNoName @base.add anotherNumberedName @base.add naNName @base.add numberedName @base.add trueName @base.add falseName @base.remove @anotherByFred assertSorted(@authorNameSort.toArray(), Batman.SetSort::compare) test "forEach(iterator) and toArray() go in reverse if sort is descending", -> noName = Batman() nullName = Batman author: Batman name: null naNName = Batman author: Batman name: NaN numberedName = Batman author: Batman name: 9 anotherNumberedName = Batman author: Batman name: 80 trueName = Batman author: Batman name: true falseName = Batman author: Batman name: false @base.add noName @base.add nullName @base.add anotherNumberedName @base.add naNName @base.add numberedName @base.add trueName @base.add falseName @base.remove @anotherByFred descendingAuthorNameSort = new Batman.SetSort(@base, 'author.name', 'desc') sorted = descendingAuthorNameSort.toArray() assertSorted(sorted, (a,b) -> Batman.SetSort::compare(b,a)) collector = [] descendingAuthorNameSort.forEach (item) -> collector.push(item) deepEqual sorted, collector test "forEach(iterator) loops in the correct order", -> expect 4 expected = [@byFred, @anotherByFred, @byMary, @byZeke] @authorNameSort.forEach (item, i) -> ok item is expected[i] test "get('length') returns the correct length", -> equal @authorNameSort.get('length'), 4 test "toArray() returns the correct order", -> expected = [@byFred, @anotherByFred, @byMary, @byZeke] deepEqual @authorNameSort.toArray(), expected setSortOnObservableSetSuite = -> test "get('length') returns the correct length when items are added to the underlying set", -> @base.add @byJill equal @authorNameSort.get('length'), 5 test "get('length') returns the correct length when items are removed from the underlying set", -> @base.remove @byFred equal @authorNameSort.get('length'), 3 test "get('length') returns the correct length when items are added to the set via the set sort proxy", -> @authorNameSort.add @byJill equal @authorNameSort.get('length'), 5 test "get('length') returns the correct length when items are added to the set via the set sort proxy", -> @authorNameSort.remove @byFred equal @authorNameSort.get('length'), 3 test "toArray() includes newly added items in the correct order", -> @base.add @byJill expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke'] deepEqual @authorNameSort.mapToProperty('author.name'), expected @base.add @anotherByZeke expected = ['Fred', 'Fred', 'Jill', 'Mary', 'Zeke', 'Zeke'] deepEqual @authorNameSort.mapToProperty('author.name'), expected test "toArray() does not include items which have been removed", -> @base.remove @anotherByFred expected = [@byFred, @byMary, @byZeke] equal @authorNameSort.toArray().length, 3 deepEqual @authorNameSort.toArray(), expected @base.remove @byZeke expected = [@byFred, @byMary] equal @authorNameSort.toArray().length, 2 deepEqual @authorNameSort.toArray(), expected test "toArray causes accessor to recalculate when order changes", -> @authorNameSort.accessor 'firstTwoNames', -> firstTwo = @toArray().slice(0,2) firstTwo.map((x) -> x.get('author.name')) deepEqual @authorNameSort.get('firstTwoNames'), ["Fred", "Fred"], "it starts with the first two" @base.remove(@byFred) deepEqual @authorNameSort.get('firstTwoNames'), ["Fred", "Mary"], "Removal causes an update" @base.add(Batman(author: @bobs)) deepEqual @authorNameSort.get('firstTwoNames'), ["Bobs", "Fred"], "Addition causes an update" @byZeke.set('author.name', "Aaron") deepEqual @authorNameSort.get('firstTwoNames'), ["Aaron", "Bobs"], "Modification causes an update" test "setting a new value of the sorted property on one of the items triggers an update", -> switchedAuthorToBobs = @anotherByFred switchedAuthorToBobs.set('author', @bobs) expected = [switchedAuthorToBobs, @byFred, @byMary, @byZeke] deepEqual @authorNameSort.toArray(), expected test "setting a new value of the sorted property on an item which has been removed should not trigger an update", -> @base.remove @anotherByFred reIndex = spyOn(@authorNameSort, "_reIndex") @anotherByFred.set('author', @mary) equal reIndex.called, false expected = [@byFred, @byMary, @byZeke] deepEqual @authorNameSort.toArray(), expected test "adding a few new values to the set should never _reIndex()", -> @authorNameSort.remove @anotherByFred reIndex = spyOn(@authorNameSort, "_reIndex") @authorNameSort.add(@anotherByFred) equal reIndex.callCount, 0 @authorNameSort.add(@byJill, @anotherByZeke) equal reIndex.callCount, 0 test "stopObserving() forgets all observers", -> @authorNameSort.stopObserving() expected = [@byFred, @anotherByFred, @byMary, @byZeke] @base.add @byJill deepEqual @authorNameSort.toArray(), expected @base.remove @byZeke deepEqual @authorNameSort.toArray(), expected @byFred.set('author', @mary) deepEqual @authorNameSort.toArray(), expected test 'mappedTo returns a SetMapping', -> expected = ["Fred", "Mary", "Zeke"] mapping = @authorNameSort.mappedTo('author.name') equal mapping.get('length'), 3 for name in expected ok mapping.has(name) @base.remove(@byMary) ok !mapping.has('Mary') @base.remove(@byFred, @anotherByFred) ok !mapping.has('Fred') @base.add(@byMary) ok mapping.has('Mary') test 'at(i) returns the item according to the sort', -> equal @authorNameSort.at(0).get('author.name'), "Fred" equal @authorNameSort.at(3).get('author.name'), "Zeke" @base.add(Batman(author: @bobs)) equal @authorNameSort.at(0).get('author.name'), "Bobs" test 'at accessor returns the item according to the sort', -> equal @authorNameSort.get('at.0.author.name'), "Fred" equal @authorNameSort.get('at.3.author.name'), "Zeke" @base.add(Batman(author: @bobs)) equal @authorNameSort.get('at.0.author.name'), "Bobs", "Adding causes update" @byMary.set('author.name', "Aaron") equal @authorNameSort.get('at.0.author.name'), "Aaron", "Update causes update" @base.remove(@byMary) equal @authorNameSort.get('at.0.author.name'), "Bobs", "Removal causes update" fixtureSetup = -> @zeke = Batman name: 'Zeke' @mary = Batman name: 'Mary' @fred = Batman name: 'Fred' @jill = Batman name: 'Jill' @bobs = Batman name: 'Bobs' @byZeke = Batman author: @zeke @byMary = Batman author: @mary @byFred = Batman author: @fred, prop: "byFred" @anotherByFred = Batman author: @fred, prop: "anotherByFred" # not yet in the set: @byJill = Batman author: @jill @anotherByZeke = Batman author: @zeke QUnit.module 'Batman.SetSort on a Batman.Set', setup: -> fixtureSetup.call(@) @base = new Batman.Set([@byMary, @byFred, @byZeke, @anotherByFred]) @authorNameSort = new Batman.SetSort(@base, 'author.name') setSortSuite() setSortOnObservableSetSuite() QUnit.module 'Batman.SetSort on a Batman.SimpleSet', setup: -> fixtureSetup.call(@) @base = new Batman.SimpleSet([@byMary, @byFred, @byZeke, @anotherByFred]) @authorNameSort = new Batman.SetSort(@base, 'author.name') setSortSuite() QUnit.module 'Batman.SetSort specific methods' test "toArray() returns the correct order when sorting on key which returns a function by calling the function", -> class Test constructor: (@name) -> getName: -> @name a = new Test('a') b = new Test('b') c = new Test('c') base = new Batman.Set([b, a, c]) sorted = base.sortedBy('getName') deepEqual sorted.toArray(), [a, b, c] test "toArray() returns the correct order when sorting on the 'valueOf' key to sort primitives", -> @base = new Batman.Set(['b', 'c', 'a']) sorted = @base.sortedBy('valueOf') deepEqual sorted.toArray(), ['a', 'b', 'c'] test "_indexOfItem returns the correct index", -> arr = [1, 3, 5, 6, 7, 8, 10] set = new Batman.Set(arr).sortedBy('') equal set._indexOfItem(4), -1 equal arr[set._indexOfItem(1)], 1 equal arr[set._indexOfItem(3)], 3 equal arr[set._indexOfItem(5)], 5 equal arr[set._indexOfItem(6)], 6 equal arr[set._indexOfItem(7)], 7 arr = [1, 2] set = new Batman.Set(arr).sortedBy('') equal arr[set._indexOfItem(1)], 1 equal arr[set._indexOfItem(2)], 2 test "_indexOfItem returns the correct item for duplicate keys", -> arr = [a = {key: 1}, b = {key: 1}, c = {key: 1}, d = {key: 1}, e = {key: 1}] set = new Batman.Set(arr).sortedBy('key') equal arr[set._indexOfItem(a)], a equal arr[set._indexOfItem(b)], b equal arr[set._indexOfItem(c)], c equal arr[set._indexOfItem(d)], d equal arr[set._indexOfItem(e)], e arr = [a = {key: 0}, b = {key: 1}, c = {key: 1}, d = {key: 4}, e = {key: 5}] set = new Batman.Set(arr).sortedBy('key') equal arr[set._indexOfItem(a)], a equal arr[set._indexOfItem(b)], b equal arr[set._indexOfItem(c)], c equal arr[set._indexOfItem(d)], d equal arr[set._indexOfItem(e)], e test "_indexOfItem calls _binarySearch", -> set = new Batman.Set([1, 2, 3]).sortedBy('') sinon.spy(Batman.SetSort, '_binarySearch') set._indexOfItem(1) ok Batman.SetSort._binarySearch.calledOnce Batman.SetSort._binarySearch.restore() test "SetSort._binarySearch returns the correct indexes for inexact searches", -> arr = [1, 2, 3, 6, 7, 8, 10] equal arr[Batman.SetSort._binarySearch(arr, 5, Batman.SetSort::compare).index], 6 equal arr[Batman.SetSort._binarySearch(arr, 9, Batman.SetSort::compare).index], 10 equal Batman.SetSort._binarySearch(arr, 11, Batman.SetSort::compare).index, arr.length
1433
assertSorted = (array, compareFunction) -> last = null for item, i in array if last ok compareFunction(last, item) < 1 last = item setSortSuite = -> test "new Batman.SetSort(set, key) constructs a sort on the set for that keypath", -> equal @authorNameSort.base, @base equal @authorNameSort.key, 'author.name' equal @authorNameSort.descending, no test "new Batman.SetSort(set, key, 'desc') constructs a reversed sort", -> reversedSort = new Batman.SetSort(@base, 'author.name', 'desc') equal reversedSort.base, @base equal reversedSort.key, 'author.name' equal reversedSort.descending, yes test "toArray() returns the sorted items", -> noName = Batman() anotherNoName = Batman() nullName = <NAME> author: <NAME> name: null naNName = <NAME> author: <NAME> name: NaN numberedName = <NAME> author: <NAME> name: 9 anotherNumberedName = <NAME>atman author: <NAME> name: 80 trueName = <NAME> author: <NAME> name: true falseName = <NAME>man author: <NAME> name: false @base.add noName @base.add nullName @base.add anotherNoName @base.add anotherNumberedName @base.add naNName @base.add numberedName @base.add trueName @base.add falseName @base.remove @anotherByFred assertSorted(@authorNameSort.toArray(), Batman.SetSort::compare) test "forEach(iterator) and toArray() go in reverse if sort is descending", -> noName = Batman() nullName = <NAME> author: <NAME> name: null naNName = <NAME> author: <NAME> name: NaN numberedName = <NAME>man author: <NAME> name: 9 anotherNumberedName = Batman author: <NAME> name: 80 trueName = <NAME> author: <NAME> name: true falseName = <NAME> author: <NAME> name: false @base.add noName @base.add nullName @base.add anotherNumberedName @base.add naNName @base.add numberedName @base.add trueName @base.add falseName @base.remove @anotherByFred descendingAuthorNameSort = new Batman.SetSort(@base, 'author.name', 'desc') sorted = descendingAuthorNameSort.toArray() assertSorted(sorted, (a,b) -> Batman.SetSort::compare(b,a)) collector = [] descendingAuthorNameSort.forEach (item) -> collector.push(item) deepEqual sorted, collector test "forEach(iterator) loops in the correct order", -> expect 4 expected = [@byFred, @anotherByF<NAME>, @byM<NAME>, @byZeke] @authorNameSort.forEach (item, i) -> ok item is expected[i] test "get('length') returns the correct length", -> equal @authorNameSort.get('length'), 4 test "toArray() returns the correct order", -> expected = [@byFred, @anotherByF<NAME>, @byM<NAME>, @byZeke] deepEqual @authorNameSort.toArray(), expected setSortOnObservableSetSuite = -> test "get('length') returns the correct length when items are added to the underlying set", -> @base.add @byJill equal @authorNameSort.get('length'), 5 test "get('length') returns the correct length when items are removed from the underlying set", -> @base.remove @byFred equal @authorNameSort.get('length'), 3 test "get('length') returns the correct length when items are added to the set via the set sort proxy", -> @authorNameSort.add @byJill equal @authorNameSort.get('length'), 5 test "get('length') returns the correct length when items are added to the set via the set sort proxy", -> @authorNameSort.remove @byF<NAME> equal @authorNameSort.get('length'), 3 test "toArray() includes newly added items in the correct order", -> @base.add @byJill expected = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] deepEqual @authorNameSort.mapToProperty('author.name'), expected @base.add @anotherByZeke expected = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] deepEqual @authorNameSort.mapToProperty('author.name'), expected test "toArray() does not include items which have been removed", -> @base.remove @anotherByFred expected = [@byFred, @byMary, @byZeke] equal @authorNameSort.toArray().length, 3 deepEqual @authorNameSort.toArray(), expected @base.remove @byZeke expected = [@byFred, @byMary] equal @authorNameSort.toArray().length, 2 deepEqual @authorNameSort.toArray(), expected test "toArray causes accessor to recalculate when order changes", -> @authorNameSort.accessor 'firstTwoNames', -> firstTwo = @toArray().slice(0,2) firstTwo.map((x) -> x.get('author.name')) deepEqual @authorNameSort.get('firstTwoNames'), ["<NAME>", "<NAME>"], "it starts with the first two" @base.remove(@byFred) deepEqual @authorNameSort.get('firstTwoNames'), ["<NAME>", "<NAME>"], "Removal causes an update" @base.add(Batman(author: @bobs)) deepEqual @authorNameSort.get('firstTwoNames'), ["<NAME>", "<NAME>"], "Addition causes an update" @byZeke.set('author.name', "<NAME>") deepEqual @authorNameSort.get('firstTwoNames'), ["<NAME>", "<NAME>"], "Modification causes an update" test "setting a new value of the sorted property on one of the items triggers an update", -> switchedAuthorToBobs = @anotherByFred switchedAuthorToBobs.set('author', @bobs) expected = [switchedAuthorToBobs, @byFred, @byM<NAME>, @byZeke] deepEqual @authorNameSort.toArray(), expected test "setting a new value of the sorted property on an item which has been removed should not trigger an update", -> @base.remove @anotherByFred reIndex = spyOn(@authorNameSort, "_reIndex") @anotherByFred.set('author', @mary) equal reIndex.called, false expected = [@byFred, @byMary, @byZeke] deepEqual @authorNameSort.toArray(), expected test "adding a few new values to the set should never _reIndex()", -> @authorNameSort.remove @anotherByFred reIndex = spyOn(@authorNameSort, "_reIndex") @authorNameSort.add(@anotherByFred) equal reIndex.callCount, 0 @authorNameSort.add(@byJill, @anotherByZeke) equal reIndex.callCount, 0 test "stopObserving() forgets all observers", -> @authorNameSort.stopObserving() expected = [@byFred, @anotherByFred, @byMary, @byZeke] @base.add @byJill deepEqual @authorNameSort.toArray(), expected @base.remove @byZeke deepEqual @authorNameSort.toArray(), expected @byFred.set('author', @mary) deepEqual @authorNameSort.toArray(), expected test 'mappedTo returns a SetMapping', -> expected = ["<NAME>", "<NAME>", "<NAME>"] mapping = @authorNameSort.mappedTo('author.name') equal mapping.get('length'), 3 for name in expected ok mapping.has(name) @base.remove(@byMary) ok !mapping.has('M<NAME>') @base.remove(@byFred, @anotherByFred) ok !mapping.has('<NAME>') @base.add(@byMary) ok mapping.has('<NAME>') test 'at(i) returns the item according to the sort', -> equal @authorNameSort.at(0).get('author.name'), "<NAME>" equal @authorNameSort.at(3).get('author.name'), "<NAME>" @base.add(Batman(author: @bobs)) equal @authorNameSort.at(0).get('author.name'), "<NAME>" test 'at accessor returns the item according to the sort', -> equal @authorNameSort.get('at.0.author.name'), "<NAME>" equal @authorNameSort.get('at.3.author.name'), "<NAME>" @base.add(Batman(author: @bobs)) equal @authorNameSort.get('at.0.author.name'), "B<NAME>", "Adding causes update" @byMary.set('author.name', "<NAME>") equal @authorNameSort.get('at.0.author.name'), "<NAME>", "Update causes update" @base.remove(@byMary) equal @authorNameSort.get('at.0.author.name'), "Bobs", "Removal causes update" fixtureSetup = -> @zeke = Batman name: '<NAME>' @mary = Batman name: '<NAME>' @fred = Batman name: '<NAME>' @jill = Batman name: '<NAME>' @bobs = Batman name: '<NAME>' @byZeke = Batman author: @zeke @byMary = Batman author: @mary @byFred = Batman author: @fred, prop: "byFred" @anotherByFred = Batman author: @fred, prop: "anotherByFred" # not yet in the set: @byJill = Batman author: @jill @anotherByZeke = Batman author: @zeke QUnit.module 'Batman.SetSort on a Batman.Set', setup: -> fixtureSetup.call(@) @base = new Batman.Set([@byMary, @byFred, @byZeke, @anotherByFred]) @authorNameSort = new Batman.SetSort(@base, 'author.name') setSortSuite() setSortOnObservableSetSuite() QUnit.module 'Batman.SetSort on a Batman.SimpleSet', setup: -> fixtureSetup.call(@) @base = new Batman.SimpleSet([@by<NAME>, @by<NAME>, @byZeke, @anotherBy<NAME>red]) @authorNameSort = new Batman.SetSort(@base, 'author.name') setSortSuite() QUnit.module 'Batman.SetSort specific methods' test "toArray() returns the correct order when sorting on key which returns a function by calling the function", -> class Test constructor: (@name) -> getName: -> @name a = new Test('a') b = new Test('b') c = new Test('c') base = new Batman.Set([b, a, c]) sorted = base.sortedBy('getName') deepEqual sorted.toArray(), [a, b, c] test "toArray() returns the correct order when sorting on the 'valueOf' key to sort primitives", -> @base = new Batman.Set(['b', 'c', 'a']) sorted = @base.sortedBy('valueOf') deepEqual sorted.toArray(), ['a', 'b', 'c'] test "_indexOfItem returns the correct index", -> arr = [1, 3, 5, 6, 7, 8, 10] set = new Batman.Set(arr).sortedBy('') equal set._indexOfItem(4), -1 equal arr[set._indexOfItem(1)], 1 equal arr[set._indexOfItem(3)], 3 equal arr[set._indexOfItem(5)], 5 equal arr[set._indexOfItem(6)], 6 equal arr[set._indexOfItem(7)], 7 arr = [1, 2] set = new Batman.Set(arr).sortedBy('') equal arr[set._indexOfItem(1)], 1 equal arr[set._indexOfItem(2)], 2 test "_indexOfItem returns the correct item for duplicate keys", -> arr = [a = {key: 1}, b = {key: 1}, c = {key: 1}, d = {key: 1}, e = {key: 1}] set = new Batman.Set(arr).sortedBy('key') equal arr[set._indexOfItem(a)], a equal arr[set._indexOfItem(b)], b equal arr[set._indexOfItem(c)], c equal arr[set._indexOfItem(d)], d equal arr[set._indexOfItem(e)], e arr = [a = {key: 0}, b = {key: 1}, c = {key: 1}, d = {key: 4}, e = {key: 5}] set = new Batman.Set(arr).sortedBy('key') equal arr[set._indexOfItem(a)], a equal arr[set._indexOfItem(b)], b equal arr[set._indexOfItem(c)], c equal arr[set._indexOfItem(d)], d equal arr[set._indexOfItem(e)], e test "_indexOfItem calls _binarySearch", -> set = new Batman.Set([1, 2, 3]).sortedBy('') sinon.spy(Batman.SetSort, '_binarySearch') set._indexOfItem(1) ok Batman.SetSort._binarySearch.calledOnce Batman.SetSort._binarySearch.restore() test "SetSort._binarySearch returns the correct indexes for inexact searches", -> arr = [1, 2, 3, 6, 7, 8, 10] equal arr[Batman.SetSort._binarySearch(arr, 5, Batman.SetSort::compare).index], 6 equal arr[Batman.SetSort._binarySearch(arr, 9, Batman.SetSort::compare).index], 10 equal Batman.SetSort._binarySearch(arr, 11, Batman.SetSort::compare).index, arr.length
true
assertSorted = (array, compareFunction) -> last = null for item, i in array if last ok compareFunction(last, item) < 1 last = item setSortSuite = -> test "new Batman.SetSort(set, key) constructs a sort on the set for that keypath", -> equal @authorNameSort.base, @base equal @authorNameSort.key, 'author.name' equal @authorNameSort.descending, no test "new Batman.SetSort(set, key, 'desc') constructs a reversed sort", -> reversedSort = new Batman.SetSort(@base, 'author.name', 'desc') equal reversedSort.base, @base equal reversedSort.key, 'author.name' equal reversedSort.descending, yes test "toArray() returns the sorted items", -> noName = Batman() anotherNoName = Batman() nullName = PI:NAME:<NAME>END_PI author: PI:NAME:<NAME>END_PI name: null naNName = PI:NAME:<NAME>END_PI author: PI:NAME:<NAME>END_PI name: NaN numberedName = PI:NAME:<NAME>END_PI author: PI:NAME:<NAME>END_PI name: 9 anotherNumberedName = PI:NAME:<NAME>END_PIatman author: PI:NAME:<NAME>END_PI name: 80 trueName = PI:NAME:<NAME>END_PI author: PI:NAME:<NAME>END_PI name: true falseName = PI:NAME:<NAME>END_PIman author: PI:NAME:<NAME>END_PI name: false @base.add noName @base.add nullName @base.add anotherNoName @base.add anotherNumberedName @base.add naNName @base.add numberedName @base.add trueName @base.add falseName @base.remove @anotherByFred assertSorted(@authorNameSort.toArray(), Batman.SetSort::compare) test "forEach(iterator) and toArray() go in reverse if sort is descending", -> noName = Batman() nullName = PI:NAME:<NAME>END_PI author: PI:NAME:<NAME>END_PI name: null naNName = PI:NAME:<NAME>END_PI author: PI:NAME:<NAME>END_PI name: NaN numberedName = PI:NAME:<NAME>END_PIman author: PI:NAME:<NAME>END_PI name: 9 anotherNumberedName = Batman author: PI:NAME:<NAME>END_PI name: 80 trueName = PI:NAME:<NAME>END_PI author: PI:NAME:<NAME>END_PI name: true falseName = PI:NAME:<NAME>END_PI author: PI:NAME:<NAME>END_PI name: false @base.add noName @base.add nullName @base.add anotherNumberedName @base.add naNName @base.add numberedName @base.add trueName @base.add falseName @base.remove @anotherByFred descendingAuthorNameSort = new Batman.SetSort(@base, 'author.name', 'desc') sorted = descendingAuthorNameSort.toArray() assertSorted(sorted, (a,b) -> Batman.SetSort::compare(b,a)) collector = [] descendingAuthorNameSort.forEach (item) -> collector.push(item) deepEqual sorted, collector test "forEach(iterator) loops in the correct order", -> expect 4 expected = [@byFred, @anotherByFPI:NAME:<NAME>END_PI, @byMPI:NAME:<NAME>END_PI, @byZeke] @authorNameSort.forEach (item, i) -> ok item is expected[i] test "get('length') returns the correct length", -> equal @authorNameSort.get('length'), 4 test "toArray() returns the correct order", -> expected = [@byFred, @anotherByFPI:NAME:<NAME>END_PI, @byMPI:NAME:<NAME>END_PI, @byZeke] deepEqual @authorNameSort.toArray(), expected setSortOnObservableSetSuite = -> test "get('length') returns the correct length when items are added to the underlying set", -> @base.add @byJill equal @authorNameSort.get('length'), 5 test "get('length') returns the correct length when items are removed from the underlying set", -> @base.remove @byFred equal @authorNameSort.get('length'), 3 test "get('length') returns the correct length when items are added to the set via the set sort proxy", -> @authorNameSort.add @byJill equal @authorNameSort.get('length'), 5 test "get('length') returns the correct length when items are added to the set via the set sort proxy", -> @authorNameSort.remove @byFPI:NAME:<NAME>END_PI equal @authorNameSort.get('length'), 3 test "toArray() includes newly added items in the correct order", -> @base.add @byJill expected = ['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'] deepEqual @authorNameSort.mapToProperty('author.name'), expected @base.add @anotherByZeke expected = ['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'] deepEqual @authorNameSort.mapToProperty('author.name'), expected test "toArray() does not include items which have been removed", -> @base.remove @anotherByFred expected = [@byFred, @byMary, @byZeke] equal @authorNameSort.toArray().length, 3 deepEqual @authorNameSort.toArray(), expected @base.remove @byZeke expected = [@byFred, @byMary] equal @authorNameSort.toArray().length, 2 deepEqual @authorNameSort.toArray(), expected test "toArray causes accessor to recalculate when order changes", -> @authorNameSort.accessor 'firstTwoNames', -> firstTwo = @toArray().slice(0,2) firstTwo.map((x) -> x.get('author.name')) deepEqual @authorNameSort.get('firstTwoNames'), ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"], "it starts with the first two" @base.remove(@byFred) deepEqual @authorNameSort.get('firstTwoNames'), ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"], "Removal causes an update" @base.add(Batman(author: @bobs)) deepEqual @authorNameSort.get('firstTwoNames'), ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"], "Addition causes an update" @byZeke.set('author.name', "PI:NAME:<NAME>END_PI") deepEqual @authorNameSort.get('firstTwoNames'), ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"], "Modification causes an update" test "setting a new value of the sorted property on one of the items triggers an update", -> switchedAuthorToBobs = @anotherByFred switchedAuthorToBobs.set('author', @bobs) expected = [switchedAuthorToBobs, @byFred, @byMPI:NAME:<NAME>END_PI, @byZeke] deepEqual @authorNameSort.toArray(), expected test "setting a new value of the sorted property on an item which has been removed should not trigger an update", -> @base.remove @anotherByFred reIndex = spyOn(@authorNameSort, "_reIndex") @anotherByFred.set('author', @mary) equal reIndex.called, false expected = [@byFred, @byMary, @byZeke] deepEqual @authorNameSort.toArray(), expected test "adding a few new values to the set should never _reIndex()", -> @authorNameSort.remove @anotherByFred reIndex = spyOn(@authorNameSort, "_reIndex") @authorNameSort.add(@anotherByFred) equal reIndex.callCount, 0 @authorNameSort.add(@byJill, @anotherByZeke) equal reIndex.callCount, 0 test "stopObserving() forgets all observers", -> @authorNameSort.stopObserving() expected = [@byFred, @anotherByFred, @byMary, @byZeke] @base.add @byJill deepEqual @authorNameSort.toArray(), expected @base.remove @byZeke deepEqual @authorNameSort.toArray(), expected @byFred.set('author', @mary) deepEqual @authorNameSort.toArray(), expected test 'mappedTo returns a SetMapping', -> expected = ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] mapping = @authorNameSort.mappedTo('author.name') equal mapping.get('length'), 3 for name in expected ok mapping.has(name) @base.remove(@byMary) ok !mapping.has('MPI:NAME:<NAME>END_PI') @base.remove(@byFred, @anotherByFred) ok !mapping.has('PI:NAME:<NAME>END_PI') @base.add(@byMary) ok mapping.has('PI:NAME:<NAME>END_PI') test 'at(i) returns the item according to the sort', -> equal @authorNameSort.at(0).get('author.name'), "PI:NAME:<NAME>END_PI" equal @authorNameSort.at(3).get('author.name'), "PI:NAME:<NAME>END_PI" @base.add(Batman(author: @bobs)) equal @authorNameSort.at(0).get('author.name'), "PI:NAME:<NAME>END_PI" test 'at accessor returns the item according to the sort', -> equal @authorNameSort.get('at.0.author.name'), "PI:NAME:<NAME>END_PI" equal @authorNameSort.get('at.3.author.name'), "PI:NAME:<NAME>END_PI" @base.add(Batman(author: @bobs)) equal @authorNameSort.get('at.0.author.name'), "BPI:NAME:<NAME>END_PI", "Adding causes update" @byMary.set('author.name', "PI:NAME:<NAME>END_PI") equal @authorNameSort.get('at.0.author.name'), "PI:NAME:<NAME>END_PI", "Update causes update" @base.remove(@byMary) equal @authorNameSort.get('at.0.author.name'), "Bobs", "Removal causes update" fixtureSetup = -> @zeke = Batman name: 'PI:NAME:<NAME>END_PI' @mary = Batman name: 'PI:NAME:<NAME>END_PI' @fred = Batman name: 'PI:NAME:<NAME>END_PI' @jill = Batman name: 'PI:NAME:<NAME>END_PI' @bobs = Batman name: 'PI:NAME:<NAME>END_PI' @byZeke = Batman author: @zeke @byMary = Batman author: @mary @byFred = Batman author: @fred, prop: "byFred" @anotherByFred = Batman author: @fred, prop: "anotherByFred" # not yet in the set: @byJill = Batman author: @jill @anotherByZeke = Batman author: @zeke QUnit.module 'Batman.SetSort on a Batman.Set', setup: -> fixtureSetup.call(@) @base = new Batman.Set([@byMary, @byFred, @byZeke, @anotherByFred]) @authorNameSort = new Batman.SetSort(@base, 'author.name') setSortSuite() setSortOnObservableSetSuite() QUnit.module 'Batman.SetSort on a Batman.SimpleSet', setup: -> fixtureSetup.call(@) @base = new Batman.SimpleSet([@byPI:NAME:<NAME>END_PI, @byPI:NAME:<NAME>END_PI, @byZeke, @anotherByPI:NAME:<NAME>END_PIred]) @authorNameSort = new Batman.SetSort(@base, 'author.name') setSortSuite() QUnit.module 'Batman.SetSort specific methods' test "toArray() returns the correct order when sorting on key which returns a function by calling the function", -> class Test constructor: (@name) -> getName: -> @name a = new Test('a') b = new Test('b') c = new Test('c') base = new Batman.Set([b, a, c]) sorted = base.sortedBy('getName') deepEqual sorted.toArray(), [a, b, c] test "toArray() returns the correct order when sorting on the 'valueOf' key to sort primitives", -> @base = new Batman.Set(['b', 'c', 'a']) sorted = @base.sortedBy('valueOf') deepEqual sorted.toArray(), ['a', 'b', 'c'] test "_indexOfItem returns the correct index", -> arr = [1, 3, 5, 6, 7, 8, 10] set = new Batman.Set(arr).sortedBy('') equal set._indexOfItem(4), -1 equal arr[set._indexOfItem(1)], 1 equal arr[set._indexOfItem(3)], 3 equal arr[set._indexOfItem(5)], 5 equal arr[set._indexOfItem(6)], 6 equal arr[set._indexOfItem(7)], 7 arr = [1, 2] set = new Batman.Set(arr).sortedBy('') equal arr[set._indexOfItem(1)], 1 equal arr[set._indexOfItem(2)], 2 test "_indexOfItem returns the correct item for duplicate keys", -> arr = [a = {key: 1}, b = {key: 1}, c = {key: 1}, d = {key: 1}, e = {key: 1}] set = new Batman.Set(arr).sortedBy('key') equal arr[set._indexOfItem(a)], a equal arr[set._indexOfItem(b)], b equal arr[set._indexOfItem(c)], c equal arr[set._indexOfItem(d)], d equal arr[set._indexOfItem(e)], e arr = [a = {key: 0}, b = {key: 1}, c = {key: 1}, d = {key: 4}, e = {key: 5}] set = new Batman.Set(arr).sortedBy('key') equal arr[set._indexOfItem(a)], a equal arr[set._indexOfItem(b)], b equal arr[set._indexOfItem(c)], c equal arr[set._indexOfItem(d)], d equal arr[set._indexOfItem(e)], e test "_indexOfItem calls _binarySearch", -> set = new Batman.Set([1, 2, 3]).sortedBy('') sinon.spy(Batman.SetSort, '_binarySearch') set._indexOfItem(1) ok Batman.SetSort._binarySearch.calledOnce Batman.SetSort._binarySearch.restore() test "SetSort._binarySearch returns the correct indexes for inexact searches", -> arr = [1, 2, 3, 6, 7, 8, 10] equal arr[Batman.SetSort._binarySearch(arr, 5, Batman.SetSort::compare).index], 6 equal arr[Batman.SetSort._binarySearch(arr, 9, Batman.SetSort::compare).index], 10 equal Batman.SetSort._binarySearch(arr, 11, Batman.SetSort::compare).index, arr.length
[ { "context": " }\n {\n 'comment': 'Funciones Parametros Varios'\n 'name': 'meta.function.lat'\n 'mat", "end": 3474, "score": 0.7496401071548462, "start": 3468, "tag": "NAME", "value": "Varios" } ]
AtomPlugin/grammars/lat.cson
jarriztg/testing-latino
0
'scopeName': 'source.lat' 'name': 'latino' 'comment': 'latino syntax: version 0.1' 'fileTypes': [ 'lat' ] 'firstLineMatch': '^#!.*\\blat' 'patterns': [ { 'comment': 'Comentarios' 'name': 'comment.line.number-sign.lat' 'match': '(#).*$\n?' 'captures': { '1': { 'name': 'comment.line.number-sign.lat' } } } { 'comment': 'Comillas' 'name': 'string.quoted.double.lat' 'begin': '"' 'end': '"' 'captures': { '1': { 'name': 'string.quoted.double.lat' } } } { 'comment': 'Comillas' 'name': 'string.quoted.single.lat' 'begin': "'", 'end': "'", 'captures': { '1': { 'name': 'string.quoted.single.lat' } } } { 'comment': 'Constantes' 'name': 'support.constant.lat' 'match': '\\b([A-Z]|[A-Z] )+\\b' 'captures': { '1': { 'name': 'support.constant.lat' } } } { 'comment': 'Constantes Numericas. LOS NUMEROS' 'name': 'constant.numeric.lat' 'match':'\\b(\d+)\\b' 'captures': { '1': { 'name': 'support.other.lat' } } } { 'comment': 'Constantes Logicas' 'name': 'constant.language.lat' 'match':'\\b(verdadero|falso)\\b' 'captures': { '1': { 'name': 'constant.language.lat' } } } { 'comment': 'Sentencias de control' 'name': 'keyword.control.lat' 'match': '\\b(si|sino|fin|mientras|desde|hasta|elegir|caso|defecto|hacer|cuando|retorno|romper|defecto|salto)\\b' 'captures': { '1': { 'name': 'keyword.control.lat' } } } { 'comment': 'Tipo de datos' 'name': 'meta.type.lat' 'match': '\\b(logico|entero|decimal|caracter|cadena)' 'captures': { '1': { 'name': 'support.type.lat' } } } { 'comment': 'Operadores' 'name': 'meta.type.lat' 'match': '(\\+|\-|\\*|\\/|\%|\&|(?:==)|(?:\:)|(?:!=)|(?:>=)|(?:<=)|\<|\>|\=|\.|\|)' 'captures': { '1': { 'name': 'keyword.operator.lat' } } } { 'comment': 'Clases' 'name': 'meta.class.lat', 'match': '(clase)' 'captures': { '1': { 'name': 'storage.type.class.lat' } } } { 'comment': 'Clases Propiedades' 'name': 'meta.class.lat', 'match': '(propiedad|constructor|esta)' 'captures': { '1': { 'name': 'storage.modifier.lat' } } } { 'comment': 'Funcion' 'name': 'meta.function.lat' 'match': '^(funcion)' 'captures': { '1': { 'name': 'storage.type.function.lat' } } } { 'comment': 'Funciones Nombres' 'name': 'meta.function.lat' 'match': '([a-zA-Z]+[a-zA-Z0-9_]|[a-zA-Z]+[a-zA-Z0-9_] ) +', 'captures': { '1': { 'name': 'entity.name.function.lat' } } } { 'comment': 'Funciones Parametros Varios' 'name': 'meta.function.lat' 'match': '([a-zA-Z]+[a-zA-Z0-9_]), (?=logico|entero|decimal|caracter|cadena)' 'captures': { '1': { 'name': 'variable.parameter.function.lat' } } } { 'comment': 'Funciones Parametro Unico' 'name': 'meta.function.lat' 'match': '([a-zA-Z]+[a-zA-Z0-9_])' 'captures': { '1': { 'name': 'variable.parameter.function.lat' } } } { 'comment': 'Funciones Parametro Unico Letra' 'name': 'meta.function.lat' 'match': '([a-zA-Z])' 'captures': { '1': { 'name': 'variable.parameter.function.lat' } } } ]
161317
'scopeName': 'source.lat' 'name': 'latino' 'comment': 'latino syntax: version 0.1' 'fileTypes': [ 'lat' ] 'firstLineMatch': '^#!.*\\blat' 'patterns': [ { 'comment': 'Comentarios' 'name': 'comment.line.number-sign.lat' 'match': '(#).*$\n?' 'captures': { '1': { 'name': 'comment.line.number-sign.lat' } } } { 'comment': 'Comillas' 'name': 'string.quoted.double.lat' 'begin': '"' 'end': '"' 'captures': { '1': { 'name': 'string.quoted.double.lat' } } } { 'comment': 'Comillas' 'name': 'string.quoted.single.lat' 'begin': "'", 'end': "'", 'captures': { '1': { 'name': 'string.quoted.single.lat' } } } { 'comment': 'Constantes' 'name': 'support.constant.lat' 'match': '\\b([A-Z]|[A-Z] )+\\b' 'captures': { '1': { 'name': 'support.constant.lat' } } } { 'comment': 'Constantes Numericas. LOS NUMEROS' 'name': 'constant.numeric.lat' 'match':'\\b(\d+)\\b' 'captures': { '1': { 'name': 'support.other.lat' } } } { 'comment': 'Constantes Logicas' 'name': 'constant.language.lat' 'match':'\\b(verdadero|falso)\\b' 'captures': { '1': { 'name': 'constant.language.lat' } } } { 'comment': 'Sentencias de control' 'name': 'keyword.control.lat' 'match': '\\b(si|sino|fin|mientras|desde|hasta|elegir|caso|defecto|hacer|cuando|retorno|romper|defecto|salto)\\b' 'captures': { '1': { 'name': 'keyword.control.lat' } } } { 'comment': 'Tipo de datos' 'name': 'meta.type.lat' 'match': '\\b(logico|entero|decimal|caracter|cadena)' 'captures': { '1': { 'name': 'support.type.lat' } } } { 'comment': 'Operadores' 'name': 'meta.type.lat' 'match': '(\\+|\-|\\*|\\/|\%|\&|(?:==)|(?:\:)|(?:!=)|(?:>=)|(?:<=)|\<|\>|\=|\.|\|)' 'captures': { '1': { 'name': 'keyword.operator.lat' } } } { 'comment': 'Clases' 'name': 'meta.class.lat', 'match': '(clase)' 'captures': { '1': { 'name': 'storage.type.class.lat' } } } { 'comment': 'Clases Propiedades' 'name': 'meta.class.lat', 'match': '(propiedad|constructor|esta)' 'captures': { '1': { 'name': 'storage.modifier.lat' } } } { 'comment': 'Funcion' 'name': 'meta.function.lat' 'match': '^(funcion)' 'captures': { '1': { 'name': 'storage.type.function.lat' } } } { 'comment': 'Funciones Nombres' 'name': 'meta.function.lat' 'match': '([a-zA-Z]+[a-zA-Z0-9_]|[a-zA-Z]+[a-zA-Z0-9_] ) +', 'captures': { '1': { 'name': 'entity.name.function.lat' } } } { 'comment': 'Funciones Parametros <NAME>' 'name': 'meta.function.lat' 'match': '([a-zA-Z]+[a-zA-Z0-9_]), (?=logico|entero|decimal|caracter|cadena)' 'captures': { '1': { 'name': 'variable.parameter.function.lat' } } } { 'comment': 'Funciones Parametro Unico' 'name': 'meta.function.lat' 'match': '([a-zA-Z]+[a-zA-Z0-9_])' 'captures': { '1': { 'name': 'variable.parameter.function.lat' } } } { 'comment': 'Funciones Parametro Unico Letra' 'name': 'meta.function.lat' 'match': '([a-zA-Z])' 'captures': { '1': { 'name': 'variable.parameter.function.lat' } } } ]
true
'scopeName': 'source.lat' 'name': 'latino' 'comment': 'latino syntax: version 0.1' 'fileTypes': [ 'lat' ] 'firstLineMatch': '^#!.*\\blat' 'patterns': [ { 'comment': 'Comentarios' 'name': 'comment.line.number-sign.lat' 'match': '(#).*$\n?' 'captures': { '1': { 'name': 'comment.line.number-sign.lat' } } } { 'comment': 'Comillas' 'name': 'string.quoted.double.lat' 'begin': '"' 'end': '"' 'captures': { '1': { 'name': 'string.quoted.double.lat' } } } { 'comment': 'Comillas' 'name': 'string.quoted.single.lat' 'begin': "'", 'end': "'", 'captures': { '1': { 'name': 'string.quoted.single.lat' } } } { 'comment': 'Constantes' 'name': 'support.constant.lat' 'match': '\\b([A-Z]|[A-Z] )+\\b' 'captures': { '1': { 'name': 'support.constant.lat' } } } { 'comment': 'Constantes Numericas. LOS NUMEROS' 'name': 'constant.numeric.lat' 'match':'\\b(\d+)\\b' 'captures': { '1': { 'name': 'support.other.lat' } } } { 'comment': 'Constantes Logicas' 'name': 'constant.language.lat' 'match':'\\b(verdadero|falso)\\b' 'captures': { '1': { 'name': 'constant.language.lat' } } } { 'comment': 'Sentencias de control' 'name': 'keyword.control.lat' 'match': '\\b(si|sino|fin|mientras|desde|hasta|elegir|caso|defecto|hacer|cuando|retorno|romper|defecto|salto)\\b' 'captures': { '1': { 'name': 'keyword.control.lat' } } } { 'comment': 'Tipo de datos' 'name': 'meta.type.lat' 'match': '\\b(logico|entero|decimal|caracter|cadena)' 'captures': { '1': { 'name': 'support.type.lat' } } } { 'comment': 'Operadores' 'name': 'meta.type.lat' 'match': '(\\+|\-|\\*|\\/|\%|\&|(?:==)|(?:\:)|(?:!=)|(?:>=)|(?:<=)|\<|\>|\=|\.|\|)' 'captures': { '1': { 'name': 'keyword.operator.lat' } } } { 'comment': 'Clases' 'name': 'meta.class.lat', 'match': '(clase)' 'captures': { '1': { 'name': 'storage.type.class.lat' } } } { 'comment': 'Clases Propiedades' 'name': 'meta.class.lat', 'match': '(propiedad|constructor|esta)' 'captures': { '1': { 'name': 'storage.modifier.lat' } } } { 'comment': 'Funcion' 'name': 'meta.function.lat' 'match': '^(funcion)' 'captures': { '1': { 'name': 'storage.type.function.lat' } } } { 'comment': 'Funciones Nombres' 'name': 'meta.function.lat' 'match': '([a-zA-Z]+[a-zA-Z0-9_]|[a-zA-Z]+[a-zA-Z0-9_] ) +', 'captures': { '1': { 'name': 'entity.name.function.lat' } } } { 'comment': 'Funciones Parametros PI:NAME:<NAME>END_PI' 'name': 'meta.function.lat' 'match': '([a-zA-Z]+[a-zA-Z0-9_]), (?=logico|entero|decimal|caracter|cadena)' 'captures': { '1': { 'name': 'variable.parameter.function.lat' } } } { 'comment': 'Funciones Parametro Unico' 'name': 'meta.function.lat' 'match': '([a-zA-Z]+[a-zA-Z0-9_])' 'captures': { '1': { 'name': 'variable.parameter.function.lat' } } } { 'comment': 'Funciones Parametro Unico Letra' 'name': 'meta.function.lat' 'match': '([a-zA-Z])' 'captures': { '1': { 'name': 'variable.parameter.function.lat' } } } ]
[ { "context": "epackage[utf8]{inputenc}\\n\\n\\\\title{42}\\n\\\\author{Jane Doe}\\n\\\\date{June 2011}\"\n\t\t\t\t@updateMerger.p.readFile", "end": 4695, "score": 0.9998135566711426, "start": 4687, "tag": "NAME", "value": "Jane Doe" } ]
test/unit/coffee/ThirdPartyDataStore/UpdateMergerTests.coffee
shyoshyo/web-sharelatex
1
Stream = require('stream') SandboxedModule = require('sandboxed-module') sinon = require('sinon') require('chai').should() modulePath = require('path').join __dirname, '../../../../app/js/Features/ThirdPartyDataStore/UpdateMerger.js' BufferedStream = require('bufferedstream') describe 'UpdateMerger :', -> beforeEach -> @updateMerger = SandboxedModule.require modulePath, requires: 'fs': @fs = unlink:sinon.stub().callsArgWith(1) 'logger-sharelatex': log: -> err: -> '../Editor/EditorController': @EditorController = {} '../Uploads/FileTypeManager':@FileTypeManager = {} '../../infrastructure/FileWriter': @FileWriter = {} '../Project/ProjectEntityHandler': @ProjectEntityHandler = {} 'settings-sharelatex':{path:{dumpPath:"dump_here"}} @project_id = "project_id_here" @user_id = "mock-user-id" @docPath = @newDocPath = "/folder/doc.tex" @filePath = @newFilePath = "/folder/file.png" @existingDocPath = '/folder/other.tex' @existingFilePath = '/folder/fig1.pdf' @linkedFileData = {provider: 'url'} @existingDocs = [ {path: '/main.tex'} {path: '/folder/other.tex'} ] @existingFiles = [ {path: '/figure.pdf'} {path: '/folder/fig1.pdf'} ] @ProjectEntityHandler.getAllEntities = sinon.stub().callsArgWith(1, null, @existingDocs, @existingFiles) @fsPath = "/tmp/file/path" @source = "dropbox" @updateRequest = new BufferedStream() @FileWriter.writeStreamToDisk = sinon.stub().yields(null, @fsPath) @callback = sinon.stub() describe 'mergeUpdate', -> describe "doc updates for a new doc", -> beforeEach -> @FileTypeManager.getType = sinon.stub().yields(null, false) @updateMerger.p.processDoc = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @docPath, @updateRequest, @source, @callback it 'should look at the file contents', -> @FileTypeManager.getType.called.should.equal true it 'should process update as doc', -> @updateMerger.p.processDoc .calledWith(@project_id, @user_id, @fsPath, @docPath, @source) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe "file updates for a new file ", -> beforeEach -> @FileTypeManager.getType = sinon.stub().yields(null, true) @updateMerger.p.processFile = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @filePath, @updateRequest, @source, @callback it 'should look at the file contents', -> @FileTypeManager.getType.called.should.equal true it 'should process update as file', -> @updateMerger.p.processFile .calledWith(@project_id, @fsPath, @filePath, @source, @user_id) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe "doc updates for an existing doc", -> beforeEach -> @FileTypeManager.getType = sinon.stub() @updateMerger.p.processDoc = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @existingDocPath, @updateRequest, @source, @callback it 'should not look at the file contents', -> @FileTypeManager.getType.called.should.equal false it 'should process update as doc', -> @updateMerger.p.processDoc .calledWith(@project_id, @user_id, @fsPath, @existingDocPath, @source) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe "file updates for an existing file", -> beforeEach -> @FileTypeManager.getType = sinon.stub() @updateMerger.p.processFile = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @existingFilePath, @updateRequest, @source, @callback it 'should not look at the file contents', -> @FileTypeManager.getType.called.should.equal false it 'should process update as file', -> @updateMerger.p.processFile .calledWith(@project_id, @fsPath, @existingFilePath, @source, @user_id) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe 'deleteUpdate', -> beforeEach -> @EditorController.deleteEntityWithPath = sinon.stub().yields() @updateMerger.deleteUpdate @user_id, @project_id, @docPath, @source, @callback it 'should delete the entity in the editor controller', -> @EditorController.deleteEntityWithPath .calledWith(@project_id, @docPath, @source, @user_id) .should.equal true describe 'private methods', -> describe 'processDoc', -> beforeEach -> @docLines = "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\n\\title{42}\n\\author{Jane Doe}\n\\date{June 2011}" @updateMerger.p.readFileIntoTextArray = sinon.stub().yields(null, @docLines) @EditorController.upsertDocWithPath = sinon.stub().yields() @updateMerger.p.processDoc @project_id, @user_id, @fsPath, @docPath, @source, @callback it 'reads the temp file from disk', -> @updateMerger.p.readFileIntoTextArray .calledWith(@fsPath) .should.equal true it 'should upsert the doc in the editor controller', -> @EditorController.upsertDocWithPath .calledWith(@project_id, @docPath, @docLines, @source, @user_id) .should.equal true describe 'processFile', -> beforeEach -> @EditorController.upsertFileWithPath = sinon.stub().yields() @updateMerger.p.processFile @project_id, @fsPath, @filePath, @source, @user_id, @callback it 'should upsert the file in the editor controller', -> @EditorController.upsertFileWithPath .calledWith(@project_id, @filePath, @fsPath, null, @source, @user_id) .should.equal true
179273
Stream = require('stream') SandboxedModule = require('sandboxed-module') sinon = require('sinon') require('chai').should() modulePath = require('path').join __dirname, '../../../../app/js/Features/ThirdPartyDataStore/UpdateMerger.js' BufferedStream = require('bufferedstream') describe 'UpdateMerger :', -> beforeEach -> @updateMerger = SandboxedModule.require modulePath, requires: 'fs': @fs = unlink:sinon.stub().callsArgWith(1) 'logger-sharelatex': log: -> err: -> '../Editor/EditorController': @EditorController = {} '../Uploads/FileTypeManager':@FileTypeManager = {} '../../infrastructure/FileWriter': @FileWriter = {} '../Project/ProjectEntityHandler': @ProjectEntityHandler = {} 'settings-sharelatex':{path:{dumpPath:"dump_here"}} @project_id = "project_id_here" @user_id = "mock-user-id" @docPath = @newDocPath = "/folder/doc.tex" @filePath = @newFilePath = "/folder/file.png" @existingDocPath = '/folder/other.tex' @existingFilePath = '/folder/fig1.pdf' @linkedFileData = {provider: 'url'} @existingDocs = [ {path: '/main.tex'} {path: '/folder/other.tex'} ] @existingFiles = [ {path: '/figure.pdf'} {path: '/folder/fig1.pdf'} ] @ProjectEntityHandler.getAllEntities = sinon.stub().callsArgWith(1, null, @existingDocs, @existingFiles) @fsPath = "/tmp/file/path" @source = "dropbox" @updateRequest = new BufferedStream() @FileWriter.writeStreamToDisk = sinon.stub().yields(null, @fsPath) @callback = sinon.stub() describe 'mergeUpdate', -> describe "doc updates for a new doc", -> beforeEach -> @FileTypeManager.getType = sinon.stub().yields(null, false) @updateMerger.p.processDoc = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @docPath, @updateRequest, @source, @callback it 'should look at the file contents', -> @FileTypeManager.getType.called.should.equal true it 'should process update as doc', -> @updateMerger.p.processDoc .calledWith(@project_id, @user_id, @fsPath, @docPath, @source) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe "file updates for a new file ", -> beforeEach -> @FileTypeManager.getType = sinon.stub().yields(null, true) @updateMerger.p.processFile = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @filePath, @updateRequest, @source, @callback it 'should look at the file contents', -> @FileTypeManager.getType.called.should.equal true it 'should process update as file', -> @updateMerger.p.processFile .calledWith(@project_id, @fsPath, @filePath, @source, @user_id) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe "doc updates for an existing doc", -> beforeEach -> @FileTypeManager.getType = sinon.stub() @updateMerger.p.processDoc = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @existingDocPath, @updateRequest, @source, @callback it 'should not look at the file contents', -> @FileTypeManager.getType.called.should.equal false it 'should process update as doc', -> @updateMerger.p.processDoc .calledWith(@project_id, @user_id, @fsPath, @existingDocPath, @source) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe "file updates for an existing file", -> beforeEach -> @FileTypeManager.getType = sinon.stub() @updateMerger.p.processFile = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @existingFilePath, @updateRequest, @source, @callback it 'should not look at the file contents', -> @FileTypeManager.getType.called.should.equal false it 'should process update as file', -> @updateMerger.p.processFile .calledWith(@project_id, @fsPath, @existingFilePath, @source, @user_id) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe 'deleteUpdate', -> beforeEach -> @EditorController.deleteEntityWithPath = sinon.stub().yields() @updateMerger.deleteUpdate @user_id, @project_id, @docPath, @source, @callback it 'should delete the entity in the editor controller', -> @EditorController.deleteEntityWithPath .calledWith(@project_id, @docPath, @source, @user_id) .should.equal true describe 'private methods', -> describe 'processDoc', -> beforeEach -> @docLines = "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\n\\title{42}\n\\author{<NAME>}\n\\date{June 2011}" @updateMerger.p.readFileIntoTextArray = sinon.stub().yields(null, @docLines) @EditorController.upsertDocWithPath = sinon.stub().yields() @updateMerger.p.processDoc @project_id, @user_id, @fsPath, @docPath, @source, @callback it 'reads the temp file from disk', -> @updateMerger.p.readFileIntoTextArray .calledWith(@fsPath) .should.equal true it 'should upsert the doc in the editor controller', -> @EditorController.upsertDocWithPath .calledWith(@project_id, @docPath, @docLines, @source, @user_id) .should.equal true describe 'processFile', -> beforeEach -> @EditorController.upsertFileWithPath = sinon.stub().yields() @updateMerger.p.processFile @project_id, @fsPath, @filePath, @source, @user_id, @callback it 'should upsert the file in the editor controller', -> @EditorController.upsertFileWithPath .calledWith(@project_id, @filePath, @fsPath, null, @source, @user_id) .should.equal true
true
Stream = require('stream') SandboxedModule = require('sandboxed-module') sinon = require('sinon') require('chai').should() modulePath = require('path').join __dirname, '../../../../app/js/Features/ThirdPartyDataStore/UpdateMerger.js' BufferedStream = require('bufferedstream') describe 'UpdateMerger :', -> beforeEach -> @updateMerger = SandboxedModule.require modulePath, requires: 'fs': @fs = unlink:sinon.stub().callsArgWith(1) 'logger-sharelatex': log: -> err: -> '../Editor/EditorController': @EditorController = {} '../Uploads/FileTypeManager':@FileTypeManager = {} '../../infrastructure/FileWriter': @FileWriter = {} '../Project/ProjectEntityHandler': @ProjectEntityHandler = {} 'settings-sharelatex':{path:{dumpPath:"dump_here"}} @project_id = "project_id_here" @user_id = "mock-user-id" @docPath = @newDocPath = "/folder/doc.tex" @filePath = @newFilePath = "/folder/file.png" @existingDocPath = '/folder/other.tex' @existingFilePath = '/folder/fig1.pdf' @linkedFileData = {provider: 'url'} @existingDocs = [ {path: '/main.tex'} {path: '/folder/other.tex'} ] @existingFiles = [ {path: '/figure.pdf'} {path: '/folder/fig1.pdf'} ] @ProjectEntityHandler.getAllEntities = sinon.stub().callsArgWith(1, null, @existingDocs, @existingFiles) @fsPath = "/tmp/file/path" @source = "dropbox" @updateRequest = new BufferedStream() @FileWriter.writeStreamToDisk = sinon.stub().yields(null, @fsPath) @callback = sinon.stub() describe 'mergeUpdate', -> describe "doc updates for a new doc", -> beforeEach -> @FileTypeManager.getType = sinon.stub().yields(null, false) @updateMerger.p.processDoc = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @docPath, @updateRequest, @source, @callback it 'should look at the file contents', -> @FileTypeManager.getType.called.should.equal true it 'should process update as doc', -> @updateMerger.p.processDoc .calledWith(@project_id, @user_id, @fsPath, @docPath, @source) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe "file updates for a new file ", -> beforeEach -> @FileTypeManager.getType = sinon.stub().yields(null, true) @updateMerger.p.processFile = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @filePath, @updateRequest, @source, @callback it 'should look at the file contents', -> @FileTypeManager.getType.called.should.equal true it 'should process update as file', -> @updateMerger.p.processFile .calledWith(@project_id, @fsPath, @filePath, @source, @user_id) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe "doc updates for an existing doc", -> beforeEach -> @FileTypeManager.getType = sinon.stub() @updateMerger.p.processDoc = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @existingDocPath, @updateRequest, @source, @callback it 'should not look at the file contents', -> @FileTypeManager.getType.called.should.equal false it 'should process update as doc', -> @updateMerger.p.processDoc .calledWith(@project_id, @user_id, @fsPath, @existingDocPath, @source) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe "file updates for an existing file", -> beforeEach -> @FileTypeManager.getType = sinon.stub() @updateMerger.p.processFile = sinon.stub().yields() @updateMerger.mergeUpdate @user_id, @project_id, @existingFilePath, @updateRequest, @source, @callback it 'should not look at the file contents', -> @FileTypeManager.getType.called.should.equal false it 'should process update as file', -> @updateMerger.p.processFile .calledWith(@project_id, @fsPath, @existingFilePath, @source, @user_id) .should.equal true it 'removes the temp file from disk', -> @fs.unlink.calledWith(@fsPath).should.equal true describe 'deleteUpdate', -> beforeEach -> @EditorController.deleteEntityWithPath = sinon.stub().yields() @updateMerger.deleteUpdate @user_id, @project_id, @docPath, @source, @callback it 'should delete the entity in the editor controller', -> @EditorController.deleteEntityWithPath .calledWith(@project_id, @docPath, @source, @user_id) .should.equal true describe 'private methods', -> describe 'processDoc', -> beforeEach -> @docLines = "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\n\\title{42}\n\\author{PI:NAME:<NAME>END_PI}\n\\date{June 2011}" @updateMerger.p.readFileIntoTextArray = sinon.stub().yields(null, @docLines) @EditorController.upsertDocWithPath = sinon.stub().yields() @updateMerger.p.processDoc @project_id, @user_id, @fsPath, @docPath, @source, @callback it 'reads the temp file from disk', -> @updateMerger.p.readFileIntoTextArray .calledWith(@fsPath) .should.equal true it 'should upsert the doc in the editor controller', -> @EditorController.upsertDocWithPath .calledWith(@project_id, @docPath, @docLines, @source, @user_id) .should.equal true describe 'processFile', -> beforeEach -> @EditorController.upsertFileWithPath = sinon.stub().yields() @updateMerger.p.processFile @project_id, @fsPath, @filePath, @source, @user_id, @callback it 'should upsert the file in the editor controller', -> @EditorController.upsertFileWithPath .calledWith(@project_id, @filePath, @fsPath, null, @source, @user_id) .should.equal true
[ { "context": "###\n * eventparser\n * https://github.com/1egoman/eventparser\n *\n * Copyright (c) 2015 Ryan Gaus\n *", "end": 48, "score": 0.9991946220397949, "start": 41, "tag": "USERNAME", "value": "1egoman" }, { "context": "b.com/1egoman/eventparser\n *\n * Copyright (c) 2015 Ryan Gaus\n * Licensed under the MIT license.\n###\n\n'use stri", "end": 95, "score": 0.9998657703399658, "start": 86, "tag": "NAME", "value": "Ryan Gaus" } ]
src/index.coffee
1egoman/eventparser
0
### * eventparser * https://github.com/1egoman/eventparser * * Copyright (c) 2015 Ryan Gaus * Licensed under the MIT license. ### 'use strict'; app = require("express")() chalk = require "chalk" path = require "path" bodyParser = require "body-parser" router = require './routes' exports.main = -> # set ejs as view engine app.set "view engine", "ejs" # include all the required middleware exports.middleware app # our routes app.use '/', router() # listen for requests PORT = process.argv.port or 8000 app.listen PORT, -> console.log chalk.blue "-> :#{PORT}" exports.middleware = (app) -> # json body parser app.use bodyParser.json() # include sass middleware to auto-compile sass stylesheets node_sass = require "node-sass-middleware" app.use node_sass src: path.join(__dirname, "../public"), dest: path.join(__dirname, "../public"), debug: true # serve static assets app.use require("express-static") path.join(__dirname, '../public') exports.main()
14174
### * eventparser * https://github.com/1egoman/eventparser * * Copyright (c) 2015 <NAME> * Licensed under the MIT license. ### 'use strict'; app = require("express")() chalk = require "chalk" path = require "path" bodyParser = require "body-parser" router = require './routes' exports.main = -> # set ejs as view engine app.set "view engine", "ejs" # include all the required middleware exports.middleware app # our routes app.use '/', router() # listen for requests PORT = process.argv.port or 8000 app.listen PORT, -> console.log chalk.blue "-> :#{PORT}" exports.middleware = (app) -> # json body parser app.use bodyParser.json() # include sass middleware to auto-compile sass stylesheets node_sass = require "node-sass-middleware" app.use node_sass src: path.join(__dirname, "../public"), dest: path.join(__dirname, "../public"), debug: true # serve static assets app.use require("express-static") path.join(__dirname, '../public') exports.main()
true
### * eventparser * https://github.com/1egoman/eventparser * * Copyright (c) 2015 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### 'use strict'; app = require("express")() chalk = require "chalk" path = require "path" bodyParser = require "body-parser" router = require './routes' exports.main = -> # set ejs as view engine app.set "view engine", "ejs" # include all the required middleware exports.middleware app # our routes app.use '/', router() # listen for requests PORT = process.argv.port or 8000 app.listen PORT, -> console.log chalk.blue "-> :#{PORT}" exports.middleware = (app) -> # json body parser app.use bodyParser.json() # include sass middleware to auto-compile sass stylesheets node_sass = require "node-sass-middleware" app.use node_sass src: path.join(__dirname, "../public"), dest: path.join(__dirname, "../public"), debug: true # serve static assets app.use require("express-static") path.join(__dirname, '../public') exports.main()
[ { "context": "abled by default.\n \"\"\"\n\n tokens: [ \"++\", \"--\" ]\n\n lintToken : (token, tokenApi) ->\n ", "end": 530, "score": 0.9759901762008667, "start": 530, "tag": "KEY", "value": "" }, { "context": "d by default.\n \"\"\"\n\n tokens: [ \"++\", \"--\" ]\n\n lintToken : (token, tokenApi) ->\n ", "end": 538, "score": 0.9733644127845764, "start": 535, "tag": "KEY", "value": "\"--" } ]
node_modules/coffeelint/src/rules/no_plusplus.coffee
buruno/site-cra
8
module.exports = class NoPlusPlus rule: name: 'no_plusplus' level : 'ignore' message : 'The increment and decrement operators are forbidden' description: """ This rule forbids the increment and decrement arithmetic operators. Some people believe the <tt>++</tt> and <tt>--</tt> to be cryptic and the cause of bugs due to misunderstandings of their precedence rules. This rule is disabled by default. """ tokens: [ "++", "--" ] lintToken : (token, tokenApi) -> return {context : "found '#{token[0]}'"}
72450
module.exports = class NoPlusPlus rule: name: 'no_plusplus' level : 'ignore' message : 'The increment and decrement operators are forbidden' description: """ This rule forbids the increment and decrement arithmetic operators. Some people believe the <tt>++</tt> and <tt>--</tt> to be cryptic and the cause of bugs due to misunderstandings of their precedence rules. This rule is disabled by default. """ tokens: [ "<KEY>++", <KEY>" ] lintToken : (token, tokenApi) -> return {context : "found '#{token[0]}'"}
true
module.exports = class NoPlusPlus rule: name: 'no_plusplus' level : 'ignore' message : 'The increment and decrement operators are forbidden' description: """ This rule forbids the increment and decrement arithmetic operators. Some people believe the <tt>++</tt> and <tt>--</tt> to be cryptic and the cause of bugs due to misunderstandings of their precedence rules. This rule is disabled by default. """ tokens: [ "PI:KEY:<KEY>END_PI++", PI:KEY:<KEY>END_PI" ] lintToken : (token, tokenApi) -> return {context : "found '#{token[0]}'"}
[ { "context": "g interface unit tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\neval(Test.bu", "end": 90, "score": 0.9998893141746521, "start": 73, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/core/test/events_test.coffee
lovely-io/lovely.io-stl
2
# # The events handling interface unit tests # # Copyright (C) 2011-2013 Nikolay Nemshilov # {Test,should} = require('lovely') eval(Test.build) Lovely = this.Lovely describe 'Events', # a dummy class to test the interface Dummy = new Lovely.Class include: Lovely.Events method: -> # some dummy method describe "#on", -> describe "\b('event', callback)", -> dummy = new Dummy() object = dummy.on('event', fun = ->) it "should return the same object back", -> object.should.equal dummy it "should start listen to the 'event'", -> object.ones('event', fun).should.be.true describe "\b('event', 'callback', arg1, arg2, arg3)", -> object = new Dummy().on('event', 'method', 1, 2, 3) it "should start listen to the 'event' with the 'method'", -> object.ones('event', object.method).should.be.true it "should stash the additional arguments for later use", -> object._listeners[0].a.should.eql [1,2,3] describe "\b('event1,event2', callback)", -> object = new Dummy().on('event1,event2', fun = ->) it "should start listening to the event1", -> object.ones('event1', fun).should.be.true it "should start listening to the event2", -> object.ones('event2', fun).should.be.true describe "\b({event1: callback1, event2: callback2})", -> object = new Dummy().on(event1: (fn1 = ->), event2: (fn2 = ->)) it "should start listening to the event1", -> object.ones('event1', fn1).should.be.true it "should start listening to the event2", -> object.ones('event2', fn2).should.be.true describe "#ones", -> describe "\b('event')", -> dummy = new Dummy() it "should return 'false' by default", -> dummy.ones('something').should.be.false it "should return 'true' when listens to the event", -> dummy.on('event', ->).ones('event').should.be.true describe "\b('event', callback)", -> object = new Dummy().on('event', fun = ->) it "should say 'true' for used callback", -> object.ones('event', fun).should.be.true it "should say 'false' for another callback", -> object.ones('event', ->).should.be.false describe "\b(callback)", -> object = new Dummy().on('event', cb = ->) it "should say 'true' for used callback", -> object.ones(cb).should.be.true it "should say 'false' for another callback", -> object.ones(->).should.be.false describe "#no", -> describe "\b('event')", -> dummy = this.dummy = new Dummy() .on('event', ->) .on('other', ->) object = dummy.no('event') it "should return the same object back", -> object.should.be.equal dummy it "should stop listening to the event", -> object.ones('event').should.be.false it "should not touch the 'other' event", -> object.ones('other').should.be.true describe "\b('event', callback)", -> object = new Dummy() .on('event', cb1 = ->) .on('event', cb2 = ->) .no('event', cb1) it "should stop listening to the first callback", -> object.ones('event', cb1).should.be.false it "should keep listening to the second callback", -> object.ones('event', cb2).should.be.true describe "\b(callback)", -> object = new Dummy() .on('event1,event2', cb1 = ->) .on('event1,event2', cb2 = ->) .no(cb1) it "should listening all events for the callback", -> object.ones('event1', cb1).should.be.false object.ones('event2', cb1).should.be.false it "should not detach other callbacks", -> object.ones('event1', this.cb2).should.be.true object.ones('event2', this.cb2).should.be.true describe "\b('event1,event2')", -> object = new Dummy() .on('event1,event2,event3', cb = ->) .no('event1,event2') it "should stop listening to the 'event1'", -> object.ones('event1').should.be.false it "should stop listening to the 'event2'", -> object.ones('event2').should.be.false it "should keep listening to the 'event3'", -> object.ones('event3').should.be.true describe "\b({event1: callback1, event2: callback2})", -> object = new Dummy() .on(event1: (cb1 = ->), event2: (cb2 = ->), event3: (cb3 = ->)) .no(event1: cb1, event2: cb2) it "should stop listening to the 'event1'", -> object.ones('event1').should.be.false it "should stop listening to the 'event2'", -> object.ones('event2').should.be.false it "should keep listening to the 'event3'", -> object.ones('event3').should.be.true describe "#emit", -> describe "\b('event')", -> result = this.result = {} dummy = new Dummy().on('event', -> result.scope = this) object = dummy.emit('event') it "should return the same object back", -> object.should.be.equal dummy it "should call the listener in the scope of the object", -> result.scope.should.be.equal object describe "\b('event', arg1, arg2, arg3)", -> result = {} object = new Dummy() .on('event', -> result.args = Lovely.A(arguments)) .emit('event', 1, 2, 3) it "should pass the arguments into the listener", -> result.args.should.eql [1,2,3]
138167
# # The events handling interface unit tests # # Copyright (C) 2011-2013 <NAME> # {Test,should} = require('lovely') eval(Test.build) Lovely = this.Lovely describe 'Events', # a dummy class to test the interface Dummy = new Lovely.Class include: Lovely.Events method: -> # some dummy method describe "#on", -> describe "\b('event', callback)", -> dummy = new Dummy() object = dummy.on('event', fun = ->) it "should return the same object back", -> object.should.equal dummy it "should start listen to the 'event'", -> object.ones('event', fun).should.be.true describe "\b('event', 'callback', arg1, arg2, arg3)", -> object = new Dummy().on('event', 'method', 1, 2, 3) it "should start listen to the 'event' with the 'method'", -> object.ones('event', object.method).should.be.true it "should stash the additional arguments for later use", -> object._listeners[0].a.should.eql [1,2,3] describe "\b('event1,event2', callback)", -> object = new Dummy().on('event1,event2', fun = ->) it "should start listening to the event1", -> object.ones('event1', fun).should.be.true it "should start listening to the event2", -> object.ones('event2', fun).should.be.true describe "\b({event1: callback1, event2: callback2})", -> object = new Dummy().on(event1: (fn1 = ->), event2: (fn2 = ->)) it "should start listening to the event1", -> object.ones('event1', fn1).should.be.true it "should start listening to the event2", -> object.ones('event2', fn2).should.be.true describe "#ones", -> describe "\b('event')", -> dummy = new Dummy() it "should return 'false' by default", -> dummy.ones('something').should.be.false it "should return 'true' when listens to the event", -> dummy.on('event', ->).ones('event').should.be.true describe "\b('event', callback)", -> object = new Dummy().on('event', fun = ->) it "should say 'true' for used callback", -> object.ones('event', fun).should.be.true it "should say 'false' for another callback", -> object.ones('event', ->).should.be.false describe "\b(callback)", -> object = new Dummy().on('event', cb = ->) it "should say 'true' for used callback", -> object.ones(cb).should.be.true it "should say 'false' for another callback", -> object.ones(->).should.be.false describe "#no", -> describe "\b('event')", -> dummy = this.dummy = new Dummy() .on('event', ->) .on('other', ->) object = dummy.no('event') it "should return the same object back", -> object.should.be.equal dummy it "should stop listening to the event", -> object.ones('event').should.be.false it "should not touch the 'other' event", -> object.ones('other').should.be.true describe "\b('event', callback)", -> object = new Dummy() .on('event', cb1 = ->) .on('event', cb2 = ->) .no('event', cb1) it "should stop listening to the first callback", -> object.ones('event', cb1).should.be.false it "should keep listening to the second callback", -> object.ones('event', cb2).should.be.true describe "\b(callback)", -> object = new Dummy() .on('event1,event2', cb1 = ->) .on('event1,event2', cb2 = ->) .no(cb1) it "should listening all events for the callback", -> object.ones('event1', cb1).should.be.false object.ones('event2', cb1).should.be.false it "should not detach other callbacks", -> object.ones('event1', this.cb2).should.be.true object.ones('event2', this.cb2).should.be.true describe "\b('event1,event2')", -> object = new Dummy() .on('event1,event2,event3', cb = ->) .no('event1,event2') it "should stop listening to the 'event1'", -> object.ones('event1').should.be.false it "should stop listening to the 'event2'", -> object.ones('event2').should.be.false it "should keep listening to the 'event3'", -> object.ones('event3').should.be.true describe "\b({event1: callback1, event2: callback2})", -> object = new Dummy() .on(event1: (cb1 = ->), event2: (cb2 = ->), event3: (cb3 = ->)) .no(event1: cb1, event2: cb2) it "should stop listening to the 'event1'", -> object.ones('event1').should.be.false it "should stop listening to the 'event2'", -> object.ones('event2').should.be.false it "should keep listening to the 'event3'", -> object.ones('event3').should.be.true describe "#emit", -> describe "\b('event')", -> result = this.result = {} dummy = new Dummy().on('event', -> result.scope = this) object = dummy.emit('event') it "should return the same object back", -> object.should.be.equal dummy it "should call the listener in the scope of the object", -> result.scope.should.be.equal object describe "\b('event', arg1, arg2, arg3)", -> result = {} object = new Dummy() .on('event', -> result.args = Lovely.A(arguments)) .emit('event', 1, 2, 3) it "should pass the arguments into the listener", -> result.args.should.eql [1,2,3]
true
# # The events handling interface unit tests # # Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI # {Test,should} = require('lovely') eval(Test.build) Lovely = this.Lovely describe 'Events', # a dummy class to test the interface Dummy = new Lovely.Class include: Lovely.Events method: -> # some dummy method describe "#on", -> describe "\b('event', callback)", -> dummy = new Dummy() object = dummy.on('event', fun = ->) it "should return the same object back", -> object.should.equal dummy it "should start listen to the 'event'", -> object.ones('event', fun).should.be.true describe "\b('event', 'callback', arg1, arg2, arg3)", -> object = new Dummy().on('event', 'method', 1, 2, 3) it "should start listen to the 'event' with the 'method'", -> object.ones('event', object.method).should.be.true it "should stash the additional arguments for later use", -> object._listeners[0].a.should.eql [1,2,3] describe "\b('event1,event2', callback)", -> object = new Dummy().on('event1,event2', fun = ->) it "should start listening to the event1", -> object.ones('event1', fun).should.be.true it "should start listening to the event2", -> object.ones('event2', fun).should.be.true describe "\b({event1: callback1, event2: callback2})", -> object = new Dummy().on(event1: (fn1 = ->), event2: (fn2 = ->)) it "should start listening to the event1", -> object.ones('event1', fn1).should.be.true it "should start listening to the event2", -> object.ones('event2', fn2).should.be.true describe "#ones", -> describe "\b('event')", -> dummy = new Dummy() it "should return 'false' by default", -> dummy.ones('something').should.be.false it "should return 'true' when listens to the event", -> dummy.on('event', ->).ones('event').should.be.true describe "\b('event', callback)", -> object = new Dummy().on('event', fun = ->) it "should say 'true' for used callback", -> object.ones('event', fun).should.be.true it "should say 'false' for another callback", -> object.ones('event', ->).should.be.false describe "\b(callback)", -> object = new Dummy().on('event', cb = ->) it "should say 'true' for used callback", -> object.ones(cb).should.be.true it "should say 'false' for another callback", -> object.ones(->).should.be.false describe "#no", -> describe "\b('event')", -> dummy = this.dummy = new Dummy() .on('event', ->) .on('other', ->) object = dummy.no('event') it "should return the same object back", -> object.should.be.equal dummy it "should stop listening to the event", -> object.ones('event').should.be.false it "should not touch the 'other' event", -> object.ones('other').should.be.true describe "\b('event', callback)", -> object = new Dummy() .on('event', cb1 = ->) .on('event', cb2 = ->) .no('event', cb1) it "should stop listening to the first callback", -> object.ones('event', cb1).should.be.false it "should keep listening to the second callback", -> object.ones('event', cb2).should.be.true describe "\b(callback)", -> object = new Dummy() .on('event1,event2', cb1 = ->) .on('event1,event2', cb2 = ->) .no(cb1) it "should listening all events for the callback", -> object.ones('event1', cb1).should.be.false object.ones('event2', cb1).should.be.false it "should not detach other callbacks", -> object.ones('event1', this.cb2).should.be.true object.ones('event2', this.cb2).should.be.true describe "\b('event1,event2')", -> object = new Dummy() .on('event1,event2,event3', cb = ->) .no('event1,event2') it "should stop listening to the 'event1'", -> object.ones('event1').should.be.false it "should stop listening to the 'event2'", -> object.ones('event2').should.be.false it "should keep listening to the 'event3'", -> object.ones('event3').should.be.true describe "\b({event1: callback1, event2: callback2})", -> object = new Dummy() .on(event1: (cb1 = ->), event2: (cb2 = ->), event3: (cb3 = ->)) .no(event1: cb1, event2: cb2) it "should stop listening to the 'event1'", -> object.ones('event1').should.be.false it "should stop listening to the 'event2'", -> object.ones('event2').should.be.false it "should keep listening to the 'event3'", -> object.ones('event3').should.be.true describe "#emit", -> describe "\b('event')", -> result = this.result = {} dummy = new Dummy().on('event', -> result.scope = this) object = dummy.emit('event') it "should return the same object back", -> object.should.be.equal dummy it "should call the listener in the scope of the object", -> result.scope.should.be.equal object describe "\b('event', arg1, arg2, arg3)", -> result = {} object = new Dummy() .on('event', -> result.args = Lovely.A(arguments)) .emit('event', 1, 2, 3) it "should pass the arguments into the listener", -> result.args.should.eql [1,2,3]
[ { "context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib", "end": 79, "score": 0.9998525381088257, "start": 66, "tag": "NAME", "value": "Henri Bergius" } ]
src/plugins/reundo.coffee
git-j/hallo
0
# Hallo - a rich text editing jQuery UI widget # (c) 2011 Henri Bergius, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget "IKS.halloreundo", options: editable: null toolbar: null uuid: '' buttonCssClass: null populateToolbar: (toolbar) -> buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonize = (label,cmd,cmd_fn) => button_label = label if ( window.action_list && window.action_list['hallojs_' + cmd] != undefined ) button_label = window.action_list['hallojs_' + cmd].title + ' ' + window.action_list['hallojs_' + cmd].tooltip buttonElement = jQuery '<span></span>' buttonElement.hallobutton uuid: @options.uuid editable: @options.editable label: button_label icon: if cmd is 'undo' then 'icon-undo' else 'icon-repeat' command: cmd command_function: cmd_fn queryState: false cssClass: @options.buttonCssClass buttonset.append buttonElement if ( window.wke ) @options.editable.registerKey 'ctrl', 90, (event) => event.preventDefault() @_undo(jQuery(event.currentTarget)) @options.editable.registerKey 'ctrl,shift', 90, (event) => event.preventDefault() @_redo(jQuery(event.currentTarget)) if ( utils && utils.cur_language == 'de' ) # german redo @options.editable.registerKey 'ctrl', 89, (event) => event.preventDefault() @_redo(jQuery(event.currentTarget)) buttonize "Undo", 'undo', () => @_undo(@options.editable.element) buttonize "Redo", 'redo', () => @_redo(@options.editable.element) else buttonize "Undo", "undo" buttonize "Redo", "redo" buttonset.hallobuttonset() toolbar.append buttonset _init: -> _undo: (target) -> #console.log('undo toolbar fn') @options.editable.undo(target) _redo: (target) -> #console.log('redo toolbar fn') return if ( typeof @options.editable._undo_stack != 'object' ) @options.editable.redo(target) )(jQuery)
206169
# Hallo - a rich text editing jQuery UI widget # (c) 2011 <NAME>, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget "IKS.halloreundo", options: editable: null toolbar: null uuid: '' buttonCssClass: null populateToolbar: (toolbar) -> buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonize = (label,cmd,cmd_fn) => button_label = label if ( window.action_list && window.action_list['hallojs_' + cmd] != undefined ) button_label = window.action_list['hallojs_' + cmd].title + ' ' + window.action_list['hallojs_' + cmd].tooltip buttonElement = jQuery '<span></span>' buttonElement.hallobutton uuid: @options.uuid editable: @options.editable label: button_label icon: if cmd is 'undo' then 'icon-undo' else 'icon-repeat' command: cmd command_function: cmd_fn queryState: false cssClass: @options.buttonCssClass buttonset.append buttonElement if ( window.wke ) @options.editable.registerKey 'ctrl', 90, (event) => event.preventDefault() @_undo(jQuery(event.currentTarget)) @options.editable.registerKey 'ctrl,shift', 90, (event) => event.preventDefault() @_redo(jQuery(event.currentTarget)) if ( utils && utils.cur_language == 'de' ) # german redo @options.editable.registerKey 'ctrl', 89, (event) => event.preventDefault() @_redo(jQuery(event.currentTarget)) buttonize "Undo", 'undo', () => @_undo(@options.editable.element) buttonize "Redo", 'redo', () => @_redo(@options.editable.element) else buttonize "Undo", "undo" buttonize "Redo", "redo" buttonset.hallobuttonset() toolbar.append buttonset _init: -> _undo: (target) -> #console.log('undo toolbar fn') @options.editable.undo(target) _redo: (target) -> #console.log('redo toolbar fn') return if ( typeof @options.editable._undo_stack != 'object' ) @options.editable.redo(target) )(jQuery)
true
# Hallo - a rich text editing jQuery UI widget # (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget "IKS.halloreundo", options: editable: null toolbar: null uuid: '' buttonCssClass: null populateToolbar: (toolbar) -> buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonize = (label,cmd,cmd_fn) => button_label = label if ( window.action_list && window.action_list['hallojs_' + cmd] != undefined ) button_label = window.action_list['hallojs_' + cmd].title + ' ' + window.action_list['hallojs_' + cmd].tooltip buttonElement = jQuery '<span></span>' buttonElement.hallobutton uuid: @options.uuid editable: @options.editable label: button_label icon: if cmd is 'undo' then 'icon-undo' else 'icon-repeat' command: cmd command_function: cmd_fn queryState: false cssClass: @options.buttonCssClass buttonset.append buttonElement if ( window.wke ) @options.editable.registerKey 'ctrl', 90, (event) => event.preventDefault() @_undo(jQuery(event.currentTarget)) @options.editable.registerKey 'ctrl,shift', 90, (event) => event.preventDefault() @_redo(jQuery(event.currentTarget)) if ( utils && utils.cur_language == 'de' ) # german redo @options.editable.registerKey 'ctrl', 89, (event) => event.preventDefault() @_redo(jQuery(event.currentTarget)) buttonize "Undo", 'undo', () => @_undo(@options.editable.element) buttonize "Redo", 'redo', () => @_redo(@options.editable.element) else buttonize "Undo", "undo" buttonize "Redo", "redo" buttonset.hallobuttonset() toolbar.append buttonset _init: -> _undo: (target) -> #console.log('undo toolbar fn') @options.editable.undo(target) _redo: (target) -> #console.log('redo toolbar fn') return if ( typeof @options.editable._undo_stack != 'object' ) @options.editable.redo(target) )(jQuery)
[ { "context": "Crack extends Skill\n target: TARGET_DIR8\n key: 'skull_crack'\n name: 'skull crack'\n mp: 3\n cooldown: 3\n\n r", "end": 72, "score": 0.9962806701660156, "start": 61, "tag": "KEY", "value": "skull_crack" } ]
js/skills/skull_crack.coffee
ktchernov/7drl-lion.github.io
27
class SkullCrack extends Skill target: TARGET_DIR8 key: 'skull_crack' name: 'skull crack' mp: 3 cooldown: 3 run: (dir) -> true # register_skill 'skull_crack', SkullCrack
83399
class SkullCrack extends Skill target: TARGET_DIR8 key: '<KEY>' name: 'skull crack' mp: 3 cooldown: 3 run: (dir) -> true # register_skill 'skull_crack', SkullCrack
true
class SkullCrack extends Skill target: TARGET_DIR8 key: 'PI:KEY:<KEY>END_PI' name: 'skull crack' mp: 3 cooldown: 3 run: (dir) -> true # register_skill 'skull_crack', SkullCrack
[ { "context": "rt of switch-reducers\n# Copyright (C) 2018-present Dario Giovannetti <dev@dariogiovannetti.net>\n# Licensed under MIT\n#", "end": 85, "score": 0.9998668432235718, "start": 68, "tag": "NAME", "value": "Dario Giovannetti" }, { "context": "s\n# Copyright (C) 2018-present Dario Giovannetti <dev@dariogiovannetti.net>\n# Licensed under MIT\n# https://github.com/kyniko", "end": 111, "score": 0.9999345541000366, "start": 87, "tag": "EMAIL", "value": "dev@dariogiovannetti.net" } ]
index.coffee
kynikos/lib.js.switch-reducers
1
# This file is part of switch-reducers # Copyright (C) 2018-present Dario Giovannetti <dev@dariogiovannetti.net> # Licensed under MIT # https://github.com/kynikos/switch-reducers/blob/master/LICENSE module.exports = (getControlVar, reducersMap) -> (args...) -> reduce = reducersMap[getControlVar(args...)] if reduce? return reduce(args...) return null
38129
# This file is part of switch-reducers # Copyright (C) 2018-present <NAME> <<EMAIL>> # Licensed under MIT # https://github.com/kynikos/switch-reducers/blob/master/LICENSE module.exports = (getControlVar, reducersMap) -> (args...) -> reduce = reducersMap[getControlVar(args...)] if reduce? return reduce(args...) return null
true
# This file is part of switch-reducers # Copyright (C) 2018-present PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Licensed under MIT # https://github.com/kynikos/switch-reducers/blob/master/LICENSE module.exports = (getControlVar, reducersMap) -> (args...) -> reduce = reducersMap[getControlVar(args...)] if reduce? return reduce(args...) return null
[ { "context": ": \"0\"\n notify_invites: \"1\"\n email: \"jasmine@example.com\"\n email_confirmed: 1\n api_token: \"0", "end": 212, "score": 0.9999100565910339, "start": 193, "tag": "EMAIL", "value": "jasmine@example.com" }, { "context": "m\"\n email_confirmed: 1\n api_token: \"0123456789abcdef0123456789abcdef\"\n notify_followers: \"0\"\n newsletter", "end": 293, "score": 0.9986782073974609, "start": 261, "tag": "KEY", "value": "0123456789abcdef0123456789abcdef" } ]
www/test/src/fixtures/models.coffee
berekuk/questhub
15
define [ "models/current-user" ], (currentUser) -> result = {} result.settings = notify_likes: "1" notify_comments: "0" notify_invites: "1" email: "jasmine@example.com" email_confirmed: 1 api_token: "0123456789abcdef0123456789abcdef" notify_followers: "0" newsletter: "0" result
7879
define [ "models/current-user" ], (currentUser) -> result = {} result.settings = notify_likes: "1" notify_comments: "0" notify_invites: "1" email: "<EMAIL>" email_confirmed: 1 api_token: "<KEY>" notify_followers: "0" newsletter: "0" result
true
define [ "models/current-user" ], (currentUser) -> result = {} result.settings = notify_likes: "1" notify_comments: "0" notify_invites: "1" email: "PI:EMAIL:<EMAIL>END_PI" email_confirmed: 1 api_token: "PI:KEY:<KEY>END_PI" notify_followers: "0" newsletter: "0" result
[ { "context": "offeescript/src/command.coffee(https://github.com/jashkenas/coffeescript)\n Thanks to Jeremy Ashkenas\n Some", "end": 88, "score": 0.9933568239212036, "start": 79, "tag": "USERNAME", "value": "jashkenas" }, { "context": "://github.com/jashkenas/coffeescript)\n Thanks to Jeremy Ashkenas\n Some stuffs is added or modified for taiji lang", "end": 131, "score": 0.9999100565910339, "start": 116, "tag": "NAME", "value": "Jeremy Ashkenas" }, { "context": "or taiji langauge.\n###\n###\nCopyright (c) 2009-2014 Jeremy Ashkenas\nCopyright (c) 2014-2015 Caoxingming\n\nPermission i", "end": 234, "score": 0.9999067187309265, "start": 219, "tag": "NAME", "value": "Jeremy Ashkenas" }, { "context": "{fileLocation})\"\n else fileLocation\n\n# Based on [michaelficarra/CoffeeScriptRedux](http://goo.gl/ZTx1p)\n# NodeJS ", "end": 15389, "score": 0.9993725419044495, "start": 15375, "tag": "USERNAME", "value": "michaelficarra" } ]
src/command.coffee
taijiweb/taijilang
34
### this file is based on coffeescript/src/command.coffee(https://github.com/jashkenas/coffeescript) Thanks to Jeremy Ashkenas Some stuffs is added or modified for taiji langauge. ### ### Copyright (c) 2009-2014 Jeremy Ashkenas Copyright (c) 2014-2015 Caoxingming 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. ### # The `taiji` utility. Handles command-line compilation of taijilang # into various forms: saved into `.js` files or printed to stdout # printed as a token stream or as the syntax tree, or launch an interactive repl. # taiji can be used both on the server based on Node.js/V8, or to run directly in the browser. # This module contains the main entry functions for tokenizing, parsing, and compiling source taiji into JavaScript. fs = require 'fs' path = require 'path' vm = require 'vm' {spawn, exec} = require 'child_process' {EventEmitter} = require 'events' mkdirp = require 'mkdirp' {extend, baseFileName} = utils = require './utils' optparse = require './optparse' taiji = require './taiji' TaijiModule = require './module' SourceMap = require './sourcemap' useWinPathSep = path.sep is '\\' # Allow taiji to emit Node.js events. extend taiji, new EventEmitter printLine = (line) -> process.stdout.write line + '\n' printWarn = (line) -> process.stderr.write line + '\n' hidden = (file) -> /^\.|~$/.test file # The help banner that is printed in conjunction with `-h`/`--help`. BANNER = ''' Usage: taiji [options] path/to/script.tj -- [args] If called without options, taiji will run your script. ''' # The list of all the valid option flags that `taiji` knows how to handle. SWITCHES = [ ['-a', '--parse', 'print out the json list that the parser produces'] ['-b', '--bare', 'compile without a top-level function wrapper'] ['-c', '--compile', 'compile to JavaScript and save as .js files'] ['-d', '--nodejs [ARGS]', 'pass options directly to the "node" binary'] ['-e', '--eval', 'pass a string from the command line as input'] ['-h', '--help', 'display this help message'] ['-i', '--interactive', 'run an interactive taiji repl'] ['-j', '--join [FILE]', 'concatenate the source taiji before compiling'] ['-m', '--map', 'generate source map and save as .map files'] ['-n', '--no-optimize', 'compile to javascript code without optimization'] ['-o', '--output [DIR]', 'set the output directory for compiled JavaScript'] ['-p', '--print', 'print out the compiled JavaScript'] ['-r', '--no-header', 'suppress the "Generated by" header'] ['-s', '--stdio', 'listen for and compile scripts over stdio'] ['-t', '--transforma', 'print out the internal expression after transforming'] ['-v', '--version', 'display the version number'] ['-z', '--optimize', 'print out the internal expression after optimizing'] ] # Top-level objects shared by all the functions. exports.testing = false exports.opts = opts = {} sourceCode = []; optionParser = null # Run `taiji` by parsing passed options and determining what action to take Many flags cause us to divert before compiling anything. # Flags passed after `--` will be passed verbatim to your script as arguments in `process.argv` exports.run = -> parseOptions() # Make the repl *CLI* use the global context so as to # (a) be consistent with the `node` repl CLI and, therefore, # (b) make packages that modify native prototypes (such as 'colors' and 'sugar') work as expected. replCliOpts = useGlobal: true return forkNode() if opts.nodejs return usage() if opts.help return version() if opts.version return require('./repl').start(replCliOpts) if opts.interactive return compileStdio() if opts.stdio return compileScript 'compileCode', null, opts.arguments[0] if opts.eval return require('./repl').start(replCliOpts) unless opts.arguments.length # console.log 'in run()'+(JSON.stringify opts) #opts.print = true # simeon literals = if opts.run then opts.arguments.splice 1 else [] process.argv = process.argv[0..1].concat literals process.argv[0] = 'taiji' opts.output = path.resolve opts.output if opts.output for source in opts.arguments source = path.resolve(source) if opts.compile or opts.run if opts.noOptimize then compilePath 'compileCodeWithoutOptimization', source, true, source else compilePath 'compile', source, true, source if opts.parse then compilePath 'parse', source, true, source if opts.transform then compilePath 'transform', source, true, source if opts.optimize then compilePath 'optimize', source, true, source # Compile a path, which could be a script or a directory. # If a directory is passed, recursively compile all '.taiji', and '.tj' extension source files in it and all subdirectories. compilePath = (action, source, topLevel, base) -> try stats = fs.statSync source catch err if err.code is 'ENOENT' then console.error "File not found: #{source}"; process.exit 1 throw err if stats.isDirectory() if opts.run then compilePath action, findDirectoryIndex(source), topLevel, base; return try files = fs.readdirSync source catch err then (if err.code is 'ENOENT' then return else throw err) for file in files then compilePath action, (path.join source, file), no, base else if topLevel or utils.isTaiji source try code = fs.readFileSync source catch err then (if err.code is 'ENOENT' then return else throw err) compileScript(action, source, code.toString(), base) findDirectoryIndex = (source) -> for ext in taiji.FILE_EXTENSIONS index = path.join source, "index#{ext}" try return index if (fs.statSync index).isFile() catch err then throw err unless err.code is 'ENOENT' console.error "Missing index.taiji or index.littaiji in #{source}" process.exit 1 # Compile a single source script, containing the given code, according to the requested options. # If evaluating the script directly sets `__filename`, `__dirname` and `module.filename` to be correct relative to the script's path. compileScript = (action, file, input, base = null) -> o = exports.opts; options = compileOptions file, base try t = task = {file, input, options} taiji.emit 'compile', task if o.run taiji.register(); runCode t.input, t.options else compiled = exports[action](t.input, new TaijiModule(file, taiji.rootModule), t.options) t.output = compiled taiji.emit 'success', task if o.print then printLine t.output.trim() else if o.compile then writeJs base, t.file, t.output, options.outputPath, t.sourceMap else writeResult base, t.file, t.output, options.outputPath, action catch err taiji.emit 'failure', err, task return if taiji.listeners('failure').length message = err.stack or "#{err}" printWarn message; process.exit 1 # Get the corresponding output JavaScript path for a source file. outputPath = (source, base, extension=".js") -> basename = utils.baseFileName source, true, useWinPathSep srcDir = path.dirname source if not opts.output then dir = srcDir else if source is base then dir = opts.output else dir = path.join opts.output, path.relative base, srcDir path.join dir, basename + extension # Write out a JavaScript source file with the compiled code. # By default, files are written out in `cwd` as `.js` files with the same name, # but the output directory can be customized with `--output`. writeJs = (base, sourcePath, js, jsPath) -> jsDir = path.dirname jsPath processFile = -> if opts.compile js = ' ' if js.length==0 fs.writeFile jsPath, js, (err) -> if err then printLine err.message fs.exists jsDir, (itExists) -> if itExists then processFile() else mkdirp jsDir, processFile writeResult = (base, sourcePath, obj, objPath, action) -> objDir = path.dirname objPath objPath = path.join(objDir, baseFileName(sourcePath, true, path.sep=='\\')+'.'+action+'.taiji.json') write = -> obj = ' ' if obj.length==0 fs.writeFile objPath, obj, (err) -> if err then printLine err.message fs.exists objDir, (itExists) -> if itExists then write() else mkdirp objDir, write # Use the [OptionParser module](optparse.html) to extract all options from `process.argv` that are specified in `SWITCHES`. parseOptions = -> optionParser = new optparse.OptionParser SWITCHES, BANNER if not exports.testing o = exports.opts = opts = optionParser.parse process.argv[2..] o.compile or= !!o.output o.run = not (o.compile or o.print or o.map) o.print = !! (o.print or (o.eval or o.stdio and o.compile)) else o = opts = exports.opts # The compile-time options to pass to the taiji compiler. compileOptions = (filename, base) -> answer = {filename, bare: opts.bare, header: opts.compile and not opts['no-header']} if filename if base cwd = process.cwd() outPath = outputPath filename, base jsDir = path.dirname outPath answer = utils.merge answer, { outputPath:outPath sourceRoot: path.relative jsDir, cwd sourceFiles: [path.relative cwd, filename] generatedFile: utils.baseFileName(outPath, no, useWinPathSep) } else answer = utils.merge answer, sourceRoot: "", sourceFiles: [utils.baseFileName filename, no, useWinPathSep] generatedFile: utils.baseFileName(filename, true, useWinPathSep) + ".js" answer # Start up a new Node.js instance with the arguments in `--nodejs` passed to the `node` binary, preserving the other options. forkNode = -> nodeArgs = opts.nodejs.split /\s+/ args = process.argv[1..] args.splice args.indexOf('--nodejs'), 2 p = spawn process.execPath, nodeArgs.concat(args),{cwd: process.cwd(), env: process.env, customFds: [0, 1, 2]} p.on 'exit', (code) -> process.exit code # Print the `--help` usage message and exit. Deprecated switches are not shown. usage = -> printLine (new optparse.OptionParser SWITCHES, BANNER).help() # Print the `--version` message and exit. version = -> printLine "taiji version #{taiji.VERSION}" # parse, transform, optimize, compile taiji code to JavaScript exports.parse = (code, taijiModule, options) -> taiji.parse(code, taijiModule, taiji.builtins, options) exports.transform = (code, taijiModule, options) -> taiji.transform(code, taijiModule, taiji.builtins, options) exports.optimize = (code, taijiModule, options) -> taiji.optimize(code, taijiModule, taiji.builtins, options) exports.compile = (code, taijiModule, options) -> taiji.compile(code, taijiModule, taiji.builtins, options) # Compile and execute a string of taiji (on the server), correctly setting `__filename`, `__dirname`, and relative `require()`. exports.runCode = runCode = (code, options = {}) -> mainModule = require.main mainModule.filename = process.argv[1] = if options.filename then fs.realpathSync(options.filename) else '.' mainModule.moduleCache and= {} dir = if options.filename then path.dirname fs.realpathSync options.filename else fs.realpathSync '.' mainModule.paths = require('module')._nodeModulePaths dir if not utils.isTaiji(mainModule.filename) or require.extensions filename = options.filename or '**evaluated taijilang code**' answer = exports.compile code, new TaijiModule(filename, taiji.rootModule), options code = answer.js ? answer mainModule._compile code, mainModule.filename # Compile and evaluate a string of taiji (in a Node.js-like environment), The taiji repl uses this to run the input. exports.evalCode = (code, options = {}) -> return unless code = code.trim() Script = vm.Script if Script if options.sandbox? if options.sandbox instanceof Script.createContext().constructor sandbox = options.sandbox else sandbox = Script.createContext() sandbox[k] = v for own k, v of options.sandbox sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox else sandbox = global sandbox.__filename = options.filename || 'eval' sandbox.__dirname = path.dirname sandbox.__filename # define module/require only if they chose not to specify their own unless sandbox isnt global or sandbox.module or sandbox.require Module = require 'module' sandbox.module = _module = new Module(options.modulename || 'eval') sandbox.require = _require = (path) -> Module._load path, _module, true _module.filename = sandbox.__filename _require[r] = require[r] for r in Object.getOwnPropertyNames require when r isnt 'paths' # use the same hack node currently uses for their own repl _require.paths = _module.paths = Module._nodeModulePaths process.cwd() _require.resolve = (request) -> Module._resolveFilename request, _module o = {} o[k] = v for own k, v of options o.bare = on # ensure return value js = exports.compile code, new TaijiModule('evaluated-code.tj', taiji.rootModule), o if sandbox is global then vm.runInThisContext js else vm.runInContext js, sandbox # Based on http://v8.googlecode.com/svn/branches/bleeding_edge/src/messages.js formatSourcePosition = (frame) -> fileName = undefined fileLocation = '' if frame.isNative() then fileLocation = "native" else if frame.isEval() fileName = frame.getScriptNameOrSourceURL() fileLocation = "#{frame.getEvalOrigin()}, " unless fileName else fileName = frame.getFileName() fileName or= "<anonymous>" line = frame.getLineNumber() column = frame.getColumnNumber() fileLocation = "#{fileName}:#{line}:#{column}" functionName = frame.getFunctionName() isConstructor = frame.isConstructor() isMethodCall = not (frame.isToplevel() or isConstructor) if isMethodCall methodName = frame.getMethodName() typeName = frame.getTypeName() if functionName tp = as = '' if typeName and functionName.indexOf typeName tp = "#{typeName}." if methodName and functionName.indexOf(".#{methodName}") isnt functionName.length - methodName.length - 1 as = " [as #{methodName}]" "#{tp}#{functionName}#{as} (#{fileLocation})" else "#{typeName}.#{methodName or '<anonymous>'} (#{fileLocation})" else if isConstructor then "new #{functionName or '<anonymous>'} (#{fileLocation})" else if functionName then "#{functionName} (#{fileLocation})" else fileLocation # Based on [michaelficarra/CoffeeScriptRedux](http://goo.gl/ZTx1p) # NodeJS / V8 have no support for transforming positions in stack traces using sourceMap # so we must monkey-patch Error to display taiji source positions. Error.prepareStackTrace = (err, stack) -> frames = for frame in stack if frame.getFunction() is exports.run then break " at #{formatSourcePosition frame}" "#{err.toString()}\n#{frames.join '\n'}\n"
38198
### this file is based on coffeescript/src/command.coffee(https://github.com/jashkenas/coffeescript) Thanks to <NAME> Some stuffs is added or modified for taiji langauge. ### ### Copyright (c) 2009-2014 <NAME> Copyright (c) 2014-2015 Caoxingming 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. ### # The `taiji` utility. Handles command-line compilation of taijilang # into various forms: saved into `.js` files or printed to stdout # printed as a token stream or as the syntax tree, or launch an interactive repl. # taiji can be used both on the server based on Node.js/V8, or to run directly in the browser. # This module contains the main entry functions for tokenizing, parsing, and compiling source taiji into JavaScript. fs = require 'fs' path = require 'path' vm = require 'vm' {spawn, exec} = require 'child_process' {EventEmitter} = require 'events' mkdirp = require 'mkdirp' {extend, baseFileName} = utils = require './utils' optparse = require './optparse' taiji = require './taiji' TaijiModule = require './module' SourceMap = require './sourcemap' useWinPathSep = path.sep is '\\' # Allow taiji to emit Node.js events. extend taiji, new EventEmitter printLine = (line) -> process.stdout.write line + '\n' printWarn = (line) -> process.stderr.write line + '\n' hidden = (file) -> /^\.|~$/.test file # The help banner that is printed in conjunction with `-h`/`--help`. BANNER = ''' Usage: taiji [options] path/to/script.tj -- [args] If called without options, taiji will run your script. ''' # The list of all the valid option flags that `taiji` knows how to handle. SWITCHES = [ ['-a', '--parse', 'print out the json list that the parser produces'] ['-b', '--bare', 'compile without a top-level function wrapper'] ['-c', '--compile', 'compile to JavaScript and save as .js files'] ['-d', '--nodejs [ARGS]', 'pass options directly to the "node" binary'] ['-e', '--eval', 'pass a string from the command line as input'] ['-h', '--help', 'display this help message'] ['-i', '--interactive', 'run an interactive taiji repl'] ['-j', '--join [FILE]', 'concatenate the source taiji before compiling'] ['-m', '--map', 'generate source map and save as .map files'] ['-n', '--no-optimize', 'compile to javascript code without optimization'] ['-o', '--output [DIR]', 'set the output directory for compiled JavaScript'] ['-p', '--print', 'print out the compiled JavaScript'] ['-r', '--no-header', 'suppress the "Generated by" header'] ['-s', '--stdio', 'listen for and compile scripts over stdio'] ['-t', '--transforma', 'print out the internal expression after transforming'] ['-v', '--version', 'display the version number'] ['-z', '--optimize', 'print out the internal expression after optimizing'] ] # Top-level objects shared by all the functions. exports.testing = false exports.opts = opts = {} sourceCode = []; optionParser = null # Run `taiji` by parsing passed options and determining what action to take Many flags cause us to divert before compiling anything. # Flags passed after `--` will be passed verbatim to your script as arguments in `process.argv` exports.run = -> parseOptions() # Make the repl *CLI* use the global context so as to # (a) be consistent with the `node` repl CLI and, therefore, # (b) make packages that modify native prototypes (such as 'colors' and 'sugar') work as expected. replCliOpts = useGlobal: true return forkNode() if opts.nodejs return usage() if opts.help return version() if opts.version return require('./repl').start(replCliOpts) if opts.interactive return compileStdio() if opts.stdio return compileScript 'compileCode', null, opts.arguments[0] if opts.eval return require('./repl').start(replCliOpts) unless opts.arguments.length # console.log 'in run()'+(JSON.stringify opts) #opts.print = true # simeon literals = if opts.run then opts.arguments.splice 1 else [] process.argv = process.argv[0..1].concat literals process.argv[0] = 'taiji' opts.output = path.resolve opts.output if opts.output for source in opts.arguments source = path.resolve(source) if opts.compile or opts.run if opts.noOptimize then compilePath 'compileCodeWithoutOptimization', source, true, source else compilePath 'compile', source, true, source if opts.parse then compilePath 'parse', source, true, source if opts.transform then compilePath 'transform', source, true, source if opts.optimize then compilePath 'optimize', source, true, source # Compile a path, which could be a script or a directory. # If a directory is passed, recursively compile all '.taiji', and '.tj' extension source files in it and all subdirectories. compilePath = (action, source, topLevel, base) -> try stats = fs.statSync source catch err if err.code is 'ENOENT' then console.error "File not found: #{source}"; process.exit 1 throw err if stats.isDirectory() if opts.run then compilePath action, findDirectoryIndex(source), topLevel, base; return try files = fs.readdirSync source catch err then (if err.code is 'ENOENT' then return else throw err) for file in files then compilePath action, (path.join source, file), no, base else if topLevel or utils.isTaiji source try code = fs.readFileSync source catch err then (if err.code is 'ENOENT' then return else throw err) compileScript(action, source, code.toString(), base) findDirectoryIndex = (source) -> for ext in taiji.FILE_EXTENSIONS index = path.join source, "index#{ext}" try return index if (fs.statSync index).isFile() catch err then throw err unless err.code is 'ENOENT' console.error "Missing index.taiji or index.littaiji in #{source}" process.exit 1 # Compile a single source script, containing the given code, according to the requested options. # If evaluating the script directly sets `__filename`, `__dirname` and `module.filename` to be correct relative to the script's path. compileScript = (action, file, input, base = null) -> o = exports.opts; options = compileOptions file, base try t = task = {file, input, options} taiji.emit 'compile', task if o.run taiji.register(); runCode t.input, t.options else compiled = exports[action](t.input, new TaijiModule(file, taiji.rootModule), t.options) t.output = compiled taiji.emit 'success', task if o.print then printLine t.output.trim() else if o.compile then writeJs base, t.file, t.output, options.outputPath, t.sourceMap else writeResult base, t.file, t.output, options.outputPath, action catch err taiji.emit 'failure', err, task return if taiji.listeners('failure').length message = err.stack or "#{err}" printWarn message; process.exit 1 # Get the corresponding output JavaScript path for a source file. outputPath = (source, base, extension=".js") -> basename = utils.baseFileName source, true, useWinPathSep srcDir = path.dirname source if not opts.output then dir = srcDir else if source is base then dir = opts.output else dir = path.join opts.output, path.relative base, srcDir path.join dir, basename + extension # Write out a JavaScript source file with the compiled code. # By default, files are written out in `cwd` as `.js` files with the same name, # but the output directory can be customized with `--output`. writeJs = (base, sourcePath, js, jsPath) -> jsDir = path.dirname jsPath processFile = -> if opts.compile js = ' ' if js.length==0 fs.writeFile jsPath, js, (err) -> if err then printLine err.message fs.exists jsDir, (itExists) -> if itExists then processFile() else mkdirp jsDir, processFile writeResult = (base, sourcePath, obj, objPath, action) -> objDir = path.dirname objPath objPath = path.join(objDir, baseFileName(sourcePath, true, path.sep=='\\')+'.'+action+'.taiji.json') write = -> obj = ' ' if obj.length==0 fs.writeFile objPath, obj, (err) -> if err then printLine err.message fs.exists objDir, (itExists) -> if itExists then write() else mkdirp objDir, write # Use the [OptionParser module](optparse.html) to extract all options from `process.argv` that are specified in `SWITCHES`. parseOptions = -> optionParser = new optparse.OptionParser SWITCHES, BANNER if not exports.testing o = exports.opts = opts = optionParser.parse process.argv[2..] o.compile or= !!o.output o.run = not (o.compile or o.print or o.map) o.print = !! (o.print or (o.eval or o.stdio and o.compile)) else o = opts = exports.opts # The compile-time options to pass to the taiji compiler. compileOptions = (filename, base) -> answer = {filename, bare: opts.bare, header: opts.compile and not opts['no-header']} if filename if base cwd = process.cwd() outPath = outputPath filename, base jsDir = path.dirname outPath answer = utils.merge answer, { outputPath:outPath sourceRoot: path.relative jsDir, cwd sourceFiles: [path.relative cwd, filename] generatedFile: utils.baseFileName(outPath, no, useWinPathSep) } else answer = utils.merge answer, sourceRoot: "", sourceFiles: [utils.baseFileName filename, no, useWinPathSep] generatedFile: utils.baseFileName(filename, true, useWinPathSep) + ".js" answer # Start up a new Node.js instance with the arguments in `--nodejs` passed to the `node` binary, preserving the other options. forkNode = -> nodeArgs = opts.nodejs.split /\s+/ args = process.argv[1..] args.splice args.indexOf('--nodejs'), 2 p = spawn process.execPath, nodeArgs.concat(args),{cwd: process.cwd(), env: process.env, customFds: [0, 1, 2]} p.on 'exit', (code) -> process.exit code # Print the `--help` usage message and exit. Deprecated switches are not shown. usage = -> printLine (new optparse.OptionParser SWITCHES, BANNER).help() # Print the `--version` message and exit. version = -> printLine "taiji version #{taiji.VERSION}" # parse, transform, optimize, compile taiji code to JavaScript exports.parse = (code, taijiModule, options) -> taiji.parse(code, taijiModule, taiji.builtins, options) exports.transform = (code, taijiModule, options) -> taiji.transform(code, taijiModule, taiji.builtins, options) exports.optimize = (code, taijiModule, options) -> taiji.optimize(code, taijiModule, taiji.builtins, options) exports.compile = (code, taijiModule, options) -> taiji.compile(code, taijiModule, taiji.builtins, options) # Compile and execute a string of taiji (on the server), correctly setting `__filename`, `__dirname`, and relative `require()`. exports.runCode = runCode = (code, options = {}) -> mainModule = require.main mainModule.filename = process.argv[1] = if options.filename then fs.realpathSync(options.filename) else '.' mainModule.moduleCache and= {} dir = if options.filename then path.dirname fs.realpathSync options.filename else fs.realpathSync '.' mainModule.paths = require('module')._nodeModulePaths dir if not utils.isTaiji(mainModule.filename) or require.extensions filename = options.filename or '**evaluated taijilang code**' answer = exports.compile code, new TaijiModule(filename, taiji.rootModule), options code = answer.js ? answer mainModule._compile code, mainModule.filename # Compile and evaluate a string of taiji (in a Node.js-like environment), The taiji repl uses this to run the input. exports.evalCode = (code, options = {}) -> return unless code = code.trim() Script = vm.Script if Script if options.sandbox? if options.sandbox instanceof Script.createContext().constructor sandbox = options.sandbox else sandbox = Script.createContext() sandbox[k] = v for own k, v of options.sandbox sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox else sandbox = global sandbox.__filename = options.filename || 'eval' sandbox.__dirname = path.dirname sandbox.__filename # define module/require only if they chose not to specify their own unless sandbox isnt global or sandbox.module or sandbox.require Module = require 'module' sandbox.module = _module = new Module(options.modulename || 'eval') sandbox.require = _require = (path) -> Module._load path, _module, true _module.filename = sandbox.__filename _require[r] = require[r] for r in Object.getOwnPropertyNames require when r isnt 'paths' # use the same hack node currently uses for their own repl _require.paths = _module.paths = Module._nodeModulePaths process.cwd() _require.resolve = (request) -> Module._resolveFilename request, _module o = {} o[k] = v for own k, v of options o.bare = on # ensure return value js = exports.compile code, new TaijiModule('evaluated-code.tj', taiji.rootModule), o if sandbox is global then vm.runInThisContext js else vm.runInContext js, sandbox # Based on http://v8.googlecode.com/svn/branches/bleeding_edge/src/messages.js formatSourcePosition = (frame) -> fileName = undefined fileLocation = '' if frame.isNative() then fileLocation = "native" else if frame.isEval() fileName = frame.getScriptNameOrSourceURL() fileLocation = "#{frame.getEvalOrigin()}, " unless fileName else fileName = frame.getFileName() fileName or= "<anonymous>" line = frame.getLineNumber() column = frame.getColumnNumber() fileLocation = "#{fileName}:#{line}:#{column}" functionName = frame.getFunctionName() isConstructor = frame.isConstructor() isMethodCall = not (frame.isToplevel() or isConstructor) if isMethodCall methodName = frame.getMethodName() typeName = frame.getTypeName() if functionName tp = as = '' if typeName and functionName.indexOf typeName tp = "#{typeName}." if methodName and functionName.indexOf(".#{methodName}") isnt functionName.length - methodName.length - 1 as = " [as #{methodName}]" "#{tp}#{functionName}#{as} (#{fileLocation})" else "#{typeName}.#{methodName or '<anonymous>'} (#{fileLocation})" else if isConstructor then "new #{functionName or '<anonymous>'} (#{fileLocation})" else if functionName then "#{functionName} (#{fileLocation})" else fileLocation # Based on [michaelficarra/CoffeeScriptRedux](http://goo.gl/ZTx1p) # NodeJS / V8 have no support for transforming positions in stack traces using sourceMap # so we must monkey-patch Error to display taiji source positions. Error.prepareStackTrace = (err, stack) -> frames = for frame in stack if frame.getFunction() is exports.run then break " at #{formatSourcePosition frame}" "#{err.toString()}\n#{frames.join '\n'}\n"
true
### this file is based on coffeescript/src/command.coffee(https://github.com/jashkenas/coffeescript) Thanks to PI:NAME:<NAME>END_PI Some stuffs is added or modified for taiji langauge. ### ### Copyright (c) 2009-2014 PI:NAME:<NAME>END_PI Copyright (c) 2014-2015 Caoxingming 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. ### # The `taiji` utility. Handles command-line compilation of taijilang # into various forms: saved into `.js` files or printed to stdout # printed as a token stream or as the syntax tree, or launch an interactive repl. # taiji can be used both on the server based on Node.js/V8, or to run directly in the browser. # This module contains the main entry functions for tokenizing, parsing, and compiling source taiji into JavaScript. fs = require 'fs' path = require 'path' vm = require 'vm' {spawn, exec} = require 'child_process' {EventEmitter} = require 'events' mkdirp = require 'mkdirp' {extend, baseFileName} = utils = require './utils' optparse = require './optparse' taiji = require './taiji' TaijiModule = require './module' SourceMap = require './sourcemap' useWinPathSep = path.sep is '\\' # Allow taiji to emit Node.js events. extend taiji, new EventEmitter printLine = (line) -> process.stdout.write line + '\n' printWarn = (line) -> process.stderr.write line + '\n' hidden = (file) -> /^\.|~$/.test file # The help banner that is printed in conjunction with `-h`/`--help`. BANNER = ''' Usage: taiji [options] path/to/script.tj -- [args] If called without options, taiji will run your script. ''' # The list of all the valid option flags that `taiji` knows how to handle. SWITCHES = [ ['-a', '--parse', 'print out the json list that the parser produces'] ['-b', '--bare', 'compile without a top-level function wrapper'] ['-c', '--compile', 'compile to JavaScript and save as .js files'] ['-d', '--nodejs [ARGS]', 'pass options directly to the "node" binary'] ['-e', '--eval', 'pass a string from the command line as input'] ['-h', '--help', 'display this help message'] ['-i', '--interactive', 'run an interactive taiji repl'] ['-j', '--join [FILE]', 'concatenate the source taiji before compiling'] ['-m', '--map', 'generate source map and save as .map files'] ['-n', '--no-optimize', 'compile to javascript code without optimization'] ['-o', '--output [DIR]', 'set the output directory for compiled JavaScript'] ['-p', '--print', 'print out the compiled JavaScript'] ['-r', '--no-header', 'suppress the "Generated by" header'] ['-s', '--stdio', 'listen for and compile scripts over stdio'] ['-t', '--transforma', 'print out the internal expression after transforming'] ['-v', '--version', 'display the version number'] ['-z', '--optimize', 'print out the internal expression after optimizing'] ] # Top-level objects shared by all the functions. exports.testing = false exports.opts = opts = {} sourceCode = []; optionParser = null # Run `taiji` by parsing passed options and determining what action to take Many flags cause us to divert before compiling anything. # Flags passed after `--` will be passed verbatim to your script as arguments in `process.argv` exports.run = -> parseOptions() # Make the repl *CLI* use the global context so as to # (a) be consistent with the `node` repl CLI and, therefore, # (b) make packages that modify native prototypes (such as 'colors' and 'sugar') work as expected. replCliOpts = useGlobal: true return forkNode() if opts.nodejs return usage() if opts.help return version() if opts.version return require('./repl').start(replCliOpts) if opts.interactive return compileStdio() if opts.stdio return compileScript 'compileCode', null, opts.arguments[0] if opts.eval return require('./repl').start(replCliOpts) unless opts.arguments.length # console.log 'in run()'+(JSON.stringify opts) #opts.print = true # simeon literals = if opts.run then opts.arguments.splice 1 else [] process.argv = process.argv[0..1].concat literals process.argv[0] = 'taiji' opts.output = path.resolve opts.output if opts.output for source in opts.arguments source = path.resolve(source) if opts.compile or opts.run if opts.noOptimize then compilePath 'compileCodeWithoutOptimization', source, true, source else compilePath 'compile', source, true, source if opts.parse then compilePath 'parse', source, true, source if opts.transform then compilePath 'transform', source, true, source if opts.optimize then compilePath 'optimize', source, true, source # Compile a path, which could be a script or a directory. # If a directory is passed, recursively compile all '.taiji', and '.tj' extension source files in it and all subdirectories. compilePath = (action, source, topLevel, base) -> try stats = fs.statSync source catch err if err.code is 'ENOENT' then console.error "File not found: #{source}"; process.exit 1 throw err if stats.isDirectory() if opts.run then compilePath action, findDirectoryIndex(source), topLevel, base; return try files = fs.readdirSync source catch err then (if err.code is 'ENOENT' then return else throw err) for file in files then compilePath action, (path.join source, file), no, base else if topLevel or utils.isTaiji source try code = fs.readFileSync source catch err then (if err.code is 'ENOENT' then return else throw err) compileScript(action, source, code.toString(), base) findDirectoryIndex = (source) -> for ext in taiji.FILE_EXTENSIONS index = path.join source, "index#{ext}" try return index if (fs.statSync index).isFile() catch err then throw err unless err.code is 'ENOENT' console.error "Missing index.taiji or index.littaiji in #{source}" process.exit 1 # Compile a single source script, containing the given code, according to the requested options. # If evaluating the script directly sets `__filename`, `__dirname` and `module.filename` to be correct relative to the script's path. compileScript = (action, file, input, base = null) -> o = exports.opts; options = compileOptions file, base try t = task = {file, input, options} taiji.emit 'compile', task if o.run taiji.register(); runCode t.input, t.options else compiled = exports[action](t.input, new TaijiModule(file, taiji.rootModule), t.options) t.output = compiled taiji.emit 'success', task if o.print then printLine t.output.trim() else if o.compile then writeJs base, t.file, t.output, options.outputPath, t.sourceMap else writeResult base, t.file, t.output, options.outputPath, action catch err taiji.emit 'failure', err, task return if taiji.listeners('failure').length message = err.stack or "#{err}" printWarn message; process.exit 1 # Get the corresponding output JavaScript path for a source file. outputPath = (source, base, extension=".js") -> basename = utils.baseFileName source, true, useWinPathSep srcDir = path.dirname source if not opts.output then dir = srcDir else if source is base then dir = opts.output else dir = path.join opts.output, path.relative base, srcDir path.join dir, basename + extension # Write out a JavaScript source file with the compiled code. # By default, files are written out in `cwd` as `.js` files with the same name, # but the output directory can be customized with `--output`. writeJs = (base, sourcePath, js, jsPath) -> jsDir = path.dirname jsPath processFile = -> if opts.compile js = ' ' if js.length==0 fs.writeFile jsPath, js, (err) -> if err then printLine err.message fs.exists jsDir, (itExists) -> if itExists then processFile() else mkdirp jsDir, processFile writeResult = (base, sourcePath, obj, objPath, action) -> objDir = path.dirname objPath objPath = path.join(objDir, baseFileName(sourcePath, true, path.sep=='\\')+'.'+action+'.taiji.json') write = -> obj = ' ' if obj.length==0 fs.writeFile objPath, obj, (err) -> if err then printLine err.message fs.exists objDir, (itExists) -> if itExists then write() else mkdirp objDir, write # Use the [OptionParser module](optparse.html) to extract all options from `process.argv` that are specified in `SWITCHES`. parseOptions = -> optionParser = new optparse.OptionParser SWITCHES, BANNER if not exports.testing o = exports.opts = opts = optionParser.parse process.argv[2..] o.compile or= !!o.output o.run = not (o.compile or o.print or o.map) o.print = !! (o.print or (o.eval or o.stdio and o.compile)) else o = opts = exports.opts # The compile-time options to pass to the taiji compiler. compileOptions = (filename, base) -> answer = {filename, bare: opts.bare, header: opts.compile and not opts['no-header']} if filename if base cwd = process.cwd() outPath = outputPath filename, base jsDir = path.dirname outPath answer = utils.merge answer, { outputPath:outPath sourceRoot: path.relative jsDir, cwd sourceFiles: [path.relative cwd, filename] generatedFile: utils.baseFileName(outPath, no, useWinPathSep) } else answer = utils.merge answer, sourceRoot: "", sourceFiles: [utils.baseFileName filename, no, useWinPathSep] generatedFile: utils.baseFileName(filename, true, useWinPathSep) + ".js" answer # Start up a new Node.js instance with the arguments in `--nodejs` passed to the `node` binary, preserving the other options. forkNode = -> nodeArgs = opts.nodejs.split /\s+/ args = process.argv[1..] args.splice args.indexOf('--nodejs'), 2 p = spawn process.execPath, nodeArgs.concat(args),{cwd: process.cwd(), env: process.env, customFds: [0, 1, 2]} p.on 'exit', (code) -> process.exit code # Print the `--help` usage message and exit. Deprecated switches are not shown. usage = -> printLine (new optparse.OptionParser SWITCHES, BANNER).help() # Print the `--version` message and exit. version = -> printLine "taiji version #{taiji.VERSION}" # parse, transform, optimize, compile taiji code to JavaScript exports.parse = (code, taijiModule, options) -> taiji.parse(code, taijiModule, taiji.builtins, options) exports.transform = (code, taijiModule, options) -> taiji.transform(code, taijiModule, taiji.builtins, options) exports.optimize = (code, taijiModule, options) -> taiji.optimize(code, taijiModule, taiji.builtins, options) exports.compile = (code, taijiModule, options) -> taiji.compile(code, taijiModule, taiji.builtins, options) # Compile and execute a string of taiji (on the server), correctly setting `__filename`, `__dirname`, and relative `require()`. exports.runCode = runCode = (code, options = {}) -> mainModule = require.main mainModule.filename = process.argv[1] = if options.filename then fs.realpathSync(options.filename) else '.' mainModule.moduleCache and= {} dir = if options.filename then path.dirname fs.realpathSync options.filename else fs.realpathSync '.' mainModule.paths = require('module')._nodeModulePaths dir if not utils.isTaiji(mainModule.filename) or require.extensions filename = options.filename or '**evaluated taijilang code**' answer = exports.compile code, new TaijiModule(filename, taiji.rootModule), options code = answer.js ? answer mainModule._compile code, mainModule.filename # Compile and evaluate a string of taiji (in a Node.js-like environment), The taiji repl uses this to run the input. exports.evalCode = (code, options = {}) -> return unless code = code.trim() Script = vm.Script if Script if options.sandbox? if options.sandbox instanceof Script.createContext().constructor sandbox = options.sandbox else sandbox = Script.createContext() sandbox[k] = v for own k, v of options.sandbox sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox else sandbox = global sandbox.__filename = options.filename || 'eval' sandbox.__dirname = path.dirname sandbox.__filename # define module/require only if they chose not to specify their own unless sandbox isnt global or sandbox.module or sandbox.require Module = require 'module' sandbox.module = _module = new Module(options.modulename || 'eval') sandbox.require = _require = (path) -> Module._load path, _module, true _module.filename = sandbox.__filename _require[r] = require[r] for r in Object.getOwnPropertyNames require when r isnt 'paths' # use the same hack node currently uses for their own repl _require.paths = _module.paths = Module._nodeModulePaths process.cwd() _require.resolve = (request) -> Module._resolveFilename request, _module o = {} o[k] = v for own k, v of options o.bare = on # ensure return value js = exports.compile code, new TaijiModule('evaluated-code.tj', taiji.rootModule), o if sandbox is global then vm.runInThisContext js else vm.runInContext js, sandbox # Based on http://v8.googlecode.com/svn/branches/bleeding_edge/src/messages.js formatSourcePosition = (frame) -> fileName = undefined fileLocation = '' if frame.isNative() then fileLocation = "native" else if frame.isEval() fileName = frame.getScriptNameOrSourceURL() fileLocation = "#{frame.getEvalOrigin()}, " unless fileName else fileName = frame.getFileName() fileName or= "<anonymous>" line = frame.getLineNumber() column = frame.getColumnNumber() fileLocation = "#{fileName}:#{line}:#{column}" functionName = frame.getFunctionName() isConstructor = frame.isConstructor() isMethodCall = not (frame.isToplevel() or isConstructor) if isMethodCall methodName = frame.getMethodName() typeName = frame.getTypeName() if functionName tp = as = '' if typeName and functionName.indexOf typeName tp = "#{typeName}." if methodName and functionName.indexOf(".#{methodName}") isnt functionName.length - methodName.length - 1 as = " [as #{methodName}]" "#{tp}#{functionName}#{as} (#{fileLocation})" else "#{typeName}.#{methodName or '<anonymous>'} (#{fileLocation})" else if isConstructor then "new #{functionName or '<anonymous>'} (#{fileLocation})" else if functionName then "#{functionName} (#{fileLocation})" else fileLocation # Based on [michaelficarra/CoffeeScriptRedux](http://goo.gl/ZTx1p) # NodeJS / V8 have no support for transforming positions in stack traces using sourceMap # so we must monkey-patch Error to display taiji source positions. Error.prepareStackTrace = (err, stack) -> frames = for frame in stack if frame.getFunction() is exports.run then break " at #{formatSourcePosition frame}" "#{err.toString()}\n#{frames.join '\n'}\n"
[ { "context": "th = '/_' if _.isEmpty path\n redisKey = \"#{uuid}#{path}\"\n debug { uuid, path, redisKey }\n @r", "end": 765, "score": 0.7178360819816589, "start": 765, "tag": "KEY", "value": "" }, { "context": "ight parsing error /' # WONTFIX\n redisKey = \"#{uuid}/#{pathKey}\"\n debug { uuid, data, key, redisKey,", "end": 1423, "score": 0.7262457013130188, "start": 1417, "tag": "KEY", "value": "uuid}/" } ]
src/services/meshblu-ref-cache-service.coffee
octoblu/meshblu-ref-cache-service
0
_ = require 'lodash' async = require 'async' debug = require('debug')('meshblu-ref-cache-service:meshblu-ref-cache-service') GenericPool = require 'generic-pool' When = require 'when' RedisNS = require '@octoblu/redis-ns' Redis = require 'ioredis' class MeshbluRefCacheService constructor: ({ @redisUri, @namespace }) -> @maxConnections = 10 @minConnections = 1 @idleTimeoutMillis ?= 60000 @redisPool = @_createRedisPool { @maxConnections, @minConnections, @idleTimeoutMillis, @namespace, @redisUri } create: ({ uuid, key, data }, callback) => async.each key, async.apply(@_saveBlob, uuid, data), callback get: ({ uuid, path }, callback) => path = '/_' if _.isEmpty path redisKey = "#{uuid}#{path}" debug { uuid, path, redisKey } @redisPool.acquire().then (client) => client.get redisKey, (error, data) => @redisPool.release client return callback error if error? try data = JSON.parse data catch error return callback null, data if data? callback @_createError 'Not Found', 404 .catch callback _saveBlob: (uuid, data, key, callback) => callback = _.once callback if key == '_' partialData = data else partialData = _.get data, key pathKey = key.replace /\./, '/' # clear highlight parsing error /' # WONTFIX redisKey = "#{uuid}/#{pathKey}" debug { uuid, data, key, redisKey, partialData } return callback() unless partialData? @redisPool.acquire().then (client) => client.set redisKey, JSON.stringify(partialData), (error, data) => @redisPool.release(client) callback error, data .catch callback _createError: (message='Internal Service Error', code=500) => error = new Error message error.code = code return error _createRedisPool: ({ maxConnections, minConnections, idleTimeoutMillis, evictionRunIntervalMillis, acquireTimeoutMillis, namespace, redisUri }) => factory = create: => return When.promise (resolve, reject) => conx = new Redis redisUri, dropBufferSupport: true client = new RedisNS namespace, conx rejectError = (error) => return reject error client.once 'error', rejectError client.once 'ready', => client.removeListener 'error', rejectError resolve client destroy: (client) => return When.promise (resolve, reject) => @_closeClient client, (error) => return reject error if error? resolve() validate: (client) => return When.promise (resolve) => client.ping (error) => return resolve false if error? resolve true options = { max: maxConnections min: minConnections testOnBorrow: true idleTimeoutMillis evictionRunIntervalMillis acquireTimeoutMillis } pool = GenericPool.createPool factory, options pool.on 'factoryCreateError', (error) => @emit 'factoryCreateError', error return pool module.exports = MeshbluRefCacheService
42221
_ = require 'lodash' async = require 'async' debug = require('debug')('meshblu-ref-cache-service:meshblu-ref-cache-service') GenericPool = require 'generic-pool' When = require 'when' RedisNS = require '@octoblu/redis-ns' Redis = require 'ioredis' class MeshbluRefCacheService constructor: ({ @redisUri, @namespace }) -> @maxConnections = 10 @minConnections = 1 @idleTimeoutMillis ?= 60000 @redisPool = @_createRedisPool { @maxConnections, @minConnections, @idleTimeoutMillis, @namespace, @redisUri } create: ({ uuid, key, data }, callback) => async.each key, async.apply(@_saveBlob, uuid, data), callback get: ({ uuid, path }, callback) => path = '/_' if _.isEmpty path redisKey = "#{uuid<KEY>}#{path}" debug { uuid, path, redisKey } @redisPool.acquire().then (client) => client.get redisKey, (error, data) => @redisPool.release client return callback error if error? try data = JSON.parse data catch error return callback null, data if data? callback @_createError 'Not Found', 404 .catch callback _saveBlob: (uuid, data, key, callback) => callback = _.once callback if key == '_' partialData = data else partialData = _.get data, key pathKey = key.replace /\./, '/' # clear highlight parsing error /' # WONTFIX redisKey = "#{<KEY>#{pathKey}" debug { uuid, data, key, redisKey, partialData } return callback() unless partialData? @redisPool.acquire().then (client) => client.set redisKey, JSON.stringify(partialData), (error, data) => @redisPool.release(client) callback error, data .catch callback _createError: (message='Internal Service Error', code=500) => error = new Error message error.code = code return error _createRedisPool: ({ maxConnections, minConnections, idleTimeoutMillis, evictionRunIntervalMillis, acquireTimeoutMillis, namespace, redisUri }) => factory = create: => return When.promise (resolve, reject) => conx = new Redis redisUri, dropBufferSupport: true client = new RedisNS namespace, conx rejectError = (error) => return reject error client.once 'error', rejectError client.once 'ready', => client.removeListener 'error', rejectError resolve client destroy: (client) => return When.promise (resolve, reject) => @_closeClient client, (error) => return reject error if error? resolve() validate: (client) => return When.promise (resolve) => client.ping (error) => return resolve false if error? resolve true options = { max: maxConnections min: minConnections testOnBorrow: true idleTimeoutMillis evictionRunIntervalMillis acquireTimeoutMillis } pool = GenericPool.createPool factory, options pool.on 'factoryCreateError', (error) => @emit 'factoryCreateError', error return pool module.exports = MeshbluRefCacheService
true
_ = require 'lodash' async = require 'async' debug = require('debug')('meshblu-ref-cache-service:meshblu-ref-cache-service') GenericPool = require 'generic-pool' When = require 'when' RedisNS = require '@octoblu/redis-ns' Redis = require 'ioredis' class MeshbluRefCacheService constructor: ({ @redisUri, @namespace }) -> @maxConnections = 10 @minConnections = 1 @idleTimeoutMillis ?= 60000 @redisPool = @_createRedisPool { @maxConnections, @minConnections, @idleTimeoutMillis, @namespace, @redisUri } create: ({ uuid, key, data }, callback) => async.each key, async.apply(@_saveBlob, uuid, data), callback get: ({ uuid, path }, callback) => path = '/_' if _.isEmpty path redisKey = "#{uuidPI:KEY:<KEY>END_PI}#{path}" debug { uuid, path, redisKey } @redisPool.acquire().then (client) => client.get redisKey, (error, data) => @redisPool.release client return callback error if error? try data = JSON.parse data catch error return callback null, data if data? callback @_createError 'Not Found', 404 .catch callback _saveBlob: (uuid, data, key, callback) => callback = _.once callback if key == '_' partialData = data else partialData = _.get data, key pathKey = key.replace /\./, '/' # clear highlight parsing error /' # WONTFIX redisKey = "#{PI:KEY:<KEY>END_PI#{pathKey}" debug { uuid, data, key, redisKey, partialData } return callback() unless partialData? @redisPool.acquire().then (client) => client.set redisKey, JSON.stringify(partialData), (error, data) => @redisPool.release(client) callback error, data .catch callback _createError: (message='Internal Service Error', code=500) => error = new Error message error.code = code return error _createRedisPool: ({ maxConnections, minConnections, idleTimeoutMillis, evictionRunIntervalMillis, acquireTimeoutMillis, namespace, redisUri }) => factory = create: => return When.promise (resolve, reject) => conx = new Redis redisUri, dropBufferSupport: true client = new RedisNS namespace, conx rejectError = (error) => return reject error client.once 'error', rejectError client.once 'ready', => client.removeListener 'error', rejectError resolve client destroy: (client) => return When.promise (resolve, reject) => @_closeClient client, (error) => return reject error if error? resolve() validate: (client) => return When.promise (resolve) => client.ping (error) => return resolve false if error? resolve true options = { max: maxConnections min: minConnections testOnBorrow: true idleTimeoutMillis evictionRunIntervalMillis acquireTimeoutMillis } pool = GenericPool.createPool factory, options pool.on 'factoryCreateError', (error) => @emit 'factoryCreateError', error return pool module.exports = MeshbluRefCacheService
[ { "context": "'offset'] is 'continue'\n context.registers.for[@name]\n else\n context.get(@attributes['offset']", "end": 3014, "score": 0.9626752138137817, "start": 3009, "tag": "USERNAME", "value": "@name" }, { "context": "on for the continue flag\n context.registers.for[@name] = from + segment.length\n context.stack =>\n ", "end": 3441, "score": 0.972736120223999, "start": 3436, "tag": "USERNAME", "value": "@name" }, { "context": " context.set 'forloop',\n name : @name\n length : length\n inde", "end": 3653, "score": 0.5123035907745361, "start": 3653, "tag": "NAME", "value": "" } ]
node_modules/liquid.coffee/src/liquid/tags/for.coffee
darkoverlordofdata/shmupwarz-ooc
1
#+--------------------------------------------------------------------+ #| for.coffee #+--------------------------------------------------------------------+ #| Copyright DarkOverlordOfData (c) 2013 #+--------------------------------------------------------------------+ #| #| This file is a part of liquid.coffee #| #| liquid.coffee is free software; you can copy, modify, and distribute #| it under the terms of the MIT License #| #+--------------------------------------------------------------------+ # # Liquid Templates # Liquid = require('../../liquid') # "For" iterates over an array or collection. # Several useful variables are available to you within the loop. # # == Basic usage: # {% for item in collection %} # {{ forloop.index }}: {{ item.name }} # {% endfor %} # # == Advanced usage: # {% for item in collection %} # <div {% if forloop.first %}class="first"{% endif %}> # Item {{ forloop.index }}: {{ item.name }} # </div> # {% endfor %} # # You can also define a limit and offset much like SQL. Remember # that offset starts at 0 for the first item. # # {% for item in collection limit:5 offset:10 %} # {{ item.name }} # {% end %} # # To reverse the for loop simply use {% for item in collection reversed %} # # == Available variables: # # forloop.name:: 'item-collection' # forloop.length:: Length of the loop # forloop.index:: The current item's position in the collection; # forloop.index starts at 1. # This is helpful for non-programmers who start believe # the first item in an array is 1, not 0. # forloop.index0:: The current item's position in the collection # where the first item is 0 # forloop.rindex:: Number of items remaining in the loop # (length - index) where 1 is the last item. # forloop.rindex0:: Number of items remaining in the loop # where 0 is the last item. # forloop.first:: Returns true if the item is the first item. # forloop.last:: Returns true if the item is the last item. # class Liquid.Tags.For extends Liquid.Block Syntax = ///(\w+)\s+in\s+(#{Liquid.StrictQuotedFragment.source})\s*(reversed)?/// constructor: (tag, markup, tokens) -> if $ = markup.match(Syntax) @variableName = $[1] @collectionName = $[2] @name = "#{$[1]}-#{$[2]}" @reversed = $[3] @attributes = {} markup.replace Liquid.TagAttributes, ($0, key, value) => @attributes[key] = value else throw new Liquid.SyntaxError("Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]") super tag, markup, tokens render: (context) -> context.registers.for = {} unless context.registers.for? collection = context.get(@collectionName) #return '' unless Array.isArray(collection) unless Array.isArray(collection) collection = ({key:k,value:v} for k,v of collection) from = if @attributes['offset'] is 'continue' context.registers.for[@name] else context.get(@attributes['offset']) limit = context.get(@attributes['limit']) to = if limit then (limit + from) else collection.length segment = collection.slice(from, to) return '' if segment.length is 0 segment.reverse() if @reversed result = '' length = segment.length # Store our progress through the collection for the continue flag context.registers.for[@name] = from + segment.length context.stack => #segment.forEach (item, index) => for item, index in segment context.set @variableName, item context.set 'forloop', name : @name length : length index : index + 1 index0 : index rindex : length - index rindex0 : length - index - 1 first : (index is 0) last : (index is length - 1) result += @renderAll(@nodelist, context) # Handle any interrupts if they exist. if context.hasInterrupt() interrupt = context.popInterrupt() break if interrupt instanceof Liquid.BreakInterrupt continue if interrupt instanceof Liquid.ContinueInterrupt #segment.length = 0 if interrupt instanceof Liquid.BreakInterrupt #return if interrupt instanceof Liquid.ContinueInterrupt result Liquid.Template.registerTag "for", Liquid.Tags.For
18706
#+--------------------------------------------------------------------+ #| for.coffee #+--------------------------------------------------------------------+ #| Copyright DarkOverlordOfData (c) 2013 #+--------------------------------------------------------------------+ #| #| This file is a part of liquid.coffee #| #| liquid.coffee is free software; you can copy, modify, and distribute #| it under the terms of the MIT License #| #+--------------------------------------------------------------------+ # # Liquid Templates # Liquid = require('../../liquid') # "For" iterates over an array or collection. # Several useful variables are available to you within the loop. # # == Basic usage: # {% for item in collection %} # {{ forloop.index }}: {{ item.name }} # {% endfor %} # # == Advanced usage: # {% for item in collection %} # <div {% if forloop.first %}class="first"{% endif %}> # Item {{ forloop.index }}: {{ item.name }} # </div> # {% endfor %} # # You can also define a limit and offset much like SQL. Remember # that offset starts at 0 for the first item. # # {% for item in collection limit:5 offset:10 %} # {{ item.name }} # {% end %} # # To reverse the for loop simply use {% for item in collection reversed %} # # == Available variables: # # forloop.name:: 'item-collection' # forloop.length:: Length of the loop # forloop.index:: The current item's position in the collection; # forloop.index starts at 1. # This is helpful for non-programmers who start believe # the first item in an array is 1, not 0. # forloop.index0:: The current item's position in the collection # where the first item is 0 # forloop.rindex:: Number of items remaining in the loop # (length - index) where 1 is the last item. # forloop.rindex0:: Number of items remaining in the loop # where 0 is the last item. # forloop.first:: Returns true if the item is the first item. # forloop.last:: Returns true if the item is the last item. # class Liquid.Tags.For extends Liquid.Block Syntax = ///(\w+)\s+in\s+(#{Liquid.StrictQuotedFragment.source})\s*(reversed)?/// constructor: (tag, markup, tokens) -> if $ = markup.match(Syntax) @variableName = $[1] @collectionName = $[2] @name = "#{$[1]}-#{$[2]}" @reversed = $[3] @attributes = {} markup.replace Liquid.TagAttributes, ($0, key, value) => @attributes[key] = value else throw new Liquid.SyntaxError("Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]") super tag, markup, tokens render: (context) -> context.registers.for = {} unless context.registers.for? collection = context.get(@collectionName) #return '' unless Array.isArray(collection) unless Array.isArray(collection) collection = ({key:k,value:v} for k,v of collection) from = if @attributes['offset'] is 'continue' context.registers.for[@name] else context.get(@attributes['offset']) limit = context.get(@attributes['limit']) to = if limit then (limit + from) else collection.length segment = collection.slice(from, to) return '' if segment.length is 0 segment.reverse() if @reversed result = '' length = segment.length # Store our progress through the collection for the continue flag context.registers.for[@name] = from + segment.length context.stack => #segment.forEach (item, index) => for item, index in segment context.set @variableName, item context.set 'forloop', name :<NAME> @name length : length index : index + 1 index0 : index rindex : length - index rindex0 : length - index - 1 first : (index is 0) last : (index is length - 1) result += @renderAll(@nodelist, context) # Handle any interrupts if they exist. if context.hasInterrupt() interrupt = context.popInterrupt() break if interrupt instanceof Liquid.BreakInterrupt continue if interrupt instanceof Liquid.ContinueInterrupt #segment.length = 0 if interrupt instanceof Liquid.BreakInterrupt #return if interrupt instanceof Liquid.ContinueInterrupt result Liquid.Template.registerTag "for", Liquid.Tags.For
true
#+--------------------------------------------------------------------+ #| for.coffee #+--------------------------------------------------------------------+ #| Copyright DarkOverlordOfData (c) 2013 #+--------------------------------------------------------------------+ #| #| This file is a part of liquid.coffee #| #| liquid.coffee is free software; you can copy, modify, and distribute #| it under the terms of the MIT License #| #+--------------------------------------------------------------------+ # # Liquid Templates # Liquid = require('../../liquid') # "For" iterates over an array or collection. # Several useful variables are available to you within the loop. # # == Basic usage: # {% for item in collection %} # {{ forloop.index }}: {{ item.name }} # {% endfor %} # # == Advanced usage: # {% for item in collection %} # <div {% if forloop.first %}class="first"{% endif %}> # Item {{ forloop.index }}: {{ item.name }} # </div> # {% endfor %} # # You can also define a limit and offset much like SQL. Remember # that offset starts at 0 for the first item. # # {% for item in collection limit:5 offset:10 %} # {{ item.name }} # {% end %} # # To reverse the for loop simply use {% for item in collection reversed %} # # == Available variables: # # forloop.name:: 'item-collection' # forloop.length:: Length of the loop # forloop.index:: The current item's position in the collection; # forloop.index starts at 1. # This is helpful for non-programmers who start believe # the first item in an array is 1, not 0. # forloop.index0:: The current item's position in the collection # where the first item is 0 # forloop.rindex:: Number of items remaining in the loop # (length - index) where 1 is the last item. # forloop.rindex0:: Number of items remaining in the loop # where 0 is the last item. # forloop.first:: Returns true if the item is the first item. # forloop.last:: Returns true if the item is the last item. # class Liquid.Tags.For extends Liquid.Block Syntax = ///(\w+)\s+in\s+(#{Liquid.StrictQuotedFragment.source})\s*(reversed)?/// constructor: (tag, markup, tokens) -> if $ = markup.match(Syntax) @variableName = $[1] @collectionName = $[2] @name = "#{$[1]}-#{$[2]}" @reversed = $[3] @attributes = {} markup.replace Liquid.TagAttributes, ($0, key, value) => @attributes[key] = value else throw new Liquid.SyntaxError("Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]") super tag, markup, tokens render: (context) -> context.registers.for = {} unless context.registers.for? collection = context.get(@collectionName) #return '' unless Array.isArray(collection) unless Array.isArray(collection) collection = ({key:k,value:v} for k,v of collection) from = if @attributes['offset'] is 'continue' context.registers.for[@name] else context.get(@attributes['offset']) limit = context.get(@attributes['limit']) to = if limit then (limit + from) else collection.length segment = collection.slice(from, to) return '' if segment.length is 0 segment.reverse() if @reversed result = '' length = segment.length # Store our progress through the collection for the continue flag context.registers.for[@name] = from + segment.length context.stack => #segment.forEach (item, index) => for item, index in segment context.set @variableName, item context.set 'forloop', name :PI:NAME:<NAME>END_PI @name length : length index : index + 1 index0 : index rindex : length - index rindex0 : length - index - 1 first : (index is 0) last : (index is length - 1) result += @renderAll(@nodelist, context) # Handle any interrupts if they exist. if context.hasInterrupt() interrupt = context.popInterrupt() break if interrupt instanceof Liquid.BreakInterrupt continue if interrupt instanceof Liquid.ContinueInterrupt #segment.length = 0 if interrupt instanceof Liquid.BreakInterrupt #return if interrupt instanceof Liquid.ContinueInterrupt result Liquid.Template.registerTag "for", Liquid.Tags.For
[ { "context": ".com\n# full_roomname = webapps@conference.digitalreasoning.com\n# STASH_JIRA_URL - The URL to your JIRA inst", "end": 485, "score": 0.9999225735664368, "start": 446, "tag": "EMAIL", "value": "webapps@conference.digitalreasoning.com" }, { "context": ":<port>/stash/webhooks/<room name>\n#\n# Author:\n# Kyle Guichard (kgsharp)\n# Chason Choate (cha55son)\nltx = requ", "end": 885, "score": 0.9998849630355835, "start": 872, "tag": "NAME", "value": "Kyle Guichard" }, { "context": "bhooks/<room name>\n#\n# Author:\n# Kyle Guichard (kgsharp)\n# Chason Choate (cha55son)\nltx = require 'ltx'", "end": 894, "score": 0.9994746446609497, "start": 887, "tag": "USERNAME", "value": "kgsharp" }, { "context": " name>\n#\n# Author:\n# Kyle Guichard (kgsharp)\n# Chason Choate (cha55son)\nltx = require 'ltx'\npath = require 'pa", "end": 913, "score": 0.9998722076416016, "start": 900, "tag": "NAME", "value": "Chason Choate" }, { "context": "r:\n# Kyle Guichard (kgsharp)\n# Chason Choate (cha55son)\nltx = require 'ltx'\npath = require 'path'\nfs = r", "end": 923, "score": 0.9990174770355225, "start": 915, "tag": "USERNAME", "value": "cha55son" } ]
index.coffee
cha55son/hubot-stash-webhooks
0
# Description: # Accepts Atlassian Stash post commit webhook POSTs and delivers to XMPP chat # # Dependencies: # None # # Configurations: # STASH_HOST_URL - The URL to your stash instance. # STASH_ROOM_SUFFIX - To be appended to the end of the roomname. # Ex. roomname = webapps # roomname_suffix = @conference.digitalreasoning.com # full_roomname = webapps@conference.digitalreasoning.com # STASH_JIRA_URL - The URL to your JIRA instance. This env var will check the other following # env vars before reading this env var: # STASH_JIRA_URL = STASH_JIRA_URL || HUBOT_JIRA_URL || JIRA_HOST_URL # # Commands: # # Notes: # Setup Stash to submit a webhook to http://<hubot host>:<port>/stash/webhooks/<room name> # # Author: # Kyle Guichard (kgsharp) # Chason Choate (cha55son) ltx = require 'ltx' path = require 'path' fs = require 'fs' sanitize = require 'sanitize-html' module.exports = (robot) -> STASH_URL = process.env.STASH_HOST_URL ROOM_SUFFIX = process.env.STASH_ROOM_SUFFIX JIRA_URL = process.env.STASH_JIRA_URL || process.env.HUBOT_JIRA_URL || process.env.JIRA_HOST_URL envs_valid = -> if !STASH_URL || !ROOM_SUFFIX robot.logger.warning "You are using the stash.coffee script but do not have all env vars defined." robot.logger.warning "STASH_PROJECTS_URL and/or STASH_ROOM_SUFFIX are not defined. Define them in config.sh." false else true envs_valid() robot.router.post '/stash/webhooks/:room', (req, res) -> return unless envs_valid() room = req.params.room json = JSON.stringify(req.body) message = JSON.parse json if process.env.DEBUG? webhook_name = 'webhook-' + Math.floor(Date.now() / 1000) + '.json' fs.writeFile path.resolve(__dirname + '/logs/' + webhook_name), JSON.stringify(req.body, null, 4), (err) -> return console.log(err) if err robot.logger.info "Stash webhook data written to: logs/#{webhook_name}" text = '' html = '' project_url = "#{STASH_URL}/projects/#{message.repository.project.key}/" repo_url = "#{project_url}repos/#{message.repository.slug}/" message.refChanges.forEach (ref, i, arr) -> action = ref.type.toLowerCase() name = ref.refId.replace('refs/tags/', '').replace('refs/heads/', '') url = "#{repo_url}commits?until=#{name}" type = if ref.refId.match('refs/tags/') then 'tag' else 'branch' repo_name = "#{message.repository.project.name}/#{message.repository.name}" html_repo_link = "<a href='#{project_url}'>#{message.repository.project.name}</a>/<a href='#{repo_url}'>#{message.repository.name}</a>" if action == 'add' text += "โž• Created #{type} #{url} on #{repo_name}" html += "โž• Created #{type} <a href='#{url}'>#{name}</a> on #{html_repo_link}" else if action == 'delete' text += "โž– Deleted #{type} #{name} on #{repo_name}" html += "โž– Deleted #{type} <em>#{name}</em> on #{html_repo_link}" else if action == 'update' text += "โžœ Updated branch #{name} on #{repo_name}" html += "โžœ Updated branch <a href='#{url}'>#{name}</a> on #{html_repo_link}" else robot.logger.error "Do not recognize ref action '#{action}'" robot.logger.error json return if type == 'branch' if message.changesets.values.length > 0 html += '<br/>' text += "\n" subset = message.changesets.values.slice(0, 3) subset.forEach (changeset, j, arr) -> user_link = "#{STASH_URL}/users/#{changeset.toCommit.author.emailAddress.split('@')[0]}" text += "#{changeset.toCommit.author.name} - #{sanitize(changeset.toCommit.message)} #{changeset.links.self[0].href}" text += "\n" unless j == arr.length - 1 # Replace newlines with <br/>. msg = sanitize(changeset.toCommit.message).replace(/\n/g, "<br/> ") # Replace JIRA issues with links. if JIRA_URL msg = msg.replace /([a-zA-Z]{2,10}-[0-9]+)/g, (match, p1) -> "<a href='#{JIRA_URL}/browse/#{match}'>#{match}</a>" html += "<a href='#{user_link}'>#{changeset.toCommit.author.name}</a> <em>#{msg}</em> " + "(<a href='#{changeset.links.self[0].href}'>#{changeset.toCommit.displayId}</a>)" html += "<br/>" unless j == arr.length - 1 if message.changesets.values.length > subset.length left = message.changesets.values.length - subset.length text += "\nand #{left} more commit#{ if left == 1 then '' else 's' }" html += "<br/><em>and #{left} more commit#{ if left == 1 then '' else 's' }</em>" text += "\n" unless i == arr.length - 1 html += "<br/>" unless i == arr.length - 1 # Build the HTML XMPP response message = "<message>" + "<body>#{sanitize(text)}</body>" + "<html xmlns='http://jabber.org/protocol/xhtml-im'>" + "<body xmlns='http://www.w3.org/1999/xhtml'>#{html}</body>" + "</html>" + "</message>" user = robot.brain.userForId 'broadcast' user.room = room + ROOM_SUFFIX user.type = 'groupchat' robot.send user, ltx.parse(message) # Respond to request res.writeHead 200, { 'Content-Type': 'text/plain' } res.end 'Thanks'
147590
# Description: # Accepts Atlassian Stash post commit webhook POSTs and delivers to XMPP chat # # Dependencies: # None # # Configurations: # STASH_HOST_URL - The URL to your stash instance. # STASH_ROOM_SUFFIX - To be appended to the end of the roomname. # Ex. roomname = webapps # roomname_suffix = @conference.digitalreasoning.com # full_roomname = <EMAIL> # STASH_JIRA_URL - The URL to your JIRA instance. This env var will check the other following # env vars before reading this env var: # STASH_JIRA_URL = STASH_JIRA_URL || HUBOT_JIRA_URL || JIRA_HOST_URL # # Commands: # # Notes: # Setup Stash to submit a webhook to http://<hubot host>:<port>/stash/webhooks/<room name> # # Author: # <NAME> (kgsharp) # <NAME> (cha55son) ltx = require 'ltx' path = require 'path' fs = require 'fs' sanitize = require 'sanitize-html' module.exports = (robot) -> STASH_URL = process.env.STASH_HOST_URL ROOM_SUFFIX = process.env.STASH_ROOM_SUFFIX JIRA_URL = process.env.STASH_JIRA_URL || process.env.HUBOT_JIRA_URL || process.env.JIRA_HOST_URL envs_valid = -> if !STASH_URL || !ROOM_SUFFIX robot.logger.warning "You are using the stash.coffee script but do not have all env vars defined." robot.logger.warning "STASH_PROJECTS_URL and/or STASH_ROOM_SUFFIX are not defined. Define them in config.sh." false else true envs_valid() robot.router.post '/stash/webhooks/:room', (req, res) -> return unless envs_valid() room = req.params.room json = JSON.stringify(req.body) message = JSON.parse json if process.env.DEBUG? webhook_name = 'webhook-' + Math.floor(Date.now() / 1000) + '.json' fs.writeFile path.resolve(__dirname + '/logs/' + webhook_name), JSON.stringify(req.body, null, 4), (err) -> return console.log(err) if err robot.logger.info "Stash webhook data written to: logs/#{webhook_name}" text = '' html = '' project_url = "#{STASH_URL}/projects/#{message.repository.project.key}/" repo_url = "#{project_url}repos/#{message.repository.slug}/" message.refChanges.forEach (ref, i, arr) -> action = ref.type.toLowerCase() name = ref.refId.replace('refs/tags/', '').replace('refs/heads/', '') url = "#{repo_url}commits?until=#{name}" type = if ref.refId.match('refs/tags/') then 'tag' else 'branch' repo_name = "#{message.repository.project.name}/#{message.repository.name}" html_repo_link = "<a href='#{project_url}'>#{message.repository.project.name}</a>/<a href='#{repo_url}'>#{message.repository.name}</a>" if action == 'add' text += "โž• Created #{type} #{url} on #{repo_name}" html += "โž• Created #{type} <a href='#{url}'>#{name}</a> on #{html_repo_link}" else if action == 'delete' text += "โž– Deleted #{type} #{name} on #{repo_name}" html += "โž– Deleted #{type} <em>#{name}</em> on #{html_repo_link}" else if action == 'update' text += "โžœ Updated branch #{name} on #{repo_name}" html += "โžœ Updated branch <a href='#{url}'>#{name}</a> on #{html_repo_link}" else robot.logger.error "Do not recognize ref action '#{action}'" robot.logger.error json return if type == 'branch' if message.changesets.values.length > 0 html += '<br/>' text += "\n" subset = message.changesets.values.slice(0, 3) subset.forEach (changeset, j, arr) -> user_link = "#{STASH_URL}/users/#{changeset.toCommit.author.emailAddress.split('@')[0]}" text += "#{changeset.toCommit.author.name} - #{sanitize(changeset.toCommit.message)} #{changeset.links.self[0].href}" text += "\n" unless j == arr.length - 1 # Replace newlines with <br/>. msg = sanitize(changeset.toCommit.message).replace(/\n/g, "<br/> ") # Replace JIRA issues with links. if JIRA_URL msg = msg.replace /([a-zA-Z]{2,10}-[0-9]+)/g, (match, p1) -> "<a href='#{JIRA_URL}/browse/#{match}'>#{match}</a>" html += "<a href='#{user_link}'>#{changeset.toCommit.author.name}</a> <em>#{msg}</em> " + "(<a href='#{changeset.links.self[0].href}'>#{changeset.toCommit.displayId}</a>)" html += "<br/>" unless j == arr.length - 1 if message.changesets.values.length > subset.length left = message.changesets.values.length - subset.length text += "\nand #{left} more commit#{ if left == 1 then '' else 's' }" html += "<br/><em>and #{left} more commit#{ if left == 1 then '' else 's' }</em>" text += "\n" unless i == arr.length - 1 html += "<br/>" unless i == arr.length - 1 # Build the HTML XMPP response message = "<message>" + "<body>#{sanitize(text)}</body>" + "<html xmlns='http://jabber.org/protocol/xhtml-im'>" + "<body xmlns='http://www.w3.org/1999/xhtml'>#{html}</body>" + "</html>" + "</message>" user = robot.brain.userForId 'broadcast' user.room = room + ROOM_SUFFIX user.type = 'groupchat' robot.send user, ltx.parse(message) # Respond to request res.writeHead 200, { 'Content-Type': 'text/plain' } res.end 'Thanks'
true
# Description: # Accepts Atlassian Stash post commit webhook POSTs and delivers to XMPP chat # # Dependencies: # None # # Configurations: # STASH_HOST_URL - The URL to your stash instance. # STASH_ROOM_SUFFIX - To be appended to the end of the roomname. # Ex. roomname = webapps # roomname_suffix = @conference.digitalreasoning.com # full_roomname = PI:EMAIL:<EMAIL>END_PI # STASH_JIRA_URL - The URL to your JIRA instance. This env var will check the other following # env vars before reading this env var: # STASH_JIRA_URL = STASH_JIRA_URL || HUBOT_JIRA_URL || JIRA_HOST_URL # # Commands: # # Notes: # Setup Stash to submit a webhook to http://<hubot host>:<port>/stash/webhooks/<room name> # # Author: # PI:NAME:<NAME>END_PI (kgsharp) # PI:NAME:<NAME>END_PI (cha55son) ltx = require 'ltx' path = require 'path' fs = require 'fs' sanitize = require 'sanitize-html' module.exports = (robot) -> STASH_URL = process.env.STASH_HOST_URL ROOM_SUFFIX = process.env.STASH_ROOM_SUFFIX JIRA_URL = process.env.STASH_JIRA_URL || process.env.HUBOT_JIRA_URL || process.env.JIRA_HOST_URL envs_valid = -> if !STASH_URL || !ROOM_SUFFIX robot.logger.warning "You are using the stash.coffee script but do not have all env vars defined." robot.logger.warning "STASH_PROJECTS_URL and/or STASH_ROOM_SUFFIX are not defined. Define them in config.sh." false else true envs_valid() robot.router.post '/stash/webhooks/:room', (req, res) -> return unless envs_valid() room = req.params.room json = JSON.stringify(req.body) message = JSON.parse json if process.env.DEBUG? webhook_name = 'webhook-' + Math.floor(Date.now() / 1000) + '.json' fs.writeFile path.resolve(__dirname + '/logs/' + webhook_name), JSON.stringify(req.body, null, 4), (err) -> return console.log(err) if err robot.logger.info "Stash webhook data written to: logs/#{webhook_name}" text = '' html = '' project_url = "#{STASH_URL}/projects/#{message.repository.project.key}/" repo_url = "#{project_url}repos/#{message.repository.slug}/" message.refChanges.forEach (ref, i, arr) -> action = ref.type.toLowerCase() name = ref.refId.replace('refs/tags/', '').replace('refs/heads/', '') url = "#{repo_url}commits?until=#{name}" type = if ref.refId.match('refs/tags/') then 'tag' else 'branch' repo_name = "#{message.repository.project.name}/#{message.repository.name}" html_repo_link = "<a href='#{project_url}'>#{message.repository.project.name}</a>/<a href='#{repo_url}'>#{message.repository.name}</a>" if action == 'add' text += "โž• Created #{type} #{url} on #{repo_name}" html += "โž• Created #{type} <a href='#{url}'>#{name}</a> on #{html_repo_link}" else if action == 'delete' text += "โž– Deleted #{type} #{name} on #{repo_name}" html += "โž– Deleted #{type} <em>#{name}</em> on #{html_repo_link}" else if action == 'update' text += "โžœ Updated branch #{name} on #{repo_name}" html += "โžœ Updated branch <a href='#{url}'>#{name}</a> on #{html_repo_link}" else robot.logger.error "Do not recognize ref action '#{action}'" robot.logger.error json return if type == 'branch' if message.changesets.values.length > 0 html += '<br/>' text += "\n" subset = message.changesets.values.slice(0, 3) subset.forEach (changeset, j, arr) -> user_link = "#{STASH_URL}/users/#{changeset.toCommit.author.emailAddress.split('@')[0]}" text += "#{changeset.toCommit.author.name} - #{sanitize(changeset.toCommit.message)} #{changeset.links.self[0].href}" text += "\n" unless j == arr.length - 1 # Replace newlines with <br/>. msg = sanitize(changeset.toCommit.message).replace(/\n/g, "<br/> ") # Replace JIRA issues with links. if JIRA_URL msg = msg.replace /([a-zA-Z]{2,10}-[0-9]+)/g, (match, p1) -> "<a href='#{JIRA_URL}/browse/#{match}'>#{match}</a>" html += "<a href='#{user_link}'>#{changeset.toCommit.author.name}</a> <em>#{msg}</em> " + "(<a href='#{changeset.links.self[0].href}'>#{changeset.toCommit.displayId}</a>)" html += "<br/>" unless j == arr.length - 1 if message.changesets.values.length > subset.length left = message.changesets.values.length - subset.length text += "\nand #{left} more commit#{ if left == 1 then '' else 's' }" html += "<br/><em>and #{left} more commit#{ if left == 1 then '' else 's' }</em>" text += "\n" unless i == arr.length - 1 html += "<br/>" unless i == arr.length - 1 # Build the HTML XMPP response message = "<message>" + "<body>#{sanitize(text)}</body>" + "<html xmlns='http://jabber.org/protocol/xhtml-im'>" + "<body xmlns='http://www.w3.org/1999/xhtml'>#{html}</body>" + "</html>" + "</message>" user = robot.brain.userForId 'broadcast' user.room = room + ROOM_SUFFIX user.type = 'groupchat' robot.send user, ltx.parse(message) # Respond to request res.writeHead 200, { 'Content-Type': 'text/plain' } res.end 'Thanks'
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesรบs Espino ", "end": 38, "score": 0.9998872876167297, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesรบs Espino Garcia <jespin", "end": 52, "score": 0.9999310374259949, "start": 40, "tag": "EMAIL", "value": "niwi@niwi.be" }, { "context": " Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesรบs Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David B", "end": 94, "score": 0.9998811483383179, "start": 75, "tag": "NAME", "value": "Jesรบs Espino Garcia" }, { "context": "iwi.be>\n# Copyright (C) 2014 Jesรบs Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragรกn Merino <bame", "end": 114, "score": 0.9999348521232605, "start": 96, "tag": "EMAIL", "value": "jespinog@gmail.com" }, { "context": "o Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragรกn Merino <bameda@dbarragan.com>\n#\n# This program is free s", "end": 158, "score": 0.9998817443847656, "start": 137, "tag": "NAME", "value": "David Barragรกn Merino" }, { "context": ".com>\n# Copyright (C) 2014 David Barragรกn Merino <bameda@dbarragan.com>\n#\n# This program is free software: you can redis", "end": 180, "score": 0.9999351501464844, "start": 160, "tag": "EMAIL", "value": "bameda@dbarragan.com" } ]
public/taiga-front/app/coffee/modules/base/storage.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesรบs Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragรกn Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/base/storage.coffee ### taiga = @.taiga class StorageService extends taiga.Service @.$inject = ["$rootScope"] constructor: ($rootScope) -> super() get: (key, _default) -> serializedValue = localStorage.getItem(key) if serializedValue == null return _default or null return JSON.parse(serializedValue) set: (key, val) -> if _.isObject(key) _.each key, (val, key) => @set(key, val) else localStorage.setItem(key, JSON.stringify(val)) contains: (key) -> value = @.get(key) return (value != null) remove: (key) -> localStorage.removeItem(key) clear: -> localStorage.clear() module = angular.module("taigaBase") module.service("$tgStorage", StorageService)
185858
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/base/storage.coffee ### taiga = @.taiga class StorageService extends taiga.Service @.$inject = ["$rootScope"] constructor: ($rootScope) -> super() get: (key, _default) -> serializedValue = localStorage.getItem(key) if serializedValue == null return _default or null return JSON.parse(serializedValue) set: (key, val) -> if _.isObject(key) _.each key, (val, key) => @set(key, val) else localStorage.setItem(key, JSON.stringify(val)) contains: (key) -> value = @.get(key) return (value != null) remove: (key) -> localStorage.removeItem(key) clear: -> localStorage.clear() module = angular.module("taigaBase") module.service("$tgStorage", StorageService)
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/base/storage.coffee ### taiga = @.taiga class StorageService extends taiga.Service @.$inject = ["$rootScope"] constructor: ($rootScope) -> super() get: (key, _default) -> serializedValue = localStorage.getItem(key) if serializedValue == null return _default or null return JSON.parse(serializedValue) set: (key, val) -> if _.isObject(key) _.each key, (val, key) => @set(key, val) else localStorage.setItem(key, JSON.stringify(val)) contains: (key) -> value = @.get(key) return (value != null) remove: (key) -> localStorage.removeItem(key) clear: -> localStorage.clear() module = angular.module("taigaBase") module.service("$tgStorage", StorageService)
[ { "context": "'name', presence: yes\n\n p = new Product name: 'nick'\n p.validate (result, errors) ->\n ok resu", "end": 941, "score": 0.8110060095787048, "start": 937, "tag": "NAME", "value": "nick" } ]
tests/batman/model/validations_test.coffee
airhorns/batman
1
validationsTestSuite = -> asyncTest "validation shouldn leave the model in the same state it left it", -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product oldState = p.state() p.validate (result, errors) -> equal p.state(), oldState QUnit.start() asyncTest "length", 3, -> class Product extends Batman.Model @validate 'exact', length: 5 @validate 'max', maxLength: 4 @validate 'range', lengthWithin: [3, 5] p = new Product exact: '12345', max: '1234', range: '1234' p.validate (result) -> ok result p.set 'exact', '123' p.set 'max', '12345' p.set 'range', '12' p.validate (result, errors) -> ok !result equal errors.length, 3 QUnit.start() asyncTest "presence", 3, -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product name: 'nick' p.validate (result, errors) -> ok result p.unset 'name' p.validate (result, errors) -> ok !result p.set 'name', '' p.validate (result, errors) -> ok !result QUnit.start() asyncTest "presence and length", 4, -> class Product extends Batman.Model @validate 'name', {presence: yes, maxLength: 10, minLength: 3} p = new Product p.validate (result, errors) -> ok !result equal errors.length, 2 p.set 'name', "beans" p.validate (result, errors) -> ok result equal errors.length, 0 QUnit.start() asyncTest "custom async validations", -> letItPass = true class Product extends Batman.Model @validate 'name', (errors, record, key, callback) -> setTimeout -> errors.add 'name', "didn't validate" unless letItPass callback() , 0 p = new Product p.validate (result, errors) -> ok result letItPass = false p.validate (result, errors) -> ok !result QUnit.start() asyncTest "numeric", -> class Product extends Batman.Model @validate 'number', numeric: yes p = new Product number: 5 p.validate (result, errors) -> ok result p.set 'number', "not_a_number" p.validate (result, errors) -> ok !result QUnit.start() QUnit.module "Batman.Model: validations" validationsTestSuite() QUnit.module "Batman.Model: Validations with I18N", setup: -> Batman.I18N.enable() teardown: -> Batman.I18N.disable() validationsTestSuite() QUnit.module "Batman.Model: binding to errors" setup: -> class @Product extends Batman.Model @validate 'name', {presence: true} @product = new @Product @someObject = Batman {product: @product} asyncTest "errors set length should be observable", 4, -> count = 0 errorsAtCount = 0: 1 1: 0 @product.get('errors').observe 'length', (newLength, oldLength) -> equal newLength, errorsAtCount[count++] @product.validate (result, errors) => equal errors.get('length'), 1 @product.set 'name', 'Foo' @product.validate (result, errors) => equal errors.get('length'), 0 QUnit.start() asyncTest "errors set contents should be observable", 3, -> x = @product.get('errors.name') x.observe 'length', (newLength, oldLength) -> equal newLength, 1 @product.validate (result, errors) => equal errors.get('length'), 1 equal errors.length, 1 QUnit.start() asyncTest "errors set length should be bindable", 4, -> @someObject.accessor 'productErrorsLength', -> errors = @get('product.errors') errors.get('length') equal @someObject.get('productErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors set is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productErrorsLength'), 1, 'the foreign key should have updated' QUnit.start() asyncTest "errors set contents should be bindable", 4, -> @someObject.accessor 'productNameErrorsLength', -> errors = @get('product.errors.name.length') equal @someObject.get('productNameErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productNameErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors set is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productNameErrorsLength'), 1, 'the foreign key should have updated' QUnit.start()
46655
validationsTestSuite = -> asyncTest "validation shouldn leave the model in the same state it left it", -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product oldState = p.state() p.validate (result, errors) -> equal p.state(), oldState QUnit.start() asyncTest "length", 3, -> class Product extends Batman.Model @validate 'exact', length: 5 @validate 'max', maxLength: 4 @validate 'range', lengthWithin: [3, 5] p = new Product exact: '12345', max: '1234', range: '1234' p.validate (result) -> ok result p.set 'exact', '123' p.set 'max', '12345' p.set 'range', '12' p.validate (result, errors) -> ok !result equal errors.length, 3 QUnit.start() asyncTest "presence", 3, -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product name: '<NAME>' p.validate (result, errors) -> ok result p.unset 'name' p.validate (result, errors) -> ok !result p.set 'name', '' p.validate (result, errors) -> ok !result QUnit.start() asyncTest "presence and length", 4, -> class Product extends Batman.Model @validate 'name', {presence: yes, maxLength: 10, minLength: 3} p = new Product p.validate (result, errors) -> ok !result equal errors.length, 2 p.set 'name', "beans" p.validate (result, errors) -> ok result equal errors.length, 0 QUnit.start() asyncTest "custom async validations", -> letItPass = true class Product extends Batman.Model @validate 'name', (errors, record, key, callback) -> setTimeout -> errors.add 'name', "didn't validate" unless letItPass callback() , 0 p = new Product p.validate (result, errors) -> ok result letItPass = false p.validate (result, errors) -> ok !result QUnit.start() asyncTest "numeric", -> class Product extends Batman.Model @validate 'number', numeric: yes p = new Product number: 5 p.validate (result, errors) -> ok result p.set 'number', "not_a_number" p.validate (result, errors) -> ok !result QUnit.start() QUnit.module "Batman.Model: validations" validationsTestSuite() QUnit.module "Batman.Model: Validations with I18N", setup: -> Batman.I18N.enable() teardown: -> Batman.I18N.disable() validationsTestSuite() QUnit.module "Batman.Model: binding to errors" setup: -> class @Product extends Batman.Model @validate 'name', {presence: true} @product = new @Product @someObject = Batman {product: @product} asyncTest "errors set length should be observable", 4, -> count = 0 errorsAtCount = 0: 1 1: 0 @product.get('errors').observe 'length', (newLength, oldLength) -> equal newLength, errorsAtCount[count++] @product.validate (result, errors) => equal errors.get('length'), 1 @product.set 'name', 'Foo' @product.validate (result, errors) => equal errors.get('length'), 0 QUnit.start() asyncTest "errors set contents should be observable", 3, -> x = @product.get('errors.name') x.observe 'length', (newLength, oldLength) -> equal newLength, 1 @product.validate (result, errors) => equal errors.get('length'), 1 equal errors.length, 1 QUnit.start() asyncTest "errors set length should be bindable", 4, -> @someObject.accessor 'productErrorsLength', -> errors = @get('product.errors') errors.get('length') equal @someObject.get('productErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors set is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productErrorsLength'), 1, 'the foreign key should have updated' QUnit.start() asyncTest "errors set contents should be bindable", 4, -> @someObject.accessor 'productNameErrorsLength', -> errors = @get('product.errors.name.length') equal @someObject.get('productNameErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productNameErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors set is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productNameErrorsLength'), 1, 'the foreign key should have updated' QUnit.start()
true
validationsTestSuite = -> asyncTest "validation shouldn leave the model in the same state it left it", -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product oldState = p.state() p.validate (result, errors) -> equal p.state(), oldState QUnit.start() asyncTest "length", 3, -> class Product extends Batman.Model @validate 'exact', length: 5 @validate 'max', maxLength: 4 @validate 'range', lengthWithin: [3, 5] p = new Product exact: '12345', max: '1234', range: '1234' p.validate (result) -> ok result p.set 'exact', '123' p.set 'max', '12345' p.set 'range', '12' p.validate (result, errors) -> ok !result equal errors.length, 3 QUnit.start() asyncTest "presence", 3, -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product name: 'PI:NAME:<NAME>END_PI' p.validate (result, errors) -> ok result p.unset 'name' p.validate (result, errors) -> ok !result p.set 'name', '' p.validate (result, errors) -> ok !result QUnit.start() asyncTest "presence and length", 4, -> class Product extends Batman.Model @validate 'name', {presence: yes, maxLength: 10, minLength: 3} p = new Product p.validate (result, errors) -> ok !result equal errors.length, 2 p.set 'name', "beans" p.validate (result, errors) -> ok result equal errors.length, 0 QUnit.start() asyncTest "custom async validations", -> letItPass = true class Product extends Batman.Model @validate 'name', (errors, record, key, callback) -> setTimeout -> errors.add 'name', "didn't validate" unless letItPass callback() , 0 p = new Product p.validate (result, errors) -> ok result letItPass = false p.validate (result, errors) -> ok !result QUnit.start() asyncTest "numeric", -> class Product extends Batman.Model @validate 'number', numeric: yes p = new Product number: 5 p.validate (result, errors) -> ok result p.set 'number', "not_a_number" p.validate (result, errors) -> ok !result QUnit.start() QUnit.module "Batman.Model: validations" validationsTestSuite() QUnit.module "Batman.Model: Validations with I18N", setup: -> Batman.I18N.enable() teardown: -> Batman.I18N.disable() validationsTestSuite() QUnit.module "Batman.Model: binding to errors" setup: -> class @Product extends Batman.Model @validate 'name', {presence: true} @product = new @Product @someObject = Batman {product: @product} asyncTest "errors set length should be observable", 4, -> count = 0 errorsAtCount = 0: 1 1: 0 @product.get('errors').observe 'length', (newLength, oldLength) -> equal newLength, errorsAtCount[count++] @product.validate (result, errors) => equal errors.get('length'), 1 @product.set 'name', 'Foo' @product.validate (result, errors) => equal errors.get('length'), 0 QUnit.start() asyncTest "errors set contents should be observable", 3, -> x = @product.get('errors.name') x.observe 'length', (newLength, oldLength) -> equal newLength, 1 @product.validate (result, errors) => equal errors.get('length'), 1 equal errors.length, 1 QUnit.start() asyncTest "errors set length should be bindable", 4, -> @someObject.accessor 'productErrorsLength', -> errors = @get('product.errors') errors.get('length') equal @someObject.get('productErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors set is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productErrorsLength'), 1, 'the foreign key should have updated' QUnit.start() asyncTest "errors set contents should be bindable", 4, -> @someObject.accessor 'productNameErrorsLength', -> errors = @get('product.errors.name.length') equal @someObject.get('productNameErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productNameErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors set is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productNameErrorsLength'), 1, 'the foreign key should have updated' QUnit.start()
[ { "context": "\"\"\"\n\n\t\t\tUsage: #{'node client.js'.cyan} \"To Name <toaddress@example.com>\" \"From Name <fromaddress@example.com>\" \"Test Sub", "end": 107, "score": 0.9999234080314636, "start": 86, "tag": "EMAIL", "value": "toaddress@example.com" }, { "context": "an} \"To Name <toaddress@example.com>\" \"From Name <fromaddress@example.com>\" \"Test Subject\" \"Test Content\" localhost\n\t\t\t\n\"\"\"", "end": 145, "score": 0.9999231696128845, "start": 122, "tag": "EMAIL", "value": "fromaddress@example.com" } ]
client.coffee
odojs/pokemon-emails
0
args = process.argv.slice 2 usage = """ Usage: #{'node client.js'.cyan} "To Name <toaddress@example.com>" "From Name <fromaddress@example.com>" "Test Subject" "Test Content" localhost """ if args.length isnt 5 console.error usage process.exit 1 deliveremail = require './deliveremail' fs = require 'fs' stream = require 'stream' moment = require 'moment' content = new stream.PassThrough() email = to: args[0] from: args[1] subject: args[2] content: args[3] host: args[4] email.toaddress = email.to.split('<')[1].split('>')[0] email.fromaddress = email.from.split('<')[1].split('>')[0] deliveremail.direct email.toaddress, email.fromaddress, email.host, content, (err, message) -> throw err if err? console.log message content.write """ From: #{email.from} To: #{email.to} Subject: #{email.subject} Date: #{moment().format('ddd, DD MMM YYYY HH:mm:ss ZZ')} MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit #{email.content} """ content.end()
72288
args = process.argv.slice 2 usage = """ Usage: #{'node client.js'.cyan} "To Name <<EMAIL>>" "From Name <<EMAIL>>" "Test Subject" "Test Content" localhost """ if args.length isnt 5 console.error usage process.exit 1 deliveremail = require './deliveremail' fs = require 'fs' stream = require 'stream' moment = require 'moment' content = new stream.PassThrough() email = to: args[0] from: args[1] subject: args[2] content: args[3] host: args[4] email.toaddress = email.to.split('<')[1].split('>')[0] email.fromaddress = email.from.split('<')[1].split('>')[0] deliveremail.direct email.toaddress, email.fromaddress, email.host, content, (err, message) -> throw err if err? console.log message content.write """ From: #{email.from} To: #{email.to} Subject: #{email.subject} Date: #{moment().format('ddd, DD MMM YYYY HH:mm:ss ZZ')} MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit #{email.content} """ content.end()
true
args = process.argv.slice 2 usage = """ Usage: #{'node client.js'.cyan} "To Name <PI:EMAIL:<EMAIL>END_PI>" "From Name <PI:EMAIL:<EMAIL>END_PI>" "Test Subject" "Test Content" localhost """ if args.length isnt 5 console.error usage process.exit 1 deliveremail = require './deliveremail' fs = require 'fs' stream = require 'stream' moment = require 'moment' content = new stream.PassThrough() email = to: args[0] from: args[1] subject: args[2] content: args[3] host: args[4] email.toaddress = email.to.split('<')[1].split('>')[0] email.fromaddress = email.from.split('<')[1].split('>')[0] deliveremail.direct email.toaddress, email.fromaddress, email.host, content, (err, message) -> throw err if err? console.log message content.write """ From: #{email.from} To: #{email.to} Subject: #{email.subject} Date: #{moment().format('ddd, DD MMM YYYY HH:mm:ss ZZ')} MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit #{email.content} """ content.end()
[ { "context": " grunt-smart-assets\n# *\n# *\n# * Copyright (c) 2014 Shapovalov Alexandr\n# * Licensed under the MIT license.\n#\n\"use strict", "end": 75, "score": 0.9997490048408508, "start": 56, "tag": "NAME", "value": "Shapovalov Alexandr" } ]
tasks/smart_assets.coffee
Freezko/grunt-smart-assets
0
# # * grunt-smart-assets # * # * # * Copyright (c) 2014 Shapovalov Alexandr # * Licensed under the MIT license. # "use strict" module.exports = (grunt) -> path = require('path') crypto = require('crypto'); _ = require('lodash'); run_task = (task, config) -> default_config = grunt.config.get('task') || {}; default_config['smart_assets'] = config grunt.config.set(task, default_config); grunt.task.run("#{task}:smart_assets"); md5 = (filepath) -> hash = crypto.createHash('md5'); grunt.log.verbose.write("Hashing #{filepath} ..."); hash.update(grunt.file.read(filepath), 'utf8'); return hash.digest('hex').slice(0, 8); patterns = [ [/<script.+src=['"]([^"']+)["']/gim] [/<link[^\>]+href=['"]([^"']+)["']/gim] [/<img[^\>]*[^\>\S]+src=['"]([^"']+)["']/gim] [/<image[^\>]*[^\>\S]+xlink:href=['"]([^"']+)["']/gim] [/<image[^\>]*[^\>\S]+src=['"]([^"']+)["']/gim] [/<(?:img|source)[^\>]*[^\>\S]+srcset=['"]([^"'\s]+)(?:\s\d[mx])["']/gim] [/<source[^\>]+src=['"]([^"']+)["']/gim] #[/<a[^\>]+href=['"]([^"']+)["']/gim] [/<input[^\>]+src=['"]([^"']+)["']/gim] [/data-(?!main).[^=]+=['"]([^'"]+)['"]/gim] [ [/data-main\s*=['"]([^"']+)['"]/gim] (m) -> if m.match(/\.js$/) return m else return m + '.js' (m) -> return m.replace('.js', '') ] [/<object[^\>]+data=['"]([^"']+)["']/gim] ] #standart task need grunt.task.loadNpmTasks('grunt-contrib-copy') # Please see the Grunt documentation for more information regarding task # creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask "smart_assets", -> tasks_to_run = [] # Merge task-specific and/or target-specific options with these defaults. options = @options() defaults_options = files: src: '**/*' streamTasks : {} html: src: '**/*' options = _.merge(defaults_options, options) if !options.files.cwd? or !options.files.dest? grunt.fail.fatal "Your not configure files.cwd or files.dest!" #clean dist before other tasks run if options.files.cleanDest grunt.task.loadNpmTasks('grunt-contrib-clean') run_task 'clean', options.files.dest grunt.registerTask "smart_assets_files", -> files = {} grunt.file.expand({cwd: options.files.cwd, filter: 'isFile'}, options.files.src).forEach (file)-> ext = path.extname file; find = -1; if options.files.streamTasks? _.forEach options.files.streamTasks, (values,key)-> find = key unless _.indexOf(values.from, ext) is -1 unless find is -1 files[find] = new Array() unless _.isArray files[find] files[find].push file else files['copy'] = new Array() unless _.isArray files['copy'] files['copy'].push file _.forEach files, (val, task) -> src = {} task_options = {} if options.files.streamTasks[task]?['options']? and _.isObject options.files.streamTasks[task]['options'] task_options.options = options.files.streamTasks[task]['options'] _.forEach val, (file) -> ext = path.extname(file) result_ext = (if options.files.streamTasks[task]?.to? then options.files.streamTasks[task].to else '') if result_ext != '' result_path = path.join(options.files.dest , file).replace(ext, result_ext) else result_path = path.join(options.files.dest , file) src[result_path] = path.join( options.files.cwd , file) task_options['files'] = src run_task task, task_options tasks_to_run.push "smart_assets_files" if _.isObject options.files.afterTasks grunt.registerTask "smart_assets_filesAfter", -> defaults = expand: true cwd : options.files.dest dest: options.files.dest _.forEach options.files.afterTasks, (options, task)-> run_task task, _.merge(defaults, options) tasks_to_run.push "smart_assets_filesAfter" if _.isObject options.html if !options.html.cwd? or !options.html.dest? grunt.fail.fatal "Your not configure html.cwd or html.dest!" grunt.registerTask "smart_assets_html", -> msg_ok = [] unless _.isArray(msg_ok) msg_warn = [] unless _.isArray(msg_warn) grunt.file.expand({cwd: options.html.cwd, filter: 'isFile'}, options.html.src).forEach (file_name)-> content = grunt.file.read path.join(options.html.cwd, file_name) patterns.forEach (pattern) -> patrn = if pattern[0]?[0]? then pattern[0][0] else pattern[0] match = content.match patrn if match != null match.forEach (result) -> result.match pattern[0] file = RegExp.$1 file_ext = path.extname(file) #ะฑะตั€ะตะผ ั€ะฐััˆะธั€ะตะฝะธะต ั„ะฐะนะปะฐ #ะธั‰ะตะผ ั€ะตะทัƒะปัŒั‚ะธั€ัƒัŽั‰ะตะต result_ext = if options.files.streamTasks[file_ext.split('.').pop()]?.to? then options.files.streamTasks[file_ext.split('.').pop()].to else '' if result_ext != '' result_file =file.replace file_ext, result_ext else result_file =file if pattern[1]? then result_file = pattern[1](result_file) result_file_path = path.join(options.html.assetDir, result_file).replace(options.files.cwd, options.files.dest) result_file = path.join(options.html.assetDir, result_file).replace(options.files.cwd, options.files.dest).replace(options.html.assetDir, '') if grunt.file.exists(result_file_path) && grunt.file.isFile(result_file_path) if pattern[2]? then result_file = pattern[2](result_file) if options.html?.rev? and options.html.rev and !pattern[2]? then result_file = [result_file, md5(result_file_path)].join('?') content = content.replace file, result_file msg_ok.push("Replace #{file} to #{result_file}") else msg_warn.push("Not replaced in html (ignore it if all ok) - #{file}") if msg_ok.length grunt.log.subhead("Changed path in html #{path.join(options.html.cwd, file_name)}:") msg_ok.forEach (msg) -> grunt.log.ok(msg) if msg_warn.length grunt.log.subhead('Error? No! Just warning...:') msg_warn.forEach (msg) -> grunt.log.warn(msg) grunt.file.write path.join(options.html.dest, file_name), content tasks_to_run.push "smart_assets_html" grunt.task.run(tasks_to_run);
93735
# # * grunt-smart-assets # * # * # * Copyright (c) 2014 <NAME> # * Licensed under the MIT license. # "use strict" module.exports = (grunt) -> path = require('path') crypto = require('crypto'); _ = require('lodash'); run_task = (task, config) -> default_config = grunt.config.get('task') || {}; default_config['smart_assets'] = config grunt.config.set(task, default_config); grunt.task.run("#{task}:smart_assets"); md5 = (filepath) -> hash = crypto.createHash('md5'); grunt.log.verbose.write("Hashing #{filepath} ..."); hash.update(grunt.file.read(filepath), 'utf8'); return hash.digest('hex').slice(0, 8); patterns = [ [/<script.+src=['"]([^"']+)["']/gim] [/<link[^\>]+href=['"]([^"']+)["']/gim] [/<img[^\>]*[^\>\S]+src=['"]([^"']+)["']/gim] [/<image[^\>]*[^\>\S]+xlink:href=['"]([^"']+)["']/gim] [/<image[^\>]*[^\>\S]+src=['"]([^"']+)["']/gim] [/<(?:img|source)[^\>]*[^\>\S]+srcset=['"]([^"'\s]+)(?:\s\d[mx])["']/gim] [/<source[^\>]+src=['"]([^"']+)["']/gim] #[/<a[^\>]+href=['"]([^"']+)["']/gim] [/<input[^\>]+src=['"]([^"']+)["']/gim] [/data-(?!main).[^=]+=['"]([^'"]+)['"]/gim] [ [/data-main\s*=['"]([^"']+)['"]/gim] (m) -> if m.match(/\.js$/) return m else return m + '.js' (m) -> return m.replace('.js', '') ] [/<object[^\>]+data=['"]([^"']+)["']/gim] ] #standart task need grunt.task.loadNpmTasks('grunt-contrib-copy') # Please see the Grunt documentation for more information regarding task # creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask "smart_assets", -> tasks_to_run = [] # Merge task-specific and/or target-specific options with these defaults. options = @options() defaults_options = files: src: '**/*' streamTasks : {} html: src: '**/*' options = _.merge(defaults_options, options) if !options.files.cwd? or !options.files.dest? grunt.fail.fatal "Your not configure files.cwd or files.dest!" #clean dist before other tasks run if options.files.cleanDest grunt.task.loadNpmTasks('grunt-contrib-clean') run_task 'clean', options.files.dest grunt.registerTask "smart_assets_files", -> files = {} grunt.file.expand({cwd: options.files.cwd, filter: 'isFile'}, options.files.src).forEach (file)-> ext = path.extname file; find = -1; if options.files.streamTasks? _.forEach options.files.streamTasks, (values,key)-> find = key unless _.indexOf(values.from, ext) is -1 unless find is -1 files[find] = new Array() unless _.isArray files[find] files[find].push file else files['copy'] = new Array() unless _.isArray files['copy'] files['copy'].push file _.forEach files, (val, task) -> src = {} task_options = {} if options.files.streamTasks[task]?['options']? and _.isObject options.files.streamTasks[task]['options'] task_options.options = options.files.streamTasks[task]['options'] _.forEach val, (file) -> ext = path.extname(file) result_ext = (if options.files.streamTasks[task]?.to? then options.files.streamTasks[task].to else '') if result_ext != '' result_path = path.join(options.files.dest , file).replace(ext, result_ext) else result_path = path.join(options.files.dest , file) src[result_path] = path.join( options.files.cwd , file) task_options['files'] = src run_task task, task_options tasks_to_run.push "smart_assets_files" if _.isObject options.files.afterTasks grunt.registerTask "smart_assets_filesAfter", -> defaults = expand: true cwd : options.files.dest dest: options.files.dest _.forEach options.files.afterTasks, (options, task)-> run_task task, _.merge(defaults, options) tasks_to_run.push "smart_assets_filesAfter" if _.isObject options.html if !options.html.cwd? or !options.html.dest? grunt.fail.fatal "Your not configure html.cwd or html.dest!" grunt.registerTask "smart_assets_html", -> msg_ok = [] unless _.isArray(msg_ok) msg_warn = [] unless _.isArray(msg_warn) grunt.file.expand({cwd: options.html.cwd, filter: 'isFile'}, options.html.src).forEach (file_name)-> content = grunt.file.read path.join(options.html.cwd, file_name) patterns.forEach (pattern) -> patrn = if pattern[0]?[0]? then pattern[0][0] else pattern[0] match = content.match patrn if match != null match.forEach (result) -> result.match pattern[0] file = RegExp.$1 file_ext = path.extname(file) #ะฑะตั€ะตะผ ั€ะฐััˆะธั€ะตะฝะธะต ั„ะฐะนะปะฐ #ะธั‰ะตะผ ั€ะตะทัƒะปัŒั‚ะธั€ัƒัŽั‰ะตะต result_ext = if options.files.streamTasks[file_ext.split('.').pop()]?.to? then options.files.streamTasks[file_ext.split('.').pop()].to else '' if result_ext != '' result_file =file.replace file_ext, result_ext else result_file =file if pattern[1]? then result_file = pattern[1](result_file) result_file_path = path.join(options.html.assetDir, result_file).replace(options.files.cwd, options.files.dest) result_file = path.join(options.html.assetDir, result_file).replace(options.files.cwd, options.files.dest).replace(options.html.assetDir, '') if grunt.file.exists(result_file_path) && grunt.file.isFile(result_file_path) if pattern[2]? then result_file = pattern[2](result_file) if options.html?.rev? and options.html.rev and !pattern[2]? then result_file = [result_file, md5(result_file_path)].join('?') content = content.replace file, result_file msg_ok.push("Replace #{file} to #{result_file}") else msg_warn.push("Not replaced in html (ignore it if all ok) - #{file}") if msg_ok.length grunt.log.subhead("Changed path in html #{path.join(options.html.cwd, file_name)}:") msg_ok.forEach (msg) -> grunt.log.ok(msg) if msg_warn.length grunt.log.subhead('Error? No! Just warning...:') msg_warn.forEach (msg) -> grunt.log.warn(msg) grunt.file.write path.join(options.html.dest, file_name), content tasks_to_run.push "smart_assets_html" grunt.task.run(tasks_to_run);
true
# # * grunt-smart-assets # * # * # * Copyright (c) 2014 PI:NAME:<NAME>END_PI # * Licensed under the MIT license. # "use strict" module.exports = (grunt) -> path = require('path') crypto = require('crypto'); _ = require('lodash'); run_task = (task, config) -> default_config = grunt.config.get('task') || {}; default_config['smart_assets'] = config grunt.config.set(task, default_config); grunt.task.run("#{task}:smart_assets"); md5 = (filepath) -> hash = crypto.createHash('md5'); grunt.log.verbose.write("Hashing #{filepath} ..."); hash.update(grunt.file.read(filepath), 'utf8'); return hash.digest('hex').slice(0, 8); patterns = [ [/<script.+src=['"]([^"']+)["']/gim] [/<link[^\>]+href=['"]([^"']+)["']/gim] [/<img[^\>]*[^\>\S]+src=['"]([^"']+)["']/gim] [/<image[^\>]*[^\>\S]+xlink:href=['"]([^"']+)["']/gim] [/<image[^\>]*[^\>\S]+src=['"]([^"']+)["']/gim] [/<(?:img|source)[^\>]*[^\>\S]+srcset=['"]([^"'\s]+)(?:\s\d[mx])["']/gim] [/<source[^\>]+src=['"]([^"']+)["']/gim] #[/<a[^\>]+href=['"]([^"']+)["']/gim] [/<input[^\>]+src=['"]([^"']+)["']/gim] [/data-(?!main).[^=]+=['"]([^'"]+)['"]/gim] [ [/data-main\s*=['"]([^"']+)['"]/gim] (m) -> if m.match(/\.js$/) return m else return m + '.js' (m) -> return m.replace('.js', '') ] [/<object[^\>]+data=['"]([^"']+)["']/gim] ] #standart task need grunt.task.loadNpmTasks('grunt-contrib-copy') # Please see the Grunt documentation for more information regarding task # creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask "smart_assets", -> tasks_to_run = [] # Merge task-specific and/or target-specific options with these defaults. options = @options() defaults_options = files: src: '**/*' streamTasks : {} html: src: '**/*' options = _.merge(defaults_options, options) if !options.files.cwd? or !options.files.dest? grunt.fail.fatal "Your not configure files.cwd or files.dest!" #clean dist before other tasks run if options.files.cleanDest grunt.task.loadNpmTasks('grunt-contrib-clean') run_task 'clean', options.files.dest grunt.registerTask "smart_assets_files", -> files = {} grunt.file.expand({cwd: options.files.cwd, filter: 'isFile'}, options.files.src).forEach (file)-> ext = path.extname file; find = -1; if options.files.streamTasks? _.forEach options.files.streamTasks, (values,key)-> find = key unless _.indexOf(values.from, ext) is -1 unless find is -1 files[find] = new Array() unless _.isArray files[find] files[find].push file else files['copy'] = new Array() unless _.isArray files['copy'] files['copy'].push file _.forEach files, (val, task) -> src = {} task_options = {} if options.files.streamTasks[task]?['options']? and _.isObject options.files.streamTasks[task]['options'] task_options.options = options.files.streamTasks[task]['options'] _.forEach val, (file) -> ext = path.extname(file) result_ext = (if options.files.streamTasks[task]?.to? then options.files.streamTasks[task].to else '') if result_ext != '' result_path = path.join(options.files.dest , file).replace(ext, result_ext) else result_path = path.join(options.files.dest , file) src[result_path] = path.join( options.files.cwd , file) task_options['files'] = src run_task task, task_options tasks_to_run.push "smart_assets_files" if _.isObject options.files.afterTasks grunt.registerTask "smart_assets_filesAfter", -> defaults = expand: true cwd : options.files.dest dest: options.files.dest _.forEach options.files.afterTasks, (options, task)-> run_task task, _.merge(defaults, options) tasks_to_run.push "smart_assets_filesAfter" if _.isObject options.html if !options.html.cwd? or !options.html.dest? grunt.fail.fatal "Your not configure html.cwd or html.dest!" grunt.registerTask "smart_assets_html", -> msg_ok = [] unless _.isArray(msg_ok) msg_warn = [] unless _.isArray(msg_warn) grunt.file.expand({cwd: options.html.cwd, filter: 'isFile'}, options.html.src).forEach (file_name)-> content = grunt.file.read path.join(options.html.cwd, file_name) patterns.forEach (pattern) -> patrn = if pattern[0]?[0]? then pattern[0][0] else pattern[0] match = content.match patrn if match != null match.forEach (result) -> result.match pattern[0] file = RegExp.$1 file_ext = path.extname(file) #ะฑะตั€ะตะผ ั€ะฐััˆะธั€ะตะฝะธะต ั„ะฐะนะปะฐ #ะธั‰ะตะผ ั€ะตะทัƒะปัŒั‚ะธั€ัƒัŽั‰ะตะต result_ext = if options.files.streamTasks[file_ext.split('.').pop()]?.to? then options.files.streamTasks[file_ext.split('.').pop()].to else '' if result_ext != '' result_file =file.replace file_ext, result_ext else result_file =file if pattern[1]? then result_file = pattern[1](result_file) result_file_path = path.join(options.html.assetDir, result_file).replace(options.files.cwd, options.files.dest) result_file = path.join(options.html.assetDir, result_file).replace(options.files.cwd, options.files.dest).replace(options.html.assetDir, '') if grunt.file.exists(result_file_path) && grunt.file.isFile(result_file_path) if pattern[2]? then result_file = pattern[2](result_file) if options.html?.rev? and options.html.rev and !pattern[2]? then result_file = [result_file, md5(result_file_path)].join('?') content = content.replace file, result_file msg_ok.push("Replace #{file} to #{result_file}") else msg_warn.push("Not replaced in html (ignore it if all ok) - #{file}") if msg_ok.length grunt.log.subhead("Changed path in html #{path.join(options.html.cwd, file_name)}:") msg_ok.forEach (msg) -> grunt.log.ok(msg) if msg_warn.length grunt.log.subhead('Error? No! Just warning...:') msg_warn.forEach (msg) -> grunt.log.warn(msg) grunt.file.write path.join(options.html.dest, file_name), content tasks_to_run.push "smart_assets_html" grunt.task.run(tasks_to_run);
[ { "context": " avatar: creator.avatar\n name: creator.name\n totalBlipCount: total\n ", "end": 7872, "score": 0.5552603006362915, "start": 7865, "tag": "NAME", "value": "creator" }, { "context": "atar: creator.avatar\n name: creator.name\n totalBlipCount: total\n ", "end": 7872, "score": 0.337285578250885, "start": 7872, "tag": "USERNAME", "value": "" }, { "context": "tar: creator.avatar\n name: creator.name\n totalBlipCount: total\n ", "end": 7877, "score": 0.37935465574264526, "start": 7873, "tag": "NAME", "value": "name" } ]
src/server/blip/search_controller.coffee
LaPingvino/rizzoma
88
_= require('underscore') async = require('async') SearchController = require('../search/controller').SearchController CouchBlipProcessor = require('../blip/couch_processor').CouchBlipProcessor CouchWaveProcessor = require('../wave/couch_processor').CouchWaveProcessor UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor Ptag = require('../ptag').Ptag SHARED_STATE_PUBLIC = require('../wave/constants').SHARED_STATE_PUBLIC class BlipSearchController extends SearchController ### ะŸั€ะพั†ะตััะพั€ ะฟะพะธัะบะพะฒะพะน ะฒั‹ะดะฐั‡ะธ ะฟั€ะธ ะฟะพะธัะบะต ะฟะพ ะฑะปะธะฟะฐะผ ะฒ ะฟัƒะฑะปะธั‡ะฝั‹ั… ะฒะพะปะฝะฐั…. ### constructor: () -> super() @_idField = 'wave_id' @_changedField = 'groupchanged' @_ptagField = 'ptags' searchBlips: (user, queryString, ptagNames, lastSearchDate, callback) -> return if @_returnIfAnonymous(user, callback) query = @_getQuery() .select(['wave_id', 'MAX(changed) AS groupchanged', 'MAX(content_timestamp) AS groupdate', 'wave_url', 'ptags']) .addPtagsFilter(user, ptagNames) .addQueryString(queryString) .groupBy('wave_id') .orderBy('groupdate') .defaultLimit() @executeQuery(query, lastSearchDate, user, ptagNames, callback) searchPublicBlips: (user, queryString, lastSearchDate, callback) -> query = @_getQuery() .select(['wave_id', 'MAX(changed) AS groupchanged', 'MAX(content_timestamp) AS groupdate', 'wave_url', 'ptags']) .addQueryString(queryString) .addAndFilter("shared_state = #{SHARED_STATE_PUBLIC}") .groupBy('wave_id') .orderBy('groupdate') .defaultLimit() @executeQuery(query, lastSearchDate, user, null, callback) _getItem: (result, changed, user, ptagNames) -> item = {waveId: result.wave_url} return item if not changed item.changeDate = result.groupdate if @_hasAllPtag(ptagNames) #ะตัะปะธ ะทะฐะฟั€ะพั ะฒัะตั… ั‚ะพะฟะธะบะพะฒ, ั‚ะพ ะฝัƒะถะฝะพ ะฟะพัั‚ะฐะฒะธั‚ัŒ ะณะฐะปะพั‡ะบัƒ follow, ั‡ั‚ะพ ะฑั‹ ะฝะฐั€ะธัะพะฒะฐั‚ัŒ ะฟั€ะฐะฒะธะปัŒะฝัƒัŽ ะบะฝะพะฟะบัƒ ะฝะฐ ะบะปะธะตะฝั‚ะต item.follow = true if @_isFollow(result, user) return item _hasAllPtag: (ptagNames) -> ### ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ true ะตัะปะธ ัั€ะตะดะธ ั‚ัะณะพะฒ ะตัั‚ัŒ ALL @param ptagNames: string @returns bool ### return true if not ptagNames ptagNames = [ptagNames] if not _.isArray(ptagNames) for ptagName in ptagNames return true if Ptag.getCommonPtagId(ptagName) == Ptag.ALL_PTAG_ID return false _isFollow: (result, user) -> ### ะžะฟั€ะตะปัะตั‚, ะฟะพะดะฟะธัะฐะฝ ะปะธ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ะฝะฐ ะดะฐะฝะฝัƒัŽ ะฒะพะปะฝัƒ. @param result: object @param user: UserModel @returns: bool ### for searchPtagId in result.ptags [userId, ptagId] = Ptag.parseSearchPtagId(searchPtagId) continue if not userId? or not ptagId? continue if not user.isEqual(userId) continue if ptagId != Ptag.FOLLOW_PTAG_ID return true return false _getChangedItems: (ids, user, ptagNames, callback) -> @_getWavesAndStuffIds(ids, (err, waves, rootBlipsIds, creatorsIds) => return callback(err, null) if err return callback(null, {}) if not ids.length tasks = [ (callback) -> CouchBlipProcessor.getByIdsAsDict(rootBlipsIds, callback) (callback) -> UserCouchProcessor.getByIdsAsDict(creatorsIds, callback, false, true) (callback) => @_getReadBlipCounts(ids, user, callback) (callback) => @_getTotalBlipCounts(ids, user, callback) ] async.parallel(tasks, (err, result) => return callback(err) if err @_compileItems(waves, result..., callback) ) ) _getWavesAndStuffIds: (ids, callback) => ### ะŸะพะปัƒั‡ะตั‚ ะฒะพะปะฝั‹ ะธ id ะบะพั€ะฝะตะฒั‹ั… ะฑะปะธะฟะพะฒ ะธ ะฐะฒั‚ะพั€ะพะฒ. @param ids: array @param callback: function ### rootBlipsIds = [] creatorsIds = [] CouchWaveProcessor.getByIdsAsDict(ids, (err, waves) -> return callback(err) if err for own id, wave of waves rootBlipsIds.push(wave.rootBlipId) creatorId = wave.getTopicCreator()?.id creatorsIds.push(creatorId) if creatorId callback(null, waves, rootBlipsIds, creatorsIds) ) _getTotalBlipCounts: (waveIds, user, callback) => ### ะŸะพะปัƒั‡ะตั‚ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฑะปะธะฟะพะฒ ะฒะพะปะฝะฐั…. @param waveIds: array @param user: object @param callback: function ### return callback() if user.isAnonymous() viewParams = group: true keys: waveIds CouchWaveProcessor.view('total_blip_count_by_wave_id_2/get', viewParams, (err, counts) => return callback(err, null) if err callback(null, @_convertCountsToDict(counts)) ) _getReadBlipCounts: (waveIds, user, callback) => ### ะŸะพะปัƒั‡ะฐะตั‚ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฟั€ะพั‡ะธั‚ะฐะฝะฝั‹ั… ะฑะปะธะฟะพะฒ ะฒะพะปะฝะฐั…. @param waveIds: array @param participantId: string @param callback: function ### return callback() if user.isAnonymous() keys = [] for waveId in waveIds for userId in user.getAllIds() keys.push([waveId, userId]) viewParams = group: true keys: keys #stale: "ok" CouchWaveProcessor.view('read_blip_count_by_wave_id_and_participant_id_2/get', viewParams, (err, counts) => return callback(err, null) if err callback(null, @_convertCountsToDict(counts)) ) _convertCountsToDict: (counts) -> ### ะšะพะฝะฒะตั€ั‚ะธั€ัƒั‚ ั€ะตะทัƒะปัŒั‚ะฐั‚ ะฒั‹ะฟะพะปะฝะตะฝะธั @_getTotalBlipCounts ะธ @_getReadBlipCounts ะฒ ั‡ะตะปะพะฒะตั‡ะตัะบะธะน ะฒะธะด - ั€ะฐัะบะฐะปะฐะดั‹ะฒะฐะตั‚ ั†ะธั„ะธั€ะบะธ ะฟะพ id ะฒะพะปะฝ. @param counts: array @returns object ### countsByWaveId = {} for count in counts waveId = count.key waveId = if _.isArray(waveId) then waveId[0] else waveId countsByWaveId[waveId] = count.value return countsByWaveId _compileItems: (waves, blips, creators, readBlipsStat, totalBlipStat, callback) -> ### ะกะพะฑะธั€ะฐะตั‚ ะฒั‹ะดะฐั‡ัƒ ะดะปั ะธะทะผะตะฝะธะฒัˆะธั…ัั ั€ะตะทัƒะปัŒั‚ะฐั‚ะพะฒ ะฟะพะธัะบะฐ. @param waves: object @param blips: object - ะบะพั€ะฝะตะฒั‹ะต ะฑะปะธะฟั‹ @param creators: object - ะฐะฒั‚ะพั€ั‹ @param stats: object - ัั‚ะฐั‚ะธัั‚ะธะบะฐ @returns: object ### items = {} for own id, wave of waves blip = blips[wave.rootBlipId] creatorId = wave.getTopicCreator()?.id creator = if creatorId then creators[creatorId] else null total = if totalBlipStat then totalBlipStat[id] else 0 read = if readBlipsStat and readBlipsStat[id] then readBlipsStat[id] else 0 if not (blip? and creator? and total?) if not blip? # ะญั‚ะพ ะผะพะถะตั‚ ะฟั€ะพะธะทะพะนั‚ะธ ั‚ะพะปัŒะบะพ ะธะท-ะทะฐ ั…ะธั‚ั€ะพะน ะพัˆะธะฑะบะธ, ะฟะพั‚ะพะผัƒ ะบะฐะบ ะฝะตััƒั‰ะตัั‚ะฒัƒัŽั‰ะธะน ะฑะปะธะฟ ัะฒะฐะปะธั‚ ะฒััŽ ะพะฑั€ะฐะฑะพั‚ะบัƒ ะฟะพะธัะบะฐ console.warn("Got search result for blip #{id} but could not load wave root blip #{wave.rootBlipId}") if not creator? console.warn("Got search result for blip #{id} but could not load wave creator #{creatorId}") if not total? console.warn("Got search result for blip #{id} but could not load total blip stat for this blip") continue items[id] = title: blip.getTitle() snippet: blip.getSnippet() avatar: creator.avatar name: creator.name totalBlipCount: total totalUnreadBlipCount: total - read isTeamTopic: wave.isTeamTopic() callback(null, items) module.exports = BlipSearchController: new BlipSearchController()
65325
_= require('underscore') async = require('async') SearchController = require('../search/controller').SearchController CouchBlipProcessor = require('../blip/couch_processor').CouchBlipProcessor CouchWaveProcessor = require('../wave/couch_processor').CouchWaveProcessor UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor Ptag = require('../ptag').Ptag SHARED_STATE_PUBLIC = require('../wave/constants').SHARED_STATE_PUBLIC class BlipSearchController extends SearchController ### ะŸั€ะพั†ะตััะพั€ ะฟะพะธัะบะพะฒะพะน ะฒั‹ะดะฐั‡ะธ ะฟั€ะธ ะฟะพะธัะบะต ะฟะพ ะฑะปะธะฟะฐะผ ะฒ ะฟัƒะฑะปะธั‡ะฝั‹ั… ะฒะพะปะฝะฐั…. ### constructor: () -> super() @_idField = 'wave_id' @_changedField = 'groupchanged' @_ptagField = 'ptags' searchBlips: (user, queryString, ptagNames, lastSearchDate, callback) -> return if @_returnIfAnonymous(user, callback) query = @_getQuery() .select(['wave_id', 'MAX(changed) AS groupchanged', 'MAX(content_timestamp) AS groupdate', 'wave_url', 'ptags']) .addPtagsFilter(user, ptagNames) .addQueryString(queryString) .groupBy('wave_id') .orderBy('groupdate') .defaultLimit() @executeQuery(query, lastSearchDate, user, ptagNames, callback) searchPublicBlips: (user, queryString, lastSearchDate, callback) -> query = @_getQuery() .select(['wave_id', 'MAX(changed) AS groupchanged', 'MAX(content_timestamp) AS groupdate', 'wave_url', 'ptags']) .addQueryString(queryString) .addAndFilter("shared_state = #{SHARED_STATE_PUBLIC}") .groupBy('wave_id') .orderBy('groupdate') .defaultLimit() @executeQuery(query, lastSearchDate, user, null, callback) _getItem: (result, changed, user, ptagNames) -> item = {waveId: result.wave_url} return item if not changed item.changeDate = result.groupdate if @_hasAllPtag(ptagNames) #ะตัะปะธ ะทะฐะฟั€ะพั ะฒัะตั… ั‚ะพะฟะธะบะพะฒ, ั‚ะพ ะฝัƒะถะฝะพ ะฟะพัั‚ะฐะฒะธั‚ัŒ ะณะฐะปะพั‡ะบัƒ follow, ั‡ั‚ะพ ะฑั‹ ะฝะฐั€ะธัะพะฒะฐั‚ัŒ ะฟั€ะฐะฒะธะปัŒะฝัƒัŽ ะบะฝะพะฟะบัƒ ะฝะฐ ะบะปะธะตะฝั‚ะต item.follow = true if @_isFollow(result, user) return item _hasAllPtag: (ptagNames) -> ### ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ true ะตัะปะธ ัั€ะตะดะธ ั‚ัะณะพะฒ ะตัั‚ัŒ ALL @param ptagNames: string @returns bool ### return true if not ptagNames ptagNames = [ptagNames] if not _.isArray(ptagNames) for ptagName in ptagNames return true if Ptag.getCommonPtagId(ptagName) == Ptag.ALL_PTAG_ID return false _isFollow: (result, user) -> ### ะžะฟั€ะตะปัะตั‚, ะฟะพะดะฟะธัะฐะฝ ะปะธ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ะฝะฐ ะดะฐะฝะฝัƒัŽ ะฒะพะปะฝัƒ. @param result: object @param user: UserModel @returns: bool ### for searchPtagId in result.ptags [userId, ptagId] = Ptag.parseSearchPtagId(searchPtagId) continue if not userId? or not ptagId? continue if not user.isEqual(userId) continue if ptagId != Ptag.FOLLOW_PTAG_ID return true return false _getChangedItems: (ids, user, ptagNames, callback) -> @_getWavesAndStuffIds(ids, (err, waves, rootBlipsIds, creatorsIds) => return callback(err, null) if err return callback(null, {}) if not ids.length tasks = [ (callback) -> CouchBlipProcessor.getByIdsAsDict(rootBlipsIds, callback) (callback) -> UserCouchProcessor.getByIdsAsDict(creatorsIds, callback, false, true) (callback) => @_getReadBlipCounts(ids, user, callback) (callback) => @_getTotalBlipCounts(ids, user, callback) ] async.parallel(tasks, (err, result) => return callback(err) if err @_compileItems(waves, result..., callback) ) ) _getWavesAndStuffIds: (ids, callback) => ### ะŸะพะปัƒั‡ะตั‚ ะฒะพะปะฝั‹ ะธ id ะบะพั€ะฝะตะฒั‹ั… ะฑะปะธะฟะพะฒ ะธ ะฐะฒั‚ะพั€ะพะฒ. @param ids: array @param callback: function ### rootBlipsIds = [] creatorsIds = [] CouchWaveProcessor.getByIdsAsDict(ids, (err, waves) -> return callback(err) if err for own id, wave of waves rootBlipsIds.push(wave.rootBlipId) creatorId = wave.getTopicCreator()?.id creatorsIds.push(creatorId) if creatorId callback(null, waves, rootBlipsIds, creatorsIds) ) _getTotalBlipCounts: (waveIds, user, callback) => ### ะŸะพะปัƒั‡ะตั‚ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฑะปะธะฟะพะฒ ะฒะพะปะฝะฐั…. @param waveIds: array @param user: object @param callback: function ### return callback() if user.isAnonymous() viewParams = group: true keys: waveIds CouchWaveProcessor.view('total_blip_count_by_wave_id_2/get', viewParams, (err, counts) => return callback(err, null) if err callback(null, @_convertCountsToDict(counts)) ) _getReadBlipCounts: (waveIds, user, callback) => ### ะŸะพะปัƒั‡ะฐะตั‚ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฟั€ะพั‡ะธั‚ะฐะฝะฝั‹ั… ะฑะปะธะฟะพะฒ ะฒะพะปะฝะฐั…. @param waveIds: array @param participantId: string @param callback: function ### return callback() if user.isAnonymous() keys = [] for waveId in waveIds for userId in user.getAllIds() keys.push([waveId, userId]) viewParams = group: true keys: keys #stale: "ok" CouchWaveProcessor.view('read_blip_count_by_wave_id_and_participant_id_2/get', viewParams, (err, counts) => return callback(err, null) if err callback(null, @_convertCountsToDict(counts)) ) _convertCountsToDict: (counts) -> ### ะšะพะฝะฒะตั€ั‚ะธั€ัƒั‚ ั€ะตะทัƒะปัŒั‚ะฐั‚ ะฒั‹ะฟะพะปะฝะตะฝะธั @_getTotalBlipCounts ะธ @_getReadBlipCounts ะฒ ั‡ะตะปะพะฒะตั‡ะตัะบะธะน ะฒะธะด - ั€ะฐัะบะฐะปะฐะดั‹ะฒะฐะตั‚ ั†ะธั„ะธั€ะบะธ ะฟะพ id ะฒะพะปะฝ. @param counts: array @returns object ### countsByWaveId = {} for count in counts waveId = count.key waveId = if _.isArray(waveId) then waveId[0] else waveId countsByWaveId[waveId] = count.value return countsByWaveId _compileItems: (waves, blips, creators, readBlipsStat, totalBlipStat, callback) -> ### ะกะพะฑะธั€ะฐะตั‚ ะฒั‹ะดะฐั‡ัƒ ะดะปั ะธะทะผะตะฝะธะฒัˆะธั…ัั ั€ะตะทัƒะปัŒั‚ะฐั‚ะพะฒ ะฟะพะธัะบะฐ. @param waves: object @param blips: object - ะบะพั€ะฝะตะฒั‹ะต ะฑะปะธะฟั‹ @param creators: object - ะฐะฒั‚ะพั€ั‹ @param stats: object - ัั‚ะฐั‚ะธัั‚ะธะบะฐ @returns: object ### items = {} for own id, wave of waves blip = blips[wave.rootBlipId] creatorId = wave.getTopicCreator()?.id creator = if creatorId then creators[creatorId] else null total = if totalBlipStat then totalBlipStat[id] else 0 read = if readBlipsStat and readBlipsStat[id] then readBlipsStat[id] else 0 if not (blip? and creator? and total?) if not blip? # ะญั‚ะพ ะผะพะถะตั‚ ะฟั€ะพะธะทะพะนั‚ะธ ั‚ะพะปัŒะบะพ ะธะท-ะทะฐ ั…ะธั‚ั€ะพะน ะพัˆะธะฑะบะธ, ะฟะพั‚ะพะผัƒ ะบะฐะบ ะฝะตััƒั‰ะตัั‚ะฒัƒัŽั‰ะธะน ะฑะปะธะฟ ัะฒะฐะปะธั‚ ะฒััŽ ะพะฑั€ะฐะฑะพั‚ะบัƒ ะฟะพะธัะบะฐ console.warn("Got search result for blip #{id} but could not load wave root blip #{wave.rootBlipId}") if not creator? console.warn("Got search result for blip #{id} but could not load wave creator #{creatorId}") if not total? console.warn("Got search result for blip #{id} but could not load total blip stat for this blip") continue items[id] = title: blip.getTitle() snippet: blip.getSnippet() avatar: creator.avatar name: <NAME>.<NAME> totalBlipCount: total totalUnreadBlipCount: total - read isTeamTopic: wave.isTeamTopic() callback(null, items) module.exports = BlipSearchController: new BlipSearchController()
true
_= require('underscore') async = require('async') SearchController = require('../search/controller').SearchController CouchBlipProcessor = require('../blip/couch_processor').CouchBlipProcessor CouchWaveProcessor = require('../wave/couch_processor').CouchWaveProcessor UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor Ptag = require('../ptag').Ptag SHARED_STATE_PUBLIC = require('../wave/constants').SHARED_STATE_PUBLIC class BlipSearchController extends SearchController ### ะŸั€ะพั†ะตััะพั€ ะฟะพะธัะบะพะฒะพะน ะฒั‹ะดะฐั‡ะธ ะฟั€ะธ ะฟะพะธัะบะต ะฟะพ ะฑะปะธะฟะฐะผ ะฒ ะฟัƒะฑะปะธั‡ะฝั‹ั… ะฒะพะปะฝะฐั…. ### constructor: () -> super() @_idField = 'wave_id' @_changedField = 'groupchanged' @_ptagField = 'ptags' searchBlips: (user, queryString, ptagNames, lastSearchDate, callback) -> return if @_returnIfAnonymous(user, callback) query = @_getQuery() .select(['wave_id', 'MAX(changed) AS groupchanged', 'MAX(content_timestamp) AS groupdate', 'wave_url', 'ptags']) .addPtagsFilter(user, ptagNames) .addQueryString(queryString) .groupBy('wave_id') .orderBy('groupdate') .defaultLimit() @executeQuery(query, lastSearchDate, user, ptagNames, callback) searchPublicBlips: (user, queryString, lastSearchDate, callback) -> query = @_getQuery() .select(['wave_id', 'MAX(changed) AS groupchanged', 'MAX(content_timestamp) AS groupdate', 'wave_url', 'ptags']) .addQueryString(queryString) .addAndFilter("shared_state = #{SHARED_STATE_PUBLIC}") .groupBy('wave_id') .orderBy('groupdate') .defaultLimit() @executeQuery(query, lastSearchDate, user, null, callback) _getItem: (result, changed, user, ptagNames) -> item = {waveId: result.wave_url} return item if not changed item.changeDate = result.groupdate if @_hasAllPtag(ptagNames) #ะตัะปะธ ะทะฐะฟั€ะพั ะฒัะตั… ั‚ะพะฟะธะบะพะฒ, ั‚ะพ ะฝัƒะถะฝะพ ะฟะพัั‚ะฐะฒะธั‚ัŒ ะณะฐะปะพั‡ะบัƒ follow, ั‡ั‚ะพ ะฑั‹ ะฝะฐั€ะธัะพะฒะฐั‚ัŒ ะฟั€ะฐะฒะธะปัŒะฝัƒัŽ ะบะฝะพะฟะบัƒ ะฝะฐ ะบะปะธะตะฝั‚ะต item.follow = true if @_isFollow(result, user) return item _hasAllPtag: (ptagNames) -> ### ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ true ะตัะปะธ ัั€ะตะดะธ ั‚ัะณะพะฒ ะตัั‚ัŒ ALL @param ptagNames: string @returns bool ### return true if not ptagNames ptagNames = [ptagNames] if not _.isArray(ptagNames) for ptagName in ptagNames return true if Ptag.getCommonPtagId(ptagName) == Ptag.ALL_PTAG_ID return false _isFollow: (result, user) -> ### ะžะฟั€ะตะปัะตั‚, ะฟะพะดะฟะธัะฐะฝ ะปะธ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ะฝะฐ ะดะฐะฝะฝัƒัŽ ะฒะพะปะฝัƒ. @param result: object @param user: UserModel @returns: bool ### for searchPtagId in result.ptags [userId, ptagId] = Ptag.parseSearchPtagId(searchPtagId) continue if not userId? or not ptagId? continue if not user.isEqual(userId) continue if ptagId != Ptag.FOLLOW_PTAG_ID return true return false _getChangedItems: (ids, user, ptagNames, callback) -> @_getWavesAndStuffIds(ids, (err, waves, rootBlipsIds, creatorsIds) => return callback(err, null) if err return callback(null, {}) if not ids.length tasks = [ (callback) -> CouchBlipProcessor.getByIdsAsDict(rootBlipsIds, callback) (callback) -> UserCouchProcessor.getByIdsAsDict(creatorsIds, callback, false, true) (callback) => @_getReadBlipCounts(ids, user, callback) (callback) => @_getTotalBlipCounts(ids, user, callback) ] async.parallel(tasks, (err, result) => return callback(err) if err @_compileItems(waves, result..., callback) ) ) _getWavesAndStuffIds: (ids, callback) => ### ะŸะพะปัƒั‡ะตั‚ ะฒะพะปะฝั‹ ะธ id ะบะพั€ะฝะตะฒั‹ั… ะฑะปะธะฟะพะฒ ะธ ะฐะฒั‚ะพั€ะพะฒ. @param ids: array @param callback: function ### rootBlipsIds = [] creatorsIds = [] CouchWaveProcessor.getByIdsAsDict(ids, (err, waves) -> return callback(err) if err for own id, wave of waves rootBlipsIds.push(wave.rootBlipId) creatorId = wave.getTopicCreator()?.id creatorsIds.push(creatorId) if creatorId callback(null, waves, rootBlipsIds, creatorsIds) ) _getTotalBlipCounts: (waveIds, user, callback) => ### ะŸะพะปัƒั‡ะตั‚ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฑะปะธะฟะพะฒ ะฒะพะปะฝะฐั…. @param waveIds: array @param user: object @param callback: function ### return callback() if user.isAnonymous() viewParams = group: true keys: waveIds CouchWaveProcessor.view('total_blip_count_by_wave_id_2/get', viewParams, (err, counts) => return callback(err, null) if err callback(null, @_convertCountsToDict(counts)) ) _getReadBlipCounts: (waveIds, user, callback) => ### ะŸะพะปัƒั‡ะฐะตั‚ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฟั€ะพั‡ะธั‚ะฐะฝะฝั‹ั… ะฑะปะธะฟะพะฒ ะฒะพะปะฝะฐั…. @param waveIds: array @param participantId: string @param callback: function ### return callback() if user.isAnonymous() keys = [] for waveId in waveIds for userId in user.getAllIds() keys.push([waveId, userId]) viewParams = group: true keys: keys #stale: "ok" CouchWaveProcessor.view('read_blip_count_by_wave_id_and_participant_id_2/get', viewParams, (err, counts) => return callback(err, null) if err callback(null, @_convertCountsToDict(counts)) ) _convertCountsToDict: (counts) -> ### ะšะพะฝะฒะตั€ั‚ะธั€ัƒั‚ ั€ะตะทัƒะปัŒั‚ะฐั‚ ะฒั‹ะฟะพะปะฝะตะฝะธั @_getTotalBlipCounts ะธ @_getReadBlipCounts ะฒ ั‡ะตะปะพะฒะตั‡ะตัะบะธะน ะฒะธะด - ั€ะฐัะบะฐะปะฐะดั‹ะฒะฐะตั‚ ั†ะธั„ะธั€ะบะธ ะฟะพ id ะฒะพะปะฝ. @param counts: array @returns object ### countsByWaveId = {} for count in counts waveId = count.key waveId = if _.isArray(waveId) then waveId[0] else waveId countsByWaveId[waveId] = count.value return countsByWaveId _compileItems: (waves, blips, creators, readBlipsStat, totalBlipStat, callback) -> ### ะกะพะฑะธั€ะฐะตั‚ ะฒั‹ะดะฐั‡ัƒ ะดะปั ะธะทะผะตะฝะธะฒัˆะธั…ัั ั€ะตะทัƒะปัŒั‚ะฐั‚ะพะฒ ะฟะพะธัะบะฐ. @param waves: object @param blips: object - ะบะพั€ะฝะตะฒั‹ะต ะฑะปะธะฟั‹ @param creators: object - ะฐะฒั‚ะพั€ั‹ @param stats: object - ัั‚ะฐั‚ะธัั‚ะธะบะฐ @returns: object ### items = {} for own id, wave of waves blip = blips[wave.rootBlipId] creatorId = wave.getTopicCreator()?.id creator = if creatorId then creators[creatorId] else null total = if totalBlipStat then totalBlipStat[id] else 0 read = if readBlipsStat and readBlipsStat[id] then readBlipsStat[id] else 0 if not (blip? and creator? and total?) if not blip? # ะญั‚ะพ ะผะพะถะตั‚ ะฟั€ะพะธะทะพะนั‚ะธ ั‚ะพะปัŒะบะพ ะธะท-ะทะฐ ั…ะธั‚ั€ะพะน ะพัˆะธะฑะบะธ, ะฟะพั‚ะพะผัƒ ะบะฐะบ ะฝะตััƒั‰ะตัั‚ะฒัƒัŽั‰ะธะน ะฑะปะธะฟ ัะฒะฐะปะธั‚ ะฒััŽ ะพะฑั€ะฐะฑะพั‚ะบัƒ ะฟะพะธัะบะฐ console.warn("Got search result for blip #{id} but could not load wave root blip #{wave.rootBlipId}") if not creator? console.warn("Got search result for blip #{id} but could not load wave creator #{creatorId}") if not total? console.warn("Got search result for blip #{id} but could not load total blip stat for this blip") continue items[id] = title: blip.getTitle() snippet: blip.getSnippet() avatar: creator.avatar name: PI:NAME:<NAME>END_PI.PI:NAME:<NAME>END_PI totalBlipCount: total totalUnreadBlipCount: total - read isTeamTopic: wave.isTeamTopic() callback(null, items) module.exports = BlipSearchController: new BlipSearchController()
[ { "context": "yles: {\n apps: \"list\"\n }\n\n localStorageKey: \"ui\"\n\n state: ->\n listStyles: @listStyles\n\n onCh", "end": 2085, "score": 0.8260679841041565, "start": 2083, "tag": "KEY", "value": "ui" } ]
app/assets/js/app-store.coffee
OlegIlyenko/learning-reactjs
1
global.ErrorActions = Reflux.createActions [ "serverError" "clear" ] global.AppActions = Reflux.createActions [ "addApp" "updateApp" "deleteApp" "updated" "list" "subscribe" "unsubscribe" ] updateHandler = (p) -> p.then AppActions.updated .fail ErrorActions.serverError AppActions.addApp.listen (app) -> updateHandler($.ajax {url: "/api/apps", type: "POST", data: JSON.stringify(app), contentType: "application/json"}) AppActions.updateApp.listen (app) -> updateHandler($.ajax {url: "/api/apps/#{app.id}", type: "PUT", data: JSON.stringify(app), contentType: "application/json"}) AppActions.deleteApp.listen (id) -> updateHandler($.ajax {url: "/api/apps/#{id}", type: "DELETE"}) global.AppListStore = Reflux.createStore listenables: [AppActions], subs: 0 eventSource: null onUpdated: (app) -> # SSE should update onSubscribe: -> @subs++ @updateSubscription() onUnsubscribe: -> @subs-- @updateSubscription() updateSubscription: -> if @eventSource? and @subs == 0 @eventSource.close() @eventSource = null else if not @eventSource? and @subs > 0 @eventSource = new EventSource("/api/apps/updates") @eventSource.addEventListener "message", (msg) => @update() @eventSource.addEventListener "error", (e) => @eventSource.close() @eventSource = null ErrorActions.serverError(e) Promise.delay(1000).then => @updateSubscription() onList: () -> @update() update: () -> $.get("/api/apps") .then (list) => @trigger(list) .fail ErrorActions.serverError getInitialState: -> [] global.ErrorStore = Reflux.createStore listenables: [ErrorActions], onServerError: (error) -> @trigger error: error message: error.statusText onClear: -> @trigger error: null message: null global.UIActions = Reflux.createActions [ "changeListState" ] global.UIStore = Reflux.createStore listenables: [UIActions], listStyles: { apps: "list" } localStorageKey: "ui" state: -> listStyles: @listStyles onChangeListState: (cmp, style) -> @listStyles[cmp] = style @update() update: -> s = @state() localStorage.setItem @localStorageKey, JSON.stringify(s) @trigger s getInitialState: -> loadedList = localStorage.getItem(@localStorageKey) if loadedList? parsed = JSON.parse(loadedList) @listStyles = parsed.listStyles @state()
95768
global.ErrorActions = Reflux.createActions [ "serverError" "clear" ] global.AppActions = Reflux.createActions [ "addApp" "updateApp" "deleteApp" "updated" "list" "subscribe" "unsubscribe" ] updateHandler = (p) -> p.then AppActions.updated .fail ErrorActions.serverError AppActions.addApp.listen (app) -> updateHandler($.ajax {url: "/api/apps", type: "POST", data: JSON.stringify(app), contentType: "application/json"}) AppActions.updateApp.listen (app) -> updateHandler($.ajax {url: "/api/apps/#{app.id}", type: "PUT", data: JSON.stringify(app), contentType: "application/json"}) AppActions.deleteApp.listen (id) -> updateHandler($.ajax {url: "/api/apps/#{id}", type: "DELETE"}) global.AppListStore = Reflux.createStore listenables: [AppActions], subs: 0 eventSource: null onUpdated: (app) -> # SSE should update onSubscribe: -> @subs++ @updateSubscription() onUnsubscribe: -> @subs-- @updateSubscription() updateSubscription: -> if @eventSource? and @subs == 0 @eventSource.close() @eventSource = null else if not @eventSource? and @subs > 0 @eventSource = new EventSource("/api/apps/updates") @eventSource.addEventListener "message", (msg) => @update() @eventSource.addEventListener "error", (e) => @eventSource.close() @eventSource = null ErrorActions.serverError(e) Promise.delay(1000).then => @updateSubscription() onList: () -> @update() update: () -> $.get("/api/apps") .then (list) => @trigger(list) .fail ErrorActions.serverError getInitialState: -> [] global.ErrorStore = Reflux.createStore listenables: [ErrorActions], onServerError: (error) -> @trigger error: error message: error.statusText onClear: -> @trigger error: null message: null global.UIActions = Reflux.createActions [ "changeListState" ] global.UIStore = Reflux.createStore listenables: [UIActions], listStyles: { apps: "list" } localStorageKey: "<KEY>" state: -> listStyles: @listStyles onChangeListState: (cmp, style) -> @listStyles[cmp] = style @update() update: -> s = @state() localStorage.setItem @localStorageKey, JSON.stringify(s) @trigger s getInitialState: -> loadedList = localStorage.getItem(@localStorageKey) if loadedList? parsed = JSON.parse(loadedList) @listStyles = parsed.listStyles @state()
true
global.ErrorActions = Reflux.createActions [ "serverError" "clear" ] global.AppActions = Reflux.createActions [ "addApp" "updateApp" "deleteApp" "updated" "list" "subscribe" "unsubscribe" ] updateHandler = (p) -> p.then AppActions.updated .fail ErrorActions.serverError AppActions.addApp.listen (app) -> updateHandler($.ajax {url: "/api/apps", type: "POST", data: JSON.stringify(app), contentType: "application/json"}) AppActions.updateApp.listen (app) -> updateHandler($.ajax {url: "/api/apps/#{app.id}", type: "PUT", data: JSON.stringify(app), contentType: "application/json"}) AppActions.deleteApp.listen (id) -> updateHandler($.ajax {url: "/api/apps/#{id}", type: "DELETE"}) global.AppListStore = Reflux.createStore listenables: [AppActions], subs: 0 eventSource: null onUpdated: (app) -> # SSE should update onSubscribe: -> @subs++ @updateSubscription() onUnsubscribe: -> @subs-- @updateSubscription() updateSubscription: -> if @eventSource? and @subs == 0 @eventSource.close() @eventSource = null else if not @eventSource? and @subs > 0 @eventSource = new EventSource("/api/apps/updates") @eventSource.addEventListener "message", (msg) => @update() @eventSource.addEventListener "error", (e) => @eventSource.close() @eventSource = null ErrorActions.serverError(e) Promise.delay(1000).then => @updateSubscription() onList: () -> @update() update: () -> $.get("/api/apps") .then (list) => @trigger(list) .fail ErrorActions.serverError getInitialState: -> [] global.ErrorStore = Reflux.createStore listenables: [ErrorActions], onServerError: (error) -> @trigger error: error message: error.statusText onClear: -> @trigger error: null message: null global.UIActions = Reflux.createActions [ "changeListState" ] global.UIStore = Reflux.createStore listenables: [UIActions], listStyles: { apps: "list" } localStorageKey: "PI:KEY:<KEY>END_PI" state: -> listStyles: @listStyles onChangeListState: (cmp, style) -> @listStyles[cmp] = style @update() update: -> s = @state() localStorage.setItem @localStorageKey, JSON.stringify(s) @trigger s getInitialState: -> loadedList = localStorage.getItem(@localStorageKey) if loadedList? parsed = JSON.parse(loadedList) @listStyles = parsed.listStyles @state()
[ { "context": "3-456-789'\n clientSecret: 'shhh-its-a-secret'\n\n doorman(config)\n require('rupert", "end": 1160, "score": 0.9177846312522888, "start": 1143, "tag": "KEY", "value": "shhh-its-a-secret" } ]
src/server/auth/route_test.coffee
RupertJS/rupert-doorman
0
request = require('supertest') express = require('express') router = require('./route') doorman = require('./config') Config = require('rupert').Config describe 'Doorman Router', -> it 'exports a routing function', -> router.should.be.an.instanceof Function it 'attaches express-session to the app', (done)-> config = new Config {} doorman(config) app = express() router(app, config) app.get '/route', (q, s, n)-> q.should.have.property('session') s.send {status: 'ok'} request(app).get('/route').expect(200).end(done) it 'loads oath provider routes', (done)-> config = new Config name: 'doorman-test' stassets: no websockets: no static: no doorman: providers: oauth2: authorizationURL: 'https://www.provider.com/oauth2/authorize' tokenURL: 'https://www.provider.com/oauth2/token' clientID: '123-456-789' clientSecret: 'shhh-its-a-secret' doorman(config) require('rupert')(config).then ({app})-> request(app) .get('/doorman/oauth2/connect') .expect(302) .end done it 'completes a login', (done)-> config = new Config name: 'doorman-test' stassets: no websockets: no static: no doorman: providers: test: libPath: './test_strategy' doorman(config) require('rupert')(config).then ({app})-> connect = request(app) .get('/doorman/test/connect') .expect(302) callback = request(app) .get('/doorman/test/callback') .query({code: 'loggedin'}) .expect(200) .expect(/window.close()/) connect.end (err)-> return done(err) if err callback.end (err, res)-> done(err) it 'returns user info on request', (done)-> config = new Config name: 'doorman-test' stassets: no websockets: no static: no doorman: providers: test: libPath: './test_strategy' doorman(config) require('rupert')(config).then ({app})-> agent = request.agent(app) agent .get('/doorman') .expect(401) .end (err)-> return done(err) if err agent .get('/doorman/test/callback') .query({code: 'loggedin'}) .expect(200) # And a window.close() .end (err, res)-> return done(err) if err agent .get('/doorman') .expect(200).end (err, res)-> return done(err) if err res.body.should.not.have.property 'test' res.body.should.not.have.property 'tokens' res.body.id.should.equal '123abc' done()
46010
request = require('supertest') express = require('express') router = require('./route') doorman = require('./config') Config = require('rupert').Config describe 'Doorman Router', -> it 'exports a routing function', -> router.should.be.an.instanceof Function it 'attaches express-session to the app', (done)-> config = new Config {} doorman(config) app = express() router(app, config) app.get '/route', (q, s, n)-> q.should.have.property('session') s.send {status: 'ok'} request(app).get('/route').expect(200).end(done) it 'loads oath provider routes', (done)-> config = new Config name: 'doorman-test' stassets: no websockets: no static: no doorman: providers: oauth2: authorizationURL: 'https://www.provider.com/oauth2/authorize' tokenURL: 'https://www.provider.com/oauth2/token' clientID: '123-456-789' clientSecret: '<KEY>' doorman(config) require('rupert')(config).then ({app})-> request(app) .get('/doorman/oauth2/connect') .expect(302) .end done it 'completes a login', (done)-> config = new Config name: 'doorman-test' stassets: no websockets: no static: no doorman: providers: test: libPath: './test_strategy' doorman(config) require('rupert')(config).then ({app})-> connect = request(app) .get('/doorman/test/connect') .expect(302) callback = request(app) .get('/doorman/test/callback') .query({code: 'loggedin'}) .expect(200) .expect(/window.close()/) connect.end (err)-> return done(err) if err callback.end (err, res)-> done(err) it 'returns user info on request', (done)-> config = new Config name: 'doorman-test' stassets: no websockets: no static: no doorman: providers: test: libPath: './test_strategy' doorman(config) require('rupert')(config).then ({app})-> agent = request.agent(app) agent .get('/doorman') .expect(401) .end (err)-> return done(err) if err agent .get('/doorman/test/callback') .query({code: 'loggedin'}) .expect(200) # And a window.close() .end (err, res)-> return done(err) if err agent .get('/doorman') .expect(200).end (err, res)-> return done(err) if err res.body.should.not.have.property 'test' res.body.should.not.have.property 'tokens' res.body.id.should.equal '123abc' done()
true
request = require('supertest') express = require('express') router = require('./route') doorman = require('./config') Config = require('rupert').Config describe 'Doorman Router', -> it 'exports a routing function', -> router.should.be.an.instanceof Function it 'attaches express-session to the app', (done)-> config = new Config {} doorman(config) app = express() router(app, config) app.get '/route', (q, s, n)-> q.should.have.property('session') s.send {status: 'ok'} request(app).get('/route').expect(200).end(done) it 'loads oath provider routes', (done)-> config = new Config name: 'doorman-test' stassets: no websockets: no static: no doorman: providers: oauth2: authorizationURL: 'https://www.provider.com/oauth2/authorize' tokenURL: 'https://www.provider.com/oauth2/token' clientID: '123-456-789' clientSecret: 'PI:KEY:<KEY>END_PI' doorman(config) require('rupert')(config).then ({app})-> request(app) .get('/doorman/oauth2/connect') .expect(302) .end done it 'completes a login', (done)-> config = new Config name: 'doorman-test' stassets: no websockets: no static: no doorman: providers: test: libPath: './test_strategy' doorman(config) require('rupert')(config).then ({app})-> connect = request(app) .get('/doorman/test/connect') .expect(302) callback = request(app) .get('/doorman/test/callback') .query({code: 'loggedin'}) .expect(200) .expect(/window.close()/) connect.end (err)-> return done(err) if err callback.end (err, res)-> done(err) it 'returns user info on request', (done)-> config = new Config name: 'doorman-test' stassets: no websockets: no static: no doorman: providers: test: libPath: './test_strategy' doorman(config) require('rupert')(config).then ({app})-> agent = request.agent(app) agent .get('/doorman') .expect(401) .end (err)-> return done(err) if err agent .get('/doorman/test/callback') .query({code: 'loggedin'}) .expect(200) # And a window.close() .end (err, res)-> return done(err) if err agent .get('/doorman') .expect(200).end (err, res)-> return done(err) if err res.body.should.not.have.property 'test' res.body.should.not.have.property 'tokens' res.body.id.should.equal '123abc' done()
[ { "context": "module.exports =\n user:\n admin:\n name: 'admin'\n email: 'admin@mob.myvnc.com'\n", "end": 54, "score": 0.9794068932533264, "start": 49, "tag": "USERNAME", "value": "admin" }, { "context": "ser:\n admin:\n name: 'admin'\n email: 'admin@mob.myvnc.com'\n", "end": 89, "score": 0.999933123588562, "start": 70, "tag": "EMAIL", "value": "admin@mob.myvnc.com" } ]
config/user.coffee
twhtanghk/restfile
0
module.exports = user: admin: name: 'admin' email: 'admin@mob.myvnc.com'
35633
module.exports = user: admin: name: 'admin' email: '<EMAIL>'
true
module.exports = user: admin: name: 'admin' email: 'PI:EMAIL:<EMAIL>END_PI'
[ { "context": "is a derived version of Angular Calculator Demo by Thom Porter (http://www.thomporter.com/docco/calc.html).\n###\n", "end": 128, "score": 0.9996508955955505, "start": 117, "tag": "NAME", "value": "Thom Porter" } ]
src/scripts/services/calc.coffee
dbtek/angular-material-calculator
4
app = require '../app' ###* # Logic implemented in this service is a derived version of Angular Calculator Demo by Thom Porter (http://www.thomporter.com/docco/calc.html). ### app.factory '$calc', -> memory = 0 stuff = [0] justGotMath = false display = '' input: (n) -> console.log "input: #{n}" if justGotMath justGotMath = false stuff = [] if !@isOperator(n) n = n.toString() if n == '.' last = stuff.pop() if @isOperator(last) || Math.ceil(last) != parseInt(last) stuff.push(last) else last += '.' stuff.push(last) @writeScreen() return if (@isOperator(n)) return if !stuff.length last = stuff.pop() stuff.push(last) if !@isOperator(last) stuff.push(n) else if stuff.length last = stuff.pop() if @isOperator(last) stuff.push(last) stuff.push(n) else if last.toString() == '0' stuff.push(n) else last += n.toString() stuff.push(last) else stuff.push(n) @writeScreen() console.log stuff @ isOperator: (n) -> if isNaN(n) return true if n != '.' return false changeSign: () -> last = stuff.pop() if @isOperator(last) second_last = stuff.pop() if second_last.substr(0,1) == '-' second_last = substr(1) else second_last = '-' + second_last stuff.push(second_last) else if last.substr(0,1) == '-' last = substr(1) else last = '-' + last stuff.push(last) @writeScreen() writeScreen: () -> write = ''; angular.forEach(stuff, (k, i)-> if write == '' write = k else write += k.toString() ) write = '0' if (write == '') display = write.toString(); return if @isOperator(n) write = if n == '/' '&divide;' else if n == '*' '&times;' else if n == '+' '&plus;' else if n == '-' '&minus;' if (!stuff.length) display = write else display += write.toString() @ clearCalc: () -> stuff = [] @writeScreen() doMath: () -> justGotMath = true stuff = [@getMath()] @writeScreen() getMath: -> last = stuff.pop() if (!@isOperator(last)) stuff.push(last) job = stuff.join(''); x = 0 eval('x = ' + job + ';'); x memoryClear: -> memory = 0 @memoryIndicator(0) memoryShow: -> stuff = [memory.toString()] @writeScreen() memoryAdd: () -> memory += @getMath() @memoryIndicator(1) memorySub: () -> memory -= @getMath() if (memory != 0) @memoryIndicator(1) else @memoryIndicator(0) display: -> display
58637
app = require '../app' ###* # Logic implemented in this service is a derived version of Angular Calculator Demo by <NAME> (http://www.thomporter.com/docco/calc.html). ### app.factory '$calc', -> memory = 0 stuff = [0] justGotMath = false display = '' input: (n) -> console.log "input: #{n}" if justGotMath justGotMath = false stuff = [] if !@isOperator(n) n = n.toString() if n == '.' last = stuff.pop() if @isOperator(last) || Math.ceil(last) != parseInt(last) stuff.push(last) else last += '.' stuff.push(last) @writeScreen() return if (@isOperator(n)) return if !stuff.length last = stuff.pop() stuff.push(last) if !@isOperator(last) stuff.push(n) else if stuff.length last = stuff.pop() if @isOperator(last) stuff.push(last) stuff.push(n) else if last.toString() == '0' stuff.push(n) else last += n.toString() stuff.push(last) else stuff.push(n) @writeScreen() console.log stuff @ isOperator: (n) -> if isNaN(n) return true if n != '.' return false changeSign: () -> last = stuff.pop() if @isOperator(last) second_last = stuff.pop() if second_last.substr(0,1) == '-' second_last = substr(1) else second_last = '-' + second_last stuff.push(second_last) else if last.substr(0,1) == '-' last = substr(1) else last = '-' + last stuff.push(last) @writeScreen() writeScreen: () -> write = ''; angular.forEach(stuff, (k, i)-> if write == '' write = k else write += k.toString() ) write = '0' if (write == '') display = write.toString(); return if @isOperator(n) write = if n == '/' '&divide;' else if n == '*' '&times;' else if n == '+' '&plus;' else if n == '-' '&minus;' if (!stuff.length) display = write else display += write.toString() @ clearCalc: () -> stuff = [] @writeScreen() doMath: () -> justGotMath = true stuff = [@getMath()] @writeScreen() getMath: -> last = stuff.pop() if (!@isOperator(last)) stuff.push(last) job = stuff.join(''); x = 0 eval('x = ' + job + ';'); x memoryClear: -> memory = 0 @memoryIndicator(0) memoryShow: -> stuff = [memory.toString()] @writeScreen() memoryAdd: () -> memory += @getMath() @memoryIndicator(1) memorySub: () -> memory -= @getMath() if (memory != 0) @memoryIndicator(1) else @memoryIndicator(0) display: -> display
true
app = require '../app' ###* # Logic implemented in this service is a derived version of Angular Calculator Demo by PI:NAME:<NAME>END_PI (http://www.thomporter.com/docco/calc.html). ### app.factory '$calc', -> memory = 0 stuff = [0] justGotMath = false display = '' input: (n) -> console.log "input: #{n}" if justGotMath justGotMath = false stuff = [] if !@isOperator(n) n = n.toString() if n == '.' last = stuff.pop() if @isOperator(last) || Math.ceil(last) != parseInt(last) stuff.push(last) else last += '.' stuff.push(last) @writeScreen() return if (@isOperator(n)) return if !stuff.length last = stuff.pop() stuff.push(last) if !@isOperator(last) stuff.push(n) else if stuff.length last = stuff.pop() if @isOperator(last) stuff.push(last) stuff.push(n) else if last.toString() == '0' stuff.push(n) else last += n.toString() stuff.push(last) else stuff.push(n) @writeScreen() console.log stuff @ isOperator: (n) -> if isNaN(n) return true if n != '.' return false changeSign: () -> last = stuff.pop() if @isOperator(last) second_last = stuff.pop() if second_last.substr(0,1) == '-' second_last = substr(1) else second_last = '-' + second_last stuff.push(second_last) else if last.substr(0,1) == '-' last = substr(1) else last = '-' + last stuff.push(last) @writeScreen() writeScreen: () -> write = ''; angular.forEach(stuff, (k, i)-> if write == '' write = k else write += k.toString() ) write = '0' if (write == '') display = write.toString(); return if @isOperator(n) write = if n == '/' '&divide;' else if n == '*' '&times;' else if n == '+' '&plus;' else if n == '-' '&minus;' if (!stuff.length) display = write else display += write.toString() @ clearCalc: () -> stuff = [] @writeScreen() doMath: () -> justGotMath = true stuff = [@getMath()] @writeScreen() getMath: -> last = stuff.pop() if (!@isOperator(last)) stuff.push(last) job = stuff.join(''); x = 0 eval('x = ' + job + ';'); x memoryClear: -> memory = 0 @memoryIndicator(0) memoryShow: -> stuff = [memory.toString()] @writeScreen() memoryAdd: () -> memory += @getMath() @memoryIndicator(1) memorySub: () -> memory -= @getMath() if (memory != 0) @memoryIndicator(1) else @memoryIndicator(0) display: -> display
[ { "context": "ndexesOf = Ember.EnumerableUtils.indexesOf\n# TODO(Peter): use selection index\nEmber.Table.RowSelectionMix", "end": 56, "score": 0.9760202169418335, "start": 51, "tag": "NAME", "value": "Peter" } ]
src/row_selection_mixin.coffee
blend/ember-table
0
indexesOf = Ember.EnumerableUtils.indexesOf # TODO(Peter): use selection index Ember.Table.RowSelectionMixin = Ember.Mixin.create # we need to set tabindex so that div responds to key events attributeBindings: 'tabindex' contentBinding: Ember.Binding.oneWay 'controller.bodyContent' rowHeightBinding: Ember.Binding.oneWay 'controller.rowHeight' numItemsShowingBinding: Ember.Binding.oneWay 'controller._numItemsShowing' startIndexBinding: Ember.Binding.oneWay 'controller._startIndex' scrollTopBinding: 'controller._tableScrollTop' tabindex: -1 KEY_EVENTS: 37: 'leftArrowPressed' 38: 'upArrowPressed' 39: 'rightArrowPressed' 40: 'downArrowPressed' selection: Ember.computed (key, value) -> content = @get('content') or [] selection = @get 'selectionIndices' value = value or [] if arguments.length is 1 # getter value = selection.map (index) -> content.objectAt(index) else # setter indices = indexesOf content, value selection.addObjects indices value .property 'selectionIndices.[]' selectionIndices: Ember.computed -> set = new Ember.Set() set.addEnumerableObserver this set .property() enumerableDidChange: Ember.K enumerableWillChange: (set, removing, adding) -> # we are clearing the set content = @get 'content' if 'number' is typeof removing set.forEach (index) -> content.objectAt(index).set 'selected', no else if removing removing.forEach (index) -> content.objectAt(index).set 'selected', no if adding and 'number' isnt typeof adding adding.forEach (index) -> content.objectAt(index).set 'selected', yes mouseDown: (event) -> index = @getIndexForEvent event sel = @get 'selectionIndices' return sel.clear() if sel.contains(index) and sel.length is 1 @setSelectionIndex index keyDown: (event) -> map = @get 'KEY_EVENTS' method = map[event.keyCode] @get(method)?.apply(this, arguments) if method upArrowPressed: (event) -> event.preventDefault() sel = @get 'selectionIndices.lastObject' index = if event.ctrlKey or event.metaKey then 0 else sel - 1 @setSelectionIndex index downArrowPressed: (event) -> event.preventDefault() sel = @get 'selectionIndices.lastObject' clen = @get 'content.length' index = if event.ctrlKey or event.metaKey then clen - 1 else sel + 1 @setSelectionIndex index getIndexForEvent: (event) -> @getRowIndexFast @getRowForEvent(event) getRowForEvent: (event) -> $rowView = $(event.target).parents('.table-row') view = Ember.View.views[$rowView.attr('id')] view.get 'row' if view # this is necessary, because if we do content.indexOf row, this will # implicitly causes us to evaluate the entire array proxy getRowIndexFast: (row) -> startIndex = @get 'startIndex' numRows = @get('numItemsShowing') + 1 sublist = @get('content').slice(startIndex, startIndex + numRows) index = sublist.indexOf row if index < 0 then index else index + startIndex setSelectionIndex: (index) -> return unless @ensureIndex index sel = @get 'selectionIndices' @get('selectionIndices').clear() @toggleSelectionIndex index toggleSelectionIndex: (index) -> return unless @ensureIndex index sel = @get 'selectionIndices' if sel.contains index then sel.remove index else sel.add index @ensureVisible index ensureIndex: (index) -> clen = @get 'content.length' index >= 0 and index < clen ensureVisible: (index) -> startIndex = @get 'startIndex' numRows = @get 'numItemsShowing' endIndex = startIndex + numRows if index < startIndex @scrollToRowIndex index else if index >= endIndex @scrollToRowIndex(index - numRows + 1) scrollToRowIndex: (index) -> rowHeight = @get 'rowHeight' scrollTop = index * rowHeight @set 'scrollTop', scrollTop # Using MultiSelection for large data set might be slow for certain cases. # TODO: Optimize this for large data set. Ember.Table.RowMultiSelectionMixin = Ember.Mixin.create Ember.Table.RowSelectionMixin, selectionRange: undefined enumerableDidChange: (set, removing, adding) -> if 'number' is typeof removing @set 'selectionRange', undefined else if removing @reduceSelectionRange removing if adding and 'number' isnt typeof adding @expandSelectionRange adding expandSelectionRange: (indices) -> range = @get 'selectionRange' [min, max] = [_.min(indices), _.max(indices)] range = min: min, max: max if not range range = min: Math.min(range.min, min), max: Math.max(range.max, max) @set 'selectionRange', range reduceSelectionRange: (indices) -> indices = @get('selectionIndices') [min, max] = [_.min(indices), _.max(indices)] range = min: min, max: max @set 'selectionRange', range mouseDown: (event) -> row = @getRowForEvent event index = @getRowIndexFast row if event.ctrlKey or event.metaKey @toggleSelectionIndex index else if event.shiftKey range = @get 'selectionRange' @setSelectionRange range.min, index, index if range else @_super event upArrowPressed: (event) -> event.preventDefault() if event.shiftKey range = @get 'selectionRange' index = range.min - 1 @setSelectionRange index, range.max, index if range else @_super event downArrowPressed: (event) -> event.preventDefault() if event.shiftKey range = @get 'selectionRange' index = range.max + 1 @setSelectionRange range.min, index, index if range else @_super event setSelectionRange: (start, end, visibleIndex) -> return unless @ensureIndex(start) and @ensureIndex(end) beg = if start < end then start else end end = if start < end then end else start sel = @get 'selectionIndices' sel.clear() sel.addObjects [beg..end] @ensureVisible visibleIndex
88445
indexesOf = Ember.EnumerableUtils.indexesOf # TODO(<NAME>): use selection index Ember.Table.RowSelectionMixin = Ember.Mixin.create # we need to set tabindex so that div responds to key events attributeBindings: 'tabindex' contentBinding: Ember.Binding.oneWay 'controller.bodyContent' rowHeightBinding: Ember.Binding.oneWay 'controller.rowHeight' numItemsShowingBinding: Ember.Binding.oneWay 'controller._numItemsShowing' startIndexBinding: Ember.Binding.oneWay 'controller._startIndex' scrollTopBinding: 'controller._tableScrollTop' tabindex: -1 KEY_EVENTS: 37: 'leftArrowPressed' 38: 'upArrowPressed' 39: 'rightArrowPressed' 40: 'downArrowPressed' selection: Ember.computed (key, value) -> content = @get('content') or [] selection = @get 'selectionIndices' value = value or [] if arguments.length is 1 # getter value = selection.map (index) -> content.objectAt(index) else # setter indices = indexesOf content, value selection.addObjects indices value .property 'selectionIndices.[]' selectionIndices: Ember.computed -> set = new Ember.Set() set.addEnumerableObserver this set .property() enumerableDidChange: Ember.K enumerableWillChange: (set, removing, adding) -> # we are clearing the set content = @get 'content' if 'number' is typeof removing set.forEach (index) -> content.objectAt(index).set 'selected', no else if removing removing.forEach (index) -> content.objectAt(index).set 'selected', no if adding and 'number' isnt typeof adding adding.forEach (index) -> content.objectAt(index).set 'selected', yes mouseDown: (event) -> index = @getIndexForEvent event sel = @get 'selectionIndices' return sel.clear() if sel.contains(index) and sel.length is 1 @setSelectionIndex index keyDown: (event) -> map = @get 'KEY_EVENTS' method = map[event.keyCode] @get(method)?.apply(this, arguments) if method upArrowPressed: (event) -> event.preventDefault() sel = @get 'selectionIndices.lastObject' index = if event.ctrlKey or event.metaKey then 0 else sel - 1 @setSelectionIndex index downArrowPressed: (event) -> event.preventDefault() sel = @get 'selectionIndices.lastObject' clen = @get 'content.length' index = if event.ctrlKey or event.metaKey then clen - 1 else sel + 1 @setSelectionIndex index getIndexForEvent: (event) -> @getRowIndexFast @getRowForEvent(event) getRowForEvent: (event) -> $rowView = $(event.target).parents('.table-row') view = Ember.View.views[$rowView.attr('id')] view.get 'row' if view # this is necessary, because if we do content.indexOf row, this will # implicitly causes us to evaluate the entire array proxy getRowIndexFast: (row) -> startIndex = @get 'startIndex' numRows = @get('numItemsShowing') + 1 sublist = @get('content').slice(startIndex, startIndex + numRows) index = sublist.indexOf row if index < 0 then index else index + startIndex setSelectionIndex: (index) -> return unless @ensureIndex index sel = @get 'selectionIndices' @get('selectionIndices').clear() @toggleSelectionIndex index toggleSelectionIndex: (index) -> return unless @ensureIndex index sel = @get 'selectionIndices' if sel.contains index then sel.remove index else sel.add index @ensureVisible index ensureIndex: (index) -> clen = @get 'content.length' index >= 0 and index < clen ensureVisible: (index) -> startIndex = @get 'startIndex' numRows = @get 'numItemsShowing' endIndex = startIndex + numRows if index < startIndex @scrollToRowIndex index else if index >= endIndex @scrollToRowIndex(index - numRows + 1) scrollToRowIndex: (index) -> rowHeight = @get 'rowHeight' scrollTop = index * rowHeight @set 'scrollTop', scrollTop # Using MultiSelection for large data set might be slow for certain cases. # TODO: Optimize this for large data set. Ember.Table.RowMultiSelectionMixin = Ember.Mixin.create Ember.Table.RowSelectionMixin, selectionRange: undefined enumerableDidChange: (set, removing, adding) -> if 'number' is typeof removing @set 'selectionRange', undefined else if removing @reduceSelectionRange removing if adding and 'number' isnt typeof adding @expandSelectionRange adding expandSelectionRange: (indices) -> range = @get 'selectionRange' [min, max] = [_.min(indices), _.max(indices)] range = min: min, max: max if not range range = min: Math.min(range.min, min), max: Math.max(range.max, max) @set 'selectionRange', range reduceSelectionRange: (indices) -> indices = @get('selectionIndices') [min, max] = [_.min(indices), _.max(indices)] range = min: min, max: max @set 'selectionRange', range mouseDown: (event) -> row = @getRowForEvent event index = @getRowIndexFast row if event.ctrlKey or event.metaKey @toggleSelectionIndex index else if event.shiftKey range = @get 'selectionRange' @setSelectionRange range.min, index, index if range else @_super event upArrowPressed: (event) -> event.preventDefault() if event.shiftKey range = @get 'selectionRange' index = range.min - 1 @setSelectionRange index, range.max, index if range else @_super event downArrowPressed: (event) -> event.preventDefault() if event.shiftKey range = @get 'selectionRange' index = range.max + 1 @setSelectionRange range.min, index, index if range else @_super event setSelectionRange: (start, end, visibleIndex) -> return unless @ensureIndex(start) and @ensureIndex(end) beg = if start < end then start else end end = if start < end then end else start sel = @get 'selectionIndices' sel.clear() sel.addObjects [beg..end] @ensureVisible visibleIndex
true
indexesOf = Ember.EnumerableUtils.indexesOf # TODO(PI:NAME:<NAME>END_PI): use selection index Ember.Table.RowSelectionMixin = Ember.Mixin.create # we need to set tabindex so that div responds to key events attributeBindings: 'tabindex' contentBinding: Ember.Binding.oneWay 'controller.bodyContent' rowHeightBinding: Ember.Binding.oneWay 'controller.rowHeight' numItemsShowingBinding: Ember.Binding.oneWay 'controller._numItemsShowing' startIndexBinding: Ember.Binding.oneWay 'controller._startIndex' scrollTopBinding: 'controller._tableScrollTop' tabindex: -1 KEY_EVENTS: 37: 'leftArrowPressed' 38: 'upArrowPressed' 39: 'rightArrowPressed' 40: 'downArrowPressed' selection: Ember.computed (key, value) -> content = @get('content') or [] selection = @get 'selectionIndices' value = value or [] if arguments.length is 1 # getter value = selection.map (index) -> content.objectAt(index) else # setter indices = indexesOf content, value selection.addObjects indices value .property 'selectionIndices.[]' selectionIndices: Ember.computed -> set = new Ember.Set() set.addEnumerableObserver this set .property() enumerableDidChange: Ember.K enumerableWillChange: (set, removing, adding) -> # we are clearing the set content = @get 'content' if 'number' is typeof removing set.forEach (index) -> content.objectAt(index).set 'selected', no else if removing removing.forEach (index) -> content.objectAt(index).set 'selected', no if adding and 'number' isnt typeof adding adding.forEach (index) -> content.objectAt(index).set 'selected', yes mouseDown: (event) -> index = @getIndexForEvent event sel = @get 'selectionIndices' return sel.clear() if sel.contains(index) and sel.length is 1 @setSelectionIndex index keyDown: (event) -> map = @get 'KEY_EVENTS' method = map[event.keyCode] @get(method)?.apply(this, arguments) if method upArrowPressed: (event) -> event.preventDefault() sel = @get 'selectionIndices.lastObject' index = if event.ctrlKey or event.metaKey then 0 else sel - 1 @setSelectionIndex index downArrowPressed: (event) -> event.preventDefault() sel = @get 'selectionIndices.lastObject' clen = @get 'content.length' index = if event.ctrlKey or event.metaKey then clen - 1 else sel + 1 @setSelectionIndex index getIndexForEvent: (event) -> @getRowIndexFast @getRowForEvent(event) getRowForEvent: (event) -> $rowView = $(event.target).parents('.table-row') view = Ember.View.views[$rowView.attr('id')] view.get 'row' if view # this is necessary, because if we do content.indexOf row, this will # implicitly causes us to evaluate the entire array proxy getRowIndexFast: (row) -> startIndex = @get 'startIndex' numRows = @get('numItemsShowing') + 1 sublist = @get('content').slice(startIndex, startIndex + numRows) index = sublist.indexOf row if index < 0 then index else index + startIndex setSelectionIndex: (index) -> return unless @ensureIndex index sel = @get 'selectionIndices' @get('selectionIndices').clear() @toggleSelectionIndex index toggleSelectionIndex: (index) -> return unless @ensureIndex index sel = @get 'selectionIndices' if sel.contains index then sel.remove index else sel.add index @ensureVisible index ensureIndex: (index) -> clen = @get 'content.length' index >= 0 and index < clen ensureVisible: (index) -> startIndex = @get 'startIndex' numRows = @get 'numItemsShowing' endIndex = startIndex + numRows if index < startIndex @scrollToRowIndex index else if index >= endIndex @scrollToRowIndex(index - numRows + 1) scrollToRowIndex: (index) -> rowHeight = @get 'rowHeight' scrollTop = index * rowHeight @set 'scrollTop', scrollTop # Using MultiSelection for large data set might be slow for certain cases. # TODO: Optimize this for large data set. Ember.Table.RowMultiSelectionMixin = Ember.Mixin.create Ember.Table.RowSelectionMixin, selectionRange: undefined enumerableDidChange: (set, removing, adding) -> if 'number' is typeof removing @set 'selectionRange', undefined else if removing @reduceSelectionRange removing if adding and 'number' isnt typeof adding @expandSelectionRange adding expandSelectionRange: (indices) -> range = @get 'selectionRange' [min, max] = [_.min(indices), _.max(indices)] range = min: min, max: max if not range range = min: Math.min(range.min, min), max: Math.max(range.max, max) @set 'selectionRange', range reduceSelectionRange: (indices) -> indices = @get('selectionIndices') [min, max] = [_.min(indices), _.max(indices)] range = min: min, max: max @set 'selectionRange', range mouseDown: (event) -> row = @getRowForEvent event index = @getRowIndexFast row if event.ctrlKey or event.metaKey @toggleSelectionIndex index else if event.shiftKey range = @get 'selectionRange' @setSelectionRange range.min, index, index if range else @_super event upArrowPressed: (event) -> event.preventDefault() if event.shiftKey range = @get 'selectionRange' index = range.min - 1 @setSelectionRange index, range.max, index if range else @_super event downArrowPressed: (event) -> event.preventDefault() if event.shiftKey range = @get 'selectionRange' index = range.max + 1 @setSelectionRange range.min, index, index if range else @_super event setSelectionRange: (start, end, visibleIndex) -> return unless @ensureIndex(start) and @ensureIndex(end) beg = if start < end then start else end end = if start < end then end else start sel = @get 'selectionIndices' sel.clear() sel.addObjects [beg..end] @ensureVisible visibleIndex
[ { "context": "\nnikita = require '@nikitajs/core/lib'\n{command} = require '../src/query'\n{tag", "end": 28, "score": 0.8221434354782104, "start": 23, "tag": "USERNAME", "value": "itajs" }, { "context": " engine\n admin_username: db[engine].admin_username\n admin_password: db[engine].admin_passwo", "end": 443, "score": 0.6829339265823364, "start": 435, "tag": "USERNAME", "value": "username" }, { "context": " engine: engine\n admin_password: db[engine].admin_password\n .should.be.rejecte", "end": 1151, "score": 0.8204889893531799, "start": 1149, "tag": "PASSWORD", "value": "db" }, { "context": "gine: engine\n admin_password: db[engine].admin_password\n .should.be.rejectedWith\n message", "end": 1174, "score": 0.8046755790710449, "start": 1160, "tag": "PASSWORD", "value": "admin_password" }, { "context": " {$status} = await @db.user\n username: 'test_user_1_user'\n password: 'test_user_1_password'\n ", "end": 1824, "score": 0.9977853894233704, "start": 1808, "tag": "USERNAME", "value": "test_user_1_user" }, { "context": "username: 'test_user_1_user'\n password: 'test_user_1_password'\n $status.should.be.true()\n {$statu", "end": 1867, "score": 0.9994226694107056, "start": 1847, "tag": "PASSWORD", "value": "test_user_1_password" }, { "context": " {$status} = await @db.user\n username: 'test_user_1_user'\n password: 'test_user_1_password'\n ", "end": 1974, "score": 0.9971861839294434, "start": 1958, "tag": "USERNAME", "value": "test_user_1_user" }, { "context": "username: 'test_user_1_user'\n password: 'test_user_1_password'\n $status.should.be.false()\n {exist", "end": 2017, "score": 0.9994183778762817, "start": 1997, "tag": "PASSWORD", "value": "test_user_1_password" }, { "context": "sts} = await @db.user.exists\n username: 'test_user_1_user'\n exists.should.be.true()\n @db.user", "end": 2131, "score": 0.9990271329879761, "start": 2115, "tag": "USERNAME", "value": "test_user_1_user" }, { "context": "ser_2_user'\n @db.user\n username: 'test_user_2_user'\n password: 'test_user_2_invalid'\n ", "end": 2455, "score": 0.9994609951972961, "start": 2439, "tag": "USERNAME", "value": "test_user_2_user" }, { "context": "username: 'test_user_2_user'\n password: 'test_user_2_invalid'\n @db.database\n database: 'test_u", "end": 2497, "score": 0.9993178248405457, "start": 2478, "tag": "PASSWORD", "value": "test_user_2_invalid" }, { "context": "ser_2_user'\n @db.user\n username: 'test_user_2_user'\n password: 'test_user_2_valid'\n ", "end": 2646, "score": 0.9992786049842834, "start": 2630, "tag": "USERNAME", "value": "test_user_2_user" }, { "context": "username: 'test_user_2_user'\n password: 'test_user_2_valid'\n @db.query\n engine: engine\n ", "end": 2686, "score": 0.9993127584457397, "start": 2669, "tag": "PASSWORD", "value": "test_user_2_valid" }, { "context": "base: 'test_user_2_db'\n admin_username: 'test_user_2_user'\n admin_password: 'test_user_2_valid'\n ", "end": 2875, "score": 0.9993277788162231, "start": 2859, "tag": "USERNAME", "value": "test_user_2_user" }, { "context": "me: 'test_user_2_user'\n admin_password: 'test_user_2_valid'\n command: switch engine\n whe", "end": 2921, "score": 0.9993242025375366, "start": 2904, "tag": "PASSWORD", "value": "test_user_2_valid" } ]
packages/db/test/user.coffee
shivaylamba/meilisearch-gatsby-plugin-guide
31
nikita = require '@nikitajs/core/lib' {command} = require '../src/query' {tags, config, db} = require './test' they = require('mocha-they')(config) return unless tags.db for engine, _ of db describe "db.user #{engine}", -> they 'requires host, hostname, username', ({ssh}) -> nikita $ssh: ssh , -> @db.user port: 5432 engine: engine admin_username: db[engine].admin_username admin_password: db[engine].admin_password .should.be.rejectedWith message: [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `db.user`:' '#/required config must have required property \'host\';' '#/required config must have required property \'password\';' '#/required config must have required property \'username\'.' ].join ' ' they 'requires admin_username, password, username', ({ssh}) -> nikita $ssh: ssh , -> @db.user host: 'localhost' port: 5432 engine: engine admin_password: db[engine].admin_password .should.be.rejectedWith message: [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `db.user`:' '#/required config must have required property \'admin_username\';' '#/required config must have required property \'password\';' '#/required config must have required property \'username\'.' ].join ' ' they 'add new user', ({ssh}) -> nikita $ssh: ssh db: db[engine] , -> @db.user.remove 'test_user_1_user' {$status} = await @db.user username: 'test_user_1_user' password: 'test_user_1_password' $status.should.be.true() {$status} = await @db.user username: 'test_user_1_user' password: 'test_user_1_password' $status.should.be.false() {exists} = await @db.user.exists username: 'test_user_1_user' exists.should.be.true() @db.user.remove 'test_user_1_user' they 'change password', ({ssh}) -> nikita $ssh: ssh db: db[engine] , -> @db.database.remove 'test_user_2_db' @db.user.remove 'test_user_2_user' @db.user username: 'test_user_2_user' password: 'test_user_2_invalid' @db.database database: 'test_user_2_db' user: 'test_user_2_user' @db.user username: 'test_user_2_user' password: 'test_user_2_valid' @db.query engine: engine host: db[engine].host port: db[engine].port database: 'test_user_2_db' admin_username: 'test_user_2_user' admin_password: 'test_user_2_valid' command: switch engine when 'mariadb', 'mysql' 'show tables' when 'postgresql' '\\dt' @db.database.remove 'test_user_2_db' @db.user.remove 'test_user_2_user'
170613
nikita = require '@nikitajs/core/lib' {command} = require '../src/query' {tags, config, db} = require './test' they = require('mocha-they')(config) return unless tags.db for engine, _ of db describe "db.user #{engine}", -> they 'requires host, hostname, username', ({ssh}) -> nikita $ssh: ssh , -> @db.user port: 5432 engine: engine admin_username: db[engine].admin_username admin_password: db[engine].admin_password .should.be.rejectedWith message: [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `db.user`:' '#/required config must have required property \'host\';' '#/required config must have required property \'password\';' '#/required config must have required property \'username\'.' ].join ' ' they 'requires admin_username, password, username', ({ssh}) -> nikita $ssh: ssh , -> @db.user host: 'localhost' port: 5432 engine: engine admin_password: <PASSWORD>[engine].<PASSWORD> .should.be.rejectedWith message: [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `db.user`:' '#/required config must have required property \'admin_username\';' '#/required config must have required property \'password\';' '#/required config must have required property \'username\'.' ].join ' ' they 'add new user', ({ssh}) -> nikita $ssh: ssh db: db[engine] , -> @db.user.remove 'test_user_1_user' {$status} = await @db.user username: 'test_user_1_user' password: '<PASSWORD>' $status.should.be.true() {$status} = await @db.user username: 'test_user_1_user' password: '<PASSWORD>' $status.should.be.false() {exists} = await @db.user.exists username: 'test_user_1_user' exists.should.be.true() @db.user.remove 'test_user_1_user' they 'change password', ({ssh}) -> nikita $ssh: ssh db: db[engine] , -> @db.database.remove 'test_user_2_db' @db.user.remove 'test_user_2_user' @db.user username: 'test_user_2_user' password: '<PASSWORD>' @db.database database: 'test_user_2_db' user: 'test_user_2_user' @db.user username: 'test_user_2_user' password: '<PASSWORD>' @db.query engine: engine host: db[engine].host port: db[engine].port database: 'test_user_2_db' admin_username: 'test_user_2_user' admin_password: '<PASSWORD>' command: switch engine when 'mariadb', 'mysql' 'show tables' when 'postgresql' '\\dt' @db.database.remove 'test_user_2_db' @db.user.remove 'test_user_2_user'
true
nikita = require '@nikitajs/core/lib' {command} = require '../src/query' {tags, config, db} = require './test' they = require('mocha-they')(config) return unless tags.db for engine, _ of db describe "db.user #{engine}", -> they 'requires host, hostname, username', ({ssh}) -> nikita $ssh: ssh , -> @db.user port: 5432 engine: engine admin_username: db[engine].admin_username admin_password: db[engine].admin_password .should.be.rejectedWith message: [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `db.user`:' '#/required config must have required property \'host\';' '#/required config must have required property \'password\';' '#/required config must have required property \'username\'.' ].join ' ' they 'requires admin_username, password, username', ({ssh}) -> nikita $ssh: ssh , -> @db.user host: 'localhost' port: 5432 engine: engine admin_password: PI:PASSWORD:<PASSWORD>END_PI[engine].PI:PASSWORD:<PASSWORD>END_PI .should.be.rejectedWith message: [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `db.user`:' '#/required config must have required property \'admin_username\';' '#/required config must have required property \'password\';' '#/required config must have required property \'username\'.' ].join ' ' they 'add new user', ({ssh}) -> nikita $ssh: ssh db: db[engine] , -> @db.user.remove 'test_user_1_user' {$status} = await @db.user username: 'test_user_1_user' password: 'PI:PASSWORD:<PASSWORD>END_PI' $status.should.be.true() {$status} = await @db.user username: 'test_user_1_user' password: 'PI:PASSWORD:<PASSWORD>END_PI' $status.should.be.false() {exists} = await @db.user.exists username: 'test_user_1_user' exists.should.be.true() @db.user.remove 'test_user_1_user' they 'change password', ({ssh}) -> nikita $ssh: ssh db: db[engine] , -> @db.database.remove 'test_user_2_db' @db.user.remove 'test_user_2_user' @db.user username: 'test_user_2_user' password: 'PI:PASSWORD:<PASSWORD>END_PI' @db.database database: 'test_user_2_db' user: 'test_user_2_user' @db.user username: 'test_user_2_user' password: 'PI:PASSWORD:<PASSWORD>END_PI' @db.query engine: engine host: db[engine].host port: db[engine].port database: 'test_user_2_db' admin_username: 'test_user_2_user' admin_password: 'PI:PASSWORD:<PASSWORD>END_PI' command: switch engine when 'mariadb', 'mysql' 'show tables' when 'postgresql' '\\dt' @db.database.remove 'test_user_2_db' @db.user.remove 'test_user_2_user'
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9991400241851807, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-fs-write-stream-err.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") fs = require("fs") stream = fs.createWriteStream(common.tmpDir + "/out", highWaterMark: 10 ) err = new Error("BAM") write = fs.write writeCalls = 0 fs.write = -> switch writeCalls++ when 0 console.error "first write" # first time is ok. write.apply fs, arguments when 1 # then it breaks console.error "second write" cb = arguments[arguments.length - 1] process.nextTick -> cb err return else # and should not be called again! throw new Error("BOOM!") return fs.close = common.mustCall((fd_, cb) -> console.error "fs.close", fd_, stream.fd assert.equal fd_, stream.fd process.nextTick cb return ) stream.on "error", common.mustCall((err_) -> console.error "error handler" assert.equal stream.fd, null assert.equal err_, err return ) stream.write new Buffer(256), -> console.error "first cb" stream.write new Buffer(256), common.mustCall((err_) -> console.error "second cb" assert.equal err_, err return ) return
18745
# 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") fs = require("fs") stream = fs.createWriteStream(common.tmpDir + "/out", highWaterMark: 10 ) err = new Error("BAM") write = fs.write writeCalls = 0 fs.write = -> switch writeCalls++ when 0 console.error "first write" # first time is ok. write.apply fs, arguments when 1 # then it breaks console.error "second write" cb = arguments[arguments.length - 1] process.nextTick -> cb err return else # and should not be called again! throw new Error("BOOM!") return fs.close = common.mustCall((fd_, cb) -> console.error "fs.close", fd_, stream.fd assert.equal fd_, stream.fd process.nextTick cb return ) stream.on "error", common.mustCall((err_) -> console.error "error handler" assert.equal stream.fd, null assert.equal err_, err return ) stream.write new Buffer(256), -> console.error "first cb" stream.write new Buffer(256), common.mustCall((err_) -> console.error "second cb" assert.equal err_, err return ) return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") fs = require("fs") stream = fs.createWriteStream(common.tmpDir + "/out", highWaterMark: 10 ) err = new Error("BAM") write = fs.write writeCalls = 0 fs.write = -> switch writeCalls++ when 0 console.error "first write" # first time is ok. write.apply fs, arguments when 1 # then it breaks console.error "second write" cb = arguments[arguments.length - 1] process.nextTick -> cb err return else # and should not be called again! throw new Error("BOOM!") return fs.close = common.mustCall((fd_, cb) -> console.error "fs.close", fd_, stream.fd assert.equal fd_, stream.fd process.nextTick cb return ) stream.on "error", common.mustCall((err_) -> console.error "error handler" assert.equal stream.fd, null assert.equal err_, err return ) stream.write new Buffer(256), -> console.error "first cb" stream.write new Buffer(256), common.mustCall((err_) -> console.error "second cb" assert.equal err_, err return ) return
[ { "context": " API downlinkMax polyfill micro-library.\n @author Daniel Lamb <dlamb.open.source@gmail.com>\n###\ndownlinkmax = -", "end": 116, "score": 0.9998528957366943, "start": 105, "tag": "NAME", "value": "Daniel Lamb" }, { "context": "ax polyfill micro-library.\n @author Daniel Lamb <dlamb.open.source@gmail.com>\n###\ndownlinkmax = ->\n limitless = Infinity\n na", "end": 145, "score": 0.999935507774353, "start": 118, "tag": "EMAIL", "value": "dlamb.open.source@gmail.com" } ]
downlinkmax.coffee
johngeorgewright/downlinkMax
68
###* @file downlinkMax is 0.26KB Network Information API downlinkMax polyfill micro-library. @author Daniel Lamb <dlamb.open.source@gmail.com> ### downlinkmax = -> limitless = Infinity nav = navigator # deal with vendor prefixing and fallback if not supported connection = nav.connection or nav.mozConnection or nav.webkitConnection or downlinkMax: limitless # check that the API doesn't already support downlinkMax unless 'downlinkMax' of connection # assume NOT W3C Editor's Draft 09 October 2014 # check if API supports bandwidth if 'bandwidth' of connection # assume W3C Working Draft 29 November 2012 # standardize connection.bandwidth value by converting megabytes per second (MB/s) to megabits per second (Mbit/s) connection.downlinkMax = connection.bandwidth * 8 else # assume W3C Working Draft 07 June 2011 # convert connection.type value to approximate downlink values # speed estimate is based on the median downlink value for common devices in megabits per second (Mbit/s) switch connection.type when 'none' speed = 0 when '2g' speed = 0.134 when 'bluetooth', 'cellular' speed = 2 when '3g' speed = 8.95 when '4g' speed = 100 when 'ethernet' speed = 550 when 'wifi' speed = 600 # other, unknown etc. else speed = limitless connection.downlinkMax = speed # return the maximum downlink speed connection.downlinkMax
91317
###* @file downlinkMax is 0.26KB Network Information API downlinkMax polyfill micro-library. @author <NAME> <<EMAIL>> ### downlinkmax = -> limitless = Infinity nav = navigator # deal with vendor prefixing and fallback if not supported connection = nav.connection or nav.mozConnection or nav.webkitConnection or downlinkMax: limitless # check that the API doesn't already support downlinkMax unless 'downlinkMax' of connection # assume NOT W3C Editor's Draft 09 October 2014 # check if API supports bandwidth if 'bandwidth' of connection # assume W3C Working Draft 29 November 2012 # standardize connection.bandwidth value by converting megabytes per second (MB/s) to megabits per second (Mbit/s) connection.downlinkMax = connection.bandwidth * 8 else # assume W3C Working Draft 07 June 2011 # convert connection.type value to approximate downlink values # speed estimate is based on the median downlink value for common devices in megabits per second (Mbit/s) switch connection.type when 'none' speed = 0 when '2g' speed = 0.134 when 'bluetooth', 'cellular' speed = 2 when '3g' speed = 8.95 when '4g' speed = 100 when 'ethernet' speed = 550 when 'wifi' speed = 600 # other, unknown etc. else speed = limitless connection.downlinkMax = speed # return the maximum downlink speed connection.downlinkMax
true
###* @file downlinkMax is 0.26KB Network Information API downlinkMax polyfill micro-library. @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### downlinkmax = -> limitless = Infinity nav = navigator # deal with vendor prefixing and fallback if not supported connection = nav.connection or nav.mozConnection or nav.webkitConnection or downlinkMax: limitless # check that the API doesn't already support downlinkMax unless 'downlinkMax' of connection # assume NOT W3C Editor's Draft 09 October 2014 # check if API supports bandwidth if 'bandwidth' of connection # assume W3C Working Draft 29 November 2012 # standardize connection.bandwidth value by converting megabytes per second (MB/s) to megabits per second (Mbit/s) connection.downlinkMax = connection.bandwidth * 8 else # assume W3C Working Draft 07 June 2011 # convert connection.type value to approximate downlink values # speed estimate is based on the median downlink value for common devices in megabits per second (Mbit/s) switch connection.type when 'none' speed = 0 when '2g' speed = 0.134 when 'bluetooth', 'cellular' speed = 2 when '3g' speed = 8.95 when '4g' speed = 100 when 'ethernet' speed = 550 when 'wifi' speed = 600 # other, unknown etc. else speed = limitless connection.downlinkMax = speed # return the maximum downlink speed connection.downlinkMax
[ { "context": "# The MIT License (MIT)\n# \n# Copyright (c) 2013 Alytis\n# \n# Permission is hereby granted, free of charge", "end": 54, "score": 0.9987066388130188, "start": 48, "tag": "NAME", "value": "Alytis" } ]
src/main.coffee
monokrome/HyperBone
0
# The MIT License (MIT) # # Copyright (c) 2013 Alytis # # 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. HyperBone = {} HyperBone.util = require './util.coffee' HyperBone.Bone = require('./bone.coffee').Bone HyperBone.Model = require('./models.coffee').Model HyperBone.Collection = require('./collection.coffee').Collection HyperBone.ServiceType = require('./service_types/base.coffee').ServiceType window.HyperBone ?= HyperBone
209178
# The MIT License (MIT) # # Copyright (c) 2013 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. HyperBone = {} HyperBone.util = require './util.coffee' HyperBone.Bone = require('./bone.coffee').Bone HyperBone.Model = require('./models.coffee').Model HyperBone.Collection = require('./collection.coffee').Collection HyperBone.ServiceType = require('./service_types/base.coffee').ServiceType window.HyperBone ?= HyperBone
true
# The MIT License (MIT) # # Copyright (c) 2013 PI:NAME:<NAME>END_PI # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. HyperBone = {} HyperBone.util = require './util.coffee' HyperBone.Bone = require('./bone.coffee').Bone HyperBone.Model = require('./models.coffee').Model HyperBone.Collection = require('./collection.coffee').Collection HyperBone.ServiceType = require('./service_types/base.coffee').ServiceType window.HyperBone ?= HyperBone
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9996116161346436, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "# Regression test for GH-784\n# https://github.com/joyent/node/issues/784\n#\n# The test works by making a to", "end": 1170, "score": 0.9996036291122437, "start": 1164, "tag": "USERNAME", "value": "joyent" } ]
test/simple/test-regress-GH-784.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. # Regression test for GH-784 # https://github.com/joyent/node/issues/784 # # The test works by making a total of 8 requests to the server. The first # two are made with the server off - they should come back as ECONNREFUSED. # The next two are made with server on - they should come back successful. # The next two are made with the server off - and so on. Without the fix # we were experiencing parse errors and instead of ECONNREFUSED. serverOn = -> console.error "Server ON" server.listen common.PORT return serverOff = -> console.error "Server OFF" server.close() pingping() return afterPing = (result) -> responses.push result console.error "afterPing. responses.length = " + responses.length switch responses.length when 2 assert.ok /ECONNREFUSED/.test(responses[0]) assert.ok /ECONNREFUSED/.test(responses[1]) serverOn() when 4 assert.ok /success/.test(responses[2]) assert.ok /success/.test(responses[3]) serverOff() when 6 assert.ok /ECONNREFUSED/.test(responses[4]) assert.ok /ECONNREFUSED/.test(responses[5]) serverOn() when 8 assert.ok /success/.test(responses[6]) assert.ok /success/.test(responses[7]) server.close() # we should go to process.on('exit') from here. ping = -> console.error "making req" opt = port: common.PORT path: "/ping" method: "POST" req = http.request(opt, (res) -> body = "" res.setEncoding "utf8" res.on "data", (chunk) -> body += chunk return res.on "end", -> assert.equal "PONG", body assert.ok not hadError gotEnd = true afterPing "success" return return ) req.end "PING" gotEnd = false hadError = false req.on "error", (error) -> console.log "Error making ping req: " + error hadError = true assert.ok not gotEnd afterPing error.message return return pingping = -> ping() ping() return common = require("../common") http = require("http") assert = require("assert") server = http.createServer((req, res) -> body = "" req.setEncoding "utf8" req.on "data", (chunk) -> body += chunk return req.on "end", -> assert.equal "PING", body res.writeHead 200 res.end "PONG" return return ) server.on "listening", pingping responses = [] pingping() process.on "exit", -> console.error "process.on('exit')" console.error responses assert.equal 8, responses.length return
149795
# 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. # Regression test for GH-784 # https://github.com/joyent/node/issues/784 # # The test works by making a total of 8 requests to the server. The first # two are made with the server off - they should come back as ECONNREFUSED. # The next two are made with server on - they should come back successful. # The next two are made with the server off - and so on. Without the fix # we were experiencing parse errors and instead of ECONNREFUSED. serverOn = -> console.error "Server ON" server.listen common.PORT return serverOff = -> console.error "Server OFF" server.close() pingping() return afterPing = (result) -> responses.push result console.error "afterPing. responses.length = " + responses.length switch responses.length when 2 assert.ok /ECONNREFUSED/.test(responses[0]) assert.ok /ECONNREFUSED/.test(responses[1]) serverOn() when 4 assert.ok /success/.test(responses[2]) assert.ok /success/.test(responses[3]) serverOff() when 6 assert.ok /ECONNREFUSED/.test(responses[4]) assert.ok /ECONNREFUSED/.test(responses[5]) serverOn() when 8 assert.ok /success/.test(responses[6]) assert.ok /success/.test(responses[7]) server.close() # we should go to process.on('exit') from here. ping = -> console.error "making req" opt = port: common.PORT path: "/ping" method: "POST" req = http.request(opt, (res) -> body = "" res.setEncoding "utf8" res.on "data", (chunk) -> body += chunk return res.on "end", -> assert.equal "PONG", body assert.ok not hadError gotEnd = true afterPing "success" return return ) req.end "PING" gotEnd = false hadError = false req.on "error", (error) -> console.log "Error making ping req: " + error hadError = true assert.ok not gotEnd afterPing error.message return return pingping = -> ping() ping() return common = require("../common") http = require("http") assert = require("assert") server = http.createServer((req, res) -> body = "" req.setEncoding "utf8" req.on "data", (chunk) -> body += chunk return req.on "end", -> assert.equal "PING", body res.writeHead 200 res.end "PONG" return return ) server.on "listening", pingping responses = [] pingping() process.on "exit", -> console.error "process.on('exit')" console.error responses assert.equal 8, responses.length return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Regression test for GH-784 # https://github.com/joyent/node/issues/784 # # The test works by making a total of 8 requests to the server. The first # two are made with the server off - they should come back as ECONNREFUSED. # The next two are made with server on - they should come back successful. # The next two are made with the server off - and so on. Without the fix # we were experiencing parse errors and instead of ECONNREFUSED. serverOn = -> console.error "Server ON" server.listen common.PORT return serverOff = -> console.error "Server OFF" server.close() pingping() return afterPing = (result) -> responses.push result console.error "afterPing. responses.length = " + responses.length switch responses.length when 2 assert.ok /ECONNREFUSED/.test(responses[0]) assert.ok /ECONNREFUSED/.test(responses[1]) serverOn() when 4 assert.ok /success/.test(responses[2]) assert.ok /success/.test(responses[3]) serverOff() when 6 assert.ok /ECONNREFUSED/.test(responses[4]) assert.ok /ECONNREFUSED/.test(responses[5]) serverOn() when 8 assert.ok /success/.test(responses[6]) assert.ok /success/.test(responses[7]) server.close() # we should go to process.on('exit') from here. ping = -> console.error "making req" opt = port: common.PORT path: "/ping" method: "POST" req = http.request(opt, (res) -> body = "" res.setEncoding "utf8" res.on "data", (chunk) -> body += chunk return res.on "end", -> assert.equal "PONG", body assert.ok not hadError gotEnd = true afterPing "success" return return ) req.end "PING" gotEnd = false hadError = false req.on "error", (error) -> console.log "Error making ping req: " + error hadError = true assert.ok not gotEnd afterPing error.message return return pingping = -> ping() ping() return common = require("../common") http = require("http") assert = require("assert") server = http.createServer((req, res) -> body = "" req.setEncoding "utf8" req.on "data", (chunk) -> body += chunk return req.on "end", -> assert.equal "PING", body res.writeHead 200 res.end "PONG" return return ) server.on "listening", pingping responses = [] pingping() process.on "exit", -> console.error "process.on('exit')" console.error responses assert.equal 8, responses.length return
[ { "context": " id: 'test-merchant-01',\n key: '123123123123',\n },\n user: {\n merchant_u", "end": 456, "score": 0.9994581341743469, "start": 444, "tag": "KEY", "value": "123123123123" }, { "context": "user_id: '0001-0001-0001-0001',\n email: 'test@test.com',\n },\n payment_account: {\n ", "end": 568, "score": 0.9999181032180786, "start": 555, "tag": "EMAIL", "value": "test@test.com" }, { "context": "11' },\n { name: 'holder_name', value: 'John Down' },\n { name: 'expiry_month', value: '1", "end": 794, "score": 0.9997109770774841, "start": 785, "tag": "NAME", "value": "John Down" } ]
test/services/requestValidationService.coffee
leonkyr/melbourneapi
1
RequestValidationService = require '../../src/services/requestValidationService' expect = require 'expect' should = require 'should' assert = require 'assert' describe 'Request Validation Service', -> describe 'Validate Pay Request', -> it 'Initial Payment Request with all new objects', -> api = new RequestValidationService() api.validatePayRequest { merchant: { id: 'test-merchant-01', key: '123123123123', }, user: { merchant_user_id: '0001-0001-0001-0001', email: 'test@test.com', }, payment_account: { type: 'card', tokenize: true, parameters: [ { name: 'number', value: '4111111111111111' }, { name: 'holder_name', value: 'John Down' }, { name: 'expiry_month', value: '10' }, { name: 'expiry_year', value: '2019' }, { name: 'cvc', value: '123' }, ], }, order: { id: 'order-0001', amount: { value: 12345, currency: 'EUR', }, description: 'Purchase from ENAY.COM' }, purchase: { ip_address: '1.1.1.1', }, signature: 'md5hash-of-some-important-parameters' }
84478
RequestValidationService = require '../../src/services/requestValidationService' expect = require 'expect' should = require 'should' assert = require 'assert' describe 'Request Validation Service', -> describe 'Validate Pay Request', -> it 'Initial Payment Request with all new objects', -> api = new RequestValidationService() api.validatePayRequest { merchant: { id: 'test-merchant-01', key: '<KEY>', }, user: { merchant_user_id: '0001-0001-0001-0001', email: '<EMAIL>', }, payment_account: { type: 'card', tokenize: true, parameters: [ { name: 'number', value: '4111111111111111' }, { name: 'holder_name', value: '<NAME>' }, { name: 'expiry_month', value: '10' }, { name: 'expiry_year', value: '2019' }, { name: 'cvc', value: '123' }, ], }, order: { id: 'order-0001', amount: { value: 12345, currency: 'EUR', }, description: 'Purchase from ENAY.COM' }, purchase: { ip_address: '1.1.1.1', }, signature: 'md5hash-of-some-important-parameters' }
true
RequestValidationService = require '../../src/services/requestValidationService' expect = require 'expect' should = require 'should' assert = require 'assert' describe 'Request Validation Service', -> describe 'Validate Pay Request', -> it 'Initial Payment Request with all new objects', -> api = new RequestValidationService() api.validatePayRequest { merchant: { id: 'test-merchant-01', key: 'PI:KEY:<KEY>END_PI', }, user: { merchant_user_id: '0001-0001-0001-0001', email: 'PI:EMAIL:<EMAIL>END_PI', }, payment_account: { type: 'card', tokenize: true, parameters: [ { name: 'number', value: '4111111111111111' }, { name: 'holder_name', value: 'PI:NAME:<NAME>END_PI' }, { name: 'expiry_month', value: '10' }, { name: 'expiry_year', value: '2019' }, { name: 'cvc', value: '123' }, ], }, order: { id: 'order-0001', amount: { value: 12345, currency: 'EUR', }, description: 'Purchase from ENAY.COM' }, purchase: { ip_address: '1.1.1.1', }, signature: 'md5hash-of-some-important-parameters' }
[ { "context": "is.setOptions options\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nOptions =\n options: {} # instance options obj", "end": 322, "score": 0.9998942613601685, "start": 305, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/core/src/options.coffee
lovely-io/lovely.io-stl
2
# # A standard options handling interface mixin # # MyClass = new Lovely.Class # include: Lovely.Options, # extend: # Options: # one: 'thing' # another: 'one' # # initialize: (options) -> # this.setOptions options # # Copyright (C) 2011-2012 Nikolay Nemshilov # Options = options: {} # instance options object # # Sets the current options # # __NOTE__: this method will _deep-merge_ the klass.Options # # @param {Object} options # @return {Class} this # setOptions: (options) -> klass = this.constructor defaults = {} while klass if 'Options' of klass defaults = klass.Options break klass = klass.__super__ this.options = Hash.merge(defaults, options) this
131173
# # A standard options handling interface mixin # # MyClass = new Lovely.Class # include: Lovely.Options, # extend: # Options: # one: 'thing' # another: 'one' # # initialize: (options) -> # this.setOptions options # # Copyright (C) 2011-2012 <NAME> # Options = options: {} # instance options object # # Sets the current options # # __NOTE__: this method will _deep-merge_ the klass.Options # # @param {Object} options # @return {Class} this # setOptions: (options) -> klass = this.constructor defaults = {} while klass if 'Options' of klass defaults = klass.Options break klass = klass.__super__ this.options = Hash.merge(defaults, options) this
true
# # A standard options handling interface mixin # # MyClass = new Lovely.Class # include: Lovely.Options, # extend: # Options: # one: 'thing' # another: 'one' # # initialize: (options) -> # this.setOptions options # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # Options = options: {} # instance options object # # Sets the current options # # __NOTE__: this method will _deep-merge_ the klass.Options # # @param {Object} options # @return {Class} this # setOptions: (options) -> klass = this.constructor defaults = {} while klass if 'Options' of klass defaults = klass.Options break klass = klass.__super__ this.options = Hash.merge(defaults, options) this
[ { "context": "@_extendAll(rr)\n rankConstraintMessageKey = 'kobo--rank-constraint-message'\n if !rr.get(rankConstraintMessageKey)\n ", "end": 6467, "score": 0.997516393661499, "start": 6438, "tag": "KEY", "value": "kobo--rank-constraint-message" }, { "context": "ed more than once\"))\n\n _beginEndKey: ->\n 'rank'\n\n linkUp: (ctx)->\n rank_list_id = @get('", "end": 6633, "score": 0.7289832234382629, "start": 6629, "tag": "KEY", "value": "rank" } ]
kobo-docker/.vols/static/kpi/xlform/src/model.row.coffee
OpenOPx/kobotoolbox
0
global = @ _ = require 'underscore' Backbone = require 'backbone' alertify = require 'alertifyjs' base = require './model.base' $configs = require './model.configs' $utils = require './model.utils' $surveyDetail = require './model.surveyDetail' $aliases = require './model.aliases' $rowDetail = require './model.rowDetail' $choices = require './model.choices' $skipLogicHelpers = require './mv.skipLogicHelpers' _t = require('utils').t readParameters = require('utils').readParameters writeParameters = require('utils').writeParameters module.exports = do -> row = {} class row.BaseRow extends base.BaseModel @kls = "BaseRow" constructor: (attributes={}, options={})-> for key, val of attributes when key is "" delete attributes[key] super(attributes, options) ensureKuid: -> if '$kuid' not of @attributes @set '$kuid', $utils.txtid() initialize: -> @ensureKuid() @convertAttributesToRowDetails() isError: -> false convertAttributesToRowDetails: -> for key, val of @attributes unless val instanceof $rowDetail.RowDetail @set key, new $rowDetail.RowDetail({key: key, value: val}, {_parent: @}), {silent: true} attributesArray: ()-> arr = ([k, v] for k, v of @attributes) arr.sort (a,b)-> if a[1]._order < b[1]._order then -1 else 1 arr isGroup: -> @constructor.kls is "Group" isInGroup: -> @_parent?._parent?.constructor.kls is "Group" detach: (opts)-> if @_parent @_parent.remove @, opts @_parent = null ` ` selectableRows: () -> questions = [] limit = false non_selectable = ['datetime', 'time', 'note', 'calculate', 'group', 'kobomatrix', 'repeat', 'rank', 'score'] survey = @getSurvey() if survey == null return null survey.forEachRow (question) => limit = limit || question is @ if !limit && question.getValue('type') not in non_selectable questions.push question , includeGroups:true questions export_relevant_values: (survey_arr, additionalSheets)-> survey_arr.push @toJSON2() toJSON2: -> outObj = {} for [key, val] in @attributesArray() if key is 'type' and val.get('typeId') in ['select_one', 'select_multiple'] outObj['type'] = val.get('typeId') outObj['select_from_list_name'] = val.get('listName') continue else result = @getValue(key) unless @hidden if _.isBoolean(result) outObj[key] = $configs.boolOutputs[if result then "true" else "false"] else if '' isnt result outObj[key] = result outObj toJSON: -> outObj = {} for [key, val] in @attributesArray() result = @getValue(key) unless @hidden if _.isBoolean(result) outObj[key] = $configs.boolOutputs[if result then "true" else "false"] else outObj[key] = result outObj class SimpleRow extends Backbone.Model finalize: -> `` simpleEnsureKuid: -> if '$kuid' not of @attributes @set('$kuid', $utils.txtid()) getTypeId: -> @get('type') linkUp: -> _isSelectQuestion: ()-> false get_type: -> $skipLogicHelpers.question_types[@getTypeId()] || $skipLogicHelpers.question_types['default'] getValue: (which)-> @get(which) class RankRow extends SimpleRow initialize: -> @simpleEnsureKuid() @set('type', 'rank__level') export_relevant_values: (surv, sheets)-> surv.push @attributes class ScoreRankMixin _extendAll: (rr)-> extend_to_row = (val, key)=> if _.isFunction(val) rr[key] = (args...)-> val.apply(rr, args) else rr[key] = val _.each @, extend_to_row extend_to_row(@forEachRow, 'forEachRow') _begin_kuid = rr.getValue('$kuid', false) _end_json = @end_json({"$kuid": "/#{_begin_kuid}"}) rr._afterIterator = (cb, ctxt)-> obj = export_relevant_values: (surv, addl)-> surv.push _.extend({}, _end_json) toJSON: -> _.extend({}, _end_json) cb(obj) if ctxt.includeGroupEnds _toJSON = rr.toJSON rr.clone = ()-> attributes = rr.toJSON2() options = _parent: rr._parent add: false merge: false remove: false silent: true r2 = new row.Row(attributes, options) r2._isCloned = true if rr._rankRows # if rr is a rank question for rankRow in rr._rankRows.models r2._rankRows.add(rankRow.toJSON()) r2._rankLevels = rr.getSurvey().choices.add(name: $utils.txtid()) for item in rr.getList().options.models r2._rankLevels.options.add(item.toJSON()) r2.set('kobo--rank-items', r2._rankLevels.get('name')) @convertAttributesToRowDetails() r2.get('type').set('list', r2._rankLevels) else # if rr is a score question for scoreRow in rr._scoreRows.models r2._scoreRows.add(scoreRow.toJSON()) r2._scoreChoices = rr.getSurvey().choices.add(name: $utils.txtid()) for item in rr.getList().options.models r2._scoreChoices.options.add(item.toJSON()) r2.set('kobo--score-choices', r2._scoreChoices.get('name')) @convertAttributesToRowDetails() r2.get('type').set('list', r2._scoreChoices) r2 rr.toJSON = ()-> _.extend _toJSON.call(rr), { 'type': "begin_#{rr._beginEndKey()}" }, @_additionalJson?() _.each @constructor.prototype, extend_to_row if rr.attributes.__rows for subrow in rr.attributes.__rows @[@_rowAttributeName].add(subrow) delete rr.attributes.__rows getValue: (which)-> @get(which) end_json: (mrg={})-> _.extend({type: "end_#{@_beginEndKey()}"}, mrg) forEachRow: (cb, ctx)-> cb(@) @[@_rowAttributeName].each (subrow)-> cb(subrow) @_afterIterator(cb, ctx) if '_afterIterator' of @ class RankRows extends Backbone.Collection model: RankRow class RankMixin extends ScoreRankMixin constructor: (rr)-> @_rankRows = new RankRows() @_rowAttributeName = '_rankRows' @_extendAll(rr) rankConstraintMessageKey = 'kobo--rank-constraint-message' if !rr.get(rankConstraintMessageKey) rr.set(rankConstraintMessageKey, _t("Items cannot be selected more than once")) _beginEndKey: -> 'rank' linkUp: (ctx)-> rank_list_id = @get('kobo--rank-items')?.get('value') if rank_list_id @_rankLevels = @getSurvey().choices.get(rank_list_id) else @_rankLevels = @getSurvey().choices.create() @_additionalJson = => 'kobo--rank-items': @getList().get('name') @getList = => @_rankLevels export_relevant_values: (survey_arr, additionalSheets)-> if @_rankLevels additionalSheets['choices'].add(@_rankLevels) begin_xlsformrow = _.clone(@toJSON2()) begin_xlsformrow.type = "begin_rank" begin_xlsformrow['kobo--rank-items'] = @getList().get('name') survey_arr.push(begin_xlsformrow) `` class ScoreChoiceList extends Array class ScoreRow extends SimpleRow initialize: -> @set('type', 'score__row') @simpleEnsureKuid() export_relevant_values: (surv, sheets)-> surv.push(@attributes) class ScoreRows extends Backbone.Collection model: ScoreRow class ScoreMixin extends ScoreRankMixin constructor: (rr)-> @_scoreRows = new ScoreRows() @_rowAttributeName = '_scoreRows' @_extendAll(rr) _beginEndKey: -> 'score' linkUp: (ctx)-> @getList = ()=> @_scoreChoices @_additionalJson = ()=> 'kobo--score-choices': @getList().get('name') score_list_id_item = @get('kobo--score-choices') if score_list_id_item score_list_id = score_list_id_item.get('value') if score_list_id @_scoreChoices = @getSurvey().choices.get(score_list_id) else ctx.warnings.push "Score choices list not found" @_scoreChoices = @getSurvey().choices.add({}) else ctx.warnings.push "Score choices list not set" @_scoreChoices = @getSurvey().choices.add(name: $utils.txtid()) `` export_relevant_values: (survey_arr, additionalSheets)-> score_list = @_scoreChoices if score_list additionalSheets['choices'].add(score_list) output = _.clone(@toJSON2()) output.type = "begin_score" output['kobo--score-choices'] = @getList().get('name') survey_arr.push(output) `` class row.Row extends row.BaseRow @kls = "Row" initialize: -> ### The best way to understand the @details collection is that it is a list of cells of the XLSForm spreadsheet. The column name is the "key" and the value is the "value". We opted for a collection (rather than just saving in the attributes of this model) because of the various state-related attributes that need to be saved for each cell and this allows more room to grow. E.g.: {"key": "type", "value": "select_one colors"} needs to keep track of how the value was built ### if @_parent defaultsUnlessDefined = @_parent.newRowDetails || $configs.newRowDetails defaultsForType = @_parent.defaultsForType || $configs.defaultsForType else console?.error "Row not linked to parent survey." defaultsUnlessDefined = $configs.newRowDetails defaultsForType = $configs.defaultsForType if @attributes.type and @attributes.type of defaultsForType curTypeDefaults = defaultsForType[@attributes.type] else curTypeDefaults = {} defaults = _.extend {}, defaultsUnlessDefined, curTypeDefaults for key, vals of defaults unless key of @attributes newVals = {} for vk, vv of vals newVals[vk] = if ("function" is typeof vv) then vv() else vv @set key, newVals if '$kuid' not of @attributes @set '$kuid', $utils.txtid() _type = @getValue('type') if _type is 'score' new ScoreMixin(@) else if _type is 'rank' new RankMixin(@) @convertAttributesToRowDetails() typeDetail = @get("type") tpVal = typeDetail.get("value") select_from_list_name = @get("select_from_list_name") if select_from_list_name and tpVal tpVal = "#{tpVal} #{select_from_list_name.get('value')}" typeDetail.set("value", tpVal, silent: true) processType = (rd, newType, ctxt)=> # if value changes, it could be set from an initialization value # or it could be changed elsewhere. # we need to keep typeId, listName, and orOther in sync. if _.isObject(newType) tpid = _.keys(newType)[0] p2 = _.values(newType)[0] else [tpid, p2, p3] = newType.split(" ") typeDetail.set("typeId", tpid, silent: true) if p2 typeDetail.set("listName", p2, silent: true) matchedList = @getSurvey().choices.get(p2) if matchedList typeDetail.set("list", matchedList) if p3 is "or_other" or tpid in ["select_one_or_other", "select_multiple_or_other"] typeDetail.set("orOther", p3, silent: true) if (rtp = $configs.lookupRowType(tpid)) typeDetail.set("rowType", rtp, silent: true) else throw new Error "type `#{tpid}` not found" processType(typeDetail, tpVal, {}) typeDetail.on "change:value", processType typeDetail.on "change:listName", (rd, listName, ctx)-> rtp = typeDetail.get("rowType") typeStr = "#{typeDetail.get("typeId")}" if rtp.specifyChoice and listName typeStr += " #{listName}" if rtp.orOtherOption and typeDetail.get("orOther") typeStr += " or_other" typeDetail.set({value: typeStr}, silent: true) typeDetail.on "change:list", (rd, cl, ctx)-> if typeDetail.get("rowType").specifyChoice clname = cl.get("name") unless clname clname = $utils.txtid() cl.set("name", clname, silent: true) @set("value", "#{@get('typeId')} #{clname}") getTypeId: -> @get('type').get('typeId') clone: -> attributes = {} options = _parent: @_parent add: false merge: false remove: false silent: true _.each @attributes, (value, key) => attributes[key] = @getValue key newRow = new row.Row attributes, options newRowType = newRow.get('type') if newRowType.get('typeId') in ['select_one', 'select_multiple'] newRowType.set 'list', @getList().clone() newRowType.set 'listName', newRowType.get('list').get 'name' @getSurvey().trigger('change') return newRow finalize: -> existing_name = @getValue("name") unless existing_name names = [] @getSurvey().forEachRow (r)-> name = r.getValue("name") names.push(name) if name label = @getValue("label") @get("name").set("value", $utils.sluggifyLabel(label, names)) @ get_type: -> $skipLogicHelpers.question_types[@getTypeId()] || $skipLogicHelpers.question_types['default'] _isSelectQuestion: -> # TODO [ald]: pull this from $aliases @get('type').get('typeId') in ['select_one', 'select_multiple'] getAcceptedFiles: -> return @attributes['body::accept']?.attributes?.value setAcceptedFiles: (bodyAcceptString) -> @setDetail('body::accept', bodyAcceptString) return getParameters: -> readParameters(@attributes.parameters?.attributes?.value) setParameters: (paramObject) -> paramString = writeParameters(paramObject) @setDetail('parameters', paramString) return getList: -> _list = @get('type')?.get('list') if (not _list) and @_isSelectQuestion() _list = new $choices.ChoiceList(name: $utils.txtid()) @setList(_list) _list setList: (list)-> listToSet = @getSurvey().choices.get(list) unless listToSet @getSurvey().choices.add(list) listToSet = @getSurvey().choices.get(list) throw new Error("List not found: #{list}") unless listToSet @get("type").set("list", listToSet) parse: -> val.parse() for key, val of @attributes linkUp: (ctx)-> val.linkUp(ctx) for key, val of @attributes class row.RowError extends row.BaseRow constructor: (obj, options)-> @_error = options.error unless window.xlfHideWarnings console?.error("Error creating row: [#{options.error}]", obj) alertify.error("Error creating row: [#{options.error}]"); super(obj, options) isError: -> true getValue: (what)-> if what of @attributes @attributes[what].get('value') else "[error]" row
83495
global = @ _ = require 'underscore' Backbone = require 'backbone' alertify = require 'alertifyjs' base = require './model.base' $configs = require './model.configs' $utils = require './model.utils' $surveyDetail = require './model.surveyDetail' $aliases = require './model.aliases' $rowDetail = require './model.rowDetail' $choices = require './model.choices' $skipLogicHelpers = require './mv.skipLogicHelpers' _t = require('utils').t readParameters = require('utils').readParameters writeParameters = require('utils').writeParameters module.exports = do -> row = {} class row.BaseRow extends base.BaseModel @kls = "BaseRow" constructor: (attributes={}, options={})-> for key, val of attributes when key is "" delete attributes[key] super(attributes, options) ensureKuid: -> if '$kuid' not of @attributes @set '$kuid', $utils.txtid() initialize: -> @ensureKuid() @convertAttributesToRowDetails() isError: -> false convertAttributesToRowDetails: -> for key, val of @attributes unless val instanceof $rowDetail.RowDetail @set key, new $rowDetail.RowDetail({key: key, value: val}, {_parent: @}), {silent: true} attributesArray: ()-> arr = ([k, v] for k, v of @attributes) arr.sort (a,b)-> if a[1]._order < b[1]._order then -1 else 1 arr isGroup: -> @constructor.kls is "Group" isInGroup: -> @_parent?._parent?.constructor.kls is "Group" detach: (opts)-> if @_parent @_parent.remove @, opts @_parent = null ` ` selectableRows: () -> questions = [] limit = false non_selectable = ['datetime', 'time', 'note', 'calculate', 'group', 'kobomatrix', 'repeat', 'rank', 'score'] survey = @getSurvey() if survey == null return null survey.forEachRow (question) => limit = limit || question is @ if !limit && question.getValue('type') not in non_selectable questions.push question , includeGroups:true questions export_relevant_values: (survey_arr, additionalSheets)-> survey_arr.push @toJSON2() toJSON2: -> outObj = {} for [key, val] in @attributesArray() if key is 'type' and val.get('typeId') in ['select_one', 'select_multiple'] outObj['type'] = val.get('typeId') outObj['select_from_list_name'] = val.get('listName') continue else result = @getValue(key) unless @hidden if _.isBoolean(result) outObj[key] = $configs.boolOutputs[if result then "true" else "false"] else if '' isnt result outObj[key] = result outObj toJSON: -> outObj = {} for [key, val] in @attributesArray() result = @getValue(key) unless @hidden if _.isBoolean(result) outObj[key] = $configs.boolOutputs[if result then "true" else "false"] else outObj[key] = result outObj class SimpleRow extends Backbone.Model finalize: -> `` simpleEnsureKuid: -> if '$kuid' not of @attributes @set('$kuid', $utils.txtid()) getTypeId: -> @get('type') linkUp: -> _isSelectQuestion: ()-> false get_type: -> $skipLogicHelpers.question_types[@getTypeId()] || $skipLogicHelpers.question_types['default'] getValue: (which)-> @get(which) class RankRow extends SimpleRow initialize: -> @simpleEnsureKuid() @set('type', 'rank__level') export_relevant_values: (surv, sheets)-> surv.push @attributes class ScoreRankMixin _extendAll: (rr)-> extend_to_row = (val, key)=> if _.isFunction(val) rr[key] = (args...)-> val.apply(rr, args) else rr[key] = val _.each @, extend_to_row extend_to_row(@forEachRow, 'forEachRow') _begin_kuid = rr.getValue('$kuid', false) _end_json = @end_json({"$kuid": "/#{_begin_kuid}"}) rr._afterIterator = (cb, ctxt)-> obj = export_relevant_values: (surv, addl)-> surv.push _.extend({}, _end_json) toJSON: -> _.extend({}, _end_json) cb(obj) if ctxt.includeGroupEnds _toJSON = rr.toJSON rr.clone = ()-> attributes = rr.toJSON2() options = _parent: rr._parent add: false merge: false remove: false silent: true r2 = new row.Row(attributes, options) r2._isCloned = true if rr._rankRows # if rr is a rank question for rankRow in rr._rankRows.models r2._rankRows.add(rankRow.toJSON()) r2._rankLevels = rr.getSurvey().choices.add(name: $utils.txtid()) for item in rr.getList().options.models r2._rankLevels.options.add(item.toJSON()) r2.set('kobo--rank-items', r2._rankLevels.get('name')) @convertAttributesToRowDetails() r2.get('type').set('list', r2._rankLevels) else # if rr is a score question for scoreRow in rr._scoreRows.models r2._scoreRows.add(scoreRow.toJSON()) r2._scoreChoices = rr.getSurvey().choices.add(name: $utils.txtid()) for item in rr.getList().options.models r2._scoreChoices.options.add(item.toJSON()) r2.set('kobo--score-choices', r2._scoreChoices.get('name')) @convertAttributesToRowDetails() r2.get('type').set('list', r2._scoreChoices) r2 rr.toJSON = ()-> _.extend _toJSON.call(rr), { 'type': "begin_#{rr._beginEndKey()}" }, @_additionalJson?() _.each @constructor.prototype, extend_to_row if rr.attributes.__rows for subrow in rr.attributes.__rows @[@_rowAttributeName].add(subrow) delete rr.attributes.__rows getValue: (which)-> @get(which) end_json: (mrg={})-> _.extend({type: "end_#{@_beginEndKey()}"}, mrg) forEachRow: (cb, ctx)-> cb(@) @[@_rowAttributeName].each (subrow)-> cb(subrow) @_afterIterator(cb, ctx) if '_afterIterator' of @ class RankRows extends Backbone.Collection model: RankRow class RankMixin extends ScoreRankMixin constructor: (rr)-> @_rankRows = new RankRows() @_rowAttributeName = '_rankRows' @_extendAll(rr) rankConstraintMessageKey = '<KEY>' if !rr.get(rankConstraintMessageKey) rr.set(rankConstraintMessageKey, _t("Items cannot be selected more than once")) _beginEndKey: -> '<KEY>' linkUp: (ctx)-> rank_list_id = @get('kobo--rank-items')?.get('value') if rank_list_id @_rankLevels = @getSurvey().choices.get(rank_list_id) else @_rankLevels = @getSurvey().choices.create() @_additionalJson = => 'kobo--rank-items': @getList().get('name') @getList = => @_rankLevels export_relevant_values: (survey_arr, additionalSheets)-> if @_rankLevels additionalSheets['choices'].add(@_rankLevels) begin_xlsformrow = _.clone(@toJSON2()) begin_xlsformrow.type = "begin_rank" begin_xlsformrow['kobo--rank-items'] = @getList().get('name') survey_arr.push(begin_xlsformrow) `` class ScoreChoiceList extends Array class ScoreRow extends SimpleRow initialize: -> @set('type', 'score__row') @simpleEnsureKuid() export_relevant_values: (surv, sheets)-> surv.push(@attributes) class ScoreRows extends Backbone.Collection model: ScoreRow class ScoreMixin extends ScoreRankMixin constructor: (rr)-> @_scoreRows = new ScoreRows() @_rowAttributeName = '_scoreRows' @_extendAll(rr) _beginEndKey: -> 'score' linkUp: (ctx)-> @getList = ()=> @_scoreChoices @_additionalJson = ()=> 'kobo--score-choices': @getList().get('name') score_list_id_item = @get('kobo--score-choices') if score_list_id_item score_list_id = score_list_id_item.get('value') if score_list_id @_scoreChoices = @getSurvey().choices.get(score_list_id) else ctx.warnings.push "Score choices list not found" @_scoreChoices = @getSurvey().choices.add({}) else ctx.warnings.push "Score choices list not set" @_scoreChoices = @getSurvey().choices.add(name: $utils.txtid()) `` export_relevant_values: (survey_arr, additionalSheets)-> score_list = @_scoreChoices if score_list additionalSheets['choices'].add(score_list) output = _.clone(@toJSON2()) output.type = "begin_score" output['kobo--score-choices'] = @getList().get('name') survey_arr.push(output) `` class row.Row extends row.BaseRow @kls = "Row" initialize: -> ### The best way to understand the @details collection is that it is a list of cells of the XLSForm spreadsheet. The column name is the "key" and the value is the "value". We opted for a collection (rather than just saving in the attributes of this model) because of the various state-related attributes that need to be saved for each cell and this allows more room to grow. E.g.: {"key": "type", "value": "select_one colors"} needs to keep track of how the value was built ### if @_parent defaultsUnlessDefined = @_parent.newRowDetails || $configs.newRowDetails defaultsForType = @_parent.defaultsForType || $configs.defaultsForType else console?.error "Row not linked to parent survey." defaultsUnlessDefined = $configs.newRowDetails defaultsForType = $configs.defaultsForType if @attributes.type and @attributes.type of defaultsForType curTypeDefaults = defaultsForType[@attributes.type] else curTypeDefaults = {} defaults = _.extend {}, defaultsUnlessDefined, curTypeDefaults for key, vals of defaults unless key of @attributes newVals = {} for vk, vv of vals newVals[vk] = if ("function" is typeof vv) then vv() else vv @set key, newVals if '$kuid' not of @attributes @set '$kuid', $utils.txtid() _type = @getValue('type') if _type is 'score' new ScoreMixin(@) else if _type is 'rank' new RankMixin(@) @convertAttributesToRowDetails() typeDetail = @get("type") tpVal = typeDetail.get("value") select_from_list_name = @get("select_from_list_name") if select_from_list_name and tpVal tpVal = "#{tpVal} #{select_from_list_name.get('value')}" typeDetail.set("value", tpVal, silent: true) processType = (rd, newType, ctxt)=> # if value changes, it could be set from an initialization value # or it could be changed elsewhere. # we need to keep typeId, listName, and orOther in sync. if _.isObject(newType) tpid = _.keys(newType)[0] p2 = _.values(newType)[0] else [tpid, p2, p3] = newType.split(" ") typeDetail.set("typeId", tpid, silent: true) if p2 typeDetail.set("listName", p2, silent: true) matchedList = @getSurvey().choices.get(p2) if matchedList typeDetail.set("list", matchedList) if p3 is "or_other" or tpid in ["select_one_or_other", "select_multiple_or_other"] typeDetail.set("orOther", p3, silent: true) if (rtp = $configs.lookupRowType(tpid)) typeDetail.set("rowType", rtp, silent: true) else throw new Error "type `#{tpid}` not found" processType(typeDetail, tpVal, {}) typeDetail.on "change:value", processType typeDetail.on "change:listName", (rd, listName, ctx)-> rtp = typeDetail.get("rowType") typeStr = "#{typeDetail.get("typeId")}" if rtp.specifyChoice and listName typeStr += " #{listName}" if rtp.orOtherOption and typeDetail.get("orOther") typeStr += " or_other" typeDetail.set({value: typeStr}, silent: true) typeDetail.on "change:list", (rd, cl, ctx)-> if typeDetail.get("rowType").specifyChoice clname = cl.get("name") unless clname clname = $utils.txtid() cl.set("name", clname, silent: true) @set("value", "#{@get('typeId')} #{clname}") getTypeId: -> @get('type').get('typeId') clone: -> attributes = {} options = _parent: @_parent add: false merge: false remove: false silent: true _.each @attributes, (value, key) => attributes[key] = @getValue key newRow = new row.Row attributes, options newRowType = newRow.get('type') if newRowType.get('typeId') in ['select_one', 'select_multiple'] newRowType.set 'list', @getList().clone() newRowType.set 'listName', newRowType.get('list').get 'name' @getSurvey().trigger('change') return newRow finalize: -> existing_name = @getValue("name") unless existing_name names = [] @getSurvey().forEachRow (r)-> name = r.getValue("name") names.push(name) if name label = @getValue("label") @get("name").set("value", $utils.sluggifyLabel(label, names)) @ get_type: -> $skipLogicHelpers.question_types[@getTypeId()] || $skipLogicHelpers.question_types['default'] _isSelectQuestion: -> # TODO [ald]: pull this from $aliases @get('type').get('typeId') in ['select_one', 'select_multiple'] getAcceptedFiles: -> return @attributes['body::accept']?.attributes?.value setAcceptedFiles: (bodyAcceptString) -> @setDetail('body::accept', bodyAcceptString) return getParameters: -> readParameters(@attributes.parameters?.attributes?.value) setParameters: (paramObject) -> paramString = writeParameters(paramObject) @setDetail('parameters', paramString) return getList: -> _list = @get('type')?.get('list') if (not _list) and @_isSelectQuestion() _list = new $choices.ChoiceList(name: $utils.txtid()) @setList(_list) _list setList: (list)-> listToSet = @getSurvey().choices.get(list) unless listToSet @getSurvey().choices.add(list) listToSet = @getSurvey().choices.get(list) throw new Error("List not found: #{list}") unless listToSet @get("type").set("list", listToSet) parse: -> val.parse() for key, val of @attributes linkUp: (ctx)-> val.linkUp(ctx) for key, val of @attributes class row.RowError extends row.BaseRow constructor: (obj, options)-> @_error = options.error unless window.xlfHideWarnings console?.error("Error creating row: [#{options.error}]", obj) alertify.error("Error creating row: [#{options.error}]"); super(obj, options) isError: -> true getValue: (what)-> if what of @attributes @attributes[what].get('value') else "[error]" row
true
global = @ _ = require 'underscore' Backbone = require 'backbone' alertify = require 'alertifyjs' base = require './model.base' $configs = require './model.configs' $utils = require './model.utils' $surveyDetail = require './model.surveyDetail' $aliases = require './model.aliases' $rowDetail = require './model.rowDetail' $choices = require './model.choices' $skipLogicHelpers = require './mv.skipLogicHelpers' _t = require('utils').t readParameters = require('utils').readParameters writeParameters = require('utils').writeParameters module.exports = do -> row = {} class row.BaseRow extends base.BaseModel @kls = "BaseRow" constructor: (attributes={}, options={})-> for key, val of attributes when key is "" delete attributes[key] super(attributes, options) ensureKuid: -> if '$kuid' not of @attributes @set '$kuid', $utils.txtid() initialize: -> @ensureKuid() @convertAttributesToRowDetails() isError: -> false convertAttributesToRowDetails: -> for key, val of @attributes unless val instanceof $rowDetail.RowDetail @set key, new $rowDetail.RowDetail({key: key, value: val}, {_parent: @}), {silent: true} attributesArray: ()-> arr = ([k, v] for k, v of @attributes) arr.sort (a,b)-> if a[1]._order < b[1]._order then -1 else 1 arr isGroup: -> @constructor.kls is "Group" isInGroup: -> @_parent?._parent?.constructor.kls is "Group" detach: (opts)-> if @_parent @_parent.remove @, opts @_parent = null ` ` selectableRows: () -> questions = [] limit = false non_selectable = ['datetime', 'time', 'note', 'calculate', 'group', 'kobomatrix', 'repeat', 'rank', 'score'] survey = @getSurvey() if survey == null return null survey.forEachRow (question) => limit = limit || question is @ if !limit && question.getValue('type') not in non_selectable questions.push question , includeGroups:true questions export_relevant_values: (survey_arr, additionalSheets)-> survey_arr.push @toJSON2() toJSON2: -> outObj = {} for [key, val] in @attributesArray() if key is 'type' and val.get('typeId') in ['select_one', 'select_multiple'] outObj['type'] = val.get('typeId') outObj['select_from_list_name'] = val.get('listName') continue else result = @getValue(key) unless @hidden if _.isBoolean(result) outObj[key] = $configs.boolOutputs[if result then "true" else "false"] else if '' isnt result outObj[key] = result outObj toJSON: -> outObj = {} for [key, val] in @attributesArray() result = @getValue(key) unless @hidden if _.isBoolean(result) outObj[key] = $configs.boolOutputs[if result then "true" else "false"] else outObj[key] = result outObj class SimpleRow extends Backbone.Model finalize: -> `` simpleEnsureKuid: -> if '$kuid' not of @attributes @set('$kuid', $utils.txtid()) getTypeId: -> @get('type') linkUp: -> _isSelectQuestion: ()-> false get_type: -> $skipLogicHelpers.question_types[@getTypeId()] || $skipLogicHelpers.question_types['default'] getValue: (which)-> @get(which) class RankRow extends SimpleRow initialize: -> @simpleEnsureKuid() @set('type', 'rank__level') export_relevant_values: (surv, sheets)-> surv.push @attributes class ScoreRankMixin _extendAll: (rr)-> extend_to_row = (val, key)=> if _.isFunction(val) rr[key] = (args...)-> val.apply(rr, args) else rr[key] = val _.each @, extend_to_row extend_to_row(@forEachRow, 'forEachRow') _begin_kuid = rr.getValue('$kuid', false) _end_json = @end_json({"$kuid": "/#{_begin_kuid}"}) rr._afterIterator = (cb, ctxt)-> obj = export_relevant_values: (surv, addl)-> surv.push _.extend({}, _end_json) toJSON: -> _.extend({}, _end_json) cb(obj) if ctxt.includeGroupEnds _toJSON = rr.toJSON rr.clone = ()-> attributes = rr.toJSON2() options = _parent: rr._parent add: false merge: false remove: false silent: true r2 = new row.Row(attributes, options) r2._isCloned = true if rr._rankRows # if rr is a rank question for rankRow in rr._rankRows.models r2._rankRows.add(rankRow.toJSON()) r2._rankLevels = rr.getSurvey().choices.add(name: $utils.txtid()) for item in rr.getList().options.models r2._rankLevels.options.add(item.toJSON()) r2.set('kobo--rank-items', r2._rankLevels.get('name')) @convertAttributesToRowDetails() r2.get('type').set('list', r2._rankLevels) else # if rr is a score question for scoreRow in rr._scoreRows.models r2._scoreRows.add(scoreRow.toJSON()) r2._scoreChoices = rr.getSurvey().choices.add(name: $utils.txtid()) for item in rr.getList().options.models r2._scoreChoices.options.add(item.toJSON()) r2.set('kobo--score-choices', r2._scoreChoices.get('name')) @convertAttributesToRowDetails() r2.get('type').set('list', r2._scoreChoices) r2 rr.toJSON = ()-> _.extend _toJSON.call(rr), { 'type': "begin_#{rr._beginEndKey()}" }, @_additionalJson?() _.each @constructor.prototype, extend_to_row if rr.attributes.__rows for subrow in rr.attributes.__rows @[@_rowAttributeName].add(subrow) delete rr.attributes.__rows getValue: (which)-> @get(which) end_json: (mrg={})-> _.extend({type: "end_#{@_beginEndKey()}"}, mrg) forEachRow: (cb, ctx)-> cb(@) @[@_rowAttributeName].each (subrow)-> cb(subrow) @_afterIterator(cb, ctx) if '_afterIterator' of @ class RankRows extends Backbone.Collection model: RankRow class RankMixin extends ScoreRankMixin constructor: (rr)-> @_rankRows = new RankRows() @_rowAttributeName = '_rankRows' @_extendAll(rr) rankConstraintMessageKey = 'PI:KEY:<KEY>END_PI' if !rr.get(rankConstraintMessageKey) rr.set(rankConstraintMessageKey, _t("Items cannot be selected more than once")) _beginEndKey: -> 'PI:KEY:<KEY>END_PI' linkUp: (ctx)-> rank_list_id = @get('kobo--rank-items')?.get('value') if rank_list_id @_rankLevels = @getSurvey().choices.get(rank_list_id) else @_rankLevels = @getSurvey().choices.create() @_additionalJson = => 'kobo--rank-items': @getList().get('name') @getList = => @_rankLevels export_relevant_values: (survey_arr, additionalSheets)-> if @_rankLevels additionalSheets['choices'].add(@_rankLevels) begin_xlsformrow = _.clone(@toJSON2()) begin_xlsformrow.type = "begin_rank" begin_xlsformrow['kobo--rank-items'] = @getList().get('name') survey_arr.push(begin_xlsformrow) `` class ScoreChoiceList extends Array class ScoreRow extends SimpleRow initialize: -> @set('type', 'score__row') @simpleEnsureKuid() export_relevant_values: (surv, sheets)-> surv.push(@attributes) class ScoreRows extends Backbone.Collection model: ScoreRow class ScoreMixin extends ScoreRankMixin constructor: (rr)-> @_scoreRows = new ScoreRows() @_rowAttributeName = '_scoreRows' @_extendAll(rr) _beginEndKey: -> 'score' linkUp: (ctx)-> @getList = ()=> @_scoreChoices @_additionalJson = ()=> 'kobo--score-choices': @getList().get('name') score_list_id_item = @get('kobo--score-choices') if score_list_id_item score_list_id = score_list_id_item.get('value') if score_list_id @_scoreChoices = @getSurvey().choices.get(score_list_id) else ctx.warnings.push "Score choices list not found" @_scoreChoices = @getSurvey().choices.add({}) else ctx.warnings.push "Score choices list not set" @_scoreChoices = @getSurvey().choices.add(name: $utils.txtid()) `` export_relevant_values: (survey_arr, additionalSheets)-> score_list = @_scoreChoices if score_list additionalSheets['choices'].add(score_list) output = _.clone(@toJSON2()) output.type = "begin_score" output['kobo--score-choices'] = @getList().get('name') survey_arr.push(output) `` class row.Row extends row.BaseRow @kls = "Row" initialize: -> ### The best way to understand the @details collection is that it is a list of cells of the XLSForm spreadsheet. The column name is the "key" and the value is the "value". We opted for a collection (rather than just saving in the attributes of this model) because of the various state-related attributes that need to be saved for each cell and this allows more room to grow. E.g.: {"key": "type", "value": "select_one colors"} needs to keep track of how the value was built ### if @_parent defaultsUnlessDefined = @_parent.newRowDetails || $configs.newRowDetails defaultsForType = @_parent.defaultsForType || $configs.defaultsForType else console?.error "Row not linked to parent survey." defaultsUnlessDefined = $configs.newRowDetails defaultsForType = $configs.defaultsForType if @attributes.type and @attributes.type of defaultsForType curTypeDefaults = defaultsForType[@attributes.type] else curTypeDefaults = {} defaults = _.extend {}, defaultsUnlessDefined, curTypeDefaults for key, vals of defaults unless key of @attributes newVals = {} for vk, vv of vals newVals[vk] = if ("function" is typeof vv) then vv() else vv @set key, newVals if '$kuid' not of @attributes @set '$kuid', $utils.txtid() _type = @getValue('type') if _type is 'score' new ScoreMixin(@) else if _type is 'rank' new RankMixin(@) @convertAttributesToRowDetails() typeDetail = @get("type") tpVal = typeDetail.get("value") select_from_list_name = @get("select_from_list_name") if select_from_list_name and tpVal tpVal = "#{tpVal} #{select_from_list_name.get('value')}" typeDetail.set("value", tpVal, silent: true) processType = (rd, newType, ctxt)=> # if value changes, it could be set from an initialization value # or it could be changed elsewhere. # we need to keep typeId, listName, and orOther in sync. if _.isObject(newType) tpid = _.keys(newType)[0] p2 = _.values(newType)[0] else [tpid, p2, p3] = newType.split(" ") typeDetail.set("typeId", tpid, silent: true) if p2 typeDetail.set("listName", p2, silent: true) matchedList = @getSurvey().choices.get(p2) if matchedList typeDetail.set("list", matchedList) if p3 is "or_other" or tpid in ["select_one_or_other", "select_multiple_or_other"] typeDetail.set("orOther", p3, silent: true) if (rtp = $configs.lookupRowType(tpid)) typeDetail.set("rowType", rtp, silent: true) else throw new Error "type `#{tpid}` not found" processType(typeDetail, tpVal, {}) typeDetail.on "change:value", processType typeDetail.on "change:listName", (rd, listName, ctx)-> rtp = typeDetail.get("rowType") typeStr = "#{typeDetail.get("typeId")}" if rtp.specifyChoice and listName typeStr += " #{listName}" if rtp.orOtherOption and typeDetail.get("orOther") typeStr += " or_other" typeDetail.set({value: typeStr}, silent: true) typeDetail.on "change:list", (rd, cl, ctx)-> if typeDetail.get("rowType").specifyChoice clname = cl.get("name") unless clname clname = $utils.txtid() cl.set("name", clname, silent: true) @set("value", "#{@get('typeId')} #{clname}") getTypeId: -> @get('type').get('typeId') clone: -> attributes = {} options = _parent: @_parent add: false merge: false remove: false silent: true _.each @attributes, (value, key) => attributes[key] = @getValue key newRow = new row.Row attributes, options newRowType = newRow.get('type') if newRowType.get('typeId') in ['select_one', 'select_multiple'] newRowType.set 'list', @getList().clone() newRowType.set 'listName', newRowType.get('list').get 'name' @getSurvey().trigger('change') return newRow finalize: -> existing_name = @getValue("name") unless existing_name names = [] @getSurvey().forEachRow (r)-> name = r.getValue("name") names.push(name) if name label = @getValue("label") @get("name").set("value", $utils.sluggifyLabel(label, names)) @ get_type: -> $skipLogicHelpers.question_types[@getTypeId()] || $skipLogicHelpers.question_types['default'] _isSelectQuestion: -> # TODO [ald]: pull this from $aliases @get('type').get('typeId') in ['select_one', 'select_multiple'] getAcceptedFiles: -> return @attributes['body::accept']?.attributes?.value setAcceptedFiles: (bodyAcceptString) -> @setDetail('body::accept', bodyAcceptString) return getParameters: -> readParameters(@attributes.parameters?.attributes?.value) setParameters: (paramObject) -> paramString = writeParameters(paramObject) @setDetail('parameters', paramString) return getList: -> _list = @get('type')?.get('list') if (not _list) and @_isSelectQuestion() _list = new $choices.ChoiceList(name: $utils.txtid()) @setList(_list) _list setList: (list)-> listToSet = @getSurvey().choices.get(list) unless listToSet @getSurvey().choices.add(list) listToSet = @getSurvey().choices.get(list) throw new Error("List not found: #{list}") unless listToSet @get("type").set("list", listToSet) parse: -> val.parse() for key, val of @attributes linkUp: (ctx)-> val.linkUp(ctx) for key, val of @attributes class row.RowError extends row.BaseRow constructor: (obj, options)-> @_error = options.error unless window.xlfHideWarnings console?.error("Error creating row: [#{options.error}]", obj) alertify.error("Error creating row: [#{options.error}]"); super(obj, options) isError: -> true getValue: (what)-> if what of @attributes @attributes[what].get('value') else "[error]" row
[ { "context": "tframes-toback.coffee\n\n // Copyright (c) 2013\n // Fabian \"fabiantheblind\" Morรณn Zirfas\n // Permission is h", "end": 70, "score": 0.9998534321784973, "start": 64, "tag": "NAME", "value": "Fabian" }, { "context": "oback.coffee\n\n // Copyright (c) 2013\n // Fabian \"fabiantheblind\" Morรณn Zirfas\n // Permission is hereby granted, f", "end": 86, "score": 0.9989681243896484, "start": 72, "tag": "USERNAME", "value": "fabiantheblind" }, { "context": "// Copyright (c) 2013\n // Fabian \"fabiantheblind\" Morรณn Zirfas\n // Permission is hereby granted, free of charge,", "end": 100, "score": 0.9998668432235718, "start": 88, "tag": "NAME", "value": "Morรณn Zirfas" }, { "context": "mit-license.php\n\n###\n\n###\n Taken from ScriptUI by Peter Kahrel\n @usage\n var progress_win = new Window (\"palett", "end": 1303, "score": 0.9997528195381165, "start": 1291, "tag": "NAME", "value": "Peter Kahrel" } ]
_dev/coffee/move-textframes-to-back.coffee
fabianmoronzirfas/mpo-id-tools
2
### move-textframes-toback.coffee // Copyright (c) 2013 // Fabian "fabiantheblind" Morรณn Zirfas // 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 CONNECTIO // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // see also http://www.opensource.org/licenses/mit-license.php ### ### Taken from ScriptUI by Peter Kahrel @usage var progress_win = new Window ("palette"); var progress = progress_bar(progress_win, 100, 'my Progress'); progress.value = i++; progress.parent.close(); #important close it!! @param {Palette} w the palette the progress is shown on @param {Number} stop [description] @return {Progressbar} [description] ### pbar = (w, stop, labeltext) -> txt = w.add('statictext',undefined,labeltext) pbar = w.add("progressbar", undefined, 1, stop) pbar.preferredSize = [300,20] w.show() return pbar main = -> # get the doc doc = app.activeDocument # check if the doc is there if doc == null alert "no document" return # get the actie page pg = doc.layoutWindows[0].activePage # get all apgeitems items = pg.pageItems # loop the items progress_win = new Window ("palette") progress = pbar(progress_win, items.length, 'Moving Text to the back') for i in [0..items.length] by 1 item = items[i] # isolate # check if we have an TextFrame if so send to back try item.sendToBack() if item.getElements()[0] instanceof TextFrame catch e progress.value = i++ progress.parent.close() # close the progress bar do main
212729
### move-textframes-toback.coffee // Copyright (c) 2013 // <NAME> "fabiantheblind" <NAME> // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to // whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice // shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTIO // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // see also http://www.opensource.org/licenses/mit-license.php ### ### Taken from ScriptUI by <NAME> @usage var progress_win = new Window ("palette"); var progress = progress_bar(progress_win, 100, 'my Progress'); progress.value = i++; progress.parent.close(); #important close it!! @param {Palette} w the palette the progress is shown on @param {Number} stop [description] @return {Progressbar} [description] ### pbar = (w, stop, labeltext) -> txt = w.add('statictext',undefined,labeltext) pbar = w.add("progressbar", undefined, 1, stop) pbar.preferredSize = [300,20] w.show() return pbar main = -> # get the doc doc = app.activeDocument # check if the doc is there if doc == null alert "no document" return # get the actie page pg = doc.layoutWindows[0].activePage # get all apgeitems items = pg.pageItems # loop the items progress_win = new Window ("palette") progress = pbar(progress_win, items.length, 'Moving Text to the back') for i in [0..items.length] by 1 item = items[i] # isolate # check if we have an TextFrame if so send to back try item.sendToBack() if item.getElements()[0] instanceof TextFrame catch e progress.value = i++ progress.parent.close() # close the progress bar do main
true
### move-textframes-toback.coffee // Copyright (c) 2013 // PI:NAME:<NAME>END_PI "fabiantheblind" PI:NAME:<NAME>END_PI // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to // whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice // shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTIO // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // see also http://www.opensource.org/licenses/mit-license.php ### ### Taken from ScriptUI by PI:NAME:<NAME>END_PI @usage var progress_win = new Window ("palette"); var progress = progress_bar(progress_win, 100, 'my Progress'); progress.value = i++; progress.parent.close(); #important close it!! @param {Palette} w the palette the progress is shown on @param {Number} stop [description] @return {Progressbar} [description] ### pbar = (w, stop, labeltext) -> txt = w.add('statictext',undefined,labeltext) pbar = w.add("progressbar", undefined, 1, stop) pbar.preferredSize = [300,20] w.show() return pbar main = -> # get the doc doc = app.activeDocument # check if the doc is there if doc == null alert "no document" return # get the actie page pg = doc.layoutWindows[0].activePage # get all apgeitems items = pg.pageItems # loop the items progress_win = new Window ("palette") progress = pbar(progress_win, items.length, 'Moving Text to the back') for i in [0..items.length] by 1 item = items[i] # isolate # check if we have an TextFrame if so send to back try item.sendToBack() if item.getElements()[0] instanceof TextFrame catch e progress.value = i++ progress.parent.close() # close the progress bar do main
[ { "context": "ners.push({\n userID: user._id\n name: user.name\n email: user.email\n firstName: user", "end": 827, "score": 0.9393222332000732, "start": 818, "tag": "NAME", "value": "user.name" }, { "context": "ncat _.assign({ userID: me.id }, me.pick('name', 'firstName', 'lastName', 'email'))\n _.assign({}, state.", "end": 1943, "score": 0.9731375575065613, "start": 1934, "tag": "NAME", "value": "firstName" }, { "context": "({ userID: me.id }, me.pick('name', 'firstName', 'lastName', 'email'))\n _.assign({}, state._prepaid, {\n", "end": 1955, "score": 0.968041181564331, "start": 1947, "tag": "NAME", "value": "lastName" } ]
app/views/teachers/ShareLicensesStoreModule.coffee
mcgilvrayb/codecombat
0
api = require 'core/api' initialState = { _prepaid: { joiners: [] } error: '' } translateError = (error) -> if error.i18n return i18n.t(error.i18n) else if error.errorID is 'no-user-with-that-email' return i18n.t('share_licenses.teacher_not_found') else if error.errorID is 'cant-fetch-nonteacher-by-email' return i18n.t('share_licenses.teacher_not_valid') else return error.message or error module.exports = ShareLicensesStoreModule = namespaced: true state: _.cloneDeep(initialState) mutations: # NOTE: Ideally, this store should fetch the prepaid, but we're already handed it by the Backbone parent setPrepaid: (state, prepaid) -> state._prepaid = prepaid addTeacher: (state, user) -> state._prepaid.joiners.push({ userID: user._id name: user.name email: user.email firstName: user.firstName lastName: user.lastName }) setError: (state, error) -> state.error = error clearData: (state) -> _.assign state, initialState actions: setPrepaid: ({ commit }, prepaid) -> prepaid = _.cloneDeep(prepaid) prepaid.joiners ?= [] api.prepaids.fetchJoiners({ prepaidID: prepaid._id }).then (joiners) -> prepaid.joiners.forEach (slimJoiner) -> fullJoiner = _.find(joiners, {_id: slimJoiner.userID}) _.assign(slimJoiner, fullJoiner) .then -> commit('setPrepaid', prepaid) addTeacher: ({ commit, state }, email) -> return if _.isEmpty(email) api.users.getByEmail(email).then (user) => api.prepaids.addJoiner({prepaidID: state._prepaid._id, userID: user._id}).then => commit('addTeacher', user) .catch (error) => commit('setError', translateError(error.responseJSON or error)) getters: prepaid: (state) -> joinersAndMe = state._prepaid.joiners.concat _.assign({ userID: me.id }, me.pick('name', 'firstName', 'lastName', 'email')) _.assign({}, state._prepaid, { joiners: joinersAndMe.map((joiner) -> _.assign {}, joiner, licensesUsed: _.countBy(state._prepaid.redeemers, (redeemer) -> (not redeemer.teacherID and joiner.userID is me.id) or (redeemer.teacherID is joiner.userID) )[true] or 0 ).reverse() }) rawJoiners: (state) -> state._prepaid.joiners.map (joiner) -> _.pick(joiner, 'userID') error: (state) -> state.error
146286
api = require 'core/api' initialState = { _prepaid: { joiners: [] } error: '' } translateError = (error) -> if error.i18n return i18n.t(error.i18n) else if error.errorID is 'no-user-with-that-email' return i18n.t('share_licenses.teacher_not_found') else if error.errorID is 'cant-fetch-nonteacher-by-email' return i18n.t('share_licenses.teacher_not_valid') else return error.message or error module.exports = ShareLicensesStoreModule = namespaced: true state: _.cloneDeep(initialState) mutations: # NOTE: Ideally, this store should fetch the prepaid, but we're already handed it by the Backbone parent setPrepaid: (state, prepaid) -> state._prepaid = prepaid addTeacher: (state, user) -> state._prepaid.joiners.push({ userID: user._id name: <NAME> email: user.email firstName: user.firstName lastName: user.lastName }) setError: (state, error) -> state.error = error clearData: (state) -> _.assign state, initialState actions: setPrepaid: ({ commit }, prepaid) -> prepaid = _.cloneDeep(prepaid) prepaid.joiners ?= [] api.prepaids.fetchJoiners({ prepaidID: prepaid._id }).then (joiners) -> prepaid.joiners.forEach (slimJoiner) -> fullJoiner = _.find(joiners, {_id: slimJoiner.userID}) _.assign(slimJoiner, fullJoiner) .then -> commit('setPrepaid', prepaid) addTeacher: ({ commit, state }, email) -> return if _.isEmpty(email) api.users.getByEmail(email).then (user) => api.prepaids.addJoiner({prepaidID: state._prepaid._id, userID: user._id}).then => commit('addTeacher', user) .catch (error) => commit('setError', translateError(error.responseJSON or error)) getters: prepaid: (state) -> joinersAndMe = state._prepaid.joiners.concat _.assign({ userID: me.id }, me.pick('name', '<NAME>', '<NAME>', 'email')) _.assign({}, state._prepaid, { joiners: joinersAndMe.map((joiner) -> _.assign {}, joiner, licensesUsed: _.countBy(state._prepaid.redeemers, (redeemer) -> (not redeemer.teacherID and joiner.userID is me.id) or (redeemer.teacherID is joiner.userID) )[true] or 0 ).reverse() }) rawJoiners: (state) -> state._prepaid.joiners.map (joiner) -> _.pick(joiner, 'userID') error: (state) -> state.error
true
api = require 'core/api' initialState = { _prepaid: { joiners: [] } error: '' } translateError = (error) -> if error.i18n return i18n.t(error.i18n) else if error.errorID is 'no-user-with-that-email' return i18n.t('share_licenses.teacher_not_found') else if error.errorID is 'cant-fetch-nonteacher-by-email' return i18n.t('share_licenses.teacher_not_valid') else return error.message or error module.exports = ShareLicensesStoreModule = namespaced: true state: _.cloneDeep(initialState) mutations: # NOTE: Ideally, this store should fetch the prepaid, but we're already handed it by the Backbone parent setPrepaid: (state, prepaid) -> state._prepaid = prepaid addTeacher: (state, user) -> state._prepaid.joiners.push({ userID: user._id name: PI:NAME:<NAME>END_PI email: user.email firstName: user.firstName lastName: user.lastName }) setError: (state, error) -> state.error = error clearData: (state) -> _.assign state, initialState actions: setPrepaid: ({ commit }, prepaid) -> prepaid = _.cloneDeep(prepaid) prepaid.joiners ?= [] api.prepaids.fetchJoiners({ prepaidID: prepaid._id }).then (joiners) -> prepaid.joiners.forEach (slimJoiner) -> fullJoiner = _.find(joiners, {_id: slimJoiner.userID}) _.assign(slimJoiner, fullJoiner) .then -> commit('setPrepaid', prepaid) addTeacher: ({ commit, state }, email) -> return if _.isEmpty(email) api.users.getByEmail(email).then (user) => api.prepaids.addJoiner({prepaidID: state._prepaid._id, userID: user._id}).then => commit('addTeacher', user) .catch (error) => commit('setError', translateError(error.responseJSON or error)) getters: prepaid: (state) -> joinersAndMe = state._prepaid.joiners.concat _.assign({ userID: me.id }, me.pick('name', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'email')) _.assign({}, state._prepaid, { joiners: joinersAndMe.map((joiner) -> _.assign {}, joiner, licensesUsed: _.countBy(state._prepaid.redeemers, (redeemer) -> (not redeemer.teacherID and joiner.userID is me.id) or (redeemer.teacherID is joiner.userID) )[true] or 0 ).reverse() }) rawJoiners: (state) -> state._prepaid.joiners.map (joiner) -> _.pick(joiner, 'userID') error: (state) -> state.error
[ { "context": "uth.method isnt 'password' || auth.username isnt \"brady\" || auth.password isnt \"test\"\n return auth.rej", "end": 222, "score": 0.9995355606079102, "start": 217, "tag": "USERNAME", "value": "brady" }, { "context": "auth.username isnt \"brady\" || auth.password isnt \"test\"\n return auth.reject() # forcing a short-circu", "end": 251, "score": 0.999537467956543, "start": 247, "tag": "PASSWORD", "value": "test" }, { "context": " haven't *outhright* accepted yet...\"\n\n username=auth.username\n password=auth.password\n other_session_stuff=\"w", "end": 440, "score": 0.9971415996551514, "start": 427, "tag": "USERNAME", "value": "auth.username" }, { "context": "pted yet...\"\n\n username=auth.username\n password=auth.password\n other_session_stuff=\"whatever\"\n auth.accept (s", "end": 465, "score": 0.9991244673728943, "start": 452, "tag": "PASSWORD", "value": "auth.password" } ]
node_modules/node-sftp-server/server_example.coffee
Drimpac2020eu/DRIMPAC_REST_API
0
fs=require 'fs' SFTPServer=require "./wrapper" srv=new SFTPServer() srv.listen(8022) srv.on "connect", (auth) -> console.warn "authentication attempted" if auth.method isnt 'password' || auth.username isnt "brady" || auth.password isnt "test" return auth.reject() # forcing a short-circuit here is weird, but you could just as easily do if/else console.warn "We haven't *outhright* accepted yet..." username=auth.username password=auth.password other_session_stuff="whatever" auth.accept (session) -> #begin_session (auth.username,auth.password,session) console.warn "Okay, we've accepted, allegedly?" session.on "readdir", (path,responder) -> # do all prepration work to read a directory console.warn "Readdir request for path: #{path}" dirs=[1...10000] i=0 responder.on "dir", () -> if dirs[i] console.warn "Returning directory: #{dirs[i]}" responder.file(dirs[i]) i++ else responder.end() # should be 'end'? responder.on "end", -> console.warn "Now I would normally do, like, cleanup stuff, for this directory listing" session.on "readfile", (path,writestream) -> # something=fs.createReadStream "/tmp/grumple.txt" # something.pipe(writestream) fs.createReadStream("/tmp/grumple.txt").pipe(writestream) #writestream.end("THE END OF THIS") #req(something) # no? session.on "writefile", (path,readstream) -> something=fs.createWriteStream "/tmp/garbage" readstream.pipe(something) # Don't know where this goes? srv.on "end", () -> console.warn "Example says user disconnected" #sometihng #srv.on "session", (authblob,session) -> # console.warn "Hey, session started! You're logged in as BLAH..." # begin_session = (username,password,session) ->
40601
fs=require 'fs' SFTPServer=require "./wrapper" srv=new SFTPServer() srv.listen(8022) srv.on "connect", (auth) -> console.warn "authentication attempted" if auth.method isnt 'password' || auth.username isnt "brady" || auth.password isnt "<PASSWORD>" return auth.reject() # forcing a short-circuit here is weird, but you could just as easily do if/else console.warn "We haven't *outhright* accepted yet..." username=auth.username password=<PASSWORD> other_session_stuff="whatever" auth.accept (session) -> #begin_session (auth.username,auth.password,session) console.warn "Okay, we've accepted, allegedly?" session.on "readdir", (path,responder) -> # do all prepration work to read a directory console.warn "Readdir request for path: #{path}" dirs=[1...10000] i=0 responder.on "dir", () -> if dirs[i] console.warn "Returning directory: #{dirs[i]}" responder.file(dirs[i]) i++ else responder.end() # should be 'end'? responder.on "end", -> console.warn "Now I would normally do, like, cleanup stuff, for this directory listing" session.on "readfile", (path,writestream) -> # something=fs.createReadStream "/tmp/grumple.txt" # something.pipe(writestream) fs.createReadStream("/tmp/grumple.txt").pipe(writestream) #writestream.end("THE END OF THIS") #req(something) # no? session.on "writefile", (path,readstream) -> something=fs.createWriteStream "/tmp/garbage" readstream.pipe(something) # Don't know where this goes? srv.on "end", () -> console.warn "Example says user disconnected" #sometihng #srv.on "session", (authblob,session) -> # console.warn "Hey, session started! You're logged in as BLAH..." # begin_session = (username,password,session) ->
true
fs=require 'fs' SFTPServer=require "./wrapper" srv=new SFTPServer() srv.listen(8022) srv.on "connect", (auth) -> console.warn "authentication attempted" if auth.method isnt 'password' || auth.username isnt "brady" || auth.password isnt "PI:PASSWORD:<PASSWORD>END_PI" return auth.reject() # forcing a short-circuit here is weird, but you could just as easily do if/else console.warn "We haven't *outhright* accepted yet..." username=auth.username password=PI:PASSWORD:<PASSWORD>END_PI other_session_stuff="whatever" auth.accept (session) -> #begin_session (auth.username,auth.password,session) console.warn "Okay, we've accepted, allegedly?" session.on "readdir", (path,responder) -> # do all prepration work to read a directory console.warn "Readdir request for path: #{path}" dirs=[1...10000] i=0 responder.on "dir", () -> if dirs[i] console.warn "Returning directory: #{dirs[i]}" responder.file(dirs[i]) i++ else responder.end() # should be 'end'? responder.on "end", -> console.warn "Now I would normally do, like, cleanup stuff, for this directory listing" session.on "readfile", (path,writestream) -> # something=fs.createReadStream "/tmp/grumple.txt" # something.pipe(writestream) fs.createReadStream("/tmp/grumple.txt").pipe(writestream) #writestream.end("THE END OF THIS") #req(something) # no? session.on "writefile", (path,readstream) -> something=fs.createWriteStream "/tmp/garbage" readstream.pipe(something) # Don't know where this goes? srv.on "end", () -> console.warn "Example says user disconnected" #sometihng #srv.on "session", (authblob,session) -> # console.warn "Hey, session started! You're logged in as BLAH..." # begin_session = (username,password,session) ->
[ { "context": "In-browser CoffeeScript REPL\n# https://github.com/larryng/coffeescript-repl\n# \n# written by Larry Ng\n\nrequi", "end": 59, "score": 0.9996258020401001, "start": 52, "tag": "USERNAME", "value": "larryng" }, { "context": "thub.com/larryng/coffeescript-repl\n# \n# written by Larry Ng\n\nrequire ['jquery', 'coffee-script', 'nodeutil'],", "end": 102, "score": 0.9998049736022949, "start": 94, "tag": "NAME", "value": "Larry Ng" }, { "context": "ON} REPL\"\n \"# <a href=\\\"https://github.com/larryng/coffeescript-repl\\\" target=\\\"_blank\\\">https://git", "end": 6709, "score": 0.999247133731842, "start": 6702, "tag": "USERNAME", "value": "larryng" }, { "context": "cript-repl\\\" target=\\\"_blank\\\">https://github.com/larryng/coffeescript-repl</a>\"\n \"#\"\n \"# hel", "end": 6774, "score": 0.9992228746414185, "start": 6767, "tag": "USERNAME", "value": "larryng" } ]
coffee/main.coffee
zhandao/coffeescript-repl
28
# In-browser CoffeeScript REPL # https://github.com/larryng/coffeescript-repl # # written by Larry Ng require ['jquery', 'coffee-script', 'nodeutil'], ($, CoffeeScript, nodeutil) -> $ -> SAVED_CONSOLE_LOG = console.log $output = $('#output') $input = $('#input') $prompt = $('#prompt') $inputdiv = $('#inputdiv') $inputl = $('#inputl') $inputr = $('#inputr') $inputcopy = $('#inputcopy') escapeHTML = (s) -> s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); class CoffeeREPL DEFAULT_SETTINGS = lastVariable: '$_' maxLines: 500 maxDepth: 2 showHidden: false colorize: true constructor: (@output, @input, @prompt, settings={}) -> @history = [] @historyi = -1 @saved = '' @multiline = false @settings = $.extend({}, DEFAULT_SETTINGS) if localStorage and localStorage.settings for k, v of JSON.parse(localStorage.settings) @settings[k] = v for k, v of settings @settings[k] = v @input.keydown @handleKeypress resetSettings: -> localStorage.clear() saveSettings: -> localStorage.settings = JSON.stringify($.extend({}, @settings)) print: (args...) => s = args.join(' ') or ' ' o = @output[0].innerHTML + s + '\n' @output[0].innerHTML = o.split('\n')[-@settings.maxLines...].join('\n') undefined processSaved: => try compiled = CoffeeScript.compile @saved compiled = compiled[14...-17] value = eval.call window, compiled window[@settings.lastVariable] = value output = nodeutil.inspect value, @settings.showHidden, @settings.maxDepth, @settings.colorize catch e if e.stack output = e.stack # FF doesn't have Error.toString() as the first line of Error.stack # while Chrome does. if output.split('\n')[0] isnt e.toString() ouput = "#{e.toString()}\n#{e.stack}" else output = e.toString() @saved = '' @print output setPrompt: => s = if @multiline then '------' else 'coffee' @prompt.html "#{s}&gt;&nbsp;" addToHistory: (s) => @history.unshift s @historyi = -1 addToSaved: (s) => @saved += if s[...-1] is '\\' then s[0...-1] else s @saved += '\n' @addToHistory s clear: => @output[0].innerHTML = '' undefined handleKeypress: (e) => switch e.which when 13 e.preventDefault() input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) if input @addToSaved input if input[...-1] isnt '\\' and not @multiline @processSaved() when 27 e.preventDefault() input = @input.val() if input and @multiline and @saved input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) @addToSaved input @processSaved() else if @multiline and @saved @processSaved() @multiline = not @multiline @setPrompt() when 38 e.preventDefault() if @historyi < @history.length-1 @historyi += 1 @input.val @history[@historyi] when 40 e.preventDefault() if @historyi > 0 @historyi += -1 @input.val @history[@historyi] resizeInput = (e) -> width = $inputdiv.width() - $inputl.width() content = $input.val() content.replace /\n/g, '<br/>' $inputcopy.html content $inputcopy.width width $input.width width $input.height $inputcopy.height() + 2 scrollToBottom = -> window.scrollTo 0, $prompt[0].offsetTop init = -> # bind other handlers $input.keydown scrollToBottom $(window).resize resizeInput $input.keyup resizeInput $input.change resizeInput $('html').click (e) -> if e.clientY > $input[0].offsetTop $input.focus() # instantiate our REPL repl = new CoffeeREPL $output, $input, $prompt # replace console.log console.log = (args...) -> SAVED_CONSOLE_LOG.apply console, args repl.print args... # expose repl as $$ window.$$ = repl # initialize window resizeInput() $input.focus() # help window.help = -> text = [ " " "<strong>Features</strong>" "<strong>========</strong>" "+ <strong>Esc</strong> toggles multiline mode." "+ <strong>Up/Down arrow</strong> flips through line history." "+ <strong>#{repl.settings.lastVariable}</strong> stores the last returned value." "+ Access the internals of this console through <strong>$$</strong>." "+ <strong>$$.clear()</strong> clears this console." " " "<strong>Settings</strong>" "<strong>========</strong>" "You can modify the behavior of this REPL by altering <strong>$$.settings</strong>:" " " "+ <strong>lastVariable</strong> (#{repl.settings.lastVariable}): variable name in which last returned value is stored" "+ <strong>maxLines</strong> (#{repl.settings.maxLines}): max line count of this console" "+ <strong>maxDepth</strong> (#{repl.settings.maxDepth}): max depth in which to inspect outputted object" "+ <strong>showHidden</strong> (#{repl.settings.showHidden}): flag to output hidden (not enumerable) properties of objects" "+ <strong>colorize</strong> (#{repl.settings.colorize}): flag to colorize output (set to false if REPL is slow)" " " "<strong>$$.saveSettings()</strong> will save settings to localStorage." "<strong>$$.resetSettings()</strong> will reset settings to default." " " ].join('\n') repl.print text # print header repl.print [ "# CoffeeScript v#{CoffeeScript.VERSION} REPL" "# <a href=\"https://github.com/larryng/coffeescript-repl\" target=\"_blank\">https://github.com/larryng/coffeescript-repl</a>" "#" "# help() for features and tips." " " ].join('\n') init()
176096
# In-browser CoffeeScript REPL # https://github.com/larryng/coffeescript-repl # # written by <NAME> require ['jquery', 'coffee-script', 'nodeutil'], ($, CoffeeScript, nodeutil) -> $ -> SAVED_CONSOLE_LOG = console.log $output = $('#output') $input = $('#input') $prompt = $('#prompt') $inputdiv = $('#inputdiv') $inputl = $('#inputl') $inputr = $('#inputr') $inputcopy = $('#inputcopy') escapeHTML = (s) -> s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); class CoffeeREPL DEFAULT_SETTINGS = lastVariable: '$_' maxLines: 500 maxDepth: 2 showHidden: false colorize: true constructor: (@output, @input, @prompt, settings={}) -> @history = [] @historyi = -1 @saved = '' @multiline = false @settings = $.extend({}, DEFAULT_SETTINGS) if localStorage and localStorage.settings for k, v of JSON.parse(localStorage.settings) @settings[k] = v for k, v of settings @settings[k] = v @input.keydown @handleKeypress resetSettings: -> localStorage.clear() saveSettings: -> localStorage.settings = JSON.stringify($.extend({}, @settings)) print: (args...) => s = args.join(' ') or ' ' o = @output[0].innerHTML + s + '\n' @output[0].innerHTML = o.split('\n')[-@settings.maxLines...].join('\n') undefined processSaved: => try compiled = CoffeeScript.compile @saved compiled = compiled[14...-17] value = eval.call window, compiled window[@settings.lastVariable] = value output = nodeutil.inspect value, @settings.showHidden, @settings.maxDepth, @settings.colorize catch e if e.stack output = e.stack # FF doesn't have Error.toString() as the first line of Error.stack # while Chrome does. if output.split('\n')[0] isnt e.toString() ouput = "#{e.toString()}\n#{e.stack}" else output = e.toString() @saved = '' @print output setPrompt: => s = if @multiline then '------' else 'coffee' @prompt.html "#{s}&gt;&nbsp;" addToHistory: (s) => @history.unshift s @historyi = -1 addToSaved: (s) => @saved += if s[...-1] is '\\' then s[0...-1] else s @saved += '\n' @addToHistory s clear: => @output[0].innerHTML = '' undefined handleKeypress: (e) => switch e.which when 13 e.preventDefault() input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) if input @addToSaved input if input[...-1] isnt '\\' and not @multiline @processSaved() when 27 e.preventDefault() input = @input.val() if input and @multiline and @saved input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) @addToSaved input @processSaved() else if @multiline and @saved @processSaved() @multiline = not @multiline @setPrompt() when 38 e.preventDefault() if @historyi < @history.length-1 @historyi += 1 @input.val @history[@historyi] when 40 e.preventDefault() if @historyi > 0 @historyi += -1 @input.val @history[@historyi] resizeInput = (e) -> width = $inputdiv.width() - $inputl.width() content = $input.val() content.replace /\n/g, '<br/>' $inputcopy.html content $inputcopy.width width $input.width width $input.height $inputcopy.height() + 2 scrollToBottom = -> window.scrollTo 0, $prompt[0].offsetTop init = -> # bind other handlers $input.keydown scrollToBottom $(window).resize resizeInput $input.keyup resizeInput $input.change resizeInput $('html').click (e) -> if e.clientY > $input[0].offsetTop $input.focus() # instantiate our REPL repl = new CoffeeREPL $output, $input, $prompt # replace console.log console.log = (args...) -> SAVED_CONSOLE_LOG.apply console, args repl.print args... # expose repl as $$ window.$$ = repl # initialize window resizeInput() $input.focus() # help window.help = -> text = [ " " "<strong>Features</strong>" "<strong>========</strong>" "+ <strong>Esc</strong> toggles multiline mode." "+ <strong>Up/Down arrow</strong> flips through line history." "+ <strong>#{repl.settings.lastVariable}</strong> stores the last returned value." "+ Access the internals of this console through <strong>$$</strong>." "+ <strong>$$.clear()</strong> clears this console." " " "<strong>Settings</strong>" "<strong>========</strong>" "You can modify the behavior of this REPL by altering <strong>$$.settings</strong>:" " " "+ <strong>lastVariable</strong> (#{repl.settings.lastVariable}): variable name in which last returned value is stored" "+ <strong>maxLines</strong> (#{repl.settings.maxLines}): max line count of this console" "+ <strong>maxDepth</strong> (#{repl.settings.maxDepth}): max depth in which to inspect outputted object" "+ <strong>showHidden</strong> (#{repl.settings.showHidden}): flag to output hidden (not enumerable) properties of objects" "+ <strong>colorize</strong> (#{repl.settings.colorize}): flag to colorize output (set to false if REPL is slow)" " " "<strong>$$.saveSettings()</strong> will save settings to localStorage." "<strong>$$.resetSettings()</strong> will reset settings to default." " " ].join('\n') repl.print text # print header repl.print [ "# CoffeeScript v#{CoffeeScript.VERSION} REPL" "# <a href=\"https://github.com/larryng/coffeescript-repl\" target=\"_blank\">https://github.com/larryng/coffeescript-repl</a>" "#" "# help() for features and tips." " " ].join('\n') init()
true
# In-browser CoffeeScript REPL # https://github.com/larryng/coffeescript-repl # # written by PI:NAME:<NAME>END_PI require ['jquery', 'coffee-script', 'nodeutil'], ($, CoffeeScript, nodeutil) -> $ -> SAVED_CONSOLE_LOG = console.log $output = $('#output') $input = $('#input') $prompt = $('#prompt') $inputdiv = $('#inputdiv') $inputl = $('#inputl') $inputr = $('#inputr') $inputcopy = $('#inputcopy') escapeHTML = (s) -> s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); class CoffeeREPL DEFAULT_SETTINGS = lastVariable: '$_' maxLines: 500 maxDepth: 2 showHidden: false colorize: true constructor: (@output, @input, @prompt, settings={}) -> @history = [] @historyi = -1 @saved = '' @multiline = false @settings = $.extend({}, DEFAULT_SETTINGS) if localStorage and localStorage.settings for k, v of JSON.parse(localStorage.settings) @settings[k] = v for k, v of settings @settings[k] = v @input.keydown @handleKeypress resetSettings: -> localStorage.clear() saveSettings: -> localStorage.settings = JSON.stringify($.extend({}, @settings)) print: (args...) => s = args.join(' ') or ' ' o = @output[0].innerHTML + s + '\n' @output[0].innerHTML = o.split('\n')[-@settings.maxLines...].join('\n') undefined processSaved: => try compiled = CoffeeScript.compile @saved compiled = compiled[14...-17] value = eval.call window, compiled window[@settings.lastVariable] = value output = nodeutil.inspect value, @settings.showHidden, @settings.maxDepth, @settings.colorize catch e if e.stack output = e.stack # FF doesn't have Error.toString() as the first line of Error.stack # while Chrome does. if output.split('\n')[0] isnt e.toString() ouput = "#{e.toString()}\n#{e.stack}" else output = e.toString() @saved = '' @print output setPrompt: => s = if @multiline then '------' else 'coffee' @prompt.html "#{s}&gt;&nbsp;" addToHistory: (s) => @history.unshift s @historyi = -1 addToSaved: (s) => @saved += if s[...-1] is '\\' then s[0...-1] else s @saved += '\n' @addToHistory s clear: => @output[0].innerHTML = '' undefined handleKeypress: (e) => switch e.which when 13 e.preventDefault() input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) if input @addToSaved input if input[...-1] isnt '\\' and not @multiline @processSaved() when 27 e.preventDefault() input = @input.val() if input and @multiline and @saved input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) @addToSaved input @processSaved() else if @multiline and @saved @processSaved() @multiline = not @multiline @setPrompt() when 38 e.preventDefault() if @historyi < @history.length-1 @historyi += 1 @input.val @history[@historyi] when 40 e.preventDefault() if @historyi > 0 @historyi += -1 @input.val @history[@historyi] resizeInput = (e) -> width = $inputdiv.width() - $inputl.width() content = $input.val() content.replace /\n/g, '<br/>' $inputcopy.html content $inputcopy.width width $input.width width $input.height $inputcopy.height() + 2 scrollToBottom = -> window.scrollTo 0, $prompt[0].offsetTop init = -> # bind other handlers $input.keydown scrollToBottom $(window).resize resizeInput $input.keyup resizeInput $input.change resizeInput $('html').click (e) -> if e.clientY > $input[0].offsetTop $input.focus() # instantiate our REPL repl = new CoffeeREPL $output, $input, $prompt # replace console.log console.log = (args...) -> SAVED_CONSOLE_LOG.apply console, args repl.print args... # expose repl as $$ window.$$ = repl # initialize window resizeInput() $input.focus() # help window.help = -> text = [ " " "<strong>Features</strong>" "<strong>========</strong>" "+ <strong>Esc</strong> toggles multiline mode." "+ <strong>Up/Down arrow</strong> flips through line history." "+ <strong>#{repl.settings.lastVariable}</strong> stores the last returned value." "+ Access the internals of this console through <strong>$$</strong>." "+ <strong>$$.clear()</strong> clears this console." " " "<strong>Settings</strong>" "<strong>========</strong>" "You can modify the behavior of this REPL by altering <strong>$$.settings</strong>:" " " "+ <strong>lastVariable</strong> (#{repl.settings.lastVariable}): variable name in which last returned value is stored" "+ <strong>maxLines</strong> (#{repl.settings.maxLines}): max line count of this console" "+ <strong>maxDepth</strong> (#{repl.settings.maxDepth}): max depth in which to inspect outputted object" "+ <strong>showHidden</strong> (#{repl.settings.showHidden}): flag to output hidden (not enumerable) properties of objects" "+ <strong>colorize</strong> (#{repl.settings.colorize}): flag to colorize output (set to false if REPL is slow)" " " "<strong>$$.saveSettings()</strong> will save settings to localStorage." "<strong>$$.resetSettings()</strong> will reset settings to default." " " ].join('\n') repl.print text # print header repl.print [ "# CoffeeScript v#{CoffeeScript.VERSION} REPL" "# <a href=\"https://github.com/larryng/coffeescript-repl\" target=\"_blank\">https://github.com/larryng/coffeescript-repl</a>" "#" "# help() for features and tips." " " ].join('\n') init()
[ { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 400, "score": 0.9959940314292908, "start": 368, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 884, "score": 0.9960975646972656, "start": 852, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 1335, "score": 0.9971256256103516, "start": 1303, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ge.attachments[0].data.text.should.eql 'Committer: Catalyst Zhang'\n message.attachments[0].data.redirectUrl.sh", "end": 1609, "score": 0.999810516834259, "start": 1595, "tag": "NAME", "value": "Catalyst Zhang" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket'\n .nodeify done\n\n it 'receive ", "end": 1697, "score": 0.9994061589241028, "start": 1691, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 1990, "score": 0.983022928237915, "start": 1958, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/commits/024cb7dc2cea5cc1360dad6531", "end": 2347, "score": 0.998784065246582, "start": 2341, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 2707, "score": 0.9842295050621033, "start": 2675, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1#comment-19446825'\n .nod", "end": 3094, "score": 0.9993884563446045, "start": 3088, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 3406, "score": 0.9887903332710266, "start": 3374, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1/hi-what-is-issue'\n .nod", "end": 3785, "score": 0.9990403056144714, "start": 3779, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 4097, "score": 0.9877110719680786, "start": 4065, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1/hi-what-is-issue'\n .nod", "end": 4483, "score": 0.9990262985229492, "start": 4477, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 4808, "score": 0.9890758991241455, "start": 4776, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1'\n .nodeify done\n", "end": 5172, "score": 0.9995830059051514, "start": 5166, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 5487, "score": 0.9867376089096069, "start": 5455, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1'\n .nodeify done\n", "end": 5851, "score": 0.9995427131652832, "start": 5845, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 6170, "score": 0.9877998232841492, "start": 6138, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1'\n .nodeify done\n", "end": 6521, "score": 0.9995943307876587, "start": 6515, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 6838, "score": 0.9941835999488831, "start": 6806, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/2'\n .nodeify done\n", "end": 7188, "score": 0.9994359016418457, "start": 7182, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 7519, "score": 0.994971752166748, "start": 7487, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1'\n .nodeify done\n", "end": 7887, "score": 0.9994657039642334, "start": 7881, "tag": "USERNAME", "value": "destec" }, { "context": "\n req.integration =\n _id: 1\n token: '02ddb822d4000975005c76484364f1ee'\n\n $bitbucket.then (bitbucket) -> bitbucket.re", "end": 8218, "score": 0.9960348010063171, "start": 8186, "tag": "KEY", "value": "02ddb822d4000975005c76484364f1ee" }, { "context": " message.attachments[0].data.title.should.eql 'Catalyst Zhang deleted a comment for pull request update pr'\n ", "end": 8410, "score": 0.9956984519958496, "start": 8396, "tag": "NAME", "value": "Catalyst Zhang" }, { "context": "ata.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1'\n .nodeify done\n", "end": 8605, "score": 0.9995404481887817, "start": 8599, "tag": "USERNAME", "value": "destec" } ]
test/services/bitbucket.coffee
jianliaoim/talk-services
40
should = require 'should' loader = require '../../src/loader' {req} = require '../util' $bitbucket = loader.load 'bitbucket' describe 'Bitbucket#Webhook', -> it 'receive invalid webhook', (done) -> data = require './bitbucket_assets/invalid_event.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then -> done new Error('Should not pass') .catch (err) -> err.message.should.eql 'Invalid event type' done() it 'receive invalid webhook(invalid issue action)', (done) -> data = require './bitbucket_assets/invalid_issue_action.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then -> done new Error('should not pass') .catch (err) -> err.message.should.eql 'Unsupported action' done() it 'receive repository push', (done) -> data = require './bitbucket_assets/repo_push.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'A new push for project Test Bitbucket' message.attachments[0].data.text.should.eql 'Committer: Catalyst Zhang' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket' .nodeify done it 'receive repository comment', (done) -> data = require './bitbucket_assets/repo_commit_comment_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'A new comment for Test Bitbucket' message.attachments[0].data.text.should.eql 'a comment for the commit.' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/commits/024cb7dc2cea5cc1360dad6531661a037e492a8d#comment-2066462' .nodeify done it 'receive issue comment notifycation', (done) -> data = require './bitbucket_assets/issue_comment_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created a comment for project destec/test-bitbucket' message.attachments[0].data.text.should.eql 'comment for the issue' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1#comment-19446825' .nodeify done it 'receive issue created notification', (done) -> data = require './bitbucket_assets/issue_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created an issue for project destec/test-bitbucket' message.attachments[0].data.text.should.eql 'the test issue' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1/hi-what-is-issue' .nodeify done it 'receive issue updated notification', (done) -> data = require './bitbucket_assets/issue_updated.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang updated an issue for project destec/test-bitbucket' message.attachments[0].data.text.should.eql 'update the test issue' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1/hi-what-is-issue' .nodeify done it 'receive pull request created notification', (done) -> data = require './bitbucket_assets/pullrequest_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created a pull request for Test Bitbucket' message.attachments[0].data.text.should.eql 'first br' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request updated notification', (done) -> data = require './bitbucket_assets/pullrequest_updated.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang updated a pull request for Test Bitbucket' message.attachments[0].data.text.should.eql 'first br' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request fulfilled notification', (done) -> data = require './bitbucket_assets/pullrequest_fulfilled.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang fulfilled the pull request update pr' message.attachments[0].data.text.should.eql '' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request rejected notification', (done) -> data = require './bitbucket_assets/pullrequest_rejected.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang rejected the pull request second pr' message.attachments[0].data.text.should.eql '' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/2' .nodeify done it 'receive pull request comment created notification', (done) -> data = require './bitbucket_assets/pullrequest_comment_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created a comment for pull request update pr' message.attachments[0].data.text.should.eql 'update pr' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request comment updated notification', (done) -> data = require './bitbucket_assets/pullrequest_comment_deleted.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '02ddb822d4000975005c76484364f1ee' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang deleted a comment for pull request update pr' message.attachments[0].data.text.should.eql 'update pr' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done
117448
should = require 'should' loader = require '../../src/loader' {req} = require '../util' $bitbucket = loader.load 'bitbucket' describe 'Bitbucket#Webhook', -> it 'receive invalid webhook', (done) -> data = require './bitbucket_assets/invalid_event.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then -> done new Error('Should not pass') .catch (err) -> err.message.should.eql 'Invalid event type' done() it 'receive invalid webhook(invalid issue action)', (done) -> data = require './bitbucket_assets/invalid_issue_action.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then -> done new Error('should not pass') .catch (err) -> err.message.should.eql 'Unsupported action' done() it 'receive repository push', (done) -> data = require './bitbucket_assets/repo_push.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'A new push for project Test Bitbucket' message.attachments[0].data.text.should.eql 'Committer: <NAME>' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket' .nodeify done it 'receive repository comment', (done) -> data = require './bitbucket_assets/repo_commit_comment_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'A new comment for Test Bitbucket' message.attachments[0].data.text.should.eql 'a comment for the commit.' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/commits/024cb7dc2cea5cc1360dad6531661a037e492a8d#comment-2066462' .nodeify done it 'receive issue comment notifycation', (done) -> data = require './bitbucket_assets/issue_comment_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created a comment for project destec/test-bitbucket' message.attachments[0].data.text.should.eql 'comment for the issue' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1#comment-19446825' .nodeify done it 'receive issue created notification', (done) -> data = require './bitbucket_assets/issue_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created an issue for project destec/test-bitbucket' message.attachments[0].data.text.should.eql 'the test issue' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1/hi-what-is-issue' .nodeify done it 'receive issue updated notification', (done) -> data = require './bitbucket_assets/issue_updated.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang updated an issue for project destec/test-bitbucket' message.attachments[0].data.text.should.eql 'update the test issue' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1/hi-what-is-issue' .nodeify done it 'receive pull request created notification', (done) -> data = require './bitbucket_assets/pullrequest_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created a pull request for Test Bitbucket' message.attachments[0].data.text.should.eql 'first br' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request updated notification', (done) -> data = require './bitbucket_assets/pullrequest_updated.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang updated a pull request for Test Bitbucket' message.attachments[0].data.text.should.eql 'first br' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request fulfilled notification', (done) -> data = require './bitbucket_assets/pullrequest_fulfilled.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang fulfilled the pull request update pr' message.attachments[0].data.text.should.eql '' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request rejected notification', (done) -> data = require './bitbucket_assets/pullrequest_rejected.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang rejected the pull request second pr' message.attachments[0].data.text.should.eql '' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/2' .nodeify done it 'receive pull request comment created notification', (done) -> data = require './bitbucket_assets/pullrequest_comment_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created a comment for pull request update pr' message.attachments[0].data.text.should.eql 'update pr' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request comment updated notification', (done) -> data = require './bitbucket_assets/pullrequest_comment_deleted.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: '<KEY>' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> (message) -> message.attachments[0].data.title.should.eql '<NAME> deleted a comment for pull request update pr' message.attachments[0].data.text.should.eql 'update pr' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done
true
should = require 'should' loader = require '../../src/loader' {req} = require '../util' $bitbucket = loader.load 'bitbucket' describe 'Bitbucket#Webhook', -> it 'receive invalid webhook', (done) -> data = require './bitbucket_assets/invalid_event.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then -> done new Error('Should not pass') .catch (err) -> err.message.should.eql 'Invalid event type' done() it 'receive invalid webhook(invalid issue action)', (done) -> data = require './bitbucket_assets/invalid_issue_action.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then -> done new Error('should not pass') .catch (err) -> err.message.should.eql 'Unsupported action' done() it 'receive repository push', (done) -> data = require './bitbucket_assets/repo_push.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'A new push for project Test Bitbucket' message.attachments[0].data.text.should.eql 'Committer: PI:NAME:<NAME>END_PI' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket' .nodeify done it 'receive repository comment', (done) -> data = require './bitbucket_assets/repo_commit_comment_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'A new comment for Test Bitbucket' message.attachments[0].data.text.should.eql 'a comment for the commit.' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/commits/024cb7dc2cea5cc1360dad6531661a037e492a8d#comment-2066462' .nodeify done it 'receive issue comment notifycation', (done) -> data = require './bitbucket_assets/issue_comment_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created a comment for project destec/test-bitbucket' message.attachments[0].data.text.should.eql 'comment for the issue' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1#comment-19446825' .nodeify done it 'receive issue created notification', (done) -> data = require './bitbucket_assets/issue_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created an issue for project destec/test-bitbucket' message.attachments[0].data.text.should.eql 'the test issue' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1/hi-what-is-issue' .nodeify done it 'receive issue updated notification', (done) -> data = require './bitbucket_assets/issue_updated.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang updated an issue for project destec/test-bitbucket' message.attachments[0].data.text.should.eql 'update the test issue' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/issue/1/hi-what-is-issue' .nodeify done it 'receive pull request created notification', (done) -> data = require './bitbucket_assets/pullrequest_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created a pull request for Test Bitbucket' message.attachments[0].data.text.should.eql 'first br' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request updated notification', (done) -> data = require './bitbucket_assets/pullrequest_updated.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang updated a pull request for Test Bitbucket' message.attachments[0].data.text.should.eql 'first br' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request fulfilled notification', (done) -> data = require './bitbucket_assets/pullrequest_fulfilled.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang fulfilled the pull request update pr' message.attachments[0].data.text.should.eql '' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request rejected notification', (done) -> data = require './bitbucket_assets/pullrequest_rejected.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang rejected the pull request second pr' message.attachments[0].data.text.should.eql '' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/2' .nodeify done it 'receive pull request comment created notification', (done) -> data = require './bitbucket_assets/pullrequest_comment_created.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.title.should.eql 'Catalyst Zhang created a comment for pull request update pr' message.attachments[0].data.text.should.eql 'update pr' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done it 'receive pull request comment updated notification', (done) -> data = require './bitbucket_assets/pullrequest_comment_deleted.json' req.headers = data.headers req.body = data.body req.integration = _id: 1 token: 'PI:KEY:<KEY>END_PI' $bitbucket.then (bitbucket) -> bitbucket.receiveEvent 'service.webhook', req .then (message) -> (message) -> message.attachments[0].data.title.should.eql 'PI:NAME:<NAME>END_PI deleted a comment for pull request update pr' message.attachments[0].data.text.should.eql 'update pr' message.attachments[0].data.redirectUrl.should.eql 'https://bitbucket.org/destec/test-bitbucket/pull-request/1' .nodeify done
[ { "context": "ey\"\n\t\t\t\t\tAWSSecretKey: \"secret\"\n\t\t\t\tfromAddress: \"bob@bob.com\"\n\t\t\t\treplyToAddress: \"sally@gmail.com\"\n\n\t\t@sesCli", "end": 505, "score": 0.9999256134033203, "start": 494, "tag": "EMAIL", "value": "bob@bob.com" }, { "context": "\t\tfromAddress: \"bob@bob.com\"\n\t\t\t\treplyToAddress: \"sally@gmail.com\"\n\n\t\t@sesClient =\n\t\t\tsendMail: sinon.stub()\n\n\t\t@se", "end": 543, "score": 0.9999260306358337, "start": 528, "tag": "EMAIL", "value": "sally@gmail.com" }, { "context": "rastructure/Metrics\": inc:->\n\n\n\n\t\t@opts =\n\t\t\tto: \"bob@bob.com\"\n\t\t\tsubject: \"new email\"\n\t\t\thtml: \"<hello></hello", "end": 931, "score": 0.9999262094497681, "start": 920, "tag": "EMAIL", "value": "bob@bob.com" }, { "context": "ent.sendMail.callsArgWith(1)\n\n\t\t\t@opts.replyTo = \"someone@else.com\"\n\t\t\t@sender.sendEmail @opts, =>\n\t\t\t\targs = @sesCl", "end": 2121, "score": 0.9998868107795715, "start": 2105, "tag": "EMAIL", "value": "someone@else.com" } ]
test/UnitTests/coffee/Email/EmailSenderTests.coffee
watercrossing/web-sharelatex
0
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Email/EmailSender.js" expect = require("chai").expect describe "EmailSender", -> beforeEach -> @RateLimiter = addCount:sinon.stub() @settings = email: transport: "ses" parameters: AWSAccessKeyID: "key" AWSSecretKey: "secret" fromAddress: "bob@bob.com" replyToAddress: "sally@gmail.com" @sesClient = sendMail: sinon.stub() @ses = createTransport: => @sesClient @sender = SandboxedModule.require modulePath, requires: 'nodemailer': @ses "settings-sharelatex":@settings '../../infrastructure/RateLimiter':@RateLimiter "logger-sharelatex": log:-> warn:-> err:-> "../../infrastructure/Metrics": inc:-> @opts = to: "bob@bob.com" subject: "new email" html: "<hello></hello>" describe "sendEmail", -> it "should set the properties on the email to send", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.html.should.equal @opts.html args.to.should.equal @opts.to args.subject.should.equal @opts.subject done() it "should return the error", (done)-> @sesClient.sendMail.callsArgWith(1, "error") @sender.sendEmail {}, (err)=> err.should.equal "error" done() it "should use the from address from settings", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.from.should.equal @settings.email.fromAddress done() it "should use the reply to address from settings", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.replyTo.should.equal @settings.email.replyToAddress done() it "should use the reply to address in options as an override", (done)-> @sesClient.sendMail.callsArgWith(1) @opts.replyTo = "someone@else.com" @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.replyTo.should.equal @opts.replyTo done() it "should not send an email when the rate limiter says no", (done)-> @opts.sendingUser_id = "12321312321" @RateLimiter.addCount.callsArgWith(1, null, false) @sender.sendEmail @opts, => @sesClient.sendMail.called.should.equal false done() it "should send the email when the rate limtier says continue", (done)-> @sesClient.sendMail.callsArgWith(1) @opts.sendingUser_id = "12321312321" @RateLimiter.addCount.callsArgWith(1, null, true) @sender.sendEmail @opts, => @sesClient.sendMail.called.should.equal true done() it "should not check the rate limiter when there is no sendingUser_id", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => @sesClient.sendMail.called.should.equal true @RateLimiter.addCount.called.should.equal false done() describe 'with plain-text email content', () -> beforeEach -> @opts.text = "hello there" it "should set the text property on the email to send", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.html.should.equal @opts.html args.text.should.equal @opts.text args.to.should.equal @opts.to args.subject.should.equal @opts.subject done()
62275
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Email/EmailSender.js" expect = require("chai").expect describe "EmailSender", -> beforeEach -> @RateLimiter = addCount:sinon.stub() @settings = email: transport: "ses" parameters: AWSAccessKeyID: "key" AWSSecretKey: "secret" fromAddress: "<EMAIL>" replyToAddress: "<EMAIL>" @sesClient = sendMail: sinon.stub() @ses = createTransport: => @sesClient @sender = SandboxedModule.require modulePath, requires: 'nodemailer': @ses "settings-sharelatex":@settings '../../infrastructure/RateLimiter':@RateLimiter "logger-sharelatex": log:-> warn:-> err:-> "../../infrastructure/Metrics": inc:-> @opts = to: "<EMAIL>" subject: "new email" html: "<hello></hello>" describe "sendEmail", -> it "should set the properties on the email to send", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.html.should.equal @opts.html args.to.should.equal @opts.to args.subject.should.equal @opts.subject done() it "should return the error", (done)-> @sesClient.sendMail.callsArgWith(1, "error") @sender.sendEmail {}, (err)=> err.should.equal "error" done() it "should use the from address from settings", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.from.should.equal @settings.email.fromAddress done() it "should use the reply to address from settings", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.replyTo.should.equal @settings.email.replyToAddress done() it "should use the reply to address in options as an override", (done)-> @sesClient.sendMail.callsArgWith(1) @opts.replyTo = "<EMAIL>" @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.replyTo.should.equal @opts.replyTo done() it "should not send an email when the rate limiter says no", (done)-> @opts.sendingUser_id = "12321312321" @RateLimiter.addCount.callsArgWith(1, null, false) @sender.sendEmail @opts, => @sesClient.sendMail.called.should.equal false done() it "should send the email when the rate limtier says continue", (done)-> @sesClient.sendMail.callsArgWith(1) @opts.sendingUser_id = "12321312321" @RateLimiter.addCount.callsArgWith(1, null, true) @sender.sendEmail @opts, => @sesClient.sendMail.called.should.equal true done() it "should not check the rate limiter when there is no sendingUser_id", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => @sesClient.sendMail.called.should.equal true @RateLimiter.addCount.called.should.equal false done() describe 'with plain-text email content', () -> beforeEach -> @opts.text = "hello there" it "should set the text property on the email to send", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.html.should.equal @opts.html args.text.should.equal @opts.text args.to.should.equal @opts.to args.subject.should.equal @opts.subject done()
true
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Email/EmailSender.js" expect = require("chai").expect describe "EmailSender", -> beforeEach -> @RateLimiter = addCount:sinon.stub() @settings = email: transport: "ses" parameters: AWSAccessKeyID: "key" AWSSecretKey: "secret" fromAddress: "PI:EMAIL:<EMAIL>END_PI" replyToAddress: "PI:EMAIL:<EMAIL>END_PI" @sesClient = sendMail: sinon.stub() @ses = createTransport: => @sesClient @sender = SandboxedModule.require modulePath, requires: 'nodemailer': @ses "settings-sharelatex":@settings '../../infrastructure/RateLimiter':@RateLimiter "logger-sharelatex": log:-> warn:-> err:-> "../../infrastructure/Metrics": inc:-> @opts = to: "PI:EMAIL:<EMAIL>END_PI" subject: "new email" html: "<hello></hello>" describe "sendEmail", -> it "should set the properties on the email to send", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.html.should.equal @opts.html args.to.should.equal @opts.to args.subject.should.equal @opts.subject done() it "should return the error", (done)-> @sesClient.sendMail.callsArgWith(1, "error") @sender.sendEmail {}, (err)=> err.should.equal "error" done() it "should use the from address from settings", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.from.should.equal @settings.email.fromAddress done() it "should use the reply to address from settings", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.replyTo.should.equal @settings.email.replyToAddress done() it "should use the reply to address in options as an override", (done)-> @sesClient.sendMail.callsArgWith(1) @opts.replyTo = "PI:EMAIL:<EMAIL>END_PI" @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.replyTo.should.equal @opts.replyTo done() it "should not send an email when the rate limiter says no", (done)-> @opts.sendingUser_id = "12321312321" @RateLimiter.addCount.callsArgWith(1, null, false) @sender.sendEmail @opts, => @sesClient.sendMail.called.should.equal false done() it "should send the email when the rate limtier says continue", (done)-> @sesClient.sendMail.callsArgWith(1) @opts.sendingUser_id = "12321312321" @RateLimiter.addCount.callsArgWith(1, null, true) @sender.sendEmail @opts, => @sesClient.sendMail.called.should.equal true done() it "should not check the rate limiter when there is no sendingUser_id", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => @sesClient.sendMail.called.should.equal true @RateLimiter.addCount.called.should.equal false done() describe 'with plain-text email content', () -> beforeEach -> @opts.text = "hello there" it "should set the text property on the email to send", (done)-> @sesClient.sendMail.callsArgWith(1) @sender.sendEmail @opts, => args = @sesClient.sendMail.args[0][0] args.html.should.equal @opts.html args.text.should.equal @opts.text args.to.should.equal @opts.to args.subject.should.equal @opts.subject done()
[ { "context": "from PortAuthority\nfetchBuses = () ->\n\tAPI_key = '4EycNF36ZzhQnyHQBsrgVCx8C'\n\tproxy = 'https://paulmakesthe.net/ba-simple-pro", "end": 93, "score": 0.9996593594551086, "start": 68, "tag": "KEY", "value": "4EycNF36ZzhQnyHQBsrgVCx8C" } ]
public/js/buses.coffee
pschfr/dashboard
1
# Fetch bus times from PortAuthority fetchBuses = () -> API_key = '4EycNF36ZzhQnyHQBsrgVCx8C' proxy = 'https://paulmakesthe.net/ba-simple-proxy.php' # portURL = 'http://truetime.portauthority.org/bustime/api/v1/getstops' + '?key=' + API_key + '&rt=P1&dir=OUTBOUND' portURL = 'http://truetime.portauthority.org/bustime/api/v1/getpredictions' + '?key=' + API_key + '&stpid=8162,20501' xhr = new XMLHttpRequest() xhr.open('GET', proxy + '?url=' + encodeURIComponent(portURL), true) xhr.onreadystatechange = () -> if (xhr.readyState == 4 && xhr.status == 200) result = JSON.parse(xhr.responseText) times = new DOMParser().parseFromString(result.contents, 'text/xml') console.log(times.childNodes[0]) xhr.send(null) fetchBuses()
165409
# Fetch bus times from PortAuthority fetchBuses = () -> API_key = '<KEY>' proxy = 'https://paulmakesthe.net/ba-simple-proxy.php' # portURL = 'http://truetime.portauthority.org/bustime/api/v1/getstops' + '?key=' + API_key + '&rt=P1&dir=OUTBOUND' portURL = 'http://truetime.portauthority.org/bustime/api/v1/getpredictions' + '?key=' + API_key + '&stpid=8162,20501' xhr = new XMLHttpRequest() xhr.open('GET', proxy + '?url=' + encodeURIComponent(portURL), true) xhr.onreadystatechange = () -> if (xhr.readyState == 4 && xhr.status == 200) result = JSON.parse(xhr.responseText) times = new DOMParser().parseFromString(result.contents, 'text/xml') console.log(times.childNodes[0]) xhr.send(null) fetchBuses()
true
# Fetch bus times from PortAuthority fetchBuses = () -> API_key = 'PI:KEY:<KEY>END_PI' proxy = 'https://paulmakesthe.net/ba-simple-proxy.php' # portURL = 'http://truetime.portauthority.org/bustime/api/v1/getstops' + '?key=' + API_key + '&rt=P1&dir=OUTBOUND' portURL = 'http://truetime.portauthority.org/bustime/api/v1/getpredictions' + '?key=' + API_key + '&stpid=8162,20501' xhr = new XMLHttpRequest() xhr.open('GET', proxy + '?url=' + encodeURIComponent(portURL), true) xhr.onreadystatechange = () -> if (xhr.readyState == 4 && xhr.status == 200) result = JSON.parse(xhr.responseText) times = new DOMParser().parseFromString(result.contents, 'text/xml') console.log(times.childNodes[0]) xhr.send(null) fetchBuses()
[ { "context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ", "end": 3796, "score": 0.9960963129997253, "start": 3789, "tag": "NAME", "value": "Patient" }, { "context": " }\n }, {\n \"name\" : \"InDemographic\",\n \"context\" : \"Patient\",\n ", "end": 4180, "score": 0.8798041939735413, "start": 4167, "tag": "NAME", "value": "InDemographic" } ]
src/example/age.coffee
luis1van/cql-execution-1
2
module.exports = { "library" : { "identifier" : { "id" : "AgeAtMP", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "parameters" : { "def" : [ { "name" : "MeasurementPeriod", "accessLevel" : "Public", "default" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "type" : "DateTime", "year" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2013", "type" : "Literal" }, "month" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "day" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "hour" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "minute" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "second" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "millisecond" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" } }, "high" : { "type" : "DateTime", "year" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2014", "type" : "Literal" }, "month" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "day" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "hour" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "minute" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "second" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "millisecond" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" } } } } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "InDemographic", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "And", "operand" : [ { "type" : "GreaterOrEqual", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "Less", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "18", "type" : "Literal" } ] } ] } } ] } } }
157508
module.exports = { "library" : { "identifier" : { "id" : "AgeAtMP", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "parameters" : { "def" : [ { "name" : "MeasurementPeriod", "accessLevel" : "Public", "default" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "type" : "DateTime", "year" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2013", "type" : "Literal" }, "month" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "day" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "hour" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "minute" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "second" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "millisecond" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" } }, "high" : { "type" : "DateTime", "year" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2014", "type" : "Literal" }, "month" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "day" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "hour" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "minute" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "second" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "millisecond" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" } } } } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "And", "operand" : [ { "type" : "GreaterOrEqual", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "Less", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "18", "type" : "Literal" } ] } ] } } ] } } }
true
module.exports = { "library" : { "identifier" : { "id" : "AgeAtMP", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "parameters" : { "def" : [ { "name" : "MeasurementPeriod", "accessLevel" : "Public", "default" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "type" : "DateTime", "year" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2013", "type" : "Literal" }, "month" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "day" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "hour" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "minute" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "second" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "millisecond" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" } }, "high" : { "type" : "DateTime", "year" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2014", "type" : "Literal" }, "month" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "day" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, "hour" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "minute" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "second" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, "millisecond" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" } } } } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "And", "operand" : [ { "type" : "GreaterOrEqual", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "Less", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "18", "type" : "Literal" } ] } ] } } ] } } }
[ { "context": " port: 27017\n name: 'worklog'\n username: 'someuser'\n password: 'somepass'\n google:\n clientId:", "end": 832, "score": 0.9995962381362915, "start": 824, "tag": "USERNAME", "value": "someuser" }, { "context": "'worklog'\n username: 'someuser'\n password: 'somepass'\n google:\n clientId: process.argv[2]\n clie", "end": 857, "score": 0.9991337060928345, "start": 849, "tag": "PASSWORD", "value": "somepass" }, { "context": "\n\n\n# class User\n# Task: class\n# constructor: (@user) ->\n# description: \"New\"\n# log: -> l @use", "end": 2500, "score": 0.9973954558372498, "start": 2494, "tag": "USERNAME", "value": "(@user" }, { "context": "@user) ->\n# description: \"New\"\n# log: -> l @user\n#\n# tasks: (q) ->\n# a = new @Task\n# a.l", "end": 2551, "score": 0.6424204111099243, "start": 2546, "tag": "USERNAME", "value": "@user" }, { "context": "\n# a.log()\n#\n#\n#\n# me = new User\n# me.name = \"Me\";\n#\n# you = new User\n# you.name = \"You\";\n#\n# me.t", "end": 2643, "score": 0.8606042861938477, "start": 2641, "tag": "NAME", "value": "Me" }, { "context": " me.name = \"Me\";\n#\n# you = new User\n# you.name = \"You\";\n#\n# me.tasks {a:1}\n# you.tasks {}\n\nsetupServer ", "end": 2682, "score": 0.9023243188858032, "start": 2679, "tag": "NAME", "value": "You" } ]
backend/backend.coffee
KamilSzot/ReactBackboneCoffeescript
0
express = require 'express' session = require 'express-session' Q = require 'q' crypto = require 'crypto' bodyParser = require 'body-parser' passport = require 'passport' util = require 'util' mongoSessionStore = require 'connect-mongodb' GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; mongodb = require 'mongodb' ID = (value) -> return new mongodb.BSONPure.ObjectID(value) l = (msg) -> console.log util.inspect(msg) + "\n" + ((new Error).stack.split "\n")[2] config = url: backend: 'http://localhost:3000' frontend: 'http://localhost:8080' home: '/' auth: '/auth/google' authReturn: '/auth/google/return' logout: '/auth/logout' db: host: 'localhost' port: 27017 name: 'worklog' username: 'someuser' password: 'somepass' google: clientId: process.argv[2] clientSecret: process.argv[3] serverParams = auto_reconnect: true dbParams = w: 1 # Default write concern. db = new mongodb.Db(config.db.name, new mongodb.Server(config.db.host, config.db.port, serverParams), dbParams) db.open (err,db) -> if err console.error "Can't connect!" return db.authenticate config.db.username, config.db.password, () -> if err console.error "Can't authenticate!" setupServer() mongo = query: (collection, query) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "find", query, { sort: [['order', 1]] } .then (cursor) -> Q.ninvoke cursor, "toArray" remove: (collection, query) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "remove", query, { single: true } update: (collection, query, data) -> delete data._id; Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "update", query, data insert: (collection, data) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "insert", data .then (docs) -> docs[0] drop: (collection) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "drop" upsert: (collection, query, update) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "findAndModify", query, [['_id', 1]], update, { upsert: true, new: true } .then ([doc, fullResult]) -> doc # findAndModify passes fullResult to its callback as last parameter on success # class User # Task: class # constructor: (@user) -> # description: "New" # log: -> l @user # # tasks: (q) -> # a = new @Task # a.log() # # # # me = new User # me.name = "Me"; # # you = new User # you.name = "You"; # # me.tasks {a:1} # you.tasks {} setupServer = -> app = express() app.use bodyParser.json() app.use session secret: "dsfdfsdfsbcvbcvb###@$3423adsad" saveUninitialized: true resave: true store: new mongoSessionStore { db: db } app.use passport.initialize() app.use passport.session() app.get config.url.auth, passport.authenticate('google', { scope: 'https://www.googleapis.com/auth/plus.login' }) app.get config.url.authReturn, passport.authenticate('google', { successRedirect: config.url.frontend + config.url.home failureRedirect: config.url.frontend + config.url.home }) passport.use new GoogleStrategy { clientID: config.google.clientId, clientSecret: config.google.clientSecret, callbackURL: config.url.backend + config.url.authReturn }, (accessToken, refreshToken, profile, done) -> mongo.upsert "user", { openId: profile.id }, { $set: profile } .then (user) -> done(null, user); .done() passport.serializeUser (user, done) -> done(null, user._id); passport.deserializeUser (user, done) -> mongo.query 'user', { _id: ID(user) } .then (users) -> done(null, users[0]); setCORS = (res) -> res.set 'Access-Control-Allow-Origin', config.url.frontend res.set 'Access-Control-Allow-Methods', 'GET,PUT,DELETE,POST' res.set 'Access-Control-Allow-Headers', 'Content-Type' res.set 'Access-Control-Allow-Credentials', 'true' respond = (res, promise) -> promise .then (result) -> # l typeof result responseText = new Buffer(JSON.stringify(result || null), 'utf-8') res.set 'ETag', crypto.createHash('md5').update(responseText).digest('hex') res.set 'Content-Type', 'application/json' setCORS res res.send responseText .catch (err) -> err = err || {} console.log err.stack setCORS res res.status(err.status || 500).send({ message: err.err || err.errmsg }) .done() app.use /^((?!\/auth|\/user).)*$/, (req, res, next) -> if req.user || req.method == "OPTIONS" next() else setCORS res res.status(401).send('Unauthorized'); app.get '/auth/google/logout', (req, res) -> req.logout(); res.redirect config.url.frontend app.post '/clear', (req, res) -> respond res, mongoDrop('task') app.route '/user/me' .get (req, res) -> if req.user respond res, Q.when(req.user) else p = Q.defer() p.reject({ status: 404 }) respond res, p.promise app.route '/:collection/:id' .get (req, res) -> respond res, mongo.query req.params.collection, { _id: ID(req.params.id) } .delete (req, res) -> respond res, mongo.remove req.params.collection, { _id: ID(req.params.id) } .put (req, res) -> respond res, mongo.update req.params.collection, { _id: ID(req.params.id) }, req.body app.route '/:collection' .post (req, res) -> mongo.upsert "sequence", { name: req.params.collection }, { $inc: { lastOrder: 1 } } .then (r) -> respond res, mongo.insert req.params.collection, util._extend(req.body, { order: r.lastOrder }) .get (req, res) -> respond res, mongo.query req.params.collection, {} app.options '*', (req, res) -> setCORS res res.send "" app.get '/', (req, res) -> res.send 'ok' app.listen 3000
159785
express = require 'express' session = require 'express-session' Q = require 'q' crypto = require 'crypto' bodyParser = require 'body-parser' passport = require 'passport' util = require 'util' mongoSessionStore = require 'connect-mongodb' GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; mongodb = require 'mongodb' ID = (value) -> return new mongodb.BSONPure.ObjectID(value) l = (msg) -> console.log util.inspect(msg) + "\n" + ((new Error).stack.split "\n")[2] config = url: backend: 'http://localhost:3000' frontend: 'http://localhost:8080' home: '/' auth: '/auth/google' authReturn: '/auth/google/return' logout: '/auth/logout' db: host: 'localhost' port: 27017 name: 'worklog' username: 'someuser' password: '<PASSWORD>' google: clientId: process.argv[2] clientSecret: process.argv[3] serverParams = auto_reconnect: true dbParams = w: 1 # Default write concern. db = new mongodb.Db(config.db.name, new mongodb.Server(config.db.host, config.db.port, serverParams), dbParams) db.open (err,db) -> if err console.error "Can't connect!" return db.authenticate config.db.username, config.db.password, () -> if err console.error "Can't authenticate!" setupServer() mongo = query: (collection, query) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "find", query, { sort: [['order', 1]] } .then (cursor) -> Q.ninvoke cursor, "toArray" remove: (collection, query) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "remove", query, { single: true } update: (collection, query, data) -> delete data._id; Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "update", query, data insert: (collection, data) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "insert", data .then (docs) -> docs[0] drop: (collection) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "drop" upsert: (collection, query, update) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "findAndModify", query, [['_id', 1]], update, { upsert: true, new: true } .then ([doc, fullResult]) -> doc # findAndModify passes fullResult to its callback as last parameter on success # class User # Task: class # constructor: (@user) -> # description: "New" # log: -> l @user # # tasks: (q) -> # a = new @Task # a.log() # # # # me = new User # me.name = "<NAME>"; # # you = new User # you.name = "<NAME>"; # # me.tasks {a:1} # you.tasks {} setupServer = -> app = express() app.use bodyParser.json() app.use session secret: "dsfdfsdfsbcvbcvb###@$3423adsad" saveUninitialized: true resave: true store: new mongoSessionStore { db: db } app.use passport.initialize() app.use passport.session() app.get config.url.auth, passport.authenticate('google', { scope: 'https://www.googleapis.com/auth/plus.login' }) app.get config.url.authReturn, passport.authenticate('google', { successRedirect: config.url.frontend + config.url.home failureRedirect: config.url.frontend + config.url.home }) passport.use new GoogleStrategy { clientID: config.google.clientId, clientSecret: config.google.clientSecret, callbackURL: config.url.backend + config.url.authReturn }, (accessToken, refreshToken, profile, done) -> mongo.upsert "user", { openId: profile.id }, { $set: profile } .then (user) -> done(null, user); .done() passport.serializeUser (user, done) -> done(null, user._id); passport.deserializeUser (user, done) -> mongo.query 'user', { _id: ID(user) } .then (users) -> done(null, users[0]); setCORS = (res) -> res.set 'Access-Control-Allow-Origin', config.url.frontend res.set 'Access-Control-Allow-Methods', 'GET,PUT,DELETE,POST' res.set 'Access-Control-Allow-Headers', 'Content-Type' res.set 'Access-Control-Allow-Credentials', 'true' respond = (res, promise) -> promise .then (result) -> # l typeof result responseText = new Buffer(JSON.stringify(result || null), 'utf-8') res.set 'ETag', crypto.createHash('md5').update(responseText).digest('hex') res.set 'Content-Type', 'application/json' setCORS res res.send responseText .catch (err) -> err = err || {} console.log err.stack setCORS res res.status(err.status || 500).send({ message: err.err || err.errmsg }) .done() app.use /^((?!\/auth|\/user).)*$/, (req, res, next) -> if req.user || req.method == "OPTIONS" next() else setCORS res res.status(401).send('Unauthorized'); app.get '/auth/google/logout', (req, res) -> req.logout(); res.redirect config.url.frontend app.post '/clear', (req, res) -> respond res, mongoDrop('task') app.route '/user/me' .get (req, res) -> if req.user respond res, Q.when(req.user) else p = Q.defer() p.reject({ status: 404 }) respond res, p.promise app.route '/:collection/:id' .get (req, res) -> respond res, mongo.query req.params.collection, { _id: ID(req.params.id) } .delete (req, res) -> respond res, mongo.remove req.params.collection, { _id: ID(req.params.id) } .put (req, res) -> respond res, mongo.update req.params.collection, { _id: ID(req.params.id) }, req.body app.route '/:collection' .post (req, res) -> mongo.upsert "sequence", { name: req.params.collection }, { $inc: { lastOrder: 1 } } .then (r) -> respond res, mongo.insert req.params.collection, util._extend(req.body, { order: r.lastOrder }) .get (req, res) -> respond res, mongo.query req.params.collection, {} app.options '*', (req, res) -> setCORS res res.send "" app.get '/', (req, res) -> res.send 'ok' app.listen 3000
true
express = require 'express' session = require 'express-session' Q = require 'q' crypto = require 'crypto' bodyParser = require 'body-parser' passport = require 'passport' util = require 'util' mongoSessionStore = require 'connect-mongodb' GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; mongodb = require 'mongodb' ID = (value) -> return new mongodb.BSONPure.ObjectID(value) l = (msg) -> console.log util.inspect(msg) + "\n" + ((new Error).stack.split "\n")[2] config = url: backend: 'http://localhost:3000' frontend: 'http://localhost:8080' home: '/' auth: '/auth/google' authReturn: '/auth/google/return' logout: '/auth/logout' db: host: 'localhost' port: 27017 name: 'worklog' username: 'someuser' password: 'PI:PASSWORD:<PASSWORD>END_PI' google: clientId: process.argv[2] clientSecret: process.argv[3] serverParams = auto_reconnect: true dbParams = w: 1 # Default write concern. db = new mongodb.Db(config.db.name, new mongodb.Server(config.db.host, config.db.port, serverParams), dbParams) db.open (err,db) -> if err console.error "Can't connect!" return db.authenticate config.db.username, config.db.password, () -> if err console.error "Can't authenticate!" setupServer() mongo = query: (collection, query) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "find", query, { sort: [['order', 1]] } .then (cursor) -> Q.ninvoke cursor, "toArray" remove: (collection, query) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "remove", query, { single: true } update: (collection, query, data) -> delete data._id; Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "update", query, data insert: (collection, data) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "insert", data .then (docs) -> docs[0] drop: (collection) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "drop" upsert: (collection, query, update) -> Q.ninvoke db, "collection", collection .then (col) -> Q.ninvoke col, "findAndModify", query, [['_id', 1]], update, { upsert: true, new: true } .then ([doc, fullResult]) -> doc # findAndModify passes fullResult to its callback as last parameter on success # class User # Task: class # constructor: (@user) -> # description: "New" # log: -> l @user # # tasks: (q) -> # a = new @Task # a.log() # # # # me = new User # me.name = "PI:NAME:<NAME>END_PI"; # # you = new User # you.name = "PI:NAME:<NAME>END_PI"; # # me.tasks {a:1} # you.tasks {} setupServer = -> app = express() app.use bodyParser.json() app.use session secret: "dsfdfsdfsbcvbcvb###@$3423adsad" saveUninitialized: true resave: true store: new mongoSessionStore { db: db } app.use passport.initialize() app.use passport.session() app.get config.url.auth, passport.authenticate('google', { scope: 'https://www.googleapis.com/auth/plus.login' }) app.get config.url.authReturn, passport.authenticate('google', { successRedirect: config.url.frontend + config.url.home failureRedirect: config.url.frontend + config.url.home }) passport.use new GoogleStrategy { clientID: config.google.clientId, clientSecret: config.google.clientSecret, callbackURL: config.url.backend + config.url.authReturn }, (accessToken, refreshToken, profile, done) -> mongo.upsert "user", { openId: profile.id }, { $set: profile } .then (user) -> done(null, user); .done() passport.serializeUser (user, done) -> done(null, user._id); passport.deserializeUser (user, done) -> mongo.query 'user', { _id: ID(user) } .then (users) -> done(null, users[0]); setCORS = (res) -> res.set 'Access-Control-Allow-Origin', config.url.frontend res.set 'Access-Control-Allow-Methods', 'GET,PUT,DELETE,POST' res.set 'Access-Control-Allow-Headers', 'Content-Type' res.set 'Access-Control-Allow-Credentials', 'true' respond = (res, promise) -> promise .then (result) -> # l typeof result responseText = new Buffer(JSON.stringify(result || null), 'utf-8') res.set 'ETag', crypto.createHash('md5').update(responseText).digest('hex') res.set 'Content-Type', 'application/json' setCORS res res.send responseText .catch (err) -> err = err || {} console.log err.stack setCORS res res.status(err.status || 500).send({ message: err.err || err.errmsg }) .done() app.use /^((?!\/auth|\/user).)*$/, (req, res, next) -> if req.user || req.method == "OPTIONS" next() else setCORS res res.status(401).send('Unauthorized'); app.get '/auth/google/logout', (req, res) -> req.logout(); res.redirect config.url.frontend app.post '/clear', (req, res) -> respond res, mongoDrop('task') app.route '/user/me' .get (req, res) -> if req.user respond res, Q.when(req.user) else p = Q.defer() p.reject({ status: 404 }) respond res, p.promise app.route '/:collection/:id' .get (req, res) -> respond res, mongo.query req.params.collection, { _id: ID(req.params.id) } .delete (req, res) -> respond res, mongo.remove req.params.collection, { _id: ID(req.params.id) } .put (req, res) -> respond res, mongo.update req.params.collection, { _id: ID(req.params.id) }, req.body app.route '/:collection' .post (req, res) -> mongo.upsert "sequence", { name: req.params.collection }, { $inc: { lastOrder: 1 } } .then (r) -> respond res, mongo.insert req.params.collection, util._extend(req.body, { order: r.lastOrder }) .get (req, res) -> respond res, mongo.query req.params.collection, {} app.options '*', (req, res) -> setCORS res res.send "" app.get '/', (req, res) -> res.send 'ok' app.listen 3000
[ { "context": " if join = match.get('join')\n keys = keys.add('eid')\n keys\n\ncleanupEmptyMap = (key,map) ->\n if Imm", "end": 736, "score": 0.6149042248725891, "start": 733, "tag": "KEY", "value": "eid" }, { "context": "p:\n# index: ['eid', 'type']\n# keypath: [['bullet','eid'], 'animation']\n# }\n\nsearch = (object_store,filters,", "end": 1444, "score": 0.8454909324645996, "start": 1429, "tag": "KEY", "value": "bullet','eid']," }, { "context": "'eid', 'type']\n# keypath: [['bullet','eid'], 'animation']\n# }\n\nsearch = (object_store,filters,row=Immutab", "end": 1455, "score": 0.3911011219024658, "start": 1446, "tag": "KEY", "value": "animation" } ]
src/javascript/search/object_store_search.coffee
dcrosby42/metroid-clone
5
Immutable = require 'immutable' Profiler = require '../profiler' ObjectStore = require './object_store' debug = -> # debugging disabled # debug = console.log # debugging enabled expandPlaceholder = (x,row) -> if Immutable.List.isList(x) row.getIn(x) else x expandMatch = (filter,row) -> if filter.has('match') filter.update 'match', (m) -> m.map (v) -> expandPlaceholder(v,row) else filter expandLookup = (filter,row) -> if filter.has('lookup') filter.update 'lookup', (l) -> l.update 'keypath', (kp) -> kp.map (v) -> expandPlaceholder(v,row) else filter keysInMatch = (match) -> keys = match.keySeq().toSet() if join = match.get('join') keys = keys.add('eid') keys cleanupEmptyMap = (key,map) -> if Immutable.is(Immutable.Map(), map.get(key)) map.remove(key) else map convertMatchesToIndexLookups = (filter,indices) -> match = filter.get('match') return filter unless match? if index = ObjectStore.selectMatchingIndex(indices,keysInMatch(match)) cleanupEmptyMap 'match', filter.set('lookup', Immutable.Map( index: index keypath: index.map (key) -> match.get(key) )).update('match', (match) -> index.reduce (m,k) -> m.remove(k) , match ) else filter # { # as: 'animation' # match: # mode: ['bullet','mode'] # lookup: # index: ['eid', 'type'] # keypath: [['bullet','eid'], 'animation'] # } search = (object_store,filters,row=Immutable.Map()) -> # search_logCall(object_store,filters,row) if filters.size == 0 return Immutable.List([row]) if !Immutable.List.isList(filters) throw new Error("ObjectStoreSearch.search requires filters to be an Immutable.List, but was #{filters}") f0 = filters.first() f0 = expandLookup(expandMatch(f0,row), row) rest = filters.shift() as = f0.get('as') throw new Error("Filter must be labeled via 'as': #{f0.toJS()}") unless as? # # First: narrow the results by applying an indexed lookup (if available). # objs = if lookup = f0.get('lookup') index = lookup.get('index') keypath = lookup.get('keypath') # search_logIndex(index,keypath) ObjectStore.getIndexedObjects(object_store, index, keypath).toList() else # No indexed lookup available; we must scan all objects ObjectStore.allObjects(object_store).toList() # # Second: apply any non-indexed match criteria to the objectset # if matchProps = f0.get('match') # search_logFilter(objs,matchProps) # PRESUMABLY, THIS IS THE EXPENSIVE PART. # The following (potentially mutli-field) comparison (matchProps.every) is run once # per existing component. # Many systems join at least two component types. # A certain subset of systems really only expect to hit one main match. (Eg, ['samus','map']) # Full-list-scans mean joins are worst-case exponential. # n + n(c1) + n(c2) + ...n(cJ-1) where n = num components, h1 = number of hits in col1, h2 = number of hits in col2, and J is the number of cols being joined # 10 comps, 2 joined cols, 3 hits in the first col: 10 + 10(3) = 40 comparisons to yield 3 results. objs = objs.filter (obj) -> matchProps.every (v,k) -> obj.get(k) == v if objs.size == 0 and f0.get('optional',false) == true objs = new Immutable.Seq([null]) # # Recurse / join # # results = [] # i = 0 # while i < objs.size # thisRow = row.set(as,objs.get(i)) # if rest.size == 0 # results.push new Immutable.Seq([thisRow]) # else # subSearchResults = search(object_store,rest,thisRow) # j = 0 # while j < subSearchResults.size # results.push subSearchResults.get(j) # j++ # i++ # return new Immutable.Seq(results) objs.map((c) -> if rest.size == 0 new Immutable.Seq([row.set(as,c)]) else search(object_store,rest,row.set(as,c)) ).flatten(1) search_logCall = (object_store,filters,row) -> Profiler.count("search") debug "search: invoked w filters",filters,row.toJS() search_logIndex = (index,keypath) -> Profiler.count("search_index") debug " search: using index:",index.toJS(), "with keypath",keypath.toJS() search_logFilter = (objs,matchProps) -> Profiler.count("filterObjects") Profiler.sample("filterObjects_numComps",objs.size) debug " search: filtering #{objs.size} objs by matching:", matchProps.toJS() module.exports = search: (objectStore, filters) -> search objectStore, filters convertMatchesToIndexLookups: convertMatchesToIndexLookups _expandMatch: expandMatch _expandLookup: expandLookup
174368
Immutable = require 'immutable' Profiler = require '../profiler' ObjectStore = require './object_store' debug = -> # debugging disabled # debug = console.log # debugging enabled expandPlaceholder = (x,row) -> if Immutable.List.isList(x) row.getIn(x) else x expandMatch = (filter,row) -> if filter.has('match') filter.update 'match', (m) -> m.map (v) -> expandPlaceholder(v,row) else filter expandLookup = (filter,row) -> if filter.has('lookup') filter.update 'lookup', (l) -> l.update 'keypath', (kp) -> kp.map (v) -> expandPlaceholder(v,row) else filter keysInMatch = (match) -> keys = match.keySeq().toSet() if join = match.get('join') keys = keys.add('<KEY>') keys cleanupEmptyMap = (key,map) -> if Immutable.is(Immutable.Map(), map.get(key)) map.remove(key) else map convertMatchesToIndexLookups = (filter,indices) -> match = filter.get('match') return filter unless match? if index = ObjectStore.selectMatchingIndex(indices,keysInMatch(match)) cleanupEmptyMap 'match', filter.set('lookup', Immutable.Map( index: index keypath: index.map (key) -> match.get(key) )).update('match', (match) -> index.reduce (m,k) -> m.remove(k) , match ) else filter # { # as: 'animation' # match: # mode: ['bullet','mode'] # lookup: # index: ['eid', 'type'] # keypath: [['<KEY> '<KEY>'] # } search = (object_store,filters,row=Immutable.Map()) -> # search_logCall(object_store,filters,row) if filters.size == 0 return Immutable.List([row]) if !Immutable.List.isList(filters) throw new Error("ObjectStoreSearch.search requires filters to be an Immutable.List, but was #{filters}") f0 = filters.first() f0 = expandLookup(expandMatch(f0,row), row) rest = filters.shift() as = f0.get('as') throw new Error("Filter must be labeled via 'as': #{f0.toJS()}") unless as? # # First: narrow the results by applying an indexed lookup (if available). # objs = if lookup = f0.get('lookup') index = lookup.get('index') keypath = lookup.get('keypath') # search_logIndex(index,keypath) ObjectStore.getIndexedObjects(object_store, index, keypath).toList() else # No indexed lookup available; we must scan all objects ObjectStore.allObjects(object_store).toList() # # Second: apply any non-indexed match criteria to the objectset # if matchProps = f0.get('match') # search_logFilter(objs,matchProps) # PRESUMABLY, THIS IS THE EXPENSIVE PART. # The following (potentially mutli-field) comparison (matchProps.every) is run once # per existing component. # Many systems join at least two component types. # A certain subset of systems really only expect to hit one main match. (Eg, ['samus','map']) # Full-list-scans mean joins are worst-case exponential. # n + n(c1) + n(c2) + ...n(cJ-1) where n = num components, h1 = number of hits in col1, h2 = number of hits in col2, and J is the number of cols being joined # 10 comps, 2 joined cols, 3 hits in the first col: 10 + 10(3) = 40 comparisons to yield 3 results. objs = objs.filter (obj) -> matchProps.every (v,k) -> obj.get(k) == v if objs.size == 0 and f0.get('optional',false) == true objs = new Immutable.Seq([null]) # # Recurse / join # # results = [] # i = 0 # while i < objs.size # thisRow = row.set(as,objs.get(i)) # if rest.size == 0 # results.push new Immutable.Seq([thisRow]) # else # subSearchResults = search(object_store,rest,thisRow) # j = 0 # while j < subSearchResults.size # results.push subSearchResults.get(j) # j++ # i++ # return new Immutable.Seq(results) objs.map((c) -> if rest.size == 0 new Immutable.Seq([row.set(as,c)]) else search(object_store,rest,row.set(as,c)) ).flatten(1) search_logCall = (object_store,filters,row) -> Profiler.count("search") debug "search: invoked w filters",filters,row.toJS() search_logIndex = (index,keypath) -> Profiler.count("search_index") debug " search: using index:",index.toJS(), "with keypath",keypath.toJS() search_logFilter = (objs,matchProps) -> Profiler.count("filterObjects") Profiler.sample("filterObjects_numComps",objs.size) debug " search: filtering #{objs.size} objs by matching:", matchProps.toJS() module.exports = search: (objectStore, filters) -> search objectStore, filters convertMatchesToIndexLookups: convertMatchesToIndexLookups _expandMatch: expandMatch _expandLookup: expandLookup
true
Immutable = require 'immutable' Profiler = require '../profiler' ObjectStore = require './object_store' debug = -> # debugging disabled # debug = console.log # debugging enabled expandPlaceholder = (x,row) -> if Immutable.List.isList(x) row.getIn(x) else x expandMatch = (filter,row) -> if filter.has('match') filter.update 'match', (m) -> m.map (v) -> expandPlaceholder(v,row) else filter expandLookup = (filter,row) -> if filter.has('lookup') filter.update 'lookup', (l) -> l.update 'keypath', (kp) -> kp.map (v) -> expandPlaceholder(v,row) else filter keysInMatch = (match) -> keys = match.keySeq().toSet() if join = match.get('join') keys = keys.add('PI:KEY:<KEY>END_PI') keys cleanupEmptyMap = (key,map) -> if Immutable.is(Immutable.Map(), map.get(key)) map.remove(key) else map convertMatchesToIndexLookups = (filter,indices) -> match = filter.get('match') return filter unless match? if index = ObjectStore.selectMatchingIndex(indices,keysInMatch(match)) cleanupEmptyMap 'match', filter.set('lookup', Immutable.Map( index: index keypath: index.map (key) -> match.get(key) )).update('match', (match) -> index.reduce (m,k) -> m.remove(k) , match ) else filter # { # as: 'animation' # match: # mode: ['bullet','mode'] # lookup: # index: ['eid', 'type'] # keypath: [['PI:KEY:<KEY>END_PI 'PI:KEY:<KEY>END_PI'] # } search = (object_store,filters,row=Immutable.Map()) -> # search_logCall(object_store,filters,row) if filters.size == 0 return Immutable.List([row]) if !Immutable.List.isList(filters) throw new Error("ObjectStoreSearch.search requires filters to be an Immutable.List, but was #{filters}") f0 = filters.first() f0 = expandLookup(expandMatch(f0,row), row) rest = filters.shift() as = f0.get('as') throw new Error("Filter must be labeled via 'as': #{f0.toJS()}") unless as? # # First: narrow the results by applying an indexed lookup (if available). # objs = if lookup = f0.get('lookup') index = lookup.get('index') keypath = lookup.get('keypath') # search_logIndex(index,keypath) ObjectStore.getIndexedObjects(object_store, index, keypath).toList() else # No indexed lookup available; we must scan all objects ObjectStore.allObjects(object_store).toList() # # Second: apply any non-indexed match criteria to the objectset # if matchProps = f0.get('match') # search_logFilter(objs,matchProps) # PRESUMABLY, THIS IS THE EXPENSIVE PART. # The following (potentially mutli-field) comparison (matchProps.every) is run once # per existing component. # Many systems join at least two component types. # A certain subset of systems really only expect to hit one main match. (Eg, ['samus','map']) # Full-list-scans mean joins are worst-case exponential. # n + n(c1) + n(c2) + ...n(cJ-1) where n = num components, h1 = number of hits in col1, h2 = number of hits in col2, and J is the number of cols being joined # 10 comps, 2 joined cols, 3 hits in the first col: 10 + 10(3) = 40 comparisons to yield 3 results. objs = objs.filter (obj) -> matchProps.every (v,k) -> obj.get(k) == v if objs.size == 0 and f0.get('optional',false) == true objs = new Immutable.Seq([null]) # # Recurse / join # # results = [] # i = 0 # while i < objs.size # thisRow = row.set(as,objs.get(i)) # if rest.size == 0 # results.push new Immutable.Seq([thisRow]) # else # subSearchResults = search(object_store,rest,thisRow) # j = 0 # while j < subSearchResults.size # results.push subSearchResults.get(j) # j++ # i++ # return new Immutable.Seq(results) objs.map((c) -> if rest.size == 0 new Immutable.Seq([row.set(as,c)]) else search(object_store,rest,row.set(as,c)) ).flatten(1) search_logCall = (object_store,filters,row) -> Profiler.count("search") debug "search: invoked w filters",filters,row.toJS() search_logIndex = (index,keypath) -> Profiler.count("search_index") debug " search: using index:",index.toJS(), "with keypath",keypath.toJS() search_logFilter = (objs,matchProps) -> Profiler.count("filterObjects") Profiler.sample("filterObjects_numComps",objs.size) debug " search: filtering #{objs.size} objs by matching:", matchProps.toJS() module.exports = search: (objectStore, filters) -> search objectStore, filters convertMatchesToIndexLookups: convertMatchesToIndexLookups _expandMatch: expandMatch _expandLookup: expandLookup
[ { "context": "# Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redistribution and us", "end": 34, "score": 0.9998286366462708, "start": 21, "tag": "NAME", "value": "Yusuke Suzuki" }, { "context": "# Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redistribution and use in source and binary ", "end": 57, "score": 0.9999335408210754, "start": 36, "tag": "EMAIL", "value": "utatane.tea@gmail.com" } ]
node_modules/esutils/test/code.coffee
Kengetsu/Yuri-san
0
# Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 'use strict' expect = require('chai').expect esutils = require '../' describe 'code', -> describe 'isDecimalDigit', -> it 'returns true if provided code is decimal digit', -> for ch in [0..9] expect(esutils.code.isDecimalDigit((ch + '').charCodeAt(0))).to.be.true it 'returns false if provided code is not decimal digit', -> for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isDecimalDigit(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isDecimalDigit(code)).to.be.false describe 'isHexDigit', -> it 'returns true if provided code is hexadecimal digit', -> for ch in [0..9] expect(esutils.code.isHexDigit((ch + '').charCodeAt(0))).to.be.true for code in ['a'.charCodeAt(0)..'f'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.true for code in ['A'.charCodeAt(0)..'F'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.true it 'returns false if provided code is not hexadecimal digit', -> for code in ['g'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.false for code in ['G'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.false describe 'isOctalDigit', -> it 'returns true if provided code is octal digit', -> for ch in [0..7] expect(esutils.code.isOctalDigit((ch + '').charCodeAt(0))).to.be.true it 'returns false if provided code is not octal digit', -> for ch in [8..9] expect(esutils.code.isOctalDigit((ch + '').charCodeAt(0))).to.be.false for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isOctalDigit(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isOctalDigit(code)).to.be.false describe 'isWhiteSpace', -> it 'returns true if provided code is white space', -> codes = [ 0x0009 # TAB 0x000B # VT 0x000C # FF 0x0020 # SP 0x00A0 # NBSP 0xFEFF # BOM # Zs 0x1680 0x180E 0x2000 0x2001 0x2002 0x2003 0x2004 0x2005 0x2006 0x2007 0x2008 0x2009 0x200A 0x202F 0x205F 0x3000 ] for code in codes expect(esutils.code.isWhiteSpace(code)).to.be.true it 'returns false if provided code is not white space', -> for ch in [0..9] expect(esutils.code.isWhiteSpace((ch + '').charCodeAt(0))).to.be.false for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isWhiteSpace(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isWhiteSpace(code)).to.be.false describe 'isLineTerminator', -> it 'returns true if provided code is line terminator', -> codes = [ 0x000A 0x000D 0x2028 0x2029 ] for code in codes expect(esutils.code.isLineTerminator(code)).to.be.true it 'returns false if provided code is not line terminator', -> for ch in [0..9] expect(esutils.code.isLineTerminator((ch + '').charCodeAt(0))).to.be.false for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isLineTerminator(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isLineTerminator(code)).to.be.false describe 'isIdentifierStart', -> it 'returns true if provided code can be a start of Identifier', -> characters = [ 'a' '$' '_' 'ใ‚†' ] for code in characters.map((ch) -> ch.charCodeAt(0)) expect(esutils.code.isIdentifierStart(code)).to.be.true it 'returns false if provided code cannot be a start of Identifier', -> for ch in [0..9] expect(esutils.code.isIdentifierStart((ch + '').charCodeAt(0))).to.be.false describe 'isIdentifierPart', -> it 'returns true if provided code can be a part of Identifier', -> characters = [ 'a' '_' '$' 'ใ‚†' ] for code in characters.map((ch) -> ch.charCodeAt(0)) expect(esutils.code.isIdentifierPart(code)).to.be.true for ch in [0..9] expect(esutils.code.isIdentifierPart((ch + '').charCodeAt(0))).to.be.true it 'returns false if provided code cannot be a part of Identifier', -> expect(esutils.code.isIdentifierPart('+'.charCodeAt(0))).to.be.false expect(esutils.code.isIdentifierPart('-'.charCodeAt(0))).to.be.false
182636
# Copyright (C) 2013 <NAME> <<EMAIL>> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 'use strict' expect = require('chai').expect esutils = require '../' describe 'code', -> describe 'isDecimalDigit', -> it 'returns true if provided code is decimal digit', -> for ch in [0..9] expect(esutils.code.isDecimalDigit((ch + '').charCodeAt(0))).to.be.true it 'returns false if provided code is not decimal digit', -> for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isDecimalDigit(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isDecimalDigit(code)).to.be.false describe 'isHexDigit', -> it 'returns true if provided code is hexadecimal digit', -> for ch in [0..9] expect(esutils.code.isHexDigit((ch + '').charCodeAt(0))).to.be.true for code in ['a'.charCodeAt(0)..'f'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.true for code in ['A'.charCodeAt(0)..'F'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.true it 'returns false if provided code is not hexadecimal digit', -> for code in ['g'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.false for code in ['G'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.false describe 'isOctalDigit', -> it 'returns true if provided code is octal digit', -> for ch in [0..7] expect(esutils.code.isOctalDigit((ch + '').charCodeAt(0))).to.be.true it 'returns false if provided code is not octal digit', -> for ch in [8..9] expect(esutils.code.isOctalDigit((ch + '').charCodeAt(0))).to.be.false for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isOctalDigit(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isOctalDigit(code)).to.be.false describe 'isWhiteSpace', -> it 'returns true if provided code is white space', -> codes = [ 0x0009 # TAB 0x000B # VT 0x000C # FF 0x0020 # SP 0x00A0 # NBSP 0xFEFF # BOM # Zs 0x1680 0x180E 0x2000 0x2001 0x2002 0x2003 0x2004 0x2005 0x2006 0x2007 0x2008 0x2009 0x200A 0x202F 0x205F 0x3000 ] for code in codes expect(esutils.code.isWhiteSpace(code)).to.be.true it 'returns false if provided code is not white space', -> for ch in [0..9] expect(esutils.code.isWhiteSpace((ch + '').charCodeAt(0))).to.be.false for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isWhiteSpace(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isWhiteSpace(code)).to.be.false describe 'isLineTerminator', -> it 'returns true if provided code is line terminator', -> codes = [ 0x000A 0x000D 0x2028 0x2029 ] for code in codes expect(esutils.code.isLineTerminator(code)).to.be.true it 'returns false if provided code is not line terminator', -> for ch in [0..9] expect(esutils.code.isLineTerminator((ch + '').charCodeAt(0))).to.be.false for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isLineTerminator(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isLineTerminator(code)).to.be.false describe 'isIdentifierStart', -> it 'returns true if provided code can be a start of Identifier', -> characters = [ 'a' '$' '_' 'ใ‚†' ] for code in characters.map((ch) -> ch.charCodeAt(0)) expect(esutils.code.isIdentifierStart(code)).to.be.true it 'returns false if provided code cannot be a start of Identifier', -> for ch in [0..9] expect(esutils.code.isIdentifierStart((ch + '').charCodeAt(0))).to.be.false describe 'isIdentifierPart', -> it 'returns true if provided code can be a part of Identifier', -> characters = [ 'a' '_' '$' 'ใ‚†' ] for code in characters.map((ch) -> ch.charCodeAt(0)) expect(esutils.code.isIdentifierPart(code)).to.be.true for ch in [0..9] expect(esutils.code.isIdentifierPart((ch + '').charCodeAt(0))).to.be.true it 'returns false if provided code cannot be a part of Identifier', -> expect(esutils.code.isIdentifierPart('+'.charCodeAt(0))).to.be.false expect(esutils.code.isIdentifierPart('-'.charCodeAt(0))).to.be.false
true
# Copyright (C) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 'use strict' expect = require('chai').expect esutils = require '../' describe 'code', -> describe 'isDecimalDigit', -> it 'returns true if provided code is decimal digit', -> for ch in [0..9] expect(esutils.code.isDecimalDigit((ch + '').charCodeAt(0))).to.be.true it 'returns false if provided code is not decimal digit', -> for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isDecimalDigit(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isDecimalDigit(code)).to.be.false describe 'isHexDigit', -> it 'returns true if provided code is hexadecimal digit', -> for ch in [0..9] expect(esutils.code.isHexDigit((ch + '').charCodeAt(0))).to.be.true for code in ['a'.charCodeAt(0)..'f'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.true for code in ['A'.charCodeAt(0)..'F'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.true it 'returns false if provided code is not hexadecimal digit', -> for code in ['g'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.false for code in ['G'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isHexDigit(code)).to.be.false describe 'isOctalDigit', -> it 'returns true if provided code is octal digit', -> for ch in [0..7] expect(esutils.code.isOctalDigit((ch + '').charCodeAt(0))).to.be.true it 'returns false if provided code is not octal digit', -> for ch in [8..9] expect(esutils.code.isOctalDigit((ch + '').charCodeAt(0))).to.be.false for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isOctalDigit(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isOctalDigit(code)).to.be.false describe 'isWhiteSpace', -> it 'returns true if provided code is white space', -> codes = [ 0x0009 # TAB 0x000B # VT 0x000C # FF 0x0020 # SP 0x00A0 # NBSP 0xFEFF # BOM # Zs 0x1680 0x180E 0x2000 0x2001 0x2002 0x2003 0x2004 0x2005 0x2006 0x2007 0x2008 0x2009 0x200A 0x202F 0x205F 0x3000 ] for code in codes expect(esutils.code.isWhiteSpace(code)).to.be.true it 'returns false if provided code is not white space', -> for ch in [0..9] expect(esutils.code.isWhiteSpace((ch + '').charCodeAt(0))).to.be.false for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isWhiteSpace(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isWhiteSpace(code)).to.be.false describe 'isLineTerminator', -> it 'returns true if provided code is line terminator', -> codes = [ 0x000A 0x000D 0x2028 0x2029 ] for code in codes expect(esutils.code.isLineTerminator(code)).to.be.true it 'returns false if provided code is not line terminator', -> for ch in [0..9] expect(esutils.code.isLineTerminator((ch + '').charCodeAt(0))).to.be.false for code in ['a'.charCodeAt(0)..'z'.charCodeAt(0)] expect(esutils.code.isLineTerminator(code)).to.be.false for code in ['A'.charCodeAt(0)..'Z'.charCodeAt(0)] expect(esutils.code.isLineTerminator(code)).to.be.false describe 'isIdentifierStart', -> it 'returns true if provided code can be a start of Identifier', -> characters = [ 'a' '$' '_' 'ใ‚†' ] for code in characters.map((ch) -> ch.charCodeAt(0)) expect(esutils.code.isIdentifierStart(code)).to.be.true it 'returns false if provided code cannot be a start of Identifier', -> for ch in [0..9] expect(esutils.code.isIdentifierStart((ch + '').charCodeAt(0))).to.be.false describe 'isIdentifierPart', -> it 'returns true if provided code can be a part of Identifier', -> characters = [ 'a' '_' '$' 'ใ‚†' ] for code in characters.map((ch) -> ch.charCodeAt(0)) expect(esutils.code.isIdentifierPart(code)).to.be.true for ch in [0..9] expect(esutils.code.isIdentifierPart((ch + '').charCodeAt(0))).to.be.true it 'returns false if provided code cannot be a part of Identifier', -> expect(esutils.code.isIdentifierPart('+'.charCodeAt(0))).to.be.false expect(esutils.code.isIdentifierPart('-'.charCodeAt(0))).to.be.false
[ { "context": "yout and Drawing Framework 0.0.3alpha\n * (c) 2010 Philipp Strathausen <strathausen@gmail.com>, http://strathausen.eu\n *", "end": 94, "score": 0.9998912811279297, "start": 75, "tag": "NAME", "value": "Philipp Strathausen" }, { "context": "work 0.0.3alpha\n * (c) 2010 Philipp Strathausen <strathausen@gmail.com>, http://strathausen.eu\n * \n * Contributions by", "end": 117, "score": 0.999934196472168, "start": 96, "tag": "EMAIL", "value": "strathausen@gmail.com" }, { "context": "usen.eu\n * \n * Contributions by:\n * Branched by Jake Stothard <stothardj@gmail.com>.\n *\n * based on the Graph ", "end": 198, "score": 0.9998997449874878, "start": 185, "tag": "NAME", "value": "Jake Stothard" }, { "context": " Contributions by:\n * Branched by Jake Stothard <stothardj@gmail.com>.\n *\n * based on the Graph JavaScript framework,", "end": 219, "score": 0.9999343156814575, "start": 200, "tag": "EMAIL", "value": "stothardj@gmail.com" }, { "context": "h JavaScript framework, version 0.0.1\n * (c) 2006 Aslak Hellesoy <aslak.hellesoy@gmail.com>\n * (c) 2006 Dave Hoov", "end": 311, "score": 0.9998990297317505, "start": 297, "tag": "NAME", "value": "Aslak Hellesoy" }, { "context": "ework, version 0.0.1\n * (c) 2006 Aslak Hellesoy <aslak.hellesoy@gmail.com>\n * (c) 2006 Dave Hoover <dave.hoover@gmail.com>", "end": 337, "score": 0.9999338388442993, "start": 313, "tag": "EMAIL", "value": "aslak.hellesoy@gmail.com" }, { "context": "k Hellesoy <aslak.hellesoy@gmail.com>\n * (c) 2006 Dave Hoover <dave.hoover@gmail.com>\n *\n * Ported from Graph:", "end": 363, "score": 0.9998936653137207, "start": 352, "tag": "NAME", "value": "Dave Hoover" }, { "context": "lak.hellesoy@gmail.com>\n * (c) 2006 Dave Hoover <dave.hoover@gmail.com>\n *\n * Ported from Graph::Layouter::Spring in\n *", "end": 386, "score": 0.9999338388442993, "start": 365, "tag": "EMAIL", "value": "dave.hoover@gmail.com" }, { "context": "based social\n * network tracker PieSpy written by Paul Mutton E<lt>paul@jibble.orgE<gt>.\n *\n * This code is fr", "end": 617, "score": 0.9998947978019714, "start": 606, "tag": "NAME", "value": "Paul Mutton" }, { "context": "etwork tracker PieSpy written by Paul Mutton E<lt>paul@jibble.orgE<gt>.\n *\n * This code is freely distributable un", "end": 638, "score": 0.9999305605888367, "start": 623, "tag": "EMAIL", "value": "paul@jibble.org" } ]
js/dracula_graph.coffee
cutburn/presup_visualization
2
### * Dracula Graph Layout and Drawing Framework 0.0.3alpha * (c) 2010 Philipp Strathausen <strathausen@gmail.com>, http://strathausen.eu * * Contributions by: * Branched by Jake Stothard <stothardj@gmail.com>. * * based on the Graph JavaScript framework, version 0.0.1 * (c) 2006 Aslak Hellesoy <aslak.hellesoy@gmail.com> * (c) 2006 Dave Hoover <dave.hoover@gmail.com> * * Ported from Graph::Layouter::Spring in * http://search.cpan.org/~pasky/Graph-Layderer-0.02/ * The algorithm is based on a spring-style layouter of a Java-based social * network tracker PieSpy written by Paul Mutton E<lt>paul@jibble.orgE<gt>. * * This code is freely distributable under the terms of an MIT-style license. * For details, see the Graph web site: http://dev.buildpatternd.com/trac * * Links: * * Graph Dracula JavaScript Framework: * http://graphdracula.net * * Demo of the original applet: * http://redsquirrel.com/dave/work/webdep/ * * Mirrored original source code at snipplr: * http://snipplr.com/view/1950/graph-javascript-framework-version-001/ * * Original usage example: * http://ajaxian.com/archives/new-javascriptcanvas-graph-library * ### ### Edge Factory ### AbstractEdge = -> AbstractEdge.prototype = hide: -> @connection.fg.hide() @connection.bg && @bg.connection.hide() EdgeFactory = -> @template = new AbstractEdge() @template.style = new Object() @template.style.directed = false @template.weight = 1 EdgeFactory.prototype = build: (source, target) -> e = jQuery.extend true, {}, @template e.source = source e.target = target e ### Graph ### Graph = -> @nodes = {} @edges = [] @snapshots = [] # previous graph states TODO to be implemented @edgeFactory = new EdgeFactory() Graph.prototype = ### add a node @id the node's ID (string or number) @content (optional, dictionary) can contain any information that is being interpreted by the layout algorithm or the graph representation ### addNode: (id, content) -> # testing if node is already existing in the graph if @nodes[id] == undefined @nodes[id] = new Graph.Node id, content @nodes[id] addEdge: (source, target, style) -> s = @addNode source t = @addNode target var edge = @edgeFactory.build s, t jQuery.extend edge.style, style s.edges.push edge @edges.push edge # NOTE: Even directed edges are added to both nodes. t.edges.push edge # TODO to be implemented # Preserve a copy of the graph state (nodes, positions, ...) # @comment a comment describing the state snapShot: (comment) -> ###/* FIXME var graph = new Graph() graph.nodes = jQuery.extend(true, {}, @nodes) graph.edges = jQuery.extend(true, {}, @edges) @snapshots.push({comment: comment, graph: graph}) */ ### removeNode: (id) -> delete @nodes[id] for i = 0; i < @edges.length; i++ if @edges[i].source.id == id || @edges[i].target.id == id @edges.splice(i, 1) i-- /* * Node */ Graph.Node = (id, node) -> node = node || {} node.id = id node.edges = [] node.hide = -> @hidden = true @shape && @shape.hide() # FIXME this is representation specific code and should be elsewhere */ for(i in @edges) (@edges[i].source.id == id || @edges[i].target == id) && @edges[i].hide && @edges[i].hide() node.show = -> @hidden = false @shape && @shape.show() for(i in @edges) (@edges[i].source.id == id || @edges[i].target == id) && @edges[i].show && @edges[i].show() node Graph.Node.prototype = { } ### Renderer base class ### Graph.Renderer = { } ### Renderer implementation using RaphaelJS ### Graph.Renderer.Raphael = (element, graph, width, height) -> @width = width || 400 @height = height || 400 var selfRef = this @r = Raphael element, @width, @height @radius = 40 # max dimension of a node @graph = graph @mouse_in = false # TODO default node rendering if(!@graph.render) { @graph.render = -> return } } /* * Dragging */ @isDrag = false @dragger = (e) -> @dx = e.clientX @dy = e.clientY selfRef.isDrag = this @set && @set.animate "fill-opacity": .1, 200 && @set.toFront() e.preventDefault && e.preventDefault() document.onmousemove = (e) { e = e || window.event if (selfRef.isDrag) { var bBox = selfRef.isDrag.set.getBBox() // TODO round the coordinates here (eg. for proper image representation) var newX = e.clientX - selfRef.isDrag.dx + (bBox.x + bBox.width / 2) var newY = e.clientY - selfRef.isDrag.dy + (bBox.y + bBox.height / 2) /* prevent shapes from being dragged out of the canvas */ var clientX = e.clientX - (newX < 20 ? newX - 20 : newX > selfRef.width - 20 ? newX - selfRef.width + 20 : 0) var clientY = e.clientY - (newY < 20 ? newY - 20 : newY > selfRef.height - 20 ? newY - selfRef.height + 20 : 0) selfRef.isDrag.set.translate(clientX - Math.round(selfRef.isDrag.dx), clientY - Math.round(selfRef.isDrag.dy)) // console.log(clientX - Math.round(selfRef.isDrag.dx), clientY - Math.round(selfRef.isDrag.dy)) for (var i in selfRef.graph.edges) { selfRef.graph.edges[i].connection && selfRef.graph.edges[i].connection.draw() } //selfRef.r.safari() selfRef.isDrag.dx = clientX selfRef.isDrag.dy = clientY } } document.onmouseup = -> selfRef.isDrag && selfRef.isDrag.set.animate({"fill-opacity": .6}, 500) selfRef.isDrag = false } @draw() } Graph.Renderer.Raphael.prototype = { translate: (point) { return [ (point[0] - @graph.layoutMinX) * @factorX + @radius, (point[1] - @graph.layoutMinY) * @factorY + @radius ] }, rotate: (point, length, angle) { var dx = length * Math.cos(angle) var dy = length * Math.sin(angle) return [point[0]+dx, point[1]+dy] }, draw: -> @factorX = (@width - 2 * @radius) / (@graph.layoutMaxX - @graph.layoutMinX) @factorY = (@height - 2 * @radius) / (@graph.layoutMaxY - @graph.layoutMinY) for (i in @graph.nodes) { @drawNode(@graph.nodes[i]) } for (var i = 0; i < @graph.edges.length; i++) { @drawEdge(@graph.edges[i]) } }, drawNode: (node) { var point = @translate([node.layoutPosX, node.layoutPosY]) node.point = point /* if node has already been drawn, move the nodes */ if(node.shape) { var oBBox = node.shape.getBBox() var opoint = { x: oBBox.x + oBBox.width / 2, y: oBBox.y + oBBox.height / 2} node.shape.translate(Math.round(point[0] - opoint.x), Math.round(point[1] - opoint.y)) @r.safari() return node }/* else, draw new nodes */ var shape /* if a node renderer is provided by the user, then use it or the default render instead */ if(!node.render) { node.render = (r, node) { /* the default node drawing */ var color = Raphael.getColor() var ellipse = r.ellipse(0, 0, 30, 20).attr({fill: color, stroke: color, "stroke-width": 2}) /* set DOM node ID */ ellipse.node.id = node.label || node.id shape = r.set(). push(ellipse). push(r.text(0, 30, node.label || node.id)) return shape } } /* or check for an ajax representation of the nodes */ if(node.shapes) { // TODO ajax representation evaluation } shape = node.render(@r, node).hide() shape.attr({"fill-opacity": .6}) /* re-reference to the node an element belongs to, needed for dragging all elements of a node */ shape.items.forEach((item){ item.set = shape; item.node.style.cursor = "move"; }) shape.mousedown(@dragger) var box = shape.getBBox() shape.translate(Math.round(point[0]-(box.x+box.width/2)),Math.round(point[1]-(box.y+box.height/2))) //console.log(box,point) node.hidden || shape.show() node.shape = shape }, drawEdge: (edge) { /* if this edge already exists the other way around and is undirected */ if(edge.backedge) return if(edge.source.hidden || edge.target.hidden) { edge.connection && edge.connection.fg.hide() | edge.connection.bg && edge.connection.bg.hide() return } /* if edge already has been drawn, only refresh the edge */ if(!edge.connection) { edge.style && edge.style.callback && edge.style.callback(edge); // TODO move this somewhere else edge.connection = @r.connection(edge.source.shape, edge.target.shape, edge.style) return } //FIXME showing doesn't work well edge.connection.fg.show() edge.connection.bg && edge.connection.bg.show() edge.connection.draw() } } Graph.Layout = {} Graph.Layout.Spring = (graph) { @graph = graph @iterations = 500 @maxRepulsiveForceDistance = 6 @k = 2 @c = 0.01 @maxVertexMovement = 0.5 @layout() } Graph.Layout.Spring.prototype = { layout: -> @layoutPrepare() for (var i = 0; i < @iterations; i++) { @layoutIteration() } @layoutCalcBounds() }, layoutPrepare: -> for (i in @graph.nodes) { var node = @graph.nodes[i] node.layoutPosX = 0 node.layoutPosY = 0 node.layoutForceX = 0 node.layoutForceY = 0 } }, layoutCalcBounds: -> var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity for (i in @graph.nodes) { var x = @graph.nodes[i].layoutPosX var y = @graph.nodes[i].layoutPosY if(x > maxx) maxx = x if(x < minx) minx = x if(y > maxy) maxy = y if(y < miny) miny = y } @graph.layoutMinX = minx @graph.layoutMaxX = maxx @graph.layoutMinY = miny @graph.layoutMaxY = maxy }, layoutIteration: -> // Forces on nodes due to node-node repulsions var prev = new Array() for(var c in @graph.nodes) { var node1 = @graph.nodes[c] for (var d in prev) { var node2 = @graph.nodes[prev[d]] @layoutRepulsive(node1, node2) } prev.push(c) } // Forces on nodes due to edge attractions for (var i = 0; i < @graph.edges.length; i++) { var edge = @graph.edges[i] @layoutAttractive(edge); } // Move by the given force for (i in @graph.nodes) { var node = @graph.nodes[i] var xmove = @c * node.layoutForceX var ymove = @c * node.layoutForceY var max = @maxVertexMovement if(xmove > max) xmove = max if(xmove < -max) xmove = -max if(ymove > max) ymove = max if(ymove < -max) ymove = -max node.layoutPosX += xmove node.layoutPosY += ymove node.layoutForceX = 0 node.layoutForceY = 0 } }, layoutRepulsive: (node1, node2) { var dx = node2.layoutPosX - node1.layoutPosX var dy = node2.layoutPosY - node1.layoutPosY var d2 = dx * dx + dy * dy if(d2 < 0.01) { dx = 0.1 * Math.random() + 0.1 dy = 0.1 * Math.random() + 0.1 var d2 = dx * dx + dy * dy } var d = Math.sqrt(d2) if(d < @maxRepulsiveForceDistance) { var repulsiveForce = @k * @k / d node2.layoutForceX += repulsiveForce * dx / d node2.layoutForceY += repulsiveForce * dy / d node1.layoutForceX -= repulsiveForce * dx / d node1.layoutForceY -= repulsiveForce * dy / d } }, layoutAttractive: (edge) { var node1 = edge.source var node2 = edge.target var dx = node2.layoutPosX - node1.layoutPosX var dy = node2.layoutPosY - node1.layoutPosY var d2 = dx * dx + dy * dy if(d2 < 0.01) { dx = 0.1 * Math.random() + 0.1 dy = 0.1 * Math.random() + 0.1 var d2 = dx * dx + dy * dy } var d = Math.sqrt(d2) if(d > @maxRepulsiveForceDistance) { d = @maxRepulsiveForceDistance d2 = d * d } var attractiveForce = (d2 - @k * @k) / @k if(edge.attraction == undefined) edge.attraction = 1 attractiveForce *= Math.log(edge.attraction) * 0.5 + 1 node2.layoutForceX -= attractiveForce * dx / d node2.layoutForceY -= attractiveForce * dy / d node1.layoutForceX += attractiveForce * dx / d node1.layoutForceY += attractiveForce * dy / d } } Graph.Layout.Ordered = (graph, order) { @graph = graph @order = order @layout() } Graph.Layout.Ordered.prototype = { layout: -> @layoutPrepare() @layoutCalcBounds() }, layoutPrepare: (order) { for (i in @graph.nodes) { var node = @graph.nodes[i] node.layoutPosX = 0 node.layoutPosY = 0 } var counter = 0 for (i in @order) { var node = @order[i] node.layoutPosX = counter node.layoutPosY = Math.random() counter++ } }, layoutCalcBounds: -> var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity for (i in @graph.nodes) { var x = @graph.nodes[i].layoutPosX var y = @graph.nodes[i].layoutPosY if(x > maxx) maxx = x if(x < minx) minx = x if(y > maxy) maxy = y if(y < miny) miny = y } @graph.layoutMinX = minx @graph.layoutMaxX = maxx @graph.layoutMinY = miny @graph.layoutMaxY = maxy } } /* * usefull JavaScript extensions, */ log(a) {console.log&&console.log(a);} /* * Raphael Tooltip Plugin * - attaches an element as a tooltip to another element * * Usage example, adding a rectangle as a tooltip to a circle: * * paper.circle(100,100,10).tooltip(paper.rect(0,0,20,30)) * * If you want to use more shapes, you'll have to put them into a set. * */ Raphael.el.tooltip = (tp) { @tp = tp @tp.o = {x: 0, y: 0} @tp.hide() @hover( (event){ @mousemove((event){ @tp.translate(event.clientX - @tp.o.x,event.clientY - @tp.o.y) @tp.o = {x: event.clientX, y: event.clientY} }) @tp.show().toFront() }, (event){ @tp.hide() @unmousemove() }) return this } /* For IE */ if (!Array.prototype.forEach) { Array.prototype.forEach = (fun /*, thisp*/) { var len = @length if (typeof fun != "") throw new TypeError() var thisp = arguments[1] for (var i = 0; i < len; i++) { if (i in this) fun.call(thisp, this[i], i, this) } } }
150076
### * Dracula Graph Layout and Drawing Framework 0.0.3alpha * (c) 2010 <NAME> <<EMAIL>>, http://strathausen.eu * * Contributions by: * Branched by <NAME> <<EMAIL>>. * * based on the Graph JavaScript framework, version 0.0.1 * (c) 2006 <NAME> <<EMAIL>> * (c) 2006 <NAME> <<EMAIL>> * * Ported from Graph::Layouter::Spring in * http://search.cpan.org/~pasky/Graph-Layderer-0.02/ * The algorithm is based on a spring-style layouter of a Java-based social * network tracker PieSpy written by <NAME> E<lt><EMAIL>E<gt>. * * This code is freely distributable under the terms of an MIT-style license. * For details, see the Graph web site: http://dev.buildpatternd.com/trac * * Links: * * Graph Dracula JavaScript Framework: * http://graphdracula.net * * Demo of the original applet: * http://redsquirrel.com/dave/work/webdep/ * * Mirrored original source code at snipplr: * http://snipplr.com/view/1950/graph-javascript-framework-version-001/ * * Original usage example: * http://ajaxian.com/archives/new-javascriptcanvas-graph-library * ### ### Edge Factory ### AbstractEdge = -> AbstractEdge.prototype = hide: -> @connection.fg.hide() @connection.bg && @bg.connection.hide() EdgeFactory = -> @template = new AbstractEdge() @template.style = new Object() @template.style.directed = false @template.weight = 1 EdgeFactory.prototype = build: (source, target) -> e = jQuery.extend true, {}, @template e.source = source e.target = target e ### Graph ### Graph = -> @nodes = {} @edges = [] @snapshots = [] # previous graph states TODO to be implemented @edgeFactory = new EdgeFactory() Graph.prototype = ### add a node @id the node's ID (string or number) @content (optional, dictionary) can contain any information that is being interpreted by the layout algorithm or the graph representation ### addNode: (id, content) -> # testing if node is already existing in the graph if @nodes[id] == undefined @nodes[id] = new Graph.Node id, content @nodes[id] addEdge: (source, target, style) -> s = @addNode source t = @addNode target var edge = @edgeFactory.build s, t jQuery.extend edge.style, style s.edges.push edge @edges.push edge # NOTE: Even directed edges are added to both nodes. t.edges.push edge # TODO to be implemented # Preserve a copy of the graph state (nodes, positions, ...) # @comment a comment describing the state snapShot: (comment) -> ###/* FIXME var graph = new Graph() graph.nodes = jQuery.extend(true, {}, @nodes) graph.edges = jQuery.extend(true, {}, @edges) @snapshots.push({comment: comment, graph: graph}) */ ### removeNode: (id) -> delete @nodes[id] for i = 0; i < @edges.length; i++ if @edges[i].source.id == id || @edges[i].target.id == id @edges.splice(i, 1) i-- /* * Node */ Graph.Node = (id, node) -> node = node || {} node.id = id node.edges = [] node.hide = -> @hidden = true @shape && @shape.hide() # FIXME this is representation specific code and should be elsewhere */ for(i in @edges) (@edges[i].source.id == id || @edges[i].target == id) && @edges[i].hide && @edges[i].hide() node.show = -> @hidden = false @shape && @shape.show() for(i in @edges) (@edges[i].source.id == id || @edges[i].target == id) && @edges[i].show && @edges[i].show() node Graph.Node.prototype = { } ### Renderer base class ### Graph.Renderer = { } ### Renderer implementation using RaphaelJS ### Graph.Renderer.Raphael = (element, graph, width, height) -> @width = width || 400 @height = height || 400 var selfRef = this @r = Raphael element, @width, @height @radius = 40 # max dimension of a node @graph = graph @mouse_in = false # TODO default node rendering if(!@graph.render) { @graph.render = -> return } } /* * Dragging */ @isDrag = false @dragger = (e) -> @dx = e.clientX @dy = e.clientY selfRef.isDrag = this @set && @set.animate "fill-opacity": .1, 200 && @set.toFront() e.preventDefault && e.preventDefault() document.onmousemove = (e) { e = e || window.event if (selfRef.isDrag) { var bBox = selfRef.isDrag.set.getBBox() // TODO round the coordinates here (eg. for proper image representation) var newX = e.clientX - selfRef.isDrag.dx + (bBox.x + bBox.width / 2) var newY = e.clientY - selfRef.isDrag.dy + (bBox.y + bBox.height / 2) /* prevent shapes from being dragged out of the canvas */ var clientX = e.clientX - (newX < 20 ? newX - 20 : newX > selfRef.width - 20 ? newX - selfRef.width + 20 : 0) var clientY = e.clientY - (newY < 20 ? newY - 20 : newY > selfRef.height - 20 ? newY - selfRef.height + 20 : 0) selfRef.isDrag.set.translate(clientX - Math.round(selfRef.isDrag.dx), clientY - Math.round(selfRef.isDrag.dy)) // console.log(clientX - Math.round(selfRef.isDrag.dx), clientY - Math.round(selfRef.isDrag.dy)) for (var i in selfRef.graph.edges) { selfRef.graph.edges[i].connection && selfRef.graph.edges[i].connection.draw() } //selfRef.r.safari() selfRef.isDrag.dx = clientX selfRef.isDrag.dy = clientY } } document.onmouseup = -> selfRef.isDrag && selfRef.isDrag.set.animate({"fill-opacity": .6}, 500) selfRef.isDrag = false } @draw() } Graph.Renderer.Raphael.prototype = { translate: (point) { return [ (point[0] - @graph.layoutMinX) * @factorX + @radius, (point[1] - @graph.layoutMinY) * @factorY + @radius ] }, rotate: (point, length, angle) { var dx = length * Math.cos(angle) var dy = length * Math.sin(angle) return [point[0]+dx, point[1]+dy] }, draw: -> @factorX = (@width - 2 * @radius) / (@graph.layoutMaxX - @graph.layoutMinX) @factorY = (@height - 2 * @radius) / (@graph.layoutMaxY - @graph.layoutMinY) for (i in @graph.nodes) { @drawNode(@graph.nodes[i]) } for (var i = 0; i < @graph.edges.length; i++) { @drawEdge(@graph.edges[i]) } }, drawNode: (node) { var point = @translate([node.layoutPosX, node.layoutPosY]) node.point = point /* if node has already been drawn, move the nodes */ if(node.shape) { var oBBox = node.shape.getBBox() var opoint = { x: oBBox.x + oBBox.width / 2, y: oBBox.y + oBBox.height / 2} node.shape.translate(Math.round(point[0] - opoint.x), Math.round(point[1] - opoint.y)) @r.safari() return node }/* else, draw new nodes */ var shape /* if a node renderer is provided by the user, then use it or the default render instead */ if(!node.render) { node.render = (r, node) { /* the default node drawing */ var color = Raphael.getColor() var ellipse = r.ellipse(0, 0, 30, 20).attr({fill: color, stroke: color, "stroke-width": 2}) /* set DOM node ID */ ellipse.node.id = node.label || node.id shape = r.set(). push(ellipse). push(r.text(0, 30, node.label || node.id)) return shape } } /* or check for an ajax representation of the nodes */ if(node.shapes) { // TODO ajax representation evaluation } shape = node.render(@r, node).hide() shape.attr({"fill-opacity": .6}) /* re-reference to the node an element belongs to, needed for dragging all elements of a node */ shape.items.forEach((item){ item.set = shape; item.node.style.cursor = "move"; }) shape.mousedown(@dragger) var box = shape.getBBox() shape.translate(Math.round(point[0]-(box.x+box.width/2)),Math.round(point[1]-(box.y+box.height/2))) //console.log(box,point) node.hidden || shape.show() node.shape = shape }, drawEdge: (edge) { /* if this edge already exists the other way around and is undirected */ if(edge.backedge) return if(edge.source.hidden || edge.target.hidden) { edge.connection && edge.connection.fg.hide() | edge.connection.bg && edge.connection.bg.hide() return } /* if edge already has been drawn, only refresh the edge */ if(!edge.connection) { edge.style && edge.style.callback && edge.style.callback(edge); // TODO move this somewhere else edge.connection = @r.connection(edge.source.shape, edge.target.shape, edge.style) return } //FIXME showing doesn't work well edge.connection.fg.show() edge.connection.bg && edge.connection.bg.show() edge.connection.draw() } } Graph.Layout = {} Graph.Layout.Spring = (graph) { @graph = graph @iterations = 500 @maxRepulsiveForceDistance = 6 @k = 2 @c = 0.01 @maxVertexMovement = 0.5 @layout() } Graph.Layout.Spring.prototype = { layout: -> @layoutPrepare() for (var i = 0; i < @iterations; i++) { @layoutIteration() } @layoutCalcBounds() }, layoutPrepare: -> for (i in @graph.nodes) { var node = @graph.nodes[i] node.layoutPosX = 0 node.layoutPosY = 0 node.layoutForceX = 0 node.layoutForceY = 0 } }, layoutCalcBounds: -> var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity for (i in @graph.nodes) { var x = @graph.nodes[i].layoutPosX var y = @graph.nodes[i].layoutPosY if(x > maxx) maxx = x if(x < minx) minx = x if(y > maxy) maxy = y if(y < miny) miny = y } @graph.layoutMinX = minx @graph.layoutMaxX = maxx @graph.layoutMinY = miny @graph.layoutMaxY = maxy }, layoutIteration: -> // Forces on nodes due to node-node repulsions var prev = new Array() for(var c in @graph.nodes) { var node1 = @graph.nodes[c] for (var d in prev) { var node2 = @graph.nodes[prev[d]] @layoutRepulsive(node1, node2) } prev.push(c) } // Forces on nodes due to edge attractions for (var i = 0; i < @graph.edges.length; i++) { var edge = @graph.edges[i] @layoutAttractive(edge); } // Move by the given force for (i in @graph.nodes) { var node = @graph.nodes[i] var xmove = @c * node.layoutForceX var ymove = @c * node.layoutForceY var max = @maxVertexMovement if(xmove > max) xmove = max if(xmove < -max) xmove = -max if(ymove > max) ymove = max if(ymove < -max) ymove = -max node.layoutPosX += xmove node.layoutPosY += ymove node.layoutForceX = 0 node.layoutForceY = 0 } }, layoutRepulsive: (node1, node2) { var dx = node2.layoutPosX - node1.layoutPosX var dy = node2.layoutPosY - node1.layoutPosY var d2 = dx * dx + dy * dy if(d2 < 0.01) { dx = 0.1 * Math.random() + 0.1 dy = 0.1 * Math.random() + 0.1 var d2 = dx * dx + dy * dy } var d = Math.sqrt(d2) if(d < @maxRepulsiveForceDistance) { var repulsiveForce = @k * @k / d node2.layoutForceX += repulsiveForce * dx / d node2.layoutForceY += repulsiveForce * dy / d node1.layoutForceX -= repulsiveForce * dx / d node1.layoutForceY -= repulsiveForce * dy / d } }, layoutAttractive: (edge) { var node1 = edge.source var node2 = edge.target var dx = node2.layoutPosX - node1.layoutPosX var dy = node2.layoutPosY - node1.layoutPosY var d2 = dx * dx + dy * dy if(d2 < 0.01) { dx = 0.1 * Math.random() + 0.1 dy = 0.1 * Math.random() + 0.1 var d2 = dx * dx + dy * dy } var d = Math.sqrt(d2) if(d > @maxRepulsiveForceDistance) { d = @maxRepulsiveForceDistance d2 = d * d } var attractiveForce = (d2 - @k * @k) / @k if(edge.attraction == undefined) edge.attraction = 1 attractiveForce *= Math.log(edge.attraction) * 0.5 + 1 node2.layoutForceX -= attractiveForce * dx / d node2.layoutForceY -= attractiveForce * dy / d node1.layoutForceX += attractiveForce * dx / d node1.layoutForceY += attractiveForce * dy / d } } Graph.Layout.Ordered = (graph, order) { @graph = graph @order = order @layout() } Graph.Layout.Ordered.prototype = { layout: -> @layoutPrepare() @layoutCalcBounds() }, layoutPrepare: (order) { for (i in @graph.nodes) { var node = @graph.nodes[i] node.layoutPosX = 0 node.layoutPosY = 0 } var counter = 0 for (i in @order) { var node = @order[i] node.layoutPosX = counter node.layoutPosY = Math.random() counter++ } }, layoutCalcBounds: -> var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity for (i in @graph.nodes) { var x = @graph.nodes[i].layoutPosX var y = @graph.nodes[i].layoutPosY if(x > maxx) maxx = x if(x < minx) minx = x if(y > maxy) maxy = y if(y < miny) miny = y } @graph.layoutMinX = minx @graph.layoutMaxX = maxx @graph.layoutMinY = miny @graph.layoutMaxY = maxy } } /* * usefull JavaScript extensions, */ log(a) {console.log&&console.log(a);} /* * Raphael Tooltip Plugin * - attaches an element as a tooltip to another element * * Usage example, adding a rectangle as a tooltip to a circle: * * paper.circle(100,100,10).tooltip(paper.rect(0,0,20,30)) * * If you want to use more shapes, you'll have to put them into a set. * */ Raphael.el.tooltip = (tp) { @tp = tp @tp.o = {x: 0, y: 0} @tp.hide() @hover( (event){ @mousemove((event){ @tp.translate(event.clientX - @tp.o.x,event.clientY - @tp.o.y) @tp.o = {x: event.clientX, y: event.clientY} }) @tp.show().toFront() }, (event){ @tp.hide() @unmousemove() }) return this } /* For IE */ if (!Array.prototype.forEach) { Array.prototype.forEach = (fun /*, thisp*/) { var len = @length if (typeof fun != "") throw new TypeError() var thisp = arguments[1] for (var i = 0; i < len; i++) { if (i in this) fun.call(thisp, this[i], i, this) } } }
true
### * Dracula Graph Layout and Drawing Framework 0.0.3alpha * (c) 2010 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>, http://strathausen.eu * * Contributions by: * Branched by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>. * * based on the Graph JavaScript framework, version 0.0.1 * (c) 2006 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * (c) 2006 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * * Ported from Graph::Layouter::Spring in * http://search.cpan.org/~pasky/Graph-Layderer-0.02/ * The algorithm is based on a spring-style layouter of a Java-based social * network tracker PieSpy written by PI:NAME:<NAME>END_PI E<lt>PI:EMAIL:<EMAIL>END_PIE<gt>. * * This code is freely distributable under the terms of an MIT-style license. * For details, see the Graph web site: http://dev.buildpatternd.com/trac * * Links: * * Graph Dracula JavaScript Framework: * http://graphdracula.net * * Demo of the original applet: * http://redsquirrel.com/dave/work/webdep/ * * Mirrored original source code at snipplr: * http://snipplr.com/view/1950/graph-javascript-framework-version-001/ * * Original usage example: * http://ajaxian.com/archives/new-javascriptcanvas-graph-library * ### ### Edge Factory ### AbstractEdge = -> AbstractEdge.prototype = hide: -> @connection.fg.hide() @connection.bg && @bg.connection.hide() EdgeFactory = -> @template = new AbstractEdge() @template.style = new Object() @template.style.directed = false @template.weight = 1 EdgeFactory.prototype = build: (source, target) -> e = jQuery.extend true, {}, @template e.source = source e.target = target e ### Graph ### Graph = -> @nodes = {} @edges = [] @snapshots = [] # previous graph states TODO to be implemented @edgeFactory = new EdgeFactory() Graph.prototype = ### add a node @id the node's ID (string or number) @content (optional, dictionary) can contain any information that is being interpreted by the layout algorithm or the graph representation ### addNode: (id, content) -> # testing if node is already existing in the graph if @nodes[id] == undefined @nodes[id] = new Graph.Node id, content @nodes[id] addEdge: (source, target, style) -> s = @addNode source t = @addNode target var edge = @edgeFactory.build s, t jQuery.extend edge.style, style s.edges.push edge @edges.push edge # NOTE: Even directed edges are added to both nodes. t.edges.push edge # TODO to be implemented # Preserve a copy of the graph state (nodes, positions, ...) # @comment a comment describing the state snapShot: (comment) -> ###/* FIXME var graph = new Graph() graph.nodes = jQuery.extend(true, {}, @nodes) graph.edges = jQuery.extend(true, {}, @edges) @snapshots.push({comment: comment, graph: graph}) */ ### removeNode: (id) -> delete @nodes[id] for i = 0; i < @edges.length; i++ if @edges[i].source.id == id || @edges[i].target.id == id @edges.splice(i, 1) i-- /* * Node */ Graph.Node = (id, node) -> node = node || {} node.id = id node.edges = [] node.hide = -> @hidden = true @shape && @shape.hide() # FIXME this is representation specific code and should be elsewhere */ for(i in @edges) (@edges[i].source.id == id || @edges[i].target == id) && @edges[i].hide && @edges[i].hide() node.show = -> @hidden = false @shape && @shape.show() for(i in @edges) (@edges[i].source.id == id || @edges[i].target == id) && @edges[i].show && @edges[i].show() node Graph.Node.prototype = { } ### Renderer base class ### Graph.Renderer = { } ### Renderer implementation using RaphaelJS ### Graph.Renderer.Raphael = (element, graph, width, height) -> @width = width || 400 @height = height || 400 var selfRef = this @r = Raphael element, @width, @height @radius = 40 # max dimension of a node @graph = graph @mouse_in = false # TODO default node rendering if(!@graph.render) { @graph.render = -> return } } /* * Dragging */ @isDrag = false @dragger = (e) -> @dx = e.clientX @dy = e.clientY selfRef.isDrag = this @set && @set.animate "fill-opacity": .1, 200 && @set.toFront() e.preventDefault && e.preventDefault() document.onmousemove = (e) { e = e || window.event if (selfRef.isDrag) { var bBox = selfRef.isDrag.set.getBBox() // TODO round the coordinates here (eg. for proper image representation) var newX = e.clientX - selfRef.isDrag.dx + (bBox.x + bBox.width / 2) var newY = e.clientY - selfRef.isDrag.dy + (bBox.y + bBox.height / 2) /* prevent shapes from being dragged out of the canvas */ var clientX = e.clientX - (newX < 20 ? newX - 20 : newX > selfRef.width - 20 ? newX - selfRef.width + 20 : 0) var clientY = e.clientY - (newY < 20 ? newY - 20 : newY > selfRef.height - 20 ? newY - selfRef.height + 20 : 0) selfRef.isDrag.set.translate(clientX - Math.round(selfRef.isDrag.dx), clientY - Math.round(selfRef.isDrag.dy)) // console.log(clientX - Math.round(selfRef.isDrag.dx), clientY - Math.round(selfRef.isDrag.dy)) for (var i in selfRef.graph.edges) { selfRef.graph.edges[i].connection && selfRef.graph.edges[i].connection.draw() } //selfRef.r.safari() selfRef.isDrag.dx = clientX selfRef.isDrag.dy = clientY } } document.onmouseup = -> selfRef.isDrag && selfRef.isDrag.set.animate({"fill-opacity": .6}, 500) selfRef.isDrag = false } @draw() } Graph.Renderer.Raphael.prototype = { translate: (point) { return [ (point[0] - @graph.layoutMinX) * @factorX + @radius, (point[1] - @graph.layoutMinY) * @factorY + @radius ] }, rotate: (point, length, angle) { var dx = length * Math.cos(angle) var dy = length * Math.sin(angle) return [point[0]+dx, point[1]+dy] }, draw: -> @factorX = (@width - 2 * @radius) / (@graph.layoutMaxX - @graph.layoutMinX) @factorY = (@height - 2 * @radius) / (@graph.layoutMaxY - @graph.layoutMinY) for (i in @graph.nodes) { @drawNode(@graph.nodes[i]) } for (var i = 0; i < @graph.edges.length; i++) { @drawEdge(@graph.edges[i]) } }, drawNode: (node) { var point = @translate([node.layoutPosX, node.layoutPosY]) node.point = point /* if node has already been drawn, move the nodes */ if(node.shape) { var oBBox = node.shape.getBBox() var opoint = { x: oBBox.x + oBBox.width / 2, y: oBBox.y + oBBox.height / 2} node.shape.translate(Math.round(point[0] - opoint.x), Math.round(point[1] - opoint.y)) @r.safari() return node }/* else, draw new nodes */ var shape /* if a node renderer is provided by the user, then use it or the default render instead */ if(!node.render) { node.render = (r, node) { /* the default node drawing */ var color = Raphael.getColor() var ellipse = r.ellipse(0, 0, 30, 20).attr({fill: color, stroke: color, "stroke-width": 2}) /* set DOM node ID */ ellipse.node.id = node.label || node.id shape = r.set(). push(ellipse). push(r.text(0, 30, node.label || node.id)) return shape } } /* or check for an ajax representation of the nodes */ if(node.shapes) { // TODO ajax representation evaluation } shape = node.render(@r, node).hide() shape.attr({"fill-opacity": .6}) /* re-reference to the node an element belongs to, needed for dragging all elements of a node */ shape.items.forEach((item){ item.set = shape; item.node.style.cursor = "move"; }) shape.mousedown(@dragger) var box = shape.getBBox() shape.translate(Math.round(point[0]-(box.x+box.width/2)),Math.round(point[1]-(box.y+box.height/2))) //console.log(box,point) node.hidden || shape.show() node.shape = shape }, drawEdge: (edge) { /* if this edge already exists the other way around and is undirected */ if(edge.backedge) return if(edge.source.hidden || edge.target.hidden) { edge.connection && edge.connection.fg.hide() | edge.connection.bg && edge.connection.bg.hide() return } /* if edge already has been drawn, only refresh the edge */ if(!edge.connection) { edge.style && edge.style.callback && edge.style.callback(edge); // TODO move this somewhere else edge.connection = @r.connection(edge.source.shape, edge.target.shape, edge.style) return } //FIXME showing doesn't work well edge.connection.fg.show() edge.connection.bg && edge.connection.bg.show() edge.connection.draw() } } Graph.Layout = {} Graph.Layout.Spring = (graph) { @graph = graph @iterations = 500 @maxRepulsiveForceDistance = 6 @k = 2 @c = 0.01 @maxVertexMovement = 0.5 @layout() } Graph.Layout.Spring.prototype = { layout: -> @layoutPrepare() for (var i = 0; i < @iterations; i++) { @layoutIteration() } @layoutCalcBounds() }, layoutPrepare: -> for (i in @graph.nodes) { var node = @graph.nodes[i] node.layoutPosX = 0 node.layoutPosY = 0 node.layoutForceX = 0 node.layoutForceY = 0 } }, layoutCalcBounds: -> var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity for (i in @graph.nodes) { var x = @graph.nodes[i].layoutPosX var y = @graph.nodes[i].layoutPosY if(x > maxx) maxx = x if(x < minx) minx = x if(y > maxy) maxy = y if(y < miny) miny = y } @graph.layoutMinX = minx @graph.layoutMaxX = maxx @graph.layoutMinY = miny @graph.layoutMaxY = maxy }, layoutIteration: -> // Forces on nodes due to node-node repulsions var prev = new Array() for(var c in @graph.nodes) { var node1 = @graph.nodes[c] for (var d in prev) { var node2 = @graph.nodes[prev[d]] @layoutRepulsive(node1, node2) } prev.push(c) } // Forces on nodes due to edge attractions for (var i = 0; i < @graph.edges.length; i++) { var edge = @graph.edges[i] @layoutAttractive(edge); } // Move by the given force for (i in @graph.nodes) { var node = @graph.nodes[i] var xmove = @c * node.layoutForceX var ymove = @c * node.layoutForceY var max = @maxVertexMovement if(xmove > max) xmove = max if(xmove < -max) xmove = -max if(ymove > max) ymove = max if(ymove < -max) ymove = -max node.layoutPosX += xmove node.layoutPosY += ymove node.layoutForceX = 0 node.layoutForceY = 0 } }, layoutRepulsive: (node1, node2) { var dx = node2.layoutPosX - node1.layoutPosX var dy = node2.layoutPosY - node1.layoutPosY var d2 = dx * dx + dy * dy if(d2 < 0.01) { dx = 0.1 * Math.random() + 0.1 dy = 0.1 * Math.random() + 0.1 var d2 = dx * dx + dy * dy } var d = Math.sqrt(d2) if(d < @maxRepulsiveForceDistance) { var repulsiveForce = @k * @k / d node2.layoutForceX += repulsiveForce * dx / d node2.layoutForceY += repulsiveForce * dy / d node1.layoutForceX -= repulsiveForce * dx / d node1.layoutForceY -= repulsiveForce * dy / d } }, layoutAttractive: (edge) { var node1 = edge.source var node2 = edge.target var dx = node2.layoutPosX - node1.layoutPosX var dy = node2.layoutPosY - node1.layoutPosY var d2 = dx * dx + dy * dy if(d2 < 0.01) { dx = 0.1 * Math.random() + 0.1 dy = 0.1 * Math.random() + 0.1 var d2 = dx * dx + dy * dy } var d = Math.sqrt(d2) if(d > @maxRepulsiveForceDistance) { d = @maxRepulsiveForceDistance d2 = d * d } var attractiveForce = (d2 - @k * @k) / @k if(edge.attraction == undefined) edge.attraction = 1 attractiveForce *= Math.log(edge.attraction) * 0.5 + 1 node2.layoutForceX -= attractiveForce * dx / d node2.layoutForceY -= attractiveForce * dy / d node1.layoutForceX += attractiveForce * dx / d node1.layoutForceY += attractiveForce * dy / d } } Graph.Layout.Ordered = (graph, order) { @graph = graph @order = order @layout() } Graph.Layout.Ordered.prototype = { layout: -> @layoutPrepare() @layoutCalcBounds() }, layoutPrepare: (order) { for (i in @graph.nodes) { var node = @graph.nodes[i] node.layoutPosX = 0 node.layoutPosY = 0 } var counter = 0 for (i in @order) { var node = @order[i] node.layoutPosX = counter node.layoutPosY = Math.random() counter++ } }, layoutCalcBounds: -> var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity for (i in @graph.nodes) { var x = @graph.nodes[i].layoutPosX var y = @graph.nodes[i].layoutPosY if(x > maxx) maxx = x if(x < minx) minx = x if(y > maxy) maxy = y if(y < miny) miny = y } @graph.layoutMinX = minx @graph.layoutMaxX = maxx @graph.layoutMinY = miny @graph.layoutMaxY = maxy } } /* * usefull JavaScript extensions, */ log(a) {console.log&&console.log(a);} /* * Raphael Tooltip Plugin * - attaches an element as a tooltip to another element * * Usage example, adding a rectangle as a tooltip to a circle: * * paper.circle(100,100,10).tooltip(paper.rect(0,0,20,30)) * * If you want to use more shapes, you'll have to put them into a set. * */ Raphael.el.tooltip = (tp) { @tp = tp @tp.o = {x: 0, y: 0} @tp.hide() @hover( (event){ @mousemove((event){ @tp.translate(event.clientX - @tp.o.x,event.clientY - @tp.o.y) @tp.o = {x: event.clientX, y: event.clientY} }) @tp.show().toFront() }, (event){ @tp.hide() @unmousemove() }) return this } /* For IE */ if (!Array.prototype.forEach) { Array.prototype.forEach = (fun /*, thisp*/) { var len = @length if (typeof fun != "") throw new TypeError() var thisp = arguments[1] for (var i = 0; i < len; i++) { if (i in this) fun.call(thisp, this[i], i, this) } } }
[ { "context": "lient\n key: 'fedex-api-key'\n password: 'password'\n account: 'fedex-user'\n meter: 'what-c", "end": 505, "score": 0.9994840025901794, "start": 497, "tag": "PASSWORD", "value": "password" } ]
test/fedex.coffee
humm64/ship_new
0
fs = require 'fs' assert = require 'assert' should = require('chai').should() expect = require('chai').expect bond = require 'bondjs' {FedexClient} = require '../lib/fedex' {ShipperClient} = require '../lib/shipper' {Builder, Parser} = require 'xml2js' describe "fedex client", -> _fedexClient = null _xmlParser = new Parser() _xmlHeader = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' before -> _fedexClient = new FedexClient key: 'fedex-api-key' password: 'password' account: 'fedex-user' meter: 'what-can-brown-do-for-you' describe "generateRequest", -> _trackRequest = null before (done) -> trackXml = _fedexClient.generateRequest('1Z5678', 'eloquent shipit') _xmlParser.parseString trackXml, (err, data) -> _trackRequest = data?['ns:TrackRequest'] assert _trackRequest? done() it "contains the correct xml namespace and scheme location", -> _trackRequest.should.have.property '$' _trackRequest['$']['xmlns:ns'].should.equal 'http://fedex.com/ws/track/v5' _trackRequest['$']['xmlns:xsi'].should.equal 'http://www.w3.org/2001/XMLSchema-instance' _trackRequest['$']['xsi:schemaLocation'].should.equal 'http://fedex.com/ws/track/v4 TrackService_v4.xsd' it "contains correct api key and password", -> _trackRequest.should.have.property 'ns:WebAuthenticationDetail' credentials = _trackRequest['ns:WebAuthenticationDetail']?[0]?['ns:UserCredential']?[0] credentials['ns:Key']?[0].should.equal 'fedex-api-key' credentials['ns:Password']?[0].should.equal 'password' it "contains correct client detail", -> _trackRequest.should.have.property 'ns:ClientDetail' clientDetail = _trackRequest['ns:ClientDetail']?[0] clientDetail['ns:AccountNumber']?[0].should.equal 'fedex-user' clientDetail['ns:MeterNumber']?[0].should.equal 'what-can-brown-do-for-you' it "contains customer reference number", -> _trackRequest.should.have.property 'ns:TransactionDetail' _trackRequest['ns:TransactionDetail']?[0]?['ns:CustomerTransactionId'][0].should.equal 'eloquent shipit' it "contains tracking version information", -> _trackRequest.should.have.property 'ns:Version' version = _trackRequest['ns:Version']?[0] version['ns:ServiceId']?[0].should.equal 'trck' version['ns:Major']?[0].should.equal '5' version['ns:Intermediate']?[0].should.equal '0' version['ns:Minor']?[0].should.equal '0' it "contains tracking number", -> _trackRequest.should.have.property 'ns:PackageIdentifier' _trackRequest['ns:PackageIdentifier']?[0]['ns:Value'][0].should.equal '1Z5678' _trackRequest['ns:PackageIdentifier']?[0]['ns:Type'][0].should.equal 'TRACKING_NUMBER_OR_DOORTAG' it "contains appropriate flags", -> _trackRequest.should.have.property 'ns:IncludeDetailedScans' _trackRequest['ns:IncludeDetailedScans'][0].should.equal 'true' describe "requestOptions", -> _options = null _generateReq = null _generateReqSpy = null before -> _generateReqSpy = bond(_fedexClient, 'generateRequest') _generateReq = _generateReqSpy.through() _options = _fedexClient.requestOptions trackingNumber: '1ZMYTRACK123', reference: 'zappos' after -> _generateReqSpy.restore() it "creates a POST request", -> _options.method.should.equal 'POST' it "uses the correct URL", -> _options.uri.should.equal 'https://ws.fedex.com/xml' it "calls generateRequest with the correct parameters", -> _generateReq.calledWith('1ZMYTRACK123', 'zappos').should.equal true describe "validateResponse", -> it "returns an error if response is not an xml document", (done) -> errorReported = false _fedexClient.validateResponse 'bad xml', (err, resp) -> expect(err).should.exist done() unless errorReported errorReported = true it "returns an error if there's no track reply", (done) -> badResponse = '<RandomXml>Random</RandomXml>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> err.should.exist done() it "returns an error if track reply doesn't contain notifications", (done) -> badResponse = '<TrackReply xmlns="http://fedex.com/ws/track/v5" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><HighestSeverity>SUCCESS</HighestSeverity></TrackReply>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> err.should.exist done() it "returns an error when there are no success notifications", (done) -> badResponse = '<TrackReply xmlns="http://fedex.com/ws/track/v5" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><HighestSeverity>SUCCESS</HighestSeverity><Notifications><Severity>SUCCESS</Severity><Source>trck</Source><Code>1</Code><Message>Request was successfully processed.</Message><LocalizedMessage>Request was successfully processed.</LocalizedMessage></Notifications></TrackReply>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> err.should.exist done() it "returns track details when notifications indicate success", (done) -> badResponse = '<TrackReply xmlns="http://fedex.com/ws/track/v5" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><HighestSeverity>SUCCESS</HighestSeverity><Notifications><Severity>SUCCESS</Severity><Source>trck</Source><Code>0</Code><Message>Request was successfully processed.</Message><LocalizedMessage>Request was successfully processed.</LocalizedMessage></Notifications><TrackDetails>details</TrackDetails></TrackReply>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> expect(err).to.be.a 'null' expect(resp).to.equal 'details' done() describe "integration tests", -> _package = null describe "delivered package", -> before (done) -> fs.readFile 'test/stub_data/fedex_delivered.xml', 'utf8', (err, xmlDoc) -> _fedexClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delivered", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELIVERED it "has a service type of fedex priority overnight", -> expect(_package.service).to.equal 'FedEx Priority Overnight' it "has a weight of 0.2 LB", -> expect(_package.weight).to.equal '0.2 LB' it "has a destination of MD", -> expect(_package.destination).to.equal 'MD' it "has 7 activities", -> expect(_package.activities).to.have.length 7 it "has first activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2014-02-17T14:05:00.000Z' expect(act.datetime).to.equal '2014-02-17T09:05:00' expect(act.details).to.equal 'Delivered' expect(act.location).to.equal 'MD 21133' it "has last activity with timestamp, location and details", -> act = _package.activities[6] expect(act.timestamp).to.deep.equal new Date '2014-02-15T15:57:00.000Z' expect(act.details).to.equal 'Picked up' expect(act.location).to.equal 'East Hanover, NJ 07936' describe "in transit package with an activity with missing location", -> before (done) -> fs.readFile 'test/stub_data/fedex_missing_location.xml', 'utf8', (err, xmlDoc) -> _fedexClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of in-transit", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.EN_ROUTE it "has a service type of FedEx SmartPost", -> expect(_package.service).to.equal 'FedEx SmartPost' it "has a weight of 1.2 LB", -> expect(_package.weight).to.equal '1.2 LB' it "has a destination of Greenacres, WA", -> expect(_package.destination).to.equal 'Greenacres, WA' it "has 3 activities", -> expect(_package.activities).to.have.length 3 it "has first activity with location Troutdale, OR 97060", -> expect(_package.activities[0].location).to.equal 'Troutdale, OR 97060' it "has second activity with no location", -> should.not.exist(_package.activities[1].location)
181146
fs = require 'fs' assert = require 'assert' should = require('chai').should() expect = require('chai').expect bond = require 'bondjs' {FedexClient} = require '../lib/fedex' {ShipperClient} = require '../lib/shipper' {Builder, Parser} = require 'xml2js' describe "fedex client", -> _fedexClient = null _xmlParser = new Parser() _xmlHeader = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' before -> _fedexClient = new FedexClient key: 'fedex-api-key' password: '<PASSWORD>' account: 'fedex-user' meter: 'what-can-brown-do-for-you' describe "generateRequest", -> _trackRequest = null before (done) -> trackXml = _fedexClient.generateRequest('1Z5678', 'eloquent shipit') _xmlParser.parseString trackXml, (err, data) -> _trackRequest = data?['ns:TrackRequest'] assert _trackRequest? done() it "contains the correct xml namespace and scheme location", -> _trackRequest.should.have.property '$' _trackRequest['$']['xmlns:ns'].should.equal 'http://fedex.com/ws/track/v5' _trackRequest['$']['xmlns:xsi'].should.equal 'http://www.w3.org/2001/XMLSchema-instance' _trackRequest['$']['xsi:schemaLocation'].should.equal 'http://fedex.com/ws/track/v4 TrackService_v4.xsd' it "contains correct api key and password", -> _trackRequest.should.have.property 'ns:WebAuthenticationDetail' credentials = _trackRequest['ns:WebAuthenticationDetail']?[0]?['ns:UserCredential']?[0] credentials['ns:Key']?[0].should.equal 'fedex-api-key' credentials['ns:Password']?[0].should.equal 'password' it "contains correct client detail", -> _trackRequest.should.have.property 'ns:ClientDetail' clientDetail = _trackRequest['ns:ClientDetail']?[0] clientDetail['ns:AccountNumber']?[0].should.equal 'fedex-user' clientDetail['ns:MeterNumber']?[0].should.equal 'what-can-brown-do-for-you' it "contains customer reference number", -> _trackRequest.should.have.property 'ns:TransactionDetail' _trackRequest['ns:TransactionDetail']?[0]?['ns:CustomerTransactionId'][0].should.equal 'eloquent shipit' it "contains tracking version information", -> _trackRequest.should.have.property 'ns:Version' version = _trackRequest['ns:Version']?[0] version['ns:ServiceId']?[0].should.equal 'trck' version['ns:Major']?[0].should.equal '5' version['ns:Intermediate']?[0].should.equal '0' version['ns:Minor']?[0].should.equal '0' it "contains tracking number", -> _trackRequest.should.have.property 'ns:PackageIdentifier' _trackRequest['ns:PackageIdentifier']?[0]['ns:Value'][0].should.equal '1Z5678' _trackRequest['ns:PackageIdentifier']?[0]['ns:Type'][0].should.equal 'TRACKING_NUMBER_OR_DOORTAG' it "contains appropriate flags", -> _trackRequest.should.have.property 'ns:IncludeDetailedScans' _trackRequest['ns:IncludeDetailedScans'][0].should.equal 'true' describe "requestOptions", -> _options = null _generateReq = null _generateReqSpy = null before -> _generateReqSpy = bond(_fedexClient, 'generateRequest') _generateReq = _generateReqSpy.through() _options = _fedexClient.requestOptions trackingNumber: '1ZMYTRACK123', reference: 'zappos' after -> _generateReqSpy.restore() it "creates a POST request", -> _options.method.should.equal 'POST' it "uses the correct URL", -> _options.uri.should.equal 'https://ws.fedex.com/xml' it "calls generateRequest with the correct parameters", -> _generateReq.calledWith('1ZMYTRACK123', 'zappos').should.equal true describe "validateResponse", -> it "returns an error if response is not an xml document", (done) -> errorReported = false _fedexClient.validateResponse 'bad xml', (err, resp) -> expect(err).should.exist done() unless errorReported errorReported = true it "returns an error if there's no track reply", (done) -> badResponse = '<RandomXml>Random</RandomXml>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> err.should.exist done() it "returns an error if track reply doesn't contain notifications", (done) -> badResponse = '<TrackReply xmlns="http://fedex.com/ws/track/v5" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><HighestSeverity>SUCCESS</HighestSeverity></TrackReply>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> err.should.exist done() it "returns an error when there are no success notifications", (done) -> badResponse = '<TrackReply xmlns="http://fedex.com/ws/track/v5" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><HighestSeverity>SUCCESS</HighestSeverity><Notifications><Severity>SUCCESS</Severity><Source>trck</Source><Code>1</Code><Message>Request was successfully processed.</Message><LocalizedMessage>Request was successfully processed.</LocalizedMessage></Notifications></TrackReply>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> err.should.exist done() it "returns track details when notifications indicate success", (done) -> badResponse = '<TrackReply xmlns="http://fedex.com/ws/track/v5" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><HighestSeverity>SUCCESS</HighestSeverity><Notifications><Severity>SUCCESS</Severity><Source>trck</Source><Code>0</Code><Message>Request was successfully processed.</Message><LocalizedMessage>Request was successfully processed.</LocalizedMessage></Notifications><TrackDetails>details</TrackDetails></TrackReply>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> expect(err).to.be.a 'null' expect(resp).to.equal 'details' done() describe "integration tests", -> _package = null describe "delivered package", -> before (done) -> fs.readFile 'test/stub_data/fedex_delivered.xml', 'utf8', (err, xmlDoc) -> _fedexClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delivered", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELIVERED it "has a service type of fedex priority overnight", -> expect(_package.service).to.equal 'FedEx Priority Overnight' it "has a weight of 0.2 LB", -> expect(_package.weight).to.equal '0.2 LB' it "has a destination of MD", -> expect(_package.destination).to.equal 'MD' it "has 7 activities", -> expect(_package.activities).to.have.length 7 it "has first activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2014-02-17T14:05:00.000Z' expect(act.datetime).to.equal '2014-02-17T09:05:00' expect(act.details).to.equal 'Delivered' expect(act.location).to.equal 'MD 21133' it "has last activity with timestamp, location and details", -> act = _package.activities[6] expect(act.timestamp).to.deep.equal new Date '2014-02-15T15:57:00.000Z' expect(act.details).to.equal 'Picked up' expect(act.location).to.equal 'East Hanover, NJ 07936' describe "in transit package with an activity with missing location", -> before (done) -> fs.readFile 'test/stub_data/fedex_missing_location.xml', 'utf8', (err, xmlDoc) -> _fedexClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of in-transit", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.EN_ROUTE it "has a service type of FedEx SmartPost", -> expect(_package.service).to.equal 'FedEx SmartPost' it "has a weight of 1.2 LB", -> expect(_package.weight).to.equal '1.2 LB' it "has a destination of Greenacres, WA", -> expect(_package.destination).to.equal 'Greenacres, WA' it "has 3 activities", -> expect(_package.activities).to.have.length 3 it "has first activity with location Troutdale, OR 97060", -> expect(_package.activities[0].location).to.equal 'Troutdale, OR 97060' it "has second activity with no location", -> should.not.exist(_package.activities[1].location)
true
fs = require 'fs' assert = require 'assert' should = require('chai').should() expect = require('chai').expect bond = require 'bondjs' {FedexClient} = require '../lib/fedex' {ShipperClient} = require '../lib/shipper' {Builder, Parser} = require 'xml2js' describe "fedex client", -> _fedexClient = null _xmlParser = new Parser() _xmlHeader = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' before -> _fedexClient = new FedexClient key: 'fedex-api-key' password: 'PI:PASSWORD:<PASSWORD>END_PI' account: 'fedex-user' meter: 'what-can-brown-do-for-you' describe "generateRequest", -> _trackRequest = null before (done) -> trackXml = _fedexClient.generateRequest('1Z5678', 'eloquent shipit') _xmlParser.parseString trackXml, (err, data) -> _trackRequest = data?['ns:TrackRequest'] assert _trackRequest? done() it "contains the correct xml namespace and scheme location", -> _trackRequest.should.have.property '$' _trackRequest['$']['xmlns:ns'].should.equal 'http://fedex.com/ws/track/v5' _trackRequest['$']['xmlns:xsi'].should.equal 'http://www.w3.org/2001/XMLSchema-instance' _trackRequest['$']['xsi:schemaLocation'].should.equal 'http://fedex.com/ws/track/v4 TrackService_v4.xsd' it "contains correct api key and password", -> _trackRequest.should.have.property 'ns:WebAuthenticationDetail' credentials = _trackRequest['ns:WebAuthenticationDetail']?[0]?['ns:UserCredential']?[0] credentials['ns:Key']?[0].should.equal 'fedex-api-key' credentials['ns:Password']?[0].should.equal 'password' it "contains correct client detail", -> _trackRequest.should.have.property 'ns:ClientDetail' clientDetail = _trackRequest['ns:ClientDetail']?[0] clientDetail['ns:AccountNumber']?[0].should.equal 'fedex-user' clientDetail['ns:MeterNumber']?[0].should.equal 'what-can-brown-do-for-you' it "contains customer reference number", -> _trackRequest.should.have.property 'ns:TransactionDetail' _trackRequest['ns:TransactionDetail']?[0]?['ns:CustomerTransactionId'][0].should.equal 'eloquent shipit' it "contains tracking version information", -> _trackRequest.should.have.property 'ns:Version' version = _trackRequest['ns:Version']?[0] version['ns:ServiceId']?[0].should.equal 'trck' version['ns:Major']?[0].should.equal '5' version['ns:Intermediate']?[0].should.equal '0' version['ns:Minor']?[0].should.equal '0' it "contains tracking number", -> _trackRequest.should.have.property 'ns:PackageIdentifier' _trackRequest['ns:PackageIdentifier']?[0]['ns:Value'][0].should.equal '1Z5678' _trackRequest['ns:PackageIdentifier']?[0]['ns:Type'][0].should.equal 'TRACKING_NUMBER_OR_DOORTAG' it "contains appropriate flags", -> _trackRequest.should.have.property 'ns:IncludeDetailedScans' _trackRequest['ns:IncludeDetailedScans'][0].should.equal 'true' describe "requestOptions", -> _options = null _generateReq = null _generateReqSpy = null before -> _generateReqSpy = bond(_fedexClient, 'generateRequest') _generateReq = _generateReqSpy.through() _options = _fedexClient.requestOptions trackingNumber: '1ZMYTRACK123', reference: 'zappos' after -> _generateReqSpy.restore() it "creates a POST request", -> _options.method.should.equal 'POST' it "uses the correct URL", -> _options.uri.should.equal 'https://ws.fedex.com/xml' it "calls generateRequest with the correct parameters", -> _generateReq.calledWith('1ZMYTRACK123', 'zappos').should.equal true describe "validateResponse", -> it "returns an error if response is not an xml document", (done) -> errorReported = false _fedexClient.validateResponse 'bad xml', (err, resp) -> expect(err).should.exist done() unless errorReported errorReported = true it "returns an error if there's no track reply", (done) -> badResponse = '<RandomXml>Random</RandomXml>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> err.should.exist done() it "returns an error if track reply doesn't contain notifications", (done) -> badResponse = '<TrackReply xmlns="http://fedex.com/ws/track/v5" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><HighestSeverity>SUCCESS</HighestSeverity></TrackReply>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> err.should.exist done() it "returns an error when there are no success notifications", (done) -> badResponse = '<TrackReply xmlns="http://fedex.com/ws/track/v5" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><HighestSeverity>SUCCESS</HighestSeverity><Notifications><Severity>SUCCESS</Severity><Source>trck</Source><Code>1</Code><Message>Request was successfully processed.</Message><LocalizedMessage>Request was successfully processed.</LocalizedMessage></Notifications></TrackReply>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> err.should.exist done() it "returns track details when notifications indicate success", (done) -> badResponse = '<TrackReply xmlns="http://fedex.com/ws/track/v5" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><HighestSeverity>SUCCESS</HighestSeverity><Notifications><Severity>SUCCESS</Severity><Source>trck</Source><Code>0</Code><Message>Request was successfully processed.</Message><LocalizedMessage>Request was successfully processed.</LocalizedMessage></Notifications><TrackDetails>details</TrackDetails></TrackReply>' _fedexClient.validateResponse _xmlHeader + badResponse, (err, resp) -> expect(err).to.be.a 'null' expect(resp).to.equal 'details' done() describe "integration tests", -> _package = null describe "delivered package", -> before (done) -> fs.readFile 'test/stub_data/fedex_delivered.xml', 'utf8', (err, xmlDoc) -> _fedexClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delivered", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELIVERED it "has a service type of fedex priority overnight", -> expect(_package.service).to.equal 'FedEx Priority Overnight' it "has a weight of 0.2 LB", -> expect(_package.weight).to.equal '0.2 LB' it "has a destination of MD", -> expect(_package.destination).to.equal 'MD' it "has 7 activities", -> expect(_package.activities).to.have.length 7 it "has first activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2014-02-17T14:05:00.000Z' expect(act.datetime).to.equal '2014-02-17T09:05:00' expect(act.details).to.equal 'Delivered' expect(act.location).to.equal 'MD 21133' it "has last activity with timestamp, location and details", -> act = _package.activities[6] expect(act.timestamp).to.deep.equal new Date '2014-02-15T15:57:00.000Z' expect(act.details).to.equal 'Picked up' expect(act.location).to.equal 'East Hanover, NJ 07936' describe "in transit package with an activity with missing location", -> before (done) -> fs.readFile 'test/stub_data/fedex_missing_location.xml', 'utf8', (err, xmlDoc) -> _fedexClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of in-transit", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.EN_ROUTE it "has a service type of FedEx SmartPost", -> expect(_package.service).to.equal 'FedEx SmartPost' it "has a weight of 1.2 LB", -> expect(_package.weight).to.equal '1.2 LB' it "has a destination of Greenacres, WA", -> expect(_package.destination).to.equal 'Greenacres, WA' it "has 3 activities", -> expect(_package.activities).to.have.length 3 it "has first activity with location Troutdale, OR 97060", -> expect(_package.activities[0].location).to.equal 'Troutdale, OR 97060' it "has second activity with no location", -> should.not.exist(_package.activities[1].location)
[ { "context": "rs,<br><br>RSCVD team'\n @mail\n from: 'rscvd@oa.works'\n to: rec.email\n subject: 'RSCVD Re", "end": 1791, "score": 0.999927818775177, "start": 1777, "tag": "EMAIL", "value": "rscvd@oa.works" }, { "context": "push {resolver: resolver, url: resolves.url, user: @user?._id}\n res[r._id] = true\n else # does", "end": 3025, "score": 0.6141780018806458, "start": 3025, "tag": "USERNAME", "value": "" } ]
worker/src/rscvd.coffee
oaworks/api
0
P.svc ?= {} P.svc.rscvd = _index: true P.svc.rscvd.form = () -> if @keys(@params).length > 1 rec = @copy @params delete rec.form rec.status = 'Awaiting verification' try if rq = await @svc.rscvd.requestees 'email:"' + rec.email + '"' if rq?.verified or rq?.verification is 'Approved' rec.status = 'Verified' rec.verified = true else if rq?.denied or rq?.verification is 'Denied' rec.status = 'Denied' rec.verified = false if rec.status is 'Awaiting verification' # not yet found in pre-verified list try av = await @svc.rscvd 'email:"' + rec.email + '" AND verified:*' if av?.hits?.hits and av.hits.hits[0]._source.verified is true rec.status = 'Verified' rec.verified = true else if av.hits.hits[0]._source.verified is false rec.status = 'Denied' rec.verified = false rec.type ?= 'paper' try rec.createdAt = new Date() try rec.neededAt = await @epoch rec['needed-by'] rec._id = await @svc.rscvd rec try txt = 'Hi ' + rec.name + ',<br><br>We got your request:<br><br>Title: ' + (rec.atitle ? rec.title ? 'Unknown') + '\nReference (if provided): ' + (rec.reference ? '') + '<br><br>' txt += 'If at any point you no longer need this item, please <a href="https://' + (if @S.dev then 'dev.' else '') + 'rscvd.org/cancel?id=' + rec._id + '">cancel your request</a>, it only takes a second.<br><br>' txt += 'Our team of volunteers will try and fill your request as soon as possible. If you would like to thank us, please consider <a href="https://rscvd.org/volunteer">joining us in helping supply requests</a>.<br><br>' txt += 'Yours,<br><br>RSCVD team' @mail from: 'rscvd@oa.works' to: rec.email subject: 'RSCVD Request Receipt' text: txt return rec else return P.svc.rscvd.requestees = _index: true _auth: true _prefix: false _sheet: '1GuIH-Onf0A0dXFokH6Ma0cS0TRbbpAeOyhDVpmDNDNw' P.svc.rscvd.resolves = (rid, resolver) -> rid ?= @params.resolves resolver ?= @params.resolver if rid rec = if typeof rid is 'object' then rid else await @svc.rscvd rid # can pass the ID of a specific record to resolve else recs = await @svc.rscvd '(status:"Awaiting verification" OR status:"Verified" OR status:"In progress" OR status:"Awaiting Peter") AND NOT resolved:"' + resolver + '" AND NOT unresolved:"' + resolver + '"' res = {} for r in (if rec? then [rec] else (recs?.hits?.hits ? [])) if r._source? rec = r._source rec._id ?= r._id meta = @copy rec meta.journal = meta.title if meta.title meta.title = meta.atitle if meta.atitle resolves = await @ill.subscription {subscription: resolver}, meta # should send the metadata in the record if resolves?.url # if resolves rec.resolved ?= [] rec.resolved.push resolver rec.resolves ?= [] rec.resolves.push {resolver: resolver, url: resolves.url, user: @user?._id} res[r._id] = true else # does not resolve rec.unresolved ?= [] rec.unresolved.push resolver res[r._id] = false @svc.rscvd rec return if rid and res[rid] then res[rid] else res P.svc.rscvd.cancel = () -> return undefined if not @params.cancel rec = await @svc.rscvd @params.cancel rec.status = 'Cancelled' @svc.rscvd rec return rec P.svc.rscvd.verify = (email, verify=true) -> email ?= @params.verify return undefined if not email re = await @svc.rscvd.requestees 'email:"' + email + '"' re = re.hits.hits[0]._source if re?.hits?.total is 1 re = undefined if re?.hits? re ?= email: email, createdAt: Date.now() if verify re.verified = true re.verified_by = @user.email else re.denied = true re.denied_by = @user.email @waitUntil @svc.rscvd.requestees re await @svc.rscvd._each 'email:"' + email + '"', {action: 'index'}, (rec) -> if not rec.status or rec.status is 'Awaiting verification' rec.verified = verify if verify rec.status = 'Verified' rec.verified_by = @user.email else rec.status = 'Denied' rec.denied_by = @user.email return rec return true P.svc.rscvd.verify._auth = true P.svc.rscvd.deny = () -> return @svc.rscvd.verify @params.deny, false P.svc.rscvd.deny._auth = true P.svc.rscvd.status = () -> return undefined if not @params.status [rid, status] = @params.status.split '/' rec = await @svc.rscvd rid rec.status = status try if rec.status is 'Done' rec.done_by = @user.email else if rec.status is 'In Progress' rec.progressed_by = @user.email @svc.rscvd rec return rec P.svc.rscvd.status._auth = true P.svc.rscvd.poll = (poll, which) -> @nolog = true poll ?= @params.poll ? (Date.now() - 180000) # default to changes in last 3 mins which = @params.which ? ['new', 'verify', 'deny', 'cancel', 'status', 'overdue'] which = which.split(',') if typeof which is 'string' @svc.rscvd.overdue() if 'overdue' in which res = new: [], verify: [], deny: [], cancel: [], status: {} if 'new' in which nn = await @svc.rscvd '(status:"Awaiting verification" OR status:"Verified") AND createdAt:>' + poll, 500 for n in nn?.hits?.hits ? [] n._source._id ?= n._id res.new.push n._source if 'verify' in which vs = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.verify"', {sort: {createdAt: 'desc'}, size: 500} for v in vs.hits.hits vn = v._source.parts.pop() res.verify.push(vn) if vn not in res.verify if 'deny' in which ds = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.deny"', {sort: {createdAt: 'desc'}, size: 500} for d in ds.hits.hits dn = d._source.parts.pop() res.deny.push(dn) if dn not in res.deny if 'cancel' in which cc = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.cancel"', {sort: {createdAt: 'desc'}, size: 500} for c in cc.hits.hits cn = c._source.parts.pop() res.cancel.push(cn) if cn not in res.cancel # TODO need to track changes to Overdue status as well if 'status' in which ss = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.status"', {sort: {createdAt: 'desc'}, size: 500} for s in ss.hits.hits st = s._source.parts.pop() res.status[s._source.parts.pop()] ?= st # only return the most recent status change for a given record ID return res P.svc.rscvd.overdue = () -> counter = 0 dn = Date.now() recs = [] if @params.overdue recs.push await @svc.rscvd @params.overdue else res = await @svc.rscvd '(status:"Awaiting verification" OR status:"Verified") AND (neededAt:<' + dn + ' OR createdAt:<' + (dn - 1209600000) + ')', 10000 for r in res.hits.hits r._source._id ?= r._id recs.push r._source for rec in recs rec.status = 'Overdue' @waitUntil @svc.rscvd rec counter += 1 return counter
112224
P.svc ?= {} P.svc.rscvd = _index: true P.svc.rscvd.form = () -> if @keys(@params).length > 1 rec = @copy @params delete rec.form rec.status = 'Awaiting verification' try if rq = await @svc.rscvd.requestees 'email:"' + rec.email + '"' if rq?.verified or rq?.verification is 'Approved' rec.status = 'Verified' rec.verified = true else if rq?.denied or rq?.verification is 'Denied' rec.status = 'Denied' rec.verified = false if rec.status is 'Awaiting verification' # not yet found in pre-verified list try av = await @svc.rscvd 'email:"' + rec.email + '" AND verified:*' if av?.hits?.hits and av.hits.hits[0]._source.verified is true rec.status = 'Verified' rec.verified = true else if av.hits.hits[0]._source.verified is false rec.status = 'Denied' rec.verified = false rec.type ?= 'paper' try rec.createdAt = new Date() try rec.neededAt = await @epoch rec['needed-by'] rec._id = await @svc.rscvd rec try txt = 'Hi ' + rec.name + ',<br><br>We got your request:<br><br>Title: ' + (rec.atitle ? rec.title ? 'Unknown') + '\nReference (if provided): ' + (rec.reference ? '') + '<br><br>' txt += 'If at any point you no longer need this item, please <a href="https://' + (if @S.dev then 'dev.' else '') + 'rscvd.org/cancel?id=' + rec._id + '">cancel your request</a>, it only takes a second.<br><br>' txt += 'Our team of volunteers will try and fill your request as soon as possible. If you would like to thank us, please consider <a href="https://rscvd.org/volunteer">joining us in helping supply requests</a>.<br><br>' txt += 'Yours,<br><br>RSCVD team' @mail from: '<EMAIL>' to: rec.email subject: 'RSCVD Request Receipt' text: txt return rec else return P.svc.rscvd.requestees = _index: true _auth: true _prefix: false _sheet: '1GuIH-Onf0A0dXFokH6Ma0cS0TRbbpAeOyhDVpmDNDNw' P.svc.rscvd.resolves = (rid, resolver) -> rid ?= @params.resolves resolver ?= @params.resolver if rid rec = if typeof rid is 'object' then rid else await @svc.rscvd rid # can pass the ID of a specific record to resolve else recs = await @svc.rscvd '(status:"Awaiting verification" OR status:"Verified" OR status:"In progress" OR status:"Awaiting Peter") AND NOT resolved:"' + resolver + '" AND NOT unresolved:"' + resolver + '"' res = {} for r in (if rec? then [rec] else (recs?.hits?.hits ? [])) if r._source? rec = r._source rec._id ?= r._id meta = @copy rec meta.journal = meta.title if meta.title meta.title = meta.atitle if meta.atitle resolves = await @ill.subscription {subscription: resolver}, meta # should send the metadata in the record if resolves?.url # if resolves rec.resolved ?= [] rec.resolved.push resolver rec.resolves ?= [] rec.resolves.push {resolver: resolver, url: resolves.url, user: @user?._id} res[r._id] = true else # does not resolve rec.unresolved ?= [] rec.unresolved.push resolver res[r._id] = false @svc.rscvd rec return if rid and res[rid] then res[rid] else res P.svc.rscvd.cancel = () -> return undefined if not @params.cancel rec = await @svc.rscvd @params.cancel rec.status = 'Cancelled' @svc.rscvd rec return rec P.svc.rscvd.verify = (email, verify=true) -> email ?= @params.verify return undefined if not email re = await @svc.rscvd.requestees 'email:"' + email + '"' re = re.hits.hits[0]._source if re?.hits?.total is 1 re = undefined if re?.hits? re ?= email: email, createdAt: Date.now() if verify re.verified = true re.verified_by = @user.email else re.denied = true re.denied_by = @user.email @waitUntil @svc.rscvd.requestees re await @svc.rscvd._each 'email:"' + email + '"', {action: 'index'}, (rec) -> if not rec.status or rec.status is 'Awaiting verification' rec.verified = verify if verify rec.status = 'Verified' rec.verified_by = @user.email else rec.status = 'Denied' rec.denied_by = @user.email return rec return true P.svc.rscvd.verify._auth = true P.svc.rscvd.deny = () -> return @svc.rscvd.verify @params.deny, false P.svc.rscvd.deny._auth = true P.svc.rscvd.status = () -> return undefined if not @params.status [rid, status] = @params.status.split '/' rec = await @svc.rscvd rid rec.status = status try if rec.status is 'Done' rec.done_by = @user.email else if rec.status is 'In Progress' rec.progressed_by = @user.email @svc.rscvd rec return rec P.svc.rscvd.status._auth = true P.svc.rscvd.poll = (poll, which) -> @nolog = true poll ?= @params.poll ? (Date.now() - 180000) # default to changes in last 3 mins which = @params.which ? ['new', 'verify', 'deny', 'cancel', 'status', 'overdue'] which = which.split(',') if typeof which is 'string' @svc.rscvd.overdue() if 'overdue' in which res = new: [], verify: [], deny: [], cancel: [], status: {} if 'new' in which nn = await @svc.rscvd '(status:"Awaiting verification" OR status:"Verified") AND createdAt:>' + poll, 500 for n in nn?.hits?.hits ? [] n._source._id ?= n._id res.new.push n._source if 'verify' in which vs = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.verify"', {sort: {createdAt: 'desc'}, size: 500} for v in vs.hits.hits vn = v._source.parts.pop() res.verify.push(vn) if vn not in res.verify if 'deny' in which ds = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.deny"', {sort: {createdAt: 'desc'}, size: 500} for d in ds.hits.hits dn = d._source.parts.pop() res.deny.push(dn) if dn not in res.deny if 'cancel' in which cc = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.cancel"', {sort: {createdAt: 'desc'}, size: 500} for c in cc.hits.hits cn = c._source.parts.pop() res.cancel.push(cn) if cn not in res.cancel # TODO need to track changes to Overdue status as well if 'status' in which ss = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.status"', {sort: {createdAt: 'desc'}, size: 500} for s in ss.hits.hits st = s._source.parts.pop() res.status[s._source.parts.pop()] ?= st # only return the most recent status change for a given record ID return res P.svc.rscvd.overdue = () -> counter = 0 dn = Date.now() recs = [] if @params.overdue recs.push await @svc.rscvd @params.overdue else res = await @svc.rscvd '(status:"Awaiting verification" OR status:"Verified") AND (neededAt:<' + dn + ' OR createdAt:<' + (dn - 1209600000) + ')', 10000 for r in res.hits.hits r._source._id ?= r._id recs.push r._source for rec in recs rec.status = 'Overdue' @waitUntil @svc.rscvd rec counter += 1 return counter
true
P.svc ?= {} P.svc.rscvd = _index: true P.svc.rscvd.form = () -> if @keys(@params).length > 1 rec = @copy @params delete rec.form rec.status = 'Awaiting verification' try if rq = await @svc.rscvd.requestees 'email:"' + rec.email + '"' if rq?.verified or rq?.verification is 'Approved' rec.status = 'Verified' rec.verified = true else if rq?.denied or rq?.verification is 'Denied' rec.status = 'Denied' rec.verified = false if rec.status is 'Awaiting verification' # not yet found in pre-verified list try av = await @svc.rscvd 'email:"' + rec.email + '" AND verified:*' if av?.hits?.hits and av.hits.hits[0]._source.verified is true rec.status = 'Verified' rec.verified = true else if av.hits.hits[0]._source.verified is false rec.status = 'Denied' rec.verified = false rec.type ?= 'paper' try rec.createdAt = new Date() try rec.neededAt = await @epoch rec['needed-by'] rec._id = await @svc.rscvd rec try txt = 'Hi ' + rec.name + ',<br><br>We got your request:<br><br>Title: ' + (rec.atitle ? rec.title ? 'Unknown') + '\nReference (if provided): ' + (rec.reference ? '') + '<br><br>' txt += 'If at any point you no longer need this item, please <a href="https://' + (if @S.dev then 'dev.' else '') + 'rscvd.org/cancel?id=' + rec._id + '">cancel your request</a>, it only takes a second.<br><br>' txt += 'Our team of volunteers will try and fill your request as soon as possible. If you would like to thank us, please consider <a href="https://rscvd.org/volunteer">joining us in helping supply requests</a>.<br><br>' txt += 'Yours,<br><br>RSCVD team' @mail from: 'PI:EMAIL:<EMAIL>END_PI' to: rec.email subject: 'RSCVD Request Receipt' text: txt return rec else return P.svc.rscvd.requestees = _index: true _auth: true _prefix: false _sheet: '1GuIH-Onf0A0dXFokH6Ma0cS0TRbbpAeOyhDVpmDNDNw' P.svc.rscvd.resolves = (rid, resolver) -> rid ?= @params.resolves resolver ?= @params.resolver if rid rec = if typeof rid is 'object' then rid else await @svc.rscvd rid # can pass the ID of a specific record to resolve else recs = await @svc.rscvd '(status:"Awaiting verification" OR status:"Verified" OR status:"In progress" OR status:"Awaiting Peter") AND NOT resolved:"' + resolver + '" AND NOT unresolved:"' + resolver + '"' res = {} for r in (if rec? then [rec] else (recs?.hits?.hits ? [])) if r._source? rec = r._source rec._id ?= r._id meta = @copy rec meta.journal = meta.title if meta.title meta.title = meta.atitle if meta.atitle resolves = await @ill.subscription {subscription: resolver}, meta # should send the metadata in the record if resolves?.url # if resolves rec.resolved ?= [] rec.resolved.push resolver rec.resolves ?= [] rec.resolves.push {resolver: resolver, url: resolves.url, user: @user?._id} res[r._id] = true else # does not resolve rec.unresolved ?= [] rec.unresolved.push resolver res[r._id] = false @svc.rscvd rec return if rid and res[rid] then res[rid] else res P.svc.rscvd.cancel = () -> return undefined if not @params.cancel rec = await @svc.rscvd @params.cancel rec.status = 'Cancelled' @svc.rscvd rec return rec P.svc.rscvd.verify = (email, verify=true) -> email ?= @params.verify return undefined if not email re = await @svc.rscvd.requestees 'email:"' + email + '"' re = re.hits.hits[0]._source if re?.hits?.total is 1 re = undefined if re?.hits? re ?= email: email, createdAt: Date.now() if verify re.verified = true re.verified_by = @user.email else re.denied = true re.denied_by = @user.email @waitUntil @svc.rscvd.requestees re await @svc.rscvd._each 'email:"' + email + '"', {action: 'index'}, (rec) -> if not rec.status or rec.status is 'Awaiting verification' rec.verified = verify if verify rec.status = 'Verified' rec.verified_by = @user.email else rec.status = 'Denied' rec.denied_by = @user.email return rec return true P.svc.rscvd.verify._auth = true P.svc.rscvd.deny = () -> return @svc.rscvd.verify @params.deny, false P.svc.rscvd.deny._auth = true P.svc.rscvd.status = () -> return undefined if not @params.status [rid, status] = @params.status.split '/' rec = await @svc.rscvd rid rec.status = status try if rec.status is 'Done' rec.done_by = @user.email else if rec.status is 'In Progress' rec.progressed_by = @user.email @svc.rscvd rec return rec P.svc.rscvd.status._auth = true P.svc.rscvd.poll = (poll, which) -> @nolog = true poll ?= @params.poll ? (Date.now() - 180000) # default to changes in last 3 mins which = @params.which ? ['new', 'verify', 'deny', 'cancel', 'status', 'overdue'] which = which.split(',') if typeof which is 'string' @svc.rscvd.overdue() if 'overdue' in which res = new: [], verify: [], deny: [], cancel: [], status: {} if 'new' in which nn = await @svc.rscvd '(status:"Awaiting verification" OR status:"Verified") AND createdAt:>' + poll, 500 for n in nn?.hits?.hits ? [] n._source._id ?= n._id res.new.push n._source if 'verify' in which vs = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.verify"', {sort: {createdAt: 'desc'}, size: 500} for v in vs.hits.hits vn = v._source.parts.pop() res.verify.push(vn) if vn not in res.verify if 'deny' in which ds = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.deny"', {sort: {createdAt: 'desc'}, size: 500} for d in ds.hits.hits dn = d._source.parts.pop() res.deny.push(dn) if dn not in res.deny if 'cancel' in which cc = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.cancel"', {sort: {createdAt: 'desc'}, size: 500} for c in cc.hits.hits cn = c._source.parts.pop() res.cancel.push(cn) if cn not in res.cancel # TODO need to track changes to Overdue status as well if 'status' in which ss = await @index 'logs', 'createdAt:>' + poll + ' AND fn:"svc.rscvd.status"', {sort: {createdAt: 'desc'}, size: 500} for s in ss.hits.hits st = s._source.parts.pop() res.status[s._source.parts.pop()] ?= st # only return the most recent status change for a given record ID return res P.svc.rscvd.overdue = () -> counter = 0 dn = Date.now() recs = [] if @params.overdue recs.push await @svc.rscvd @params.overdue else res = await @svc.rscvd '(status:"Awaiting verification" OR status:"Verified") AND (neededAt:<' + dn + ' OR createdAt:<' + (dn - 1209600000) + ')', 10000 for r in res.hits.hits r._source._id ?= r._id recs.push r._source for rec in recs rec.status = 'Overdue' @waitUntil @svc.rscvd rec counter += 1 return counter
[ { "context": "ink it does you can request a takedown by emailing help@openaccessbutton.org.'\n meta =\n title: params.metadata.title ?", "end": 3836, "score": 0.9999260902404785, "start": 3811, "tag": "EMAIL", "value": "help@openaccessbutton.org" }, { "context": " when undefined if no file is given\n bcc = ['joe@oa.works']\n tos = []\n if typeof uc?.owner is 'st", "end": 9063, "score": 0.9997556805610657, "start": 9051, "tag": "EMAIL", "value": "joe@oa.works" }, { "context": " tmpl = tmpl.content\n\n ml =\n from: 'deposits@oa.works'\n to: tos\n template: tmpl\n v", "end": 10097, "score": 0.9998932480812073, "start": 10080, "tag": "EMAIL", "value": "deposits@oa.works" }, { "context": " # dev https://docs.google.com/spreadsheets/d/1XA29lqVPCJ2FQ6siLywahxBTLFaDCZKaN5qUeoTuApg/edit#gid=0\n # live https://docs.google.com/s", "end": 15804, "score": 0.976195216178894, "start": 15760, "tag": "KEY", "value": "1XA29lqVPCJ2FQ6siLywahxBTLFaDCZKaN5qUeoTuApg" }, { "context": " # live https://docs.google.com/spreadsheets/d/10DNDmOG19shNnuw6cwtCpK-sBnexRCCtD4WnxJx_DPQ/edit#gid=0\n for l in await @src.google.sheet", "end": 15912, "score": 0.9769896268844604, "start": 15868, "tag": "KEY", "value": "10DNDmOG19shNnuw6cwtCpK-sBnexRCCtD4WnxJx_DPQ" }, { "context": "or l in await @src.google.sheets (if @S.dev then '1XA29lqVPCJ2FQ6siLywahxBTLFaDCZKaN5qUeoTuApg' else '10DNDmOG19shNnuw6cwtCpK-sBnexRCCtD4WnxJx_D", "end": 16025, "score": 0.9722647070884705, "start": 15981, "tag": "KEY", "value": "1XA29lqVPCJ2FQ6siLywahxBTLFaDCZKaN5qUeoTuApg" }, { "context": "A29lqVPCJ2FQ6siLywahxBTLFaDCZKaN5qUeoTuApg' else '10DNDmOG19shNnuw6cwtCpK-sBnexRCCtD4WnxJx_DPQ')\n try\n f.version_evidence.string", "end": 16077, "score": 0.9880717396736145, "start": 16033, "tag": "KEY", "value": "10DNDmOG19shNnuw6cwtCpK-sBnexRCCtD4WnxJx_DPQ" } ]
worker/src/svc/oaworks/deposit.coffee
oaworks/paradigm
1
# need listing of deposits and deposited for each user ID # and/or given a uid, find the most recent URL that this users uid submitted a deposit for # need to handle old/new user configs somehow - just store all the old ones and let the UI pick them up # make sure all users submit the config with the incoming query (for those that still don't, temporarily copy them from old imported ones) # NOTE to receive files cloudflare should be setup to DNS route this directly to backend, and any calls to it should call that dns subdomain # because otherwise cloudflare will limit file upload size (100mb by default, and enterprise plans required for more) # however also busboy is required, so needs to be a direct call to backend P.svc.oaworks.deposits = _index: true # store a record of all deposits P.svc.oaworks.deposit = (params, file, dev) -> params ?= @copy @params file ?= @request.files[0] if @request.files # TODO check where these will end up - will they only work on bg with busboy? file = file[0] if Array.isArray file dev ?= @S.dev dep = {} dep[k] = params[k] for k in ['embedded', 'demo', 'pilot', 'live', 'email', 'plugin'] dep.pilot = Date.now() if dep.pilot dep.live = Date.now() if dep.live is true dep.name = file?.filename ? file?.name dep.from = params.from if params.from isnt 'anonymous' # if confirmed is true the submitter has confirmed this is the right file (and decode saves it as a "true" string, not bool, so doesn't clash in ES). If confirmed is the checksum this is a resubmit by an admin dep.confirmed = decodeURIComponent(params.confirmed) if params.confirmed dep.doi = params.doi ? params.metadata?.doi params.metadata = await @svc.oaworks.metadata(params.doi) if not params.metadata? and params.doi uc = params.config # should exist but may not uc = JSON.parse(params.config) if typeof params.config is 'string' if not params.config and params.from uc = await @fetch 'https://' + (if dev then 'dev.' else '') + 'api.cottagelabs.com/service/oab/deposit/config?uid=' + params.from perms = await @svc.oaworks.permissions params.metadata ? params.doi # SYP only works on DOI so far, so deposit only works if permissions can work, which requires a DOI if about a specific article arch = await @svc.oaworks.archivable file, undefined, (if dep.confirmed and dep.confirmed isnt true then dep.confirmed else undefined), params.metadata if arch?.archivable and (not dep.confirmed or dep.confirmed is arch.checksum) # if the depositor confirms we don't deposit, we manually review - only deposit on admin confirmation (but on dev allow it) zn = content: file.data, name: arch.name zn.publish = @S.svc.oaworks?.deposit?.zenodo is true creators = [] for a in params.metadata?.author ? [] if a.family? at = {name: a.family + (if a.given then ', ' + a.given else '')} try at.orcid = a.ORCID.split('/').pop() if a.ORCID try at.affiliation = a.affiliation.name if typeof a.affiliation is 'object' and a.affiliation.name? creators.push at creators = [{name:'Unknown'}] if creators.length is 0 description = if params.metadata.abstract then params.metadata.abstract + '<br><br>' else '' description += perms.best_permission?.deposit_statement ? (if params.metadata.doi? then 'The publisher\'s final version of this work can be found at https://doi.org/' + d.metadata.doi else '') description = description.trim() description += '.' if description.lastIndexOf('.') isnt description.length-1 description += ' ' if description.length description += '<br><br>Deposited by shareyourpaper.org and openaccessbutton.org. We\'ve taken reasonable steps to ensure this content doesn\'t violate copyright. However, if you think it does you can request a takedown by emailing help@openaccessbutton.org.' meta = title: params.metadata.title ? 'Unknown', description: description.trim(), creators: creators, version: if arch.version is 'preprint' then 'Submitted Version' else if arch.version is 'postprint' then 'Accepted Version' else if arch.version is 'publisher pdf' then 'Published Version' else 'Accepted Version', journal_title: params.metadata.journal journal_volume: params.metadata.volume journal_issue: params.metadata.issue journal_pages: params.metadata.page if params.doi in_zenodo = await @src.zenodo.records.doi params.doi if in_zenodo and dep.confirmed isnt arch.checksum and not dev dep.zenodo = already: in_zenodo.id # we don't put it in again although we could with doi as related field - but leave for review for now else meta['related_identifiers'] = [{relation: (if meta.version is 'postprint' or meta.version is 'AAM' or meta.version is 'preprint' then 'isPreviousVersionOf' else 'isIdenticalTo'), identifier: params.doi}] meta.prereserve_doi = true meta['access_right'] = 'open' meta.license = perms.best_permission?.licence ? 'cc-by' # zenodo also accepts other-closed and other-nc, possibly more meta.license = 'other-closed' if meta.license.indexOf('other') isnt -1 and meta.license.indexOf('closed') isnt -1 meta.license = 'other-nc' if meta.license.indexOf('other') isnt -1 and meta.license.indexOf('non') isnt -1 and meta.license.indexOf('commercial') isnt -1 meta.license += '-4.0' if meta.license.toLowerCase().indexOf('cc') is 0 and isNaN(parseInt(meta.license.substring(meta.license.length-1))) try if perms.best_permission?.embargo_end and moment(perms.best_permission.embargo_end,'YYYY-MM-DD').valueOf() > Date.now() meta['access_right'] = 'embargoed' meta['embargo_date'] = perms.best_permission.embargo_end # check date format required by zenodo dep.embargo = perms.best_permission.embargo_end try meta['publication_date'] = params.metadata.published if params.metadata.published? and typeof params.metadata.published is 'string' if uc uc.community = uc.community_ID if uc.community_ID? and not uc.community? if uc.community uc.communities ?= [] uc.communities.push({identifier: ccm}) for ccm in (if typeof uc.community is 'string' then uc.community.split(',') else uc.community) if uc.community? or uc.communities? uc.communities ?= uc.community uc.communities = [uc.communities] if not Array.isArray uc.communities meta['communities'] = [] meta.communities.push(if typeof com is 'string' then {identifier: com} else com) for com in uc.communities if tk = (if dev or dep.demo then @S.svc.oaworks?.zenodo?.sandbox else @S.svc.oaworks?.zenodo?.token) if not dep.zenodo?.already z = await @src.zenodo.deposition.create meta, zn, tk if z.id dep.zenodo = id: z.id url: 'https://' + (if dev or dep.demo then 'sandbox.' else '') + 'zenodo.org/record/' + z.id doi: z.metadata.prereserve_doi.doi if z.metadata?.prereserve_doi?.doi? file: z.uploaded?.links?.download ? z.uploaded?.links?.download dep.doi ?= dep.zenodo.doi dep.type = 'zenodo' else dep.error = 'Deposit to Zenodo failed' try dep.error += ': ' + JSON.stringify z dep.type = 'review' else dep.error = 'No Zenodo credentials available' dep.type = 'review' dep.version = arch?.version if not dep.type and params.from and (not dep.embedded or (dep.embedded.indexOf('oa.works') is -1 and dep.embedded.indexOf('openaccessbutton.org') is -1 and dep.embedded.indexOf('shareyourpaper.org') is -1)) dep.type = if params.redeposit then 'redeposit' else if file then 'forward' else 'dark' if dep.doi and not dep.error dep.type ?= 'review' dep.url = if typeof params.redeposit is 'string' then params.redeposit else if params.url then params.url else undefined if not exists = await @svc.oaworks.deposits 'doi:"' + dep.doi + '"' + (if dep.from then ' AND from:"' + dep.from + '"' else '') dep.createdAt = Date.now() @waitUntil @svc.oaworks.deposits dep else improved = false if dep.name and not exists.name improved = true exists.name = dep.name if dep.confirmed and (not exists.confirmed or (exists.confirmed is 'true' and dep.confirmed isnt 'true')) improved = true exists.confirmed = dep.confirmed exists.type = [exists.type] if typeof exists.type is 'string' if dep.type not in exists.type improved = true exists.type.push dep.type if dep.zenodo? and not dep.zenodo.already? and not exists.zenodo improved = true exists.zenodo = dep.zenodo if improved exists.updatedAt = Date.now() exists.duplicate ?= 0 exists.duplicate += 1 @waitUntil @svc.oaworks.deposits exists dep.duplicate = exists.duplicate ? 1 if (dep.type isnt 'review' or file?) and arch?.archivable isnt false and not dep.duplicate # so when true or when undefined if no file is given bcc = ['joe@oa.works'] tos = [] if typeof uc?.owner is 'string' and uc.owner.indexOf('@') isnt -1 tos.push uc.owner else if uc.email tos.push uc.email if tos.length is 0 tos = @copy bcc bcc = [] ed = @copy dep ed.metadata = params.metadata ? {} as = [] for author in (ed.metadata.author ? []) if author.family as.push (if author.given then author.given + ' ' else '') + author.family ed.metadata.author = as ed.adminlink = (if ed.embedded then ed.embedded else 'https://shareyourpaper.org' + (if ed.metadata.doi then '/' + ed.metadata.doi else '')) ed.adminlink += if ed.adminlink.includes('?') then '&' else '?' if arch?.checksum? ed.confirmed = encodeURIComponent arch.checksum ed.adminlink += 'confirmed=' + ed.confirmed + '&' ed.adminlink += 'email=' + ed.email tmpl = await @svc.oaworks.templates dep.type + '_deposit.html' tmpl = tmpl.content ml = from: 'deposits@oa.works' to: tos template: tmpl vars: ed subject: (sub.subject ? dep.type + ' deposit') html: sub.content ml.bcc = bcc if bcc and bcc.length # passing undefined to mail seems to cause errors, so only set if definitely exists ml.attachments = [{filename: (file.filename ? file.name), content: file.data}] if file @waitUntil @mail ml return dep P.svc.oaworks.deposit._bg = true P.svc.oaworks.archivable = (file, url, confirmed, meta={}) -> file ?= @request.files[0] if @request.files # TODO check where these will end up - will they only work on bg with busboy? file = file[0] if Array.isArray file f = {archivable: undefined, archivable_reason: undefined, version: 'unknown', same_paper: undefined, licence: undefined} # handle different sorts of file passing if typeof file is 'string' file = data: file if not file? and url? file = await @fetch url # check if this gets file content if file? file.name ?= file.filename try f.name = file.name try f.format = if file.name? and file.name.includes('.') then file.name.split('.').pop() else 'html' if file.data if f.format is 'pdf' try content = await @convert.pdf2txt file.data if not content? and f.format? and @convert[f.format+'2txt']? try content = await @convert[f.format+'2txt'] file.data if not content? content = await @convert.file2txt file.data, {name: file.name} if not content? fd = file.data if typeof file.data isnt 'string' try fd = file.data.toString() try if fd.startsWith '<html' content = await @convert.html2txt fd else if file.data.startsWith '<xml' content = await @convert.xml2txt fd try content ?= file.data try content = content.toString() if not content? and not confirmed if file? or url? f.error = file.error ? 'Could not extract any content' else _clean = (str) -> return str.toLowerCase().replace(/[^a-z0-9\/\.]+/g, "").replace(/\s\s+/g, ' ').trim() contentsmall = if content.length < 20000 then content else content.substring(0,6000) + content.substring(content.length-6000,content.length) lowercontentsmall = contentsmall.toLowerCase() lowercontentstart = _clean(if lowercontentsmall.length < 6000 then lowercontentsmall else lowercontentsmall.substring(0,6000)) f.name ?= meta.title try f.checksum = crypto.createHash('md5').update(content, 'utf8').digest('base64') f.same_paper_evidence = {} # check if the file meets our expectations try f.same_paper_evidence.words_count = content.split(' ').length # will need to be at least 500 words try f.same_paper_evidence.words_more_than_threshold = if f.same_paper_evidence.words_count > 500 then true else false try f.same_paper_evidence.doi_match = if meta.doi and lowercontentstart.indexOf(_clean meta.doi) isnt -1 then true else false # should have the doi in it near the front #if content and not f.same_paper_evidence.doi_match and not meta.title? # meta = API.service.oab.metadata undefined, meta, content # get at least title again if not already tried to get it, and could not find doi in the file try f.same_paper_evidence.title_match = if meta.title and lowercontentstart.replace(/\./g,'').includes(_clean meta.title.replace(/ /g,'').replace(/\./g,'')) then true else false if meta.author? try authorsfound = 0 f.same_paper_evidence.author_match = false # get the surnames out if possible, or author name strings, and find at least one in the doc if there are three or less, or find at least two otherwise meta.author = {name: meta.author} if typeof meta.author is 'string' meta.author = [meta.author] if not Array.isArray meta.author for a in meta.author if f.same_paper_evidence.author_match is true break else try an = (a.last ? a.lastname ? a.family ? a.surname ? a.name).trim().split(',')[0].split(' ')[0] af = (a.first ? a.firstname ? a.given ? a.name).trim().split(',')[0].split(' ')[0] inc = lowercontentstart.indexOf _clean an if an.length > 2 and af.length > 0 and inc isnt -1 and lowercontentstart.substring(inc-20, inc + an.length+20).includes _clean af authorsfound += 1 if (meta.author.length < 3 and authorsfound is 1) or (meta.author.length > 2 and authorsfound > 1) f.same_paper_evidence.author_match = true break if f.format? for ft in ['doc','tex','pdf','htm','xml','txt','rtf','odf','odt','page'] if f.format.indexOf(ft) isnt -1 f.same_paper_evidence.document_format = true break f.same_paper = if f.same_paper_evidence.words_more_than_threshold and (f.same_paper_evidence.doi_match or f.same_paper_evidence.title_match or f.same_paper_evidence.author_match) and f.same_paper_evidence.document_format then true else false if f.same_paper_evidence.words_count < 150 and f.format is 'pdf' # there was likely a pdf file reading failure due to bad PDF formatting f.same_paper_evidence.words_count = 0 f.archivable_reason = 'We could not find any text in the provided PDF. It is possible the PDF is a scan in which case text is only contained within images which we do not yet extract. Or, the PDF may have errors in it\'s structure which stops us being able to machine-read it' f.version_evidence = score: 0, strings_checked: 0, strings_matched: [] try # dev https://docs.google.com/spreadsheets/d/1XA29lqVPCJ2FQ6siLywahxBTLFaDCZKaN5qUeoTuApg/edit#gid=0 # live https://docs.google.com/spreadsheets/d/10DNDmOG19shNnuw6cwtCpK-sBnexRCCtD4WnxJx_DPQ/edit#gid=0 for l in await @src.google.sheets (if @S.dev then '1XA29lqVPCJ2FQ6siLywahxBTLFaDCZKaN5qUeoTuApg' else '10DNDmOG19shNnuw6cwtCpK-sBnexRCCtD4WnxJx_DPQ') try f.version_evidence.strings_checked += 1 wts = l.whattosearch if wts.includes('<<') and wts.includes '>>' wtm = wts.split('<<')[1].split('>>')[0] wts = wts.replace('<<'+wtm+'>>', meta[wtm.toLowerCase()]) if meta[wtm.toLowerCase()]? matched = false if l.howtosearch is 'string' matched = if (l.wheretosearch is 'file' and contentsmall.indexOf(wts) isnt -1) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.indexOf(wts) isnt -1) or (f.name? and f.name.indexOf(wts) isnt -1))) then true else false else re = new RegExp wts, 'gium' matched = if (l.wheretosearch is 'file' and lowercontentsmall.match(re) isnt null) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.match(re) isnt null) or (f.name? and f.name.match(re) isnt null))) then true else false if matched sc = l.score ? l.score_value if typeof sc is 'string' try sc = parseInt sc sc = 1 if typeof sc isnt 'number' if l.whatitindicates is 'publisher pdf' then f.version_evidence.score += sc else f.version_evidence.score -= sc f.version_evidence.strings_matched.push {indicates: l.whatitindicates, found: l.howtosearch + ' ' + wts, in: l.wheretosearch, score_value: sc} f.version = 'publishedVersion' if f.version_evidence.score > 0 f.version = 'acceptedVersion' if f.version_evidence.score < 0 if f.version is 'unknown' and f.version_evidence.strings_checked > 0 #and f.format? and f.format isnt 'pdf' f.version = 'acceptedVersion' try ls = await @svc.lantern.licence undefined, undefined, lowercontentsmall # check lantern for licence info in the file content if ls?.licence? f.licence = ls.licence f.licence_evidence = {string_match: ls.match} f.lantern = ls f.archivable = false if confirmed f.archivable = true if confirmed is f.checksum f.archivable_reason = 'The administrator has confirmed that this file is a version that can be archived.' f.admin_confirms = true else f.archivable_reason = 'The depositor says that this file is a version that can be archived' f.depositor_says = true else if f.same_paper if f.format isnt 'pdf' f.archivable = true f.archivable_reason = 'Since the file is not a PDF, we assume it is a Postprint.' if not f.archivable and f.licence? and f.licence.toLowerCase().startsWith 'cc' f.archivable = true f.archivable_reason = 'It appears this file contains a ' + f.lantern.licence + ' licence statement. Under this licence the article can be archived' if not f.archivable if f.version is 'publishedVersion' f.archivable_reason = 'The file given is a Publisher PDF, and only postprints are allowed' else f.archivable_reason = 'We cannot confirm if it is an archivable version or not' else f.archivable_reason ?= if not f.same_paper_evidence.words_more_than_threshold then 'The file is less than 500 words, and so does not appear to be a full article' else if not f.same_paper_evidence.document_format then 'File is an unexpected format ' + f.format else if not meta.doi and not meta.title then 'We have insufficient metadata to validate file is for the correct paper ' else 'File does not contain expected metadata such as DOI or title' return f
108760
# need listing of deposits and deposited for each user ID # and/or given a uid, find the most recent URL that this users uid submitted a deposit for # need to handle old/new user configs somehow - just store all the old ones and let the UI pick them up # make sure all users submit the config with the incoming query (for those that still don't, temporarily copy them from old imported ones) # NOTE to receive files cloudflare should be setup to DNS route this directly to backend, and any calls to it should call that dns subdomain # because otherwise cloudflare will limit file upload size (100mb by default, and enterprise plans required for more) # however also busboy is required, so needs to be a direct call to backend P.svc.oaworks.deposits = _index: true # store a record of all deposits P.svc.oaworks.deposit = (params, file, dev) -> params ?= @copy @params file ?= @request.files[0] if @request.files # TODO check where these will end up - will they only work on bg with busboy? file = file[0] if Array.isArray file dev ?= @S.dev dep = {} dep[k] = params[k] for k in ['embedded', 'demo', 'pilot', 'live', 'email', 'plugin'] dep.pilot = Date.now() if dep.pilot dep.live = Date.now() if dep.live is true dep.name = file?.filename ? file?.name dep.from = params.from if params.from isnt 'anonymous' # if confirmed is true the submitter has confirmed this is the right file (and decode saves it as a "true" string, not bool, so doesn't clash in ES). If confirmed is the checksum this is a resubmit by an admin dep.confirmed = decodeURIComponent(params.confirmed) if params.confirmed dep.doi = params.doi ? params.metadata?.doi params.metadata = await @svc.oaworks.metadata(params.doi) if not params.metadata? and params.doi uc = params.config # should exist but may not uc = JSON.parse(params.config) if typeof params.config is 'string' if not params.config and params.from uc = await @fetch 'https://' + (if dev then 'dev.' else '') + 'api.cottagelabs.com/service/oab/deposit/config?uid=' + params.from perms = await @svc.oaworks.permissions params.metadata ? params.doi # SYP only works on DOI so far, so deposit only works if permissions can work, which requires a DOI if about a specific article arch = await @svc.oaworks.archivable file, undefined, (if dep.confirmed and dep.confirmed isnt true then dep.confirmed else undefined), params.metadata if arch?.archivable and (not dep.confirmed or dep.confirmed is arch.checksum) # if the depositor confirms we don't deposit, we manually review - only deposit on admin confirmation (but on dev allow it) zn = content: file.data, name: arch.name zn.publish = @S.svc.oaworks?.deposit?.zenodo is true creators = [] for a in params.metadata?.author ? [] if a.family? at = {name: a.family + (if a.given then ', ' + a.given else '')} try at.orcid = a.ORCID.split('/').pop() if a.ORCID try at.affiliation = a.affiliation.name if typeof a.affiliation is 'object' and a.affiliation.name? creators.push at creators = [{name:'Unknown'}] if creators.length is 0 description = if params.metadata.abstract then params.metadata.abstract + '<br><br>' else '' description += perms.best_permission?.deposit_statement ? (if params.metadata.doi? then 'The publisher\'s final version of this work can be found at https://doi.org/' + d.metadata.doi else '') description = description.trim() description += '.' if description.lastIndexOf('.') isnt description.length-1 description += ' ' if description.length description += '<br><br>Deposited by shareyourpaper.org and openaccessbutton.org. We\'ve taken reasonable steps to ensure this content doesn\'t violate copyright. However, if you think it does you can request a takedown by emailing <EMAIL>.' meta = title: params.metadata.title ? 'Unknown', description: description.trim(), creators: creators, version: if arch.version is 'preprint' then 'Submitted Version' else if arch.version is 'postprint' then 'Accepted Version' else if arch.version is 'publisher pdf' then 'Published Version' else 'Accepted Version', journal_title: params.metadata.journal journal_volume: params.metadata.volume journal_issue: params.metadata.issue journal_pages: params.metadata.page if params.doi in_zenodo = await @src.zenodo.records.doi params.doi if in_zenodo and dep.confirmed isnt arch.checksum and not dev dep.zenodo = already: in_zenodo.id # we don't put it in again although we could with doi as related field - but leave for review for now else meta['related_identifiers'] = [{relation: (if meta.version is 'postprint' or meta.version is 'AAM' or meta.version is 'preprint' then 'isPreviousVersionOf' else 'isIdenticalTo'), identifier: params.doi}] meta.prereserve_doi = true meta['access_right'] = 'open' meta.license = perms.best_permission?.licence ? 'cc-by' # zenodo also accepts other-closed and other-nc, possibly more meta.license = 'other-closed' if meta.license.indexOf('other') isnt -1 and meta.license.indexOf('closed') isnt -1 meta.license = 'other-nc' if meta.license.indexOf('other') isnt -1 and meta.license.indexOf('non') isnt -1 and meta.license.indexOf('commercial') isnt -1 meta.license += '-4.0' if meta.license.toLowerCase().indexOf('cc') is 0 and isNaN(parseInt(meta.license.substring(meta.license.length-1))) try if perms.best_permission?.embargo_end and moment(perms.best_permission.embargo_end,'YYYY-MM-DD').valueOf() > Date.now() meta['access_right'] = 'embargoed' meta['embargo_date'] = perms.best_permission.embargo_end # check date format required by zenodo dep.embargo = perms.best_permission.embargo_end try meta['publication_date'] = params.metadata.published if params.metadata.published? and typeof params.metadata.published is 'string' if uc uc.community = uc.community_ID if uc.community_ID? and not uc.community? if uc.community uc.communities ?= [] uc.communities.push({identifier: ccm}) for ccm in (if typeof uc.community is 'string' then uc.community.split(',') else uc.community) if uc.community? or uc.communities? uc.communities ?= uc.community uc.communities = [uc.communities] if not Array.isArray uc.communities meta['communities'] = [] meta.communities.push(if typeof com is 'string' then {identifier: com} else com) for com in uc.communities if tk = (if dev or dep.demo then @S.svc.oaworks?.zenodo?.sandbox else @S.svc.oaworks?.zenodo?.token) if not dep.zenodo?.already z = await @src.zenodo.deposition.create meta, zn, tk if z.id dep.zenodo = id: z.id url: 'https://' + (if dev or dep.demo then 'sandbox.' else '') + 'zenodo.org/record/' + z.id doi: z.metadata.prereserve_doi.doi if z.metadata?.prereserve_doi?.doi? file: z.uploaded?.links?.download ? z.uploaded?.links?.download dep.doi ?= dep.zenodo.doi dep.type = 'zenodo' else dep.error = 'Deposit to Zenodo failed' try dep.error += ': ' + JSON.stringify z dep.type = 'review' else dep.error = 'No Zenodo credentials available' dep.type = 'review' dep.version = arch?.version if not dep.type and params.from and (not dep.embedded or (dep.embedded.indexOf('oa.works') is -1 and dep.embedded.indexOf('openaccessbutton.org') is -1 and dep.embedded.indexOf('shareyourpaper.org') is -1)) dep.type = if params.redeposit then 'redeposit' else if file then 'forward' else 'dark' if dep.doi and not dep.error dep.type ?= 'review' dep.url = if typeof params.redeposit is 'string' then params.redeposit else if params.url then params.url else undefined if not exists = await @svc.oaworks.deposits 'doi:"' + dep.doi + '"' + (if dep.from then ' AND from:"' + dep.from + '"' else '') dep.createdAt = Date.now() @waitUntil @svc.oaworks.deposits dep else improved = false if dep.name and not exists.name improved = true exists.name = dep.name if dep.confirmed and (not exists.confirmed or (exists.confirmed is 'true' and dep.confirmed isnt 'true')) improved = true exists.confirmed = dep.confirmed exists.type = [exists.type] if typeof exists.type is 'string' if dep.type not in exists.type improved = true exists.type.push dep.type if dep.zenodo? and not dep.zenodo.already? and not exists.zenodo improved = true exists.zenodo = dep.zenodo if improved exists.updatedAt = Date.now() exists.duplicate ?= 0 exists.duplicate += 1 @waitUntil @svc.oaworks.deposits exists dep.duplicate = exists.duplicate ? 1 if (dep.type isnt 'review' or file?) and arch?.archivable isnt false and not dep.duplicate # so when true or when undefined if no file is given bcc = ['<EMAIL>'] tos = [] if typeof uc?.owner is 'string' and uc.owner.indexOf('@') isnt -1 tos.push uc.owner else if uc.email tos.push uc.email if tos.length is 0 tos = @copy bcc bcc = [] ed = @copy dep ed.metadata = params.metadata ? {} as = [] for author in (ed.metadata.author ? []) if author.family as.push (if author.given then author.given + ' ' else '') + author.family ed.metadata.author = as ed.adminlink = (if ed.embedded then ed.embedded else 'https://shareyourpaper.org' + (if ed.metadata.doi then '/' + ed.metadata.doi else '')) ed.adminlink += if ed.adminlink.includes('?') then '&' else '?' if arch?.checksum? ed.confirmed = encodeURIComponent arch.checksum ed.adminlink += 'confirmed=' + ed.confirmed + '&' ed.adminlink += 'email=' + ed.email tmpl = await @svc.oaworks.templates dep.type + '_deposit.html' tmpl = tmpl.content ml = from: '<EMAIL>' to: tos template: tmpl vars: ed subject: (sub.subject ? dep.type + ' deposit') html: sub.content ml.bcc = bcc if bcc and bcc.length # passing undefined to mail seems to cause errors, so only set if definitely exists ml.attachments = [{filename: (file.filename ? file.name), content: file.data}] if file @waitUntil @mail ml return dep P.svc.oaworks.deposit._bg = true P.svc.oaworks.archivable = (file, url, confirmed, meta={}) -> file ?= @request.files[0] if @request.files # TODO check where these will end up - will they only work on bg with busboy? file = file[0] if Array.isArray file f = {archivable: undefined, archivable_reason: undefined, version: 'unknown', same_paper: undefined, licence: undefined} # handle different sorts of file passing if typeof file is 'string' file = data: file if not file? and url? file = await @fetch url # check if this gets file content if file? file.name ?= file.filename try f.name = file.name try f.format = if file.name? and file.name.includes('.') then file.name.split('.').pop() else 'html' if file.data if f.format is 'pdf' try content = await @convert.pdf2txt file.data if not content? and f.format? and @convert[f.format+'2txt']? try content = await @convert[f.format+'2txt'] file.data if not content? content = await @convert.file2txt file.data, {name: file.name} if not content? fd = file.data if typeof file.data isnt 'string' try fd = file.data.toString() try if fd.startsWith '<html' content = await @convert.html2txt fd else if file.data.startsWith '<xml' content = await @convert.xml2txt fd try content ?= file.data try content = content.toString() if not content? and not confirmed if file? or url? f.error = file.error ? 'Could not extract any content' else _clean = (str) -> return str.toLowerCase().replace(/[^a-z0-9\/\.]+/g, "").replace(/\s\s+/g, ' ').trim() contentsmall = if content.length < 20000 then content else content.substring(0,6000) + content.substring(content.length-6000,content.length) lowercontentsmall = contentsmall.toLowerCase() lowercontentstart = _clean(if lowercontentsmall.length < 6000 then lowercontentsmall else lowercontentsmall.substring(0,6000)) f.name ?= meta.title try f.checksum = crypto.createHash('md5').update(content, 'utf8').digest('base64') f.same_paper_evidence = {} # check if the file meets our expectations try f.same_paper_evidence.words_count = content.split(' ').length # will need to be at least 500 words try f.same_paper_evidence.words_more_than_threshold = if f.same_paper_evidence.words_count > 500 then true else false try f.same_paper_evidence.doi_match = if meta.doi and lowercontentstart.indexOf(_clean meta.doi) isnt -1 then true else false # should have the doi in it near the front #if content and not f.same_paper_evidence.doi_match and not meta.title? # meta = API.service.oab.metadata undefined, meta, content # get at least title again if not already tried to get it, and could not find doi in the file try f.same_paper_evidence.title_match = if meta.title and lowercontentstart.replace(/\./g,'').includes(_clean meta.title.replace(/ /g,'').replace(/\./g,'')) then true else false if meta.author? try authorsfound = 0 f.same_paper_evidence.author_match = false # get the surnames out if possible, or author name strings, and find at least one in the doc if there are three or less, or find at least two otherwise meta.author = {name: meta.author} if typeof meta.author is 'string' meta.author = [meta.author] if not Array.isArray meta.author for a in meta.author if f.same_paper_evidence.author_match is true break else try an = (a.last ? a.lastname ? a.family ? a.surname ? a.name).trim().split(',')[0].split(' ')[0] af = (a.first ? a.firstname ? a.given ? a.name).trim().split(',')[0].split(' ')[0] inc = lowercontentstart.indexOf _clean an if an.length > 2 and af.length > 0 and inc isnt -1 and lowercontentstart.substring(inc-20, inc + an.length+20).includes _clean af authorsfound += 1 if (meta.author.length < 3 and authorsfound is 1) or (meta.author.length > 2 and authorsfound > 1) f.same_paper_evidence.author_match = true break if f.format? for ft in ['doc','tex','pdf','htm','xml','txt','rtf','odf','odt','page'] if f.format.indexOf(ft) isnt -1 f.same_paper_evidence.document_format = true break f.same_paper = if f.same_paper_evidence.words_more_than_threshold and (f.same_paper_evidence.doi_match or f.same_paper_evidence.title_match or f.same_paper_evidence.author_match) and f.same_paper_evidence.document_format then true else false if f.same_paper_evidence.words_count < 150 and f.format is 'pdf' # there was likely a pdf file reading failure due to bad PDF formatting f.same_paper_evidence.words_count = 0 f.archivable_reason = 'We could not find any text in the provided PDF. It is possible the PDF is a scan in which case text is only contained within images which we do not yet extract. Or, the PDF may have errors in it\'s structure which stops us being able to machine-read it' f.version_evidence = score: 0, strings_checked: 0, strings_matched: [] try # dev https://docs.google.com/spreadsheets/d/<KEY>/edit#gid=0 # live https://docs.google.com/spreadsheets/d/<KEY>/edit#gid=0 for l in await @src.google.sheets (if @S.dev then '<KEY>' else '<KEY>') try f.version_evidence.strings_checked += 1 wts = l.whattosearch if wts.includes('<<') and wts.includes '>>' wtm = wts.split('<<')[1].split('>>')[0] wts = wts.replace('<<'+wtm+'>>', meta[wtm.toLowerCase()]) if meta[wtm.toLowerCase()]? matched = false if l.howtosearch is 'string' matched = if (l.wheretosearch is 'file' and contentsmall.indexOf(wts) isnt -1) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.indexOf(wts) isnt -1) or (f.name? and f.name.indexOf(wts) isnt -1))) then true else false else re = new RegExp wts, 'gium' matched = if (l.wheretosearch is 'file' and lowercontentsmall.match(re) isnt null) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.match(re) isnt null) or (f.name? and f.name.match(re) isnt null))) then true else false if matched sc = l.score ? l.score_value if typeof sc is 'string' try sc = parseInt sc sc = 1 if typeof sc isnt 'number' if l.whatitindicates is 'publisher pdf' then f.version_evidence.score += sc else f.version_evidence.score -= sc f.version_evidence.strings_matched.push {indicates: l.whatitindicates, found: l.howtosearch + ' ' + wts, in: l.wheretosearch, score_value: sc} f.version = 'publishedVersion' if f.version_evidence.score > 0 f.version = 'acceptedVersion' if f.version_evidence.score < 0 if f.version is 'unknown' and f.version_evidence.strings_checked > 0 #and f.format? and f.format isnt 'pdf' f.version = 'acceptedVersion' try ls = await @svc.lantern.licence undefined, undefined, lowercontentsmall # check lantern for licence info in the file content if ls?.licence? f.licence = ls.licence f.licence_evidence = {string_match: ls.match} f.lantern = ls f.archivable = false if confirmed f.archivable = true if confirmed is f.checksum f.archivable_reason = 'The administrator has confirmed that this file is a version that can be archived.' f.admin_confirms = true else f.archivable_reason = 'The depositor says that this file is a version that can be archived' f.depositor_says = true else if f.same_paper if f.format isnt 'pdf' f.archivable = true f.archivable_reason = 'Since the file is not a PDF, we assume it is a Postprint.' if not f.archivable and f.licence? and f.licence.toLowerCase().startsWith 'cc' f.archivable = true f.archivable_reason = 'It appears this file contains a ' + f.lantern.licence + ' licence statement. Under this licence the article can be archived' if not f.archivable if f.version is 'publishedVersion' f.archivable_reason = 'The file given is a Publisher PDF, and only postprints are allowed' else f.archivable_reason = 'We cannot confirm if it is an archivable version or not' else f.archivable_reason ?= if not f.same_paper_evidence.words_more_than_threshold then 'The file is less than 500 words, and so does not appear to be a full article' else if not f.same_paper_evidence.document_format then 'File is an unexpected format ' + f.format else if not meta.doi and not meta.title then 'We have insufficient metadata to validate file is for the correct paper ' else 'File does not contain expected metadata such as DOI or title' return f
true
# need listing of deposits and deposited for each user ID # and/or given a uid, find the most recent URL that this users uid submitted a deposit for # need to handle old/new user configs somehow - just store all the old ones and let the UI pick them up # make sure all users submit the config with the incoming query (for those that still don't, temporarily copy them from old imported ones) # NOTE to receive files cloudflare should be setup to DNS route this directly to backend, and any calls to it should call that dns subdomain # because otherwise cloudflare will limit file upload size (100mb by default, and enterprise plans required for more) # however also busboy is required, so needs to be a direct call to backend P.svc.oaworks.deposits = _index: true # store a record of all deposits P.svc.oaworks.deposit = (params, file, dev) -> params ?= @copy @params file ?= @request.files[0] if @request.files # TODO check where these will end up - will they only work on bg with busboy? file = file[0] if Array.isArray file dev ?= @S.dev dep = {} dep[k] = params[k] for k in ['embedded', 'demo', 'pilot', 'live', 'email', 'plugin'] dep.pilot = Date.now() if dep.pilot dep.live = Date.now() if dep.live is true dep.name = file?.filename ? file?.name dep.from = params.from if params.from isnt 'anonymous' # if confirmed is true the submitter has confirmed this is the right file (and decode saves it as a "true" string, not bool, so doesn't clash in ES). If confirmed is the checksum this is a resubmit by an admin dep.confirmed = decodeURIComponent(params.confirmed) if params.confirmed dep.doi = params.doi ? params.metadata?.doi params.metadata = await @svc.oaworks.metadata(params.doi) if not params.metadata? and params.doi uc = params.config # should exist but may not uc = JSON.parse(params.config) if typeof params.config is 'string' if not params.config and params.from uc = await @fetch 'https://' + (if dev then 'dev.' else '') + 'api.cottagelabs.com/service/oab/deposit/config?uid=' + params.from perms = await @svc.oaworks.permissions params.metadata ? params.doi # SYP only works on DOI so far, so deposit only works if permissions can work, which requires a DOI if about a specific article arch = await @svc.oaworks.archivable file, undefined, (if dep.confirmed and dep.confirmed isnt true then dep.confirmed else undefined), params.metadata if arch?.archivable and (not dep.confirmed or dep.confirmed is arch.checksum) # if the depositor confirms we don't deposit, we manually review - only deposit on admin confirmation (but on dev allow it) zn = content: file.data, name: arch.name zn.publish = @S.svc.oaworks?.deposit?.zenodo is true creators = [] for a in params.metadata?.author ? [] if a.family? at = {name: a.family + (if a.given then ', ' + a.given else '')} try at.orcid = a.ORCID.split('/').pop() if a.ORCID try at.affiliation = a.affiliation.name if typeof a.affiliation is 'object' and a.affiliation.name? creators.push at creators = [{name:'Unknown'}] if creators.length is 0 description = if params.metadata.abstract then params.metadata.abstract + '<br><br>' else '' description += perms.best_permission?.deposit_statement ? (if params.metadata.doi? then 'The publisher\'s final version of this work can be found at https://doi.org/' + d.metadata.doi else '') description = description.trim() description += '.' if description.lastIndexOf('.') isnt description.length-1 description += ' ' if description.length description += '<br><br>Deposited by shareyourpaper.org and openaccessbutton.org. We\'ve taken reasonable steps to ensure this content doesn\'t violate copyright. However, if you think it does you can request a takedown by emailing PI:EMAIL:<EMAIL>END_PI.' meta = title: params.metadata.title ? 'Unknown', description: description.trim(), creators: creators, version: if arch.version is 'preprint' then 'Submitted Version' else if arch.version is 'postprint' then 'Accepted Version' else if arch.version is 'publisher pdf' then 'Published Version' else 'Accepted Version', journal_title: params.metadata.journal journal_volume: params.metadata.volume journal_issue: params.metadata.issue journal_pages: params.metadata.page if params.doi in_zenodo = await @src.zenodo.records.doi params.doi if in_zenodo and dep.confirmed isnt arch.checksum and not dev dep.zenodo = already: in_zenodo.id # we don't put it in again although we could with doi as related field - but leave for review for now else meta['related_identifiers'] = [{relation: (if meta.version is 'postprint' or meta.version is 'AAM' or meta.version is 'preprint' then 'isPreviousVersionOf' else 'isIdenticalTo'), identifier: params.doi}] meta.prereserve_doi = true meta['access_right'] = 'open' meta.license = perms.best_permission?.licence ? 'cc-by' # zenodo also accepts other-closed and other-nc, possibly more meta.license = 'other-closed' if meta.license.indexOf('other') isnt -1 and meta.license.indexOf('closed') isnt -1 meta.license = 'other-nc' if meta.license.indexOf('other') isnt -1 and meta.license.indexOf('non') isnt -1 and meta.license.indexOf('commercial') isnt -1 meta.license += '-4.0' if meta.license.toLowerCase().indexOf('cc') is 0 and isNaN(parseInt(meta.license.substring(meta.license.length-1))) try if perms.best_permission?.embargo_end and moment(perms.best_permission.embargo_end,'YYYY-MM-DD').valueOf() > Date.now() meta['access_right'] = 'embargoed' meta['embargo_date'] = perms.best_permission.embargo_end # check date format required by zenodo dep.embargo = perms.best_permission.embargo_end try meta['publication_date'] = params.metadata.published if params.metadata.published? and typeof params.metadata.published is 'string' if uc uc.community = uc.community_ID if uc.community_ID? and not uc.community? if uc.community uc.communities ?= [] uc.communities.push({identifier: ccm}) for ccm in (if typeof uc.community is 'string' then uc.community.split(',') else uc.community) if uc.community? or uc.communities? uc.communities ?= uc.community uc.communities = [uc.communities] if not Array.isArray uc.communities meta['communities'] = [] meta.communities.push(if typeof com is 'string' then {identifier: com} else com) for com in uc.communities if tk = (if dev or dep.demo then @S.svc.oaworks?.zenodo?.sandbox else @S.svc.oaworks?.zenodo?.token) if not dep.zenodo?.already z = await @src.zenodo.deposition.create meta, zn, tk if z.id dep.zenodo = id: z.id url: 'https://' + (if dev or dep.demo then 'sandbox.' else '') + 'zenodo.org/record/' + z.id doi: z.metadata.prereserve_doi.doi if z.metadata?.prereserve_doi?.doi? file: z.uploaded?.links?.download ? z.uploaded?.links?.download dep.doi ?= dep.zenodo.doi dep.type = 'zenodo' else dep.error = 'Deposit to Zenodo failed' try dep.error += ': ' + JSON.stringify z dep.type = 'review' else dep.error = 'No Zenodo credentials available' dep.type = 'review' dep.version = arch?.version if not dep.type and params.from and (not dep.embedded or (dep.embedded.indexOf('oa.works') is -1 and dep.embedded.indexOf('openaccessbutton.org') is -1 and dep.embedded.indexOf('shareyourpaper.org') is -1)) dep.type = if params.redeposit then 'redeposit' else if file then 'forward' else 'dark' if dep.doi and not dep.error dep.type ?= 'review' dep.url = if typeof params.redeposit is 'string' then params.redeposit else if params.url then params.url else undefined if not exists = await @svc.oaworks.deposits 'doi:"' + dep.doi + '"' + (if dep.from then ' AND from:"' + dep.from + '"' else '') dep.createdAt = Date.now() @waitUntil @svc.oaworks.deposits dep else improved = false if dep.name and not exists.name improved = true exists.name = dep.name if dep.confirmed and (not exists.confirmed or (exists.confirmed is 'true' and dep.confirmed isnt 'true')) improved = true exists.confirmed = dep.confirmed exists.type = [exists.type] if typeof exists.type is 'string' if dep.type not in exists.type improved = true exists.type.push dep.type if dep.zenodo? and not dep.zenodo.already? and not exists.zenodo improved = true exists.zenodo = dep.zenodo if improved exists.updatedAt = Date.now() exists.duplicate ?= 0 exists.duplicate += 1 @waitUntil @svc.oaworks.deposits exists dep.duplicate = exists.duplicate ? 1 if (dep.type isnt 'review' or file?) and arch?.archivable isnt false and not dep.duplicate # so when true or when undefined if no file is given bcc = ['PI:EMAIL:<EMAIL>END_PI'] tos = [] if typeof uc?.owner is 'string' and uc.owner.indexOf('@') isnt -1 tos.push uc.owner else if uc.email tos.push uc.email if tos.length is 0 tos = @copy bcc bcc = [] ed = @copy dep ed.metadata = params.metadata ? {} as = [] for author in (ed.metadata.author ? []) if author.family as.push (if author.given then author.given + ' ' else '') + author.family ed.metadata.author = as ed.adminlink = (if ed.embedded then ed.embedded else 'https://shareyourpaper.org' + (if ed.metadata.doi then '/' + ed.metadata.doi else '')) ed.adminlink += if ed.adminlink.includes('?') then '&' else '?' if arch?.checksum? ed.confirmed = encodeURIComponent arch.checksum ed.adminlink += 'confirmed=' + ed.confirmed + '&' ed.adminlink += 'email=' + ed.email tmpl = await @svc.oaworks.templates dep.type + '_deposit.html' tmpl = tmpl.content ml = from: 'PI:EMAIL:<EMAIL>END_PI' to: tos template: tmpl vars: ed subject: (sub.subject ? dep.type + ' deposit') html: sub.content ml.bcc = bcc if bcc and bcc.length # passing undefined to mail seems to cause errors, so only set if definitely exists ml.attachments = [{filename: (file.filename ? file.name), content: file.data}] if file @waitUntil @mail ml return dep P.svc.oaworks.deposit._bg = true P.svc.oaworks.archivable = (file, url, confirmed, meta={}) -> file ?= @request.files[0] if @request.files # TODO check where these will end up - will they only work on bg with busboy? file = file[0] if Array.isArray file f = {archivable: undefined, archivable_reason: undefined, version: 'unknown', same_paper: undefined, licence: undefined} # handle different sorts of file passing if typeof file is 'string' file = data: file if not file? and url? file = await @fetch url # check if this gets file content if file? file.name ?= file.filename try f.name = file.name try f.format = if file.name? and file.name.includes('.') then file.name.split('.').pop() else 'html' if file.data if f.format is 'pdf' try content = await @convert.pdf2txt file.data if not content? and f.format? and @convert[f.format+'2txt']? try content = await @convert[f.format+'2txt'] file.data if not content? content = await @convert.file2txt file.data, {name: file.name} if not content? fd = file.data if typeof file.data isnt 'string' try fd = file.data.toString() try if fd.startsWith '<html' content = await @convert.html2txt fd else if file.data.startsWith '<xml' content = await @convert.xml2txt fd try content ?= file.data try content = content.toString() if not content? and not confirmed if file? or url? f.error = file.error ? 'Could not extract any content' else _clean = (str) -> return str.toLowerCase().replace(/[^a-z0-9\/\.]+/g, "").replace(/\s\s+/g, ' ').trim() contentsmall = if content.length < 20000 then content else content.substring(0,6000) + content.substring(content.length-6000,content.length) lowercontentsmall = contentsmall.toLowerCase() lowercontentstart = _clean(if lowercontentsmall.length < 6000 then lowercontentsmall else lowercontentsmall.substring(0,6000)) f.name ?= meta.title try f.checksum = crypto.createHash('md5').update(content, 'utf8').digest('base64') f.same_paper_evidence = {} # check if the file meets our expectations try f.same_paper_evidence.words_count = content.split(' ').length # will need to be at least 500 words try f.same_paper_evidence.words_more_than_threshold = if f.same_paper_evidence.words_count > 500 then true else false try f.same_paper_evidence.doi_match = if meta.doi and lowercontentstart.indexOf(_clean meta.doi) isnt -1 then true else false # should have the doi in it near the front #if content and not f.same_paper_evidence.doi_match and not meta.title? # meta = API.service.oab.metadata undefined, meta, content # get at least title again if not already tried to get it, and could not find doi in the file try f.same_paper_evidence.title_match = if meta.title and lowercontentstart.replace(/\./g,'').includes(_clean meta.title.replace(/ /g,'').replace(/\./g,'')) then true else false if meta.author? try authorsfound = 0 f.same_paper_evidence.author_match = false # get the surnames out if possible, or author name strings, and find at least one in the doc if there are three or less, or find at least two otherwise meta.author = {name: meta.author} if typeof meta.author is 'string' meta.author = [meta.author] if not Array.isArray meta.author for a in meta.author if f.same_paper_evidence.author_match is true break else try an = (a.last ? a.lastname ? a.family ? a.surname ? a.name).trim().split(',')[0].split(' ')[0] af = (a.first ? a.firstname ? a.given ? a.name).trim().split(',')[0].split(' ')[0] inc = lowercontentstart.indexOf _clean an if an.length > 2 and af.length > 0 and inc isnt -1 and lowercontentstart.substring(inc-20, inc + an.length+20).includes _clean af authorsfound += 1 if (meta.author.length < 3 and authorsfound is 1) or (meta.author.length > 2 and authorsfound > 1) f.same_paper_evidence.author_match = true break if f.format? for ft in ['doc','tex','pdf','htm','xml','txt','rtf','odf','odt','page'] if f.format.indexOf(ft) isnt -1 f.same_paper_evidence.document_format = true break f.same_paper = if f.same_paper_evidence.words_more_than_threshold and (f.same_paper_evidence.doi_match or f.same_paper_evidence.title_match or f.same_paper_evidence.author_match) and f.same_paper_evidence.document_format then true else false if f.same_paper_evidence.words_count < 150 and f.format is 'pdf' # there was likely a pdf file reading failure due to bad PDF formatting f.same_paper_evidence.words_count = 0 f.archivable_reason = 'We could not find any text in the provided PDF. It is possible the PDF is a scan in which case text is only contained within images which we do not yet extract. Or, the PDF may have errors in it\'s structure which stops us being able to machine-read it' f.version_evidence = score: 0, strings_checked: 0, strings_matched: [] try # dev https://docs.google.com/spreadsheets/d/PI:KEY:<KEY>END_PI/edit#gid=0 # live https://docs.google.com/spreadsheets/d/PI:KEY:<KEY>END_PI/edit#gid=0 for l in await @src.google.sheets (if @S.dev then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI') try f.version_evidence.strings_checked += 1 wts = l.whattosearch if wts.includes('<<') and wts.includes '>>' wtm = wts.split('<<')[1].split('>>')[0] wts = wts.replace('<<'+wtm+'>>', meta[wtm.toLowerCase()]) if meta[wtm.toLowerCase()]? matched = false if l.howtosearch is 'string' matched = if (l.wheretosearch is 'file' and contentsmall.indexOf(wts) isnt -1) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.indexOf(wts) isnt -1) or (f.name? and f.name.indexOf(wts) isnt -1))) then true else false else re = new RegExp wts, 'gium' matched = if (l.wheretosearch is 'file' and lowercontentsmall.match(re) isnt null) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.match(re) isnt null) or (f.name? and f.name.match(re) isnt null))) then true else false if matched sc = l.score ? l.score_value if typeof sc is 'string' try sc = parseInt sc sc = 1 if typeof sc isnt 'number' if l.whatitindicates is 'publisher pdf' then f.version_evidence.score += sc else f.version_evidence.score -= sc f.version_evidence.strings_matched.push {indicates: l.whatitindicates, found: l.howtosearch + ' ' + wts, in: l.wheretosearch, score_value: sc} f.version = 'publishedVersion' if f.version_evidence.score > 0 f.version = 'acceptedVersion' if f.version_evidence.score < 0 if f.version is 'unknown' and f.version_evidence.strings_checked > 0 #and f.format? and f.format isnt 'pdf' f.version = 'acceptedVersion' try ls = await @svc.lantern.licence undefined, undefined, lowercontentsmall # check lantern for licence info in the file content if ls?.licence? f.licence = ls.licence f.licence_evidence = {string_match: ls.match} f.lantern = ls f.archivable = false if confirmed f.archivable = true if confirmed is f.checksum f.archivable_reason = 'The administrator has confirmed that this file is a version that can be archived.' f.admin_confirms = true else f.archivable_reason = 'The depositor says that this file is a version that can be archived' f.depositor_says = true else if f.same_paper if f.format isnt 'pdf' f.archivable = true f.archivable_reason = 'Since the file is not a PDF, we assume it is a Postprint.' if not f.archivable and f.licence? and f.licence.toLowerCase().startsWith 'cc' f.archivable = true f.archivable_reason = 'It appears this file contains a ' + f.lantern.licence + ' licence statement. Under this licence the article can be archived' if not f.archivable if f.version is 'publishedVersion' f.archivable_reason = 'The file given is a Publisher PDF, and only postprints are allowed' else f.archivable_reason = 'We cannot confirm if it is an archivable version or not' else f.archivable_reason ?= if not f.same_paper_evidence.words_more_than_threshold then 'The file is less than 500 words, and so does not appear to be a full article' else if not f.same_paper_evidence.document_format then 'File is an unexpected format ' + f.format else if not meta.doi and not meta.title then 'We have insufficient metadata to validate file is for the correct paper ' else 'File does not contain expected metadata such as DOI or title' return f
[ { "context": "maximum of props on a single line in JSX\n# @author Yannick Croissant\n###\n'use strict'\n\n# -----------------------------", "end": 95, "score": 0.9998496770858765, "start": 78, "tag": "NAME", "value": "Yannick Croissant" } ]
src/tests/rules/jsx-max-props-per-line.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Limit maximum of props on a single line in JSX # @author Yannick Croissant ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/jsx-max-props-per-line' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'jsx-max-props-per-line', rule, valid: [ code: '<App />' , code: '<App foo />' , code: '<App foo bar />' options: [maximum: 2] , code: '<App foo bar />' options: [when: 'multiline'] , code: '<App foo {...this.props} />' options: [when: 'multiline'] , code: '<App foo bar baz />' options: [maximum: 2, when: 'multiline'] , code: '<App {...this.props} bar />' options: [maximum: 2] , code: ['<App', ' foo', ' bar', '/>'].join '\n' , code: ['<App', ' foo bar', ' baz', '/>'].join '\n' options: [maximum: 2] ] invalid: [ code: '<App foo bar baz />' # output: ['<App foo', 'bar', 'baz />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: '<App foo bar baz />' # output: ['<App foo bar', 'baz />'].join '\n' options: [maximum: 2] errors: [message: 'Prop `baz` must be placed on a new line'] , code: '<App {...this.props} bar />' # output: ['<App {...this.props}', 'bar />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: '<App bar {...this.props} />' # output: ['<App bar', '{...this.props} />'].join '\n' errors: [message: 'Prop `this.props` must be placed on a new line'] , code: ['<App', ' foo bar', ' baz', '/>'].join '\n' # output: ['<App', ' foo', 'bar', ' baz', '/>'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App', ' foo {...this.props}', ' baz', '/>'].join '\n' # output: ['<App', ' foo', '{...this.props}', ' baz', '/>'].join '\n' errors: [message: 'Prop `this.props` must be placed on a new line'] , code: ['<App', ' foo={{', ' }} bar', '/>'].join '\n' # output: ['<App', ' foo={{', ' }}', 'bar', '/>'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App foo={{', '}} bar />'].join '\n' # output: ['<App foo={{', '}}', 'bar />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App foo bar={{', '}} baz />'].join '\n' # output: ['<App foo bar={{', '}}', 'baz />'].join '\n' options: [maximum: 2] errors: [message: 'Prop `baz` must be placed on a new line'] , code: ['<App foo={{', '}} {...rest} />'].join '\n' # output: ['<App foo={{', '}}', '{...rest} />'].join '\n' errors: [message: 'Prop `rest` must be placed on a new line'] , code: ['<App {', ' ...this.props', '} bar />'].join '\n' # output: ['<App {', ' ...this.props', '}', 'bar />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App {', ' ...this.props', '} {', ' ...rest', '} />'].join '\n' # output: ['<App {', ' ...this.props', '}', '{', ' ...rest', '} />'].join( # '\n' # ) errors: [message: 'Prop `rest` must be placed on a new line'] , code: ['<App', ' foo={{', ' }} bar baz bor', '/>'].join '\n' # output: ['<App', ' foo={{', ' }} bar', 'baz bor', '/>'].join '\n' options: [maximum: 2] errors: [message: 'Prop `baz` must be placed on a new line'] ]
157363
###* # @fileoverview Limit maximum of props on a single line in JSX # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/jsx-max-props-per-line' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'jsx-max-props-per-line', rule, valid: [ code: '<App />' , code: '<App foo />' , code: '<App foo bar />' options: [maximum: 2] , code: '<App foo bar />' options: [when: 'multiline'] , code: '<App foo {...this.props} />' options: [when: 'multiline'] , code: '<App foo bar baz />' options: [maximum: 2, when: 'multiline'] , code: '<App {...this.props} bar />' options: [maximum: 2] , code: ['<App', ' foo', ' bar', '/>'].join '\n' , code: ['<App', ' foo bar', ' baz', '/>'].join '\n' options: [maximum: 2] ] invalid: [ code: '<App foo bar baz />' # output: ['<App foo', 'bar', 'baz />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: '<App foo bar baz />' # output: ['<App foo bar', 'baz />'].join '\n' options: [maximum: 2] errors: [message: 'Prop `baz` must be placed on a new line'] , code: '<App {...this.props} bar />' # output: ['<App {...this.props}', 'bar />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: '<App bar {...this.props} />' # output: ['<App bar', '{...this.props} />'].join '\n' errors: [message: 'Prop `this.props` must be placed on a new line'] , code: ['<App', ' foo bar', ' baz', '/>'].join '\n' # output: ['<App', ' foo', 'bar', ' baz', '/>'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App', ' foo {...this.props}', ' baz', '/>'].join '\n' # output: ['<App', ' foo', '{...this.props}', ' baz', '/>'].join '\n' errors: [message: 'Prop `this.props` must be placed on a new line'] , code: ['<App', ' foo={{', ' }} bar', '/>'].join '\n' # output: ['<App', ' foo={{', ' }}', 'bar', '/>'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App foo={{', '}} bar />'].join '\n' # output: ['<App foo={{', '}}', 'bar />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App foo bar={{', '}} baz />'].join '\n' # output: ['<App foo bar={{', '}}', 'baz />'].join '\n' options: [maximum: 2] errors: [message: 'Prop `baz` must be placed on a new line'] , code: ['<App foo={{', '}} {...rest} />'].join '\n' # output: ['<App foo={{', '}}', '{...rest} />'].join '\n' errors: [message: 'Prop `rest` must be placed on a new line'] , code: ['<App {', ' ...this.props', '} bar />'].join '\n' # output: ['<App {', ' ...this.props', '}', 'bar />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App {', ' ...this.props', '} {', ' ...rest', '} />'].join '\n' # output: ['<App {', ' ...this.props', '}', '{', ' ...rest', '} />'].join( # '\n' # ) errors: [message: 'Prop `rest` must be placed on a new line'] , code: ['<App', ' foo={{', ' }} bar baz bor', '/>'].join '\n' # output: ['<App', ' foo={{', ' }} bar', 'baz bor', '/>'].join '\n' options: [maximum: 2] errors: [message: 'Prop `baz` must be placed on a new line'] ]
true
###* # @fileoverview Limit maximum of props on a single line in JSX # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/jsx-max-props-per-line' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'jsx-max-props-per-line', rule, valid: [ code: '<App />' , code: '<App foo />' , code: '<App foo bar />' options: [maximum: 2] , code: '<App foo bar />' options: [when: 'multiline'] , code: '<App foo {...this.props} />' options: [when: 'multiline'] , code: '<App foo bar baz />' options: [maximum: 2, when: 'multiline'] , code: '<App {...this.props} bar />' options: [maximum: 2] , code: ['<App', ' foo', ' bar', '/>'].join '\n' , code: ['<App', ' foo bar', ' baz', '/>'].join '\n' options: [maximum: 2] ] invalid: [ code: '<App foo bar baz />' # output: ['<App foo', 'bar', 'baz />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: '<App foo bar baz />' # output: ['<App foo bar', 'baz />'].join '\n' options: [maximum: 2] errors: [message: 'Prop `baz` must be placed on a new line'] , code: '<App {...this.props} bar />' # output: ['<App {...this.props}', 'bar />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: '<App bar {...this.props} />' # output: ['<App bar', '{...this.props} />'].join '\n' errors: [message: 'Prop `this.props` must be placed on a new line'] , code: ['<App', ' foo bar', ' baz', '/>'].join '\n' # output: ['<App', ' foo', 'bar', ' baz', '/>'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App', ' foo {...this.props}', ' baz', '/>'].join '\n' # output: ['<App', ' foo', '{...this.props}', ' baz', '/>'].join '\n' errors: [message: 'Prop `this.props` must be placed on a new line'] , code: ['<App', ' foo={{', ' }} bar', '/>'].join '\n' # output: ['<App', ' foo={{', ' }}', 'bar', '/>'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App foo={{', '}} bar />'].join '\n' # output: ['<App foo={{', '}}', 'bar />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App foo bar={{', '}} baz />'].join '\n' # output: ['<App foo bar={{', '}}', 'baz />'].join '\n' options: [maximum: 2] errors: [message: 'Prop `baz` must be placed on a new line'] , code: ['<App foo={{', '}} {...rest} />'].join '\n' # output: ['<App foo={{', '}}', '{...rest} />'].join '\n' errors: [message: 'Prop `rest` must be placed on a new line'] , code: ['<App {', ' ...this.props', '} bar />'].join '\n' # output: ['<App {', ' ...this.props', '}', 'bar />'].join '\n' errors: [message: 'Prop `bar` must be placed on a new line'] , code: ['<App {', ' ...this.props', '} {', ' ...rest', '} />'].join '\n' # output: ['<App {', ' ...this.props', '}', '{', ' ...rest', '} />'].join( # '\n' # ) errors: [message: 'Prop `rest` must be placed on a new line'] , code: ['<App', ' foo={{', ' }} bar baz bor', '/>'].join '\n' # output: ['<App', ' foo={{', ' }} bar', 'baz bor', '/>'].join '\n' options: [maximum: 2] errors: [message: 'Prop `baz` must be placed on a new line'] ]
[ { "context": "omjs์™€ ํ†ต์‹ ํ•  ํฌํŠธ\n}\nnaver = {\n id = '๋„ค์ด๋ฒ„ ์•„์ด๋””'\n pw = '๋„ค์ด๋ฒ„ ๋น„๋ฐ€๋ฒˆํ˜ธ'\n chat_room = |https://chat.cafe.naver.com/room/", "end": 574, "score": 0.9740051627159119, "start": 566, "tag": "NAME", "value": "๋„ค์ด๋ฒ„ ๋น„๋ฐ€๋ฒˆํ˜ธ" }, { "context": "= false # ssh ์—ฌ๋ถ€\n nick = 'never' # ๋ด‡ ๋‹‰๋„ค์ž„\n channel = '#nev", "end": 849, "score": 0.9218568801879883, "start": 844, "tag": "USERNAME", "value": "never" }, { "context": "# ssh ์—ฌ๋ถ€\n nick = 'never' # ๋ด‡ ๋‹‰๋„ค์ž„\n channel = '#never_cafe_chat' # ์ ‘์†ํ• ", "end": 877, "score": 0.5362552404403687, "start": 876, "tag": "NAME", "value": "๋ด‡" } ]
sample-config.cson
disjukr/never-cafe-chat
6
# ์ด ํŒŒ์ผ์€ ์ƒ˜ํ”Œ์ž…๋‹ˆ๋‹ค. # ์ด ํŒŒ์ผ์„ ๋ณต์‚ฌํ•˜์—ฌ ๊ฐ™์€ ๊ฒฝ๋กœ์— config.cson ํŒŒ์ผ์„ ๋งŒ๋“ค๊ณ  ์›ํ•˜๋Š” ์ •๋ณด๋กœ ์ˆ˜์ •ํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค. # ์ด ์„ค์ •ํŒŒ์ผ์˜ ํฌ๋งท์— ๋Œ€ํ•ด์„œ๋Š” http://noe.mearie.org/cson/ ์ด ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•ด์ฃผ์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. user-agent = |Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 phantom = { args = [ # phantomjs ์ปค๋งจ๋“œ๋ผ์ธ ์ธ์ž '--ignore-ssl-errors=true' '--web-security=false' '--load-images=false' '--cookies-file=cookie.txt' ] port = 5353 # phantomjs์™€ ํ†ต์‹ ํ•  ํฌํŠธ } naver = { id = '๋„ค์ด๋ฒ„ ์•„์ด๋””' pw = '๋„ค์ด๋ฒ„ ๋น„๋ฐ€๋ฒˆํ˜ธ' chat_room = |https://chat.cafe.naver.com/room/00000000/sample:0000000000000 # ์ฑ„ํŒ…๋ฐฉ ์ฃผ์†Œ } irc = { server = 'irc.ozinger.org' # ๋ด‡์ด ๋“ค์–ด๊ฐˆ irc ์„œ๋ฒ„. port = 6667 # irc ์„œ๋ฒ„ ํฌํŠธ. secure = false # ssh ์—ฌ๋ถ€ nick = 'never' # ๋ด‡ ๋‹‰๋„ค์ž„ channel = '#never_cafe_chat' # ์ ‘์†ํ•  irc ์ฑ„๋„ optional-relay = false # ๋ด‡์ด ๋ฉ˜์…˜๋œ ๊ฒฝ์šฐ์—๋งŒ ์นดํŽ˜ ์ฑ„ํŒ…์œผ๋กœ ์ค‘๊ณ„ }
130636
# ์ด ํŒŒ์ผ์€ ์ƒ˜ํ”Œ์ž…๋‹ˆ๋‹ค. # ์ด ํŒŒ์ผ์„ ๋ณต์‚ฌํ•˜์—ฌ ๊ฐ™์€ ๊ฒฝ๋กœ์— config.cson ํŒŒ์ผ์„ ๋งŒ๋“ค๊ณ  ์›ํ•˜๋Š” ์ •๋ณด๋กœ ์ˆ˜์ •ํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค. # ์ด ์„ค์ •ํŒŒ์ผ์˜ ํฌ๋งท์— ๋Œ€ํ•ด์„œ๋Š” http://noe.mearie.org/cson/ ์ด ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•ด์ฃผ์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. user-agent = |Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 phantom = { args = [ # phantomjs ์ปค๋งจ๋“œ๋ผ์ธ ์ธ์ž '--ignore-ssl-errors=true' '--web-security=false' '--load-images=false' '--cookies-file=cookie.txt' ] port = 5353 # phantomjs์™€ ํ†ต์‹ ํ•  ํฌํŠธ } naver = { id = '๋„ค์ด๋ฒ„ ์•„์ด๋””' pw = '<NAME>' chat_room = |https://chat.cafe.naver.com/room/00000000/sample:0000000000000 # ์ฑ„ํŒ…๋ฐฉ ์ฃผ์†Œ } irc = { server = 'irc.ozinger.org' # ๋ด‡์ด ๋“ค์–ด๊ฐˆ irc ์„œ๋ฒ„. port = 6667 # irc ์„œ๋ฒ„ ํฌํŠธ. secure = false # ssh ์—ฌ๋ถ€ nick = 'never' # <NAME> ๋‹‰๋„ค์ž„ channel = '#never_cafe_chat' # ์ ‘์†ํ•  irc ์ฑ„๋„ optional-relay = false # ๋ด‡์ด ๋ฉ˜์…˜๋œ ๊ฒฝ์šฐ์—๋งŒ ์นดํŽ˜ ์ฑ„ํŒ…์œผ๋กœ ์ค‘๊ณ„ }
true
# ์ด ํŒŒ์ผ์€ ์ƒ˜ํ”Œ์ž…๋‹ˆ๋‹ค. # ์ด ํŒŒ์ผ์„ ๋ณต์‚ฌํ•˜์—ฌ ๊ฐ™์€ ๊ฒฝ๋กœ์— config.cson ํŒŒ์ผ์„ ๋งŒ๋“ค๊ณ  ์›ํ•˜๋Š” ์ •๋ณด๋กœ ์ˆ˜์ •ํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค. # ์ด ์„ค์ •ํŒŒ์ผ์˜ ํฌ๋งท์— ๋Œ€ํ•ด์„œ๋Š” http://noe.mearie.org/cson/ ์ด ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•ด์ฃผ์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. user-agent = |Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 phantom = { args = [ # phantomjs ์ปค๋งจ๋“œ๋ผ์ธ ์ธ์ž '--ignore-ssl-errors=true' '--web-security=false' '--load-images=false' '--cookies-file=cookie.txt' ] port = 5353 # phantomjs์™€ ํ†ต์‹ ํ•  ํฌํŠธ } naver = { id = '๋„ค์ด๋ฒ„ ์•„์ด๋””' pw = 'PI:NAME:<NAME>END_PI' chat_room = |https://chat.cafe.naver.com/room/00000000/sample:0000000000000 # ์ฑ„ํŒ…๋ฐฉ ์ฃผ์†Œ } irc = { server = 'irc.ozinger.org' # ๋ด‡์ด ๋“ค์–ด๊ฐˆ irc ์„œ๋ฒ„. port = 6667 # irc ์„œ๋ฒ„ ํฌํŠธ. secure = false # ssh ์—ฌ๋ถ€ nick = 'never' # PI:NAME:<NAME>END_PI ๋‹‰๋„ค์ž„ channel = '#never_cafe_chat' # ์ ‘์†ํ•  irc ์ฑ„๋„ optional-relay = false # ๋ด‡์ด ๋ฉ˜์…˜๋œ ๊ฒฝ์šฐ์—๋งŒ ์นดํŽ˜ ์ฑ„ํŒ…์œผ๋กœ ์ค‘๊ณ„ }
[ { "context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)\n# MIT Licensed\n###\n\nrequire.p", "end": 44, "score": 0.9998378753662109, "start": 36, "tag": "NAME", "value": "Jae Kwon" }, { "context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)\n# MIT Licensed\n###\n\nrequire.paths.unshift 'vendo", "end": 63, "score": 0.9999312162399292, "start": 46, "tag": "EMAIL", "value": "jae@ycatalyst.com" } ]
logic/referrals.coffee
jaekwon/YCatalyst
3
### # YCatalyst # Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com) # MIT Licensed ### require.paths.unshift 'vendor' mongo = require '../mongo' mailer = require './mailer' utils = require '../utils' config = require '../config' # submit/create a new referral. # referral = :first_name, :last_name, :email, :referred_by exports.submit = (referral, cb) -> referral._id = utils.randid() referral.created_at = new Date() # look for a previous referral with the same email mongo.referrals.findOne {email: referral.email}, (err, existing) -> if err cb(err) return if existing cb('That user appears to already have been referred') return mongo.referrals.save referral, (err, stuff) -> cb(err) if not err # send an email to the email mailer.send_referral referral, (err) -> cb(err)
201752
### # YCatalyst # Copyright(c) 2011 <NAME> (<EMAIL>) # MIT Licensed ### require.paths.unshift 'vendor' mongo = require '../mongo' mailer = require './mailer' utils = require '../utils' config = require '../config' # submit/create a new referral. # referral = :first_name, :last_name, :email, :referred_by exports.submit = (referral, cb) -> referral._id = utils.randid() referral.created_at = new Date() # look for a previous referral with the same email mongo.referrals.findOne {email: referral.email}, (err, existing) -> if err cb(err) return if existing cb('That user appears to already have been referred') return mongo.referrals.save referral, (err, stuff) -> cb(err) if not err # send an email to the email mailer.send_referral referral, (err) -> cb(err)
true
### # YCatalyst # Copyright(c) 2011 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # MIT Licensed ### require.paths.unshift 'vendor' mongo = require '../mongo' mailer = require './mailer' utils = require '../utils' config = require '../config' # submit/create a new referral. # referral = :first_name, :last_name, :email, :referred_by exports.submit = (referral, cb) -> referral._id = utils.randid() referral.created_at = new Date() # look for a previous referral with the same email mongo.referrals.findOne {email: referral.email}, (err, existing) -> if err cb(err) return if existing cb('That user appears to already have been referred') return mongo.referrals.save referral, (err, stuff) -> cb(err) if not err # send an email to the email mailer.send_referral referral, (err) -> cb(err)