code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
import Ember from 'ember'; export default Ember.Component.extend({ tagName : '', item : null, isFollowing : false, isLoggedIn : false, init() { this.set('isLoggedIn', !!this.get('application.user.login')); if (this.get('application.places.length') > 0) { this.set('isFollowing', !!this.get('application.places').findBy('id', this.get('item.id'))); } } });
b37t1td/barapp-freecodecamp
client/app/components/user-following.js
JavaScript
mit
389
const ircFramework = require('irc-framework') const store = require('../store') const attachEvents = require('./attachEvents') const connect = connection => { const state = store.getState() let ircClient = state.ircClients[connection.id] if (!ircClient) { ircClient = new ircFramework.Client({ nick: connection.nick, host: connection.host, port: connection.port, tls: connection.tls, username: connection.username || connection.nick, password: connection.password, // "Not enough parameters" with empty gecos so a space is used. gecos: connection.gecos || ' ', // Custom auto reconnect mechanism is implemented, see events/connection.js. auto_reconnect: false, }) attachEvents(ircClient, connection.id) store.dispatch({ type: 'SET_IRC_CLIENT', payload: { connectionId: connection.id, ircClient, }, }) } ircClient.connect() } module.exports = connect
daGrevis/msks
backend/src/irc/connect.js
JavaScript
mit
982
const assert = require('assert') const { unparse } = require('uuid-parse') const supertest = require('supertest') const createApp = require('../app') const { createSetup, getAuthPassword } = require('./lib') const { createPlayer, createKick } = require('./fixtures') describe('Query player kick', () => { let setup let request beforeAll(async () => { setup = await createSetup() const app = await createApp({ ...setup, disableUI: true }) request = supertest(app.callback()) }, 20000) afterAll(async () => { await setup.teardown() }, 20000) test('should resolve all fields', async () => { const { config: server, pool } = setup.serversPool.values().next().value const cookie = await getAuthPassword(request, 'admin@banmanagement.com') const player = createPlayer() const actor = createPlayer() const kick = createKick(player, actor) await pool('bm_players').insert([player, actor]) await pool('bm_player_kicks').insert(kick) const { body, statusCode } = await request .post('/graphql') .set('Cookie', cookie) .set('Accept', 'application/json') .send({ query: `query playerKick { playerKick(id:"1", serverId: "${server.id}") { id reason created actor { id name } acl { update delete yours } } }` }) assert.strictEqual(statusCode, 200) assert(body) assert(body.data) assert.deepStrictEqual(body.data.playerKick, { id: '1', reason: kick.reason, created: kick.created, actor: { id: unparse(actor.id), name: actor.name }, acl: { delete: true, update: true, yours: false } }) }) })
BanManagement/BanManager-WebUI
server/test/playerKick.query.test.js
JavaScript
mit
1,807
var assert = require('chai').assert var sendgrid = require('../lib/sendgrid'); describe('test_access_settings_activity_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["limit"] = '1' request.method = 'GET' request.path = '/v3/access_settings/activity' request.headers['X-Mock'] = 200 it('test_access_settings_activity_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_access_settings_whitelist_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "ips": [ { "ip": "192.168.1.1" }, { "ip": "192.*.*.*" }, { "ip": "192.168.1.3/32" } ] }; request.method = 'POST' request.path = '/v3/access_settings/whitelist' request.headers['X-Mock'] = 201 it('test_access_settings_whitelist_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_access_settings_whitelist_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/access_settings/whitelist' request.headers['X-Mock'] = 200 it('test_access_settings_whitelist_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_access_settings_whitelist_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "ids": [ 1, 2, 3 ] }; request.method = 'DELETE' request.path = '/v3/access_settings/whitelist' request.headers['X-Mock'] = 204 it('test_access_settings_whitelist_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_access_settings_whitelist__rule_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/access_settings/whitelist/{rule_id}' request.headers['X-Mock'] = 200 it('test_access_settings_whitelist__rule_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_access_settings_whitelist__rule_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/access_settings/whitelist/{rule_id}' request.headers['X-Mock'] = 204 it('test_access_settings_whitelist__rule_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_alerts_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "email_to": "example@example.com", "frequency": "daily", "type": "stats_notification" }; request.method = 'POST' request.path = '/v3/alerts' request.headers['X-Mock'] = 201 it('test_alerts_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_alerts_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/alerts' request.headers['X-Mock'] = 200 it('test_alerts_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_alerts__alert_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "email_to": "example@example.com" }; request.method = 'PATCH' request.path = '/v3/alerts/{alert_id}' request.headers['X-Mock'] = 200 it('test_alerts__alert_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_alerts__alert_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/alerts/{alert_id}' request.headers['X-Mock'] = 200 it('test_alerts__alert_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_alerts__alert_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/alerts/{alert_id}' request.headers['X-Mock'] = 204 it('test_alerts__alert_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_api_keys_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "My API Key", "sample": "data", "scopes": [ "mail.send", "alerts.create", "alerts.read" ] }; request.method = 'POST' request.path = '/v3/api_keys' request.headers['X-Mock'] = 201 it('test_api_keys_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_api_keys_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["limit"] = '1' request.method = 'GET' request.path = '/v3/api_keys' request.headers['X-Mock'] = 200 it('test_api_keys_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_api_keys__api_key_id__put', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "A New Hope", "scopes": [ "user.profile.read", "user.profile.update" ] }; request.method = 'PUT' request.path = '/v3/api_keys/{api_key_id}' request.headers['X-Mock'] = 200 it('test_api_keys__api_key_id__put had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_api_keys__api_key_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "A New Hope" }; request.method = 'PATCH' request.path = '/v3/api_keys/{api_key_id}' request.headers['X-Mock'] = 200 it('test_api_keys__api_key_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_api_keys__api_key_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/api_keys/{api_key_id}' request.headers['X-Mock'] = 200 it('test_api_keys__api_key_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_api_keys__api_key_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/api_keys/{api_key_id}' request.headers['X-Mock'] = 204 it('test_api_keys__api_key_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_asm_groups_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "description": "Suggestions for products our users might like.", "is_default": true, "name": "Product Suggestions" }; request.method = 'POST' request.path = '/v3/asm/groups' request.headers['X-Mock'] = 201 it('test_asm_groups_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_asm_groups_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["id"] = '1' request.method = 'GET' request.path = '/v3/asm/groups' request.headers['X-Mock'] = 200 it('test_asm_groups_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_asm_groups__group_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "description": "Suggestions for items our users might like.", "id": 103, "name": "Item Suggestions" }; request.method = 'PATCH' request.path = '/v3/asm/groups/{group_id}' request.headers['X-Mock'] = 201 it('test_asm_groups__group_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_asm_groups__group_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/asm/groups/{group_id}' request.headers['X-Mock'] = 200 it('test_asm_groups__group_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_asm_groups__group_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/asm/groups/{group_id}' request.headers['X-Mock'] = 204 it('test_asm_groups__group_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_asm_groups__group_id__suppressions_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "recipient_emails": [ "test1@example.com", "test2@example.com" ] }; request.method = 'POST' request.path = '/v3/asm/groups/{group_id}/suppressions' request.headers['X-Mock'] = 201 it('test_asm_groups__group_id__suppressions_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_asm_groups__group_id__suppressions_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/asm/groups/{group_id}/suppressions' request.headers['X-Mock'] = 200 it('test_asm_groups__group_id__suppressions_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_asm_groups__group_id__suppressions_search_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "recipient_emails": [ "exists1@example.com", "exists2@example.com", "doesnotexists@example.com" ] }; request.method = 'POST' request.path = '/v3/asm/groups/{group_id}/suppressions/search' request.headers['X-Mock'] = 200 it('test_asm_groups__group_id__suppressions_search_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_asm_groups__group_id__suppressions__email__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/asm/groups/{group_id}/suppressions/{email}' request.headers['X-Mock'] = 204 it('test_asm_groups__group_id__suppressions__email__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_asm_suppressions_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/asm/suppressions' request.headers['X-Mock'] = 200 it('test_asm_suppressions_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_asm_suppressions_global_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "recipient_emails": [ "test1@example.com", "test2@example.com" ] }; request.method = 'POST' request.path = '/v3/asm/suppressions/global' request.headers['X-Mock'] = 201 it('test_asm_suppressions_global_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_asm_suppressions_global__email__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/asm/suppressions/global/{email}' request.headers['X-Mock'] = 200 it('test_asm_suppressions_global__email__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_asm_suppressions_global__email__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/asm/suppressions/global/{email}' request.headers['X-Mock'] = 204 it('test_asm_suppressions_global__email__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_asm_suppressions__email__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/asm/suppressions/{email}' request.headers['X-Mock'] = 200 it('test_asm_suppressions__email__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_browsers_stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["end_date"] = '2016-04-01' request.queryParams["aggregated_by"] = 'day' request.queryParams["browsers"] = 'test_string' request.queryParams["limit"] = 'test_string' request.queryParams["offset"] = 'test_string' request.queryParams["start_date"] = '2016-01-01' request.method = 'GET' request.path = '/v3/browsers/stats' request.headers['X-Mock'] = 200 it('test_browsers_stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_campaigns_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "categories": [ "spring line" ], "custom_unsubscribe_url": "", "html_content": "<html><head><title></title></head><body><p>Check out our spring line!</p></body></html>", "ip_pool": "marketing", "list_ids": [ 110, 124 ], "plain_content": "Check out our spring line!", "segment_ids": [ 110 ], "sender_id": 124451, "subject": "New Products for Spring!", "suppression_group_id": 42, "title": "March Newsletter" }; request.method = 'POST' request.path = '/v3/campaigns' request.headers['X-Mock'] = 201 it('test_campaigns_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_campaigns_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/campaigns' request.headers['X-Mock'] = 200 it('test_campaigns_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_campaigns__campaign_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "categories": [ "summer line" ], "html_content": "<html><head><title></title></head><body><p>Check out our summer line!</p></body></html>", "plain_content": "Check out our summer line!", "subject": "New Products for Summer!", "title": "May Newsletter" }; request.method = 'PATCH' request.path = '/v3/campaigns/{campaign_id}' request.headers['X-Mock'] = 200 it('test_campaigns__campaign_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_campaigns__campaign_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/campaigns/{campaign_id}' request.headers['X-Mock'] = 200 it('test_campaigns__campaign_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_campaigns__campaign_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/campaigns/{campaign_id}' request.headers['X-Mock'] = 204 it('test_campaigns__campaign_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_campaigns__campaign_id__schedules_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "send_at": 1489451436 }; request.method = 'PATCH' request.path = '/v3/campaigns/{campaign_id}/schedules' request.headers['X-Mock'] = 200 it('test_campaigns__campaign_id__schedules_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_campaigns__campaign_id__schedules_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "send_at": 1489771528 }; request.method = 'POST' request.path = '/v3/campaigns/{campaign_id}/schedules' request.headers['X-Mock'] = 201 it('test_campaigns__campaign_id__schedules_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_campaigns__campaign_id__schedules_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/campaigns/{campaign_id}/schedules' request.headers['X-Mock'] = 200 it('test_campaigns__campaign_id__schedules_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_campaigns__campaign_id__schedules_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/campaigns/{campaign_id}/schedules' request.headers['X-Mock'] = 204 it('test_campaigns__campaign_id__schedules_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_campaigns__campaign_id__schedules_now_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'POST' request.path = '/v3/campaigns/{campaign_id}/schedules/now' request.headers['X-Mock'] = 201 it('test_campaigns__campaign_id__schedules_now_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_campaigns__campaign_id__schedules_test_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "to": "your.email@example.com" }; request.method = 'POST' request.path = '/v3/campaigns/{campaign_id}/schedules/test' request.headers['X-Mock'] = 204 it('test_campaigns__campaign_id__schedules_test_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_categories_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["category"] = 'test_string' request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/categories' request.headers['X-Mock'] = 200 it('test_categories_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_categories_stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["end_date"] = '2016-04-01' request.queryParams["aggregated_by"] = 'day' request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.queryParams["start_date"] = '2016-01-01' request.queryParams["categories"] = 'test_string' request.method = 'GET' request.path = '/v3/categories/stats' request.headers['X-Mock'] = 200 it('test_categories_stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_categories_stats_sums_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["end_date"] = '2016-04-01' request.queryParams["aggregated_by"] = 'day' request.queryParams["limit"] = '1' request.queryParams["sort_by_metric"] = 'test_string' request.queryParams["offset"] = '1' request.queryParams["start_date"] = '2016-01-01' request.queryParams["sort_by_direction"] = 'asc' request.method = 'GET' request.path = '/v3/categories/stats/sums' request.headers['X-Mock'] = 200 it('test_categories_stats_sums_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_clients_stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["aggregated_by"] = 'day' request.queryParams["start_date"] = '2016-01-01' request.queryParams["end_date"] = '2016-04-01' request.method = 'GET' request.path = '/v3/clients/stats' request.headers['X-Mock'] = 200 it('test_clients_stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_clients__client_type__stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["aggregated_by"] = 'day' request.queryParams["start_date"] = '2016-01-01' request.queryParams["end_date"] = '2016-04-01' request.method = 'GET' request.path = '/v3/clients/{client_type}/stats' request.headers['X-Mock'] = 200 it('test_clients__client_type__stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_custom_fields_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "pet", "type": "text" }; request.method = 'POST' request.path = '/v3/contactdb/custom_fields' request.headers['X-Mock'] = 201 it('test_contactdb_custom_fields_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_contactdb_custom_fields_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/contactdb/custom_fields' request.headers['X-Mock'] = 200 it('test_contactdb_custom_fields_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_custom_fields__custom_field_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/contactdb/custom_fields/{custom_field_id}' request.headers['X-Mock'] = 200 it('test_contactdb_custom_fields__custom_field_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_custom_fields__custom_field_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/contactdb/custom_fields/{custom_field_id}' request.headers['X-Mock'] = 202 it('test_contactdb_custom_fields__custom_field_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 202, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "your list name" }; request.method = 'POST' request.path = '/v3/contactdb/lists' request.headers['X-Mock'] = 201 it('test_contactdb_lists_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/contactdb/lists' request.headers['X-Mock'] = 200 it('test_contactdb_lists_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = [ 1, 2, 3, 4 ]; request.method = 'DELETE' request.path = '/v3/contactdb/lists' request.headers['X-Mock'] = 204 it('test_contactdb_lists_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists__list_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "newlistname" }; request.queryParams["list_id"] = '1' request.method = 'PATCH' request.path = '/v3/contactdb/lists/{list_id}' request.headers['X-Mock'] = 200 it('test_contactdb_lists__list_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists__list_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["list_id"] = '1' request.method = 'GET' request.path = '/v3/contactdb/lists/{list_id}' request.headers['X-Mock'] = 200 it('test_contactdb_lists__list_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists__list_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.queryParams["delete_contacts"] = 'true' request.method = 'DELETE' request.path = '/v3/contactdb/lists/{list_id}' request.headers['X-Mock'] = 202 it('test_contactdb_lists__list_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 202, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists__list_id__recipients_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = [ "recipient_id1", "recipient_id2" ]; request.method = 'POST' request.path = '/v3/contactdb/lists/{list_id}/recipients' request.headers['X-Mock'] = 201 it('test_contactdb_lists__list_id__recipients_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists__list_id__recipients_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["page"] = '1' request.queryParams["page_size"] = '1' request.queryParams["list_id"] = '1' request.method = 'GET' request.path = '/v3/contactdb/lists/{list_id}/recipients' request.headers['X-Mock'] = 200 it('test_contactdb_lists__list_id__recipients_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists__list_id__recipients__recipient_id__post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'POST' request.path = '/v3/contactdb/lists/{list_id}/recipients/{recipient_id}' request.headers['X-Mock'] = 201 it('test_contactdb_lists__list_id__recipients__recipient_id__post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_contactdb_lists__list_id__recipients__recipient_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.queryParams["recipient_id"] = '1' request.queryParams["list_id"] = '1' request.method = 'DELETE' request.path = '/v3/contactdb/lists/{list_id}/recipients/{recipient_id}' request.headers['X-Mock'] = 204 it('test_contactdb_lists__list_id__recipients__recipient_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = [ { "email": "jones@example.com", "first_name": "Guy", "last_name": "Jones" } ]; request.method = 'PATCH' request.path = '/v3/contactdb/recipients' request.headers['X-Mock'] = 201 it('test_contactdb_recipients_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = [ { "age": 25, "email": "example@example.com", "first_name": "", "last_name": "User" }, { "age": 25, "email": "example2@example.com", "first_name": "Example", "last_name": "User" } ]; request.method = 'POST' request.path = '/v3/contactdb/recipients' request.headers['X-Mock'] = 201 it('test_contactdb_recipients_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["page"] = '1' request.queryParams["page_size"] = '1' request.method = 'GET' request.path = '/v3/contactdb/recipients' request.headers['X-Mock'] = 200 it('test_contactdb_recipients_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = [ "recipient_id1", "recipient_id2" ]; request.method = 'DELETE' request.path = '/v3/contactdb/recipients' request.headers['X-Mock'] = 200 it('test_contactdb_recipients_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients_billable_count_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/contactdb/recipients/billable_count' request.headers['X-Mock'] = 200 it('test_contactdb_recipients_billable_count_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients_count_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/contactdb/recipients/count' request.headers['X-Mock'] = 200 it('test_contactdb_recipients_count_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients_search_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["%7Bfield_name%7D"] = 'test_string' request.queryParams["{field_name}"] = 'test_string' request.method = 'GET' request.path = '/v3/contactdb/recipients/search' request.headers['X-Mock'] = 200 it('test_contactdb_recipients_search_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients__recipient_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/contactdb/recipients/{recipient_id}' request.headers['X-Mock'] = 200 it('test_contactdb_recipients__recipient_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients__recipient_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/contactdb/recipients/{recipient_id}' request.headers['X-Mock'] = 204 it('test_contactdb_recipients__recipient_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_contactdb_recipients__recipient_id__lists_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/contactdb/recipients/{recipient_id}/lists' request.headers['X-Mock'] = 200 it('test_contactdb_recipients__recipient_id__lists_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_reserved_fields_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/contactdb/reserved_fields' request.headers['X-Mock'] = 200 it('test_contactdb_reserved_fields_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_segments_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "conditions": [ { "and_or": "", "field": "last_name", "operator": "eq", "value": "Miller" }, { "and_or": "and", "field": "last_clicked", "operator": "gt", "value": "01/02/2015" }, { "and_or": "or", "field": "clicks.campaign_identifier", "operator": "eq", "value": "513" } ], "list_id": 4, "name": "Last Name Miller" }; request.method = 'POST' request.path = '/v3/contactdb/segments' request.headers['X-Mock'] = 200 it('test_contactdb_segments_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_segments_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/contactdb/segments' request.headers['X-Mock'] = 200 it('test_contactdb_segments_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_segments__segment_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "conditions": [ { "and_or": "", "field": "last_name", "operator": "eq", "value": "Miller" } ], "list_id": 5, "name": "The Millers" }; request.queryParams["segment_id"] = 'test_string' request.method = 'PATCH' request.path = '/v3/contactdb/segments/{segment_id}' request.headers['X-Mock'] = 200 it('test_contactdb_segments__segment_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_segments__segment_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["segment_id"] = '1' request.method = 'GET' request.path = '/v3/contactdb/segments/{segment_id}' request.headers['X-Mock'] = 200 it('test_contactdb_segments__segment_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_contactdb_segments__segment_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.queryParams["delete_contacts"] = 'true' request.method = 'DELETE' request.path = '/v3/contactdb/segments/{segment_id}' request.headers['X-Mock'] = 204 it('test_contactdb_segments__segment_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_contactdb_segments__segment_id__recipients_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["page"] = '1' request.queryParams["page_size"] = '1' request.method = 'GET' request.path = '/v3/contactdb/segments/{segment_id}/recipients' request.headers['X-Mock'] = 200 it('test_contactdb_segments__segment_id__recipients_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_devices_stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["aggregated_by"] = 'day' request.queryParams["limit"] = '1' request.queryParams["start_date"] = '2016-01-01' request.queryParams["end_date"] = '2016-04-01' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/devices/stats' request.headers['X-Mock'] = 200 it('test_devices_stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_geo_stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["end_date"] = '2016-04-01' request.queryParams["country"] = 'US' request.queryParams["aggregated_by"] = 'day' request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.queryParams["start_date"] = '2016-01-01' request.method = 'GET' request.path = '/v3/geo/stats' request.headers['X-Mock'] = 200 it('test_geo_stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["subuser"] = 'test_string' request.queryParams["ip"] = 'test_string' request.queryParams["limit"] = '1' request.queryParams["exclude_whitelabels"] = 'true' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/ips' request.headers['X-Mock'] = 200 it('test_ips_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_assigned_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/ips/assigned' request.headers['X-Mock'] = 200 it('test_ips_assigned_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_pools_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "marketing" }; request.method = 'POST' request.path = '/v3/ips/pools' request.headers['X-Mock'] = 200 it('test_ips_pools_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_pools_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/ips/pools' request.headers['X-Mock'] = 200 it('test_ips_pools_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_pools__pool_name__put', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "new_pool_name" }; request.method = 'PUT' request.path = '/v3/ips/pools/{pool_name}' request.headers['X-Mock'] = 200 it('test_ips_pools__pool_name__put had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_pools__pool_name__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/ips/pools/{pool_name}' request.headers['X-Mock'] = 200 it('test_ips_pools__pool_name__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_pools__pool_name__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/ips/pools/{pool_name}' request.headers['X-Mock'] = 204 it('test_ips_pools__pool_name__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_ips_pools__pool_name__ips_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "ip": "0.0.0.0" }; request.method = 'POST' request.path = '/v3/ips/pools/{pool_name}/ips' request.headers['X-Mock'] = 201 it('test_ips_pools__pool_name__ips_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_ips_pools__pool_name__ips__ip__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/ips/pools/{pool_name}/ips/{ip}' request.headers['X-Mock'] = 204 it('test_ips_pools__pool_name__ips__ip__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_ips_warmup_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "ip": "0.0.0.0" }; request.method = 'POST' request.path = '/v3/ips/warmup' request.headers['X-Mock'] = 200 it('test_ips_warmup_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_warmup_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/ips/warmup' request.headers['X-Mock'] = 200 it('test_ips_warmup_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_warmup__ip_address__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/ips/warmup/{ip_address}' request.headers['X-Mock'] = 200 it('test_ips_warmup__ip_address__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_ips_warmup__ip_address__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/ips/warmup/{ip_address}' request.headers['X-Mock'] = 204 it('test_ips_warmup__ip_address__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_ips__ip_address__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/ips/{ip_address}' request.headers['X-Mock'] = 200 it('test_ips__ip_address__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_batch_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'POST' request.path = '/v3/mail/batch' request.headers['X-Mock'] = 201 it('test_mail_batch_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_mail_batch__batch_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail/batch/{batch_id}' request.headers['X-Mock'] = 200 it('test_mail_batch__batch_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_send_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "asm": { "group_id": 1, "groups_to_display": [ 1, 2, 3 ] }, "attachments": [ { "content": "[BASE64 encoded content block here]", "content_id": "ii_139db99fdb5c3704", "disposition": "inline", "filename": "file1.jpg", "name": "file1", "type": "jpg" } ], "batch_id": "[YOUR BATCH ID GOES HERE]", "categories": [ "category1", "category2" ], "content": [ { "type": "text/html", "value": "<html><p>Hello, world!</p><img src=[CID GOES HERE]></img></html>" } ], "custom_args": { "New Argument 1": "New Value 1", "activationAttempt": "1", "customerAccountNumber": "[CUSTOMER ACCOUNT NUMBER GOES HERE]" }, "from": { "email": "sam.smith@example.com", "name": "Sam Smith" }, "headers": {}, "ip_pool_name": "[YOUR POOL NAME GOES HERE]", "mail_settings": { "bcc": { "email": "ben.doe@example.com", "enable": true }, "bypass_list_management": { "enable": true }, "footer": { "enable": true, "html": "<p>Thanks</br>The SendGrid Team</p>", "text": "Thanks,/n The SendGrid Team" }, "sandbox_mode": { "enable": false }, "spam_check": { "enable": true, "post_to_url": "http://example.com/compliance", "threshold": 3 } }, "personalizations": [ { "bcc": [ { "email": "sam.doe@example.com", "name": "Sam Doe" } ], "cc": [ { "email": "jane.doe@example.com", "name": "Jane Doe" } ], "custom_args": { "New Argument 1": "New Value 1", "activationAttempt": "1", "customerAccountNumber": "[CUSTOMER ACCOUNT NUMBER GOES HERE]" }, "headers": { "X-Accept-Language": "en", "X-Mailer": "MyApp" }, "send_at": 1409348513, "subject": "Hello, World!", "substitutions": { "id": "substitutions", "type": "object" }, "to": [ { "email": "john.doe@example.com", "name": "John Doe" } ] } ], "reply_to": { "email": "sam.smith@example.com", "name": "Sam Smith" }, "sections": { "section": { ":sectionName1": "section 1 text", ":sectionName2": "section 2 text" } }, "send_at": 1409348513, "subject": "Hello, World!", "template_id": "[YOUR TEMPLATE ID GOES HERE]", "tracking_settings": { "click_tracking": { "enable": true, "enable_text": true }, "ganalytics": { "enable": true, "utm_campaign": "[NAME OF YOUR REFERRER SOURCE]", "utm_content": "[USE THIS SPACE TO DIFFERENTIATE YOUR EMAIL FROM ADS]", "utm_medium": "[NAME OF YOUR MARKETING MEDIUM e.g. email]", "utm_name": "[NAME OF YOUR CAMPAIGN]", "utm_term": "[IDENTIFY PAID KEYWORDS HERE]" }, "open_tracking": { "enable": true, "substitution_tag": "%opentrack" }, "subscription_tracking": { "enable": true, "html": "If you would like to unsubscribe and stop receiving these emails <% clickhere %>.", "substitution_tag": "<%click here%>", "text": "If you would like to unsubscribe and stop receiveing these emails <% click here %>." } } }; request.method = 'POST' request.path = '/v3/mail/send' request.headers['X-Mock'] = 202 it('test_mail_send_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 202, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/mail_settings' request.headers['X-Mock'] = 200 it('test_mail_settings_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_address_whitelist_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": true, "list": [ "email1@example.com", "example.com" ] }; request.method = 'PATCH' request.path = '/v3/mail_settings/address_whitelist' request.headers['X-Mock'] = 200 it('test_mail_settings_address_whitelist_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_address_whitelist_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail_settings/address_whitelist' request.headers['X-Mock'] = 200 it('test_mail_settings_address_whitelist_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_bcc_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "email": "email@example.com", "enabled": false }; request.method = 'PATCH' request.path = '/v3/mail_settings/bcc' request.headers['X-Mock'] = 200 it('test_mail_settings_bcc_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_bcc_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail_settings/bcc' request.headers['X-Mock'] = 200 it('test_mail_settings_bcc_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_bounce_purge_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": true, "hard_bounces": 5, "soft_bounces": 5 }; request.method = 'PATCH' request.path = '/v3/mail_settings/bounce_purge' request.headers['X-Mock'] = 200 it('test_mail_settings_bounce_purge_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_bounce_purge_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail_settings/bounce_purge' request.headers['X-Mock'] = 200 it('test_mail_settings_bounce_purge_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_footer_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": true, "html_content": "...", "plain_content": "..." }; request.method = 'PATCH' request.path = '/v3/mail_settings/footer' request.headers['X-Mock'] = 200 it('test_mail_settings_footer_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_footer_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail_settings/footer' request.headers['X-Mock'] = 200 it('test_mail_settings_footer_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_forward_bounce_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "email": "example@example.com", "enabled": true }; request.method = 'PATCH' request.path = '/v3/mail_settings/forward_bounce' request.headers['X-Mock'] = 200 it('test_mail_settings_forward_bounce_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_forward_bounce_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail_settings/forward_bounce' request.headers['X-Mock'] = 200 it('test_mail_settings_forward_bounce_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_forward_spam_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "email": "", "enabled": false }; request.method = 'PATCH' request.path = '/v3/mail_settings/forward_spam' request.headers['X-Mock'] = 200 it('test_mail_settings_forward_spam_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_forward_spam_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail_settings/forward_spam' request.headers['X-Mock'] = 200 it('test_mail_settings_forward_spam_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_plain_content_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": false }; request.method = 'PATCH' request.path = '/v3/mail_settings/plain_content' request.headers['X-Mock'] = 200 it('test_mail_settings_plain_content_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_plain_content_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail_settings/plain_content' request.headers['X-Mock'] = 200 it('test_mail_settings_plain_content_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_spam_check_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": true, "max_score": 5, "url": "url" }; request.method = 'PATCH' request.path = '/v3/mail_settings/spam_check' request.headers['X-Mock'] = 200 it('test_mail_settings_spam_check_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_spam_check_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail_settings/spam_check' request.headers['X-Mock'] = 200 it('test_mail_settings_spam_check_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_template_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": true, "html_content": "<% body %>" }; request.method = 'PATCH' request.path = '/v3/mail_settings/template' request.headers['X-Mock'] = 200 it('test_mail_settings_template_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mail_settings_template_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/mail_settings/template' request.headers['X-Mock'] = 200 it('test_mail_settings_template_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_mailbox_providers_stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["end_date"] = '2016-04-01' request.queryParams["mailbox_providers"] = 'test_string' request.queryParams["aggregated_by"] = 'day' request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.queryParams["start_date"] = '2016-01-01' request.method = 'GET' request.path = '/v3/mailbox_providers/stats' request.headers['X-Mock'] = 200 it('test_mailbox_providers_stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_partner_settings_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/partner_settings' request.headers['X-Mock'] = 200 it('test_partner_settings_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_partner_settings_new_relic_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enable_subuser_statistics": true, "enabled": true, "license_key": "" }; request.method = 'PATCH' request.path = '/v3/partner_settings/new_relic' request.headers['X-Mock'] = 200 it('test_partner_settings_new_relic_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_partner_settings_new_relic_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/partner_settings/new_relic' request.headers['X-Mock'] = 200 it('test_partner_settings_new_relic_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_scopes_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/scopes' request.headers['X-Mock'] = 200 it('test_scopes_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["aggregated_by"] = 'day' request.queryParams["limit"] = '1' request.queryParams["start_date"] = '2016-01-01' request.queryParams["end_date"] = '2016-04-01' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/stats' request.headers['X-Mock'] = 200 it('test_stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "email": "John@example.com", "ips": [ "1.1.1.1", "2.2.2.2" ], "password": "johns_password", "username": "John@example.com" }; request.method = 'POST' request.path = '/v3/subusers' request.headers['X-Mock'] = 200 it('test_subusers_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["username"] = 'test_string' request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/subusers' request.headers['X-Mock'] = 200 it('test_subusers_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers_reputations_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["usernames"] = 'test_string' request.method = 'GET' request.path = '/v3/subusers/reputations' request.headers['X-Mock'] = 200 it('test_subusers_reputations_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers_stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["end_date"] = '2016-04-01' request.queryParams["aggregated_by"] = 'day' request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.queryParams["start_date"] = '2016-01-01' request.queryParams["subusers"] = 'test_string' request.method = 'GET' request.path = '/v3/subusers/stats' request.headers['X-Mock'] = 200 it('test_subusers_stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers_stats_monthly_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["subuser"] = 'test_string' request.queryParams["limit"] = '1' request.queryParams["sort_by_metric"] = 'test_string' request.queryParams["offset"] = '1' request.queryParams["date"] = 'test_string' request.queryParams["sort_by_direction"] = 'asc' request.method = 'GET' request.path = '/v3/subusers/stats/monthly' request.headers['X-Mock'] = 200 it('test_subusers_stats_monthly_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers_stats_sums_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["end_date"] = '2016-04-01' request.queryParams["aggregated_by"] = 'day' request.queryParams["limit"] = '1' request.queryParams["sort_by_metric"] = 'test_string' request.queryParams["offset"] = '1' request.queryParams["start_date"] = '2016-01-01' request.queryParams["sort_by_direction"] = 'asc' request.method = 'GET' request.path = '/v3/subusers/stats/sums' request.headers['X-Mock'] = 200 it('test_subusers_stats_sums_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers__subuser_name__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "disabled": false }; request.method = 'PATCH' request.path = '/v3/subusers/{subuser_name}' request.headers['X-Mock'] = 204 it('test_subusers__subuser_name__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_subusers__subuser_name__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/subusers/{subuser_name}' request.headers['X-Mock'] = 204 it('test_subusers__subuser_name__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_subusers__subuser_name__ips_put', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = [ "127.0.0.1" ]; request.method = 'PUT' request.path = '/v3/subusers/{subuser_name}/ips' request.headers['X-Mock'] = 200 it('test_subusers__subuser_name__ips_put had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers__subuser_name__monitor_put', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "email": "example@example.com", "frequency": 500 }; request.method = 'PUT' request.path = '/v3/subusers/{subuser_name}/monitor' request.headers['X-Mock'] = 200 it('test_subusers__subuser_name__monitor_put had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers__subuser_name__monitor_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "email": "example@example.com", "frequency": 50000 }; request.method = 'POST' request.path = '/v3/subusers/{subuser_name}/monitor' request.headers['X-Mock'] = 200 it('test_subusers__subuser_name__monitor_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers__subuser_name__monitor_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/subusers/{subuser_name}/monitor' request.headers['X-Mock'] = 200 it('test_subusers__subuser_name__monitor_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_subusers__subuser_name__monitor_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/subusers/{subuser_name}/monitor' request.headers['X-Mock'] = 204 it('test_subusers__subuser_name__monitor_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_subusers__subuser_name__stats_monthly_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["date"] = 'test_string' request.queryParams["sort_by_direction"] = 'asc' request.queryParams["limit"] = '1' request.queryParams["sort_by_metric"] = 'test_string' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/subusers/{subuser_name}/stats/monthly' request.headers['X-Mock'] = 200 it('test_subusers__subuser_name__stats_monthly_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_suppression_blocks_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["start_time"] = '1' request.queryParams["limit"] = '1' request.queryParams["end_time"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/suppression/blocks' request.headers['X-Mock'] = 200 it('test_suppression_blocks_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_suppression_blocks_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "delete_all": false, "emails": [ "example1@example.com", "example2@example.com" ] }; request.method = 'DELETE' request.path = '/v3/suppression/blocks' request.headers['X-Mock'] = 204 it('test_suppression_blocks_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_suppression_blocks__email__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/suppression/blocks/{email}' request.headers['X-Mock'] = 200 it('test_suppression_blocks__email__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_suppression_blocks__email__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/suppression/blocks/{email}' request.headers['X-Mock'] = 204 it('test_suppression_blocks__email__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_suppression_bounces_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["start_time"] = '1' request.queryParams["end_time"] = '1' request.method = 'GET' request.path = '/v3/suppression/bounces' request.headers['X-Mock'] = 200 it('test_suppression_bounces_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_suppression_bounces_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "delete_all": true, "emails": [ "example@example.com", "example2@example.com" ] }; request.method = 'DELETE' request.path = '/v3/suppression/bounces' request.headers['X-Mock'] = 204 it('test_suppression_bounces_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_suppression_bounces__email__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/suppression/bounces/{email}' request.headers['X-Mock'] = 200 it('test_suppression_bounces__email__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_suppression_bounces__email__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.queryParams["email_address"] = 'example@example.com' request.method = 'DELETE' request.path = '/v3/suppression/bounces/{email}' request.headers['X-Mock'] = 204 it('test_suppression_bounces__email__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_suppression_invalid_emails_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["start_time"] = '1' request.queryParams["limit"] = '1' request.queryParams["end_time"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/suppression/invalid_emails' request.headers['X-Mock'] = 200 it('test_suppression_invalid_emails_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_suppression_invalid_emails_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "delete_all": false, "emails": [ "example1@example.com", "example2@example.com" ] }; request.method = 'DELETE' request.path = '/v3/suppression/invalid_emails' request.headers['X-Mock'] = 204 it('test_suppression_invalid_emails_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_suppression_invalid_emails__email__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/suppression/invalid_emails/{email}' request.headers['X-Mock'] = 200 it('test_suppression_invalid_emails__email__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_suppression_invalid_emails__email__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/suppression/invalid_emails/{email}' request.headers['X-Mock'] = 204 it('test_suppression_invalid_emails__email__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_suppression_spam_reports__email__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/suppression/spam_reports/{email}' request.headers['X-Mock'] = 200 it('test_suppression_spam_reports__email__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_suppression_spam_report__email__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/suppression/spam_report/{email}' request.headers['X-Mock'] = 204 it('test_suppression_spam_report__email__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_suppression_spam_reports_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["start_time"] = '1' request.queryParams["limit"] = '1' request.queryParams["end_time"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/suppression/spam_reports' request.headers['X-Mock'] = 200 it('test_suppression_spam_reports_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_suppression_spam_reports_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "delete_all": false, "emails": [ "example1@example.com", "example2@example.com" ] }; request.method = 'DELETE' request.path = '/v3/suppression/spam_reports' request.headers['X-Mock'] = 204 it('test_suppression_spam_reports_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_suppression_unsubscribes_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["start_time"] = '1' request.queryParams["limit"] = '1' request.queryParams["end_time"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/suppression/unsubscribes' request.headers['X-Mock'] = 200 it('test_suppression_unsubscribes_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_templates_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "example_name" }; request.method = 'POST' request.path = '/v3/templates' request.headers['X-Mock'] = 201 it('test_templates_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_templates_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/templates' request.headers['X-Mock'] = 200 it('test_templates_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_templates__template_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "name": "new_example_name" }; request.method = 'PATCH' request.path = '/v3/templates/{template_id}' request.headers['X-Mock'] = 200 it('test_templates__template_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_templates__template_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/templates/{template_id}' request.headers['X-Mock'] = 200 it('test_templates__template_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_templates__template_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/templates/{template_id}' request.headers['X-Mock'] = 204 it('test_templates__template_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_templates__template_id__versions_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "active": 1, "html_content": "<%body%>", "name": "example_version_name", "plain_content": "<%body%>", "subject": "<%subject%>", "template_id": "ddb96bbc-9b92-425e-8979-99464621b543" }; request.method = 'POST' request.path = '/v3/templates/{template_id}/versions' request.headers['X-Mock'] = 201 it('test_templates__template_id__versions_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_templates__template_id__versions__version_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "active": 1, "html_content": "<%body%>", "name": "updated_example_name", "plain_content": "<%body%>", "subject": "<%subject%>" }; request.method = 'PATCH' request.path = '/v3/templates/{template_id}/versions/{version_id}' request.headers['X-Mock'] = 200 it('test_templates__template_id__versions__version_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_templates__template_id__versions__version_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/templates/{template_id}/versions/{version_id}' request.headers['X-Mock'] = 200 it('test_templates__template_id__versions__version_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_templates__template_id__versions__version_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/templates/{template_id}/versions/{version_id}' request.headers['X-Mock'] = 204 it('test_templates__template_id__versions__version_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_templates__template_id__versions__version_id__activate_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'POST' request.path = '/v3/templates/{template_id}/versions/{version_id}/activate' request.headers['X-Mock'] = 200 it('test_templates__template_id__versions__version_id__activate_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_tracking_settings_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/tracking_settings' request.headers['X-Mock'] = 200 it('test_tracking_settings_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_tracking_settings_click_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": true }; request.method = 'PATCH' request.path = '/v3/tracking_settings/click' request.headers['X-Mock'] = 200 it('test_tracking_settings_click_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_tracking_settings_click_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/tracking_settings/click' request.headers['X-Mock'] = 200 it('test_tracking_settings_click_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_tracking_settings_google_analytics_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": true, "utm_campaign": "website", "utm_content": "", "utm_medium": "email", "utm_source": "sendgrid.com", "utm_term": "" }; request.method = 'PATCH' request.path = '/v3/tracking_settings/google_analytics' request.headers['X-Mock'] = 200 it('test_tracking_settings_google_analytics_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_tracking_settings_google_analytics_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/tracking_settings/google_analytics' request.headers['X-Mock'] = 200 it('test_tracking_settings_google_analytics_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_tracking_settings_open_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": true }; request.method = 'PATCH' request.path = '/v3/tracking_settings/open' request.headers['X-Mock'] = 200 it('test_tracking_settings_open_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_tracking_settings_open_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/tracking_settings/open' request.headers['X-Mock'] = 200 it('test_tracking_settings_open_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_tracking_settings_subscription_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "enabled": true, "html_content": "html content", "landing": "landing page html", "plain_content": "text content", "replace": "replacement tag", "url": "url" }; request.method = 'PATCH' request.path = '/v3/tracking_settings/subscription' request.headers['X-Mock'] = 200 it('test_tracking_settings_subscription_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_tracking_settings_subscription_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/tracking_settings/subscription' request.headers['X-Mock'] = 200 it('test_tracking_settings_subscription_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_account_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/account' request.headers['X-Mock'] = 200 it('test_user_account_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_credits_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/credits' request.headers['X-Mock'] = 200 it('test_user_credits_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_email_put', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "email": "example@example.com" }; request.method = 'PUT' request.path = '/v3/user/email' request.headers['X-Mock'] = 200 it('test_user_email_put had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_email_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/email' request.headers['X-Mock'] = 200 it('test_user_email_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_password_put', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "new_password": "new_password", "old_password": "old_password" }; request.method = 'PUT' request.path = '/v3/user/password' request.headers['X-Mock'] = 200 it('test_user_password_put had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_profile_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "city": "Orange", "first_name": "Example", "last_name": "User" }; request.method = 'PATCH' request.path = '/v3/user/profile' request.headers['X-Mock'] = 200 it('test_user_profile_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_profile_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/profile' request.headers['X-Mock'] = 200 it('test_user_profile_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_scheduled_sends_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "batch_id": "YOUR_BATCH_ID", "status": "pause" }; request.method = 'POST' request.path = '/v3/user/scheduled_sends' request.headers['X-Mock'] = 201 it('test_user_scheduled_sends_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_user_scheduled_sends_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/scheduled_sends' request.headers['X-Mock'] = 200 it('test_user_scheduled_sends_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_scheduled_sends__batch_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "status": "pause" }; request.method = 'PATCH' request.path = '/v3/user/scheduled_sends/{batch_id}' request.headers['X-Mock'] = 204 it('test_user_scheduled_sends__batch_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_user_scheduled_sends__batch_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/scheduled_sends/{batch_id}' request.headers['X-Mock'] = 200 it('test_user_scheduled_sends__batch_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_scheduled_sends__batch_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/user/scheduled_sends/{batch_id}' request.headers['X-Mock'] = 204 it('test_user_scheduled_sends__batch_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_user_settings_enforced_tls_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "require_tls": true, "require_valid_cert": false }; request.method = 'PATCH' request.path = '/v3/user/settings/enforced_tls' request.headers['X-Mock'] = 200 it('test_user_settings_enforced_tls_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_settings_enforced_tls_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/settings/enforced_tls' request.headers['X-Mock'] = 200 it('test_user_settings_enforced_tls_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_username_put', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "username": "test_username" }; request.method = 'PUT' request.path = '/v3/user/username' request.headers['X-Mock'] = 200 it('test_user_username_put had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_username_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/username' request.headers['X-Mock'] = 200 it('test_user_username_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_webhooks_event_settings_patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "bounce": true, "click": true, "deferred": true, "delivered": true, "dropped": true, "enabled": true, "group_resubscribe": true, "group_unsubscribe": true, "open": true, "processed": true, "spam_report": true, "unsubscribe": true, "url": "url" }; request.method = 'PATCH' request.path = '/v3/user/webhooks/event/settings' request.headers['X-Mock'] = 200 it('test_user_webhooks_event_settings_patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_webhooks_event_settings_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/webhooks/event/settings' request.headers['X-Mock'] = 200 it('test_user_webhooks_event_settings_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_webhooks_event_test_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "url": "url" }; request.method = 'POST' request.path = '/v3/user/webhooks/event/test' request.headers['X-Mock'] = 204 it('test_user_webhooks_event_test_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_user_webhooks_parse_settings_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "hostname": "myhostname.com", "send_raw": false, "spam_check": true, "url": "http://email.myhosthame.com" }; request.method = 'POST' request.path = '/v3/user/webhooks/parse/settings' request.headers['X-Mock'] = 201 it('test_user_webhooks_parse_settings_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_user_webhooks_parse_settings_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/webhooks/parse/settings' request.headers['X-Mock'] = 200 it('test_user_webhooks_parse_settings_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_webhooks_parse_settings__hostname__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "send_raw": true, "spam_check": false, "url": "http://newdomain.com/parse" }; request.method = 'PATCH' request.path = '/v3/user/webhooks/parse/settings/{hostname}' request.headers['X-Mock'] = 200 it('test_user_webhooks_parse_settings__hostname__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_webhooks_parse_settings__hostname__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/user/webhooks/parse/settings/{hostname}' request.headers['X-Mock'] = 200 it('test_user_webhooks_parse_settings__hostname__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_user_webhooks_parse_settings__hostname__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/user/webhooks/parse/settings/{hostname}' request.headers['X-Mock'] = 204 it('test_user_webhooks_parse_settings__hostname__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_user_webhooks_parse_stats_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["aggregated_by"] = 'day' request.queryParams["limit"] = 'test_string' request.queryParams["start_date"] = '2016-01-01' request.queryParams["end_date"] = '2016-04-01' request.queryParams["offset"] = 'test_string' request.method = 'GET' request.path = '/v3/user/webhooks/parse/stats' request.headers['X-Mock'] = 200 it('test_user_webhooks_parse_stats_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "automatic_security": false, "custom_spf": true, "default": true, "domain": "example.com", "ips": [ "192.168.1.1", "192.168.1.2" ], "subdomain": "news", "username": "john@example.com" }; request.method = 'POST' request.path = '/v3/whitelabel/domains' request.headers['X-Mock'] = 201 it('test_whitelabel_domains_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["username"] = 'test_string' request.queryParams["domain"] = 'test_string' request.queryParams["exclude_subusers"] = 'true' request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/whitelabel/domains' request.headers['X-Mock'] = 200 it('test_whitelabel_domains_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains_default_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/whitelabel/domains/default' request.headers['X-Mock'] = 200 it('test_whitelabel_domains_default_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains_subuser_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/whitelabel/domains/subuser' request.headers['X-Mock'] = 200 it('test_whitelabel_domains_subuser_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains_subuser_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/whitelabel/domains/subuser' request.headers['X-Mock'] = 204 it('test_whitelabel_domains_subuser_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains__domain_id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "custom_spf": true, "default": false }; request.method = 'PATCH' request.path = '/v3/whitelabel/domains/{domain_id}' request.headers['X-Mock'] = 200 it('test_whitelabel_domains__domain_id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains__domain_id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/whitelabel/domains/{domain_id}' request.headers['X-Mock'] = 200 it('test_whitelabel_domains__domain_id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains__domain_id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/whitelabel/domains/{domain_id}' request.headers['X-Mock'] = 204 it('test_whitelabel_domains__domain_id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains__domain_id__subuser_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "username": "jane@example.com" }; request.method = 'POST' request.path = '/v3/whitelabel/domains/{domain_id}/subuser' request.headers['X-Mock'] = 201 it('test_whitelabel_domains__domain_id__subuser_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains__id__ips_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "ip": "192.168.0.1" }; request.method = 'POST' request.path = '/v3/whitelabel/domains/{id}/ips' request.headers['X-Mock'] = 200 it('test_whitelabel_domains__id__ips_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains__id__ips__ip__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/whitelabel/domains/{id}/ips/{ip}' request.headers['X-Mock'] = 200 it('test_whitelabel_domains__id__ips__ip__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_domains__id__validate_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'POST' request.path = '/v3/whitelabel/domains/{id}/validate' request.headers['X-Mock'] = 200 it('test_whitelabel_domains__id__validate_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_ips_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "domain": "example.com", "ip": "192.168.1.1", "subdomain": "email" }; request.method = 'POST' request.path = '/v3/whitelabel/ips' request.headers['X-Mock'] = 201 it('test_whitelabel_ips_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_ips_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["ip"] = 'test_string' request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.method = 'GET' request.path = '/v3/whitelabel/ips' request.headers['X-Mock'] = 200 it('test_whitelabel_ips_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_ips__id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/whitelabel/ips/{id}' request.headers['X-Mock'] = 200 it('test_whitelabel_ips__id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_ips__id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/whitelabel/ips/{id}' request.headers['X-Mock'] = 204 it('test_whitelabel_ips__id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_ips__id__validate_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'POST' request.path = '/v3/whitelabel/ips/{id}/validate' request.headers['X-Mock'] = 200 it('test_whitelabel_ips__id__validate_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "default": true, "domain": "example.com", "subdomain": "mail" }; request.queryParams["limit"] = '1' request.queryParams["offset"] = '1' request.method = 'POST' request.path = '/v3/whitelabel/links' request.headers['X-Mock'] = 201 it('test_whitelabel_links_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 201, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["limit"] = '1' request.method = 'GET' request.path = '/v3/whitelabel/links' request.headers['X-Mock'] = 200 it('test_whitelabel_links_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links_default_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["domain"] = 'test_string' request.method = 'GET' request.path = '/v3/whitelabel/links/default' request.headers['X-Mock'] = 200 it('test_whitelabel_links_default_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links_subuser_get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.queryParams["username"] = 'test_string' request.method = 'GET' request.path = '/v3/whitelabel/links/subuser' request.headers['X-Mock'] = 200 it('test_whitelabel_links_subuser_get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links_subuser_delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.queryParams["username"] = 'test_string' request.method = 'DELETE' request.path = '/v3/whitelabel/links/subuser' request.headers['X-Mock'] = 204 it('test_whitelabel_links_subuser_delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links__id__patch', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "default": true }; request.method = 'PATCH' request.path = '/v3/whitelabel/links/{id}' request.headers['X-Mock'] = 200 it('test_whitelabel_links__id__patch had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links__id__get', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.method = 'GET' request.path = '/v3/whitelabel/links/{id}' request.headers['X-Mock'] = 200 it('test_whitelabel_links__id__get had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links__id__delete', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'DELETE' request.path = '/v3/whitelabel/links/{id}' request.headers['X-Mock'] = 204 it('test_whitelabel_links__id__delete had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 204, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links__id__validate_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = null; request.method = 'POST' request.path = '/v3/whitelabel/links/{id}/validate' request.headers['X-Mock'] = 200 it('test_whitelabel_links__id__validate_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); }) describe('test_whitelabel_links__link_id__subuser_post', function () { this.timeout(30000); var API_KEY = 'SendGrid API Key' if(process.env.TRAVIS) { var TEST_HOST = process.env.MOCK_HOST } else { var TEST_HOST = 'localhost' } var sg = sendgrid(API_KEY, TEST_HOST) var request = sg.emptyRequest() if(TEST_HOST == 'localhost') { request.test = true request.port = 4010 } request.body = { "username": "jane@example.com" }; request.method = 'POST' request.path = '/v3/whitelabel/links/{link_id}/subuser' request.headers['X-Mock'] = 200 it('test_whitelabel_links__link_id__subuser_post had the correct response code', function(done) { sg.API(request, function (error, response) { assert.equal(response.statusCode, 200, 'response code is not correct') done(); }) }); })
instapapas/instapapas
node_modules/sendgrid/test/test.js
JavaScript
mit
187,714
// All code points in the Khmer Symbols block as per Unicode v5.0.0: [ 0x19E0, 0x19E1, 0x19E2, 0x19E3, 0x19E4, 0x19E5, 0x19E6, 0x19E7, 0x19E8, 0x19E9, 0x19EA, 0x19EB, 0x19EC, 0x19ED, 0x19EE, 0x19EF, 0x19F0, 0x19F1, 0x19F2, 0x19F3, 0x19F4, 0x19F5, 0x19F6, 0x19F7, 0x19F8, 0x19F9, 0x19FA, 0x19FB, 0x19FC, 0x19FD, 0x19FE, 0x19FF ];
mathiasbynens/unicode-data
5.0.0/blocks/Khmer-Symbols-code-points.js
JavaScript
mit
360
jQuery(document).ready(function() { $('.alert-close').bind('click', function() { $(this).parent().fadeOut(100); }); function createAutoClosingAlert(selector, delay) { var alert = $(selector).alert(); window.setTimeout(function() { alert.alert('close') }, delay); } createAutoClosingAlert(".alert", 20000); });
scr-be/mantle-bundle
src/Resources/public/js/scribe/alert.js
JavaScript
mit
337
CucumberJsBrowserRunner.StepDefinitions.test3(function () { var And = Given = When = Then = this.defineStep, runner; Given(/^test3$/, function(callback) { callback(); }); When(/^test3$/, function(callback) { callback(); }); Then(/^test3$/, function(callback) { callback(); }); });
akania/cucumberjs-browserRunner
tests/features/step_definitions/test3_steps.js
JavaScript
mit
356
'use strict'; var run = require('./helpers').runMochaJSON; var assert = require('assert'); describe('.only()', function() { describe('bdd', function() { it('should run only tests that marked as `only`', function(done) { run('options/only/bdd.fixture.js', ['--ui', 'bdd'], function(err, res) { if (err) { done(err); return; } assert.equal(res.stats.pending, 0); assert.equal(res.stats.passes, 11); assert.equal(res.stats.failures, 0); assert.equal(res.code, 0); done(); }); }); }); describe('tdd', function() { it('should run only tests that marked as `only`', function(done) { run('options/only/tdd.fixture.js', ['--ui', 'tdd'], function(err, res) { if (err) { done(err); return; } assert.equal(res.stats.pending, 0); assert.equal(res.stats.passes, 8); assert.equal(res.stats.failures, 0); assert.equal(res.code, 0); done(); }); }); }); describe('qunit', function() { it('should run only tests that marked as `only`', function(done) { run('options/only/qunit.fixture.js', ['--ui', 'qunit'], function( err, res ) { if (err) { done(err); return; } assert.equal(res.stats.pending, 0); assert.equal(res.stats.passes, 5); assert.equal(res.stats.failures, 0); assert.equal(res.code, 0); done(); }); }); }); });
boneskull/mocha
test/integration/only.spec.js
JavaScript
mit
1,531
module.exports = require('eden-class').extend(function() { /* Require -------------------------------*/ /* Constants -------------------------------*/ /* Public.Properties -------------------------------*/ /* Protected Properties -------------------------------*/ this._table = null; this._where = []; /* Private Properties -------------------------------*/ /* Magic -------------------------------*/ this.___construct = function(table) { this.argument().test(1, 'string', 'undef'); if(typeof table === 'string') { this.setTable(table); } }; /* Public.Methods -------------------------------*/ /** * Set the table name in which you want to delete from * * @param string name * @return this */ this.setTable = function(table) { //argument test this.argument().test(1, 'string'); this._table = table; return this; }; /** * Returns the string version of the query * * @param bool * @return string * @notes returns the query based on the registry */ this.getQuery = function() { return 'DELETE FROM {TABLE} WHERE {WHERE};' .replace('{TABLE}' , this._table) .replace('{WHERE}' , this._where.join(' AND ')); }; /** * Where clause * * @param array|string where * @return this * @notes loads a where phrase into registry */ this.where = function(where) { //Argument 1 must be a string or array this.argument().test(1, 'string', 'array'); if(typeof where === 'string') { where = [where]; } this._where = this._where.concat(where); return this; }; /* Protected Methods -------------------------------*/ /* Private Methods -------------------------------*/ }).register('eden/mysql/delete');
edenjs/mysql
mysql/delete.js
JavaScript
mit
1,715
const path = require('path'); const { expect } = require('chai'); const delay = require('../../../../lib/utils/delay'); describe('Compiler service', () => { it('Should execute a basic test', async () => { await runTests('testcafe-fixtures/basic-test.js', 'Basic test'); }); it('Should handle an error', async () => { try { await runTests('testcafe-fixtures/error-test.js', 'Throw an error', { shouldFail: true }); } catch (err) { expect(err[0].startsWith([ `The specified selector does not match any element in the DOM tree. ` + ` > | Selector('#not-exists') ` + ` [[user-agent]] ` + ` 1 |fixture \`Compiler service\`;` + ` 2 |` + ` 3 |test(\`Throw an error\`, async t => {` + ` > 4 | await t.click('#not-exists');` + ` 5 |});` + ` 6 | at <anonymous> (${path.join(__dirname, 'testcafe-fixtures/error-test.js')}:4:13)` ])).to.be.true; } }); it('Should allow using ClientFunction in assertions', async () => { await runTests('testcafe-fixtures/client-function-in-assertions.js', 'ClientFunction in assertions'); }); it('Should execute Selectors in sync mode', async () => { await runTests('testcafe-fixtures/synchronous-selectors.js'); }); it('debug', async () => { let resolver = null; const result = new Promise(resolve => { resolver = resolve; }); runTests('testcafe-fixtures/debug.js') .then(() => resolver()); setTimeout(async () => { const client = global.testCafe.runner.compilerService.cdp; await client.Debugger.resume(); await delay(1000); await client.Debugger.resume(); }, 10000); return result; }); });
AndreyBelym/testcafe
test/functional/fixtures/compiler-service/test.js
JavaScript
mit
1,948
var fans=require('../../modules/blog/fans'); var User=require('../../modules/resume/user'); var async = require('asyncawait/async'); var await = require('asyncawait/await'); module.exports=(async(function(method,req,res){ var result; if(method==='get'){ } else if(method==='post'){ var userId=req.session.uid; var targetId=req.body.targetId; if(userId){ if(userId==targetId){ result={ status:-1, msg:"你咋可以自己关注自己呢?自恋!" } }else{ //已登录才能关注,查询是否已关注过 var isFansDate=await(fans.findOne({ where:{ userId:userId, targetId:targetId } })) if(isFansDate){ result={ status:-1, msg:"已关注" } } else{ var fansDate=await(fans.create({ userId:userId, targetId:targetId })) if(fansDate){ result={ status:0, msg:"关注成功" } }else{ result={ status:-1, msg:"关注失败" } } } } }else{ result={ status:-1, msg:"未登录" } } } else if(method==='delete'){ var targetId=req.query.targetId; var userId=req.session.uid; if(userId){ //已登录才能取消关注,查询是否已关注过 var isFansDate=await(fans.findOne({ where:{ userId:userId, targetId:targetId } })) if(isFansDate){ var fansDate=await(fans.destroy({ where:{ userId:userId, targetId:targetId } })) if(fansDate){ result={ status:0, msg:"取消关注成功" } }else{ result={ status:-1, msg:"取消关注失败" } } } else{ result={ status:-1, msg:"未关注" } } }else{ result={ status:-1, msg:"未登录" } } } res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"}); res.end(JSON.stringify(result)) }))
weijiafen/antBlog
src/main/server/controler/blog/fans.js
JavaScript
mit
1,918
// @flow import React, { Component } from 'react' import { Helmet } from 'react-helmet' import AlternativeMedia from './AlternativeMedia' import ImageViewer from './ImageViewer' import { Code, CodeBlock, Title } from '../components' const propFn = k => { const style = { display: 'inline-block', marginBottom: 4, marginRight: 4 } return ( <span key={k} style={style}> <Code>{k}</Code> </span> ) } const commonProps = [ 'carouselProps', 'currentIndex', 'currentView', 'frameProps', 'getStyles', 'isFullscreen', 'isModal', 'modalProps', 'interactionIsIdle', 'trackProps', 'views', ] export default class CustomComponents extends Component<*> { render() { return ( <div> <Helmet> <title>Components - React Images</title> <meta name="description" content="React Images allows you to augment layout and functionality by replacing the default components with your own." /> </Helmet> <Title>Components</Title> <p> The main feature of this library is providing consumers with the building blocks necessary to create <em>their</em> component. </p> <h3>Replacing Components</h3> <p> React-Images allows you to augment layout and functionality by replacing the default components with your own, using the <Code>components</Code>{' '} property. These components are given all the current props and state letting you achieve anything you dream up. </p> <h3>Inner Props</h3> <p> All functional properties that the component needs are provided in <Code>innerProps</Code> which you must spread. </p> <h3>Common Props</h3> <p> Every component receives <Code>commonProps</Code> which are spread onto the component. These include: </p> <p>{commonProps.map(propFn)}</p> <CodeBlock> {`import React from 'react'; import Carousel from 'react-images'; const CustomHeader = ({ innerProps, isModal }) => isModal ? ( <div {...innerProps}> // your component internals </div> ) : null; class Component extends React.Component { render() { return <Carousel components={{ Header: CustomHeader }} />; } }`} </CodeBlock> <h2>Component API</h2> <h3>{'<Container />'}</h3> <p>Wrapper for the carousel. Attachment point for mouse and touch event listeners.</p> <h3>{'<Footer />'}</h3> <p> Element displayed beneath the views. Renders <Code>FooterCaption</Code> and <Code>FooterCount</Code> by default. </p> <h3>{'<FooterCaption />'}</h3> <p> Text associated with the current view. Renders <Code>{'{viewData.caption}'}</Code> by default. </p> <h3>{'<FooterCount />'}</h3> <p> How far through the carousel the user is. Renders{' '} <Code> {'{currentIndex}'}&nbsp;of&nbsp;{'{totalViews}'} </Code>{' '} by default </p> <h3>{'<Header />'}</h3> <p> Element displayed above the views. Renders <Code>FullscreenButton</Code> and <Code>CloseButton</Code> by default. </p> <h3>{'<HeaderClose />'}</h3> <p> The button to close the modal. Accepts the <Code>onClose</Code> function. </p> <h3>{'<HeaderFullscreen />'}</h3> <p> The button to fullscreen the modal. Accepts the <Code>toggleFullscreen</Code> function. </p> <h3>{'<Navigation />'}</h3> <p> Wrapper for the <Code>{'<NavigationNext />'}</Code> and <Code>{'<NavigationPrev />'}</Code> buttons. </p> <h3>{'<NavigationPrev />'}</h3> <p> Button allowing the user to navigate to the previous view. Accepts an <Code>onClick</Code> function. </p> <h3>{'<NavigationNext />'}</h3> <p> Button allowing the user to navigate to the next view. Accepts an <Code>onClick</Code> function. </p> <h3>{'<View />'}</h3> <p> The view component renders your media to the user. Receives the current view object as the <Code>data</Code> property. </p> <h2>Examples</h2> <ImageViewer {...this.props} /> <AlternativeMedia /> </div> ) } }
jossmac/react-images
docs/pages/CustomComponents/index.js
JavaScript
mit
4,414
var gulp = require('gulp'); var browserify = require('browserify'); //transform jsx to js var reactify = require('reactify'); //convert to stream var source = require('vinyl-source-stream'); var nodemon = require('gulp-nodemon'); gulp.task('browserify', function() { //source browserify('./src/js/main.js') //convert jsx to js .transform('reactify') //creates a bundle .bundle() .pipe(source('main.js')) .pipe(gulp.dest('dist/js')) }); gulp.task('copy', function() { gulp.src('src/index.html') .pipe(gulp.dest('dist')); gulp.src('src/assets/**/*.*') .pipe(gulp.dest('dist/assets')); }); gulp.task('nodemon', function(cb) { var called = false; return nodemon({ script: 'server.js' }).on('start', function() { if (!called) { called = true; cb(); } }); }); gulp.task('default', ['browserify', 'copy', 'nodemon'], function() { return gulp.watch('src/**/*.*', ['browserify', 'copy']); });
felixcriv/react_scheduler_component
gulpfile.js
JavaScript
mit
1,039
module.exports = function(config) { config.set({ basePath: '../../', frameworks: ['jasmine', 'requirejs'], files: [ {pattern: 'test/unit/require.conf.js', included: true}, {pattern: 'test/unit/tests/global.js', included: true}, {pattern: 'src/client/**/*.*', included: false}, {pattern: 'test/unit/tests/**/*.*', included: false}, ], plugins: [ 'karma-jasmine', 'karma-requirejs', 'karma-coverage', 'karma-html-reporter', 'karma-phantomjs-launcher', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-safari-launcher', 'karma-ie-launcher' ], reporters: ['coverage', 'html', 'progress'], preprocessors: { 'src/client/component/**/*.js': ['coverage'], 'src/client/service/**/*.js': ['coverage'] }, coverageReporter: { type: 'html', dir: 'test/unit/coverage/', includeAllSources: true }, htmlReporter: { outputDir: 'results' //it is annoying that this file path isn't from basePath :( }, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['Chrome'/*, 'PhantomJS', 'Firefox', 'IE', 'Safari'*/], captureTimeout: 5000, singleRun: true }); };
robsix/3ditor
test/unit/karma.conf.js
JavaScript
mit
1,463
/** * @namespace http * * The C<http> namespace groups functions and classes used while making * HTTP Requests. * */ ECMAScript.Extend('http', function (ecma) { // Intentionally private var _documentLocation = null function _getDocumentLocation () { if (!_documentLocation) _documentLocation = new ecma.http.Location(); return _documentLocation; } /** * @constant HTTP_STATUS_NAMES * HTTP/1.1 Status Code Definitions * * Taken from, RFC 2616 Section 10: * L<http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html> * * These names are used in conjuction with L<ecma.http.Request> for * indicating callback functions. The name is prepended with C<on> such * that * onMethodNotAllowed * corresponds to the callback triggered when a 405 status is received. * # Names * * 100 Continue * 101 SwitchingProtocols * 200 Ok * 201 Created * 202 Accepted * 203 NonAuthoritativeInformation * 204 NoContent * 205 ResetContent * 206 PartialContent * 300 MultipleChoices * 301 MovedPermanently * 302 Found * 303 SeeOther * 304 NotModified * 305 UseProxy * 306 Unused * 307 TemporaryRedirect * 400 BadRequest * 401 Unauthorized * 402 PaymentRequired * 403 Forbidden * 404 NotFound * 405 MethodNotAllowed * 406 NotAcceptable * 407 ProxyAuthenticationRequired * 408 RequestTimeout * 409 Conflict * 410 Gone * 411 LengthRequired * 412 PreconditionFailed * 413 RequestEntityTooLarge * 414 RequestURITooLong * 415 UnsupportedMediaType * 416 RequestedRangeNotSatisfiable * 417 ExpectationFailed * 500 InternalServerError * 501 NotImplemented * 502 BadGateway * 503 ServiceUnavailable * 504 GatewayTimeout * 505 HTTPVersionNotSupported */ this.HTTP_STATUS_NAMES = { 100: 'Continue', 101: 'SwitchingProtocols', 200: 'Ok', 201: 'Created', 202: 'Accepted', 203: 'NonAuthoritativeInformation', 204: 'NoContent', 205: 'ResetContent', 206: 'PartialContent', 300: 'MultipleChoices', 301: 'MovedPermanently', 302: 'Found', 303: 'SeeOther', 304: 'NotModified', 305: 'UseProxy', 306: 'Unused', 307: 'TemporaryRedirect', 400: 'BadRequest', 401: 'Unauthorized', 402: 'PaymentRequired', 403: 'Forbidden', 404: 'NotFound', 405: 'MethodNotAllowed', 406: 'NotAcceptable', 407: 'ProxyAuthenticationRequired', 408: 'RequestTimeout', 409: 'Conflict', 410: 'Gone', 411: 'LengthRequired', 412: 'PreconditionFailed', 413: 'RequestEntityTooLarge', 414: 'RequestURITooLong', 415: 'UnsupportedMediaType', 416: 'RequestedRangeNotSatisfiable', 417: 'ExpectationFailed', 500: 'InternalServerError', 501: 'NotImplemented', 502: 'BadGateway', 503: 'ServiceUnavailable', 504: 'GatewayTimeout', 505: 'HTTPVersionNotSupported' }; /** * @function isSameOrigin * * Compare originating servers. * * var bool = ecma.http.isSameOrigin(uri); * var bool = ecma.http.isSameOrigin(uri, uri); * * Is the resource located on the server at the port using the same protocol * which served the document. * * var bool = ecma.http.isSameOrigin('http://www.example.com'); * * Are the two URI's served from the same origin * * var bool = ecma.http.isSameOrigin('http://www.example.com', 'https://www.example.com'); * */ this.isSameOrigin = function(uri1, uri2) { if (!(uri1)) return false; var loc1 = uri1 instanceof ecma.http.Location ? uri1 : new ecma.http.Location(uri1); var loc2 = uri2 || _getDocumentLocation(); return loc1.isSameOrigin(loc2); }; });
ryangies/lsn-javascript
src/lib/ecma/http/http.js
JavaScript
mit
3,860
import debounce from 'debounce'; import $ from 'jquery'; const groupElementsByTop = (groups, element) => { const top = $(element).offset().top; groups[top] = groups[top] || []; groups[top].push(element); return groups; }; const groupElementsByZero = (groups, element) => { groups[0] = groups[0] || []; groups[0].push(element); return groups; }; const clearHeight = elements => $(elements).css('height', 'auto'); const getHeight = element => $(element).height(); const applyMaxHeight = (elements) => { const heights = elements.map(getHeight); const maxHeight = Math.max.apply(null, heights); $(elements).height(maxHeight); }; const equalizeHeights = (elements, groupByTop) => { // Sort into groups. const groups = groupByTop ? elements.reduce(groupElementsByTop, {}) : elements.reduce(groupElementsByZero, {}); // Convert to arrays. const groupsAsArray = Object.keys(groups).map((key) => { return groups[key]; }); // Apply max height. groupsAsArray.forEach(clearHeight); groupsAsArray.forEach(applyMaxHeight); }; $.fn.equalHeight = function ({ groupByTop = false, resizeTimeout = 20, updateOnDOMReady = true, updateOnDOMLoad = false } = {}) { // Convert to native array. const elements = this.toArray(); // Handle resize event. $(window).on('resize', debounce(() => { equalizeHeights(elements, groupByTop); }, resizeTimeout)); // Handle load event. $(window).on('load', () => { if (updateOnDOMLoad) { equalizeHeights(elements, groupByTop); } }); // Handle ready event. $(document).on('ready', () => { if (updateOnDOMReady) { equalizeHeights(elements, groupByTop); } }); return this; };
dubbs/equal-height
src/jquery.equalHeight.js
JavaScript
mit
1,714
// Structure to represent a proof class ProofTree { constructor({equation, rule, newScope=false }) { this.equation = equation; this.rule = rule; this.newScope = newScope; this.parent = null; this.children = []; this.isSound = !newScope; } isAssumption() { return this.newScope; } isEmpty() { return this.parent === null && this.children === []; } size() { if (this.isEmpty()) return 0; if (this.children.length) return 1 + this.children.map(c=>c.size()).reduce((acc, c)=>acc+c); return 1; } lastNumber() { return this.size(); } walk(fn) { fn(this); this.children.forEach(child => { child.walk(fn); }); } last() { if (this.children.length === 0) return this; var last = this; this.children.forEach(child => { if (!child.isAssumption()) { last = child.last(); } }); return last; } setLines() { var count = 1; this.walk((child) => { child.lineNumber = count; count ++; }); } root() { if (this.parent === null) return this; return this.parent.root(); } inScope(target) { if (this.lineNumber === target) { return true; } else { if (this.parent === null) return false; var child = null; var anySiblings = this.parent.children.some(child => { return !child.isAssumption() && (child.lineNumber === target) }) if (anySiblings) { return true; } return this.parent.inScope(target); } } // inScope(line1, line2, context=this.root()) { // // if (line1 === line2) return true; // if (line1 > line2) return false; // var line1Obj = context.line(line1); // var line2Obj = context.line(line2); // return this.inScope(line1Obj.lineNumber, line2Obj.parent.lineNumber, context); // } line(lineNumber) { var line = null; var count = 1; this.walk(child => { if (lineNumber === count) line = child; count ++; }); return line; } addLine(line) { line.parent = this.last(); line.parent.children.push(line); this.root().setLines(); } closeBox() { this.isSound = true; } addLineTo(line, lineNumber) { // line.parent = this.line() } addLineNewScope({equation, rule}) { var line = new ProofTree({ equation, rule, newScope: true }); line.parent = this.last(); this.children.push(line); line.root().setLines(); } } // Synonym as it reads better sometimes ProofTree.prototype.scope = ProofTree.prototype.line; export default ProofTree;
jackdeadman/Natural-Deduction-React
src/js/classes/Proof/ProofTree.js
JavaScript
mit
2,618
version https://git-lfs.github.com/spec/v1 oid sha256:20e35c5c96301564881e3f892b8c5e38c98b131ea58889ed9889b15874e39cbe size 8394
yogeshsaroya/new-cdnjs
ajax/libs/preconditions/5.2.4/preconditions.min.js
JavaScript
mit
129
/** * Javascript file for Category Show. * It requires jQuery. */ function wpcs_gen_tag() { // Category Show searches for term_id since 0.4.1 and not term slug. // There is a need to add the id%% tag to be compatible with other versions $("#wpcs_gen_tag").val("%%wpcs-"+$("#wpcs_term_dropdown").val()+"%%"+$("#wpcs_order_type").val()+$("#wpcs_order_by").val()+"%%id%%"); $("#wpcs_gen_tag").select(); $("#wpcs_gen_tag").focus(); }
mfolker/saddind
wp-content/plugins/wp-catergory-show/wp-category-show.js
JavaScript
mit
438
function mathGame(){ var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.auto, 'math', { preload: onPreload, create: onCreate, // resize:onResize }); WebFontConfig = { active: function() { game.time.events.add(Phaser.Timer.SECOND, createText, this); }, google: { families: ['Fredericka the Great'] } }; var sumsArray = []; var questionText; var randomSum; var timeTween; var numberTimer; var buttonMask; var replay; var score=0; var scoreText; var isGameOver = false; var topScore; var numbersArray = [-3,-2,-1,1,2,3]; function buildThrees(initialNummber,currentIndex,limit,currentString){ for(var i=0;i<numbersArray.length;i++){ var sum = initialNummber+numbersArray[i]; var outputString = currentString+(numbersArray[i]<0?"":"+")+numbersArray[i]; if(sum>0 && sum<4 && currentIndex==limit){ sumsArray[limit][sum-1].push(outputString); } if(currentIndex<limit){ buildThrees(sum,currentIndex+1,limit,outputString); } } } function onPreload() { // responsiveScale(); game.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js'); game.load.image("timebar", "/images/math/timebar.png"); game.load.image("buttonmask", "/images/math/buttonmask.png"); game.load.spritesheet("buttons", "/images/math/buttons.png",400,50); game.load.spritesheet('myguy', '/images/math/dance.png', 70, 120); game.load.image("background", "/images/math/board2.png"); game.load.image("replay", "images/math/replay.png"); game.load.image("home", "images/home.png"); } function onCreate() { topScore = localStorage.getItem("topScore")==null?0:localStorage.getItem("topScore"); // game.stage.backgroundColor = "#cccccc"; chalkBoard = game.add.sprite(1100, 850,"background"); chalkBoard.x = 0; chalkBoard.y = 0; chalkBoard.height = game.height; chalkBoard.width = game.width; game.stage.disableVisibilityChange = true; gameOverSprite = this.game.add.sprite(600, 300, 'myguy'); gameOverSprite.visible = false; gameOverSprite.frame = 0; gameOverSprite.animations.add('left', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13], 10, true); replay = game.add.button(game.width*.6, game.height*.1,"replay",replay,this); replay.visable = false; home = game.add.button(game.width*.75, game.height*.1, 'home', function onClick(){window.location.href ="/home"}); home.scale.setTo(0.2,0.2); for(var i=1;i<5;i++){ sumsArray[i]=[[],[],[]]; for(var j=1;j<=3;j++){ buildThrees(j,1,i,j); } } questionText = game.add.text(game.width*.5,game.height*.3,"-"); questionText.anchor.set(0.5); scoreText = game.add.text(game.width*.1,game.height*.10,"-"); for(var i=0;i<3;i++){ var numberButton = game.add.button(game.width*.3,game.height*.4+i*75,"buttons",checkAnswer,this).frame=i; } numberTimer = game.add.sprite(game.width*.3,game.height*.4,"timebar"); nextNumber(); } function createText() { questionText.font = 'Fredericka the Great'; questionText.fontSize = 37; questionText.addColor('#edf0f3',0); scoreText.font = 'Fredericka the Great'; scoreText.fontSize = 37; scoreText.addColor('#edf0f3',0); }; function gameOver(gameOverString){ // game.stage.backgroundColor = "#ff0000"; console.log(gameOverString) questionText.text = "Wrong Answer!"; questionText.addColor('#ff471a',0); isGameOver = true; localStorage.setItem("topScore",Math.max(score,topScore)); numberTimer.destroy(); buttonMask.destroy(); replay.visible = true; // gameOverSprite.visible = true; // gameOverSprite.animations.play('left'); } function checkAnswer(button){ var correctAnswer; if(!isGameOver){ if(button.frame==randomSum){ score+=Math.floor((buttonMask.x+350)/4); nextNumber(); } else{ if(score>0) { timeTween.stop(); } correctAnswer = randomSum; gameOver(correctAnswer); } } } function replay(){ $("#math").html(""); mathGame(); } function nextNumber(){ scoreText.text = "Score: "+score.toString()+"\nBest Score: "+topScore.toString(); if(buttonMask){ buttonMask.destroy(); game.tweens.removeAll(); } buttonMask = game.add.graphics(game.width*.3,game.height*.4); buttonMask.beginFill(0xffffff); buttonMask.drawRect(0, 0, 400, 200); buttonMask.endFill(); numberTimer.mask = buttonMask; if(score>0){ timeTween=game.add.tween(buttonMask); timeTween.to({ x: -350 }, 9000, "Linear",true); timeTween.onComplete.addOnce(function(){ gameOver("?"); }, this); } randomSum = game.rnd.between(0,2); questionText.text = sumsArray[Math.min(Math.round((score-100)/400)+1,4)][randomSum][game.rnd.between(0,sumsArray[Math.min(Math.round((score-100)/400)+1,4)][randomSum].length-1)]; } } // }
JulianBoralli/klink
app/assets/javascripts/math.js
JavaScript
mit
5,149
'use strict';exports.__esModule = true;var _stringify = require('babel-runtime/core-js/json/stringify');var _stringify2 = _interopRequireDefault(_stringify);var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);var _inherits2 = require('babel-runtime/helpers/inherits');var _inherits3 = _interopRequireDefault(_inherits2);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _class = function (_think$controller$bas) {(0, _inherits3.default)(_class, _think$controller$bas);function _class() {(0, _classCallCheck3.default)(this, _class);return (0, _possibleConstructorReturn3.default)(this, _think$controller$bas.apply(this, arguments));} /** * some base method in here */_class.prototype. get = function get(key) { if (key == undefined) { return this.http._get; } return this.http._get[key]; };_class.prototype. post = function post(key) { if (key == undefined) { return this.http._post; } return this.http._post[key]; };_class.prototype. getCookie = function getCookie(key) { if (key == undefined) { return ''; } return this.http._cookie; };_class.prototype. setCookie = function setCookie(key, val) { if (typeof val !== 'string') { val = (0, _stringify2.default)(val); } return this.http._cookie[key] = val; };_class.prototype. apiErrorHandle = function apiErrorHandle(errno) { var API_ERROR_MSG_TABLE = { // user '101': '用户未登录', '102': '用户密码错误', '111': '密码不一致', // category '3000': 'Category name is empty' }; var msg = API_ERROR_MSG_TABLE[errno] || 'system error'; console.log(msg); this.fail(errno, msg); };return _class;}(think.controller.base);exports.default = _class;
JackPu/albums
App/user/controller/base.js
JavaScript
mit
4,099
// Generated by CoffeeScript 1.8.0 (function() { var TaskSchema, mongoose; mongoose = require('./mongoose'); TaskSchema = mongoose.Schema({ id: { type: Number, unique: true }, title: { type: String }, url: { type: String, unique: true }, status: { type: Number, "default": 1 } }); module.exports = mongoose.model('Task', TaskSchema); }).call(this); //# sourceMappingURL=tasks.js.map
youqingkui/fav-dailyzhihu2evernote
models/tasks.js
JavaScript
mit
472
var mongoose = require('mongoose'), _ = require('underscore'), roomTokenizer = function(msg) { var tokens = []; tokens = tokens.concat(msg.content.split(' ')); tokens.push(msg.author); return tokens; }; exports.init = function(db) { var EntitySchemaDefinition, EntitySchema, EntityModel; //create schema EntitySchemaDefinition = { content : { type: String, required: true }, author: { email: String, username: String, avatar: String }, room: { type: mongoose.Schema.ObjectId, required: true }, status: { type: Number, required: true }, date : { type: Date }, keywords: [String] }; EntitySchema = new mongoose.Schema(EntitySchemaDefinition, {autoIndex: false} ); EntitySchema.index({keywords: 1}); //during save update all keywords EntitySchema.pre('save', function(next) { //set dates if ( !this.date ) { this.date = new Date(); } //clearing keywords this.keywords.length = 0; //adding keywords this.keywords = this.keywords.concat(roomTokenizer(this)); next(); }); EntityModel = db.model('Message', EntitySchema); return EntityModel; };
vitoss/Corpo-Chat
service/lib/model/Message.js
JavaScript
mit
1,286
import React, { PropTypes } from 'react' import { Grid, Row, Col } from 'react-bootstrap' import Sort from '../../components/Sort' import ProjectFilterForm from '../../components/ProjectFilterForm' import Search from '../../containers/Search' import ProjectsDashboardStatContainer from '../../containers/ProjectsDashboardStatContainer'; import { PROJECTS_SORT } from '../../resources/options' const ProjectsDashboard = (props) => { return ( <Grid fluid> <Row> <Col xs={12} md={4}> <ProjectsDashboardStatContainer /> </Col> <Col xs={12} md={8}> Latest Updates </Col> </Row> <Row> <Col md={12}> <Search types={['projects']} searchId='projectsDashboardSearch' filterElement={<ProjectFilterForm />} sortElement={<Sort options={PROJECTS_SORT} />} /> </Col> </Row> </Grid> ) } export default ProjectsDashboard
envisioning/tdb-storybook
src/pages/ProjectsDashboard/index.js
JavaScript
mit
978
export default function mapNodesToColumns({ children = [], columns = 1, dimensions = [], } = {}) { let nodes = [] let heights = [] if (columns === 1) { return children } // use dimensions to calculate the best column for each child if (dimensions.length && dimensions.length === children.length) { for(let i=0; i<columns; i++) { nodes[i] = [] heights[i] = 0 } children.forEach((child, i) => { let { width, height } = dimensions[i] let index = heights.indexOf(Math.min(...heights)) nodes[index].push(child) heights[index] += height / width }) } // equally spread the children across the columns else { for(let i=0; i<columns; i++) { nodes[i] = children.filter((child, j) => j % columns === i) } } return nodes }
novascreen/react-columns
src/mapNodesToColumns.js
JavaScript
mit
811
/** * @fileoverview enforce or disallow capitalization of the first letter of a comment * @author Kevin Partington */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const LETTER_PATTERN = require("../util/patterns/letters"); const astUtils = require("../util/ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN, WHITESPACE = /\s/g, MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/, // TODO: Combine w/ max-len pattern? DEFAULTS = { ignorePattern: null, ignoreInlineComments: false, ignoreConsecutiveComments: false }; /* * Base schema body for defining the basic capitalization rule, ignorePattern, * and ignoreInlineComments values. * This can be used in a few different ways in the actual schema. */ const SCHEMA_BODY = { type: "object", properties: { ignorePattern: { type: "string" }, ignoreInlineComments: { type: "boolean" }, ignoreConsecutiveComments: { type: "boolean" } }, additionalProperties: false }; /** * Get normalized options for either block or line comments from the given * user-provided options. * - If the user-provided options is just a string, returns a normalized * set of options using default values for all other options. * - If the user-provided options is an object, then a normalized option * set is returned. Options specified in overrides will take priority * over options specified in the main options object, which will in * turn take priority over the rule's defaults. * * @param {Object|string} rawOptions The user-provided options. * @param {string} which Either "line" or "block". * @returns {Object} The normalized options. */ function getNormalizedOptions(rawOptions, which) { if (!rawOptions) { return Object.assign({}, DEFAULTS); } return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions); } /** * Get normalized options for block and line comments. * * @param {Object|string} rawOptions The user-provided options. * @returns {Object} An object with "Line" and "Block" keys and corresponding * normalized options objects. */ function getAllNormalizedOptions(rawOptions) { return { Line: getNormalizedOptions(rawOptions, "line"), Block: getNormalizedOptions(rawOptions, "block") }; } /** * Creates a regular expression for each ignorePattern defined in the rule * options. * * This is done in order to avoid invoking the RegExp constructor repeatedly. * * @param {Object} normalizedOptions The normalized rule options. * @returns {void} */ function createRegExpForIgnorePatterns(normalizedOptions) { Object.keys(normalizedOptions).forEach(key => { const ignorePatternStr = normalizedOptions[key].ignorePattern; if (ignorePatternStr) { const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`); normalizedOptions[key].ignorePatternRegExp = regExp; } }); } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "enforce or disallow capitalization of the first letter of a comment", category: "Stylistic Issues", recommended: false, url: "https://eslint.org/docs/rules/capitalized-comments" }, fixable: "code", schema: [ { enum: ["always", "never"] }, { oneOf: [ SCHEMA_BODY, { type: "object", properties: { line: SCHEMA_BODY, block: SCHEMA_BODY }, additionalProperties: false } ] } ], messages: { unexpectedLowercaseComment: "Comments should not begin with a lowercase character", unexpectedUppercaseComment: "Comments should not begin with an uppercase character" } }, create(context) { const capitalize = context.options[0] || "always", normalizedOptions = getAllNormalizedOptions(context.options[1]), sourceCode = context.getSourceCode(); createRegExpForIgnorePatterns(normalizedOptions); //---------------------------------------------------------------------- // Helpers //---------------------------------------------------------------------- /** * Checks whether a comment is an inline comment. * * For the purpose of this rule, a comment is inline if: * 1. The comment is preceded by a token on the same line; and * 2. The command is followed by a token on the same line. * * Note that the comment itself need not be single-line! * * Also, it follows from this definition that only block comments can * be considered as possibly inline. This is because line comments * would consume any following tokens on the same line as the comment. * * @param {ASTNode} comment The comment node to check. * @returns {boolean} True if the comment is an inline comment, false * otherwise. */ function isInlineComment(comment) { const previousToken = sourceCode.getTokenBefore(comment, { includeComments: true }), nextToken = sourceCode.getTokenAfter(comment, { includeComments: true }); return Boolean( previousToken && nextToken && comment.loc.start.line === previousToken.loc.end.line && comment.loc.end.line === nextToken.loc.start.line ); } /** * Determine if a comment follows another comment. * * @param {ASTNode} comment The comment to check. * @returns {boolean} True if the comment follows a valid comment. */ function isConsecutiveComment(comment) { const previousTokenOrComment = sourceCode.getTokenBefore(comment, { includeComments: true }); return Boolean( previousTokenOrComment && ["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1 ); } /** * Check a comment to determine if it is valid for this rule. * * @param {ASTNode} comment The comment node to process. * @param {Object} options The options for checking this comment. * @returns {boolean} True if the comment is valid, false otherwise. */ function isCommentValid(comment, options) { // 1. Check for default ignore pattern. if (DEFAULT_IGNORE_PATTERN.test(comment.value)) { return true; } // 2. Check for custom ignore pattern. const commentWithoutAsterisks = comment.value .replace(/\*/g, ""); if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) { return true; } // 3. Check for inline comments. if (options.ignoreInlineComments && isInlineComment(comment)) { return true; } // 4. Is this a consecutive comment (and are we tolerating those)? if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) { return true; } // 5. Does the comment start with a possible URL? if (MAYBE_URL.test(commentWithoutAsterisks)) { return true; } // 6. Is the initial word character a letter? const commentWordCharsOnly = commentWithoutAsterisks .replace(WHITESPACE, ""); if (commentWordCharsOnly.length === 0) { return true; } const firstWordChar = commentWordCharsOnly[0]; if (!LETTER_PATTERN.test(firstWordChar)) { return true; } // 7. Check the case of the initial word character. const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(), isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase(); if (capitalize === "always" && isLowercase) { return false; } if (capitalize === "never" && isUppercase) { return false; } return true; } /** * Process a comment to determine if it needs to be reported. * * @param {ASTNode} comment The comment node to process. * @returns {void} */ function processComment(comment) { const options = normalizedOptions[comment.type], commentValid = isCommentValid(comment, options); if (!commentValid) { const messageId = capitalize === "always" ? "unexpectedLowercaseComment" : "unexpectedUppercaseComment"; context.report({ node: null, // Intentionally using loc instead loc: comment.loc, messageId, fix(fixer) { const match = comment.value.match(LETTER_PATTERN); return fixer.replaceTextRange( // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*) [comment.range[0] + match.index + 2, comment.range[0] + match.index + 3], capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase() ); } }); } } //---------------------------------------------------------------------- // Public //---------------------------------------------------------------------- return { Program() { const comments = sourceCode.getAllComments(); comments.filter(token => token.type !== "Shebang").forEach(processComment); } }; } };
Aladdin-ADD/eslint
lib/rules/capitalized-comments.js
JavaScript
mit
10,861
module.exports = { FIREBASE_URL: 'https://amber-heat-<your-app>.firebaseio.com/', TWITTER_KEY: '', TWITTER_SECRET: '', TWITTER_CALLBACK: process.env.TWITTER_CALLBACK || 'Twitter Callback Url' };
mikhailbartashevich/ngCarcass
server/config.js
JavaScript
mit
199
'use strict' const _ = require('lodash') module.exports = { getQueryString(url) { const qs = {} _.forEach(url.split('?').pop().split('&'), s => { if (!s) return const kv = s.split('=') if (kv[0]) { qs[kv[0]] = decodeURIComponent(kv[1]) } }) return qs }, toQueryString(o) { return _.keys(o).map(k => k + '=' + encodeURIComponent(o[k])).join('&') }, isMobile(v) { return /^1[358]\d{9}$/.test(v) }, getRandomStr() { return (1e32 * Math.random()).toString(36).slice(0, 16) } }
tmspnn/uic
src/util/helpers.js
JavaScript
mit
554
'use strict'; var eachAsync = require('each-async'); var onetime = require('onetime'); var arrify = require('arrify'); module.exports = function (hostnames, cb) { cb = onetime(cb); eachAsync(arrify(hostnames), function (hostname, i, next) { var img = new Image(); img.onload = function () { cb(true); // skip to end next(new Error()); }; img.onerror = function () { next(); }; img.src = '//' + hostname + '/favicon.ico?' + Date.now(); }, function () { cb(false); }); };
arthurvr/is-reachable
browser.js
JavaScript
mit
506
//IP Flow Information Export (IPFIX) Entities // Last Updated 2013-01-15 // http://www.iana.org/assignments/ipfix/ipfix.xml var entities = []; //ipfix-information-elements entities['elements'] = { "1":{"name":"octetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"octets"}, "2":{"name":"packetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"packets"}, "3":{"name":"deltaFlowCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter"}, "4":{"name":"protocolIdentifier","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "5":{"name":"ipClassOfService","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "6":{"name":"tcpControlBits","dataType":"unsigned8","dataTypeSemantics":"flags","group":"minMax"}, "7":{"name":"sourceTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "8":{"name":"sourceIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"ipHeader"}, "9":{"name":"sourceIPv4PrefixLength","dataType":"unsigned8","group":"ipHeader","units":"bits"}, "10":{"name":"ingressInterface","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "11":{"name":"destinationTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "12":{"name":"destinationIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"ipHeader"}, "13":{"name":"destinationIPv4PrefixLength","dataType":"unsigned8","group":"ipHeader","units":"bits"}, "14":{"name":"egressInterface","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "15":{"name":"ipNextHopIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"derived"}, "16":{"name":"bgpSourceAsNumber","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"derived"}, "17":{"name":"bgpDestinationAsNumber","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"derived"}, "18":{"name":"bgpNextHopIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"derived"}, "19":{"name":"postMCastPacketDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"packets"}, "20":{"name":"postMCastOctetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"octets"}, "21":{"name":"flowEndSysUpTime","dataType":"unsigned32","group":"timestamp","units":"milliseconds"}, "22":{"name":"flowStartSysUpTime","dataType":"unsigned32","group":"timestamp","units":"milliseconds"}, "23":{"name":"postOctetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"octets"}, "24":{"name":"postPacketDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"packets"}, "25":{"name":"minimumIpTotalLength","dataType":"unsigned64","group":"minMax","units":"octets"}, "26":{"name":"maximumIpTotalLength","dataType":"unsigned64","group":"minMax","units":"octets"}, "27":{"name":"sourceIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"ipHeader"}, "28":{"name":"destinationIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"ipHeader"}, "29":{"name":"sourceIPv6PrefixLength","dataType":"unsigned8","group":"ipHeader","units":"bits"}, "30":{"name":"destinationIPv6PrefixLength","dataType":"unsigned8","group":"ipHeader","units":"bits"}, "31":{"name":"flowLabelIPv6","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"ipHeader"}, "32":{"name":"icmpTypeCodeIPv4","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "33":{"name":"igmpType","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "36":{"name":"flowActiveTimeout","dataType":"unsigned16","group":"misc","units":"seconds"}, "37":{"name":"flowIdleTimeout","dataType":"unsigned16","group":"misc","units":"seconds"}, "40":{"name":"exportedOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"octets"}, "41":{"name":"exportedMessageTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"messages"}, "42":{"name":"exportedFlowRecordTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"flows"}, "44":{"name":"sourceIPv4Prefix","dataType":"ipv4Address","group":"ipHeader"}, "45":{"name":"destinationIPv4Prefix","dataType":"ipv4Address","group":"ipHeader"}, "46":{"name":"mplsTopLabelType","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"derived"}, "47":{"name":"mplsTopLabelIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"derived"}, "52":{"name":"minimumTTL","dataType":"unsigned8","group":"minMax","units":"hops"}, "53":{"name":"maximumTTL","dataType":"unsigned8","group":"minMax","units":"hops"}, "54":{"name":"fragmentIdentification","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"ipHeader"}, "55":{"name":"postIpClassOfService","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "56":{"name":"sourceMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier","group":"subIpHeader"}, "57":{"name":"postDestinationMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier","group":"subIpHeader"}, "58":{"name":"vlanId","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"subIpHeader"}, "59":{"name":"postVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"subIpHeader"}, "60":{"name":"ipVersion","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "61":{"name":"flowDirection","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"misc"}, "62":{"name":"ipNextHopIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"derived"}, "63":{"name":"bgpNextHopIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"derived"}, "64":{"name":"ipv6ExtensionHeaders","dataType":"unsigned32","dataTypeSemantics":"flags","group":"minMax"}, "70":{"name":"mplsTopLabelStackSection","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "71":{"name":"mplsLabelStackSection2","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "72":{"name":"mplsLabelStackSection3","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "73":{"name":"mplsLabelStackSection4","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "74":{"name":"mplsLabelStackSection5","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "75":{"name":"mplsLabelStackSection6","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "76":{"name":"mplsLabelStackSection7","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "77":{"name":"mplsLabelStackSection8","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "78":{"name":"mplsLabelStackSection9","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "79":{"name":"mplsLabelStackSection10","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "80":{"name":"destinationMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier","group":"subIpHeader"}, "81":{"name":"postSourceMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier","group":"subIpHeader"}, "82":{"name":"interfaceName","dataType":"string"},"83":{"name":"interfaceDescription","dataType":"string"}, "85":{"name":"octetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"octets"}, "86":{"name":"packetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "88":{"name":"fragmentOffset","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"ipHeader"}, "90":{"name":"mplsVpnRouteDistinguisher","dataType":"octetArray","dataTypeSemantics":"identifier","group":"derived"}, "91":{"name":"mplsTopLabelPrefixLength","dataType":"unsigned8","dataTypeSemantics":"identifier","units":"bits"}, "94":{"name":"applicationDescription","dataType":"string"}, "95":{"name":"applicationId","dataType":"octetArray","dataTypeSemantics":"identifier"}, "96":{"name":"applicationName","dataType":"string"}, "98":{"name":"postIpDiffServCodePoint","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "99":{"name":"multicastReplicationFactor","dataType":"unsigned32","dataTypeSemantics":"quantity"}, "101":{"name":"classificationEngineId","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "128":{"name":"bgpNextAdjacentAsNumber","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"derived"}, "129":{"name":"bgpPrevAdjacentAsNumber","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"derived"}, "130":{"name":"exporterIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"config"}, "131":{"name":"exporterIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"config"}, "132":{"name":"droppedOctetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"octets"}, "133":{"name":"droppedPacketDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"packets"}, "134":{"name":"droppedOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"octets"}, "135":{"name":"droppedPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "136":{"name":"flowEndReason","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"misc"}, "137":{"name":"commonPropertiesId","dataType":"unsigned64","dataTypeSemantics":"identifier","group":"scope"}, "138":{"name":"observationPointId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "139":{"name":"icmpTypeCodeIPv6","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "140":{"name":"mplsTopLabelIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"derived"}, "141":{"name":"lineCardId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "142":{"name":"portId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "143":{"name":"meteringProcessId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "144":{"name":"exportingProcessId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "145":{"name":"templateId","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"scope"}, "146":{"name":"wlanChannelId","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"subIpHeader"}, "147":{"name":"wlanSSID","dataType":"string","group":"subIpHeader"}, "148":{"name":"flowId","dataType":"unsigned64","dataTypeSemantics":"identifier","group":"scope"}, "149":{"name":"observationDomainId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "150":{"name":"flowStartSeconds","dataType":"dateTimeSeconds","group":"timestamp","units":"seconds"}, "151":{"name":"flowEndSeconds","dataType":"dateTimeSeconds","group":"timestamp","units":"seconds"}, "152":{"name":"flowStartMilliseconds","dataType":"dateTimeMilliseconds","group":"timestamp","units":"milliseconds"}, "153":{"name":"flowEndMilliseconds","dataType":"dateTimeMilliseconds","group":"timestamp","units":"milliseconds"}, "154":{"name":"flowStartMicroseconds","dataType":"dateTimeMicroseconds","group":"timestamp","units":"microseconds"}, "155":{"name":"flowEndMicroseconds","dataType":"dateTimeMicroseconds","group":"timestamp","units":"microseconds"}, "156":{"name":"flowStartNanoseconds","dataType":"dateTimeNanoseconds","group":"timestamp","units":"nanoseconds"}, "157":{"name":"flowEndNanoseconds","dataType":"dateTimeNanoseconds","group":"timestamp","units":"nanoseconds"}, "158":{"name":"flowStartDeltaMicroseconds","dataType":"unsigned32","group":"timestamp","units":"microseconds"}, "159":{"name":"flowEndDeltaMicroseconds","dataType":"unsigned32","group":"timestamp","units":"microseconds"}, "160":{"name":"systemInitTimeMilliseconds","dataType":"dateTimeMilliseconds","group":"timestamp","units":"milliseconds"}, "161":{"name":"flowDurationMilliseconds","dataType":"unsigned32","group":"misc","units":"milliseconds"}, "162":{"name":"flowDurationMicroseconds","dataType":"unsigned32","group":"misc","units":"microseconds"}, "163":{"name":"observedFlowTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"flows"}, "164":{"name":"ignoredPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"packets"}, "165":{"name":"ignoredOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"octets"}, "166":{"name":"notSentFlowTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"flows"}, "167":{"name":"notSentPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"packets"}, "168":{"name":"notSentOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"octets"}, "169":{"name":"destinationIPv6Prefix","dataType":"ipv6Address","group":"ipHeader"}, "170":{"name":"sourceIPv6Prefix","dataType":"ipv6Address","group":"ipHeader"}, "171":{"name":"postOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"octets"}, "172":{"name":"postPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "173":{"name":"flowKeyIndicator","dataType":"unsigned64","dataTypeSemantics":"flags","group":"config"}, "174":{"name":"postMCastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "175":{"name":"postMCastOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"octets"}, "176":{"name":"icmpTypeIPv4","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "177":{"name":"icmpCodeIPv4","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "178":{"name":"icmpTypeIPv6","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "179":{"name":"icmpCodeIPv6","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "180":{"name":"udpSourcePort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "181":{"name":"udpDestinationPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "182":{"name":"tcpSourcePort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "183":{"name":"tcpDestinationPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "184":{"name":"tcpSequenceNumber","dataType":"unsigned32","group":"transportHeader"}, "185":{"name":"tcpAcknowledgementNumber","dataType":"unsigned32","group":"transportHeader"}, "186":{"name":"tcpWindowSize","dataType":"unsigned16","group":"transportHeader"}, "187":{"name":"tcpUrgentPointer","dataType":"unsigned16","group":"transportHeader"}, "188":{"name":"tcpHeaderLength","dataType":"unsigned8","group":"transportHeader","units":"octets"}, "189":{"name":"ipHeaderLength","dataType":"unsigned8","group":"ipHeader","units":"octets"}, "190":{"name":"totalLengthIPv4","dataType":"unsigned16","group":"ipHeader","units":"octets"}, "191":{"name":"payloadLengthIPv6","dataType":"unsigned16","group":"ipHeader","units":"octets"}, "192":{"name":"ipTTL","dataType":"unsigned8","group":"ipHeader","units":"hops"}, "193":{"name":"nextHeaderIPv6","dataType":"unsigned8","group":"ipHeader"}, "194":{"name":"mplsPayloadLength","dataType":"unsigned32","group":"subIpHeader","units":"octets"}, "195":{"name":"ipDiffServCodePoint","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "196":{"name":"ipPrecedence","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "197":{"name":"fragmentFlags","dataType":"unsigned8","dataTypeSemantics":"flags","group":"ipHeader"}, "198":{"name":"octetDeltaSumOfSquares","dataType":"unsigned64","group":"flowCounter"}, "199":{"name":"octetTotalSumOfSquares","dataType":"unsigned64","group":"flowCounter","units":"octets"}, "200":{"name":"mplsTopLabelTTL","dataType":"unsigned8","group":"subIpHeader","units":"hops"}, "201":{"name":"mplsLabelStackLength","dataType":"unsigned32","group":"subIpHeader","units":"octets"}, "202":{"name":"mplsLabelStackDepth","dataType":"unsigned32","group":"subIpHeader","units":"label stack entries"}, "203":{"name":"mplsTopLabelExp","dataType":"unsigned8","dataTypeSemantics":"flags","group":"subIpHeader"}, "204":{"name":"ipPayloadLength","dataType":"unsigned32","group":"derived","units":"octets"}, "205":{"name":"udpMessageLength","dataType":"unsigned16","group":"transportHeader","units":"octets"}, "206":{"name":"isMulticast","dataType":"unsigned8","dataTypeSemantics":"flags","group":"ipHeader"}, "207":{"name":"ipv4IHL","dataType":"unsigned8","group":"ipHeader","units":"4 octets"}, "208":{"name":"ipv4Options","dataType":"unsigned32","dataTypeSemantics":"flags","group":"minMax"}, "209":{"name":"tcpOptions","dataType":"unsigned64","dataTypeSemantics":"flags","group":"minMax"}, "210":{"name":"paddingOctets","dataType":"octetArray","group":"padding"}, "211":{"name":"collectorIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"config"}, "212":{"name":"collectorIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"config"}, "213":{"name":"exportInterface","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"config"}, "214":{"name":"exportProtocolVersion","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"config"}, "215":{"name":"exportTransportProtocol","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"config"}, "216":{"name":"collectorTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"config"}, "217":{"name":"exporterTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"config"}, "218":{"name":"tcpSynTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "219":{"name":"tcpFinTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "220":{"name":"tcpRstTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "221":{"name":"tcpPshTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "222":{"name":"tcpAckTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "223":{"name":"tcpUrgTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "224":{"name":"ipTotalLength","dataType":"unsigned64","group":"ipHeader","units":"octets"}, "225":{"name":"postNATSourceIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier"}, "226":{"name":"postNATDestinationIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier"}, "227":{"name":"postNAPTSourceTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "228":{"name":"postNAPTDestinationTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "229":{"name":"natOriginatingAddressRealm","dataType":"unsigned8","dataTypeSemantics":"flags"}, "230":{"name":"natEvent","dataType":"unsigned8"}, "231":{"name":"initiatorOctets","dataType":"unsigned64","units":"octets"}, "232":{"name":"responderOctets","dataType":"unsigned64","units":"octets"}, "233":{"name":"firewallEvent","dataType":"unsigned8"}, "234":{"name":"ingressVRFID","dataType":"unsigned32"}, "235":{"name":"egressVRFID","dataType":"unsigned32"}, "236":{"name":"VRFname","dataType":"string"}, "237":{"name":"postMplsTopLabelExp","dataType":"unsigned8","dataTypeSemantics":"flags","group":"subIpHeader"}, "238":{"name":"tcpWindowScale","dataType":"unsigned16","group":"transportHeader"}, "239":{"name":"biflowDirection","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"misc"}, "240":{"name":"ethernetHeaderLength","dataType":"unsigned8","dataTypeSemantics":"identifier","units":"octets"}, "241":{"name":"ethernetPayloadLength","dataType":"unsigned16","dataTypeSemantics":"identifier","units":"octets"}, "242":{"name":"ethernetTotalLength","dataType":"unsigned16","dataTypeSemantics":"identifier","units":"octets"}, "243":{"name":"dot1qVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier","units":"octets"}, "244":{"name":"dot1qPriority","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "245":{"name":"dot1qCustomerVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "246":{"name":"dot1qCustomerPriority","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "247":{"name":"metroEvcId","dataType":"string"}, "248":{"name":"metroEvcType","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "249":{"name":"pseudoWireId","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "250":{"name":"pseudoWireType","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "251":{"name":"pseudoWireControlWord","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "252":{"name":"ingressPhysicalInterface","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "253":{"name":"egressPhysicalInterface","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "254":{"name":"postDot1qVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "255":{"name":"postDot1qCustomerVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "256":{"name":"ethernetType","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "257":{"name":"postIpPrecedence","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "258":{"name":"collectionTimeMilliseconds","dataType":"dateTimeMilliseconds"}, "259":{"name":"exportSctpStreamId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "260":{"name":"maxExportSeconds","dataType":"dateTimeSeconds","units":"seconds"}, "261":{"name":"maxFlowEndSeconds","dataType":"dateTimeSeconds","units":"seconds"}, "262":{"name":"messageMD5Checksum","dataType":"octetArray"}, "263":{"name":"messageScope","dataType":"unsigned8"}, "264":{"name":"minExportSeconds","dataType":"dateTimeSeconds","units":"seconds"}, "265":{"name":"minFlowStartSeconds","dataType":"dateTimeSeconds","units":"seconds"}, "266":{"name":"opaqueOctets","dataType":"octetArray"}, "267":{"name":"sessionScope","dataType":"unsigned8"}, "268":{"name":"maxFlowEndMicroseconds","dataType":"dateTimeMicroseconds","units":"microseconds"}, "269":{"name":"maxFlowEndMilliseconds","dataType":"dateTimeMilliseconds","units":"milliseconds"}, "270":{"name":"maxFlowEndNanoseconds","dataType":"dateTimeNanoseconds","units":"nanoseconds"}, "271":{"name":"minFlowStartMicroseconds","dataType":"dateTimeMicroseconds","units":"microseconds"}, "272":{"name":"minFlowStartMilliseconds","dataType":"dateTimeMilliseconds","units":"milliseconds"}, "273":{"name":"minFlowStartNanoseconds","dataType":"dateTimeNanoseconds","units":"nanoseconds"}, "274":{"name":"collectorCertificate","dataType":"octetArray"}, "275":{"name":"exporterCertificate","dataType":"octetArray"}, "276":{"name":"dataRecordsReliability","dataType":"boolean","dataTypeSemantics":"identifier"}, "277":{"name":"observationPointType","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "278":{"name":"connectionCountNew","dataType":"unsigned32","dataTypeSemantics":"deltaCounter"}, "279":{"name":"connectionSumDuration","dataType":"unsigned64"}, "280":{"name":"connectionTransactionId","dataType":"unsigned64","dataTypeSemantics":"identifier"}, "281":{"name":"postNATSourceIPv6Address","dataType":"ipv6Address"}, "282":{"name":"postNATDestinationIPv6Address","dataType":"ipv6Address"}, "283":{"name":"natPoolId","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "284":{"name":"natPoolName","dataType":"string"}, "285":{"name":"anonymizationFlags","dataType":"unsigned16","dataTypeSemantics":"flags"}, "286":{"name":"anonymizationTechnique","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "287":{"name":"informationElementIndex","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "288":{"name":"p2pTechnology","dataType":"string"}, "289":{"name":"tunnelTechnology","dataType":"string"}, "290":{"name":"encryptedTechnology","dataType":"string"}, "291":{"name":"basicList","dataType":"basicList","dataTypeSemantics":"list"}, "292":{"name":"subTemplateList","dataType":"subTemplateList","dataTypeSemantics":"list"}, "293":{"name":"subTemplateMultiList","dataType":"subTemplateMultiList","dataTypeSemantics":"list"}, "294":{"name":"bgpValidityState","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "295":{"name":"IPSecSPI","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "296":{"name":"greKey","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "297":{"name":"natType","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "298":{"name":"initiatorPackets","dataType":"unsigned64","dataTypeSemantics":"identifier","units":"packets"}, "299":{"name":"responderPackets","dataType":"unsigned64","dataTypeSemantics":"identifier","units":"packets"}, "300":{"name":"observationDomainName","dataType":"string"}, "301":{"name":"selectionSequenceId","dataType":"unsigned64","dataTypeSemantics":"identifier"}, "302":{"name":"selectorId","dataType":"unsigned64","dataTypeSemantics":"identifier"}, "303":{"name":"informationElementId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "304":{"name":"selectorAlgorithm","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "305":{"name":"samplingPacketInterval","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"packets"}, "306":{"name":"samplingPacketSpace","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"packets"}, "307":{"name":"samplingTimeInterval","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"microseconds"}, "308":{"name":"samplingTimeSpace","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"microseconds"}, "309":{"name":"samplingSize","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"packets"}, "310":{"name":"samplingPopulation","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"packets"}, "311":{"name":"samplingProbability","dataType":"float64","dataTypeSemantics":"quantity"}, "312":{"name":"dataLinkFrameSize","dataType":"unsigned16"}, "313":{"name":"ipHeaderPacketSection","dataType":"octetArray"}, "314":{"name":"ipPayloadPacketSection","dataType":"octetArray"}, "315":{"name":"dataLinkFrameSection","dataType":"octetArray"}, "316":{"name":"mplsLabelStackSection","dataType":"octetArray"}, "317":{"name":"mplsPayloadPacketSection","dataType":"octetArray"}, "318":{"name":"selectorIdTotalPktsObserved","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "319":{"name":"selectorIdTotalPktsSelected","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "320":{"name":"absoluteError","dataType":"float64","dataTypeSemantics":"quantity","units":"The units of the Information Element for which the error is specified."}, "321":{"name":"relativeError","dataType":"float64","dataTypeSemantics":"quantity"}, "322":{"name":"observationTimeSeconds","dataType":"dateTimeSeconds","dataTypeSemantics":"quantity","units":"seconds"}, "323":{"name":"observationTimeMilliseconds","dataType":"dateTimeMilliseconds","dataTypeSemantics":"quantity","units":"milliseconds"}, "324":{"name":"observationTimeMicroseconds","dataType":"dateTimeMicroseconds","dataTypeSemantics":"quantity","units":"microseconds"}, "325":{"name":"observationTimeNanoseconds","dataType":"dateTimeNanoseconds","dataTypeSemantics":"quantity","units":"nanoseconds"}, "326":{"name":"digestHashValue","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "327":{"name":"hashIPPayloadOffset","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "328":{"name":"hashIPPayloadSize","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "329":{"name":"hashOutputRangeMin","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "330":{"name":"hashOutputRangeMax","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "331":{"name":"hashSelectedRangeMin","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "332":{"name":"hashSelectedRangeMax","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "333":{"name":"hashDigestOutput","dataType":"boolean","dataTypeSemantics":"quantity"}, "334":{"name":"hashInitialiserValue","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "335":{"name":"selectorName","dataType":"string"}, "336":{"name":"upperCILimit","dataType":"float64","dataTypeSemantics":"quantity"}, "337":{"name":"lowerCILimit","dataType":"float64","dataTypeSemantics":"quantity"}, "338":{"name":"confidenceLevel","dataType":"float64","dataTypeSemantics":"quantity"}, "339":{"name":"informationElementDataType","dataType":"unsigned8"}, "340":{"name":"informationElementDescription","dataType":"string"}, "341":{"name":"informationElementName","dataType":"string"}, "342":{"name":"informationElementRangeBegin","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "343":{"name":"informationElementRangeEnd","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "344":{"name":"informationElementSemantics","dataType":"unsigned8"}, "345":{"name":"informationElementUnits","dataType":"unsigned16"}, "346":{"name":"privateEnterpriseNumber","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "347":{"name":"virtualStationInterfaceId","dataType":"octetArray","dataTypeSemantics":"identifier"}, "348":{"name":"virtualStationInterfaceName","dataType":"string"}, "349":{"name":"virtualStationUUID","dataType":"octetArray","dataTypeSemantics":"identifier"}, "350":{"name":"virtualStationName","dataType":"string"}, "351":{"name":"layer2SegmentId","dataType":"unsigned64","dataTypeSemantics":"identifier"}, "352":{"name":"layer2OctetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","units":"octets"}, "353":{"name":"layer2OctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"octets"}, "354":{"name":"ingressUnicastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "355":{"name":"ingressMulticastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "356":{"name":"ingressBroadcastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "357":{"name":"egressUnicastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "358":{"name":"egressBroadcastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "359":{"name":"monitoringIntervalStartMilliSeconds","dataType":"dateTimeMilliseconds","units":"milliseconds"}, "360":{"name":"monitoringIntervalEndMilliSeconds","dataType":"dateTimeMilliseconds","units":"milliseconds"}, "361":{"name":"portRangeStart","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "362":{"name":"portRangeEnd","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "363":{"name":"portRangeStepSize","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "364":{"name":"portRangeNumPorts","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "365":{"name":"staMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier"}, "366":{"name":"staIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier"}, "367":{"name":"wtpMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier"}, "368":{"name":"ingressInterfaceType","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "369":{"name":"egressInterfaceType","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "370":{"name":"rtpSequenceNumber","dataType":"unsigned16"}, "371":{"name":"userName","dataType":"string"}, "372":{"name":"applicationCategoryName","dataType":"string"}, "373":{"name":"applicationSubCategoryName","dataType":"string"}, "374":{"name":"applicationGroupName","dataType":"string"}, "375":{"name":"originalFlowsPresent","dataType":"unsigned64","dataTypeSemantics":"deltaCounter"}, "376":{"name":"originalFlowsInitiated","dataType":"unsigned64","dataTypeSemantics":"deltaCounter"}, "377":{"name":"originalFlowsCompleted","dataType":"unsigned64","dataTypeSemantics":"deltaCounter"}, "378":{"name":"distinctCountOfSourceIPAddress","dataType":"unsigned64","dataTypeSemantics":"totalCounter"}, "379":{"name":"distinctCountOfDestinationIPAddress","dataType":"unsigned64","dataTypeSemantics":"totalCounter"}, "380":{"name":"distinctCountOfSourceIPv4Address","dataType":"unsigned32","dataTypeSemantics":"totalCounter"}, "381":{"name":"distinctCountOfDestinationIPv4Address","dataType":"unsigned32","dataTypeSemantics":"totalCounter"}, "382":{"name":"distinctCountOfSourceIPv6Address","dataType":"unsigned64","dataTypeSemantics":"totalCounter"}, "383":{"name":"distinctCountOfDestinationIPv6Address","dataType":"unsigned64","dataTypeSemantics":"totalCounter"}, "384":{"name":"valueDistributionMethod","dataType":"unsigned8"}, "385":{"name":"rfc3550JitterMilliseconds","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"milliseconds"}, "386":{"name":"rfc3550JitterMicroseconds","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"microseconds"}, "387":{"name":"rfc3550JitterNanoseconds","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"nanoseconds"} } //ipfix-mpls-label-type entities['mpls'] = { "1":{"description":"TE-MIDPT: Any TE tunnel mid-point or tail label"}, "2":{"description":"Pseudowire: Any PWE3 or Cisco AToM based label"}, "3":{"description":"VPN: Any label associated with VPN"}, "4":{"description":"BGP: Any label associated with BGP or BGP routing"}, "5":{"description":"LDP: Any label associated with dynamically assigned labels using LDP"} } //classification-engine-ids entities['engineIds'] = { "1":{"description":"IANA-L3", "length":"1"}, "2":{"description":"PANA-L3", "length":"1"}, "3":{"description":"IANA-L4", "length":"2"}, "4":{"description":"PANA-L4", "length":"2"}, "6":{"description":"USER-Defined", "length":"3"}, "12":{"description":"PANA-L2", "length":"5"}, "13":{"description":"PANA-L7", "length":"3"}, "18":{"description":"ETHERTYPE", "length":"2"}, "19":{"description":"LLC", "length":"1"}, "20":{"description":"PANA-L7-PEN", "length":"3"}, } //ipfix-version-numbers entities['version'] = { "9":{"version":"Cisco Systems NetFlow Version 9"}, "10":{"version":"IPFIX as documented in RFC5101"} } //ipfix-set-ids entities['setIds'] = { "2":{"setId":"Template Set"}, "3":{"setId":"Option Template Set"} } //ipfix-information-element-data-types entities['dataTypes'] = { "octetArray":{}, "unsigned8":{}, "unsigned16":{}, "unsigned32":{}, "unsigned64":{}, "signed8":{}, "signed16":{}, "signed32":{}, "signed64":{}, "float32":{}, "float64":{}, "boolean":{}, "macAddress":{ "key":"%0-%1-%2-%3-%4-%5"}, "string":{}, "dateTimeSeconds":{}, "dateTimeMilliseconds":{}, "dateTimeMicroseconds":{}, "dateTimeNanoseconds":{}, "ipv4Address":{"key":"%0.%1.%2.%3"}, "ipv6Address":{"key":"%0:%1:%2:%3:%4:%5:%6:%7"}, "basicList":{}, "subTemplateList":{}, "subTemplateMultiList":{} } //ipfix-information-element-semantics entities['ieSemantics'] = { "0":{"description":"default"}, "1":{"description":"quantity"}, "2":{"description":"totalCounter"}, "3":{"description":"deltaCounter"}, "4":{"description":"identifier"}, "5":{"description":"flags"}, "6":{"description":"list"} } //ipfix-information-element-units entities['units'] = { "0":{"name":"none"}, "1":{"name":"bits"}, "2":{"name":"octets"}, "3":{"name":"packets"}, "4":{"name":"flows"}, "5":{"name":"seconds"}, "6":{"name":"milliseconds"}, "7":{"name":"microseconds"}, "8":{"name":"nanoseconds"}, "9":{"name":"4-octet words"}, "10":{"name":"messages"}, "11":{"name":"hops"}, "12":{"name":"entries"} } //ipfix-structured-data-types-semantics entities['sdSemantics'] = { "0x00":{"name":"noneOf"}, "0x01":{"name":"exactlyOneOf"}, "0x02":{"name":"oneOrMoreOf"}, "0x03":{"name":"allOf"}, "0x04":{"name":"ordered"}, "0xFF":{"name":"undefined"}, } exports.entities = entities;
shaofis/Netflow
lib/ipfix.js
JavaScript
mit
37,954
/* @flow */ import { InputTypeComposer, type ObjectTypeComposerFieldConfigAsObjectDefinition, } from 'graphql-compose'; import { getTypeName, type CommonOpts, desc } from '../../../utils'; import { getAllAsFieldConfigMap } from '../../Commons/FieldNames'; export function getRangeITC<TContext>( opts: CommonOpts<TContext> ): InputTypeComposer<TContext> | ObjectTypeComposerFieldConfigAsObjectDefinition<any, any> { const name = getTypeName('QueryRange', opts); const description = desc( ` Matches documents with fields that have terms within a certain range. [Documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html) ` ); const subName = getTypeName('QueryRangeSettings', opts); const fields = getAllAsFieldConfigMap( opts, opts.getOrCreateITC(subName, () => ({ name: subName, fields: { gt: 'JSON', gte: 'JSON', lt: 'JSON', lte: 'JSON', boost: 'Float', relation: 'String', }, })) ); if (typeof fields === 'object') { return opts.getOrCreateITC(name, () => ({ name, description, fields, })); } return { type: 'JSON', description, }; }
nodkz/graphql-compose-elasticsearch
src/elasticDSL/Query/TermLevel/Range.js
JavaScript
mit
1,241
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({lblItem:"\u30a2\u30a4\u30c6\u30e0",title:"\u30b5\u30a4\u30f3 \u30a4\u30f3",info:"{server} {resource} \u306e\u30a2\u30a4\u30c6\u30e0\u306b\u30a2\u30af\u30bb\u30b9\u3059\u308b\u306b\u306f\u30b5\u30a4\u30f3 \u30a4\u30f3\u3057\u3066\u304f\u3060\u3055\u3044",oAuthInfo:"{server} \u306b\u30b5\u30a4\u30f3 \u30a4\u30f3\u3057\u3066\u304f\u3060\u3055\u3044\u3002",lblUser:"\u30e6\u30fc\u30b6\u30fc\u540d:",lblPwd:"\u30d1\u30b9\u30ef\u30fc\u30c9:",lblOk:"OK",lblSigning:"\u30b5\u30a4\u30f3 \u30a4\u30f3\u3057\u3066\u3044\u307e\u3059...", lblCancel:"\u30ad\u30e3\u30f3\u30bb\u30eb",errorMsg:"\u30e6\u30fc\u30b6\u30fc\u540d\u307e\u305f\u306f\u30d1\u30b9\u30ef\u30fc\u30c9\u304c\u7121\u52b9\u3067\u3059\u3002\u3082\u3046\u4e00\u5ea6\u3084\u308a\u76f4\u3057\u3066\u304f\u3060\u3055\u3044\u3002",invalidUser:"\u5165\u529b\u3057\u305f\u30e6\u30fc\u30b6\u30fc\u540d\u307e\u305f\u306f\u30d1\u30b9\u30ef\u30fc\u30c9\u304c\u6b63\u3057\u304f\u3042\u308a\u307e\u305b\u3093\u3002",forbidden:"\u30e6\u30fc\u30b6\u30fc\u540d\u3068\u30d1\u30b9\u30ef\u30fc\u30c9\u306f\u6709\u52b9\u3067\u3059\u304c\u3001\u3053\u306e\u30ea\u30bd\u30fc\u30b9\u3078\u306e\u30a2\u30af\u30bb\u30b9\u6a29\u304c\u3042\u308a\u307e\u305b\u3093\u3002", noAuthService:"\u8a8d\u8a3c\u30b5\u30fc\u30d3\u30b9\u306b\u30a2\u30af\u30bb\u30b9\u3067\u304d\u307e\u305b\u3093\u3002"});
ycabon/presentations
2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/identity/nls/ja/identity.js
JavaScript
mit
1,486
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Split the input into chunks. exports.default = (function (input, fail) { var len = input.length; var level = 0; var parenLevel = 0; var lastOpening; var lastOpeningParen; var lastMultiComment; var lastMultiCommentEndBrace; var chunks = []; var emitFrom = 0; var chunkerCurrentIndex; var currentChunkStartIndex; var cc; var cc2; var matched; function emitChunk(force) { var len = chunkerCurrentIndex - emitFrom; if (((len < 512) && !force) || !len) { return; } chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1)); emitFrom = chunkerCurrentIndex + 1; } for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) { cc = input.charCodeAt(chunkerCurrentIndex); if (((cc >= 97) && (cc <= 122)) || (cc < 34)) { // a-z or whitespace continue; } switch (cc) { case 40: // ( parenLevel++; lastOpeningParen = chunkerCurrentIndex; continue; case 41: // ) if (--parenLevel < 0) { return fail('missing opening `(`', chunkerCurrentIndex); } continue; case 59: // ; if (!parenLevel) { emitChunk(); } continue; case 123: // { level++; lastOpening = chunkerCurrentIndex; continue; case 125: // } if (--level < 0) { return fail('missing opening `{`', chunkerCurrentIndex); } if (!level && !parenLevel) { emitChunk(); } continue; case 92: // \ if (chunkerCurrentIndex < len - 1) { chunkerCurrentIndex++; continue; } return fail('unescaped `\\`', chunkerCurrentIndex); case 34: case 39: case 96: // ", ' and ` matched = 0; currentChunkStartIndex = chunkerCurrentIndex; for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) { cc2 = input.charCodeAt(chunkerCurrentIndex); if (cc2 > 96) { continue; } if (cc2 == cc) { matched = 1; break; } if (cc2 == 92) { // \ if (chunkerCurrentIndex == len - 1) { return fail('unescaped `\\`', chunkerCurrentIndex); } chunkerCurrentIndex++; } } if (matched) { continue; } return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex); case 47: // /, check for comment if (parenLevel || (chunkerCurrentIndex == len - 1)) { continue; } cc2 = input.charCodeAt(chunkerCurrentIndex + 1); if (cc2 == 47) { // //, find lnfeed for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) { cc2 = input.charCodeAt(chunkerCurrentIndex); if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; } } } else if (cc2 == 42) { // /*, find */ lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex; for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) { cc2 = input.charCodeAt(chunkerCurrentIndex); if (cc2 == 125) { lastMultiCommentEndBrace = chunkerCurrentIndex; } if (cc2 != 42) { continue; } if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) { break; } } if (chunkerCurrentIndex == len - 1) { return fail('missing closing `*/`', currentChunkStartIndex); } chunkerCurrentIndex++; } continue; case 42: // *, check for unmatched */ if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) { return fail('unmatched `/*`', chunkerCurrentIndex); } continue; } } if (level !== 0) { if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) { return fail('missing closing `}` or `*/`', lastOpening); } else { return fail('missing closing `}`', lastOpening); } } else if (parenLevel !== 0) { return fail('missing closing `)`', lastOpeningParen); } emitChunk(true); return chunks; }); //# sourceMappingURL=chunker.js.map
lordtiago/linvs
node_modules/less/lib/less/parser/chunker.js
JavaScript
mit
5,641
angular.module("umbraco") .controller("Umbraco.PropertyEditors.RTEController", function ($rootScope, $scope, $q, $locale, dialogService, $log, imageHelper, assetsService, $timeout, tinyMceService, angularHelper, stylesheetResource, macroService, editorState) { $scope.isLoading = true; //To id the html textarea we need to use the datetime ticks because we can have multiple rte's per a single property alias // because now we have to support having 2x (maybe more at some stage) content editors being displayed at once. This is because // we have this mini content editor panel that can be launched with MNTP. var d = new Date(); var n = d.getTime(); $scope.textAreaHtmlId = $scope.model.alias + "_" + n + "_rte"; function syncContent(editor){ editor.save(); angularHelper.safeApply($scope, function () { $scope.model.value = editor.getContent(); }); //make the form dirty manually so that the track changes works, setting our model doesn't trigger // the angular bits because tinymce replaces the textarea. angularHelper.getCurrentForm($scope).$setDirty(); } tinyMceService.configuration().then(function (tinyMceConfig) { //config value from general tinymce.config file var validElements = tinyMceConfig.validElements; //These are absolutely required in order for the macros to render inline //we put these as extended elements because they get merged on top of the normal allowed elements by tiny mce var extendedValidElements = "@[id|class|style],-div[id|dir|class|align|style],ins[datetime|cite],-ul[class|style],-li[class|style],span[id|class|style]"; var invalidElements = tinyMceConfig.inValidElements; var plugins = _.map(tinyMceConfig.plugins, function (plugin) { if (plugin.useOnFrontend) { return plugin.name; } }).join(" "); var editorConfig = $scope.model.config.editor; if (!editorConfig || angular.isString(editorConfig)) { editorConfig = tinyMceService.defaultPrevalues(); } //config value on the data type var toolbar = editorConfig.toolbar.join(" | "); var stylesheets = []; var styleFormats = []; var await = []; if (!editorConfig.maxImageSize && editorConfig.maxImageSize != 0) { editorConfig.maxImageSize = tinyMceService.defaultPrevalues().maxImageSize; } //queue file loading if (typeof tinymce === "undefined") { // Don't reload tinymce if already loaded await.push(assetsService.loadJs("lib/tinymce/tinymce.min.js", $scope)); } //queue rules loading angular.forEach(editorConfig.stylesheets, function (val, key) { stylesheets.push(Umbraco.Sys.ServerVariables.umbracoSettings.cssPath + "/" + val + ".css?" + new Date().getTime()); await.push(stylesheetResource.getRulesByName(val).then(function (rules) { angular.forEach(rules, function (rule) { var r = {}; r.title = rule.name; if (rule.selector[0] == ".") { r.inline = "span"; r.classes = rule.selector.substring(1); } else if (rule.selector[0] == "#") { r.inline = "span"; r.attributes = { id: rule.selector.substring(1) }; } else if (rule.selector[0] != "." && rule.selector.indexOf(".") > -1) { var split = rule.selector.split("."); r.block = split[0]; r.classes = rule.selector.substring(rule.selector.indexOf(".") + 1).replace(".", " "); } else if (rule.selector[0] != "#" && rule.selector.indexOf("#") > -1) { var split = rule.selector.split("#"); r.block = split[0]; r.classes = rule.selector.substring(rule.selector.indexOf("#") + 1); } else { r.block = rule.selector; } styleFormats.push(r); }); })); }); //stores a reference to the editor var tinyMceEditor = null; // these languages are available for localization var availableLanguages = [ 'da', 'de', 'en', 'en_us', 'fi', 'fr', 'he', 'it', 'ja', 'nl', 'no', 'pl', 'pt', 'ru', 'sv', 'zh' ]; //define fallback language var language = 'en_us'; //get locale from angular and match tinymce format. Angular localization is always in the format of ru-ru, de-de, en-gb, etc. //wheras tinymce is in the format of ru, de, en, en_us, etc. var localeId = $locale.id.replace('-', '_'); //try matching the language using full locale format var languageMatch = _.find(availableLanguages, function(o) { return o === localeId; }); //if no matches, try matching using only the language if (languageMatch === undefined) { var localeParts = localeId.split('_'); languageMatch = _.find(availableLanguages, function(o) { return o === localeParts[0]; }); } //if a match was found - set the language if (languageMatch !== undefined) { language = languageMatch; } //wait for queue to end $q.all(await).then(function () { //create a baseline Config to exten upon var baseLineConfigObj = { mode: "exact", skin: "umbraco", plugins: plugins, valid_elements: validElements, invalid_elements: invalidElements, extended_valid_elements: extendedValidElements, menubar: false, statusbar: false, relative_urls: false, height: editorConfig.dimensions.height, width: editorConfig.dimensions.width, maxImageSize: editorConfig.maxImageSize, toolbar: toolbar, content_css: stylesheets, style_formats: styleFormats, language: language, //see http://archive.tinymce.com/wiki.php/Configuration:cache_suffix cache_suffix: "?umb__rnd=" + Umbraco.Sys.ServerVariables.application.cacheBuster }; if (tinyMceConfig.customConfig) { //if there is some custom config, we need to see if the string value of each item might actually be json and if so, we need to // convert it to json instead of having it as a string since this is what tinymce requires for (var i in tinyMceConfig.customConfig) { var val = tinyMceConfig.customConfig[i]; if (val) { val = val.toString().trim(); if (val.detectIsJson()) { try { tinyMceConfig.customConfig[i] = JSON.parse(val); //now we need to check if this custom config key is defined in our baseline, if it is we don't want to //overwrite the baseline config item if it is an array, we want to concat the items in the array, otherwise //if it's an object it will overwrite the baseline if (angular.isArray(baseLineConfigObj[i]) && angular.isArray(tinyMceConfig.customConfig[i])) { //concat it and below this concat'd array will overwrite the baseline in angular.extend tinyMceConfig.customConfig[i] = baseLineConfigObj[i].concat(tinyMceConfig.customConfig[i]); } } catch (e) { //cannot parse, we'll just leave it } } if (val === "true") { tinyMceConfig.customConfig[i] = true; } if (val === "false") { tinyMceConfig.customConfig[i] = false; } } } angular.extend(baseLineConfigObj, tinyMceConfig.customConfig); } //set all the things that user configs should not be able to override baseLineConfigObj.elements = $scope.textAreaHtmlId; //this is the exact textarea id to replace! baseLineConfigObj.setup = function (editor) { //set the reference tinyMceEditor = editor; //enable browser based spell checking editor.on('init', function (e) { editor.getBody().setAttribute('spellcheck', true); }); //We need to listen on multiple things here because of the nature of tinymce, it doesn't //fire events when you think! //The change event doesn't fire when content changes, only when cursor points are changed and undo points //are created. the blur event doesn't fire if you insert content into the editor with a button and then //press save. //We have a couple of options, one is to do a set timeout and check for isDirty on the editor, or we can //listen to both change and blur and also on our own 'saving' event. I think this will be best because a //timer might end up using unwanted cpu and we'd still have to listen to our saving event in case they clicked //save before the timeout elapsed. //TODO: We need to re-enable something like this to ensure the track changes is working with tinymce // so we can detect if the form is dirty or not, Per has some better events to use as this one triggers // even if you just enter/exit with mouse cursuor which doesn't really mean it's changed. // see: http://issues.umbraco.org/issue/U4-4485 //var alreadyDirty = false; //editor.on('change', function (e) { // angularHelper.safeApply($scope, function () { // $scope.model.value = editor.getContent(); // if (!alreadyDirty) { // //make the form dirty manually so that the track changes works, setting our model doesn't trigger // // the angular bits because tinymce replaces the textarea. // var currForm = angularHelper.getCurrentForm($scope); // currForm.$setDirty(); // alreadyDirty = true; // } // }); //}); //when we leave the editor (maybe) editor.on('blur', function (e) { editor.save(); angularHelper.safeApply($scope, function () { $scope.model.value = editor.getContent(); }); }); //when buttons modify content editor.on('ExecCommand', function (e) { syncContent(editor); }); // Update model on keypress editor.on('KeyUp', function (e) { syncContent(editor); }); // Update model on change, i.e. copy/pasted text, plugins altering content editor.on('SetContent', function (e) { if (!e.initial) { syncContent(editor); } }); editor.on('ObjectResized', function (e) { var qs = "?width=" + e.width + "&height=" + e.height + "&mode=max"; var srcAttr = $(e.target).attr("src"); var path = srcAttr.split("?")[0]; $(e.target).attr("data-mce-src", path + qs); syncContent(editor); }); tinyMceService.createLinkPicker(editor, $scope, function(currentTarget, anchorElement) { $scope.linkPickerOverlay = { view: "linkpicker", currentTarget: currentTarget, anchors: editorState.current ? tinyMceService.getAnchorNames(JSON.stringify(editorState.current.properties)) : [], ignoreUserStartNodes: $scope.model.config.ignoreUserStartNodes === "1", show: true, submit: function(model) { tinyMceService.insertLinkInEditor(editor, model.target, anchorElement); $scope.linkPickerOverlay.show = false; $scope.linkPickerOverlay = null; } }; }); //Create the insert media plugin tinyMceService.createMediaPicker(editor, $scope, function(currentTarget, userData){ var ignoreUserStartNodes = false; var startNodeId = userData.startMediaIds.length !== 1 ? -1 : userData.startMediaIds[0]; var startNodeIsVirtual = userData.startMediaIds.length !== 1; if ($scope.model.config.ignoreUserStartNodes === "1") { ignoreUserStartNodes = true; startNodeId = -1; startNodeIsVirtual = true; } $scope.mediaPickerOverlay = { currentTarget: currentTarget, onlyImages: true, showDetails: true, disableFolderSelect: true, startNodeId: startNodeId, startNodeIsVirtual: startNodeIsVirtual, ignoreUserStartNodes: ignoreUserStartNodes, view: "mediapicker", show: true, submit: function(model) { tinyMceService.insertMediaInEditor(editor, model.selectedImages[0]); $scope.mediaPickerOverlay.show = false; $scope.mediaPickerOverlay = null; } }; }); //Create the embedded plugin tinyMceService.createInsertEmbeddedMedia(editor, $scope, function() { $scope.embedOverlay = { view: "embed", show: true, submit: function(model) { tinyMceService.insertEmbeddedMediaInEditor(editor, model.embed.preview); $scope.embedOverlay.show = false; $scope.embedOverlay = null; } }; }); //Create the insert macro plugin tinyMceService.createInsertMacro(editor, $scope, function(dialogData) { $scope.macroPickerOverlay = { view: "macropicker", dialogData: dialogData, show: true, submit: function(model) { var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine); tinyMceService.insertMacroInEditor(editor, macroObject, $scope); $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; } }; }); }; /** Loads in the editor */ function loadTinyMce() { //we need to add a timeout here, to force a redraw so TinyMCE can find //the elements needed $timeout(function () { tinymce.DOM.events.domLoaded = true; tinymce.init(baseLineConfigObj); $scope.isLoading = false; }, 200, false); } loadTinyMce(); //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server; //uses an empty string in the editor when the value is null tinyMceEditor.setContent(newVal || "", { format: 'raw' }); //we need to manually fire this event since it is only ever fired based on loading from the DOM, this // is required for our plugins listening to this event to execute tinyMceEditor.fire('LoadContent', null); }; //listen for formSubmitting event (the result is callback used to remove the event subscription) var unsubscribe = $scope.$on("formSubmitting", function () { //TODO: Here we should parse out the macro rendered content so we can save on a lot of bytes in data xfer // we do parse it out on the server side but would be nice to do that on the client side before as well. if (tinyMceEditor !== undefined && tinyMceEditor != null && !$scope.isLoading) { $scope.model.value = tinyMceEditor.getContent(); } }); //when the element is disposed we need to unsubscribe! // NOTE: this is very important otherwise if this is part of a modal, the listener still exists because the dom // element might still be there even after the modal has been hidden. $scope.$on('$destroy', function () { unsubscribe(); if (tinyMceEditor !== undefined && tinyMceEditor != null) { tinyMceEditor.destroy(); } }); }); }); });
tompipe/Umbraco-CMS
src/Umbraco.Web.UI.Client/src/views/propertyeditors/rte/rte.controller.js
JavaScript
mit
20,615
'use strict'; var isA = require("Espresso/oop").isA; var oop = require("Espresso/oop").oop; var init = require("Espresso/oop").init; var trim = require("Espresso/trim").trim; var isA = require("Espresso/oop").isA; var oop = require("Espresso/oop").oop; function RequestInterface(){ oop(this,"Espresso/Http/RequestInterface"); } module.exports = RequestInterface;
quimsy/espresso
Http/RequestInterface.js
JavaScript
mit
369
module.exports = function(dataUri, maxDimension, callback){ var source = new Image(); source.addEventListener('load', function(){ var canvas = document.createElement('canvas'), ratio = Math.max(source.width, source.height) / maxDimension; canvas.width = source.width / ratio; canvas.height = source.height / ratio; var context = canvas.getContext('2d'); context.drawImage( source, 0, 0, source.width, source.height, 0, 0, canvas.width, canvas.height ); callback(null, canvas.toDataURL()); }); source.src = dataUri; };
MauriceButler/resizeo
index.js
JavaScript
mit
715
// @flow import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import Middleware from './Middleware'; type Base = { href?: string, target?: string, }; type Link = { crossOrigin?: string, href?: string, hrefLang?: string, integrity?: string, media?: string, preload?: boolean, prefetch?: boolean, rel?: string, sizes?: string, title?: string, type?: string, }; type Meta = { content?: string, httpEquiv?: string, charSet?: string, name?: string }; type Script = { async?: boolean, crossOrigin?: string, defer?: boolean, integrity?: string, script?: string, src?: string, type?: string, }; type Stylesheet = { href?: string, media?: string, rel?: string }; type Head = { base?: Base, meta?: Array<Meta>, links?: Array<Link>, scripts?: Array<Script>, stylesheets?: Array<Stylesheet>, title?: string, }; type Result = { body?: string, containerId?: string, head?: Head, lang?: string, scripts?: Array<Script>, status?: number, stylesheets?: Array<Stylesheet>, }; export type Props = { render: (context: *) => Promise<Result> | Result, }; export function renderHead(head: Head, additionalStylesheets?: Array<Stylesheet> = []): string { const metaTags = head.meta || []; const links = head.links || []; const scripts = head.scripts || []; const stylesheets = [...(head.stylesheets || []), ...additionalStylesheets]; return renderToStaticMarkup( <head> {head.base && <base {...head.base} />} {metaTags.map((tag, i) => <meta key={i} {...tag} />)} <title> {head.title} </title> {links.map((linkAttrs, i) => <link key={i} {...linkAttrs} />)} {stylesheets.map((stylesheetAttrs, i) => <link key={`s-${i}`} {...stylesheetAttrs} rel={stylesheetAttrs.rel || 'stylesheet'} />, )} {scripts.map((scriptAttrs, i) => <script key={`scr-${i}`} {...scriptAttrs} dangerouslySetInnerHTML={{ __html: scriptAttrs.script }} />, )} </head>, ); } export function renderFooter(scripts?: Array<Script> = []): string { return renderToStaticMarkup( <footer> {scripts.map((scriptAttrs, i) => <script key={`fscr-${i}`} {...scriptAttrs} dangerouslySetInnerHTML={{ __html: scriptAttrs.script }} />, )} </footer>, ).replace(/<(\/)?footer>/g, ''); } export default function RenderApp({ render }: Props) { return ( <Middleware use={async ctx => { const { body = '', containerId = 'app', lang = 'en', head = {}, scripts = [], status, stylesheets = [], } = await render(ctx); ctx.status = status || 200; ctx.body = ` <html lang="${lang}"> ${renderHead(head, stylesheets)} <body> <div id="${containerId}">${body}</div> ${renderFooter(scripts)} </body> </html> `.trim(); }} /> ); }
michalkvasnicak/spust
packages/spust-koa/src/RenderApp.js
JavaScript
mit
2,997
import { RESOURCE, SERVER_ERRORS, INITIAL_STATE_WITH_CACHED_LIST, INITIAL_STATE_WITH_LIST_BEING_FETCHED, INITIAL_STATE_WITH_CACHED_AND_SELECTED_LIST, } from '../mocks' import { generateListResourceActions } from './mocks' const request = () => Promise.resolve([RESOURCE]) const errorRequest = () => Promise.reject(SERVER_ERRORS) it('will dispatch two actions on success', async () => { const actions = await generateListResourceActions({ request }) expect(actions.length).toBe(2) }) it('will dispatch two actions on error', async () => { const actions = await generateListResourceActions({ request: errorRequest }) expect(actions.length).toBe(2) }) it('will dispatch one action if the list is cached but not selected', async () => { const actions = await generateListResourceActions({ request: errorRequest, initialState: INITIAL_STATE_WITH_CACHED_LIST, }) expect(actions.length).toBe(1) }) it('will dispatch two action if the list is cached but shouldIgnoreCache is passed', async () => { const actions = await generateListResourceActions({ request: errorRequest, shouldIgnoreCache: true, initialState: INITIAL_STATE_WITH_CACHED_LIST, }) expect(actions.length).toBe(2) }) it('will dispatch no actions if the list is cached and selected', async () => { const actions = await generateListResourceActions({ request: errorRequest, initialState: INITIAL_STATE_WITH_CACHED_AND_SELECTED_LIST, }) expect(actions.length).toBe(0) }) it('will dispatch no actions if the list is being fetched', async () => { const actions = await generateListResourceActions({ request: errorRequest, initialState: INITIAL_STATE_WITH_LIST_BEING_FETCHED, }) expect(actions.length).toBe(0) }) it('will have a update selectedResourceList action', async () => { const [inititalAction] = await generateListResourceActions({ request: errorRequest, initialState: INITIAL_STATE_WITH_CACHED_LIST, }) expect(inititalAction).toMatchSnapshot() }) it('will have an initial action', async () => { const [inititalAction] = await generateListResourceActions({ request }) expect(inititalAction).toMatchSnapshot() }) it('will have a success action', async () => { const [_, successAction] = await generateListResourceActions({ request }) expect(successAction).toMatchSnapshot() }) it('will have a error action', async () => { const [_, errorAction] = await generateListResourceActions({ request: errorRequest }) expect(errorAction).toMatchSnapshot() })
travisbloom/redux-resources
src/actions/listResource.spec.js
JavaScript
mit
2,626
import React, {Component} from 'react'; import MiniInfoBar from '../components/MiniInfoBar'; export default class About extends Component { state = { showKitten: false } handleToggleKitten() { this.setState({showKitten: !this.state.showKitten}); } render() { const {showKitten} = this.state; const kitten = require('./kitten.jpg'); return ( <div> <div className="container"> <h1>About Us</h1> <p>This project was orginally created by Erik Rasmussen (<a href="https://twitter.com/erikras" target="_blank">@erikras</a>), but has since seen many contributions from the open source community. Thank you to <a href="https://github.com/erikras/react-redux-universal-hot-example/graphs/contributors" target="_blank">all the contributors</a>. </p> <h3>Mini Bar <span style={{color: '#aaa'}}>(not that kind)</span></h3> <p>Hey! You found the mini info bar! The following component is display-only. Note that it shows the same time as the info bar.</p> <MiniInfoBar/> <h3>Images</h3> <p> Psst! Would you like to see a kitten? <button className={'btn btn-' + (showKitten ? 'danger' : 'success')} style={{marginLeft: 50}} onClick={::this.handleToggleKitten}> {showKitten ? 'No! Take it away!' : 'Yes! Please!'}</button> </p> {showKitten && <div><img src={kitten}/></div>} </div> </div> ); } }
vbdoug/hot-react
src/views/About.js
JavaScript
mit
1,598
define([ "dojo/_base/array", "dojo/_base/connect", "dojo/_base/declare", "dojo/_base/lang", "dojo/_base/window", "dojo/dom", "dojo/dom-class", "dojo/dom-construct", "dojo/dom-style", "dijit/registry", "dijit/_Contained", "dijit/_Container", "dijit/_WidgetBase", "./ProgressIndicator", "./ToolBarButton", "./View", "dojo/has", "dojo/has!dojo-bidi?dojox/mobile/bidi/Heading" ], function(array, connect, declare, lang, win, dom, domClass, domConstruct, domStyle, registry, Contained, Container, WidgetBase, ProgressIndicator, ToolBarButton, View, has, BidiHeading){ // module: // dojox/mobile/Heading var dm = lang.getObject("dojox.mobile", true); var Heading = declare(has("dojo-bidi") ? "dojox.mobile.NonBidiHeading" : "dojox.mobile.Heading", [WidgetBase, Container, Contained],{ // summary: // A widget that represents a navigation bar. // description: // Heading is a widget that represents a navigation bar, which // usually appears at the top of an application. It usually // displays the title of the current view and can contain a // navigational control. If you use it with // dojox/mobile/ScrollableView, it can also be used as a fixed // header bar or a fixed footer bar. In such cases, specify the // fixed="top" attribute to be a fixed header bar or the // fixed="bottom" attribute to be a fixed footer bar. Heading can // have one or more ToolBarButton widgets as its children. // back: String // A label for the navigational control to return to the previous View. back: "", // href: String // A URL to open when the navigational control is pressed. href: "", // moveTo: String // The id of the transition destination of the navigation control. // If the value has a hash sign ('#') before the id (e.g. #view1) // and the dojox/mobile/bookmarkable module is loaded by the user application, // the view transition updates the hash in the browser URL so that the // user can bookmark the destination view. In this case, the user // can also use the browser's back/forward button to navigate // through the views in the browser history. // // If null, transitions to a blank view. // If '#', returns immediately without transition. moveTo: "", // transition: String // A type of animated transition effect. You can choose from the // standard transition types, "slide", "fade", "flip", or from the // extended transition types, "cover", "coverv", "dissolve", // "reveal", "revealv", "scaleIn", "scaleOut", "slidev", // "swirl", "zoomIn", "zoomOut", "cube", and "swap". If "none" is // specified, transition occurs immediately without animation. transition: "slide", // label: String // A title text of the heading. If the label is not specified, the // innerHTML of the node is used as a label. label: "", // iconBase: String // The default icon path for child items. iconBase: "", // tag: String // A name of HTML tag to create as domNode. tag: "h1", // busy: Boolean // If true, a progress indicator spins on this widget. busy: false, // progStyle: String // A css class name to add to the progress indicator. progStyle: "mblProgWhite", /* internal properties */ // baseClass: String // The name of the CSS class of this widget. baseClass: "mblHeading", buildRendering: function(){ if(!this.templateString){ // true if this widget is not templated // Create root node if it wasn't created by _TemplatedMixin this.domNode = this.containerNode = this.srcNodeRef || win.doc.createElement(this.tag); } this.inherited(arguments); if(!this.templateString){ // true if this widget is not templated if(!this.label){ array.forEach(this.domNode.childNodes, function(n){ if(n.nodeType == 3){ var v = lang.trim(n.nodeValue); if(v){ this.label = v; this.labelNode = domConstruct.create("span", {innerHTML:v}, n, "replace"); } } }, this); } if(!this.labelNode){ this.labelNode = domConstruct.create("span", null, this.domNode); } this.labelNode.className = "mblHeadingSpanTitle"; this.labelDivNode = domConstruct.create("div", { className: "mblHeadingDivTitle", innerHTML: this.labelNode.innerHTML }, this.domNode); } dom.setSelectable(this.domNode, false); }, startup: function(){ if(this._started){ return; } var parent = this.getParent && this.getParent(); if(!parent || !parent.resize){ // top level widget var _this = this; setTimeout(function(){ // necessary to render correctly _this.resize(); }, 0); } this.inherited(arguments); }, resize: function(){ if(this.labelNode){ // find the rightmost left button (B), and leftmost right button (C) // +-----------------------------+ // | |A| |B| |C| |D| | // +-----------------------------+ var leftBtn, rightBtn; var children = this.containerNode.childNodes; for(var i = children.length - 1; i >= 0; i--){ var c = children[i]; if(c.nodeType === 1 && domStyle.get(c, "display") !== "none"){ if(!rightBtn && domStyle.get(c, "float") === "right"){ rightBtn = c; } if(!leftBtn && domStyle.get(c, "float") === "left"){ leftBtn = c; } } } if(!this.labelNodeLen && this.label){ this.labelNode.style.display = "inline"; this.labelNodeLen = this.labelNode.offsetWidth; this.labelNode.style.display = ""; } var bw = this.domNode.offsetWidth; // bar width var rw = rightBtn ? bw - rightBtn.offsetLeft + 5 : 0; // rightBtn width var lw = leftBtn ? leftBtn.offsetLeft + leftBtn.offsetWidth + 5 : 0; // leftBtn width var tw = this.labelNodeLen || 0; // title width domClass[bw - Math.max(rw,lw)*2 > tw ? "add" : "remove"](this.domNode, "mblHeadingCenterTitle"); } array.forEach(this.getChildren(), function(child){ if(child.resize){ child.resize(); } }); }, _setBackAttr: function(/*String*/back){ // tags: // private this._set("back", back); if(!this.backButton){ this.backButton = new ToolBarButton({ arrow: "left", label: back, moveTo: this.moveTo, back: !this.moveTo, href: this.href, transition: this.transition, transitionDir: -1 }); this.backButton.placeAt(this.domNode, "first"); }else{ this.backButton.set("label", back); } this.resize(); }, _setMoveToAttr: function(/*String*/moveTo){ // tags: // private this._set("moveTo", moveTo); if(this.backButton){ this.backButton.set("moveTo", moveTo); } }, _setHrefAttr: function(/*String*/href){ // tags: // private this._set("href", href); if(this.backButton){ this.backButton.set("href", href); } }, _setTransitionAttr: function(/*String*/transition){ // tags: // private this._set("transition", transition); if(this.backButton){ this.backButton.set("transition", transition); } }, _setLabelAttr: function(/*String*/label){ // tags: // private this._set("label", label); this.labelNode.innerHTML = this.labelDivNode.innerHTML = this._cv ? this._cv(label) : label; }, _setBusyAttr: function(/*Boolean*/busy){ // tags: // private var prog = this._prog; if(busy){ if(!prog){ prog = this._prog = new ProgressIndicator({size:30, center:false}); domClass.add(prog.domNode, this.progStyle); } domConstruct.place(prog.domNode, this.domNode, "first"); prog.start(); }else if(prog){ prog.stop(); } this._set("busy", busy); } }); return has("dojo-bidi") ? declare("dojox.mobile.Heading", [Heading, BidiHeading]) : Heading; });
aguadev/aguadev
html/dojo-1.8.3/dojox-1.9.0/mobile/Heading.js
JavaScript
mit
7,774
/** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../..' export const input = ( <editor> <block> <mark key="a"> <anchor />o </mark> n <mark key="b"> e<focus /> </mark> </block> </editor> ) export const run = editor => { return Array.from(Editor.activeMarks(editor, { union: true })) } export const output = [{ key: 'a' }, { key: 'b' }]
isubastiCadmus/slate
packages/slate/test/queries/activeMarks/union.js
JavaScript
mit
418
/* * Popular Repositories * Copyright (c) 2014 Alberto Congiu (@4lbertoC) * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; var React = require('react'); /** * Like Array.map(), but on an object's own properties. * Returns an array. * * @param {object} obj The object to call the function on. * @param {function(*, string)} func The function to call on each * of the object's properties. It takes as input parameters the * value and the key of the current property. * @returns {Array} The result. */ function mapObject(obj, func) { var results = []; if (obj) { for(var key in obj) { if (obj.hasOwnProperty(key)) { results.push(func(obj[key], key)); } } } return results; } /** * A component that displays a GitHub repo's languages. * * @prop {GitHubRepoLanguages} gitHubRepoLanguages. */ var LanguageList = React.createClass({ propTypes: { gitHubRepoLanguages: React.PropTypes.object.isRequired }, render() { var gitHubRepoLanguages = this.props.gitHubRepoLanguages; /* jshint ignore:start */ return ( <div className="text-center language-list"> {mapObject(gitHubRepoLanguages, (percentage, languageName) => { return ( <div className="language" key={languageName}> <h3 className="language-name">{languageName}</h3> <h5 className="language-percentage">{percentage}</h5> </div> ); })} </div> ); /* jshint ignore:end */ } }); module.exports = LanguageList;
4lbertoC/popularrepositories
src/components/layout/LanguageList.js
JavaScript
mit
1,648
import assert from 'assert' import {fixCase} from '../../src/lib/words/case' import Locale from '../../src/locale/locale' describe('Corrects accidental uPPERCASE\n', () => { let testCase = { 'Hey, JEnnifer!': 'Hey, Jennifer!', 'CMSko': 'CMSko', 'FPs': 'FPs', 'ČSNka': 'ČSNka', 'BigONE': 'BigONE', // specific brand names 'two Panzer IVs': 'two Panzer IVs', 'How about ABC?': 'How about ABC?', 'cAPSLOCK': 'capslock', '(cAPSLOCK)': '(capslock)', 'iPhone': 'iPhone', 'iT': 'it', 'Central Europe and Cyrillic tests: aĎIÉUБUГ': 'Central Europe and Cyrillic tests: aďiéuбuг', } Object.keys(testCase).forEach((key) => { it('', () => { assert.equal(fixCase(key, new Locale('en-us')), testCase[key]) }) }) })
viktorbezdek/react-htmlcontent
test/words/case.test.js
JavaScript
mit
783
/** * Reparse the Grunt command line options flags. * * Using the arguments parsing logic from Grunt: * https://github.com/gruntjs/grunt/blob/master/lib/grunt/cli.js */ module.exports = function(grunt){ // Get the current Grunt CLI instance. var nopt = require('nopt'), parsedOptions = parseOptions(nopt, grunt.cli.optlist); grunt.log.debug('(nopt-grunt-fix) old flags: ', grunt.option.flags()); // Reassign the options. resetOptions(grunt, parsedOptions); grunt.log.debug('(nopt-grunt-fix) new flags: ', grunt.option.flags()); return grunt; }; // Normalise the parameters and then parse them. function parseOptions(nopt, optlist){ var params = getParams(optlist); var parsedOptions = nopt(params.known, params.aliases, process.argv, 2); initArrays(optlist, parsedOptions); return parsedOptions; } // Reassign the options on the Grunt instance. function resetOptions(grunt, parsedOptions){ for (var i in parsedOptions){ if (parsedOptions.hasOwnProperty(i) && i != 'argv'){ grunt.option(i, parsedOptions[i]); } } } // Parse `optlist` into a form that nopt can handle. function getParams(optlist){ var aliases = {}; var known = {}; Object.keys(optlist).forEach(function(key) { var short = optlist[key].short; if (short) { aliases[short] = '--' + key; } known[key] = optlist[key].type; }); return { known: known, aliases: aliases } } // Initialize any Array options that weren't initialized. function initArrays(optlist, parsedOptions){ Object.keys(optlist).forEach(function(key) { if (optlist[key].type === Array && !(key in parsedOptions)) { parsedOptions[key] = []; } }); }
widgetworks/nopt-grunt-fix
index.js
JavaScript
mit
1,652
module.exports = { "name": "ATmega16HVB", "timeout": 200, "stabDelay": 100, "cmdexeDelay": 25, "syncLoops": 32, "byteDelay": 0, "pollIndex": 3, "pollValue": 83, "preDelay": 1, "postDelay": 1, "pgmEnable": [172, 83, 0, 0], "erase": { "cmd": [172, 128, 0, 0], "delay": 45, "pollMethod": 1 }, "flash": { "write": [64, 76, 0], "read": [32, 0, 0], "mode": 65, "blockSize": 128, "delay": 10, "poll2": 0, "poll1": 0, "size": 16384, "pageSize": 128, "pages": 128, "addressOffset": null }, "eeprom": { "write": [193, 194, 0], "read": [160, 0, 0], "mode": 65, "blockSize": 4, "delay": 10, "poll2": 0, "poll1": 0, "size": 512, "pageSize": 4, "pages": 128, "addressOffset": 0 }, "sig": [30, 148, 13], "signature": { "size": 3, "startAddress": 0, "read": [48, 0, 0, 0] }, "fuses": { "startAddress": 0, "write": { "low": [172, 160, 0, 0], "high": [172, 168, 0, 0] }, "read": { "low": [80, 0, 0, 0], "high": [88, 8, 0, 0] } } }
noopkat/avrgirl-chips-json
atmega/atmega16hvb.js
JavaScript
mit
1,112
const express = require('express'); const app = express(); const path = require('path'); const userCtrl = require('./userCtrl.js'); //extra middleware const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended: true}), bodyParser.json()); app.use(express.static(path.join(__dirname, '../../node_modules/'))); app.use(express.static(path.join(__dirname, '../client/'))); app.post('/requestDB', userCtrl.sendTableList); app.post('/requestTable', userCtrl.sendTable); app.post('/createTable', userCtrl.createTable); app.post('/insert', userCtrl.insertEntry); app.post('/update', userCtrl.updateEntry); app.post('/delete', userCtrl.deleteEntry); app.post('/query', userCtrl.rawQuery); app.post('/dropTable', userCtrl.dropTable); app.listen(3000, ()=> console.log('listening on port 3000'));
dbviews/dbview
src/server/server.js
JavaScript
mit
814
exports.find = function(options) { options || (options = {}); options.param || (options.param = 'query'); options.parse || (options.parse = JSON.parse); return function(req, res, next) { var query = req.query[options.param]; var conditions = query ? options.parse(query) : {}; req.find = req.model.find(conditions); next(); }; }; exports.limit = function(options) { options || (options = {}); options.param || (options.param = 'limit'); return function(req, res, next) { if (req.query[options.param] !== undefined) { var limit = parseInt(req.query[options.param], 10); if (options.max) { limit = Math.min(limit, options.max); } req.find = req.find.limit(limit); } next(); }; }; exports.skip = function(options) { options || (options = {}); options.param || (options.param = 'skip'); return function(req, res, next) { if (req.query[options.param] !== undefined) { var skip = parseInt(req.query[options.param], 10); req.find = req.find.skip(skip); } next(); }; }; exports.select = function(options) { options || (options = {}); options.param || (options.param = 'select'); options.delimiter || (options.delimiter = ','); return function(req, res, next) { if (req.query[options.param] !== undefined) { var select = req.query[options.param].split(options.delimiter).join(' '); req.find = req.find.select(select); } next(); }; }; exports.sort = function(options) { options || (options = {}); options.param || (options.param = 'sort'); options.delimiter || (options.delimiter = ','); return function(req, res, next) { if (req.query[options.param] !== undefined) { var sort = req.query[options.param].split(options.delimiter).join(' '); req.find = req.find.sort(sort); } next(); }; }; exports.exec = function() { return function(req, res, next) { req.find.exec(function(err, results) { if (err) return next(err); req.results = results; next(); }); }; }; exports.count = function(options) { options || (options = {}); options.param || (options.param = 'query'); options.parse || (options.parse = JSON.parse); return function(req, res, next) { var query = req.query[options.param]; var conditions = query ? options.parse(query) : {}; req.model.count(conditions, function(err, count) { if (err) return next(err); req.count = count; next(); }); }; };
scttnlsn/emt
lib/query.js
JavaScript
mit
2,776
// MooTools: the javascript framework. // Load this file's selection again by visiting: http://mootools.net/more/f0c28d76aff2f0ba12270c81dc5e8d18 // Or build this file again with packager using: packager build More/Assets More/Hash.Cookie /* --- script: More.js name: More description: MooTools More license: MIT-style license authors: - Guillermo Rauch - Thomas Aylott - Scott Kyle - Arian Stolwijk - Tim Wienk - Christoph Pojer - Aaron Newton - Jacob Thornton requires: - Core/MooTools provides: [MooTools.More] ... */ MooTools.More = { 'version': '1.4.0.1', 'build': 'a4244edf2aa97ac8a196fc96082dd35af1abab87' }; /* --- script: Assets.js name: Assets description: Provides methods to dynamically load JavaScript, CSS, and Image files into the document. license: MIT-style license authors: - Valerio Proietti requires: - Core/Element.Event - /MooTools.More provides: [Assets] ... */ var Asset = { javascript: function(source, properties){ if (!properties) properties = {}; var script = new Element('script', {src: source, type: 'text/javascript'}), doc = properties.document || document, load = properties.onload || properties.onLoad; delete properties.onload; delete properties.onLoad; delete properties.document; if (load){ if (typeof script.onreadystatechange != 'undefined'){ script.addEvent('readystatechange', function(){ if (['loaded', 'complete'].contains(this.readyState)) load.call(this); }); } else { script.addEvent('load', load); } } return script.set(properties).inject(doc.head); }, css: function(source, properties){ if (!properties) properties = {}; var link = new Element('link', { rel: 'stylesheet', media: 'screen', type: 'text/css', href: source }); var load = properties.onload || properties.onLoad, doc = properties.document || document; delete properties.onload; delete properties.onLoad; delete properties.document; if (load) link.addEvent('load', load); return link.set(properties).inject(doc.head); }, image: function(source, properties){ if (!properties) properties = {}; var image = new Image(), element = document.id(image) || new Element('img'); ['load', 'abort', 'error'].each(function(name){ var type = 'on' + name, cap = 'on' + name.capitalize(), event = properties[type] || properties[cap] || function(){}; delete properties[cap]; delete properties[type]; image[type] = function(){ if (!image) return; if (!element.parentNode){ element.width = image.width; element.height = image.height; } image = image.onload = image.onabort = image.onerror = null; event.delay(1, element, element); element.fireEvent(name, element, 1); }; }); image.src = element.src = source; if (image && image.complete) image.onload.delay(1); return element.set(properties); }, images: function(sources, options){ sources = Array.from(sources); var fn = function(){}, counter = 0; options = Object.merge({ onComplete: fn, onProgress: fn, onError: fn, properties: {} }, options); return new Elements(sources.map(function(source, index){ return Asset.image(source, Object.append(options.properties, { onload: function(){ counter++; options.onProgress.call(this, counter, index, source); if (counter == sources.length) options.onComplete(); }, onerror: function(){ counter++; options.onError.call(this, counter, index, source); if (counter == sources.length) options.onComplete(); } })); })); } }; /* --- name: Hash description: Contains Hash Prototypes. Provides a means for overcoming the JavaScript practical impossibility of extending native Objects. license: MIT-style license. requires: - Core/Object - /MooTools.More provides: [Hash] ... */ (function(){ if (this.Hash) return; var Hash = this.Hash = new Type('Hash', function(object){ if (typeOf(object) == 'hash') object = Object.clone(object.getClean()); for (var key in object) this[key] = object[key]; return this; }); this.$H = function(object){ return new Hash(object); }; Hash.implement({ forEach: function(fn, bind){ Object.forEach(this, fn, bind); }, getClean: function(){ var clean = {}; for (var key in this){ if (this.hasOwnProperty(key)) clean[key] = this[key]; } return clean; }, getLength: function(){ var length = 0; for (var key in this){ if (this.hasOwnProperty(key)) length++; } return length; } }); Hash.alias('each', 'forEach'); Hash.implement({ has: Object.prototype.hasOwnProperty, keyOf: function(value){ return Object.keyOf(this, value); }, hasValue: function(value){ return Object.contains(this, value); }, extend: function(properties){ Hash.each(properties || {}, function(value, key){ Hash.set(this, key, value); }, this); return this; }, combine: function(properties){ Hash.each(properties || {}, function(value, key){ Hash.include(this, key, value); }, this); return this; }, erase: function(key){ if (this.hasOwnProperty(key)) delete this[key]; return this; }, get: function(key){ return (this.hasOwnProperty(key)) ? this[key] : null; }, set: function(key, value){ if (!this[key] || this.hasOwnProperty(key)) this[key] = value; return this; }, empty: function(){ Hash.each(this, function(value, key){ delete this[key]; }, this); return this; }, include: function(key, value){ if (this[key] == undefined) this[key] = value; return this; }, map: function(fn, bind){ return new Hash(Object.map(this, fn, bind)); }, filter: function(fn, bind){ return new Hash(Object.filter(this, fn, bind)); }, every: function(fn, bind){ return Object.every(this, fn, bind); }, some: function(fn, bind){ return Object.some(this, fn, bind); }, getKeys: function(){ return Object.keys(this); }, getValues: function(){ return Object.values(this); }, toQueryString: function(base){ return Object.toQueryString(this, base); } }); Hash.alias({indexOf: 'keyOf', contains: 'hasValue'}); })(); /* --- script: Hash.Cookie.js name: Hash.Cookie description: Class for creating, reading, and deleting Cookies in JSON format. license: MIT-style license authors: - Valerio Proietti - Aaron Newton requires: - Core/Cookie - Core/JSON - /MooTools.More - /Hash provides: [Hash.Cookie] ... */ Hash.Cookie = new Class({ Extends: Cookie, options: { autoSave: true }, initialize: function(name, options){ this.parent(name, options); this.load(); }, save: function(){ var value = JSON.encode(this.hash); if (!value || value.length > 4096) return false; //cookie would be truncated! if (value == '{}') this.dispose(); else this.write(value); return true; }, load: function(){ this.hash = new Hash(JSON.decode(this.read(), true)); return this; } }); Hash.each(Hash.prototype, function(method, name){ if (typeof method == 'function') Hash.Cookie.implement(name, function(){ var value = method.apply(this.hash, arguments); if (this.options.autoSave) this.save(); return value; }); });
donatj/CorpusPHP
Source/js/mootools.more.js
JavaScript
mit
7,181
'use strict'; module.exports = require('./toPairsIn'); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2VudHJpZXNJbi5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLE9BQU8sT0FBUCxHQUFpQixRQUFRLGFBQVIsQ0FBakIiLCJmaWxlIjoiZW50cmllc0luLmpzIiwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHMgPSByZXF1aXJlKCcuL3RvUGFpcnNJbicpO1xuIl19
justin-lai/hackd.in
compiled/client/lib/lodash/entriesIn.js
JavaScript
mit
394
var chalk = require('chalk'); var safeStringify = require('fast-safe-stringify') function handleErrorObject(key, value) { if (value instanceof Error) { return Object.getOwnPropertyNames(value).reduce(function(error, key) { error[key] = value[key] return error }, {}) } return value } function stringify(o) { return safeStringify(o, handleErrorObject, ' '); } function debug() { if (!process.env.WINSTON_CLOUDWATCH_DEBUG) return; var args = [].slice.call(arguments); var lastParam = args.pop(); var color = chalk.red; if (lastParam !== true) { args.push(lastParam); color = chalk.green; } args[0] = color(args[0]); args.unshift(chalk.blue('DEBUG:')); console.log.apply(console, args); } module.exports = { stringify: stringify, debug: debug };
lazywithclass/winston-cloudwatch
lib/utils.js
JavaScript
mit
806
"use strict" const createTileGridConverter = require(`./createTileGridConverter`) const colorDepth = require(`./colorDepth`) module.exports = ({palette, images}) => { const converter = createTileGridConverter({ tileWidth: 7, tileHeight: 9, columns: 19, tileCount: 95, raw32bitData: colorDepth.convert8to32({palette, raw8bitData: images}), }) return { convertToPng: converter.convertToPng } }
chuckrector/mappo
src/converter/createVerge1SmallFntConverter.js
JavaScript
mit
426
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ $(document).ready(function(){ var oldAction = $('#comment-form').attr("action"); hljs.initHighlightingOnLoad(); $('#coolness div').hover(function(){ $('#coolness .second').fadeOut(500); }, function(){ $('#coolness .second').fadeIn(1000).stop(false, true); }); $(".reply a").click(function() { var add = this.className; var action = oldAction + '/' + add; $("#comment-form").attr("action", action); console.log($('#comment-form').attr("action")); }); });
mzj/yabb
src/MZJ/YabBundle/Resources/public/js/bootstrap.js
JavaScript
mit
683
(function(Object) { Object.Model.Background = Object.Model.PresentationObject.extend({ "initialize" : function() { Object.Model.PresentationObject.prototype.initialize.call(this); } },{ "type" : "Background", "attributes" : _.defaults({ "skybox" : { "type" : "res-texture", "name" : "skybox", "_default" : "" }, "name" : { "type" : "string", "_default" : "new Background", "name" : "name" } }, Object.Model.PresentationObject.attributes) }); }(sp.module("object")));
larsrohwedder/scenepoint
client_src/modules/object/model/Background.js
JavaScript
mit
532
import './Modal.scss' import pugTpl from './Modal.pug' import mixin from '../../mixin' import alert from '@vue2do/component/module/Modal/alert' import confirm from '@vue2do/component/module/Modal/confirm' export default { name: 'PageCompModal', template: pugTpl(), mixins: [mixin], data() { return { testName: 'test' } }, methods: { simple() { this.$refs.simple.show() }, alert() { alert({ message: '这是一个警告弹窗', theme: this.typeTheme, ui: this.typeUI }) }, confirm() { confirm({ message: '这是一个确认弹窗', title: '测试确认弹出', theme: 'danger', ui: 'bootstrap' }) }, showFullPop() { this.$refs.fullPop.show() }, hideFullPop() { this.$refs.fullPop.hide() }, showPureModal() { this.$refs.pureModal.show() }, hidePureModal() { this.$refs.pureModal.hide() } } }
zen0822/vue2do
app/doc/client/component/page/Component/message/Modal/Modal.js
JavaScript
mit
995
var a;function SongView(){ListView.call(this);this.name="SongView";this.allDataLoaded=this.songsLoaded=false;this.sortVariable="bezeichnung"}Temp.prototype=ListView.prototype;SongView.prototype=new Temp;songView=new SongView;a=SongView.prototype; a.getData=function(d){if(d){var c=[];allSongs!=null&&$.each(churchcore_sortData(allSongs,"bezeichnung"),function(b,e){$.each(e.arrangement,function(f,g){f=[];f.song_id=e.id;f.arrangement_id=g.id;f.id=e.id+"_"+g.id;c.push(f)})})}else{c={};allSongs!=null&&$.each(allSongs,function(b,e){$.each(e.arrangement,function(f,g){f=[];f.song_id=e.id;f.arrangement_id=g.id;f.id=e.id+"_"+g.id;c[f.id]=f})})}return c}; a.renderFilter=function(){if(masterData.settings.filterSongcategory==""||masterData.settings.filterSongcategory==null)delete masterData.settings.filterSongcategory;else this.filter.filterSongcategory=masterData.settings.filterSongcategory;var d=[],c=new CC_Form;c.setHelp("ChurchService-Filter");c.addHtml('<div id="filterKategorien"></div>');c.addSelect({data:this.sortMasterData(masterData.songcategory),label:"Song-Kategorien",selected:this.filter.filterSongcategory,freeoption:true,cssid:"filterSongcategory", type:"medium",func:function(b){return masterData.auth.viewsongcategory!=null&&masterData.auth.viewsongcategory[b.id]}});c.addCheckbox({cssid:"searchStandard",label:"Nur Standard-Arrangement"});d.push(c.render(true));d.push('<div id="cdb_filtercover"></div>');$("#cdb_filter").html(d.join(""));$.each(this.filter,function(b,e){$("#"+b).val(e)});filter=this.filter;this.implantStandardFilterCallbacks(this,"cdb_filter");this.renderCalendar()}; a.groupingFunction=function(d){if(this.filter.searchStandard==null){var c="";c=c+"<b>"+allSongs[d.song_id].bezeichnung+"</b>";if(allSongs[d.song_id].author!="")c=c+"&nbsp; <small>"+allSongs[d.song_id].author+"</small>";return c=c+'&nbsp; <a href="#" class="edit-song" data-id="'+d.song_id+'">'+form_renderImage({src:"options.png",width:16})+"</a>"}else return null}; a.checkFilter=function(d){if(d==null)return false;var c=allSongs[d.song_id],b=c.arrangement[d.arrangement_id];if(songView.filter!=null){var e=songView.filter;if(e.searchEntry!=null&&c.bezeichnung.toLowerCase().indexOf(e.searchEntry.toLowerCase())==-1&&e.searchEntry!=d.arrangement_id)return false;if(e.filterSongcategory!=null&&c.songcategory_id!=e.filterSongcategory)return false;if(!churchcore_inArray(c.songcategory_id,masterData.auth.viewsongcategory))return false;if(e.searchStandard&&b.default_yn== 0)return false}return true};a.renderTooltip=function(d,c){var b=d.parents("div.entrydetail").attr("data-song-id"),e=d.parent().attr("data-id"),f=d.attr("tooltip");return this.renderTooltipForFiles(d,c,allSongs[b].arrangement[e].files[f],masterData.auth.editsong)};a.tooltipCallback=function(d,c){var b=c.parents("div.entrydetail").attr("data-song-id"),e=c.parent().attr("data-id");return this.tooltipCallbackForFiles(d,c,allSongs[b].arrangement,e)}; a.renderFiles=function(d,c){var b=this;b.clearTooltip(true);masterData.auth.editsong?b.renderFilelist("",d,c,function(e){delete d[c].files[e];b.renderFiles(d,c)}):b.renderFilelist("",d,c);$("div.filelist[data-id="+c+"] span[tooltip],a[tooltip]").hover(function(){drin=true;this_object.prepareTooltip($(this),null,$(this).attr("data-tooltiptype"))},function(){drin=false;window.setTimeout(function(){drin||this_object.clearTooltip()},100)})}; a.renderEntryDetail=function(d){var c=this,b=d.indexOf("_"),e=allSongs[d.substr(0,b)],f=e.arrangement[d.substr(b+1,99)];b=[];b.push('<div class="entrydetail" id="entrydetail_'+d+'" data-song-id="'+e.id+'" data-arrangement-id="'+f.id+'">');b.push('<div class="well">');b.push('<b style="font-size:140%">'+e.bezeichnung+" - "+f.bezeichnung+"</b>");e.autor!=""&&b.push("<br/><small>Autor: "+e.author+"</small>");e.copyright!=""&&b.push("<br/><small>Copyright: "+e.copyright+"</small>");e.ccli!=""&&b.push("<br/><small>CCLI: "+ e.ccli+"</small>");b.push("</div>");b.push('<div class="row-fluid">');b.push('<div class="span6">');b.push("<legend>Informationen &nbsp; ");masterData.auth.editsong&&b.push('<a href="#" class="edit">'+c.renderImage("options",20)+"</a>");b.push("</legend>");b.push("<p>Tonart: "+f.tonality);b.push("&nbsp; BPM: "+f.bpm);b.push("&nbsp; Takt: "+f.beat);b.push("<p>L&auml;nge: "+f.length_min+":"+f.length_sec);b.push("<p>Bemerkung:<br/><p><small> "+f.note.replace(/\n/g,"<br/>")+"</small>");b.push("</div>"); b.push('<div class="span6">');b.push("<legend>Dateien</legend>");b.push('<div class="we_ll">');b.push('<div class="filelist" data-id="'+f.id+'"></div>');masterData.auth.editsong&&b.push('<p><div id="upload_button_'+f.id+'">Nochmal bitte...</div>');b.push("</div>");b.push("</div>");b.push("</div>");if(masterData.auth.editsong){b.push("<hr/><p>");b.push(form_renderButton({label:"Weiteres Arrangement hinzuf&uuml;gen",htmlclass:"add",type:"small"})+"&nbsp; ");if(f.default_yn==0){b.push(form_renderButton({label:"Zum Standard machen", htmlclass:"makestandard",type:"small"})+"&nbsp; ");b.push(form_renderButton({label:"Arrangement entfernen",htmlclass:"delete",type:"small"})+"&nbsp; ")}}b.push("</div>");$("tr[id="+d+"]").after('<tr id="detail'+d+'"><td colspan="7" id="detailTD'+d+'">'+b.join("")+"</td></tr>");c.renderFiles(allSongs[e.id].arrangement,f.id);masterData.auth.editsong&&new qq.FileUploader({element:document.getElementById("upload_button_"+f.id),action:"?q=churchservice/uploadfile",params:{domain_type:"song_arrangement", domain_id:f.id},multiple:true,debug:true,onSubmit:function(){},onComplete:function(g,i,h){if(h.success){if(f.files==null)f.files={};f.files[h.id]={bezeichnung:h.bezeichnung,filename:h.filename,id:h.id,domain_type:"song_arrangement",domain_id:f.id};c.renderFiles(allSongs[e.id].arrangement,f.id)}else alert("Sorry, Fehler beim Hochladen aufgetreten! Datei zu gross oder Dateiname schon vergeben?")}});$("td[id=detailTD"+d+"] a.edit").click(function(){c.editArrangement(e.id,f.id);return false});$("td[id=detailTD"+ d+"] input.add").click(function(){c.addArrangement(e.id);return false});$("td[id=detailTD"+d+"] input.delete").click(function(){c.deleteArrangement(e.id,f.id);return false});$("td[id=detailTD"+d+"] input.makestandard").click(function(){c.makeAsStandardArrangement(e.id,f.id);return false})};a.loadSongData=function(){if(!this.songsLoaded&&this.allDataLoaded){var d=this.showDialog("Lade Songs","Lade Songs...",300,300);cs_loadSongs(function(){this_object.songsLoaded=true;d.dialog("close");this_object.renderList()})}}; a.renderMenu=function(){this_object=this;menu=new CC_Menu("Men&uuml;");masterData.auth.editsong&&menu.addEntry("Neuen Song anlegen","anewentry","star");menu.renderDiv("cdb_menu",churchcore_handyformat())?$("#cdb_menu a").click(function(){if($(this).attr("id")=="anewentry")this_object.renderAddEntry();else $(this).attr("id")=="ahelp"&&churchcore_openNewWindow("http://intern.churchtools.de/?q=help&doc=ChurchService");return false}):$("#cdb_menu").hide()}; a.editSong=function(d){var c=this,b=new CC_Form("Infos des Songs",allSongs[d]);b.addInput({label:"Bezeichnung",cssid:"bezeichnung",required:true,disabled:!masterData.auth.editsong});b.addSelect({label:"Song-Kategorie",cssid:"songcategory_id",data:masterData.songcategory,disabled:!masterData.auth.editsong});b.addInput({label:"Autor",cssid:"author",disabled:!masterData.auth.editsong});b.addInput({label:"Copyright",cssid:"copyright",disabled:!masterData.auth.editsong});b.addInput({label:"CCLI-Nummer", cssid:"ccli",disabled:!masterData.auth.editsong});var e=form_showDialog("Song editieren",b.render(false,"horizontal"),500,500);masterData.auth.editsong&&e.dialog("addbutton","Speichern",function(){obj=b.getAllValsAsObject();if(obj!=null){obj.func="editSong";obj.id=d;churchInterface.jsendWrite(obj,function(){c.songsLoaded=false;c.loadSongData()});$(this).dialog("close")}});e.dialog("addbutton","Abbrechen",function(){$(this).dialog("close")})}; a.renderAddEntry=function(){var d=this,c=new CC_Form("Bitte Infos des neuen Songs angeben");c.addInput({label:"Bezeichnung",cssid:"bezeichnung",required:true});c.addSelect({label:"Song-Kategorie",cssid:"songcategory_id",required:true,data:masterData.songcategory,selected:masterData.settings.filterSongcategory});c.addInput({label:"Autor",cssid:"author"});c.addInput({label:"Copyright",cssid:"copyright"});c.addInput({label:"CCLI-Nummer",cssid:"ccli"});c.addInput({label:"Tonart",type:"small",cssid:"tonality"}); c.addInput({label:"BPM",type:"small",cssid:"bpm"});c.addInput({label:"Takt",type:"small",cssid:"beat"});form_showDialog("Neuen Song anlegen",c.render(false,"horizontal"),500,500,{Erstellen:function(){var b=c.getAllValsAsObject();if(b!=null){b.func="addNewSong";churchInterface.jsendWrite(b,function(){d.songsLoaded=false;d.filter.searchEntry=b.bezeichnung;if(d.filter.filterSongcategory!=b.songcategory_id){delete d.filter.filterSongcategory;delete masterData.settings.filterSongcategory}d.renderFilter(); d.loadSongData()});$(this).dialog("close")}},Abbrechen:function(){$(this).dialog("close")}})};function processFieldInput(d,c){var b=d.parents("td").attr("data-oldval");d.parents("td").removeAttr("data-oldval");if(c){newval=d.val();d.parents("td").html(newval)}else d.parents("td").html(b)}a=SongView.prototype;a.addFurtherListCallbacks=function(){var d=this;$("#cdb_content a.edit-song").click(function(){d.editSong($(this).attr("data-id"));return false})}; a.editArrangement=function(d,c){var b=this,e=new CC_Form("Bitte Arrangement anpassen",allSongs[d].arrangement[c]);e.addInput({label:"Bezeichnung",cssid:"bezeichnung",required:true});e.addInput({label:"Tonart",cssid:"tonality"});e.addInput({label:"BPM",cssid:"bpm"});e.addInput({label:"Takt",cssid:"beat"});e.addInput({label:"L&auml;nge Minuten:Sekunden",type:"mini",cssid:"length_min",controlgroup_start:true});e.addHtml(" : ");e.addInput({controlgroup_end:true,type:"mini",cssid:"length_sec"});e.addTextarea({label:"Bemerkungen", rows:3,cssid:"note"});form_showDialog("Arrangement editieren",e.render(false,"horizontal"),500,500,{Absenden:function(){obj=e.getAllValsAsObject();if(obj!=null){obj.func="editArrangement";obj.id=c;churchInterface.jsendWrite(obj,function(){b.songsLoaded=false;b.loadSongData()});$(this).dialog("close")}},Abbrechen:function(){$(this).dialog("close")}})}; a.deleteArrangement=function(d,c){var b=this,e=allSongs[d].arrangement[c];if(e.files!=null){alert("Bitte zuerst die Dateien entfernen!");return null}if(confirm("Wirklich Arrangement "+e.bezeichnung+" entfernen?")){e={};e.func="delArrangement";e.song_id=d;e.id=c;churchInterface.jsendWrite(e,function(){b.songsLoaded=false;b.loadSongData()})}}; a.makeAsStandardArrangement=function(d,c){var b=this,e={};e.func="makeAsStandardArrangement";e.id=c;e.song_id=d;churchInterface.jsendWrite(e,function(){b.songsLoaded=false;b.loadSongData()})};a.addArrangement=function(d){var c=this,b={};b.func="addArrangement";b.song_id=d;b.bezeichnung="Neues Arrangement";churchInterface.jsendWrite(b,function(e,f){c.songsLoaded=false;c.open=true;c.filter.searchEntry=f;c.renderFilter();c.loadSongData()})};a.getCountCols=function(){return 6}; a.getListHeader=function(){this.loadSongData();var d=[];songView.listViewTableHeight=masterData.settings.listViewTableHeight==0?null:665;this.filter.searchStandard!=null&&d.push("<th>Nr.");d.push("<th>Bezeichnung<th>Tonart<th>BPM<th>Takt<th>Tags");return d.join("")}; a.renderListEntry=function(d){var c=[],b=allSongs[d.song_id],e=b.arrangement[d.arrangement_id];if(this.filter.searchStandard==null){c.push('<td><a href="#" id="detail'+d.id+'">'+e.bezeichnung+"</a>");e.default_yn==1&&c.push(" *")}else{c.push('<td><a href="#" id="detail'+d.id+'">'+b.bezeichnung+"</a>");masterData.auth.editsong!=null&&c.push('&nbsp; <a href="#" class="edit-song" data-id="'+d.song_id+'">'+form_renderImage({src:"options.png",width:16})+"</a>")}c.push("<td>"+e.tonality);c.push("<td>"+ e.bpm);c.push("<td>"+e.beat);c.push("<td>");return c.join("")};a.messageReceiver=function(d,c){if(d=="allDataLoaded"){this.allDataLoaded=true;this==churchInterface.getCurrentView()&&this.loadSongData()}this==churchInterface.getCurrentView()&&d=="allDataLoaded"&&this.renderList();if(d=="filterChanged")if(c[0]=="filterSongcategory"){masterData.settings.filterSongcategory=$("#filterSongcategory").val();churchInterface.jsonWrite({func:"saveSetting",sub:"filterSongcategory",val:masterData.settings.filterSongcategory})}}; a.addSecondMenu=function(){return""};
isbm/churchtools
system/churchservice/cs_songview.js
JavaScript
mit
12,398
"use strict"; var i = 180; //3分固定 function count(){ if(i <= 0){ document.getElementById("output").innerHTML = "完成!"; }else{ document.getElementById("output").innerHTML = i + "s"; } i -= 1; } window.onload = function(){ setInterval("count()", 1000); };
Shin-nosukeSaito/elctron_app
ramen.js
JavaScript
mit
280
define(['omega/entity', 'omega/core'], function (e, o) { 'use strict'; var triggerKey = function (action, e) { o.trigger(action, { keyCode: e.keyCode, shiftKey: e.shiftKey, ctrlKey: e.ctrlKey, altKey: e.altKey }); }; window.onkeydown = function (e) { triggerKey('KeyDown', e); }; window.onkeyup = function (e) { triggerKey('KeyUp', e); }; // --- return e.extend({ keyboard: {keys: {}}, init: function () { o.bind('KeyDown', function (e) { this.keyboard.keys[e.keyCode] = true; this.trigger('KeyDown', e); }, this); o.bind('KeyUp', function (e) { this.keyboard.keys[e.keyCode] = false; this.trigger('KeyUp', e); }, this); }, isKeyDown: function (keyCode) { return (this.keyboard.keys[keyCode]); } }); });
alecsammon/OmegaJS
omega/behaviour/keyboard.js
JavaScript
mit
897
$(window).on('load', function() {//main const dom = {//define inputs tswitch: $("#wave-switch input"), aSlider: $("input#angle"),//angle slider nSlider: $("input#refractive-index-ratio"), }; let layout = {//define layout of pot showlegend: false, scene: { aspectmode: "cube", xaxis: {range: [-2, 2]}, yaxis: {range: [-2, 2]}, zaxis: {range: [-2, 2]}, camera: { eye: {x: 0, y: 0, z: -2}//adjust camera starting view } }, }; //define constants let size = 100; let t = 0; let isPlay = false; let E_0 = 0.5; let w_r = 2e9; let c = 3e8; // Speed of light let n1 = 1; let k_1 = (n1*w_r)/c; let k_2,theta_i,theta_t; let x_data = numeric.linspace(2, 0, size);//x and y data is always the same and just change z let x_data_t = math.add(-2,x_data); let y_data = numeric.linspace(-2, 2, size); //constants based of of inputs let condition = $("input[name = wave-switch]:checked").val(); let angle_of_incidence = parseFloat($("input#angle").val()); let n2 = parseFloat($("input#refractive-index-ratio").val()); function snell(theta_i){//snells law console.log(Math.sin(theta_i)); console.log((n1 / n2)) return Math.asin((n1 / n2) * Math.sin(theta_i)); }; function getData_wave_incident(){//produces data for the incident wave on the boundry let z,z_square = []; let k_x = Math.cos(theta_i)*k_1; let k_y = Math.sin(theta_i)*k_1; for (let v=0;v < y_data.length ;v++) { let z_row = []; for (let i = 0; i < x_data.length ; i++) { z = E_0* Math.sin(k_x* x_data[i]+k_y*y_data[v]+w_r*t); z_row.push(z); } z_square.push(z_row); } return z_square } function getData_wave_reflected(){//produces data for the reflected wave on the boundry let z,z_square = []; let k_x = Math.cos(-theta_i)*k_1; let k_y = Math.sin(-theta_i)*k_1; let E_0_r = reflect(); for (let v=0;v < y_data.length ;v++) { let z_row = []; for (let i = 0; i < x_data.length ; i++) { z = E_0_r* Math.sin(k_x* x_data[i]+k_y*y_data[v]-w_r*t); z_row.push(z); } z_square.push(z_row); } return z_square } function getData_wave_transmitted(){//produces data for the incident wave on the boundry let z,z_square = []; let E_0_t = transmit(); let k_y = Math.sin(theta_i)*k_1; let k_x = Math.cos(theta_t)*k_2; for (let v=0;v < y_data.length ;v++) { let z_row = []; for (let i = 0; i < x_data_t.length ; i++) { z = E_0_t*Math.sin(k_x*x_data_t[i]+k_y*y_data[v]+w_r*t); z_row.push(z); } z_square.push(z_row);//Not entirelly sure the physics is correct need to review } return z_square } function transmit(){//gives the new amplitude of the transmitted wave let E_t0; if (isNaN(theta_t) === true){//if snells law return not a number this means total internal refection is occurring hence no transmitted wave(no attenuation accounted for) return 0 } else { E_t0 = E_0 * (2. * n1 * Math.cos(theta_i)) / (n1 * Math.cos(theta_i) + n2 * Math.cos(theta_t)) return E_t0 } }; function reflect() {//gives the amplitude of the refected wave if (n1 === n2) {//if both materials have same refractive index then there is no reflection return 0 } else { let E_r0; if (isNaN(theta_t) === true){ E_r0 = E_0; } else { E_r0 = E_0 * (n1 * Math.cos(theta_i) - n2 * Math.cos(theta_t)) / (n1 * Math.cos(theta_i) + n2 * Math.cos(theta_t)) } return E_r0 } }; function plot_data() {//produces the traces of the plot $("#angle-display").html($("input#angle").val().toString()+"°");//update display $("#refractive-index-ratio-display").html($("input#refractive-index-ratio").val().toString()); condition = $("input[name = wave-switch]:checked").val();//update value of constants angle_of_incidence = parseFloat($("input#angle").val()); n2 = parseFloat($("input#refractive-index-ratio").val()); k_2 = (n2*w_r)/c; theta_i = Math.PI * (angle_of_incidence / 180); theta_t = snell(theta_i); if (isNaN(Math.asin(n2))=== true){//update value of citical angle $("#critical_angle-display").html("No Total Internal Reflection possible"); }else{ $("#critical_angle-display").html(((180*Math.asin(n2))/Math.PI).toFixed(2).toString()+"°"); } let data = []; if (condition === "incident") {//creates trace dependent of the conditions of the system let incident_wave = { opacity: 1, x: x_data, y: y_data, z: getData_wave_incident(), type: 'surface', name: "Incident" }; data.push(incident_wave); } else if(condition === "reflected") { let reflected_wave = { opacity: 1, x: x_data, y: y_data, z: getData_wave_reflected(), type: 'surface', name: "Reflected" }; data.push(reflected_wave); } else{ let incident_plus_reflected_wave = { opacity: 1, x: x_data, y: y_data, z: math.add(getData_wave_incident(),getData_wave_reflected()), type: 'surface', name:"Reflected and Incident combined" }; data.push(incident_plus_reflected_wave); } let transmitted_wave = { opacity: 1, x: x_data_t, y: y_data, z: getData_wave_transmitted(), type: 'surface', name:"Transmitted" }; let opacity_1;//opacity gives qualitative representation of refractive index let opacity_2; if((1 < n2) && (n2 <= 15)){//decide opacity dependant on refractive index opacity_1 = 0; opacity_2 = n2/10 } else if((0.1 <= n2) && (n2< 1)){ opacity_1 = 0.1/n2; opacity_2 = 0; } else{ opacity_1 = 0; opacity_2 = 0; } let material_1 =//dielectric one { opacity: opacity_1, color: '#379F9F', type: "mesh3d", name: "material 1", z: [-2, -2, 2, 2, -2, -2, 2, 2], y: [-2, 2, 2, -2, -2, 2, 2, -2], x: [2, 2, 2, 2, 0, 0, 0, 0], i: [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2], j: [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3], k: [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6], }; let material_2 =//dielectric two { opacity: opacity_2, color: '#379F9F', type: "mesh3d", name: "material 2", z: [-2, -2, 2, 2, -2, -2, 2, 2], y: [-2, 2, 2, -2, -2, 2, 2, -2], x: [0, 0, 0, 0, -2, -2, -2, -2], i: [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2], j: [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3], k: [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6], }; data.push(transmitted_wave,material_1,material_2); if (data.length < 5) {//animate function requires data sets of the same length hence those unused in situation must be filled with empty traces let extensionSize = data.length; for (let i = 0; i < (5 - extensionSize); ++i){ data.push( { type: "scatter3d", mode: "lines", x: [0], y: [0], z: [0] } ); } } return data } function update_graph(){//update animation Plotly.animate("graph", {data: plot_data()},//updated data { fromcurrent: true, transition: {duration: 0,}, frame: {duration: 0, redraw: false,}, mode: "afterall" } ); }; function play_loop(){//handles the play button if(isPlay === true) { t++;//keeps time ticking Plotly.animate("graph", {data: plot_data()}, { fromcurrent: true, transition: {duration: 0,}, frame: {duration: 0, redraw: false,}, mode: "afterall" }); requestAnimationFrame(play_loop);//prepares next frame } return 0; }; function initial() { Plotly.purge("graph"); Plotly.newPlot('graph', plot_data(),layout);//create plot dom.tswitch.on("change", update_graph);//change of input produces reaction dom.aSlider.on("input", update_graph); dom.nSlider.on("input", update_graph); $('#playButton').on('click', function() { document.getElementById("playButton").value = (isPlay) ? "Play" : "Stop";//change button label isPlay = !isPlay; w_t = 0;//reset time to 0 requestAnimationFrame(play_loop); }); }; initial(); });
cydcowley/Imperial-Visualizations
visuals_EM/Waves and Dielectrics/scripts/2D_Dielectric_Dielectric.js
JavaScript
mit
10,284
'use strict'; memoryApp.controller('AuthCtrl', function ($scope, $location, AuthService) { $scope.register = function () { var username = $scope.registerUsername; var password = $scope.registerPassword; if (username && password) { AuthService.register(username, password).then( function () { $location.path('/dashboard'); }, function (error) { $scope.registerError = error; } ); } else { $scope.registerError = 'Username and password required'; } }; $scope.login = function () { var username = $scope.loginUsername; var password = $scope.loginPassword; if (username && password) { AuthService.login(username, password).then( function () { $location.path('/dashboard'); }, function (error) { $scope.loginError = error; } ); } else { $scope.error = 'Username and password required'; } }; });
emilkjer/django-memorycms
backend/static/js/controllers/auth.js
JavaScript
mit
980
var xmas = {}; (function() { xmas.present = { box: {} }; }()); (function(global) { global.xmas.present.box.color = 'Red'; }(this));
watilde/rejs-example
test/fixture1.js
JavaScript
mit
146
/** * A decorator for making sure specific function being invoked serializely. * * Usage: * class A { * @serialize * async foo() {} * } * */ export default function serialize(target, key, descriptor) { let prev = null; function serializeFunc(...args) { const next = () => Promise.resolve(descriptor.value.apply(this, args)).then(() => { prev = null; }); prev = prev ? prev.then(next) : next(); return prev; } return { ...descriptor, value: serializeFunc, }; }
ringcentral/ringcentral-js-widget
packages/ringcentral-integration/lib/serialize.js
JavaScript
mit
524
var functions = {} functions.evaluateSnapshotType = function (name) { var splittedName = name.split('-') var type = splittedName[splittedName.length - 1].split('.')[0] return type === 'motion' ? type : type === 'snapshot' ? 'periodic' : 'unknown' } functions.getSnapshotDate = function (name) { var splittedData = name.split('.')[0].split('-')[0].split('/') return splittedData[splittedData.length - 1] } module.exports = functions
rackdon/securityCam-server
src/utils/commonUtils.js
JavaScript
mit
446
(function() { 'use strict'; angular .module('rtsApp') .directive('hasAuthority', hasAuthority); hasAuthority.$inject = ['Principal']; function hasAuthority(Principal) { var directive = { restrict: 'A', link: linkFunc }; return directive; function linkFunc(scope, element, attrs) { var authority = attrs.hasAuthority.replace(/\s+/g, ''); var setVisible = function () { element.removeClass('hidden'); }, setHidden = function () { element.addClass('hidden'); }, defineVisibility = function (reset) { if (reset) { setVisible(); } Principal.hasAuthority(authority) .then(function (result) { if (result) { setVisible(); } else { setHidden(); } }); }; if (authority.length > 0) { defineVisibility(true); scope.$watch(function() { return Principal.isAuthenticated(); }, function() { defineVisibility(true); }); } } } })();
EnricoSchw/readthisstuff.com
src/main/webapp/app/services/auth/has-authority.directive.js
JavaScript
mit
1,477
var async = require('async'); function captainHook(schema) { // Pre-Save Setup schema.pre('validate', function (next) { var self = this; this._wasNew = this.isNew; if (this.isNew) { this.runPreMethods(schema.preCreateMethods, self, function(){ next(); }); } else { this.runPreMethods(schema.preUpdateMethods, self, function(){ next(); }); } }); // Post-Save Setup schema.post('save', function () { var self = this; if (this._wasNew) { this.runPostMethods(schema.postCreateMethods, self); } else { this.runPostMethods(schema.postUpdateMethods, self); } }); /** * Pre-Hooks * These hooks run before an instance has been created / updated */ schema.methods.runPreMethods = function(methods, self, callback){ async.eachSeries(methods, function(fn, cb) { fn(self, cb); }, function(err){ if (err){ throw err; } callback(); }); }; // Pre-Create Methods schema.preCreateMethods = []; schema.preCreate = function(fn){ schema.preCreateMethods.push(fn); }; // Pre-Update Methods schema.preUpdateMethods = []; schema.preUpdate = function(fn){ schema.preUpdateMethods.push(fn); }; /** * Post-Hooks * These hooks run after an instance has been created / updated */ schema.methods.runPostMethods = function(methods, self){ async.eachSeries(methods, function(fn, cb) { fn(self, cb); }, function(err){ if (err){ throw err; } }); }; // Post-Create Methods schema.postCreateMethods = []; schema.postCreate = function(fn){ schema.postCreateMethods.push(fn); }; // Post-Update Methods schema.postUpdateMethods = []; schema.postUpdate = function(fn){ schema.postUpdateMethods.push(fn); }; } module.exports = captainHook;
hackley/captain-hook
lib/index.js
JavaScript
mit
1,881
import * as React from 'react'; function CubeIcon(props) { return ( <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...props} > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" /> </svg> ); } export default CubeIcon;
dreamyguy/gitinsight
frontend/src/components/primitives/Icon/Cube.js
JavaScript
mit
442
var repl = require('repl'); var server = repl.start({}); var con = server.context; con.name='zfpx'; con.age = 5; con.grow = function(){ return ++con.age; }
liushaohua/node-demo
part01/repl.js
JavaScript
mit
160
export default { queryRouteList: '/routes', queryUserInfo: '/user', logoutUser: '/user/logout', loginUser: 'POST /user/login', queryUser: '/user/:id', queryUserList: '/users', updateUser: 'Patch /user/:id', createUser: 'POST /user', removeUser: 'DELETE /user/:id', removeUserList: 'POST /users/delete', queryPostList: '/posts', queryDashboard: '/dashboard', }
zuiidea/antd-admin
src/services/api.js
JavaScript
mit
388
import Controller from '@ember/controller'; import { debounce } from '@ember/runloop'; import fetch from 'fetch'; import RSVP from 'rsvp'; export default class extends Controller { searchRepo(term) { return new RSVP.Promise((resolve, reject) => { debounce(_performSearch, term, resolve, reject, 600); }); } } function _performSearch(term, resolve, reject) { let url = `https://api.github.com/search/repositories?q=${term}`; fetch(url).then((resp) => resp.json()).then((json) => resolve(json.items), reject); }
cibernox/ember-power-select
tests/dummy/app/templates/snippets/debounce-searches-1-js.js
JavaScript
mit
534
import controller from './controller'; import template from './template.pug'; routes.$inject = ['$stateProvider', '$urlRouterProvider']; export default function routes($stateProvider, $urlRouterProvider){ $stateProvider.state('main.item', { url: '/:id/item', template: template, controllerAs: 'ctrl', controller: controller }) }
bfunc/AngularWebpack
src/main/item/routes.js
JavaScript
mit
346
var config = require('./config') var webpack = require('webpack') var merge = require('webpack-merge') var utils = require('./utils') var baseWebpackConfig = require('./webpack.base.conf') var HtmlWebpackPlugin = require('html-webpack-plugin') var FriendlyErrors = require('friendly-errors-webpack-plugin') // add hot-reload related code to entry chunks Object.keys(baseWebpackConfig.entry).forEach(function (name) { baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) }) module.exports = merge(baseWebpackConfig, { module: { loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) }, // eval-source-map is faster for development devtool: '#eval-source-map', plugins: [ new webpack.DefinePlugin({ 'process.env': config.dev.env }), // https://github.com/glenjamin/webpack-hot-middleware#installation--usage new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: 'example/index.html', template: 'example/index.html', inject: true }), new FriendlyErrors() ] })
sunpeijun/component
build/webpack.dev.conf.js
JavaScript
mit
1,248
var margin = {top: 0, right: 0, bottom: 0, left: 130}, width = 1500 - margin.right - margin.left, height = 470 - margin.top - margin.bottom; var i = 0, duration = 750, root; var tree = d3.layout.tree() .size([height, width]); var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.y, d.x]; }); var svg = d3.select("#treeplot").append("svg") .attr("width", width + margin.right + margin.left) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.json("/pattern_discovery/data?id={{selections.current_dataset}}", function(error, flare) { if (error) throw error; $("#wait").empty(); root = flare; root.x0 = height / 2; root.y0 = 0; function collapse(d) { if (d.children) { d._children = d.children; d._children.forEach(collapse); d.children = null; } } root.children.forEach(collapse); update(root); }); d3.select(self.frameElement).style("height", "800px"); function update(source) { // Compute the new tree layout. var nodes = tree.nodes(root).reverse(), links = tree.links(nodes); // Normalize for fixed-depth. nodes.forEach(function(d) { d.y = d.depth * 300; }); // Update the nodes… var node = svg.selectAll("g.node") .data(nodes, function(d) { return d.id || (d.id = ++i); }); // Enter any new nodes at the parent's previous position. var nodeEnter = node.enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }) .on("click", click); nodeEnter.append("circle") .attr("r", 1e-6) .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); nodeEnter.append("text") .attr("x", function(d) { return d.children || d._children ? -10 : 10; }) .attr("dy", ".35em") .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) .text(function(d) { return d.name; }) .style("fill-opacity", 1e-6); // Transition nodes to their new position. var nodeUpdate = node.transition() .duration(duration) .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }); nodeUpdate.select("circle") .attr("r", 4.5) .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); nodeUpdate.select("text") .style("fill-opacity", 1); // Transition exiting nodes to the parent's new position. var nodeExit = node.exit().transition() .duration(duration) .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; }) .remove(); nodeExit.select("circle") .attr("r", 1e-6); nodeExit.select("text") .style("fill-opacity", 1e-6); // Update the links… var link = svg.selectAll("path.link") .data(links, function(d) { return d.target.id; }); // Enter any new links at the parent's previous position. link.enter().insert("path", "g") .attr("class", "link") .attr("d", function(d) { var o = {x: source.x0, y: source.y0}; return diagonal({source: o, target: o}); }); // Transition links to their new position. link.transition() .duration(duration) .attr("d", diagonal); // Transition exiting nodes to the parent's new position. link.exit().transition() .duration(duration) .attr("d", function(d) { var o = {x: source.x, y: source.y}; return diagonal({source: o, target: o}); }) .remove(); // Stash the old positions for transition. nodes.forEach(function(d) { d.x0 = d.x; d.y0 = d.y; }); } // Toggle children on click. function click(d) { if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } update(d); }
lzlarryli/limelight
app/templates/js/treeplot.js
JavaScript
mit
4,263
import { EventBus } from '../wires/event_bus'; class EventStore { constructor(storeAdapter) { this.adapter = storeAdapter; } appendToStream(streamId, expectedVersion, events) { if (events.length === 0) { return; } events.forEach(function(event) { this.adapter.append(streamId, expectedVersion, event); EventBus.publish('domain.'+streamId+'.'+event.name, event); expectedVersion++; }, this); } loadEventStream(streamId) { var version = 0, events = [], records = this.readEventStream(streamId, 0, null); records.forEach(function(r) { version = r.version; events.push(r.data); }); return new EventStream(streamId, events, version); } readEventStream(streamId, skipEvents, maxCount) { return this.adapter.read(streamId, skipEvents, maxCount); } } class EventStream { constructor(streamId, events, version) { this.streamId = streamId; this.events = events; this.version = version; } } export { EventStore, EventStream };
goldoraf/osef
src/storage/event_store.js
JavaScript
mit
1,162
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm0 15l-5-5h3V9h4v4h3l-5 5z" }), 'AssignmentReturned');
AlloyTeam/Nuclear
components/icon/esm/assignment-returned.js
JavaScript
mit
355
(function () { 'use strict'; angular .module('app.home') .config(appRun); /* @ngInject */ function appRun($stateProvider) { $stateProvider .state('root.home', { url: '/', templateUrl: 'app/home/home.html', controller: 'Home', controllerAs: 'vm', }); } })();
hawkup/github-stars
angularjs/app/home/config.route.js
JavaScript
mit
326
import React from 'react'; import { Text, View, TextInput, } from 'react-native'; import newChallengeStyles from '../../styles/newChallenge/newChallengeStyles'; import mainStyles from '../../styles/main/mainStyles'; import ItemSelectView from './ItemSelectView'; const propTypes = { onChallengeUpdate: React.PropTypes.func, }; const prizeItemStyle = { marginTop: 10, labelFontSize: 22, iconFontSize: 30, iconColor: mainStyles.themeColors.textPrimary, }; class PrizeView extends React.Component { constructor(props) { super(props); this.state = { prize: null, customPrize: '', prizes: [ { label: 'Diner', style: prizeItemStyle }, { label: 'Drinks', style: prizeItemStyle }, { label: 'Gift', style: prizeItemStyle }, { label: 'Define your own', style: prizeItemStyle }, ], }; } setCustomPrize = (customPrize) => { this.setState({ customPrize }); this.props.onChallengeUpdate({ prize: customPrize }); } selectPrize = (prizeLabel) => { const prizes = this.state.prizes; prizes.forEach(prize => { if (prizeLabel === prize.label) { prize.style = { ...prizeItemStyle, iconColor: mainStyles.themeColors.primary }; } else { prize.style = { ...prizeItemStyle, opacity: 0.2 }; } }); this.setState({ prize: prizeLabel, prizes }); this.props.onChallengeUpdate({ prize: prizeLabel }); } render = () => ( <View style={newChallengeStyles.mainContainer}> <View style={newChallengeStyles.contentContainer}> <Text style={newChallengeStyles.titleFont}>Prize (optional)</Text> <View style={newChallengeStyles.itemsContainer} > {this.state.prizes.map(prize => (<ItemSelectView key={prize.label} label={prize.label} style={prize.style} onItemSelect={this.selectPrize} />) )} </View> {this.state.prize === 'Define your own' ? <View style={newChallengeStyles.settingInputContainer} > <TextInput style={newChallengeStyles.inputFont} placeholder="Birthday cake for Paul" placeholderTextColor={mainStyles.themeColors.textPrimary} onChangeText={this.setCustomPrize} value={this.state.customPrize} /> </View> : null} </View> </View> ); } PrizeView.propTypes = propTypes; export default PrizeView;
SamyZ/BoomApp
js/views/newChallenge/PrizeView.js
JavaScript
mit
2,598
import React, {PropTypes} from 'react'; import L from 'leaflet'; import gh from '../api/GitHubApi'; import RaisedButton from 'material-ui/RaisedButton'; const REPO_TIMESPAN = { ALLTIME: 0, THIRTYDAYS: 1, SIXTYDAYS: 2, ONEYEAR: 3 }; const defaultMapConfig = { options: { center: [ 39.7589, -84.1916 ], zoomControl: false, zoom: 4, maxZoom: 20, minZoom: 2, scrollwheel: false, infoControl: false, attributionControl: false }, tileLayer: { uri: 'http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', options: { maxZoom: 18, id: '' } } }; class RepoUserHeatmap extends React.Component { constructor(props, context) { super(props, context); this.state = { timespan: REPO_TIMESPAN.THIRTYDAYS, data: [] }; this.initializeMap = this.initializeMap.bind(this); } componentDidMount() { this.initializeMap(); this.updateData(); gh.getTopRepos().then(data => { console.log('=== REPOS ==='); console.log(data); return gh.getContributors(data.data[0].full_name); }).then(contribs => { console.log('=== CONTRIBS ==='); console.log(contribs); return gh.getUser(contribs.data[0].login); }).then(user => { console.log('=== USER ==='); console.log(user); return gh.getRateLimit(); }).then(limit => { console.log('=== RATE LIMIT ==='); console.log(limit); }).catch(err => { console.log('ERROR:'); console.log(err); }); } componentWillUnmount() { this.map = null; } initializeMap() { if (this.map) { return; } this.map = L.map(this.mapDiv, this.props.mapOptions || defaultMapConfig.options); if (this.props.mapLayers && this.props.mapLayers.length > 0) { for (let i=0; i < this.props.mapLayers.length; i++) { this.props.mapLayers[i].addTo(this.map); } } else { L.tileLayer(defaultMapConfig.tileLayer.uri, defaultMapConfig.tileLayer.options).addTo(this.map); } } updateData() { } render() { return ( <div className="map-container"> <div className="os-map" ref={(div) => { this.mapDiv = div; }}></div> <RaisedButton label="Default" /> </div> ); } } RepoUserHeatmap.propTypes = { mapOptions: PropTypes.object, mapLayers: PropTypes.array }; export default RepoUserHeatmap;
jefferey/octoviz
src/components/views/RepoUserHeatmap.js
JavaScript
mit
2,707
function lessThan (a, b) { return a < b } function main () { for (var i = 0; i < 10000; i++) { lessThan(1, 0x7fffffff) } for (var i = 0; i < 10000; i++) { lessThan(1, Infinity) } for (var i = 0; i < 10000; i++) { lessThan(1, 0x7fffffff) } } main()
bigeasy/hotspot
jit/less-than.js
JavaScript
mit
304
/*! * hybridify-all <https://github.com/hybridables/hybridify-all> * * Copyright (c) 2015 Charlike Mike Reagent, contributors. * Released under the MIT license. */ 'use strict' var reduce = require('object.reduce') var hybridify = require('hybridify') /** * > Hybridifies all the selected functions in an object. * * **Example:** * * ```js * var hybridifyAll = require('hybridify-all') * var fs = require('fs') * * fs = hybridifyAll(fs) * fs.readFile(__filename, 'utf8', function(err, res) { * //=> err, res * }) * .then(function(res) { * //=> res * return fs.stat(__filename) * }) * .then(function(stat) { * assert.strictEqual(stat.size, fs.statSync(__filename).size) * }) * ``` * * @name hybridifyAll * @param {Object|Function} `<source>` the source object for the async functions * @param {Object|Function} `[dest]` the destination to set all the hybridified methods * @return {Object|Function} * @api public */ module.exports = function hybridifyAll (source, dest) { if (!source) { throw new Error('hybridify-all: should have at least 1 arguments') } if (typeOf(source) !== 'function' && typeOf(source) !== 'object') { throw new TypeError('hybridify-all: expect `source` be object|function') } dest = dest || {} if (typeof source === 'function') { dest = hybridify(source) } return Object.keys(source).length ? reduce(source, function (dest, fn, key) { if (typeof fn === 'function') { dest[key] = hybridify(fn) } return dest }, dest) : dest } /** * Get correct type of value * * @param {*} `val` * @return {String} * @api private */ function typeOf (val) { if (Array.isArray(val)) { return 'array' } if (typeof val !== 'object') { return typeof val } return Object.prototype.toString(val).slice(8, -1).toLowerCase() }
hybridables/hybridify-all
index.js
JavaScript
mit
1,844
/*! p5.dom.js v0.3.3 May 10, 2017 */ /** * <p>The web is much more than just canvas and p5.dom makes it easy to interact * with other HTML5 objects, including text, hyperlink, image, input, video, * audio, and webcam.</p> * <p>There is a set of creation methods, DOM manipulation methods, and * an extended p5.Element that supports a range of HTML elements. See the * <a href="https://github.com/processing/p5.js/wiki/Beyond-the-canvas"> * beyond the canvas tutorial</a> for a full overview of how this addon works. * * <p>Methods and properties shown in black are part of the p5.js core, items in * blue are part of the p5.dom library. You will need to include an extra file * in order to access the blue functions. See the * <a href="http://p5js.org/libraries/#using-a-library">using a library</a> * section for information on how to include this library. p5.dom comes with * <a href="http://p5js.org/download">p5 complete</a> or you can download the single file * <a href="https://raw.githubusercontent.com/lmccart/p5.js/master/lib/addons/p5.dom.js"> * here</a>.</p> * <p>See <a href="https://github.com/processing/p5.js/wiki/Beyond-the-canvas">tutorial: beyond the canvas</a> * for more info on how to use this libary.</a> * * @module p5.dom * @submodule p5.dom * @for p5.dom * @main */ (function (root, factory) { if (typeof define === 'function' && define.amd) define('p5.dom', ['p5'], function (p5) { (factory(p5));}); else if (typeof exports === 'object') factory(require('../p5')); else factory(root['p5']); }(this, function (p5) { // ============================================================================= // p5 additions // ============================================================================= /** * Searches the page for an element with the given ID, class, or tag name (using the '#' or '.' * prefixes to specify an ID or class respectively, and none for a tag) and returns it as * a p5.Element. If a class or tag name is given with more than 1 element, * only the first element will be returned. * The DOM node itself can be accessed with .elt. * Returns null if none found. You can also specify a container to search within. * * @method select * @param {String} name id, class, or tag name of element to search for * @param {String} [container] id, p5.Element, or HTML element to search within * @return {Object|p5.Element|Null} p5.Element containing node found * @example * <div ><code class='norender'> * function setup() { * createCanvas(100,100); * //translates canvas 50px down * select('canvas').position(100, 100); * } * </code></div> * <div ><code class='norender'> * // these are all valid calls to select() * var a = select('#moo'); * var b = select('#blah', '#myContainer'); * var c = select('#foo', b); * var d = document.getElementById('beep'); * var e = select('p', d); * </code></div> * */ p5.prototype.select = function (e, p) { var res = null; var container = getContainer(p); if (e[0] === '.'){ e = e.slice(1); res = container.getElementsByClassName(e); if (res.length) { res = res[0]; } else { res = null; } }else if (e[0] === '#'){ e = e.slice(1); res = container.getElementById(e); }else { res = container.getElementsByTagName(e); if (res.length) { res = res[0]; } else { res = null; } } if (res) { return wrapElement(res); } else { return null; } }; /** * Searches the page for elements with the given class or tag name (using the '.' prefix * to specify a class and no prefix for a tag) and returns them as p5.Elements * in an array. * The DOM node itself can be accessed with .elt. * Returns an empty array if none found. * You can also specify a container to search within. * * @method selectAll * @param {String} name class or tag name of elements to search for * @param {String} [container] id, p5.Element, or HTML element to search within * @return {Array} Array of p5.Elements containing nodes found * @example * <div class='norender'><code> * function setup() { * createButton('btn'); * createButton('2nd btn'); * createButton('3rd btn'); * var buttons = selectAll('button'); * * for (var i = 0; i < buttons.length; i++){ * buttons[i].size(100,100); * } * } * </code></div> * <div class='norender'><code> * // these are all valid calls to selectAll() * var a = selectAll('.moo'); * var b = selectAll('div'); * var c = selectAll('button', '#myContainer'); * var d = select('#container'); * var e = selectAll('p', d); * var f = document.getElementById('beep'); * var g = select('.blah', f); * </code></div> * */ p5.prototype.selectAll = function (e, p) { var arr = []; var res; var container = getContainer(p); if (e[0] === '.'){ e = e.slice(1); res = container.getElementsByClassName(e); } else { res = container.getElementsByTagName(e); } if (res) { for (var j = 0; j < res.length; j++) { var obj = wrapElement(res[j]); arr.push(obj); } } return arr; }; /** * Helper function for select and selectAll */ function getContainer(p) { var container = document; if (typeof p === 'string' && p[0] === '#'){ p = p.slice(1); container = document.getElementById(p) || document; } else if (p instanceof p5.Element){ container = p.elt; } else if (p instanceof HTMLElement){ container = p; } return container; } /** * Helper function for getElement and getElements. */ function wrapElement(elt) { if(elt.tagName === "INPUT" && elt.type === "checkbox") { var converted = new p5.Element(elt); converted.checked = function(){ if (arguments.length === 0){ return this.elt.checked; } else if(arguments[0]) { this.elt.checked = true; } else { this.elt.checked = false; } return this; }; return converted; } else if (elt.tagName === "VIDEO" || elt.tagName === "AUDIO") { return new p5.MediaElement(elt); } else if ( elt.tagName === "SELECT" ){ return createSelect( new p5.Element(elt) ); } else { return new p5.Element(elt); } } /** * Removes all elements created by p5, except any canvas / graphics * elements created by createCanvas or createGraphics. * Event handlers are removed, and element is removed from the DOM. * @method removeElements * @example * <div class='norender'><code> * function setup() { * createCanvas(100, 100); * createDiv('this is some text'); * createP('this is a paragraph'); * } * function mousePressed() { * removeElements(); // this will remove the div and p, not canvas * } * </code></div> * */ p5.prototype.removeElements = function (e) { for (var i=0; i<this._elements.length; i++) { if (!(this._elements[i].elt instanceof HTMLCanvasElement)) { this._elements[i].remove(); } } }; /** * Helpers for create methods. */ function addElement(elt, pInst, media) { var node = pInst._userNode ? pInst._userNode : document.body; node.appendChild(elt); var c = media ? new p5.MediaElement(elt) : new p5.Element(elt); pInst._elements.push(c); return c; } /** * Creates a &lt;div&gt;&lt;/div&gt; element in the DOM with given inner HTML. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createDiv * @param {String} html inner HTML for element created * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var myDiv; * function setup() { * myDiv = createDiv('this is some text'); * } * </code></div> */ /** * Creates a &lt;p&gt;&lt;/p&gt; element in the DOM with given inner HTML. Used * for paragraph length text. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createP * @param {String} html inner HTML for element created * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var myP; * function setup() { * myP = createP('this is some text'); * } * </code></div> */ /** * Creates a &lt;span&gt;&lt;/span&gt; element in the DOM with given inner HTML. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createSpan * @param {String} html inner HTML for element created * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var mySpan; * function setup() { * mySpan = createSpan('this is some text'); * } * </code></div> */ var tags = ['div', 'p', 'span']; tags.forEach(function(tag) { var method = 'create' + tag.charAt(0).toUpperCase() + tag.slice(1); p5.prototype[method] = function(html) { var elt = document.createElement(tag); elt.innerHTML = typeof html === undefined ? "" : html; return addElement(elt, this); } }); /** * Creates an &lt;img&gt; element in the DOM with given src and * alternate text. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createImg * @param {String} src src path or url for image * @param {String} [alt] alternate text to be used if image does not load * @param {Function} [successCallback] callback to be called once image data is loaded * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var img; * function setup() { * img = createImg('http://p5js.org/img/asterisk-01.png'); * } * </code></div> */ p5.prototype.createImg = function() { var elt = document.createElement('img'); var args = arguments; var self; var setAttrs = function(){ self.width = elt.offsetWidth || elt.width; self.height = elt.offsetHeight || elt.height; if (args.length > 1 && typeof args[1] === 'function'){ self.fn = args[1]; self.fn(); }else if (args.length > 1 && typeof args[2] === 'function'){ self.fn = args[2]; self.fn(); } }; elt.src = args[0]; if (args.length > 1 && typeof args[1] === 'string'){ elt.alt = args[1]; } elt.onload = function(){ setAttrs(); } self = addElement(elt, this); return self; }; /** * Creates an &lt;a&gt;&lt;/a&gt; element in the DOM for including a hyperlink. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createA * @param {String} href url of page to link to * @param {String} html inner html of link element to display * @param {String} [target] target where new link should open, * could be _blank, _self, _parent, _top. * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var myLink; * function setup() { * myLink = createA('http://p5js.org/', 'this is a link'); * } * </code></div> */ p5.prototype.createA = function(href, html, target) { var elt = document.createElement('a'); elt.href = href; elt.innerHTML = html; if (target) elt.target = target; return addElement(elt, this); }; /** INPUT **/ /** * Creates a slider &lt;input&gt;&lt;/input&gt; element in the DOM. * Use .size() to set the display length of the slider. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createSlider * @param {Number} min minimum value of the slider * @param {Number} max maximum value of the slider * @param {Number} [value] default value of the slider * @param {Number} [step] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value) * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div><code> * var slider; * function setup() { * slider = createSlider(0, 255, 100); * slider.position(10, 10); * slider.style('width', '80px'); * } * * function draw() { * var val = slider.value(); * background(val); * } * </code></div> * * <div><code> * var slider; * function setup() { * colorMode(HSB); * slider = createSlider(0, 360, 60, 40); * slider.position(10, 10); * slider.style('width', '80px'); * } * * function draw() { * var val = slider.value(); * background(val, 100, 100, 1); * } * </code></div> */ p5.prototype.createSlider = function(min, max, value, step) { var elt = document.createElement('input'); elt.type = 'range'; elt.min = min; elt.max = max; if (step === 0) { elt.step = .000000000000000001; // smallest valid step } else if (step) { elt.step = step; } if (typeof(value) === "number") elt.value = value; return addElement(elt, this); }; /** * Creates a &lt;button&gt;&lt;/button&gt; element in the DOM. * Use .size() to set the display size of the button. * Use .mousePressed() to specify behavior on press. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createButton * @param {String} label label displayed on the button * @param {String} [value] value of the button * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var button; * function setup() { * createCanvas(100, 100); * background(0); * button = createButton('click me'); * button.position(19, 19); * button.mousePressed(changeBG); * } * * function changeBG() { * var val = random(255); * background(val); * } * </code></div> */ p5.prototype.createButton = function(label, value) { var elt = document.createElement('button'); elt.innerHTML = label; if (value) elt.value = value; return addElement(elt, this); }; /** * Creates a checkbox &lt;input&gt;&lt;/input&gt; element in the DOM. * Calling .checked() on a checkbox returns if it is checked or not * * @method createCheckbox * @param {String} [label] label displayed after checkbox * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false.Unchecked if no value given * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var checkbox; * * function setup() { * checkbox = createCheckbox('label', false); * checkbox.changed(myCheckedEvent); * } * * function myCheckedEvent() { * if (this.checked()) { * console.log("Checking!"); * } else { * console.log("Unchecking!"); * } * } * </code></div> */ p5.prototype.createCheckbox = function() { var elt = document.createElement('div'); var checkbox = document.createElement('input'); checkbox.type = 'checkbox'; elt.appendChild(checkbox); //checkbox must be wrapped in p5.Element before label so that label appears after var self = addElement(elt, this); self.checked = function(){ var cb = self.elt.getElementsByTagName('input')[0]; if (cb) { if (arguments.length === 0){ return cb.checked; }else if(arguments[0]){ cb.checked = true; }else{ cb.checked = false; } } return self; }; this.value = function(val){ self.value = val; return this; }; if (arguments[0]){ var ran = Math.random().toString(36).slice(2); var label = document.createElement('label'); checkbox.setAttribute('id', ran); label.htmlFor = ran; self.value(arguments[0]); label.appendChild(document.createTextNode(arguments[0])); elt.appendChild(label); } if (arguments[1]){ checkbox.checked = true; } return self; }; /** * Creates a dropdown menu &lt;select&gt;&lt;/select&gt; element in the DOM. * It also helps to assign select-box methods to p5.Element when selecting existing select box * @method createSelect * @param {boolean} [multiple] true if dropdown should support multiple selections * @return {p5.Element} * @example * <div><code> * var sel; * * function setup() { * textAlign(CENTER); * background(200); * sel = createSelect(); * sel.position(10, 10); * sel.option('pear'); * sel.option('kiwi'); * sel.option('grape'); * sel.changed(mySelectEvent); * } * * function mySelectEvent() { * var item = sel.value(); * background(200); * text("it's a "+item+"!", 50, 50); * } * </code></div> */ /** * @method createSelect * @param {Object} existing DOM select element * @return {p5.Element} */ p5.prototype.createSelect = function() { var elt, self; var arg = arguments[0]; if( typeof arg === 'object' && arg.elt.nodeName === 'SELECT' ) { self = arg; elt = this.elt = arg.elt; } else { elt = document.createElement('select'); if( arg && typeof arg === 'boolean' ) { elt.setAttribute('multiple', 'true'); } self = addElement(elt, this); } self.option = function(name, value) { var index; //see if there is already an option with this name for (var i = 0; i < this.elt.length; i++) { if(this.elt[i].innerHTML == name) { index = i; break; } } //if there is an option with this name we will modify it if(index !== undefined) { //if the user passed in false then delete that option if(value === false) { this.elt.remove(index); } else { //otherwise if the name and value are the same then change both if(this.elt[index].innerHTML == this.elt[index].value) { this.elt[index].innerHTML = this.elt[index].value = value; //otherwise just change the value } else { this.elt[index].value = value; } } } //if it doesn't exist make it else { var opt = document.createElement('option'); opt.innerHTML = name; if (arguments.length > 1) opt.value = value; else opt.value = name; elt.appendChild(opt); } }; self.selected = function(value) { var arr = []; if (arguments.length > 0) { for (var i = 0; i < this.elt.length; i++) { if (value.toString() === this.elt[i].value) { this.elt.selectedIndex = i; } } return this; } else { if (arg) { for (var i = 0; i < this.elt.selectedOptions.length; i++) { arr.push(this.elt.selectedOptions[i].value); } return arr; } else { return this.elt.value; } } }; return self; }; /** * Creates a radio button &lt;input&gt;&lt;/input&gt; element in the DOM. * The .option() method can be used to set options for the radio after it is * created. The .value() method will return the currently selected option. * * @method createRadio * @param {String} [divId] the id and name of the created div and input field respectively * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div><code> * var radio; * * function setup() { * radio = createRadio(); * radio.option("black"); * radio.option("white"); * radio.option("gray"); * radio.style('width', '60px'); * textAlign(CENTER); * fill(255, 0, 0); * } * * function draw() { * var val = radio.value(); * background(val); * text(val, width/2, height/2); * } * </code></div> * <div><code> * var radio; * * function setup() { * radio = createRadio(); * radio.option('apple', 1); * radio.option('bread', 2); * radio.option('juice', 3); * radio.style('width', '60px'); * textAlign(CENTER); * } * * function draw() { * background(200); * var val = radio.value(); * if (val) { * text('item cost is $'+val, width/2, height/2); * } * } * </code></div> */ p5.prototype.createRadio = function() { var radios = document.querySelectorAll("input[type=radio]"); var count = 0; if(radios.length > 1){ var length = radios.length; var prev=radios[0].name; var current = radios[1].name; count = 1; for(var i = 1; i < length; i++) { current = radios[i].name; if(prev != current){ count++; } prev = current; } } else if (radios.length == 1){ count = 1; } var elt = document.createElement('div'); var self = addElement(elt, this); var times = -1; self.option = function(name, value){ var opt = document.createElement('input'); opt.type = 'radio'; opt.innerHTML = name; if (arguments.length > 1) opt.value = value; else opt.value = name; opt.setAttribute('name',"defaultradio"+count); elt.appendChild(opt); if (name){ times++; var ran = Math.random().toString(36).slice(2); var label = document.createElement('label'); opt.setAttribute('id', "defaultradio"+count+"-"+times); label.htmlFor = "defaultradio"+count+"-"+times; label.appendChild(document.createTextNode(name)); elt.appendChild(label); } return opt; }; self.selected = function(){ var length = this.elt.childNodes.length; if(arguments.length == 1) { for (var i = 0; i < length; i+=2){ if(this.elt.childNodes[i].value == arguments[0]) this.elt.childNodes[i].checked = true; } return this; } else { for (var i = 0; i < length; i+=2){ if(this.elt.childNodes[i].checked == true) return this.elt.childNodes[i].value; } } }; self.value = function(){ var length = this.elt.childNodes.length; if(arguments.length == 1) { for (var i = 0; i < length; i+=2){ if(this.elt.childNodes[i].value == arguments[0]) this.elt.childNodes[i].checked = true; } return this; } else { for (var i = 0; i < length; i+=2){ if(this.elt.childNodes[i].checked == true) return this.elt.childNodes[i].value; } return ""; } }; return self }; /** * Creates an &lt;input&gt;&lt;/input&gt; element in the DOM for text input. * Use .size() to set the display length of the box. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createInput * @param {Number} [value] default value of the input box * @param {String} [type] type of text, ie text, password etc. Defaults to text * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * function setup(){ * var inp = createInput(''); * inp.input(myInputEvent); * } * * function myInputEvent(){ * console.log('you are typing: ', this.value()); * } * * </code></div> */ p5.prototype.createInput = function(value, type) { var elt = document.createElement('input'); elt.type = type ? type : 'text'; if (value) elt.value = value; return addElement(elt, this); }; /** * Creates an &lt;input&gt;&lt;/input&gt; element in the DOM of type 'file'. * This allows users to select local files for use in a sketch. * * @method createFileInput * @param {Function} [callback] callback function for when a file loaded * @param {String} [multiple] optional to allow multiple files selected * @return {Object|p5.Element} pointer to p5.Element holding created DOM element * @example * var input; * var img; * * function setup() { * input = createFileInput(handleFile); * input.position(0, 0); * } * * function draw() { * if (img) { * image(img, 0, 0, width, height); * } * } * * function handleFile(file) { * print(file); * if (file.type === 'image') { * img = createImg(file.data); * img.hide(); * } * } */ p5.prototype.createFileInput = function(callback, multiple) { // Is the file stuff supported? if (window.File && window.FileReader && window.FileList && window.Blob) { // Yup, we're ok and make an input file selector var elt = document.createElement('input'); elt.type = 'file'; // If we get a second argument that evaluates to true // then we are looking for multiple files if (multiple) { // Anything gets the job done elt.multiple = 'multiple'; } // Function to handle when a file is selected // We're simplifying life and assuming that we always // want to load every selected file function handleFileSelect(evt) { // These are the files var files = evt.target.files; // Load each one and trigger a callback for (var i = 0; i < files.length; i++) { var f = files[i]; var reader = new FileReader(); function makeLoader(theFile) { // Making a p5.File object var p5file = new p5.File(theFile); return function(e) { p5file.data = e.target.result; callback(p5file); }; }; reader.onload = makeLoader(f); // Text or data? // This should likely be improved if (f.type.indexOf('text') > -1) { reader.readAsText(f); } else { reader.readAsDataURL(f); } } } // Now let's handle when a file was selected elt.addEventListener('change', handleFileSelect, false); return addElement(elt, this); } else { console.log('The File APIs are not fully supported in this browser. Cannot create element.'); } }; /** VIDEO STUFF **/ function createMedia(pInst, type, src, callback) { var elt = document.createElement(type); // allow src to be empty var src = src || ''; if (typeof src === 'string') { src = [src]; } for (var i=0; i<src.length; i++) { var source = document.createElement('source'); source.src = src[i]; elt.appendChild(source); } if (typeof callback !== 'undefined') { var callbackHandler = function() { callback(); elt.removeEventListener('canplaythrough', callbackHandler); } elt.addEventListener('canplaythrough', callbackHandler); } var c = addElement(elt, pInst, true); c.loadedmetadata = false; // set width and height onload metadata elt.addEventListener('loadedmetadata', function() { c.width = elt.videoWidth; c.height = elt.videoHeight; // set elt width and height if not set if (c.elt.width === 0) c.elt.width = elt.videoWidth; if (c.elt.height === 0) c.elt.height = elt.videoHeight; c.loadedmetadata = true; }); return c; } /** * Creates an HTML5 &lt;video&gt; element in the DOM for simple playback * of audio/video. Shown by default, can be hidden with .hide() * and drawn into canvas using video(). Appends to the container * node if one is specified, otherwise appends to body. The first parameter * can be either a single string path to a video file, or an array of string * paths to different formats of the same video. This is useful for ensuring * that your video can play across different browsers, as each supports * different formats. See <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats">this * page</a> for further information about supported formats. * * @method createVideo * @param {String|Array} src path to a video file, or array of paths for * supporting different browsers * @param {Object} [callback] callback function to be called upon * 'canplaythrough' event fire, that is, when the * browser can play the media, and estimates that * enough data has been loaded to play the media * up to its end without having to stop for * further buffering of content * @return {Object|p5.Element} pointer to video p5.Element */ p5.prototype.createVideo = function(src, callback) { return createMedia(this, 'video', src, callback); }; /** AUDIO STUFF **/ /** * Creates a hidden HTML5 &lt;audio&gt; element in the DOM for simple audio * playback. Appends to the container node if one is specified, * otherwise appends to body. The first parameter * can be either a single string path to a audio file, or an array of string * paths to different formats of the same audio. This is useful for ensuring * that your audio can play across different browsers, as each supports * different formats. See <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats">this * page for further information about supported formats</a>. * * @method createAudio * @param {String|Array} src path to an audio file, or array of paths for * supporting different browsers * @param {Object} [callback] callback function to be called upon * 'canplaythrough' event fire, that is, when the * browser can play the media, and estimates that * enough data has been loaded to play the media * up to its end without having to stop for * further buffering of content * @return {Object|p5.Element} pointer to audio p5.Element */ p5.prototype.createAudio = function(src, callback) { return createMedia(this, 'audio', src, callback); }; /** CAMERA STUFF **/ p5.prototype.VIDEO = 'video'; p5.prototype.AUDIO = 'audio'; navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; /** * <p>Creates a new &lt;video&gt; element that contains the audio/video feed * from a webcam. This can be drawn onto the canvas using video().</p> * <p>More specific properties of the feed can be passing in a Constraints object. * See the * <a href="http://w3c.github.io/mediacapture-main/getusermedia.html#media-track-constraints"> W3C * spec</a> for possible properties. Note that not all of these are supported * by all browsers.</p> * <p>Security note: A new browser security specification requires that getUserMedia, * which is behind createCapture(), only works when you're running the code locally, * or on HTTPS. Learn more <a href="http://stackoverflow.com/questions/34197653/getusermedia-in-chrome-47-without-using-https">here</a> * and <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia">here</a>.</p> * * @method createCapture * @param {String|Constant|Object} type type of capture, either VIDEO or * AUDIO if none specified, default both, * or a Constraints object * @param {Function} callback function to be called once * stream has loaded * @return {Object|p5.Element} capture video p5.Element * @example * <div class='norender'><code> * var capture; * * function setup() { * createCanvas(480, 120); * capture = createCapture(VIDEO); * } * * function draw() { * image(capture, 0, 0, width, width*capture.height/capture.width); * filter(INVERT); * } * </code></div> * <div class='norender'><code> * function setup() { * createCanvas(480, 120); * var constraints = { * video: { * mandatory: { * minWidth: 1280, * minHeight: 720 * }, * optional: [ * { maxFrameRate: 10 } * ] * }, * audio: true * }; * createCapture(constraints, function(stream) { * console.log(stream); * }); * } * </code></div> */ p5.prototype.createCapture = function() { var useVideo = true; var useAudio = true; var constraints; var cb; for (var i=0; i<arguments.length; i++) { if (arguments[i] === p5.prototype.VIDEO) { useAudio = false; } else if (arguments[i] === p5.prototype.AUDIO) { useVideo = false; } else if (typeof arguments[i] === 'object') { constraints = arguments[i]; } else if (typeof arguments[i] === 'function') { cb = arguments[i]; } } if (navigator.getUserMedia) { var elt = document.createElement('video'); if (!constraints) { constraints = {video: useVideo, audio: useAudio}; } navigator.getUserMedia(constraints, function(stream) { elt.src = window.URL.createObjectURL(stream); if (cb) { cb(stream); } }, function(e) { console.log(e); }); } else { throw 'getUserMedia not supported in this browser'; } var c = addElement(elt, this, true); c.loadedmetadata = false; // set width and height onload metadata elt.addEventListener('loadedmetadata', function() { elt.play(); if (elt.width) { c.width = elt.videoWidth = elt.width; c.height = elt.videoHeight = elt.height; } else { c.width = c.elt.width = elt.videoWidth; c.height = c.elt.height = elt.videoHeight; } c.loadedmetadata = true; }); return c; }; /** * Creates element with given tag in the DOM with given content. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createElement * @param {String} tag tag for the new element * @param {String} [content] html content to be inserted into the element * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var h2 = createElement('h2','im an h2 p5.element!'); * </code></div> */ p5.prototype.createElement = function(tag, content) { var elt = document.createElement(tag); if (typeof content !== 'undefined') { elt.innerHTML = content; } return addElement(elt, this); }; // ============================================================================= // p5.Element additions // ============================================================================= /** * * Adds specified class to the element. * * @for p5.Element * @method addClass * @param {String} class name of class to add * @return {Object|p5.Element} * @example * <div class='norender'><code> * var div = createDiv('div'); * div.addClass('myClass'); * </code></div> */ p5.Element.prototype.addClass = function(c) { if (this.elt.className) { // PEND don't add class more than once //var regex = new RegExp('[^a-zA-Z\d:]?'+c+'[^a-zA-Z\d:]?'); //if (this.elt.className.search(/[^a-zA-Z\d:]?hi[^a-zA-Z\d:]?/) === -1) { this.elt.className = this.elt.className+' '+c; //} } else { this.elt.className = c; } return this; } /** * * Removes specified class from the element. * * @method removeClass * @param {String} class name of class to remove * @return {Object|p5.Element} */ p5.Element.prototype.removeClass = function(c) { var regex = new RegExp('(?:^|\\s)'+c+'(?!\\S)'); this.elt.className = this.elt.className.replace(regex, ''); this.elt.className = this.elt.className.replace(/^\s+|\s+$/g, ""); //prettify (optional) return this; } /** * * Attaches the element as a child to the parent specified. * Accepts either a string ID, DOM node, or p5.Element. * If no argument is specified, an array of children DOM nodes is returned. * * @method child * @param {String|Object|p5.Element} [child] the ID, DOM node, or p5.Element * to add to the current element * @return {p5.Element} * @example * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * var div1 = createDiv('this is the child'); * div0.child(div1); // use p5.Element * </code></div> * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * var div1 = createDiv('this is the child'); * div1.id('apples'); * div0.child('apples'); // use id * </code></div> * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * var elt = document.getElementById('myChildDiv'); * div0.child(elt); // use element from page * </code></div> */ p5.Element.prototype.child = function(c) { if (typeof c === 'undefined'){ return this.elt.childNodes } if (typeof c === 'string') { if (c[0] === '#') { c = c.substring(1); } c = document.getElementById(c); } else if (c instanceof p5.Element) { c = c.elt; } this.elt.appendChild(c); return this; }; /** * Centers a p5 Element either vertically, horizontally, * or both, relative to its parent or according to * the body if the Element has no parent. If no argument is passed * the Element is aligned both vertically and horizontally. * * @param {String} align passing 'vertical', 'horizontal' aligns element accordingly * @return {Object|p5.Element} pointer to p5.Element * @example * <div><code> * function setup() { * var div = createDiv('').size(10,10); * div.style('background-color','orange'); * div.center(); * * } * </code></div> */ p5.Element.prototype.center = function(align) { var style = this.elt.style.display; var hidden = this.elt.style.display === 'none'; var parentHidden = this.parent().style.display === 'none'; var pos = { x : this.elt.offsetLeft, y : this.elt.offsetTop }; if (hidden) this.show(); this.elt.style.display = 'block'; this.position(0,0); if (parentHidden) this.parent().style.display = 'block'; var wOffset = Math.abs(this.parent().offsetWidth - this.elt.offsetWidth); var hOffset = Math.abs(this.parent().offsetHeight - this.elt.offsetHeight); var y = pos.y; var x = pos.x; if (align === 'both' || align === undefined){ this.position(wOffset/2, hOffset/2); }else if (align === 'horizontal'){ this.position(wOffset/2, y); }else if (align === 'vertical'){ this.position(x, hOffset/2); } this.style('display', style); if (hidden) this.hide(); if (parentHidden) this.parent().style.display = 'none'; return this; }; /** * * If an argument is given, sets the inner HTML of the element, * replacing any existing html. If true is included as a second * argument, html is appended instead of replacing existing html. * If no arguments are given, returns * the inner HTML of the element. * * @for p5.Element * @method html * @param {String} [html] the HTML to be placed inside the element * @param {boolean} [append] whether to append HTML to existing * @return {Object|p5.Element|String} * @example * <div class='norender'><code> * var div = createDiv('').size(100,100); * div.html('hi'); * </code></div> * <div class='norender'><code> * var div = createDiv('Hello ').size(100,100); * div.html('World', true); * </code></div> */ p5.Element.prototype.html = function() { if (arguments.length === 0) { return this.elt.innerHTML; } else if (arguments[1]) { this.elt.innerHTML += arguments[0]; return this; } else { this.elt.innerHTML = arguments[0]; return this; } }; /** * * Sets the position of the element relative to (0, 0) of the * window. Essentially, sets position:absolute and left and top * properties of style. If no arguments given returns the x and y position * of the element in an object. * * @method position * @param {Number} [x] x-position relative to upper left of window * @param {Number} [y] y-position relative to upper left of window * @return {Object|p5.Element} * @example * <div><code class='norender'> * function setup() { * var cnv = createCanvas(100, 100); * // positions canvas 50px to the right and 100px * // below upper left corner of the window * cnv.position(50, 100); * } * </code></div> */ p5.Element.prototype.position = function() { if (arguments.length === 0){ return { 'x' : this.elt.offsetLeft , 'y' : this.elt.offsetTop }; }else{ this.elt.style.position = 'absolute'; this.elt.style.left = arguments[0]+'px'; this.elt.style.top = arguments[1]+'px'; this.x = arguments[0]; this.y = arguments[1]; return this; } }; /* Helper method called by p5.Element.style() */ p5.Element.prototype._translate = function(){ this.elt.style.position = 'absolute'; // save out initial non-translate transform styling var transform = ''; if (this.elt.style.transform) { transform = this.elt.style.transform.replace(/translate3d\(.*\)/g, ''); transform = transform.replace(/translate[X-Z]?\(.*\)/g, ''); } if (arguments.length === 2) { this.elt.style.transform = 'translate('+arguments[0]+'px, '+arguments[1]+'px)'; } else if (arguments.length > 2) { this.elt.style.transform = 'translate3d('+arguments[0]+'px,'+arguments[1]+'px,'+arguments[2]+'px)'; if (arguments.length === 3) { this.elt.parentElement.style.perspective = '1000px'; } else { this.elt.parentElement.style.perspective = arguments[3]+'px'; } } // add any extra transform styling back on end this.elt.style.transform += transform; return this; }; /* Helper method called by p5.Element.style() */ p5.Element.prototype._rotate = function(){ // save out initial non-rotate transform styling var transform = ''; if (this.elt.style.transform) { var transform = this.elt.style.transform.replace(/rotate3d\(.*\)/g, ''); transform = transform.replace(/rotate[X-Z]?\(.*\)/g, ''); } if (arguments.length === 1){ this.elt.style.transform = 'rotate('+arguments[0]+'deg)'; }else if (arguments.length === 2){ this.elt.style.transform = 'rotate('+arguments[0]+'deg, '+arguments[1]+'deg)'; }else if (arguments.length === 3){ this.elt.style.transform = 'rotateX('+arguments[0]+'deg)'; this.elt.style.transform += 'rotateY('+arguments[1]+'deg)'; this.elt.style.transform += 'rotateZ('+arguments[2]+'deg)'; } // add remaining transform back on this.elt.style.transform += transform; return this; }; /** * Sets the given style (css) property (1st arg) of the element with the * given value (2nd arg). If a single argument is given, .style() * returns the value of the given property; however, if the single argument * is given in css syntax ('text-align:center'), .style() sets the css * appropriatly. .style() also handles 2d and 3d css transforms. If * the 1st arg is 'rotate', 'translate', or 'position', the following arguments * accept Numbers as values. ('translate', 10, 100, 50); * * @method style * @param {String} property property to be set * @param {String|Number|p5.Color} [value] value to assign to property (only String|Number for rotate/translate) * @return {String|Object|p5.Element} value of property, if no value is specified * or p5.Element * @example * <div><code class="norender"> * var myDiv = createDiv("I like pandas."); * myDiv.style("font-size", "18px"); * myDiv.style("color", "#ff0000"); * </code></div> * <div><code class="norender"> * var col = color(25,23,200,50); * var button = createButton("button"); * button.style("background-color", col); * button.position(10, 10); * </code></div> * <div><code class="norender"> * var myDiv = createDiv("I like lizards."); * myDiv.style("position", 20, 20); * myDiv.style("rotate", 45); * </code></div> * <div><code class="norender"> * var myDiv; * function setup() { * background(200); * myDiv = createDiv("I like gray."); * myDiv.position(20, 20); * } * * function draw() { * myDiv.style("font-size", mouseX+"px"); * } * </code></div> */ p5.Element.prototype.style = function(prop, val) { var self = this; if (val instanceof p5.Color) { val = 'rgba(' + val.levels[0] + ',' + val.levels[1] + ',' + val.levels[2] + ',' + val.levels[3]/255 + ')' } if (typeof val === 'undefined') { if (prop.indexOf(':') === -1) { var styles = window.getComputedStyle(self.elt); var style = styles.getPropertyValue(prop); return style; } else { var attrs = prop.split(';'); for (var i = 0; i < attrs.length; i++) { var parts = attrs[i].split(':'); if (parts[0] && parts[1]) { this.elt.style[parts[0].trim()] = parts[1].trim(); } } } } else { if (prop === 'rotate' || prop === 'translate' || prop === 'position'){ var trans = Array.prototype.shift.apply(arguments); var f = this[trans] || this['_'+trans]; f.apply(this, arguments); } else { this.elt.style[prop] = val; if (prop === 'width' || prop === 'height' || prop === 'left' || prop === 'top') { var numVal = val.replace(/\D+/g, ''); this[prop] = parseInt(numVal, 10); // pend: is this necessary? } } } return this; }; /** * * Adds a new attribute or changes the value of an existing attribute * on the specified element. If no value is specified, returns the * value of the given attribute, or null if attribute is not set. * * @method attribute * @param {String} attr attribute to set * @param {String} [value] value to assign to attribute * @return {String|Object|p5.Element} value of attribute, if no value is * specified or p5.Element * @example * <div class="norender"><code> * var myDiv = createDiv("I like pandas."); * myDiv.attribute("align", "center"); * </code></div> */ p5.Element.prototype.attribute = function(attr, value) { //handling for checkboxes and radios to ensure options get //attributes not divs if(this.elt.firstChild != null && (this.elt.firstChild.type === 'checkbox' || this.elt.firstChild.type === 'radio')) { if(typeof value === 'undefined') { return this.elt.firstChild.getAttribute(attr); } else { for(var i=0; i<this.elt.childNodes.length; i++) { this.elt.childNodes[i].setAttribute(attr, value); } } } else if (typeof value === 'undefined') { return this.elt.getAttribute(attr); } else { this.elt.setAttribute(attr, value); return this; } }; /** * * Removes an attribute on the specified element. * * @method removeAttribute * @param {String} attr attribute to remove * @return {Object|p5.Element} * * @example * <div><code> * var button; * var checkbox; * * function setup() { * checkbox = createCheckbox('enable', true); * checkbox.changed(enableButton); * button = createButton('button'); * button.position(10, 10); * } * * function enableButton() { * if( this.checked() ) { * // Re-enable the button * button.removeAttribute('disabled'); * } else { * // Disable the button * button.attribute('disabled',''); * } * } * </code></div> */ p5.Element.prototype.removeAttribute = function(attr) { if(this.elt.firstChild != null && (this.elt.firstChild.type === 'checkbox' || this.elt.firstChild.type === 'radio')) { for(var i=0; i<this.elt.childNodes.length; i++) { this.elt.childNodes[i].removeAttribute(attr); } } this.elt.removeAttribute(attr); return this; }; /** * Either returns the value of the element if no arguments * given, or sets the value of the element. * * @method value * @param {String|Number} [value] * @return {String|Object|p5.Element} value of element if no value is specified or p5.Element * @example * <div class='norender'><code> * // gets the value * var inp; * function setup() { * inp = createInput(''); * } * * function mousePressed() { * print(inp.value()); * } * </code></div> * <div class='norender'><code> * // sets the value * var inp; * function setup() { * inp = createInput('myValue'); * } * * function mousePressed() { * inp.value("myValue"); * } * </code></div> */ p5.Element.prototype.value = function() { if (arguments.length > 0) { this.elt.value = arguments[0]; return this; } else { if (this.elt.type === 'range') { return parseFloat(this.elt.value); } else return this.elt.value; } }; /** * * Shows the current element. Essentially, setting display:block for the style. * * @method show * @return {Object|p5.Element} * @example * <div class='norender'><code> * var div = createDiv('div'); * div.style("display", "none"); * div.show(); // turns display to block * </code></div> */ p5.Element.prototype.show = function() { this.elt.style.display = 'block'; return this; }; /** * Hides the current element. Essentially, setting display:none for the style. * * @method hide * @return {Object|p5.Element} * @example * <div class='norender'><code> * var div = createDiv('this is a div'); * div.hide(); * </code></div> */ p5.Element.prototype.hide = function() { this.elt.style.display = 'none'; return this; }; /** * * Sets the width and height of the element. AUTO can be used to * only adjust one dimension. If no arguments given returns the width and height * of the element in an object. * * @method size * @param {Number} [w] width of the element * @param {Number} [h] height of the element * @return {Object|p5.Element} * @example * <div class='norender'><code> * var div = createDiv('this is a div'); * div.size(100, 100); * </code></div> */ p5.Element.prototype.size = function(w, h) { if (arguments.length === 0){ return { 'width' : this.elt.offsetWidth , 'height' : this.elt.offsetHeight }; }else{ var aW = w; var aH = h; var AUTO = p5.prototype.AUTO; if (aW !== AUTO || aH !== AUTO) { if (aW === AUTO) { aW = h * this.width / this.height; } else if (aH === AUTO) { aH = w * this.height / this.width; } // set diff for cnv vs normal div if (this.elt instanceof HTMLCanvasElement) { var j = {}; var k = this.elt.getContext('2d'); for (var prop in k) { j[prop] = k[prop]; } this.elt.setAttribute('width', aW * this._pInst._pixelDensity); this.elt.setAttribute('height', aH * this._pInst._pixelDensity); this.elt.setAttribute('style', 'width:' + aW + 'px; height:' + aH + 'px'); this._pInst.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); for (var prop in j) { this.elt.getContext('2d')[prop] = j[prop]; } } else { this.elt.style.width = aW+'px'; this.elt.style.height = aH+'px'; this.elt.width = aW; this.elt.height = aH; this.width = aW; this.height = aH; } this.width = this.elt.offsetWidth; this.height = this.elt.offsetHeight; if (this._pInst) { // main canvas associated with p5 instance if (this._pInst._curElement.elt === this.elt) { this._pInst._setProperty('width', this.elt.offsetWidth); this._pInst._setProperty('height', this.elt.offsetHeight); } } } return this; } }; /** * Removes the element and deregisters all listeners. * @method remove * @example * <div class='norender'><code> * var myDiv = createDiv('this is some text'); * myDiv.remove(); * </code></div> */ p5.Element.prototype.remove = function() { // deregister events for (var ev in this._events) { this.elt.removeEventListener(ev, this._events[ev]); } if (this.elt.parentNode) { this.elt.parentNode.removeChild(this.elt); } delete(this); }; // ============================================================================= // p5.MediaElement additions // ============================================================================= /** * Extends p5.Element to handle audio and video. In addition to the methods * of p5.Element, it also contains methods for controlling media. It is not * called directly, but p5.MediaElements are created by calling createVideo, * createAudio, and createCapture. * * @class p5.MediaElement * @constructor * @param {String} elt DOM node that is wrapped * @param {Object} [pInst] pointer to p5 instance */ p5.MediaElement = function(elt, pInst) { p5.Element.call(this, elt, pInst); var self = this; this.elt.crossOrigin = 'anonymous'; this._prevTime = 0; this._cueIDCounter = 0; this._cues = []; this._pixelDensity = 1; /** * Path to the media element source. * * @property src * @return {String} src */ Object.defineProperty(self, 'src', { get: function() { var firstChildSrc = self.elt.children[0].src; var srcVal = self.elt.src === window.location.href ? '' : self.elt.src; var ret = firstChildSrc === window.location.href ? srcVal : firstChildSrc; return ret; }, set: function(newValue) { for (var i = 0; i < self.elt.children.length; i++) { self.elt.removeChild(self.elt.children[i]); } var source = document.createElement('source'); source.src = newValue; elt.appendChild(source); self.elt.src = newValue; }, }); // private _onended callback, set by the method: onended(callback) self._onended = function() {}; self.elt.onended = function() { self._onended(self); } }; p5.MediaElement.prototype = Object.create(p5.Element.prototype); /** * Play an HTML5 media element. * * @method play * @return {Object|p5.Element} */ p5.MediaElement.prototype.play = function() { if (this.elt.currentTime === this.elt.duration) { this.elt.currentTime = 0; } if (this.elt.readyState > 1) { this.elt.play(); } else { // in Chrome, playback cannot resume after being stopped and must reload this.elt.load(); this.elt.play(); } return this; }; /** * Stops an HTML5 media element (sets current time to zero). * * @method stop * @return {Object|p5.Element} */ p5.MediaElement.prototype.stop = function() { this.elt.pause(); this.elt.currentTime = 0; return this; }; /** * Pauses an HTML5 media element. * * @method pause * @return {Object|p5.Element} */ p5.MediaElement.prototype.pause = function() { this.elt.pause(); return this; }; /** * Set 'loop' to true for an HTML5 media element, and starts playing. * * @method loop * @return {Object|p5.Element} */ p5.MediaElement.prototype.loop = function() { this.elt.setAttribute('loop', true); this.play(); return this; }; /** * Set 'loop' to false for an HTML5 media element. Element will stop * when it reaches the end. * * @method noLoop * @return {Object|p5.Element} */ p5.MediaElement.prototype.noLoop = function() { this.elt.setAttribute('loop', false); return this; }; /** * Set HTML5 media element to autoplay or not. * * @method autoplay * @param {Boolean} autoplay whether the element should autoplay * @return {Object|p5.Element} */ p5.MediaElement.prototype.autoplay = function(val) { this.elt.setAttribute('autoplay', val); return this; }; /** * Sets volume for this HTML5 media element. If no argument is given, * returns the current volume. * * @param {Number} [val] volume between 0.0 and 1.0 * @return {Number|p5.MediaElement} current volume or p5.MediaElement * @method volume */ p5.MediaElement.prototype.volume = function(val) { if (typeof val === 'undefined') { return this.elt.volume; } else { this.elt.volume = val; } }; /** * If no arguments are given, returns the current playback speed of the * element. The speed parameter sets the speed where 2.0 will play the * element twice as fast, 0.5 will play at half the speed, and -1 will play * the element in normal speed in reverse.(Note that not all browsers support * backward playback and even if they do, playback might not be smooth.) * * @method speed * @param {Number} [speed] speed multiplier for element playback * @return {Number|Object|p5.MediaElement} current playback speed or p5.MediaElement */ p5.MediaElement.prototype.speed = function(val) { if (typeof val === 'undefined') { return this.elt.playbackRate; } else { this.elt.playbackRate = val; } }; /** * If no arguments are given, returns the current time of the element. * If an argument is given the current time of the element is set to it. * * @method time * @param {Number} [time] time to jump to (in seconds) * @return {Number|Object|p5.MediaElement} current time (in seconds) * or p5.MediaElement */ p5.MediaElement.prototype.time = function(val) { if (typeof val === 'undefined') { return this.elt.currentTime; } else { this.elt.currentTime = val; } }; /** * Returns the duration of the HTML5 media element. * * @method duration * @return {Number} duration */ p5.MediaElement.prototype.duration = function() { return this.elt.duration; }; p5.MediaElement.prototype.pixels = []; p5.MediaElement.prototype.loadPixels = function() { if (!this.canvas) { this.canvas = document.createElement('canvas'); this.drawingContext = this.canvas.getContext('2d'); } if (this.loadedmetadata) { // wait for metadata for w/h if (this.canvas.width !== this.elt.width) { this.canvas.width = this.elt.width; this.canvas.height = this.elt.height; this.width = this.canvas.width; this.height = this.canvas.height; } this.drawingContext.drawImage(this.elt, 0, 0, this.canvas.width, this.canvas.height); p5.Renderer2D.prototype.loadPixels.call(this); } return this; } p5.MediaElement.prototype.updatePixels = function(x, y, w, h){ if (this.loadedmetadata) { // wait for metadata p5.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); } return this; } p5.MediaElement.prototype.get = function(x, y, w, h){ if (this.loadedmetadata) { // wait for metadata return p5.Renderer2D.prototype.get.call(this, x, y, w, h); } else if (typeof x === 'undefined') { return new p5.Image(1, 1); } else if (w > 1) { return new p5.Image(x, y, w, h); } else { return [0, 0, 0, 255]; } }; p5.MediaElement.prototype.set = function(x, y, imgOrCol){ if (this.loadedmetadata) { // wait for metadata p5.Renderer2D.prototype.set.call(this, x, y, imgOrCol); } }; p5.MediaElement.prototype.copy = function(){ p5.Renderer2D.prototype.copy.apply(this, arguments); }; p5.MediaElement.prototype.mask = function(){ this.loadPixels(); p5.Image.prototype.mask.apply(this, arguments); }; /** * Schedule an event to be called when the audio or video * element reaches the end. If the element is looping, * this will not be called. The element is passed in * as the argument to the onended callback. * * @method onended * @param {Function} callback function to call when the * soundfile has ended. The * media element will be passed * in as the argument to the * callback. * @return {Object|p5.MediaElement} * @example * <div><code> * function setup() { * audioEl = createAudio('assets/beat.mp3'); * audioEl.showControls(true); * audioEl.onended(sayDone); * } * * function sayDone(elt) { * alert('done playing ' + elt.src ); * } * </code></div> */ p5.MediaElement.prototype.onended = function(callback) { this._onended = callback; return this; }; /*** CONNECT TO WEB AUDIO API / p5.sound.js ***/ /** * Send the audio output of this element to a specified audioNode or * p5.sound object. If no element is provided, connects to p5's master * output. That connection is established when this method is first called. * All connections are removed by the .disconnect() method. * * This method is meant to be used with the p5.sound.js addon library. * * @method connect * @param {AudioNode|p5.sound object} audioNode AudioNode from the Web Audio API, * or an object from the p5.sound library */ p5.MediaElement.prototype.connect = function(obj) { var audioContext, masterOutput; // if p5.sound exists, same audio context if (typeof p5.prototype.getAudioContext === 'function') { audioContext = p5.prototype.getAudioContext(); masterOutput = p5.soundOut.input; } else { try { audioContext = obj.context; masterOutput = audioContext.destination } catch(e) { throw 'connect() is meant to be used with Web Audio API or p5.sound.js' } } // create a Web Audio MediaElementAudioSourceNode if none already exists if (!this.audioSourceNode) { this.audioSourceNode = audioContext.createMediaElementSource(this.elt); // connect to master output when this method is first called this.audioSourceNode.connect(masterOutput); } // connect to object if provided if (obj) { if (obj.input) { this.audioSourceNode.connect(obj.input); } else { this.audioSourceNode.connect(obj); } } // otherwise connect to master output of p5.sound / AudioContext else { this.audioSourceNode.connect(masterOutput); } }; /** * Disconnect all Web Audio routing, including to master output. * This is useful if you want to re-route the output through * audio effects, for example. * * @method disconnect */ p5.MediaElement.prototype.disconnect = function() { if (this.audioSourceNode) { this.audioSourceNode.disconnect(); } else { throw 'nothing to disconnect'; } }; /*** SHOW / HIDE CONTROLS ***/ /** * Show the default MediaElement controls, as determined by the web browser. * * @method showControls */ p5.MediaElement.prototype.showControls = function() { // must set style for the element to show on the page this.elt.style['text-align'] = 'inherit'; this.elt.controls = true; }; /** * Hide the default mediaElement controls. * * @method hideControls */ p5.MediaElement.prototype.hideControls = function() { this.elt.controls = false; }; /*** SCHEDULE EVENTS ***/ /** * Schedule events to trigger every time a MediaElement * (audio/video) reaches a playback cue point. * * Accepts a callback function, a time (in seconds) at which to trigger * the callback, and an optional parameter for the callback. * * Time will be passed as the first parameter to the callback function, * and param will be the second parameter. * * * @method addCue * @param {Number} time Time in seconds, relative to this media * element's playback. For example, to trigger * an event every time playback reaches two * seconds, pass in the number 2. This will be * passed as the first parameter to * the callback function. * @param {Function} callback Name of a function that will be * called at the given time. The callback will * receive time and (optionally) param as its * two parameters. * @param {Object} [value] An object to be passed as the * second parameter to the * callback function. * @return {Number} id ID of this cue, * useful for removeCue(id) * @example * <div><code> * function setup() { * background(255,255,255); * * audioEl = createAudio('assets/beat.mp3'); * audioEl.showControls(); * * // schedule three calls to changeBackground * audioEl.addCue(0.5, changeBackground, color(255,0,0) ); * audioEl.addCue(1.0, changeBackground, color(0,255,0) ); * audioEl.addCue(2.5, changeBackground, color(0,0,255) ); * audioEl.addCue(3.0, changeBackground, color(0,255,255) ); * audioEl.addCue(4.2, changeBackground, color(255,255,0) ); * audioEl.addCue(5.0, changeBackground, color(255,255,0) ); * } * * function changeBackground(val) { * background(val); * } * </code></div> */ p5.MediaElement.prototype.addCue = function(time, callback, val) { var id = this._cueIDCounter++; var cue = new Cue(callback, time, id, val); this._cues.push(cue); if (!this.elt.ontimeupdate) { this.elt.ontimeupdate = this._onTimeUpdate.bind(this); } return id; }; /** * Remove a callback based on its ID. The ID is returned by the * addCue method. * * @method removeCue * @param {Number} id ID of the cue, as returned by addCue */ p5.MediaElement.prototype.removeCue = function(id) { for (var i = 0; i < this._cues.length; i++) { if (this._cues[i] === id) { console.log(id) this._cues.splice(i, 1); } } if (this._cues.length === 0) { this.elt.ontimeupdate = null } }; /** * Remove all of the callbacks that had originally been scheduled * via the addCue method. * * @method clearCues */ p5.MediaElement.prototype.clearCues = function() { this._cues = []; this.elt.ontimeupdate = null; }; // private method that checks for cues to be fired if events // have been scheduled using addCue(callback, time). p5.MediaElement.prototype._onTimeUpdate = function() { var playbackTime = this.time(); for (var i = 0 ; i < this._cues.length; i++) { var callbackTime = this._cues[i].time; var val = this._cues[i].val; if (this._prevTime < callbackTime && callbackTime <= playbackTime) { // pass the scheduled callbackTime as parameter to the callback this._cues[i].callback(val); } } this._prevTime = playbackTime; }; // Cue inspired by JavaScript setTimeout, and the // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org var Cue = function(callback, time, id, val) { this.callback = callback; this.time = time; this.id = id; this.val = val; }; // ============================================================================= // p5.File // ============================================================================= /** * Base class for a file * Using this for createFileInput * * @class p5.File * @constructor * @param {File} file File that is wrapped * @param {Object} [pInst] pointer to p5 instance */ p5.File = function(file, pInst) { /** * Underlying File object. All normal File methods can be called on this. * * @property file */ this.file = file; this._pInst = pInst; // Splitting out the file type into two components // This makes determining if image or text etc simpler var typeList = file.type.split('/'); /** * File type (image, text, etc.) * * @property type */ this.type = typeList[0]; /** * File subtype (usually the file extension jpg, png, xml, etc.) * * @property subtype */ this.subtype = typeList[1]; /** * File name * * @property name */ this.name = file.name; /** * File size * * @property size */ this.size = file.size; /** * URL string containing image data. * * @property data */ this.data = undefined; }; }));
dsii-2017-unirsm/dsii-2017-unirsm.github.io
taniasabatini/10PRINT/libraries/p5.dom.js
JavaScript
mit
70,383
import { createStore } from '@utils/store.utils'; import placeholderImage from '../images/placeholder.jpeg'; import { getPhotoUrl, getPrefetchedPhotoForDisplay } from './api'; import { getLocalPhotoPath, getRandomLocalPhoto } from './photos.local'; import Settings from './settings'; export const getStateObject = (force = false) => { const fetchFromServer = Settings.fetchFromServer; const newPhotoDuration = Settings.newPhotoDuration; let photoUrl; let placeholderPhotoUrl; let photoMeta; let placeholderPhotoMeta; // if allowed to fetch from server // begin with assuming we get a // prefetched photo from the api if (fetchFromServer) { photoMeta = getPrefetchedPhotoForDisplay(force ? 0 : newPhotoDuration); photoUrl = getPhotoUrl(photoMeta); } // or a locally stored photo if (!photoUrl) { photoMeta = getRandomLocalPhoto(); photoUrl = getLocalPhotoPath(photoMeta); } // or a fallback placeholder photo if (!photoUrl) { photoMeta = null; photoUrl = placeholderImage; } // get a random image as placeholder // to handle offline network scenarios placeholderPhotoMeta = getRandomLocalPhoto(); placeholderPhotoUrl = getLocalPhotoPath(placeholderPhotoMeta); return { fetchFromServer, photoUrl, photoMeta, placeholderPhotoUrl, placeholderPhotoMeta, newPhotoDuration, }; }; export default createStore();
emadalam/mesmerized
src/modules/background/utils/store.js
JavaScript
mit
1,498
import {Component} from 'react'; import {reduxForm} from 'redux-form'; import './CreateTodoForm.styl'; class CreateTodoForm extends Component { render() { return ( <form className="create-todo-form" onSubmit={this.props.handleSubmit} autoComplete="off"> <input type="text" placeholder="Todo text..." {...this.props.fields.text}></input> <button type="submit">Create</button> </form> ); } } CreateTodoForm.propTypes = { fields: React.PropTypes.object.isRequired, handleSubmit: React.PropTypes.func.isRequired }; export default reduxForm({ form: 'CreateTodoForm', fields: ['text'] })(CreateTodoForm);
malykhinvi/generator-spa
generators/app/templates/src/pages/TodosPage/CreateTodoForm.js
JavaScript
mit
651
import React, { useState, useRef } from 'react'; import { computeOutOffsetByIndex, computeInOffsetByIndex } from './lib/Util'; // import { SVGComponent } from './lib-hooks/svgComp-hooks'; import Spline from './lib/Spline'; import DragNode from './lib/Node'; const index = ({ data, onNodeDeselect, onNodeMove, onNodeStartMove, onNodeSelect, onNewConnector, onRemoveConnector }) => { const [dataS, setDataS] = useState(data); const [source, setSource] = useState([]); const [dragging, setDragging] = useState(false); const [mousePos, setMousePos] = useState({x: 0, y: 0}); const svgRef = useRef(); const onMouseMove = e => { let [pX, pY] = [e.clientX, e.clientY]; e.stopPropagation(); e.preventDefault(); const svgRect = svgRef.current.getBoundingClientRect(); // console.log(svgRect); setMousePos(old => { return { ...old, ...{x: pX - svgRect.left, y: pY - svgRect.top} } }); } const onMouseUp = e => { setDragging(false); } const handleNodeStart = nid => { onNodeStartMove(nid); } const handleNodeStop = (nid, pos) => { onNodeMove(nid, pos); } const handleNodeMove = (idx, pos) => { let dataT = dataS; dataT.nodes[idx].x = pos.x; dataT.nodes[idx].y = pos.y; // console.log(dataT); // console.log({...dataS,...dataT}); setDataS(old => { return { ...old, ...dataT } }); } const handleStartConnector = (nid, outputIdx) => { let newSrc = [nid, outputIdx]; setDragging(true); setSource(newSrc); // Not sure if this will work... } const handleCompleteConnector = (nid, inputIdx) => { if (dragging) { let fromNode = getNodeById(data.nodes, source[0]); let fromPinName = fromNode.fields.out[source[1]].name; let toNode = getNodeById(data.nodes, nid); let toPinName = toNode.fields.in[inputIdx].name; onNewConnector(fromNode.nid, fromPinName, toNode.nid, toPinName); } setDragging(false); } const handleRemoveConnector = connector => { if (onRemoveConnector) { onRemoveConnector(connector); } } const handleNodeSelect = nid => { if (onNodeSelect) { onNodeSelect(nid); } } const handleNodeDeselect = nid => { if (onNodeDeselect) { onNodeDeselect(nid); } } const computePinIdxfromLabel = (pins, pinLabel) => { let reval = 0; for (let pin of pins) { if (pin.name === pinLabel) { return reval; } else { reval++; } } } const getNodeById = (nodes, nid) => { let reval = 0; for(const node of nodes) { if (node.nid === nid) { return nodes[reval]; } else { reval++; } } } let newConn = null; let i = 0; // console.log(dragging); if (dragging) { let sourceNode = getNodeById(dataS.nodes, source[0]); let connectorStart = computeOutOffsetByIndex(sourceNode.x, sourceNode.y, source[1]); let connectorEnd = { x: mousePos.x, y: mousePos.y }; // console.log(mousePos); newConn = <Spline start={connectorStart} end={connectorEnd} /> } let splineIdx = 0; return ( <div className={dragging ? 'dragging' : ''} onMouseMove={onMouseMove} onMouseUp={onMouseUp} > {dataS.nodes.map(node => { // console.log(node); return <DragNode index={i++} nid={node.nid} title={node.type} inputs={node.fields.in} outputs={node.fields.out} pos={{x: node.x, y: node.y}} key={node.nid} onNodeStart={nid => handleNodeStart(nid)} onNodeStop={(nid, pos) => handleNodeStop(nid, pos)} onNodeMove={(idx, pos) => handleNodeMove(idx, pos)} onStartConnector={(nid, outputIdx) => handleStartConnector(nid, outputIdx)} onCompleteConnector={(nid, inputIdx) => handleCompleteConnector(nid, inputIdx)} onNodeSelect={nid => handleNodeSelect(nid)} onNodeDeselect={nid => handleNodeDeselect(nid)} /> })} <svg style={{position: 'absolute', height: "100%", width: "100%", zIndex: 9000}} ref={svgRef}> {data.connections.map(connector => { // console.log(data); // console.log(connector); let fromNode = getNodeById(data.nodes, connector.from_node); let toNode = getNodeById(data.nodes, connector.to_node); let splinestart = computeOutOffsetByIndex(fromNode.x, fromNode.y, computePinIdxfromLabel(fromNode.fields.out, connector.from)); let splineend = computeInOffsetByIndex(toNode.x, toNode.y, computePinIdxfromLabel(toNode.fields.in, connector.to)); return <Spline start={splinestart} end={splineend} key={splineIdx++} mousePos={mousePos} onRemove={() => handleRemoveConnector(connector)} /> })} {newConn} </svg> </div> ); } export default index;
lightsinthesky/react-node-graph
index.js
JavaScript
mit
6,053
var t = require('chai').assert; var P = require('bluebird'); var Renderer = require('../').Renderer; var view = { "name": { "first": "Michael", "last": "Jackson" }, "age": "RIP", calc: function () { return 2 + 4; }, delayed: function () { return new P(function (resolve) { setTimeout(resolve.bind(undefined, 'foo'), 100); }); } }; describe('Renderer', function () { describe('Basics features', function () { it('should render properties', function (done) { var renderer = new Renderer(); renderer.render('Hello {{name.first}} {{name.last}}', { "name": { "first": "Michael", "last": "Jackson" } }).then(function (result) { t.equal(result, 'Hello Michael Jackson'); done(); }) }); it('should render variables', function (done) { var renderer = new Renderer(); renderer.render('* {{name}} * {{age}} * {{company}} * {{{company}}} * {{&company}}{{=<% %>=}} * {{company}}<%={{ }}=%>', { "name": "Chris", "company": "<b>GitHub</b>" }).then(function (result) { t.equal(result, '* Chris * * &lt;b&gt;GitHub&lt;&#x2F;b&gt; * <b>GitHub</b> * <b>GitHub</b> * {{company}}'); done(); }) }); it('should render variables with dot notation', function (done) { var renderer = new Renderer(); renderer.render('{{name.first}} {{name.last}} {{age}}', { "name": { "first": "Michael", "last": "Jackson" }, "age": "RIP" }).then(function (result) { t.equal(result, 'Michael Jackson RIP'); done(); }) }); it('should render sections with false values or empty lists', function (done) { var renderer = new Renderer(); renderer.render('Shown. {{#person}}Never shown!{{/person}}', { "person": false }).then(function (result) { t.equal(result, 'Shown. '); done(); }) }); it('should render sections with non-empty lists', function (done) { var renderer = new Renderer(); renderer.render('{{#stooges}}<b>{{name}}</b>{{/stooges}}', { "stooges": [ {"name": "Moe"}, {"name": "Larry"}, {"name": "Curly"} ] }).then(function (result) { t.equal(result, '<b>Moe</b><b>Larry</b><b>Curly</b>'); done(); }) }); it('should render sections using . for array of strings', function (done) { var renderer = new Renderer(); renderer.render('{{#musketeers}}* {{.}}{{/musketeers}}', { "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] }).then(function (result) { t.equal(result, '* Athos* Aramis* Porthos* D&#39;Artagnan'); done(); }) }); it('should render function', function (done) { var renderer = new Renderer(); renderer.render('{{title}} spends {{calc}}', { title: "Joe", calc: function () { return 2 + 4; } }).then(function (result) { t.equal(result, 'Joe spends 6'); done(); }) }); it('should render function with variable as context', function (done) { var renderer = new Renderer(); renderer.render('{{#beatles}}* {{name}} {{/beatles}}', { "beatles": [ {"firstName": "John", "lastName": "Lennon"}, {"firstName": "Paul", "lastName": "McCartney"}, {"firstName": "George", "lastName": "Harrison"}, {"firstName": "Ringo", "lastName": "Starr"} ], "name": function () { return this.firstName + " " + this.lastName; } }).then(function (result) { t.equal(result, '* John Lennon * Paul McCartney * George Harrison * Ringo Starr '); done(); }) }); it('should render inverted sections', function (done) { var renderer = new Renderer(); renderer.render('{{#repos}}<b>{{name}}</b>{{/repos}}{{^repos}}No repos :({{/repos}}', { "repos": [] }).then(function (result) { t.equal(result, 'No repos :('); done(); }) }); it('should render ignore comments', function (done) { var renderer = new Renderer(); renderer.render('Today{{! ignore me }}.').then(function (result) { t.equal(result, 'Today.'); done(); }) }); it('should render partials', function (done) { var renderer = new Renderer(); renderer.render('{{#names}}{{> user}}{{/names}}', { names: [{ name: 'Athos' }, { name: 'Porthos' }] }, { user: 'Hello {{name}}.' }).then(function (result) { t.equal(result, 'Hello Athos.Hello Porthos.'); done(); }) }); }); describe('Promise functions', function () { it('should render with promise functions', function (done) { var renderer = new Renderer(); renderer.render('3+5={{#add}}[3,5]{{/add}}', { add: function (a, b) { return new P(function (resolve) { setTimeout(function () { resolve(a + b); }, 100); }) } }).then(function (result) { t.equal(result, '3+5=8'); done(); }); }); }); describe('Custom view', function () { function View() { this.buffer = []; this.text = function (text) { this.buffer.push(text); return this; }; this.write = function (i) { this.buffer.push(i); return this; }; } it('should render with custom view', function (done) { var view = new View(); var renderer = new Renderer(); renderer.render('The number is:{{#write}}1{{/write}}', view).then(function (result) { t.notOk(result); t.deepEqual(view.buffer, ['The number is:', 1]); done(); }) }); }); }) ;
taoyuan/mustem
test/renderer.test.js
JavaScript
mit
5,908
/** * Pre Tests * Check to make sure jQuery and Zest are loaded */ module("Setup"); test("jQuery is loaded", function() { expect(3); ok( jQuery, "jQuery is defined." ); ok( $, "$ is defined."); equal( typeof jQuery, "function", "jQuery is a function." ); }); test("Zest is loaded", function() { expect(3); ok( Zest, "Zest is defined." ); ok( Z$, "Z$ is defined." ); equal( typeof Zest, "function", "Zest is a function." ); });
ItsJonQ/zest
test/units/setup.js
JavaScript
mit
518
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Task = mongoose.model('Task'), Project = mongoose.model('Project'), Person = mongoose.model('Person'), _ = require('lodash'); /** * Create a Task */ var person, project; exports.createTask = function(req, res) { var task = new Task(req.body); task.user = req.user; Person.findById(req.body.personId).exec(function(err, person_object) { person = person_object; Project.findById(req.body.projectId).exec(function(err, project_object) { project = project_object; task.projectName = project.name; task.personName = person.name; task.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { person.tasks.push(task); person.save(); project.tasks.push(task); project.save(); res.jsonp(task); } }); }); }); }; /** * Show the current Task */ exports.readTask = function(req, res) { res.jsonp(req.task); }; /** * Update a Task */ exports.updateTask = function(req, res) { var task = req.task; task = _.extend(task, req.body); task.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(task); } }); }; /** * Delete an Task */ exports.deleteTask = function(req, res) { var task = req.task; Project.findById(req.task.project).exec(function(err, project) { if (project && project.tasks) { var i = project.tasks.indexOf(task._id); project.tasks.splice(i, 1); project.save(); } }); Person.findById(req.task.person).exec(function(err, person) { if (person && person.tasks) { var i = person.tasks.indexOf(task._id); person.tasks.splice(i, 1); person.save(); } }); task.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(task); } }); }; /** * List of Tasks */ exports.listTasks = function(req, res) { Task.find({'user':req.user._id}).sort('-created').populate('person', 'name').populate('project', 'name').exec(function(err, tasks) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(tasks); } }); }; /** * Task middleware */ exports.taskByID = function(req, res, next, id) { Task.findById(id).populate('user', 'username').exec(function(err, task) { if (err) return next(err); if (!task) return next(new Error('Failed to load Task ' + id)); req.task = task; next(); }); }; /** * Task authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.task.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
andela-ajayeoba/Calendarize
app/controllers/tasks.server.controller.js
JavaScript
mit
3,108
// angular.module is a global place for creating, registering and retrieving Angular modules // 'directory' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'directory.services' is found in services.js // 'directory.controllers' is found in controllers.js angular.module('directory', ['ionic', 'directory.controllers', 'ionic.contrib.ui.cards']) .config(function ($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider .state('landing', { url: '/landing', templateUrl: 'templates/index.html', controller: 'FbCtrl' }) .state('profilec', { url: '/createProfile', templateUrl: 'templates/profilec.html', controller: 'ProfileCtrl' }) .state('matches', { url: '/matches', templateUrl: 'templates/matches.html', controller: 'TestCtrl' }) .state('food', { url: '/restaurants', templateUrl: 'templates/restaurants.html', controller: 'RecCtrl' }) .state('chat', { url: '/chat', templateUrl: 'templates/chat.html', controller: 'ChatCtrl' }) .state('home', { url: '/home', templateUrl: 'templates/home.html', controller: 'DocCtrl' }) .state('stats', { url: '/stats', templateUrl: 'templates/stats.html', controller: 'DocCtrl' }) .state('graphs', { url: '/graphs', templateUrl: 'templates/graphs.html', controller: 'GraphCtrl' }) .state('doc-index', { url: '/docs', templateUrl: 'templates/doc-index.html', controller: 'DocCtrl' }) .state('doc-detail', { url: '/doclist/:doclistId', templateUrl: 'templates/doc-detail.html', controller: 'DocCtrl' }); /*.state('employee-index', { url: '/employees', templateUrl: 'templates/employee-index.html', controller: 'EmployeeIndexCtrl' }) .state('employee-detail', { url: '/employee/:employeeId', templateUrl: 'templates/employee-detail.html', controller: 'EmployeeDetailCtrl' }) .state('employee-reports', { url: '/employee/:employeeId/reports', templateUrl: 'templates/employee-reports.html', controller: 'EmployeeReportsCtrl' }); */ // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('landing'); });
zzeleznick/zzeleznick.github.io
hackerlove/main/www/js/app.js
JavaScript
mit
3,330
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; import { get } from '@ember/object'; export default Route.extend({ ajax: service(), model() { return get(this, 'ajax').request( 'https://api.github.com/repos/ember-cli/ember-ajax/commits', { headers: { 'User-Agent': 'Ember AJAX Testing' } } ); } });
ember-cli/ember-ajax
tests/dummy/app/routes/commits.js
JavaScript
mit
404
const fs = require('fs'); class Loader { static extend (name, loader) { return { name, loader }; } static get (name, options) { const item = options.loaders.find((loader) => name === loader.name); if (!item) { throw new Error(`Missing loader for ${name}`); } return item.loader; } static getFileContent (filename, options) { return fs.readFileSync(filename, options).toString(); } constructor (options) { this.options = options; } /* istanbul ignore next */ /* eslint-disable-next-line class-methods-use-this */ load () { throw new Error('Cannot call abstract Loader.load() method'); } emitTemplate (source) { this.options.source.template = source || ''; return Promise.resolve(); } emitScript (source) { this.options.source.script = source || ''; return Promise.resolve(); } emitErrors (errors) { this.options.source.errors.push(...errors); return Promise.resolve(); } pipe (name, source) { const LoaderClass = Loader.get(name, this.options); return new LoaderClass(this.options).load(source); } } module.exports = Loader;
vuedoc/parser
lib/Loader.js
JavaScript
mit
1,150
/** * @license angular-sortable-column * (c) 2013 Knight Rider Consulting, Inc. http://www.knightrider.com * License: MIT */ /** * * @author Dale "Ducky" Lotts * @since 7/21/13 */ basePath = '..'; files = [ JASMINE, JASMINE_ADAPTER, 'bower_components/jquery/dist/jquery.js', 'bower_components/angular/angular.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-mocks/angular-mocks.js', 'src/js/sortableColumn.js', 'test/*.spec.js' ]; // list of files to exclude exclude = [ ]; preprocessors = { '**/src/js/*.js': 'coverage' }; // test results reporter to use // possible values: 'dots', 'progress', 'junit' reporters = ['progress', 'coverage']; // web server port port = 9876; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_INFO; // enable / disable watching file and executing tests whenever any file changes autoWatch = false; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers = ['Chrome']; // If browser does not capture in given timeout [ms], kill it captureTimeout = 60000; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = true;
dalelotts/angular-sortable-column
test/test.conf.js
JavaScript
mit
1,481
const storage = require("./storage"); const recognition = require("./recognition"); async function labelPictures(bucketName) { const bucket = await storage.getOrCreateBucket(bucketName); const fileNames = await storage.ls(bucket); for (const file of fileNames) { console.log(`Retrieve labels for file ${file.name}`); try { const labels = await recognition.getLabels(file.metadata.mediaLink); const metadata = { metadata: { labels: JSON.stringify(labels) } }; console.log(`Set metadata for file ${file.name}`); await storage.setMetadata(file, metadata); } catch (ex) { console.warn("Failed to set metadata for file ${file.name}", ex); } } } async function main(bucketName) { try { await labelPictures(bucketName); } catch (error) { console.error(error); } } if (process.argv.length < 3) { throw new Error("Please specify a bucket name"); } main(process.argv[2]);
zack17/klio-picture-labeler
labler.js
JavaScript
mit
1,072
'use strict'; describe('TestComponent', function () { var componentController; beforeEach(module('APPLICATION')); beforeEach(inject(function ($componentController) { componentController = $componentController('testComponent', null, { test: { data: 'data' } }); })); it('is defined', function () { expect(componentController).toBeDefined(); }); describe('when called', function () { it('modifyTestData modifies test data', function () { componentController.data = 'data'; componentController.modifyTestData(); expect(componentController.data).toBe(' edited in the component controller'); }); }); });
tomtomssi/AngularTemplate
app/component/test_component/TestComponent.spec.js
JavaScript
mit
754
import Ember from 'ember'; export default Ember.Controller.extend({ resume: Ember.inject.controller(), actions: { scrollToElem: function(selector) { this.get('resume').send('scrollToElem', selector); }, selectTemplate: function(template) { this.get('resume').send('selectTemplate', template); }, selectPalette: function(palette) { this.get('resume').send('selectPalette', palette); } } });
iorrah/you-rockstar
app/controllers/resume/index.js
JavaScript
mit
439
process.env.NODE_ENV = 'test'; const chai = require('chai'); const chaiHttp = require('chai-http'); const should = chai.should(); const CostCalculator = require("../libs/costcalculator"); describe('Calculate Cost', () => { describe("Book Meeting Room", () => { it("it should calcuate cost for meeting room for 30m", async (done) => { try { let result = await CostCalculator("5bd7283ebfc02163c7b4d5d7", new Date("2020-01-01T09:00:00"), new Date("2020-01-01T09:30:00")); result.should.equal(2.8); done(); } catch(err) { done(err); } }); }); });
10layer/jexpress
test/costcalculator.js
JavaScript
mit
675
module.exports = { // Token you get from discord "token": "", // Prefix before your commands "prefix": "", // Port for webserver (Not working) "port": 8080, // Mongodb stuff "mongodb": { // Mongodb uri "uri": "" }, // Channel IDs "channelIDs": { // Where to announce the events in ACCF "events": "", // Where to announce online towns "onlineTowns": "", // Where to log the logs "logs": "" } }
rey2952/RoverBot
config.js
JavaScript
mit
455
Object.prototype.getKeyByValue = function( value ) { for( var prop in this ) { if( this.hasOwnProperty( prop ) ) { if( this[ prop ] === value ) return prop; } } }
tametheboardgame/tametheboardgame.github.io
CrushTheCrown/tools.js
JavaScript
mit
217
require('./ramda-mori')
fractalPlatform/Fractal.js
tests/index.js
JavaScript
mit
24
/*istanbul ignore next*/'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var _request2 = require('request'); var _request3 = _interopRequireDefault(_request2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * A set of utlity methods. * @abstract */ var EgoJSUtils = (function () { function EgoJSUtils() { _classCallCheck(this, EgoJSUtils); } _createClass(EgoJSUtils, null, [{ key: '_fullfilledPromise', /** * Returns an already fullfilled promise with a given value. * @param {bollean} success - Whether to call `resolve` or `reject`. * @param {*} response - The object to resolve or reject. * @return {Promise<*,*>} * @private * @ignore */ value: function _fullfilledPromise(success, response) { return new Promise(function (resolve, reject) { if (success) { resolve(response); } else { reject(response); } }); } /** * Returns an already rejected promise. * @example * EgoJSUtils.rejectedPromise('error message').catch((e) => { * // It will log 'error message' * console.log(e); * }); * * @param {*} response - The object to send to the `.catch` method. * @return {Promise<null, *>} This promise won't call `.then` but `.catch` directly. */ }, { key: 'rejectedPromise', value: function rejectedPromise(response) { return this._fullfilledPromise(false, response); } /** * Returns an already resolved promise. * @example * EgoJSUtils.rejectedPromise('hello world').then((message) => { * // It will log 'hello world' * console.log(message); * }); * * @param {*} response - The object to send to the `.then` method. * @return {Promise<*, null>} This promise won't call `.catch`. */ }, { key: 'resolvedPromise', value: function resolvedPromise(response) { return this._fullfilledPromise(true, response); } /** * It will merge a given list of Objects into a new one. It works recursively, so any "sub * objects" will also be merged. This method returns a new Object, so none of the targets will * be modified. * @example * const a = { * b: 'c', * d: { * e: 'f', * g: { * h: ['i'], * }, * }, * j: 'k', * }; * const b = { * j: 'key', * d: { * g: { * h: ['x', 'y', 'z'], * l: 'm', * }, * }, * }; * // The result will be * // { * // b: 'c', * // d: { * // e: 'f', * // g: { * // h: ['x', 'y', 'z'], * // l: 'm', * // }, * // }, * // j: 'key', * // } * ._mergeObjects(a, b); * * @param {...Object} objects - The list of objects to merge. * @return {Object} A new object with the merged properties. */ }, { key: 'mergeObjects', value: function mergeObjects() { /*istanbul ignore next*/ var _this = this; var result = {}; /*istanbul ignore next*/ for (var _len = arguments.length, objects = Array(_len), _key = 0; _key < _len; _key++) { objects[_key] = arguments[_key]; } objects.forEach(function (obj) { if (typeof obj !== 'undefined') { Object.keys(obj).forEach(function (objKey) { var current = obj[objKey]; var target = result[objKey]; if (typeof target !== 'undefined' && current.constructor === Object && target.constructor === Object) { result[objKey] = /*istanbul ignore next*/_this.mergeObjects(target, current); } else { result[objKey] = current; } }, /*istanbul ignore next*/_this); } }, this); return result; } /** * Wraps a Request call into a Promise. * @example * request({uri: 'https://homer0.com/rosario'}) * .then((response) => doSomething(response)) * .catch((err) => handleErrors(err)); * * @param {Object} data The request settings. The same you would use with request(). * @return {Promise<Object, Error>} It will be resolved or rejected depending on the response. */ }, { key: 'request', value: function request(data) { return new Promise(function (resolve, reject) { /*istanbul ignore next*/(0, _request3.default)(data, function (err, httpResponse, body) { if (err) { reject(err); } else { resolve(body); } }); }); } }]); return EgoJSUtils; })(); /*istanbul ignore next*/exports.default = EgoJSUtils;
homer0/egojs
dist/utils.js
JavaScript
mit
6,397
// shexmap-simple - Simple ShEx2 validator for HTML. // Copyright 2017 Eric Prud'hommeux // Release under MIT License. const ShEx = ShExWebApp; // @@ rename globally const ShExJsUrl = 'https://github.com/shexSpec/shex.js' const RdfJs = N3js; const ShExApi = ShEx.Api({ fetch: window.fetch.bind(window), rdfjs: RdfJs, jsonld: null }) const MapModule = ShEx.Map({rdfjs: RdfJs, Validator: ShEx.Validator}); ShEx.ShapeMap.start = ShEx.Validator.start const SharedForTests = {} // an object to share state with a test harness const START_SHAPE_LABEL = "START"; const START_SHAPE_INDEX_ENTRY = "- start -"; // specificially not a JSON-LD @id form. const INPUTAREA_TIMEOUT = 250; const NO_MANIFEST_LOADED = "no manifest loaded"; const LOG_PROGRESS = false; const DefaultBase = location.origin + location.pathname; const Caches = {}; Caches.inputSchema = makeSchemaCache($("#inputSchema textarea.schema")); Caches.inputData = makeTurtleCache($("#inputData textarea")); Caches.manifest = makeManifestCache($("#manifestDrop")); Caches.extension = makeExtensionCache($("#extensionDrop")); Caches.shapeMap = makeShapeMapCache($("#textMap")); // @@ rename to #shapeMap Caches.bindings = makeJSONCache($("#bindings1 textarea")); Caches.statics = makeJSONCache($("#staticVars textarea")); Caches.outputSchema = makeSchemaCache($("#outputSchema textarea")); // let ShExRSchema; // defined in calling page const ParseTriplePattern = (function () { const uri = "<[^>]*>|[a-zA-Z0-9_-]*:[a-zA-Z0-9_-]*"; const literal = "((?:" + "'(?:[^'\\\\]|\\\\')*'" + "|" + "\"(?:[^\"\\\\]|\\\\\")*\"" + "|" + "'''(?:(?:'|'')?[^'\\\\]|\\\\')*'''" + "|" + "\"\"\"(?:(?:\"|\"\")?[^\"\\\\]|\\\\\")*\"\"\"" + ")" + "(?:@[a-zA-Z-]+|\\^\\^(?:" + uri + "))?)"; const uriOrKey = uri + "|FOCUS|_"; // const termOrKey = uri + "|" + literal + "|FOCUS|_"; return "(\\s*{\\s*)("+ uriOrKey+")?(\\s*)("+ uri+"|a)?(\\s*)("+ uriOrKey+"|" + literal + ")?(\\s*)(})?(\\s*)"; })(); const Getables = [ {queryStringParm: "schema", location: Caches.inputSchema.selection, cache: Caches.inputSchema}, {queryStringParm: "data", location: Caches.inputData.selection, cache: Caches.inputData }, {queryStringParm: "manifest", location: Caches.manifest.selection, cache: Caches.manifest , fail: e => $("#manifestDrop li").text(NO_MANIFEST_LOADED)}, {queryStringParm: "extension", location: Caches.extension.selection, cache: Caches.extension }, {queryStringParm: "shape-map", location: $("#textMap"), cache: Caches.shapeMap }, {queryStringParm: "bindings", location: Caches.bindings.selection, cache: Caches.bindings }, {queryStringParm: "statics", location: Caches.statics.selection, cache: Caches.statics }, {queryStringParm: "outSchema", location: Caches.outputSchema.selection,cache: Caches.outputSchema}, ]; const QueryParams = Getables.concat([ {queryStringParm: "interface", location: $("#interface"), deflt: "human" }, {queryStringParm: "success", location: $("#success"), deflt: "proof" }, {queryStringParm: "regexpEngine", location: $("#regexpEngine"), deflt: "eval-threaded-nerr" }, ]); // utility functions function parseTurtle (text, meta, base) { const ret = new RdfJs.Store(); RdfJs.Parser._resetBlankNodePrefix(); const parser = new RdfJs.Parser({baseIRI: base, format: "text/turtle" }); const quads = parser.parse(text); if (quads !== undefined) ret.addQuads(quads); meta.base = parser._base; meta.prefixes = parser._prefixes; return ret; } const shexParser = ShEx.Parser.construct(DefaultBase, null, {index: true}); function parseShEx (text, meta, base) { shexParser._setOptions({duplicateShape: $("#duplicateShape").val()}); shexParser._setBase(base); const ret = shexParser.parse(text); // ret = ShEx.Util.canonicalize(ret, DefaultBase); meta.base = ret._base; // base set above. meta.prefixes = ret._prefixes || {}; // @@ revisit after separating shexj from meta and indexes return ret; } function sum (s) { // cheap way to identify identical strings return s.replace(/\s/g, "").split("").reduce(function (a,b){ a = ((a<<5) - a) + b.charCodeAt(0); return a&a },0); } // <n3.js-specific> function rdflib_termToLex (node, resolver) { if (node === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type") return "a"; if (node === ShEx.Validator.start) return START_SHAPE_LABEL; if (node === resolver._base) return "<>"; if (node.indexOf(resolver._base) === 0/* && ['#', '?'].indexOf(node.substr(resolver._base.length)) !== -1 */) return "<" + node.substr(resolver._base.length) + ">"; if (node.indexOf(resolver._basePath) === 0 && ['#', '?', '/', '\\'].indexOf(node.substr(resolver._basePath.length)) === -1) return "<" + node.substr(resolver._basePath.length) + ">"; return ShEx.ShExTerm.intermalTermToTurtle(node, resolver.meta.base, resolver.meta.prefixes); } function rdflib_lexToTerm (lex, resolver) { return lex === START_SHAPE_LABEL ? ShEx.Validator.start : lex === "a" ? "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" : new RdfJs.Lexer().tokenize(lex + " ") // need " " to parse "chat"@en .map(token => { const left = token.type === "typeIRI" ? "^^" : token.type === "langcode" ? "@" : token.type === "type" ? "^^" + resolver.meta.prefixes[token.prefix] : token.type === "prefixed" ? resolver.meta.prefixes[token.prefix] : token.type === "blank" ? "_:" : ""; const right = token.type === "IRI" || token.type === "typeIRI" ? resolver._resolveAbsoluteIRI(token) : token.value; return left + right; }).join(""); return lex === ShEx.Validator.start ? lex : lex[0] === "<" ? lex.substr(1, lex.length - 2) : lex; } // </n3.js-specific> // caches for textarea parsers function _makeCache (selection) { let _dirty = true; const ret = { selection: selection, parsed: null, // a Promise meta: { prefixes: {}, base: DefaultBase }, dirty: function (newVal) { const ret = _dirty; _dirty = newVal; return ret; }, get: function () { return selection.val(); }, set: async function (text, base) { _dirty = true; selection.val(text); this.meta.base = base; if (base !== DefaultBase) { this.url = base; // @@crappyHack1 -- parms should differntiate: // working base: base for URL resolution. // loaded base: place where you can GET current doc. // Note that Caches.manifest.set takes a 3rd parm. } }, refresh: async function () { if (!_dirty) return this.parsed; this.parsed = await this.parse(selection.val(), this.meta.base); await this.parsed; _dirty = false; return this.parsed; }, asyncGet: async function (url) { url = new URL(url, window.location).href const _cache = this; let resp try { resp = await fetch(url, {headers: { accept: 'text/shex,text/turtle,*/*;q=0.9, test/html;q=0.8', cache: 'no-cache' }}) } catch (e) { throw Error("unable to fetch <" + url + ">: " + '\n' + e.message); } if (!resp.ok) throw Error("fetch <" + url + "> got error response " + resp.status + ": " + resp.statusText); const data = await resp.text(); _cache.meta.base = url; try { await _cache.set(data, url, undefined, resp.headers.get('content-type')); } catch (e) { throw Error("error setting " + this.queryStringParm + " with <" + url + ">: " + '\n' + e.message); } $("#loadForm").dialog("close"); toggleControls(); return { url: url, data: data }; }, url: undefined // only set if inputarea caches some web resource. }; ret.meta.termToLex = function (trm) { return rdflib_termToLex(trm, new IRIResolver(ret.meta)); }; ret.meta.lexToTerm = function (lex) { return rdflib_lexToTerm(lex, new IRIResolver(ret.meta)); }; return ret; } function makeSchemaCache (selection) { const ret = _makeCache(selection); let graph = null; ret.language = null; ret.parse = async function (text, base) { const isJSON = text.match(/^\s*\{/); graph = isJSON ? null : tryN3(text); this.language = isJSON ? "ShExJ" : graph ? "ShExR" : "ShExC"; $("#results .status").text("parsing "+this.language+" schema...").show(); const schema = isJSON ? ShEx.Util.ShExJtoAS(JSON.parse(text)) : graph ? parseShExR() : parseShEx(text, ret.meta, base); $("#results .status").hide(); markEditMapDirty(); // ShapeMap validity may have changed. return schema; function tryN3 (text) { try { if (text.match(/^\s*$/)) return null; const db = parseTurtle (text, ret.meta, DefaultBase); // interpret empty schema as ShExC if (db.getQuads().length === 0) return null; return db; } catch (e) { return null; } } function parseShExR () { const graphParser = ShEx.Validator.construct( parseShEx(ShExRSchema, {}, base), // !! do something useful with the meta parm (prefixes and base) ShEx.Util.rdfjsDB(graph), {} ); const schemaRoot = graph.getQuads(null, ShEx.Util.RDF.type, "http://www.w3.org/ns/shex#Schema")[0].subject; // !!check const val = graphParser.validate(schemaRoot, ShEx.Validator.start); // start shape return ShEx.Util.ShExJtoAS(ShEx.Util.ShExRtoShExJ(ShEx.Util.valuesToSchema(ShEx.Util.valToValues(val)))); } }; ret.getItems = async function () { const obj = await this.refresh(); const start = "start" in obj ? [START_SHAPE_LABEL] : []; const rest = "shapes" in obj ? obj.shapes.map(se => Caches.inputSchema.meta.termToLex(se.id)) : []; return start.concat(rest); }; return ret; } function makeTurtleCache (selection) { const ret = _makeCache(selection); ret.parse = async function (text, base) { const res = ShEx.Util.rdfjsDB(parseTurtle(text, ret.meta, base)); markEditMapDirty(); // ShapeMap validity may have changed. return res; }; ret.getItems = async function () { const data = await this.refresh(); return data.getQuads().map(t => { return Caches.inputData.meta.termToLex(t.subject); // !!check }); }; return ret; } function makeManifestCache (selection) { const ret = _makeCache(selection); ret.set = async function (textOrObj, url, source) { $("#inputSchema .manifest li").remove(); $("#inputData .passes li, #inputData .fails li").remove(); if (typeof textOrObj !== "object") { if (url !== DefaultBase) { this.url = url; // @@crappyHack1 -- parms should differntiate: } try { // exceptions pass through to caller (asyncGet) textOrObj = JSON.parse(textOrObj); } catch (e) { $("#inputSchema .manifest").append($("<li/>").text(NO_MANIFEST_LOADED)); const throwMe = Error(e + '\n' + textOrObj); throwMe.action = 'load manifest' throw throwMe // @@DELME(2017-12-29) // transform deprecated examples.js structure // textOrObj = eval(textOrObj).reduce(function (acc, schema) { // function x (data, status) { // return { // schemaLabel: schema.name, // schema: schema.schema, // dataLabel: data.name, // data: data.data, // queryMap: data.queryMap, // outputSchema: data.outputSchema, // outputShape: data.outputShape, // staticVars: data.staticVars, // createRoot: data.createRoot, // status: status // }; // } // return acc.concat( // schema.passes.map(data => x(data, "conformant")), // schema.fails.map(data => x(data, "nonconformant")) // ); // }, []); } } if (!Array.isArray(textOrObj)) textOrObj = [textOrObj]; const demos = textOrObj.reduce((acc, elt) => { if ("action" in elt) { // compatibility with test suite structure. const action = elt.action; let schemaLabel = action.schema.substr(action.schema.lastIndexOf('/')+1); let dataLabel = elt["@id"]; let match = null; const emptyGraph = "-- empty graph --"; if ("comment" in elt) { if ((match = elt.comment.match(/^(.*?) \/ { (.*?) }$/))) { schemaLabel = match[1]; dataLabel = match[2] || emptyGraph; } else if ((match = elt.comment.match(/^(.*?) on { (.*?) }$/))) { schemaLabel = match[1]; dataLabel = match[2] || emptyGraph; } else if ((match = elt.comment.match(/^(.*?) as { (.*?) }$/))) { schemaLabel = match[2]; dataLabel = match[1] || emptyGraph; } } const queryMap = "map" in action ? null : ldToTurtle(action.focus, Caches.inputData.meta.termToLex) + "@" + ("shape" in action ? ldToTurtle(action.shape, Caches.inputSchema.meta.termToLex) : START_SHAPE_LABEL); const queryMapURL = "map" in action ? action.map : null; elt = Object.assign( { schemaLabel: schemaLabel, schemaURL: action.schema || url, // dataLabel: "comment" in elt ? elt.comment : (queryMap || dataURL), dataLabel: dataLabel, dataURL: action.data || DefaultBase }, (queryMap ? { queryMap: queryMap } : { queryMapURL: queryMapURL }), { status: elt["@type"] === "sht:ValidationFailure" ? "nonconformant" : "conformant" } ); if ("termResolver" in action || "termResolverURL" in action) { elt.meta = action.termResolver; elt.metaURL = action.termResolverURL || DefaultBase; } } ["schemaURL", "dataURL", "queryMapURL"].forEach(parm => { if (parm in elt) { elt[parm] = new URL(elt[parm], new URL(url, DefaultBase).href).href; } else { delete elt[parm]; } }); return acc.concat(elt); }, []); await prepareManifest(demos, url); $("#manifestDrop").show(); // may have been hidden if no manifest loaded. }; ret.parse = async function (text, base) { throw Error("should not try to parse manifest cache"); }; ret.getItems = async function () { throw Error("should not try to get manifest cache items"); }; return ret; function maybeGET(obj, base, key, accept) { // !!not used if (obj[key] != null) { // Take the passed data, guess base if not provided. if (!(key + "URL" in obj)) obj[key + "URL"] = base; obj[key] = Promise.resolve(obj[key]); } else if (key + "URL" in obj) { // absolutize the URL obj[key + "URL"] = ret.meta.lexToTerm("<"+obj[key + "URL"]+">"); // Load the remote resource. obj[key] = new Promise((resolve, reject) => { $.ajax({ accepts: { mycustomtype: accept }, url: ret.meta.lexToTerm("<"+obj[key + "URL"]+">"), dataType: "text" }).then(text => { resolve(text); }).fail(e => { results.append($("<pre/>").text( "Error " + e.status + " " + e.statusText + " on GET " + obj[key + "URL"] ).addClass("error")); reject(e); }); }); } else { // Ignore this parameter. obj[key] = Promise.resolve(obj[key]); } } } function makeExtensionCache (selection) { const ret = _makeCache(selection); ret.set = async function (code, url, source, mediaType) { this.url = url; // @@crappyHack1 -- parms should differntiate: try { // exceptions pass through to caller (asyncGet) // const resp = await fetch('http://localhost/checkouts/shexSpec/extensions/Eval/') // const text = await resp.text(); if (mediaType.startsWith('text/html')) return this.grepHtmlIndexForPackage(code, url, source) const extension = Function(`"use strict"; const module = {exports: {}}; ${code} return module.exports; `)() const name = extension.name; const id = "extension_" + name; // Delete any old li associated with this extension. const old = $(`.extensionControl[data-url="${extension.url}"]`) if (old.length) { results.append($("<div/>").append( $("<span/>").text(`removing old ${old.attr('data-name')} extension`) )); old.parent().remove(); } // Create a new li. const elt = $("<li/>", { class: "menuItem", title: extension.description }).append( $("<input/>", { type: "checkbox", checked: "checked", class: "extensionControl", id: id, "data-name": name, "data-url": extension.url }), $("<label/>", { for: id }).append( $("<a/>", {href: extension.url, text: name}) ) ); elt.insertBefore("#load-extension-button"); $("#" + id).data("code", extension); Caches.extension.url = url; // @@ cheesy hack that only works to remember one extension URL results.append($("<div/>").append( $("<span/>").text(`extension ${name} loaded from <${url}>`) )); } catch (e) { // $("#inputSchema .extension").append($("<li/>").text(NO_EXTENSION_LOADED)); const throwMe = Error(e + '\n' + code); throwMe.action = 'load extension' throw throwMe } // $("#extensionDrop").show(); // may have been hidden if no extension loaded. }; /* Poke around in HTML for a PACKAGE link in <table class="implementations"> <td property="code:softwareAgent" resource="https://github.com/shexSpec/shex.js">shexjs</td> <td><a property="shex:package" href="PACKAGE"/>...</td>... </table> */ ret.grepHtmlIndexForPackage = async function (code, url, source) { const jq = $(code); const impls = $(jq.find('table.implementations')) if (impls.length !== 1) { results.append($("<div/>").append( $("<span/>").text("unparsable extension index at " + url) ).addClass("error")); return; } const tr = $(impls).find(`tr td[resource="${ShExJsUrl}"]`).parent() if (tr.length !== 1) { results.append($("<div/>").append( $("<span/>").text("no entry for shexjs in index HTML at " + url) ).addClass("error")); return; } const href = tr.find('[property="shex:package"]').attr('href') if (!href) { results.append($("<div/>").append( $("<span/>").text("no package for shexjs in index HTML at " + url) ).addClass("error")); return; } const refd = await fetch(href); if (!refd.ok) { results.append($("<div/>").append( $("<span/>").text(`error fetching implementation: ${refd.status} (${refd.statusText}) for URL <${href}>`) ).addClass("error")); } else { code = await refd.text(); await this.set(code, url, source, refd.headers.get('content-type')); } }; ret.parse = async function (text, base) { throw Error("should not try to parse extension cache"); }; ret.getItems = async function () { throw Error("should not try to get extension cache items"); }; return ret; } function ldToTurtle (ld, termToLex) { return typeof ld === "object" ? lit(ld) : termToLex(ld); function lit (o) { let ret = "\""+o["@value"].replace(/["\r\n\t]/g, (c) => { return {'"': "\\\"", "\r": "\\r", "\n": "\\n", "\t": "\\t"}[c]; }) +"\""; if ("@type" in o) ret += "^^<" + o["@type"] + ">"; if ("@language" in o) ret += "@" + o["@language"]; return ret; } } function makeShapeMapCache (selection) { const ret = _makeCache(selection); ret.parse = async function (text) { removeEditMapPair(null); $("#textMap").val(text); copyTextMapToEditMap(); await copyEditMapToFixedMap(); }; // ret.parse = function (text, base) { }; ret.getItems = async function () { throw Error("should not try to get manifest cache items"); }; return ret; } function makeJSONCache(selection) { const ret = _makeCache(selection); ret.parse = async function (text) { return Promise.resolve(JSON.parse(text)); }; return ret; } // controls for manifest buttons async function paintManifest (selector, list, func, listItems, side) { $(selector).empty(); await Promise.all(list.map(async entry => { // build button disabled and with leading "..." to indicate that it's being loaded const button = $("<button/>").text("..." + entry.label.substr(3)).attr("disabled", "disabled"); const li = $("<li/>").append(button); $(selector).append(li); if (entry.text === undefined) { entry.text = await fetchOK(entry.url).catch(responseOrError => { // leave a message in the schema or data block return "# " + renderErrorMessage( responseOrError instanceof Error ? { url: entry.url, status: -1, statusText: responseOrError.message } : responseOrError, side); }) textLoaded(); } else { textLoaded(); } function textLoaded () { li.on("click", async () => { SharedForTests.promise = func(entry.name, entry, li, listItems, side); }); listItems[side][sum(entry.text)] = li; // enable and get rid of the "..." in the label now that it's loaded button.text(entry.label).removeAttr("disabled"); } })) setTextAreaHandlers(listItems); } function fetchOK (url) { return fetch(url).then(responseOrError => { if (!responseOrError.ok) { throw responseOrError; } return responseOrError.text() }); } function renderErrorMessage (response, what) { const message = "failed to load " + "queryMap" + " from <" + response.url + ">, got: " + response.status + " " + response.statusText; results.append($("<pre/>").text(message).addClass("error")); return message; } async function clearData () { // Clear out data textarea. await Caches.inputData.set("", DefaultBase); $("#inputData .status").text(" "); // Clear out every form of ShapeMap. $("#textMap").val("").removeClass("error"); makeFreshEditMap(); $("#fixedMap").empty(); results.clear(); } async function clearAll () { $("#results .status").hide(); await Caches.inputSchema.set("", DefaultBase); $(".inputShape").val(""); $("#inputSchema .status").text(" "); $("#inputSchema li.selected").removeClass("selected"); clearData(); $("#inputData .passes, #inputData .fails").hide(); $("#inputData .passes p:first").text(""); $("#inputData .fails p:first").text(""); $("#inputData .passes ul, #inputData .fails ul").empty(); } async function pickSchema (name, schemaTest, elt, listItems, side) { if ($(elt).hasClass("selected")) { await clearAll(); } else { await Caches.inputSchema.set(schemaTest.text, new URL((schemaTest.url || ""), DefaultBase).href); Caches.inputSchema.url = undefined; // @@ crappyHack1 $("#inputSchema .status").text(name); clearData(); const headings = { "passes": "Passing:", "fails": "Failing:", "indeterminant": "Data:" }; await Promise.all(Object.keys(headings).map(async function (key) { if (key in schemaTest) { $("#inputData ." + key + "").show(); $("#inputData ." + key + " p:first").text(headings[key]); await paintManifest("#inputData ." + key + " ul", schemaTest[key], pickData, listItems, "inputData"); } else { $("#inputData ." + key + " ul").empty(); } })); $("#inputSchema li.selected").removeClass("selected"); $(elt).addClass("selected"); try { await Caches.inputSchema.refresh(); } catch (e) { failMessage(e, "parsing schema"); } } } async function pickData (name, dataTest, elt, listItems, side) { clearData(); if ($(elt).hasClass("selected")) { $(elt).removeClass("selected"); } else { // Update data pane. await Caches.inputData.set(dataTest.text, new URL((dataTest.url || ""), DefaultBase).href); Caches.inputData.url = undefined; // @@ crappyHack1 $("#inputData .status").text(name); $("#inputData li.selected").removeClass("selected"); $(elt).addClass("selected"); try { await Caches.inputData.refresh(); } catch (e) { failMessage(e, "parsing data"); } // Update ShapeMap pane. removeEditMapPair(null); if (dataTest.entry.queryMap !== undefined) { await queryMapLoaded(dataTest.entry.queryMap); } else if (dataTest.entry.queryMapURL !== undefined) { try { const resp = await fetchOK(dataTest.entry.queryMapURL) queryMapLoaded(resp); } catch (e) { renderErrorMessage(e, "queryMap"); } } else { results.append($("<div/>").text("No queryMap or queryMapURL supplied in manifest").addClass("warning")); } async function queryMapLoaded (text) { dataTest.entry.queryMap = text; try { $("#textMap").val(JSON.parse(dataTest.entry.queryMap).map(entry => `<${entry.node}>@<${entry.shape}>`).join(",\n")); } catch (e) { $("#textMap").val(dataTest.entry.queryMap); } await copyTextMapToEditMap(); Caches.outputSchema.set(dataTest.entry.outputSchema, dataTest.outputSchemaUrl); $("#outputSchema .status").text(name); Caches.statics.set(JSON.stringify(dataTest.entry.staticVars, null, " ")); $("#staticVars .status").text(name); $("#outputShape").val(dataTest.entry.outputShape); // targetSchema.start in Map-test $("#createRoot").val(dataTest.entry.createRoot); // createRoot in Map-test // callValidator(); } } } // Control results area content. const results = (function () { const resultsElt = document.querySelector("#results div"); const resultsSel = $("#results div"); return { replace: function (text) { return resultsSel.text(text); }, append: function (text) { return resultsSel.append(text); }, clear: function () { resultsSel.removeClass("passes fails error"); $("#results .status").text("").hide(); $("#shapeMap-tabs").removeAttr("title"); return resultsSel.text(""); }, start: function () { resultsSel.removeClass("passes fails error"); $("#results").addClass("running"); }, finish: function () { $("#results").removeClass("running"); const height = resultsSel.height(); resultsSel.height(1); resultsSel.animate({height:height}, 100); }, text: function () { return $(resultsElt).text(); } }; })(); let LastFailTime = 0; // Validation UI function disableResultsAndValidate (evt) { if (new Date().getTime() - LastFailTime < 100) { results.append( $("<div/>").addClass("warning").append( $("<h2/>").text("see shape map errors above"), $("<button/>").text("validate (ctl-enter)").on("click", disableResultsAndValidate), " again to continue." ) ); return; // return if < 100ms since last error. } results.clear(); results.start(); SharedForTests.promise = new Promise((resolve, reject) => { setTimeout(async function () { const errors = await copyEditMapToTextMap() // will update if #editMap is dirty if (errors.length === 0) resolve(await callValidator()) }, 0); }) } function hasFocusNode () { return $(".focus").map((idx, elt) => { return $(elt).val(); }).get().some(str => { return str.length > 0; }); } let Mapper = null async function callValidator (done) { $("#fixedMap .pair").removeClass("passes fails"); $("#results .status").hide(); let currentAction = "parsing input schema"; try { await Caches.inputSchema.refresh(); // @@ throw away parser stack? $("#schemaDialect").text(Caches.inputSchema.language); if (hasFocusNode()) { currentAction = "parsing input data"; $("#results .status").text("parsing data...").show(); const inputData = await Caches.inputData.refresh(); // need prefixes for ShapeMap // $("#shapeMap-tabs").tabs("option", "active", 2); // select fixedMap currentAction = "parsing shape map"; const fixedMap = fixedShapeMapToTerms($("#fixedMap tr").map((idx, tr) => { return { node: Caches.inputData.meta.lexToTerm($(tr).find("input.focus").val()), shape: Caches.inputSchema.meta.lexToTerm($(tr).find("input.inputShape").val()) }; }).get()); currentAction = "creating validator"; $("#results .status").text("creating validator...").show(); // const dataURL = "data:text/json," + // JSON.stringify( // ShEx.Util.AStoShExJ( // ShEx.Util.canonicalize( // Caches.inputSchema.refresh()))); const alreadLoaded = { schema: await Caches.inputSchema.refresh(), url: Caches.inputSchema.url || DefaultBase }; // shex-node loads IMPORTs and tests the schema for structural faults. try { const loaded = await ShExApi.load([alreadLoaded], [], [], []); let time; const validator = ShEx.Validator.construct( loaded.schema, inputData, { results: "api", regexModule: ShEx[$("#regexpEngine").val()] }); $(".extensionControl:checked").each(function () { $(this).data("code").register(validator, ShEx); }) Mapper = MapModule.register(validator, ShEx); currentAction = "validating"; $("#results .status").text("validating...").show(); time = new Date(); const ret = validator.validate(fixedMap, LOG_PROGRESS ? makeConsoleTracker() : null); time = new Date() - time; $("#shapeMap-tabs").attr("title", "last validation: " + time + " ms") // const dated = Object.assign({ _when: new Date().toISOString() }, ret); $("#results .status").text("rendering results...").show(); await Promise.all(ret.map(renderEntry)); // for debugging values and schema formats: // try { // const x = ShExUtil.valToValues(ret); // // const x = ShExUtil.ShExJtoAS(valuesToSchema(valToValues(ret))); // res = results.replace(JSON.stringify(x, null, " ")); // const y = ShExUtil.valuesToSchema(x); // res = results.append(JSON.stringify(y, null, " ")); // } catch (e) { // console.dir(e); // } finishRendering(); return { validationResults: ret }; // for tester or whoever is awaiting this promise } catch (e) { $("#results .status").text("validation errors:").show(); failMessage(e, currentAction); console.error(e); // dump details to console. return { validationError: e }; } } else { const outputLanguage = Caches.inputSchema.language === "ShExJ" ? "ShExC" : "ShExJ"; $("#results .status"). text("parsed "+Caches.inputSchema.language+" schema, generated "+outputLanguage+" "). append($("<button>(copy to input)</button>"). css("border-radius", ".5em"). on("click", async function () { await Caches.inputSchema.set($("#results div").text(), DefaultBase); })). append(":"). show(); let parsedSchema; if (Caches.inputSchema.language === "ShExJ") { const opts = { simplifyParentheses: false, base: Caches.inputSchema.meta.base, prefixes: Caches.inputSchema.meta.prefixes } new ShEx.Writer(opts).writeSchema(Caches.inputSchema.parsed, (error, text) => { if (error) { $("#results .status").text("unwritable ShExJ schema:\n" + error).show(); // res.addClass("error"); } else { results.append($("<pre/>").text(text).addClass("passes")); } }); } else { const pre = $("<pre/>"); pre.text(JSON.stringify(ShEx.Util.AStoShExJ(ShEx.Util.canonicalize(Caches.inputSchema.parsed)), null, " ")).addClass("passes"); results.append(pre); } results.finish(); return { transformation: { from: Caches.inputSchema.language, to: outputLanguage } } } } catch (e) { failMessage(e, currentAction); console.error(e); // dump details to console. return { inputError: e }; } function makeConsoleTracker () { function padding (depth) { return (new Array(depth + 1)).join(" "); } // AKA " ".repeat(depth) function sm (node, shape) { return `${Caches.inputData.meta.termToLex(node)}@${Caches.inputSchema.meta.termToLex(shape)}`; } const logger = { recurse: x => { console.log(`${padding(logger.depth)}↻ ${sm(x.node, x.shape)}`); return x; }, known: x => { console.log(`${padding(logger.depth)}↵ ${sm(x.node, x.shape)}`); return x; }, enter: (point, label) => { console.log(`${padding(logger.depth)}→ ${sm(point, label)}`); ++logger.depth; }, exit: (point, label, ret) => { --logger.depth; console.log(`${padding(logger.depth)}← ${sm(point, label)}`); }, depth: 0 }; return logger; } } async function renderEntry (entry) { const fails = entry.status === "nonconformant"; // locate FixedMap entry const shapeString = entry.shape === ShEx.Validator.start ? START_SHAPE_INDEX_ENTRY : entry.shape; const fixedMapEntry = $("#fixedMap .pair"+ "[data-node='"+entry.node+"']"+ "[data-shape='"+shapeString+"']"); const klass = (fails ^ fixedMapEntry.find(".shapeMap-joiner").hasClass("nonconformant")) ? "fails" : "passes"; const resultStr = fails ? "✗" : "✓"; let elt = null; if (!fails) { if ($("#success").val() === "query" || $("#success").val() === "remainder") { const proofStore = new RdfJs.Store(); ShEx.Util.getProofGraph(entry.appinfo, proofStore, RdfJs.DataFactory); entry.graph = proofStore.getQuads(); } if ($("#success").val() === "remainder") { const remainder = new RdfJs.Store(); remainder.addQuads((await Caches.inputData.refresh()).getQuads()); entry.graph.forEach(q => remainder.removeQuad(q)); entry.graph = remainder.getQuads(); } } if (entry.graph) { const wr = new RdfJs.Writer(Caches.inputData.meta); wr.addQuads(entry.graph); wr.end((error, results) => { if (error) throw error; entry.turtle = "" + "# node: " + entry.node + "\n" + "# shape: " + entry.shape + "\n" + results.trim(); elt = $("<pre/>").text(entry.turtle).addClass(klass); }); delete entry.graph; } else { let renderMe = entry switch ($("#interface").val()) { case "human": elt = $("<div class='human'/>").append( $("<span/>").text(resultStr), $("<span/>").text( `${Caches.inputData.meta.termToLex(entry.node)}@${fails ? "!" : ""}${Caches.inputSchema.meta.termToLex(entry.shape)}` )).addClass(klass); if (fails) elt.append($("<pre>").text(ShEx.Util.errsToSimple(entry.appinfo).join("\n"))); break; case "minimal": if (fails) entry.reason = ShEx.Util.errsToSimple(entry.appinfo).join("\n"); renderMe = Object.keys(entry).reduce((acc, key) => { if (key !== "appinfo") acc[key] = entry[key]; return acc }, {}); // falling through to default covers the appinfo case default: elt = $("<pre/>").text(JSON.stringify(renderMe, null, " ")).addClass(klass); } } results.append(elt); // update the FixedMap fixedMapEntry.addClass(klass).find("a").text(resultStr); const nodeLex = fixedMapEntry.find("input.focus").val(); const shapeLex = fixedMapEntry.find("input.inputShape").val(); const anchor = encodeURIComponent(nodeLex) + "@" + encodeURIComponent(shapeLex); elt.attr("id", anchor); fixedMapEntry.find("a").attr("href", "#" + anchor); fixedMapEntry.attr("title", entry.elapsed + " ms") if (entry.status === "conformant") { const resultBindings = ShEx.Util.valToExtension(entry.appinfo, MapModule.url); await Caches.bindings.set(JSON.stringify(resultBindings, null, " ")); } else { await Caches.bindings.set("{}"); } } function finishRendering (done) { $("#results .status").text("rendering results...").show(); // Add commas to JSON results. if ($("#interface").val() !== "human") $("#results div *").each((idx, elt) => { if (idx === 0) $(elt).prepend("["); $(elt).append(idx === $("#results div *").length - 1 ? "]" : ","); }); $("#results .status").hide(); // for debugging values and schema formats: // try { // const x = ShEx.Util.valToValues(ret); // // const x = ShEx.Util.ShExJtoAS(valuesToSchema(valToValues(ret))); // res = results.replace(JSON.stringify(x, null, " ")); // const y = ShEx.Util.valuesToSchema(x); // res = results.append(JSON.stringify(y, null, " ")); // } catch (e) { // console.dir(e); // } results.finish(); } function failMessage (e, action, text) { $("#results .status").empty().text("Errors encountered:").show() const div = $("<div/>").addClass("error"); div.append($("<h3/>").text("error " + action + ":\n")); div.append($("<pre/>").text(e.message)); if (text) div.append($("<pre/>").text(text)); results.append(div); LastFailTime = new Date().getTime(); } async function materialize () { SharedForTests.promise = materializeAsync() } async function materializeAsync () { if (Caches.bindings.get().trim().length === 0) { results.replace("You must validate data against a ShExMap schema to populate mappings bindings."). removeClass("passes fails").addClass("error"); return null; } results.start(); const parsing = "output schema"; try { const outputSchemaText = Caches.outputSchema.selection.val(); const outputSchemaIsJSON = outputSchemaText.match(/^\s*\{/); const outputSchema = await Caches.outputSchema.refresh(); // const resultBindings = Object.assign( // await Caches.statics.refresh(), // await Caches.bindings.refresh() // ); function _dup (obj) { return JSON.parse(JSON.stringify(obj)); } const resultBindings = _dup(await Caches.bindings.refresh()); if (Caches.statics.get().trim().length === 0) await Caches.statics.set("{ }"); const _t = await Caches.statics.refresh(); if (_t && Object.keys(_t) > 0) { if (!Array.isArray(resultBindings)) resultBindings = [resultBindings]; resultBindings.unshift(_t); } // const trivialMaterializer = Mapper.trivialMaterializer(outputSchema); const outputShapeMap = fixedShapeMapToTerms([{ node: Caches.inputData.meta.lexToTerm($("#createRoot").val()), shape: Caches.outputSchema.meta.lexToTerm($("#outputShape").val()) // resolve with Caches.outputSchema }]); const binder = Mapper.binder(resultBindings); await Caches.bindings.set(JSON.stringify(resultBindings, null, " ")); // const outputGraph = trivialMaterializer.materialize(binder, lexToTerm($("#createRoot").val()), outputShape); // binder = Mapper.binder(resultBindings); const generatedGraph = new RdfJs.Store(); $("#results div").empty(); $("#results .status").text("materializing data...").show(); outputShapeMap.forEach(pair => { try { const materializer = MapModule.materializer.construct(outputSchema, Mapper, {}); const res = materializer.validate(binder, pair.node, pair.shape); if ("errors" in res) { renderEntry( { node: pair.node, shape: pair.shape, status: "errors" in res ? "nonconformant" : "conformant", appinfo: res, elapsed: -1 }) // $("#results .status").text("validation errors:").show(); // $("#results .status").text("synthesis errors:").show(); // failMessage(e, currentAction); } else { // console.log("g:", ShEx.Util.valToTurtle(res)); generatedGraph.addQuads(ShEx.Util.valToN3js(res, RdfJs.DataFactory)); } } catch (e) { console.dir(e); } }); finishRendering(); $("#results .status").text("materialization results").show(); const writer = new RdfJs.Writer({ prefixes: Caches.outputSchema.parsed._prefixes }); writer.addQuads(generatedGraph.getQuads()); writer.end(function (error, result) { results.append( $("<div/>", {class: "passes"}).append( $("<span/>", {class: "shapeMap"}).append( "# ", $("<span/>", {class: "data"}).text($("#createRoot").val()), $("<span/>", {class: "valStatus"}).text("@"), $("<span/>", {class: "schema"}).text($("#outputShape").val()), ), $("<pre/>").text(result) ) ) // results.append($("<pre/>").text(result)); }); results.finish(); return { materializationResults: generatedGraph }; } catch (e) { results.replace("error parsing " + parsing + ":\n" + e). removeClass("passes fails").addClass("error"); // results.finish(); return null; } } function addEmptyEditMapPair (evt) { addEditMapPairs(null, $(evt.target).parent().parent()); markEditMapDirty(); return false; } function addEditMapPairs (pairs, target) { (pairs || [{node: {type: "empty"}}]).forEach(pair => { const nodeType = (typeof pair.node !== "object" || "@value" in pair.node) ? "node" : pair.node.type; let skip = false; let node, shape; switch (nodeType) { case "empty": node = shape = ""; break; case "node": node = ldToTurtle(pair.node, Caches.inputData.meta.termToLex); shape = startOrLdToTurtle(pair.shape); break; case "TriplePattern": node = renderTP(pair.node); shape = startOrLdToTurtle(pair.shape); break; case "Extension": failMessage(Error("unsupported extension: <" + pair.node.language + ">"), "parsing Query Map", pair.node.lexical); skip = true; // skip this entry. break; default: results.append($("<div/>").append( $("<span/>").text("unrecognized ShapeMap:"), $("<pre/>").text(JSON.stringify(pair)) ).addClass("error")); skip = true; // skip this entry. break; } if (!skip) { const spanElt = $("<tr/>", {class: "pair"}); const focusElt = $("<textarea/>", { rows: '1', type: 'text', class: 'data focus' }).text(node).on("change", markEditMapDirty); const joinerElt = $("<span>", { class: 'shapeMap-joiner' }).append("@").addClass(pair.status); joinerElt.append( $("<input>", {style: "border: none; width: .2em;", readonly: "readonly"}).val(pair.status === "nonconformant" ? "!" : " ").on("click", function (evt) { const status = $(this).parent().hasClass("nonconformant") ? "conformant" : "nonconformant"; $(this).parent().removeClass("conformant nonconformant"); $(this).parent().addClass(status); $(this).val(status === "nonconformant" ? "!" : ""); markEditMapDirty(); evt.preventDefault(); }) ); // if (pair.status === "nonconformant") { // joinerElt.append("!"); // } const shapeElt = $("<input/>", { type: 'text', value: shape, class: 'schema inputShape' }).on("change", markEditMapDirty); const addElt = $("<button/>", { class: "addPair", title: "add a node/shape pair"}).text("+"); const removeElt = $("<button/>", { class: "removePair", title: "remove this node/shape pair"}).text("-"); addElt.on("click", addEmptyEditMapPair); removeElt.on("click", removeEditMapPair); spanElt.append([focusElt, joinerElt, shapeElt, addElt, removeElt].map(elt => { return $("<td/>").append(elt); })); if (target) { target.after(spanElt); } else { $("#editMap").append(spanElt); } } }); if ($("#editMap .removePair").length === 1) $("#editMap .removePair").css("visibility", "hidden"); else $("#editMap .removePair").css("visibility", "visible"); $("#editMap .pair").each(idx => { addContextMenus("#editMap .pair:nth("+idx+") .focus", Caches.inputData); addContextMenus(".pair:nth("+idx+") .inputShape", Caches.inputSchema); }); return false; function renderTP (tp) { const ret = ["subject", "predicate", "object"].map(k => { const ld = tp[k]; if (ld === ShEx.ShapeMap.focus) return "FOCUS"; if (!ld) // ?? ShEx.Uti.any return "_"; return ldToTurtle(ld, Caches.inputData.meta.termToLex); }); return "{" + ret.join(" ") + "}"; } function startOrLdToTurtle (term) { return term === ShEx.Validator.start ? START_SHAPE_LABEL : ldToTurtle(term, Caches.inputSchema.meta.termToLex); } } function removeEditMapPair (evt) { markEditMapDirty(); if (evt) { $(evt.target).parent().parent().remove(); } else { $("#editMap .pair").remove(); } if ($("#editMap .removePair").length === 1) $("#editMap .removePair").css("visibility", "hidden"); return false; } function prepareControls () { $("#menu-button").on("click", toggleControls); $("#interface").on("change", setInterface); $("#success").on("change", setInterface); $("#regexpEngine").on("change", toggleControls); $("#validate").on("click", disableResultsAndValidate); $("#clear").on("click", clearAll); $("#materialize").on("click", materialize); $("#download-results-button").on("click", downloadResults); $("#loadForm").dialog({ autoOpen: false, modal: true, buttons: { "GET": function (evt, ui) { results.clear(); const target = Getables.find(g => g.queryStringParm === $("#loadForm span.whatToLoad").text()); const url = $("#loadInput").val(); const tips = $(".validateTips"); function updateTips (t) { tips .text( t ) .addClass( "ui-state-highlight" ); setTimeout(function() { tips.removeClass( "ui-state-highlight", 1500 ); }, 500 ); } if (url.length < 5) { $("#loadInput").addClass("ui-state-error"); updateTips("URL \"" + url + "\" is way too short."); return; } tips.removeClass("ui-state-highlight").text(); SharedForTests.promise = target.cache.asyncGet(url).catch(function (e) { updateTips(e.message); }); }, "Cancel": function() { $("#loadInput").removeClass("ui-state-error"); $("#loadForm").dialog("close"); toggleControls(); } }, close: function() { $("#loadInput").removeClass("ui-state-error"); $("#loadForm").dialog("close"); toggleControls(); } }); Getables.forEach(target => { const type = target.queryStringParm $("#load-"+type+"-button").click(evt => { const prefillURL = target.url ? target.url : target.cache.meta.base && target.cache.meta.base !== DefaultBase ? target.cache.meta.base : ""; $("#loadInput").val(prefillURL); $("#loadForm").attr("class", type).find("span.whatToLoad").text(type); $("#loadForm").dialog("open"); }); }); $("#about").dialog({ autoOpen: false, modal: true, width: "50%", buttons: { "Dismiss": dismissModal }, close: dismissModal }); $("#about-button").click(evt => { $("#about").dialog("open"); }); $("#shapeMap-tabs").tabs({ activate: async function (event, ui) { if (ui.oldPanel.get(0) === $("#editMap-tab").get(0)) await copyEditMapToTextMap(); else if (ui.oldPanel.get(0) === $("#textMap").get(0)) await copyTextMapToEditMap() } }); $("#textMap").on("change", evt => { results.clear(); SharedForTests.promise = copyTextMapToEditMap(); }); Caches.inputData.selection.on("change", dataInputHandler); // input + paste? // $("#copyEditMapToFixedMap").on("click", copyEditMapToFixedMap); // may add this button to tutorial function dismissModal (evt) { // $.unblockUI(); $("#about").dialog("close"); toggleControls(); return true; } // Prepare file uploads $("input.inputfile").each((idx, elt) => { $(elt).on("change", function (evt) { const reader = new FileReader(); reader.onload = function(evt) { if(evt.target.readyState != 2) return; if(evt.target.error) { alert("Error while reading file"); return; } $($(elt).attr("data-target")).val(evt.target.result); }; reader.readAsText(evt.target.files[0]); }); }); } async function dataInputHandler (evt) { const active = $('#shapeMap-tabs ul li.ui-tabs-active a').attr('href'); if (active === "#editMap-tab") return await copyEditMapToTextMap(); else // if (active === "#textMap") return await copyTextMapToEditMap(); } async function toggleControls (evt) { // don't use `return false` 'cause the browser doesn't wait around for a promise before looking at return false to decide the event is handled if (evt) evt.preventDefault(); const revealing = evt && $("#controls").css("display") !== "flex"; $("#controls").css("display", revealing ? "flex" : "none"); toggleControlsArrow(revealing ? "up" : "down"); if (revealing) { let target = evt.target; while (target.tagName !== "BUTTON") target = target.parentElement; if ($("#menuForm").css("position") === "absolute") { $("#controls"). css("top", 0). css("left", $("#menu-button").css("margin-left")); } else { const bottonBBox = target.getBoundingClientRect(); const controlsBBox = $("#menuForm").get(0).getBoundingClientRect(); const left = bottonBBox.right - bottonBBox.width; // - controlsBBox.width; $("#controls").css("top", bottonBBox.bottom).css("left", left); } $("#permalink a").removeAttr("href"); // can't click until ready const permalink = await getPermalink(); $("#permalink a").attr("href", permalink); } } function toggleControlsArrow (which) { // jQuery can't find() a prefixed attribute (xlink:href); fall back to DOM: if (document.getElementById("menu-button") === null) return; const down = $(document.getElementById("menu-button"). querySelectorAll('use[*|href="#down-arrow"]')); const up = $(document.getElementById("menu-button"). querySelectorAll('use[*|href="#up-arrow"]')); switch (which) { case "down": down.show(); up.hide(); break; case "up": down.hide(); up.show(); break; default: throw Error("toggleControlsArrow expected [up|down], got \"" + which + "\""); } } function setInterface (evt) { toggleControls(); customizeInterface(); } function downloadResults (evt) { const typed = [ { type: "text/plain", name: "results.txt" }, { type: "application/json", name: "results.json" } ][$("#interface").val() === "appinfo" ? 1 : 0]; const blob = new Blob([results.text()], {type: typed.type}); $("#download-results-button") .attr("href", window.URL.createObjectURL(blob)) .attr("download", typed.name); toggleControls(); console.log(results.text()); } /** * * location.search: e.g. "?schema=asdf&data=qwer&shape-map=ab%5Ecd%5E%5E_ef%5Egh" */ const parseQueryString = function(query) { if (query[0]==='?') query=query.substr(1); // optional leading '?' const map = {}; query.replace(/([^&,=]+)=?([^&,]*)(?:[&,]+|$)/g, function(match, key, value) { key=decodeURIComponent(key);value=decodeURIComponent(value); (map[key] = map[key] || []).push(value); }); return map; }; function markEditMapDirty () { $("#editMap").attr("data-dirty", true); } function markEditMapClean () { $("#editMap").attr("data-dirty", false); } /** getShapeMap -- zip a node list and a shape list into a ShapeMap * use {Caches.inputData,Caches.inputSchema}.meta.{prefix,base} to complete IRIs * @return array of encountered errors */ async function copyEditMapToFixedMap () { $("#fixedMap tbody").empty(); // empty out the fixed map. const fixedMapTab = $("#shapeMap-tabs").find('[href="#fixedMap-tab"]'); const restoreText = fixedMapTab.text(); fixedMapTab.text("resolving Fixed Map").addClass("running"); $("#fixedMap .pair").remove(); // clear out existing edit map (make optional?) const nodeShapePromises = $("#editMap .pair").get().reduce((acc, queryPair) => { $(queryPair).find(".error").removeClass("error"); // remove previous error markers const node = $(queryPair).find(".focus").val(); const shape = $(queryPair).find(".inputShape").val(); const status = $(queryPair).find(".shapeMap-joiner").hasClass("nonconformant") ? "nonconformant" : "conformant"; if (!node || !shape) return acc; const smparser = ShEx.ShapeMapParser.construct( Caches.shapeMap.meta.base, Caches.inputSchema.meta, Caches.inputData.meta); const nodes = []; try { const sm = smparser.parse(node + '@' + shape)[0]; const added = typeof sm.node === "string" || "@value" in sm.node ? Promise.resolve({nodes: [node], shape: shape, status: status}) : getQuads(sm.node.subject, sm.node.predicate, sm.node.object) .then(nodes => Promise.resolve({nodes: nodes, shape: shape, status: status})); return acc.concat(added); } catch (e) { // find which cell was broken try { smparser.parse(node + '@' + "START"); } catch (e) { $(queryPair).find(".focus").addClass("error"); } try { smparser.parse("<>" + '@' + shape); } catch (e) { $(queryPair).find(".inputShape").addClass("error"); } failMessage(e, "parsing Edit Map", node + '@' + shape); nodes = Promise.resolve([]); // skip this entry return acc; } }, []); const pairs = await Promise.all(nodeShapePromises) pairs.reduce((acc, pair) => { pair.nodes.forEach(node => { const nodeTerm = Caches.inputData.meta.lexToTerm(node + " "); // for langcode lookahead let shapeTerm = Caches.inputSchema.meta.lexToTerm(pair.shape); if (shapeTerm === ShEx.Validator.start) shapeTerm = START_SHAPE_INDEX_ENTRY; const key = nodeTerm + "|" + shapeTerm; if (key in acc) return; const spanElt = createEntry(node, nodeTerm, pair.shape, shapeTerm, pair.status); acc[key] = spanElt; // just needs the key so far. }); return acc; }, {}) // scroll inputs to right $("#fixedMap input").each((idx, focusElt) => { focusElt.scrollLeft = focusElt.scrollWidth; }); fixedMapTab.text(restoreText).removeClass("running"); return []; // no errors async function getQuads (s, p, o) { const get = s === ShEx.ShapeMap.focus ? "subject" : "object"; return (await Caches.inputData.refresh()).getQuads(mine(s), mine(p), mine(o)).map(t => { return Caches.inputData.meta.termToLex(t[get]);// !!check }); function mine (term) { return term === ShEx.ShapeMap.focus || term === ShEx.ShapeMap.wildcard ? null : term; } } function createEntry (node, nodeTerm, shape, shapeTerm, status) { const spanElt = $("<tr/>", {class: "pair" ,"data-node": nodeTerm ,"data-shape": shapeTerm }); const focusElt = $("<input/>", { type: 'text', value: node, class: 'data focus', disabled: "disabled" }); const joinerElt = $("<span>", { class: 'shapeMap-joiner' }).append("@").addClass(status); if (status === "nonconformant") { joinerElt.addClass("negated"); joinerElt.append("!"); } const shapeElt = $("<input/>", { type: 'text', value: shape, class: 'schema inputShape', disabled: "disabled" }); const removeElt = $("<button/>", { class: "removePair", title: "remove this node/shape pair"}).text("-"); removeElt.on("click", evt => { // Remove related result. let href, result; if ((href = $(evt.target).closest("tr").find("a").attr("href")) && (result = document.getElementById(href.substr(1)))) $(result).remove(); // Remove FixedMap entry. $(evt.target).closest("tr").remove(); }); spanElt.append([focusElt, joinerElt, shapeElt, removeElt, $("<a/>")].map(elt => { return $("<td/>").append(elt); })); $("#fixedMap").append(spanElt); return spanElt; } } function lexifyFirstColumn (row) { // !!not used return Caches.inputData.meta.termToLex(row[0]); // row[0] is the first column. } /** * @return list of errors encountered */ async function copyEditMapToTextMap () { if ($("#editMap").attr("data-dirty") === "true") { const text = $("#editMap .pair").get().reduce((acc, queryPair) => { const node = $(queryPair).find(".focus").val(); const shape = $(queryPair).find(".inputShape").val(); if (!node || !shape) return acc; const status = $(queryPair).find(".shapeMap-joiner").hasClass("nonconformant") ? "!" : ""; return acc.concat([node+"@"+status+shape]); }, []).join(",\n"); $("#textMap").empty().val(text); const ret = await copyEditMapToFixedMap(); markEditMapClean(); return ret; } else { return []; // no errors } } /** * Parse query map to populate #editMap and #fixedMap. * @returns list of errors. ([] means everything was good.) */ async function copyTextMapToEditMap () { $("#textMap").removeClass("error"); const shapeMap = $("#textMap").val(); results.clear(); try { await Caches.inputSchema.refresh(); await Caches.inputData.refresh(); const smparser = ShEx.ShapeMapParser.construct( Caches.shapeMap.meta.base, Caches.inputSchema.meta, Caches.inputData.meta); const sm = smparser.parse(shapeMap); removeEditMapPair(null); addEditMapPairs(sm.length ? sm : null); const ret = await copyEditMapToFixedMap(); markEditMapClean(); results.clear(); return ret; } catch (e) { $("#textMap").addClass("error"); failMessage(e, "parsing Query Map"); makeFreshEditMap() return [e]; } } function makeFreshEditMap () { removeEditMapPair(null); addEditMapPairs(null, null); markEditMapClean(); return []; } /** fixedShapeMapToTerms -- map ShapeMap to API terms * @@TODO: add to ShExValidator so API accepts ShapeMap */ function fixedShapeMapToTerms (shapeMap) { return shapeMap; /*.map(pair => { return {node: Caches.inputData.meta.lexToTerm(pair.node + " "), shape: Caches.inputSchema.meta.lexToTerm(pair.shape)}; });*/ } /** * Load URL search parameters */ async function loadSearchParameters () { // don't overwrite if we arrived here from going back and forth in history if (Caches.inputSchema.selection.val() !== "" || Caches.inputData.selection.val() !== "") return Promise.resolve(); const iface = parseQueryString(location.search); toggleControlsArrow("down"); $(".manifest li").text("no manifest schemas loaded"); if ("examples" in iface) { // deprecated ?examples= interface iface.manifestURL = iface.examples; delete iface.examples; } if (!("manifest" in iface) && !("manifestURL" in iface)) { iface.manifestURL = ["../examples/manifest.json"]; } if ("output-map" in iface) parseShapeMap("output-map", function (node, shape) { // only works for one n/s pair $("#createNode").val(node); $("#outputShape").val(shape); }); // Load all known query parameters. Save load results into array like: /* [ [ "data", { "skipped": "skipped" } ], [ "manifest", { "fromUrl": { "url": "http://...", "data": "..." } } ], ] */ const loadedAsArray = await Promise.all(QueryParams.map(async input => { const label = input.queryStringParm; const parm = label; if (parm + "URL" in iface) { const url = iface[parm + "URL"][0]; if (url.length > 0) { // manifest= loads no manifest // !!! set anyways in asyncGet? input.cache.url = url; // all fooURL query parms are caches. try { const got = await input.cache.asyncGet(url) return [label, {fromUrl: got}] } catch(e) { if ("fail" in input) { input.fail(e); } else { input.location.val(e.message); } results.append($("<pre/>").text(e).addClass("error")); return [label, { loadFailure: e instanceof Error ? e : Error(e) }]; }; } } else if (parm in iface) { const prepend = input.location.prop("tagName") === "TEXTAREA" ? input.location.val() : ""; const value = prepend + iface[parm].join(""); const origValue = input.location.val(); try { if ("cache" in input) { await input.cache.set(value, location.href); } else { input.location.val(prepend + value); if (input.location.val() === null) throw Error(`Unable to set value to ${prepend + value}`) } return [label, { literal: value }] } catch (e) { input.location.val(origValue); if ("fail" in input) { input.fail(e); } results.append($("<pre/>").text( "error setting " + label + ":\n" + e + "\n" + value ).addClass("error")); return [label, { failure: e }] } } else if ("deflt" in input) { input.location.val(input.deflt); return [label, { deflt: "deflt" }]; // flag that it was a default } return [label, { skipped: "skipped" }] })) // convert loaded array into Object: /* { "data": { "skipped": "skipped" }, "manifest": { "fromUrl": { "url": "http://...", "data": "..." } }, } */ const loaded = loadedAsArray.reduce((acc, fromArray) => { acc[fromArray[0]] = fromArray[1] return acc }, {}) // Parse the shape-map using the prefixes and base. const shapeMapErrors = $("#textMap").val().trim().length > 0 ? copyTextMapToEditMap() : makeFreshEditMap(); customizeInterface(); $("body").keydown(async function (e) { // keydown because we need to preventDefault const code = e.keyCode || e.charCode; // standards anyone? if (e.ctrlKey && (code === 10 || code === 13)) { // ctrl-enter // const at = $(":focus"); const smErrors = await dataInputHandler(); if (smErrors.length === 0) $("#validate")/*.focus()*/.click(); // at.focus(); return false; // same as e.preventDefault(); } else if (e.ctrlKey && e.key === "\\") { $("#materialize").click(); return false; // same as e.preventDefault(); } else if (e.ctrlKey && e.key === "[") { bindingsToTable() return false; // same as e.preventDefault(); } else if (e.ctrlKey && e.key === "]") { tableToBindings() return false; // same as e.preventDefault(); } else { return true; } }); addContextMenus("#focus0", Caches.inputData); addContextMenus("#inputShape0", Caches.inputSchema); addContextMenus("#outputShape", Caches.outputSchema); if ("schemaURL" in iface || // some schema is non-empty ("schema" in iface && iface.schema.reduce((r, elt) => { return r+elt.length; }, 0)) && shapeMapErrors.length === 0) { return callValidator(); } return loaded; } function setTextAreaHandlers (listItems) { const textAreaCaches = ["inputSchema", "inputData", "shapeMap"] const timeouts = Object.keys(Caches).reduce((acc, k) => { acc[k] = undefined; return acc; }, {}); Object.keys(Caches).forEach(function (cache) { Caches[cache].selection.keyup(function (e) { // keyup to capture backspace const code = e.keyCode || e.charCode; // if (!(e.ctrlKey)) { // results.clear(); // } if (!(e.ctrlKey && (code === 10 || code === 13))) { later(e.target, cache, Caches[cache]); } }); }); function later (target, side, cache) { cache.dirty(true); if (timeouts[side]) clearTimeout(timeouts[side]); timeouts[side] = setTimeout(() => { timeouts[side] = undefined; const curSum = sum($(target).val()); if (curSum in listItems[side]) listItems[side][curSum].addClass("selected"); else $("#"+side+" .selected").removeClass("selected"); delete cache.url; }, INPUTAREA_TIMEOUT); } } /** * update location with a current values of some inputs */ async function getPermalink () { let parms = []; await copyEditMapToTextMap(); parms = parms.concat(QueryParams.reduce((acc, input) => { let parm = input.queryStringParm; let val = input.location.val(); if (input.cache && input.cache.url && // Specifically avoid loading from DefaultBase?schema=blah // because that will load the HTML page. !input.cache.url.startsWith(DefaultBase)) { parm += "URL"; val = input.cache.url; } return val.length > 0 ? acc.concat(parm + "=" + encodeURIComponent(val)) : acc; }, [])); const s = parms.join("&"); return location.origin + location.pathname + "?" + s; } function customizeInterface () { if ($("#interface").val() === "minimal") { $("#inputSchema .status").html("schema (<span id=\"schemaDialect\">ShEx</span>)").show(); $("#inputData .status").html("data (<span id=\"dataDialect\">Turtle</span>)").show(); $("#actions").parent().children().not("#actions").hide(); $("#title img, #title h1").hide(); $("#menuForm").css("position", "absolute").css( "left", $("#inputSchema .status").get(0).getBoundingClientRect().width - $("#menuForm").get(0).getBoundingClientRect().width ); $("#controls").css("position", "relative"); } else { $("#inputSchema .status").html("schema (<span id=\"schemaDialect\">ShEx</span>)").hide(); $("#inputData .status").html("data (<span id=\"dataDialect\">Turtle</span>)").hide(); $("#actions").parent().children().not("#actions").show(); $("#title img, #title h1").show(); $("#menuForm").removeAttr("style"); $("#controls").css("position", "absolute"); } } /** * Prepare drag and drop into text areas */ async function prepareDragAndDrop () { QueryParams.filter(q => { return "cache" in q; }).map(q => { return { location: q.location, targets: [{ ext: "", // Will match any file media: "", // or media type. target: q.cache }] }; }).concat([ {location: $("body"), targets: [ {media: "application/json", target: Caches.manifest}, {ext: ".shex", media: "text/shex", target: Caches.inputSchema}, {ext: ".ttl", media: "text/turtle", target: Caches.inputData}, {ext: ".json", media: "application/json", target: Caches.manifest}, {ext: ".smap", media: "text/plain", target: Caches.shapeMap}]} ]).forEach(desc => { const droparea = desc.location; // kudos to http://html5demos.com/dnd-upload desc.location. on("drag dragstart dragend dragover dragenter dragleave drop", function (e) { e.preventDefault(); e.stopPropagation(); }). on("dragover dragenter", (evt) => { desc.location.addClass("hover"); }). on("dragend dragleave drop", (evt) => { desc.location.removeClass("hover"); }). on("drop", (evt) => { evt.preventDefault(); droparea.removeClass("droppable"); $("#results .status").removeClass("error"); results.clear(); let xfer = evt.originalEvent.dataTransfer; const prefTypes = [ {type: "files"}, {type: "application/json"}, {type: "text/uri-list"}, {type: "text/plain"} ]; const promises = []; if (prefTypes.find(l => { if (l.type.indexOf("/") === -1) { if (l.type in xfer && xfer[l.type].length > 0) { $("#results .status").text("handling "+xfer[l.type].length+" files...").show(); promises.push(readfiles(xfer[l.type], desc.targets)); return true; } } else { if (xfer.getData(l.type)) { const val = xfer.getData(l.type); $("#results .status").text("handling "+l.type+"...").show(); if (l.type === "application/json") { if (desc.location.get(0) === $("body").get(0)) { let parsed = JSON.parse(val); if (!(Array.isArray(parsed))) { parsed = [parsed]; } parsed.map(elt => { const action = "action" in elt ? elt.action: elt; action.schemaURL = action.schema; delete action.schema; action.dataURL = action.data; delete action.data; }); promises.push(Caches.manifest.set(parsed, DefaultBase, "drag and drop")); } else { promises.push(inject(desc.targets, DefaultBase, val, l.type)); } } else if (l.type === "text/uri-list") { $.ajax({ accepts: { mycustomtype: 'text/shex,text/turtle,*/*' }, url: val, dataType: "text" }).fail(function (jqXHR, textStatus) { const error = jqXHR.statusText === "OK" ? textStatus : jqXHR.statusText; results.append($("<pre/>").text("GET <" + val + "> failed: " + error)); }).done(function (data, status, jqXhr) { try { promises.push(inject(desc.targets, val, data, (jqXhr.getResponseHeader("Content-Type") || "unknown-media-type").split(/[ ;,]/)[0])); $("#loadForm").dialog("close"); toggleControls(); } catch (e) { results.append($("<pre/>").text("unable to evaluate <" + val + ">: " + (e.stack || e))); } }); } else if (l.type === "text/plain") { promises.push(inject(desc.targets, DefaultBase, val, l.type)); } $("#results .status").text("").hide(); // desc.targets.text(xfer.getData(l.type)); return true; async function inject (targets, url, data, mediaType) { const target = targets.length === 1 ? targets[0].target : targets.reduce((ret, elt) => { return ret ? ret : mediaType === elt.media ? elt.target : null; }, null); if (target) { const appendTo = $("#append").is(":checked") ? target.get() : ""; await target.set(appendTo + data, url, 'drag and drop', mediaType); } else { results.append("don't know what to do with " + mediaType + "\n"); } } } } return false; }) === undefined) results.append($("<pre/>").text( "drag and drop not recognized:\n" + JSON.stringify({ dropEffect: xfer.dropEffect, effectAllowed: xfer.effectAllowed, files: xfer.files.length, items: [].slice.call(xfer.items).map(i => { return {kind: i.kind, type: i.type}; }) }, null, 2) )); SharedForTests.promise = Promise.all(promises); }); }); /*async*/ function readfiles(files, targets) { // returns promise but doesn't use await const formData = new FormData(); let successes = 0; const promises = []; for (let i = 0; i < files.length; i++) { const file = files[i], name = file.name; const target = targets.reduce((ret, elt) => { return ret ? ret : name.endsWith(elt.ext) ? elt.target : null; }, null); if (target) { promises.push(new Promise((resolve, reject) => { formData.append("file", file); const reader = new FileReader(); reader.onload = (function (target) { return async function (event) { const appendTo = $("#append").is(":checked") ? target.get() : ""; await target.set(appendTo + event.target.result, DefaultBase); ++successes; resolve() }; })(target); reader.readAsText(file); })) } else { results.append("don't know what to do with " + name + "\n"); } } return Promise.all(promises).then(() => { $("#results .status").text("loaded "+successes+" files.").show(); }) } } async function prepareManifest (demoList, base) { const listItems = Object.keys(Caches).reduce((acc, k) => { acc[k] = {}; return acc; }, {}); const nesting = demoList.reduce(function (acc, elt) { const key = elt.schemaLabel + "|" + elt.schema; if (!(key in acc)) { // first entry with this schema acc[key] = { label: elt.schemaLabel, text: elt.schema, url: elt.schemaURL || (elt.schema ? base : undefined) }; } else { // nth entry with this schema } if ("dataLabel" in elt) { const dataEntry = { label: elt.dataLabel, text: elt.data, url: elt.dataURL || (elt.data ? base : undefined), outputSchemaUrl: elt.outputSchemaURL || (elt.outputSchema ? base : undefined), entry: elt }; const target = elt.status === "nonconformant" ? "fails" : elt.status === "conformant" ? "passes" : "indeterminant"; if (!(target in acc[key])) { // first entry with this data acc[key][target] = [dataEntry]; } else { // n'th entry with this data acc[key][target].push(dataEntry); } } else { // this is a schema-only example } return acc; }, {}); const nestingAsList = Object.keys(nesting).map(e => nesting[e]); await paintManifest("#inputSchema .manifest ul", nestingAsList, pickSchema, listItems, "inputSchema"); } function addContextMenus (inputSelector, cache) { // !!! terribly stateful; only one context menu at a time! const DATA_HANDLE = 'runCallbackThingie' let terms = null, nodeLex = null, target, scrollLeft, m, addSpace = ""; $(inputSelector).on('contextmenu', rightClickHandler) $.contextMenu({ trigger: 'none', selector: inputSelector, build: function($trigger, e) { // return callback set by the mouseup handler return $trigger.data(DATA_HANDLE)(); } }); async function buildMenuItemsPromise (elt, evt) { if (elt.hasClass("data")) { nodeLex = elt.val(); const shapeLex = elt.parent().parent().find(".schema").val() // Would like to use SMParser but that means users can't fix bad SMs. /* const sm = smparser.parse(nodeLex + '@START')[0]; const m = typeof sm.node === "string" || "@value" in sm.node ? null : tpToM(sm.node); */ m = nodeLex.match(RegExp("^"+ParseTriplePattern+"$")); if (m) { target = evt.target; const selStart = target.selectionStart; scrollLeft = target.scrollLeft; terms = [0, 1, 2].reduce((acc, ord) => { if (m[(ord+1)*2-1] !== undefined) { const at = acc.start + m[(ord+1)*2-1].length; const len = m[(ord+1)*2] ? m[(ord+1)*2].length : 0; return { start: at + len, tz: acc.tz.concat([[at, len]]), match: acc.match === null && at + len >= selStart ? ord : acc.match }; } else { return acc; } }, {start: 0, tz: [], match: null }); function norm (tz) { return tz.map(t => { return t.startsWith('!') ? "- " + t.substr(1) + " -" : Caches.inputData.meta.termToLex(t); // !!check }); } const queryMapKeywords = ["FOCUS", "_"]; const getTermsFunctions = [ () => { return queryMapKeywords.concat(norm(store.getSubjects())); }, () => { return norm(store.getPredicates()); }, () => { return queryMapKeywords.concat(norm(store.getObjects())); }, ]; const store = await Caches.inputData.refresh(); if (terms.match === null) return false; // prevent contextMenu from whining about an empty list return listToCTHash(getTermsFunctions[terms.match]()) } } terms = nodeLex = null; try { return listToCTHash(await cache.getItems()) } catch (e) { failMessage(e, cache === Caches.inputSchema ? "parsing schema" : "parsing data"); let items = {}; const failContent = "no choices found"; items[failContent] = failContent; return items } // hack to emulate regex parsing product /* function tpToM (tp) { return [nodeLex, '{', lex(tp.subject), " ", lex(tp.predicate), " ", lex(tp.object), "", "}", ""]; function lex (node) { return node === ShEx.ShapeMap.focus ? "FOCUS" : node === null ? "_" : Caches.inputData.meta.termToLex(node); } } */ } function rightClickHandler (e) { e.preventDefault(); const $this = $(this); $this.off('contextmenu', rightClickHandler); // when the items are ready, const p = buildMenuItemsPromise($this, e) p.then(items => { // store a callback on the trigger $this.data(DATA_HANDLE, function () { return { callback: menuCallback, items: items }; }); const _offset = $this.offset(); $this.contextMenu({ x: _offset.left + 10, y: _offset.top + 10 }) $this.on('contextmenu', rightClickHandler) }); } function menuCallback (key, options) { markEditMapDirty(); if (options.items[key].ignore) { // ignore the event } else if (terms) { const term = terms.tz[terms.match]; let val = nodeLex.substr(0, term[0]) + key + addSpace + nodeLex.substr(term[0] + term[1]); if (terms.match === 2 && !m[9]) val = val + "}"; else if (term[0] + term[1] === nodeLex.length) val = val + " "; $(options.selector).val(val); // target.scrollLeft = scrollLeft + val.length - nodeLex.length; target.scrollLeft = target.scrollWidth; } else { $(options.selector).val(key); } } function listToCTHash (items) { return items.reduce((acc, item) => { acc[item] = { name: item } return acc }, {}) } } function bindingsToTable () { let d = JSON.parse($("#bindings1 textarea").val()) let div = $("<div/>").css("overflow", "auto").css("border", "thin solid red") div.css("width", $("#bindings1 textarea").width()+10) div.css("height", $("#bindings1 textarea").height()+12) $("#bindings1 textarea").hide() let thead = $("<thead/>") let tbody = $("<tbody/>") let table = $("<table>").append(thead, tbody) $("#bindings1").append(div.append(table)) let vars = []; function varsIn (a) { return a.forEach(elt => { if (Array.isArray(elt)) { varsIn(elt) } else { let tr = $("<tr/>") let cols = [] Object.keys(elt).forEach(k => { if (vars.indexOf(k) === -1) vars.push(k) let i = vars.indexOf(k) cols[i] = elt[k] }) // tr.append(cols.map(c => $("<td/>").text(c))) for (let colI = 0; colI < cols.length; ++colI) tr.append($("<td/>").text(cols[colI] ? Caches.inputData.meta.termToLex(n3ify(cols[colI])) : "").css("background-color", "#f7f7f7")) tbody.append(tr) } }) } varsIn(Array.isArray(d) ? d : [d]) vars.forEach(v => { thead.append($("<th/>").css("font-size", "small").text(v.substr(v.lastIndexOf("#")+1, 999))) }) } function tableToBindings () { $("#bindings1 div").remove() $("#bindings1 textarea").show() } prepareControls(); const dndPromise = prepareDragAndDrop(); // async 'cause it calls Cache.X.set("") const loads = loadSearchParameters(); const ready = Promise.all([ dndPromise, loads ]); if ('_testCallback' in window) { SharedForTests.promise = ready.then(ab => ({drop: ab[0], loads: ab[1]})); window._testCallback(SharedForTests); } ready.then(resolves => { if (!('_testCallback' in window)) console.log('search parameters:', resolves[1]); // Update UI to say we're done loading everything? }, e => { // Drop catch on the floor presuming thrower updated the UI. }); function n3ify (ldterm) { if (typeof ldterm !== "object") return ldterm; const ret = "\"" + ldterm.value + "\""; if ("language" in ldterm) return ret + "@" + ldterm.language; if ("type" in ldterm) return ret + "^^" + ldterm.type; return ret; }
shexSpec/shex.js
packages/extension-map/doc/shexmap-simple.js
JavaScript
mit
82,436
var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) { this.gid = Math.round(Math.random() * maxSegments); this.topPoint = origin; this.radius = baseRadius; this.maxSegments = maxSegments; this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.genes.pSubBranch) : 0; this.segmentLenght = baseSegment; this.depth = depth; //current position of the branch in chain this.tree = tree; this.segments = 0; //always start in 0 //Directions are represented as a Vector3 where dirx*i+diry*j+dirz*k and //each dir is the magnitude that can go from 0 to 1 and multiplies the max segment lenght //Starting direction is UP this.direction = { x: 0, y: 1, z: 0 }; this.material = new THREE.MeshLambertMaterial({ color: Math.floor(Math.random()*16777215),//tree.genes.color, side: 2, shading: THREE.FlatShading }); }; /** * Conceptually grows and renders the branch * @param {THREE.Scene} scene The scene to which the branch belongs */ Branch.prototype.grow = function (scene) { var thisBranch = this; //calculate new direction, our drawing space is a 200x200x200 cube var newX = newPos('x'); var newY = newPos('y'); var newZ = newPos('z'); if (newY < 0 || newY > 300 ){ // newZ < -100 || newZ > 100 || // newX < -100 || newX > 100) { randomizeDir(); return true; } else { //direction is ok and branch is going to grow thisBranch.segments += 1; } var destination = new THREE.Vector3(newX, newY, newZ); var lcurve = new THREE.LineCurve3(this.topPoint, destination); var geometry = new THREE.TubeGeometry( lcurve, //path thisBranch.tree.genes.segmentLenght, //segments thisBranch.radius, //radius 8, //radiusSegments true //opened, muuuch more efficient but not so nice ); // modify next segment's radius thisBranch.radius = thisBranch.radius * thisBranch.tree.genes.radiusDimP; var tube = new THREE.Mesh(geometry, this.material); scene.add(tube); this.topPoint = destination; randomizeDir(); //Helper functions. function randomizeDir() { //we want our dir to be from -1 to thisBranch.direction.x = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.y = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.z = (thisBranch.tree.mtwister.random() * 2) - 1; } function newPos(dimension) { return thisBranch.topPoint[dimension] + (thisBranch.direction[dimension] * thisBranch.segmentLenght); } //calculate segment lenght for new segment thisBranch.segmentLenght = thisBranch.segmentLenght * thisBranch.tree.genes.segmentLenghtDim; if (thisBranch.lenghtSubbranch !== 0 && thisBranch.segments % thisBranch.lenghtSubbranch === 0) { thisBranch.tree.spawnBranch(thisBranch.topPoint, thisBranch.radius, thisBranch.segmentLenght, this.maxSegments, this.depth); } //check if we can kill branch if (thisBranch.radius <= thisBranch.tree.genes.minRadius) { return false; //kill branch } //Kill if we have reached the max number of segments if (thisBranch.segments > thisBranch.maxSegments) { return false; } else { return true; } };
tupini07/Brownian-Shrubs
js/Branch.js
JavaScript
mit
3,324
'use strict'; var assert = require('assert') , TestEvents = require('../lib/TestEvents'); var wasCalled = false; var FN = function (ev) { wasCalled = true; }; describe('TestEvents', function () { beforeEach(function () { wasCalled = false; }); describe('#on', function () { it('Should bind a function for an event', function () { TestEvents.on(TestEvents.EMITTED_EVENTS, FN); }); }); describe('#emit', function () { it('Should call bound function for an event', function () { TestEvents.emit(TestEvents.EMITTED_EVENTS); assert.equal(wasCalled, true); }); }); })
briangallagher/testDrivenDevelopment
node_modules/fh-health/test/TestEvents.js
JavaScript
mit
623